code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
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;
using Samba.Presentation.Common;
namespace Samba.Modules.CashModule
{
/// <summary>
/// Interaction logic for CashView.xaml
/// </summary>
[Export]
public partial class CashView : UserControl
{
[ImportingConstructor]
public CashView(CashViewModel viewModel)
{
InitializeComponent();
DataContext = viewModel;
}
private void FilteredTextBox_Loaded(object sender, RoutedEventArgs e)
{
DescriptionEditor.BackgroundFocus();
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.CashModule/CashView.xaml.cs | C# | gpl3 | 986 |
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("Samba.Modules.CashModule")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Samba.Modules.CashModule")]
[assembly: AssemblyCopyright("Copyright © 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: InternalsVisibleTo("Samba.Modules.CashModule")]
// 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("a7f67ffa-9d91-44b4-9de0-8eaeb7b73ce4")]
// 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")]
| zzgaminginc-pointofssale | Samba.Modules.CashModule/Properties/AssemblyInfo.cs | C# | gpl3 | 1,520 |
using System;
using Samba.Domain;
using Samba.Domain.Models.Transactions;
using Samba.Presentation.Common;
namespace Samba.Modules.CashModule
{
public interface ICashTransactionViewModel
{
PaymentType PaymentType { get; set; }
decimal Amount { get; }
string Description { get; set; }
string DateString { get; }
decimal CashPaymentValue { get; set; }
decimal CreditCardPaymentValue { get; set; }
decimal TicketPaymentValue { get; set; }
bool IsSelected { get; set; }
string TextColor { get; }
}
public class CashTransactionViewModelBase : ObservableObject
{
private bool _isSelected;
public bool IsSelected
{
get { return _isSelected; }
set
{
if (_isSelected != value)
{
_isSelected = value;
RaisePropertyChanged("TextColor");
}
}
}
}
public class CashOperationViewModel : CashTransactionViewModelBase, ICashTransactionViewModel
{
public PaymentType PaymentType { get; set; }
public decimal Amount { get { return 0; } }
public string Description { get; set; }
public DateTime Date { get; set; }
public string DateString { get { return DateTime.Now.Day == Date.Day ? Date.ToShortTimeString() : Date.ToShortDateString(); } }
public decimal CashPaymentValue { get; set; }
public decimal CreditCardPaymentValue { get; set; }
public decimal TicketPaymentValue { get; set; }
public string TextColor { get { return IsSelected ? "White" : "Black"; } }
}
public class CashTransactionViewModel : CashTransactionViewModelBase, ICashTransactionViewModel
{
public CashTransactionViewModel(CashTransaction transaction)
{
Model = transaction;
}
public CashTransaction Model { get; set; }
public TransactionType TransactionType { get { return (TransactionType)Model.TransactionType; } set { Model.TransactionType = (int)value; } }
public PaymentType PaymentType { get { return (PaymentType)Model.PaymentType; } set { Model.PaymentType = (int)value; } }
public string Description { get { return Model.Name; } set { Model.Name = value; } }
public decimal Amount { get { return Model.Amount; } set { Model.Amount = value; } }
public DateTime Date { get { return Model.Date; } set { Model.Date = value; } }
public string DateString { get { return DateTime.Now.Day == Date.Day ? Date.ToShortTimeString() : Date.ToShortDateString(); } }
public decimal CashPaymentValue { get { return PaymentType == PaymentType.Cash ? Model.Amount : 0; } set { } }
public decimal CreditCardPaymentValue { get { return PaymentType == PaymentType.CreditCard ? Model.Amount : 0; } set { } }
public decimal TicketPaymentValue { get { return PaymentType == PaymentType.Ticket ? Model.Amount : 0; } set { } }
public string TextColor { get { if (IsSelected) return "White"; return Amount < 0 ? "Red" : "Black"; } }
}
}
| zzgaminginc-pointofssale | Samba.Modules.CashModule/CashTransactionViewModel.cs | C# | gpl3 | 3,236 |
using System.ComponentModel.Composition;
using Microsoft.Practices.Prism.MefExtensions.Modularity;
using Microsoft.Practices.Prism.Regions;
using Samba.Domain.Models.Customers;
using Samba.Localization.Properties;
using Samba.Presentation.Common;
using Samba.Services;
namespace Samba.Modules.CashModule
{
[ModuleExport(typeof(CashModule))]
public class CashModule : ModuleBase
{
private readonly IRegionManager _regionManager;
private readonly CashView _cashView;
public ICategoryCommand NavigateCashViewCommand { get; set; }
[ImportingConstructor]
public CashModule(IRegionManager regionManager, CashView cashView)
{
_regionManager = regionManager;
_cashView = cashView;
NavigateCashViewCommand = new CategoryCommand<string>(Resources.Drawer, Resources.Common, "images/Xls.png", OnNavigateCashView, CanNavigateCashView) { Order = 70 };
PermissionRegistry.RegisterPermission(PermissionNames.NavigateCashView, PermissionCategories.Navigation, Resources.CanNavigateCash);
PermissionRegistry.RegisterPermission(PermissionNames.MakeCashTransaction, PermissionCategories.Cash, Resources.CanMakeCashTransaction);
}
private static bool CanNavigateCashView(string arg)
{
return AppServices.IsUserPermittedFor(PermissionNames.NavigateCashView) && AppServices.MainDataContext.CurrentWorkPeriod != null;
}
private void OnNavigateCashView(string obj)
{
ActivateTransactionList();
}
private void ActivateTransactionList()
{
ActivateModuleScreen();
((CashViewModel)_cashView.DataContext).SelectedCustomer = null;
((CashViewModel)_cashView.DataContext).ActivateTransactionList();
}
private void ActivateModuleScreen()
{
AppServices.ActiveAppScreen = AppScreens.CashView;
_regionManager.Regions[RegionNames.MainRegion].Activate(_cashView);
}
protected override void OnInitialization()
{
_regionManager.RegisterViewWithRegion(RegionNames.MainRegion, typeof(CashView));
EventServiceFactory.EventService.GetEvent<GenericEvent<Customer>>().Subscribe(
x =>
{
if (x.Topic == EventTopicNames.MakePaymentToCustomer)
{
ActivateModuleScreen();
((CashViewModel)_cashView.DataContext).MakePaymentToCustomer(x.Value);
}
if (x.Topic == EventTopicNames.GetPaymentFromCustomer)
{
ActivateModuleScreen();
((CashViewModel)_cashView.DataContext).GetPaymentFromCustomer(x.Value);
}
if (x.Topic == EventTopicNames.AddLiabilityAmount)
{
ActivateModuleScreen();
((CashViewModel)_cashView.DataContext).AddLiabilityAmount(x.Value);
}
if (x.Topic == EventTopicNames.AddReceivableAmount)
{
ActivateModuleScreen();
((CashViewModel)_cashView.DataContext).AddReceivableAmount(x.Value);
}
});
}
protected override void OnPostInitialization()
{
CommonEventPublisher.PublishNavigationCommandEvent(NavigateCashViewCommand);
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.CashModule/CashModule.cs | C# | gpl3 | 3,661 |
using System.Data.Entity;
using Samba.Domain.Foundation;
using Samba.Domain.Models.Actions;
using Samba.Domain.Models.Customers;
using Samba.Domain.Models.Inventory;
using Samba.Domain.Models.Menus;
using Samba.Domain.Models.Settings;
using Samba.Domain.Models.Tables;
using Samba.Domain.Models.Tickets;
using Samba.Domain.Models.Transactions;
using Samba.Domain.Models.Users;
using Samba.Infrastructure.Data.SQL;
namespace Samba.Persistance.Data
{
public class SambaContext : CommonDbContext
{
public SambaContext(bool disableProxy)
: base("SambaData2")
{
if (disableProxy)
ObjContext().ContextOptions.ProxyCreationEnabled = false;
}
public DbSet<MenuItem> MenuItems { get; set; }
public DbSet<MenuItemPortion> MenuItemPortions { get; set; }
public DbSet<MenuItemProperty> MenuItemProperties { get; set; }
public DbSet<MenuItemPropertyGroup> MenuItemPropertyGroups { get; set; }
public DbSet<ScreenMenu> ScreenMenus { get; set; }
public DbSet<ScreenMenuCategory> ScreenMenuCategories { get; set; }
public DbSet<ScreenMenuItem> ScreenMenuItems { get; set; }
public DbSet<Payment> Payments { get; set; }
public DbSet<Ticket> Tickets { get; set; }
public DbSet<TicketItem> TicketItems { get; set; }
public DbSet<TicketItemProperty> TicketItemProperties { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<UserRole> UserRoles { get; set; }
public DbSet<Table> Tables { get; set; }
public DbSet<Terminal> Terminals { get; set; }
public DbSet<Printer> Printers { get; set; }
public DbSet<ProgramSetting> ProgramSettings { get; set; }
public DbSet<PrinterMap> PrinterMaps { get; set; }
public DbSet<PrinterTemplate> PrinterTemplates { get; set; }
public DbSet<TableScreen> TableScreens { get; set; }
public DbSet<Numerator> Numerators { get; set; }
public DbSet<Reason> Reasons { get; set; }
public DbSet<Discount> Discounts { get; set; }
public DbSet<WorkPeriod> WorkPeriods { get; set; }
public DbSet<PaidItem> PaidItems { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<Permission> Permissions { get; set; }
public DbSet<CashTransaction> CashTransactions { get; set; }
public DbSet<AccountTransaction> AccountTransactions { get; set; }
public DbSet<InventoryItem> InventoryItems { get; set; }
public DbSet<Recipe> Recipes { get; set; }
public DbSet<RecipeItem> RecipeItems { get; set; }
public DbSet<Transaction> Transactions { get; set; }
public DbSet<TransactionItem> TransactionItems { get; set; }
public DbSet<PeriodicConsumption> PeriodicConsumptions { get; set; }
public DbSet<PeriodicConsumptionItem> PeriodicConsumptionItems { get; set; }
public DbSet<CostItem> CostItems { get; set; }
public DbSet<TicketTag> TicketTags { get; set; }
public DbSet<AppAction> RuleActions { get; set; }
public DbSet<ActionContainer> ActionContainers { get; set; }
public DbSet<AppRule> Rules { get; set; }
public DbSet<Trigger> Triggers { get; set; }
public DbSet<MenuItemPriceDefinition> MenuItemPriceDefinitions { get; set; }
public DbSet<MenuItemPrice> MenuItemPrices { get; set; }
public DbSet<VatTemplate> VatTemplates { get; set; }
public DbSet<TaxServiceTemplate> TaxServiceTemplates { get; set; }
public DbSet<TaxService> TaxServices { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.ComplexType<Price>();
modelBuilder.ComplexType<DocumentDate>();
modelBuilder.Entity<MenuItem>().HasMany(p => p.PropertyGroups).WithMany();
modelBuilder.Entity<Department>().HasMany(p => p.TicketTagGroups).WithMany();
modelBuilder.Entity<Department>().HasMany(p => p.TaxServiceTemplates).WithMany();
modelBuilder.Entity<TableScreen>().HasMany(p => p.Tables).WithMany();
modelBuilder.Entity<Terminal>().HasMany(p => p.PrintJobs).WithMany();
const int scale = 2;
const int precision = 16;
modelBuilder.ComplexType<Price>().Property(x => x.Amount).HasPrecision(precision, scale);
//TaxServiceTemplate
modelBuilder.Entity<TaxServiceTemplate>().Property(x => x.Amount).HasPrecision(precision, scale);
//TaxService
modelBuilder.Entity<TaxService>().Property(x => x.Amount).HasPrecision(precision, scale);
modelBuilder.Entity<TaxService>().Property(x => x.CalculationAmount).HasPrecision(precision, scale);
//VatTemplate
modelBuilder.Entity<VatTemplate>().Property(x => x.Rate).HasPrecision(precision, scale);
//MenuItemPrice
modelBuilder.Entity<MenuItemPrice>().Property(x => x.Price).HasPrecision(precision, scale);
//Recipe
modelBuilder.Entity<Recipe>().Property(x => x.FixedCost).HasPrecision(precision, scale);
//CostItem
modelBuilder.Entity<CostItem>().Property(x => x.Quantity).HasPrecision(precision, scale);
modelBuilder.Entity<CostItem>().Property(x => x.CostPrediction).HasPrecision(precision, scale);
modelBuilder.Entity<CostItem>().Property(x => x.Cost).HasPrecision(precision, scale);
//PeriodicConsumptionIntem
modelBuilder.Entity<PeriodicConsumptionItem>().Property(x => x.InStock).HasPrecision(precision, scale);
modelBuilder.Entity<PeriodicConsumptionItem>().Property(x => x.Purchase).HasPrecision(precision, scale);
modelBuilder.Entity<PeriodicConsumptionItem>().Property(x => x.Consumption).HasPrecision(precision, scale);
modelBuilder.Entity<PeriodicConsumptionItem>().Property(x => x.PhysicalInventory).HasPrecision(precision, scale);
modelBuilder.Entity<PeriodicConsumptionItem>().Property(x => x.Cost).HasPrecision(precision, scale);
modelBuilder.Entity<PeriodicConsumptionItem>().Property(x => x.UnitMultiplier).HasPrecision(precision, scale);
//RecipeItem
modelBuilder.Entity<RecipeItem>().Property(x => x.Quantity).HasPrecision(precision, scale);
//TransactionItem
modelBuilder.Entity<TransactionItem>().Property(x => x.Price).HasPrecision(precision, scale);
modelBuilder.Entity<TransactionItem>().Property(x => x.Quantity).HasPrecision(precision, scale);
//CashTransaction
modelBuilder.Entity<CashTransaction>().Property(x => x.Amount).HasPrecision(precision, scale);
//AccountTransaction
modelBuilder.Entity<AccountTransaction>().Property(x => x.Amount).HasPrecision(precision, scale);
//WorkPeriod
modelBuilder.Entity<WorkPeriod>().Property(x => x.CashAmount).HasPrecision(precision, scale);
modelBuilder.Entity<WorkPeriod>().Property(x => x.CreditCardAmount).HasPrecision(precision, scale);
modelBuilder.Entity<WorkPeriod>().Property(x => x.TicketAmount).HasPrecision(precision, scale);
//PaidItem
modelBuilder.Entity<PaidItem>().Property(x => x.Quantity).HasPrecision(precision, scale);
modelBuilder.Entity<PaidItem>().Property(x => x.Price).HasPrecision(precision, scale);
//TicketItemProperty
modelBuilder.Entity<TicketItemProperty>().Property(x => x.Quantity).HasPrecision(precision, scale);
modelBuilder.Entity<TicketItemProperty>().Property(x => x.VatAmount).HasPrecision(precision, scale);
//TicketItem
modelBuilder.Entity<TicketItem>().Property(x => x.Quantity).HasPrecision(precision, scale);
modelBuilder.Entity<TicketItem>().Property(x => x.Price).HasPrecision(precision, scale);
modelBuilder.Entity<TicketItem>().Property(x => x.VatRate).HasPrecision(precision, scale);
modelBuilder.Entity<TicketItem>().Property(x => x.VatAmount).HasPrecision(precision, scale);
//Ticket
modelBuilder.Entity<Ticket>().Property(x => x.RemainingAmount).HasPrecision(precision, scale);
modelBuilder.Entity<Ticket>().Property(x => x.TotalAmount).HasPrecision(precision, scale);
//Payment
modelBuilder.Entity<Payment>().Property(x => x.Amount).HasPrecision(precision, scale);
//Discount
modelBuilder.Entity<Discount>().Property(x => x.Amount).HasPrecision(precision, scale);
modelBuilder.Entity<Discount>().Property(x => x.DiscountAmount).HasPrecision(precision, scale);
//modelBuilder.Entity<MenuItem>().Property(x => x.LastUpdateTime).HasStoreType("timestamp").IsConcurrencyToken();
////modelBuilder.Entity<MenuItemPortion>().Property(x => x.LastUpdateTime).HasStoreType("timestamp").IsConcurrencyToken();
////modelBuilder.Entity<MenuItemProperty>().Property(x => x.LastUpdateTime).HasStoreType("timestamp").IsConcurrencyToken();
//modelBuilder.Entity<MenuItemPropertyGroup>().Property(x => x.LastUpdateTime).HasStoreType("timestamp").IsConcurrencyToken();
//modelBuilder.Entity<ScreenMenu>().Property(x => x.LastUpdateTime).HasStoreType("timestamp").IsConcurrencyToken();
////modelBuilder.Entity<ScreenMenuCategory>().Property(x => x.LastUpdateTime).HasStoreType("timestamp").IsConcurrencyToken();
////modelBuilder.Entity<ScreenMenuItem>().Property(x => x.LastUpdateTime).HasStoreType("timestamp").IsConcurrencyToken();
////modelBuilder.Entity<Payment>().Property(x => x.LastUpdateTime).HasStoreType("timestamp").IsConcurrencyToken();
//modelBuilder.Entity<Ticket>().Property(x => x.LastUpdateTime).HasStoreType("timestamp").IsConcurrencyToken();
////modelBuilder.Entity<TicketItem>().Property(x => x.LastUpdateTime).HasStoreType("timestamp").IsConcurrencyToken();
////modelBuilder.Entity<TicketItemProperty>().Property(x => x.LastUpdateTime).HasStoreType("timestamp").IsConcurrencyToken();
//modelBuilder.Entity<Department>().Property(x => x.LastUpdateTime).HasStoreType("timestamp").IsConcurrencyToken();
//modelBuilder.Entity<User>().Property(x => x.LastUpdateTime).HasStoreType("timestamp").IsConcurrencyToken();
//modelBuilder.Entity<UserRole>().Property(x => x.LastUpdateTime).HasStoreType("timestamp").IsConcurrencyToken();
//modelBuilder.Entity<Table>().Property(x => x.LastUpdateTime).HasStoreType("timestamp").IsConcurrencyToken();
//modelBuilder.Entity<Terminal>().Property(x => x.LastUpdateTime).HasStoreType("timestamp").IsConcurrencyToken();
//modelBuilder.Entity<Printer>().Property(x => x.LastUpdateTime).HasStoreType("timestamp").IsConcurrencyToken();
//modelBuilder.Entity<ProgramSetting>().Property(x => x.LastUpdateTime).HasStoreType("timestamp").IsConcurrencyToken();
//modelBuilder.Entity<PrinterMap>().Property(x => x.LastUpdateTime).HasStoreType("timestamp").IsConcurrencyToken();
//modelBuilder.Entity<PrinterTemplate>().Property(x => x.LastUpdateTime).HasStoreType("timestamp").IsConcurrencyToken();
//modelBuilder.Entity<CurrencyContext>().Property(x => x.LastUpdateTime).HasStoreType("timestamp").IsConcurrencyToken();
//modelBuilder.Entity<TableScreen>().Property(x => x.LastUpdateTime).HasStoreType("timestamp").IsConcurrencyToken();
////modelBuilder.Entity<TableScreenItem>().Property(x => x.LastUpdateTime).HasStoreType("timestamp").IsConcurrencyToken();
modelBuilder.Entity<Numerator>().Property(x => x.LastUpdateTime).IsConcurrencyToken().HasColumnType(
"timestamp");
base.OnModelCreating(modelBuilder);
}
}
} | zzgaminginc-pointofssale | Samba.Persistance.Data/SambaContext.cs | C# | gpl3 | 12,273 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using Samba.Infrastructure.Data;
using Samba.Infrastructure.Data.Serializer;
namespace Samba.Persistance.Data
{
public static class Dao
{
private static readonly IDictionary<Type, IDictionary<int, Dictionary<int, IEntity>>> Cache = new Dictionary<Type, IDictionary<int, Dictionary<int, IEntity>>>();
private static void AddToCache<T>(int key, T item) where T : class,IEntity
{
if (item == null) return;
var type = typeof(T);
if (!Cache.ContainsKey(type)) Cache.Add(type, new Dictionary<int, Dictionary<int, IEntity>>());
if (!Cache[type].ContainsKey(key)) Cache[type].Add(key, new Dictionary<int, IEntity>());
try
{
Cache[type][key].Add(item.Id, item);
}
catch (Exception)
{
#if DEBUG
throw;
#else
Cache[type][key].Clear();
#endif
}
}
private static T GetFromCache<T>(Expression<Func<T, bool>> predictate, int key)
{
try
{
if (Cache.ContainsKey(typeof(T)))
if (Cache[typeof(T)].ContainsKey(key))
return Cache[typeof(T)][key].Values.Cast<T>().SingleOrDefault(predictate.Compile());
}
catch (Exception)
{
#if DEBUG
throw;
#else
ResetCache();
return default(T);
#endif
}
return default(T);
}
public static void ResetCache()
{
foreach (var arrayList in Cache.Values)
{
foreach (var item in arrayList.Values)
{
item.Clear();
}
arrayList.Clear();
}
Cache.Clear();
}
public static TResult Single<TSource, TResult>(int id, Expression<Func<TSource, TResult>> expression) where TSource : class,IEntity
{
using (var workspace = WorkspaceFactory.CreateReadOnly())
{
return workspace.Single(id, expression);
}
}
public static T Single<T>(Expression<Func<T, bool>> predictate, params Expression<Func<T, object>>[] includes) where T : class
{
using (var workspace = WorkspaceFactory.CreateReadOnly())
{
var result = workspace.Single(predictate, includes);
return result;
}
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public static T SingleWithCache<T>(Expression<Func<T, bool>> predictate, params Expression<Func<T, object>>[] includes) where T : class, IEntity
{
var lpredict = predictate;
var key = ObjectCloner.DataHash(includes);
var ci = GetFromCache(lpredict, key);
if (ci != null) return ci;
using (var workspace = WorkspaceFactory.CreateReadOnly())
{
var result = workspace.Single(lpredict, includes);
AddToCache(key, result);
return result;
}
}
public static IEnumerable<string> Distinct<T>(Expression<Func<T, string>> expression) where T : class
{
using (var workspace = WorkspaceFactory.CreateReadOnly())
{
return workspace.Distinct(expression).ToList();
}
}
public static IEnumerable<T> Query<T>(Expression<Func<T, bool>> predictate, params Expression<Func<T, object>>[] includes) where T : class
{
using (var workspace = WorkspaceFactory.CreateReadOnly())
{
return workspace.Query(predictate, includes).ToList();
}
}
public static IEnumerable<T> Query<T>(params Expression<Func<T, object>>[] includes) where T : class
{
using (var workspace = WorkspaceFactory.CreateReadOnly())
{
return workspace.Query(null, includes).ToList();
}
}
public static IEnumerable<TResult> Select<TSource, TResult>(Expression<Func<TSource, TResult>> expression,
Expression<Func<TSource, bool>> predictate) where TSource : class
{
using (var workspace = WorkspaceFactory.CreateReadOnly())
{
return workspace.Select(expression, predictate).ToList();
}
}
public static IDictionary<int, T> BuildDictionary<T>() where T : class,IEntity
{
IDictionary<int, T> result = new Dictionary<int, T>();
using (var workspace = WorkspaceFactory.CreateReadOnly())
{
var values = workspace.Query<T>(null);
foreach (var value in values)
{
result.Add(value.Id, value);
}
}
return result;
}
public static int Count<T>(Expression<Func<T, bool>> predictate) where T : class
{
using (var workspace = WorkspaceFactory.CreateReadOnly())
{
return workspace.Count(predictate);
}
}
public static decimal Sum<T>(Expression<Func<T, decimal>> func, Expression<Func<T, bool>> predictate) where T : class
{
using (var workspace = WorkspaceFactory.CreateReadOnly())
{
return workspace.Sum(func, predictate);
}
}
public static T Last<T>(Expression<Func<T, bool>> predictate, params Expression<Func<T, object>>[] includes) where T : class ,IEntity
{
using (var workspace = WorkspaceFactory.CreateReadOnly())
{
return workspace.Last(predictate, includes);
}
}
public static IEnumerable<T> Last<T>(int recordCount) where T : class,IEntity
{
using (var workspace = WorkspaceFactory.CreateReadOnly())
{
return workspace.Last<T>(recordCount).OrderBy(x => x.Id);
}
}
}
}
| zzgaminginc-pointofssale | Samba.Persistance.Data/Dao.cs | C# | gpl3 | 6,496 |
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("Samba.Persistance.Data")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Samba.Persistance.Data")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[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("2d375059-7b02-4eb8-8c94-f01c15308233")]
// 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")]
| zzgaminginc-pointofssale | Samba.Persistance.Data/Properties/AssemblyInfo.cs | C# | gpl3 | 1,474 |
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Globalization;
using System.IO;
using System.Linq;
using FluentMigrator.Runner;
using FluentMigrator.Runner.Announcers;
using FluentMigrator.Runner.Initialization;
using Microsoft.Win32;
using Samba.Infrastructure.Data;
using Samba.Infrastructure.Data.MongoDB;
using Samba.Infrastructure.Data.SQL;
using Samba.Infrastructure.Data.Text;
using Samba.Infrastructure.Settings;
namespace Samba.Persistance.Data
{
public static class WorkspaceFactory
{
private static TextFileWorkspace _textFileWorkspace;
private static readonly MongoWorkspace MongoWorkspace;
private static string _connectionString = LocalSettings.ConnectionString;
static WorkspaceFactory()
{
Database.SetInitializer(new Initializer());
if (string.IsNullOrEmpty(LocalSettings.ConnectionString))
{
if (IsSqlce40Installed())
LocalSettings.ConnectionString = "data source=" + LocalSettings.DocumentPath + "\\SambaData2.sdf";
else LocalSettings.ConnectionString = GetTextFileName();
}
if (LocalSettings.ConnectionString.EndsWith(".sdf"))
{
Database.DefaultConnectionFactory =
new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0", "", LocalSettings.ConnectionString);
}
else if (LocalSettings.ConnectionString.EndsWith(".txt"))
{
_textFileWorkspace = GetTextFileWorkspace();
}
else if (_connectionString.StartsWith("mongodb://"))
{
MongoWorkspace = GetMongoWorkspace();
}
else if (!string.IsNullOrEmpty(LocalSettings.ConnectionString))
{
var cs = LocalSettings.GetSqlServerConnectionString();
if (!cs.Trim().EndsWith(";"))
cs += ";";
if (!cs.ToLower().Contains("multipleactiveresultsets"))
cs += " MultipleActiveResultSets=True;";
if (!cs.ToLower(CultureInfo.InvariantCulture).Contains("user id") && (!cs.ToLower(CultureInfo.InvariantCulture).Contains("integrated security")))
cs += " Integrated Security=True;";
if (cs.ToLower(CultureInfo.InvariantCulture).Contains("user id") && !cs.ToLower().Contains("persist security info"))
cs += " Persist Security Info=True;";
Database.DefaultConnectionFactory =
new SqlConnectionFactory(cs);
}
}
private static bool IsSqlce40Installed()
{
var rk = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Microsoft SQL Server Compact Edition\\v4.0");
return rk != null;
}
public static IWorkspace Create()
{
if (MongoWorkspace != null) return MongoWorkspace;
if (_textFileWorkspace != null) return _textFileWorkspace;
return new EFWorkspace(new SambaContext(false));
}
public static IReadOnlyWorkspace CreateReadOnly()
{
if (MongoWorkspace != null) return MongoWorkspace;
if (_textFileWorkspace != null) return _textFileWorkspace;
return new ReadOnlyEFWorkspace(new SambaContext(true));
}
private static TextFileWorkspace GetTextFileWorkspace()
{
var fileName = GetTextFileName();
return new TextFileWorkspace(fileName, false);
}
private static string GetTextFileName()
{
return _connectionString.EndsWith(".txt")
? _connectionString
: LocalSettings.DocumentPath + "\\SambaData.txt";
}
private static MongoWorkspace GetMongoWorkspace()
{
return new MongoWorkspace(_connectionString);
}
public static void SetDefaultConnectionString(string cTestdataTxt)
{
_connectionString = cTestdataTxt;
if (string.IsNullOrEmpty(_connectionString) || _connectionString.EndsWith(".txt"))
_textFileWorkspace = GetTextFileWorkspace();
}
}
class Initializer : IDatabaseInitializer<SambaContext>
{
public void InitializeDatabase(SambaContext context)
{
if (!context.Database.Exists())
{
Create(context);
}
//#if DEBUG
// else if (!context.Database.CompatibleWithModel(false))
// {
// context.Database.Delete();
// Create(context);
// }
//#else
else
{
Migrate(context);
}
//#endif
var version = context.ObjContext().ExecuteStoreQuery<long>("select top(1) Version from VersionInfo order by version desc").FirstOrDefault();
LocalSettings.CurrentDbVersion = version;
}
private static void Create(CommonDbContext context)
{
context.Database.Create();
context.ObjContext().ExecuteStoreCommand("CREATE TABLE VersionInfo (Version bigint not null)");
context.ObjContext().ExecuteStoreCommand("CREATE NONCLUSTERED INDEX IX_Tickets_LastPaymentDate ON Tickets(LastPaymentDate)");
if (!context.Database.Connection.ConnectionString.ToLower().Contains(".sdf"))
{
context.ObjContext().ExecuteStoreCommand("CREATE NONCLUSTERED INDEX IDX_TicketItems_All ON TicketItems (TicketId) INCLUDE (Id,MenuItemId,MenuItemName,PortionName,Price,CurrencyCode,Quantity,PortionCount,Locked,Voided,ReasonId,Gifted,OrderNumber,CreatingUserId,CreatedDateTime,ModifiedUserId,ModifiedDateTime,PriceTag,Tag,DepartmentId,VatRate,VatAmount,VatTemplateId,VatIncluded)");
context.ObjContext().ExecuteStoreCommand("CREATE NONCLUSTERED INDEX IDX_TicketItemProperties_All ON TicketItemProperties (TicketItemId) INCLUDE (Id,Name,PropertyPrice_CurrencyCode,PropertyPrice_Amount,PropertyGroupId,Quantity,MenuItemId,PortionName,CalculateWithParentPrice,VatAmount)");
context.ObjContext().ExecuteStoreCommand("CREATE NONCLUSTERED INDEX IDX_Payments_All ON Payments (Ticket_Id) INCLUDE (Id,Amount,Date,PaymentType,UserId,DepartmentId)");
}
GetMigrateVersions(context);
LocalSettings.CurrentDbVersion = LocalSettings.DbVersion;
}
private static void GetMigrateVersions(CommonDbContext context)
{
for (var i = 0; i < LocalSettings.DbVersion; i++)
{
context.ObjContext().ExecuteStoreCommand("Insert into VersionInfo (Version) Values (" + (i + 1) + ")");
}
}
private static void Migrate(CommonDbContext context)
{
if (!File.Exists(LocalSettings.UserPath + "\\migrate.txt")) return;
var db = context.Database.Connection.ConnectionString.Contains(".sdf") ? "sqlserverce" : "sqlserver";
using (IAnnouncer announcer = new TextWriterAnnouncer(Console.Out))
{
IRunnerContext migrationContext =
new RunnerContext(announcer)
{
Connection = context.Database.Connection.ConnectionString,
Database = db,
Target = LocalSettings.AppPath + "\\Samba.Persistance.DbMigration.dll"
};
var executor = new TaskExecutor(migrationContext);
executor.Execute();
}
File.Delete(LocalSettings.UserPath + "\\migrate.txt");
}
}
}
| zzgaminginc-pointofssale | Samba.Persistance.Data/WorkspaceFactory.cs | C# | gpl3 | 8,017 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace Samba.Persistance.Data
{
public static class ExpUtility
{
public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
{
if (second == null) return first;
// build parameter map (from parameters of second to parameters of first)
var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f);
// replace parameters in the second lambda expression with parameters from the first
var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);
// apply composition of lambda expression bodies to parameters from the first expression
return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);
}
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
{
return first.Compose(second, Expression.And);
}
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
{
return first.Compose(second, Expression.Or);
}
}
public class ParameterRebinder : ExpressionVisitor
{
private readonly Dictionary<ParameterExpression, ParameterExpression> map;
public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
{
this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
}
public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
{
return new ParameterRebinder(map).Visit(exp);
}
protected override Expression VisitParameter(ParameterExpression p)
{
ParameterExpression replacement;
if (map.TryGetValue(p, out replacement))
{
p = replacement;
}
return base.VisitParameter(p);
}
}
}
| zzgaminginc-pointofssale | Samba.Persistance.Data/ExpUtility.cs | C# | gpl3 | 2,329 |
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("Samba.Services.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Samba.Services.Test")]
[assembly: AssemblyCopyright("Copyright © 2010")]
[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("57ec9dc6-7db1-4fff-a189-f0f742eff8cf")]
// 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.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| zzgaminginc-pointofssale | Samba.Services.Test/Properties/AssemblyInfo.cs | C# | gpl3 | 1,409 |
using System;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;
using Samba.Infrastructure.Settings;
using Samba.Services;
namespace Samba.Presentation
{
/// <summary>
/// Interaction logic for MessageClientStatusView.xaml
/// </summary>
public partial class MessageClientStatusView : UserControl
{
private readonly Timer _timer;
private void OnTimerTick(object state)
{
if(Application.Current == null) return;
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle,
new Action(delegate
{
if (AppServices.MessagingService.IsConnected)
{
StatusLabel.Content = Localization.Properties.Resources.MS_Connected;
StatusLabel.Foreground = Brushes.Green;
}
else
{
StatusLabel.Content = Localization.Properties.Resources.MS_Disconnected;
StatusLabel.Foreground = Brushes.Red;
}
}));
}
public MessageClientStatusView()
{
InitializeComponent();
_timer = new Timer(OnTimerTick, null, Timeout.Infinite, 1000);
if (LocalSettings.StartMessagingClient)
{
_timer.Change(10000, 10000);
}
else StatusLabel.Visibility = Visibility.Collapsed;
}
}
}
| zzgaminginc-pointofssale | Samba.Presentation/MessageClientStatusView.xaml.cs | C# | gpl3 | 1,651 |
using System;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using Samba.Domain.Models.Settings;
using Samba.Presentation.Common;
using Samba.Services;
namespace Samba.Presentation
{
/// <summary>
/// Interaction logic for WorkPeriodStatusViewModel.xaml
/// </summary>
public partial class WorkPeriodStatusView : UserControl
{
private Timer _timer;
public WorkPeriodStatusView()
{
InitializeComponent();
EventServiceFactory.EventService.GetEvent<GenericEvent<WorkPeriod>>().Subscribe(OnWorkperiodStatusChanged);
}
private void OnWorkperiodStatusChanged(EventParameters<WorkPeriod> obj)
{
if (obj.Topic == EventTopicNames.WorkPeriodStatusChanged)
{
_timer.Change(1, 60000);
}
}
protected override void OnInitialized(EventArgs e)
{
_timer = new Timer(OnTimerTick, null, 30000, 60000);
base.OnInitialized(e);
}
private void OnTimerTick(object state)
{
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action(delegate
{
try
{
if (AppServices.ActiveAppScreen == AppScreens.LoginScreen) return;
if (AppServices.MainDataContext.IsCurrentWorkPeriodOpen)
{
var ts = new TimeSpan(DateTime.Now.Ticks - AppServices.MainDataContext.CurrentWorkPeriod.StartDate.Ticks);
tbWorkPeriodStatus.Visibility = ts.TotalHours > 24 ? Visibility.Visible : Visibility.Collapsed;
}
else tbWorkPeriodStatus.Visibility = Visibility.Collapsed;
}
catch (Exception)
{
_timer.Change(Timeout.Infinite, Timeout.Infinite);
}
}));
}
}
}
| zzgaminginc-pointofssale | Samba.Presentation/WorkPeriodStatusView.xaml.cs | C# | gpl3 | 2,090 |
using System;
using System.Linq;
using System.Windows;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Samba.Infrastructure;
using Samba.Infrastructure.Settings;
using Samba.Presentation.Common.ErrorReport;
using Samba.Presentation.Common.Services;
namespace Samba.Presentation
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
if (e.Args.Length > 0)
{
var langArg = e.Args.Where(x => !x.Contains("="));
if (langArg.Count() > 0)
{
var lang = langArg.ElementAt(0).Trim('/');
if (string.IsNullOrEmpty(LocalSettings.CurrentLanguage) && LocalSettings.SupportedLanguages.Contains(lang))
LocalSettings.CurrentLanguage = lang;
}
LocalSettings.StartupArguments = e.Args.Aggregate("", (current, arg) => current + arg);
}
#if (DEBUG)
RunInDebugMode();
#else
RunInReleaseMode();
#endif
this.ShutdownMode = ShutdownMode.OnMainWindowClose;
}
protected override void OnExit(ExitEventArgs e)
{
if (MessagingClient.IsConnected)
MessagingClient.Disconnect();
TriggerService.CloseTriggers();
}
private static void RunInDebugMode()
{
var bootstrapper = new Bootstrapper();
bootstrapper.Run();
}
private static void RunInReleaseMode()
{
AppDomain.CurrentDomain.UnhandledException += AppDomainUnhandledException;
Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
try
{
var bootstrapper = new Bootstrapper();
bootstrapper.Run();
}
catch (Exception ex)
{
HandleException(ex);
}
}
static void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
HandleException(e.Exception);
}
private static void AppDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
HandleException(e.ExceptionObject as Exception);
}
private static void HandleException(Exception ex)
{
if (ex == null) return;
ExceptionPolicy.HandleException(ex, "Policy");
//MessageBox.Show(Localization.Properties.Resources.UnhandledExceptionErrorMessage, Localization.Properties.Resources.Warning);
ExceptionReporter.Show(ex);
Environment.Exit(1);
}
}
}
| zzgaminginc-pointofssale | Samba.Presentation/App.xaml.cs | C# | gpl3 | 2,963 |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Data;
namespace Samba.Presentation
{
public class VisibilityConverter : IValueConverter
{
public object Convert(
object value,
Type targetType,
object parameter,
CultureInfo culture)
{
//bool visibility = (bool)value;
//return visibility ? Visibility.Visible : Visibility.Collapsed;
bool param = parameter != null ? bool.Parse(parameter as string) : true;
bool val = (bool)value;
return val == param ?
Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(
object value,
Type targetType,
object parameter,
CultureInfo culture)
{
Visibility visibility = (Visibility)value;
return (visibility == Visibility.Visible);
}
}
//public class BoolToVisibilityConverter : IValueConverter
//{
// public object Convert(object value, Type targetType,
// object parameter, System.Globalization.CultureInfo culture)
// {
// bool param = bool.Parse(parameter as string);
// bool val = (bool)value;
// return val == param ?
// Visibility.Visible : Visibility.Hidden;
// }
// public object ConvertBack(object value, Type targetType,
// object parameter, System.Globalization.CultureInfo culture)
// {
// throw new NotImplementedException();
// }
//}
}
| zzgaminginc-pointofssale | Samba.Presentation/VisibilityConverter.cs | C# | gpl3 | 1,767 |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("Samba POS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Samba POS")]
[assembly: AssemblyCopyright("Copyright © 2010")]
[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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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")]
| zzgaminginc-pointofssale | Samba.Presentation/Properties/AssemblyInfo.cs | C# | gpl3 | 2,282 |
using System;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.Prism.Logging;
namespace Samba.Presentation
{
public class EntLibLoggerAdapter : ILoggerFacade
{
public void Log(string message, Category category, Priority priority)
{
try
{
Logger.Write(message, category.ToString(), (int)priority);
}
catch (Exception)
{
}
}
}
}
| zzgaminginc-pointofssale | Samba.Presentation/EntLibLoggerAdapter.cs | C# | gpl3 | 505 |
using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.ComponentModel.Composition;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Threading;
using Samba.Domain.Models.Users;
using Samba.Infrastructure.Settings;
using Samba.Presentation.Common;
using Samba.Presentation.Common.Services;
using Samba.Services;
namespace Samba.Presentation
{
/// <summary>
/// Interaction logic for Shell.xaml
/// </summary>
[Export]
public partial class Shell : Window
{
private readonly DispatcherTimer _timer;
[ImportingConstructor]
public Shell()
{
InitializeComponent();
LanguageProperty.OverrideMetadata(
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
var selectedIndexChange = DependencyPropertyDescriptor.FromProperty(Selector.SelectedIndexProperty, typeof(TabControl));
selectedIndexChange.AddValueChanged(MainTabControl, MainTabControlSelectedIndexChanged);
EventServiceFactory.EventService.GetEvent<GenericEvent<User>>().Subscribe(x =>
{
if (x.Topic == EventTopicNames.UserLoggedIn) UserLoggedIn(x.Value);
if (x.Topic == EventTopicNames.UserLoggedOut) UserLoggedOut(x.Value);
});
EventServiceFactory.EventService.GetEvent<GenericEvent<UserControl>>().Subscribe(
x =>
{
if (x.Topic == EventTopicNames.DashboardClosed)
AppServices.ResetCache();
});
UserRegion.Visibility = Visibility.Collapsed;
RightUserRegion.Visibility = Visibility.Collapsed;
Height = Properties.Settings.Default.ShellHeight;
Width = Properties.Settings.Default.ShellWidth;
_timer = new DispatcherTimer();
_timer.Tick += TimerTick;
TimeLabel.Text = "..."; // DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString();
#if !DEBUG
WindowStyle = WindowStyle.None;
WindowState = WindowState.Maximized;
#endif
}
void TimerTick(object sender, EventArgs e)
{
var time = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString();
TimeLabel.Text = TimeLabel.Text.Contains(":") ? time.Replace(":", " ") : time;
MethodQueue.RunQueue();
}
private void MainTabControlSelectedIndexChanged(object sender, EventArgs e)
{
MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}
public void UserLoggedIn(User user)
{
UserRegion.Visibility = Visibility.Visible;
RightUserRegion.Visibility = Visibility.Visible;
}
public void UserLoggedOut(User user)
{
AppServices.ActiveAppScreen = AppScreens.LoginScreen;
MainTabControl.SelectedIndex = 0;
UserRegion.Visibility = Visibility.Collapsed;
RightUserRegion.Visibility = Visibility.Collapsed;
}
private void TextBlockMouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ClickCount == 2)
{
if (WindowStyle != WindowStyle.SingleBorderWindow)
{
WindowStyle = WindowStyle.SingleBorderWindow;
WindowState = WindowState.Normal;
}
else
{
WindowStyle = WindowStyle.None;
WindowState = WindowState.Maximized;
}
}
}
private void WindowClosing(object sender, CancelEventArgs e)
{
if (AppServices.MainDataContext.SelectedTicket != null)
{
e.Cancel = true;
return;
}
if (WindowState == WindowState.Normal)
{
Properties.Settings.Default.ShellHeight = Height;
Properties.Settings.Default.ShellWidth = Width;
}
Properties.Settings.Default.Save();
}
private void WindowLoaded(object sender, RoutedEventArgs e)
{
Title = Title + " [App: " + LocalSettings.AppVersion + "]";
if (LocalSettings.CurrentDbVersion > 0)
Title += " [DB: " + LocalSettings.DbVersion + "-" + LocalSettings.CurrentDbVersion + "]";
_timer.Interval = TimeSpan.FromSeconds(1);
_timer.Start();
}
}
}
| zzgaminginc-pointofssale | Samba.Presentation/Shell.xaml.cs | C# | gpl3 | 5,000 |
using System;
using System.ComponentModel.Composition.Hosting;
using System.Windows;
using Microsoft.Practices.Prism.Logging;
using Microsoft.Practices.Prism.MefExtensions;
using Microsoft.Practices.ServiceLocation;
using Samba.Infrastructure.Settings;
using Samba.Localization.Engine;
using Samba.Localization.Properties;
using Samba.Presentation.Common;
using Samba.Presentation.Common.Services;
using Samba.Presentation.ViewModels;
using Samba.Services;
namespace Samba.Presentation
{
public class Bootstrapper : MefBootstrapper
{
private readonly EntLibLoggerAdapter _logger = new EntLibLoggerAdapter();
protected override DependencyObject CreateShell()
{
return Container.GetExportedValue<Shell>();
}
protected override void ConfigureAggregateCatalog()
{
base.ConfigureAggregateCatalog();
var path = System.IO.Path.GetDirectoryName(Application.ResourceAssembly.Location);
if (path != null)
{
AggregateCatalog.Catalogs.Add(new DirectoryCatalog(path, "Samba.Login*"));
AggregateCatalog.Catalogs.Add(new DirectoryCatalog(path, "Samba.Modules*"));
AggregateCatalog.Catalogs.Add(new DirectoryCatalog(path, "Samba.Presentation*"));
AggregateCatalog.Catalogs.Add(new DirectoryCatalog(path, "Samba.Services.dll"));
}
LocalSettings.AppPath = path;
}
protected override ILoggerFacade CreateLogger()
{
return _logger;
}
protected override void InitializeModules()
{
base.InitializeModules();
var moduleInitializationService = ServiceLocator.Current.GetInstance<IModuleInitializationService>();
moduleInitializationService.Initialize();
}
protected override void InitializeShell()
{
LocalizeDictionary.ChangeLanguage(LocalSettings.CurrentLanguage);
LocalSettings.SetTraceLogPath("app");
InteractionService.UserIntraction = ServiceLocator.Current.GetInstance<IUserInteraction>();
InteractionService.UserIntraction.ToggleSplashScreen();
AppServices.MainDispatcher = Application.Current.Dispatcher;
AppServices.MessagingService.RegisterMessageListener(new MessageListener());
if (LocalSettings.StartMessagingClient)
AppServices.MessagingService.StartMessagingClient();
GenericRuleRegistator.RegisterOnce();
PresentationServices.Initialize();
base.InitializeShell();
try
{
var creationService = new DataCreationService();
creationService.CreateData();
}
catch (Exception e)
{
if (!string.IsNullOrEmpty(LocalSettings.ConnectionString))
{
var connectionString =
InteractionService.UserIntraction.GetStringFromUser(
"Connection String",
Resources.DatabaseErrorMessage + e.Message,
LocalSettings.ConnectionString);
var cs = String.Join(" ", connectionString);
if (!string.IsNullOrEmpty(cs))
LocalSettings.ConnectionString = cs.Trim();
AppServices.LogError(e, Resources.CurrentErrorLoggedMessage);
}
else
{
AppServices.LogError(e);
LocalSettings.ConnectionString = "";
}
LocalSettings.SaveSettings();
Environment.Exit(1);
}
if (string.IsNullOrEmpty(LocalSettings.MajorCurrencyName))
{
LocalSettings.MajorCurrencyName = Resources.Dollar;
LocalSettings.MinorCurrencyName = Resources.Cent;
LocalSettings.PluralCurrencySuffix = Resources.PluralCurrencySuffix;
}
Application.Current.MainWindow = (Shell)Shell;
Application.Current.MainWindow.Show();
InteractionService.UserIntraction.ToggleSplashScreen();
TriggerService.UpdateCronObjects();
RuleExecutor.NotifyEvent(RuleEventNames.ApplicationStarted, new { CommandLineArguments = LocalSettings.StartupArguments });
}
}
}
| zzgaminginc-pointofssale | Samba.Presentation/Bootstrapper.cs | C# | gpl3 | 4,580 |
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("Samba.Login")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Samba.Login")]
[assembly: AssemblyCopyright("Copyright © 2010")]
[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("07c2d44c-9d48-4686-924a-aea06958993c")]
// 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")]
| zzgaminginc-pointofssale | Samba.Modules.LoginModule/Properties/AssemblyInfo.cs | C# | gpl3 | 1,434 |
using System.ComponentModel.Composition;
using Microsoft.Practices.Prism.MefExtensions.Modularity;
using Microsoft.Practices.Prism.Modularity;
using Microsoft.Practices.Prism.Regions;
namespace Samba.Login
{
[ModuleExport(typeof(LoginModule))]
public class LoginModule : IModule
{
readonly IRegionManager _regionManager;
[ImportingConstructor]
public LoginModule(IRegionManager regionManager)
{
_regionManager = regionManager;
}
public void Initialize()
{
_regionManager.RegisterViewWithRegion("MainRegion", typeof(LoginView));
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.LoginModule/LoginModule.cs | C# | gpl3 | 668 |
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel.Composition;
using System.Windows.Input;
using Samba.Presentation.Common;
namespace Samba.Login
{
/// <summary>
/// Interaction logic for LoginView.xaml
/// </summary>
[Export]
public partial class LoginView : UserControl
{
[ImportingConstructor]
public LoginView(LoginViewModel viewModel)
{
InitializeComponent();
DataContext = viewModel;
}
private void LoginPadControl_PinSubmitted(object sender, string pinValue)
{
pinValue.PublishEvent(EventTopicNames.PinSubmitted);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Application.Current.Shutdown();
}
private void UserControl_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
{
if (!string.IsNullOrEmpty(e.Text)&& char.IsDigit(e.Text, 0))
PadControl.UpdatePinValue(e.Text);
}
private void UserControl_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if(e.Key == Key.Enter)
PadControl.SubmitPin();
}
private void Hyperlink_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
{
Uri u = new Uri(Localization.Properties.Resources.ClientServerConnectionHelpUrlString);
Process.Start(new ProcessStartInfo(u.AbsoluteUri));
e.Handled = true;
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.LoginModule/LoginView.xaml.cs | C# | gpl3 | 1,707 |
using System.Windows;
using System.Windows.Controls;
using Samba.Presentation.Common;
using Samba.Services;
namespace Samba.Login
{
public delegate void PinSubmittedEventHandler(object sender, string pinValue);
/// <summary>
/// Interaction logic for LoginPadControl.xaml
/// </summary>
public partial class LoginPadControl : UserControl
{
public event PinSubmittedEventHandler PinSubmitted;
private string _pinValue = string.Empty;
public LoginPadControl()
{
InitializeComponent();
PinValue = EmptyString;
}
private string PinValue { get { return _pinValue; } set { _pinValue = value; UpdatePinTextBox(_pinValue); } }
private static string EmptyString { get { return " " + Localization.Properties.Resources.EnterPin; } }
private void UpdatePinTextBox(string _pinValue)
{
if (_pinValue == EmptyString)
PinTextBox.Text = _pinValue;
else
PinTextBox.Text = "".PadLeft(_pinValue.Length, '*');
}
private bool CheckPinValue()
{
if (_pinValue == EmptyString)
PinValue = "";
return _pinValue.Length < 9;
}
public void UpdatePinValue(string value)
{
if (CheckPinValue())
{
PinValue += value;
}
}
public void SubmitPin()
{
if (PinSubmitted != null && AppServices.CanStartApplication())
PinSubmitted(this, _pinValue);
else
{
if (!AppServices.CanStartApplication())
MessageBox.Show(Localization.Properties.Resources.CheckDBVersion);
}
PinValue = EmptyString;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
SubmitPin();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
UpdatePinValue("1");
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
UpdatePinValue("2");
}
private void Button_Click_3(object sender, RoutedEventArgs e)
{
UpdatePinValue("3");
}
private void Button_Click_4(object sender, RoutedEventArgs e)
{
UpdatePinValue("4");
}
private void Button_Click_5(object sender, RoutedEventArgs e)
{
UpdatePinValue("5");
}
private void Button_Click_6(object sender, RoutedEventArgs e)
{
UpdatePinValue("6");
}
private void Button_Click_7(object sender, RoutedEventArgs e)
{
UpdatePinValue("7");
}
private void Button_Click_8(object sender, RoutedEventArgs e)
{
UpdatePinValue("8");
}
private void Button_Click_9(object sender, RoutedEventArgs e)
{
UpdatePinValue("9");
}
private void Button_Click_10(object sender, RoutedEventArgs e)
{
UpdatePinValue("0");
}
private void Button_Click_11(object sender, RoutedEventArgs e)
{
PinValue = "";
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
PinTextBox.BackgroundFocus();
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.LoginModule/LoginPadControl.xaml.cs | C# | gpl3 | 3,564 |
using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using Samba.Infrastructure.Settings;
using Samba.Localization.Properties;
using Samba.Services;
namespace Samba.Login
{
[Export]
public class LoginViewModel
{
public string LogoPath
{
get
{
if (File.Exists(LocalSettings.LogoPath))
return LocalSettings.LogoPath;
if (File.Exists(LocalSettings.DocumentPath + "\\Images\\logo.png"))
return LocalSettings.DocumentPath + "\\Images\\logo.png";
if (File.Exists(LocalSettings.AppPath + "\\Images\\logo.png"))
return LocalSettings.AppPath + "\\Images\\logo.png";
return LocalSettings.AppPath + "\\Images\\empty.png";
}
set { LocalSettings.LogoPath = value; }
}
public string AppLabel { get { return "SAMBA POS " + LocalSettings.AppVersion + " - " + GetDatabaseLabel(); } }
public string AdminPasswordHint { get { return GetAdminPasswordHint(); } }
public string SqlHint { get { return GetSqlHint(); } }
public bool IsExitButtonVisible { get { return !AppServices.CurrentTerminal.HideExitButton; } }
private static string GetSqlHint()
{
return !string.IsNullOrEmpty(GetAdminPasswordHint())
? Resources.SqlHint : "";
}
private static string GetDatabaseLabel()
{
return LocalSettings.DatabaseLabel;
}
public static string GetAdminPasswordHint()
{
if ((GetDatabaseLabel() == "TX" || GetDatabaseLabel() == "CE")
&& AppServices.MainDataContext.Users.Count() == 1
&& AppServices.MainDataContext.Users.ElementAt(0).PinCode == "1234")
{
return Resources.AdminPasswordHint;
}
return "";
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.LoginModule/LoginViewModel.cs | C# | gpl3 | 2,033 |
using System;
using System.ComponentModel.Composition;
using Microsoft.Practices.Prism.Events;
using Samba.Domain.Models.Settings;
using Samba.Domain.Models.Tickets;
using Samba.Domain.Models.Users;
using Samba.Presentation.Common;
using Samba.Presentation.ViewModels;
using Samba.Services;
namespace Samba.Modules.TicketModule
{
[Export]
public class TicketEditorViewModel : ObservableObject
{
[ImportingConstructor]
public TicketEditorViewModel()
{
TicketListViewModel = new TicketListViewModel();
MenuItemSelectorViewModel = new MenuItemSelectorViewModel(TicketListViewModel.AddMenuItemCommand);
PaymentViewModel = new PaymentEditorViewModel();
SelectedTicketItemsViewModel = new SelectedTicketItemsViewModel();
TicketExplorerViewModel = new TicketExplorerViewModel();
DisplayCategoriesScreen();
EventServiceFactory.EventService.GetEvent<GenericEvent<TicketViewModel>>().Subscribe(OnTicketViewModelEvent);
EventServiceFactory.EventService.GetEvent<GenericEvent<Ticket>>().Subscribe(OnTicketEvent);
EventServiceFactory.EventService.GetEvent<GenericEvent<User>>().Subscribe(OnUserLoginEvent);
EventServiceFactory.EventService.GetEvent<GenericEvent<WorkPeriod>>().Subscribe(OnWorkPeriodEvent);
EventServiceFactory.EventService.GetEvent<GenericEvent<EventAggregator>>().Subscribe(
x =>
{
if (x.Topic == EventTopicNames.ActivateTicketView || x.Topic == EventTopicNames.DisplayTicketView)
{
DisplayCategoriesScreen();
}
});
}
public CaptionCommand<Ticket> DisplayPaymentScreenCommand { get; set; }
public MenuItemSelectorViewModel MenuItemSelectorViewModel { get; set; }
public TicketListViewModel TicketListViewModel { get; set; }
public PaymentEditorViewModel PaymentViewModel { get; set; }
public SelectedTicketItemsViewModel SelectedTicketItemsViewModel { get; set; }
public TicketExplorerViewModel TicketExplorerViewModel { get; set; }
private int _selectedView;
public int SelectedView
{
get { return _selectedView; }
set { _selectedView = value; RaisePropertyChanged("SelectedView"); }
}
private int _selectedSubView;
public int SelectedSubView
{
get { return _selectedSubView; }
set { _selectedSubView = value; RaisePropertyChanged("SelectedSubView"); }
}
private void OnUserLoginEvent(EventParameters<User> obj)
{
if (obj.Topic == EventTopicNames.UserLoggedOut)
{
CloseTicket();
}
}
private void CloseTicket()
{
if (AppServices.MainDataContext.SelectedTicket != null)
AppServices.MainDataContext.CloseTicket();
TicketListViewModel.SelectedDepartment = null;
}
private void OnWorkPeriodEvent(EventParameters<WorkPeriod> obj)
{
if (obj.Topic == EventTopicNames.DisplayTicketExplorer)
{
DisplayTicketExplorerScreen();
}
}
private void OnTicketViewModelEvent(EventParameters<TicketViewModel> obj)
{
if (obj.Topic == EventTopicNames.SelectedItemsChanged)
{
if (SelectedTicketItemsViewModel.ShouldDisplay(obj.Value))
DisplayTicketDetailsScreen();
else DisplayCategoriesScreen();
}
if (obj.Topic == EventTopicNames.SelectVoidReason
|| obj.Topic == EventTopicNames.SelectGiftReason
|| obj.Topic == EventTopicNames.SelectExtraProperty
|| obj.Topic == EventTopicNames.SelectTicketTag
|| obj.Topic == EventTopicNames.EditTicketNote)
{
DisplayTicketDetailsScreen();
}
}
private void OnTicketEvent(EventParameters<Ticket> obj)
{
switch (obj.Topic)
{
case EventTopicNames.MakePayment:
AppServices.ActiveAppScreen = AppScreens.Payment;
PaymentViewModel.Prepare();
DisplayPaymentScreen();
break;
case EventTopicNames.PaymentSubmitted:
DisplayCategoriesScreen();
break;
}
}
private void DisplayCategoriesScreen()
{
DisplayTicketItemsScreen();
}
private void DisplayPaymentScreen()
{
SelectedView = 1;
}
public void DisplayTicketItemsScreen()
{
SelectedView = 0;
SelectedSubView = 0;
this.PublishEvent(EventTopicNames.FocusTicketScreen);
}
public void DisplayTicketDetailsScreen()
{
SelectedView = 0;
SelectedSubView = 1;
this.PublishEvent(EventTopicNames.FocusTicketScreen);
}
public void DisplayTicketExplorerScreen()
{
SelectedView = 0;
SelectedSubView = 2;
TicketExplorerViewModel.StartDate = AppServices.MainDataContext.CurrentWorkPeriod.StartDate.Date;
if (!AppServices.IsUserPermittedFor(PermissionNames.DisplayOldTickets))
{
TicketExplorerViewModel.StartDate = AppServices.MainDataContext.CurrentWorkPeriod.StartDate;
}
TicketExplorerViewModel.EndDate = DateTime.Now;
TicketExplorerViewModel.Refresh();
}
public bool HandleTextInput(string text)
{
if ((AppServices.ActiveAppScreen == AppScreens.TicketList || AppServices.ActiveAppScreen == AppScreens.SingleTicket)
&& SelectedView == 0 && SelectedSubView == 0)
return MenuItemSelectorViewModel.HandleTextInput(text);
return false;
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.TicketModule/TicketEditorViewModel.cs | C# | gpl3 | 6,315 |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Timers;
using System.Windows.Input;
using System.Windows.Threading;
using Samba.Domain.Models.Tickets;
using Samba.Localization.Properties;
using Samba.Persistance.Data;
using Samba.Presentation.Common;
using Samba.Services;
namespace Samba.Modules.TicketModule
{
public class TicketExplorerViewModel : ObservableObject
{
private readonly Timer _timer;
public TicketExplorerViewModel()
{
ResetFilters();
_timer = new Timer(250);
_timer.Elapsed += TimerElapsed;
CloseCommand = new CaptionCommand<string>(Resources.Close, OnCloseCommandExecuted);
PreviousWorkPeriod = new CaptionCommand<string>("<<", OnExecutePreviousWorkPeriod);
NextWorkPeriod = new CaptionCommand<string>(">>", OnExecuteNextWorkPeriod);
RefreshDatesCommand = new CaptionCommand<string>(Resources.Refresh, OnRefreshDates);
}
private IList<TicketExplorerFilter> _filters;
public IList<TicketExplorerFilter> Filters
{
get { return _filters; }
set
{
_filters = value;
RaisePropertyChanged("Filters");
}
}
public ICaptionCommand PreviousWorkPeriod { get; set; }
public ICaptionCommand NextWorkPeriod { get; set; }
public ICaptionCommand RefreshDatesCommand { get; set; }
public ICaptionCommand CloseCommand { get; set; }
public bool CanChanageDateFilter { get { return AppServices.IsUserPermittedFor(PermissionNames.DisplayOldTickets); } }
private DateTime _startDate;
public DateTime StartDate
{
get { return _startDate; }
set
{
_startDate = value;
EndDate = value;
RaisePropertyChanged("StartDate");
}
}
private DateTime _endDate;
public DateTime EndDate
{
get { return _endDate; }
set { _endDate = value; RaisePropertyChanged("EndDate"); }
}
private IList<TicketExplorerRowViewModel> _tickets;
public IList<TicketExplorerRowViewModel> Tickets
{
get { return _tickets; }
set
{
_tickets = value;
RaisePropertyChanged("Tickets");
}
}
public TicketExplorerRowViewModel SelectedRow { get; set; }
private decimal _total;
public decimal Total
{
get { return _total; }
set
{
_total = value;
RaisePropertyChanged("Total");
RaisePropertyChanged("TotalStr");
}
}
public string TotalStr { get { return string.Format(Resources.Total_f, Total); } }
public void Refresh()
{
EndDate = EndDate.Date.AddDays(1).AddMinutes(-1);
Expression<Func<Ticket, bool>> qFilter = x => x.Date >= StartDate && x.Date < EndDate;
qFilter = Filters.Aggregate(qFilter, (current, filter) => current.And(filter.GetExpression()));
Tickets = Dao.Query(qFilter).Select(x => new TicketExplorerRowViewModel(x)).ToList();
Total = Tickets.Sum(x => x.Sum);
RaisePropertyChanged("CanChanageDateFilter");
}
void TimerElapsed(object sender, ElapsedEventArgs e)
{
_timer.Stop();
AppServices.MainDispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(DisplaySelectedRow));
}
public void QueueDisplayTicket()
{
_timer.Stop();
_timer.Start();
}
public void DisplaySelectedRow()
{
if (SelectedRow != null)
{
if (AppServices.MainDataContext.SelectedTicket != null)
AppServices.MainDataContext.CloseTicket();
AppServices.MainDataContext.OpenTicket(SelectedRow.Id);
if (AppServices.MainDataContext.SelectedTicket != null)
EventServiceFactory.EventService.PublishEvent(EventTopicNames.RefreshSelectedTicket);
CommandManager.InvalidateRequerySuggested();
}
}
private void OnCloseCommandExecuted(string obj)
{
EventServiceFactory.EventService.PublishEvent(EventTopicNames.DisplayTicketView);
}
private void OnRefreshDates(string obj)
{
Refresh();
}
private void OnExecuteNextWorkPeriod(string obj)
{
StartDate = StartDate.Date.AddDays(1);
EndDate = StartDate;
Refresh();
}
private void OnExecutePreviousWorkPeriod(string obj)
{
StartDate = StartDate.Date.AddDays(-1);
EndDate = StartDate;
Refresh();
}
public void ResetFilters()
{
Filters = new List<TicketExplorerFilter> { new TicketExplorerFilter { FilterType = FilterType.OpenTickets } };
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.TicketModule/TicketExplorerViewModel.cs | C# | gpl3 | 5,359 |
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using Samba.Domain.Models.Tickets;
using Samba.Localization.Properties;
using Samba.Presentation.Common;
namespace Samba.Modules.TicketModule
{
public enum FilterType
{
OpenTickets,
AllTickets,
Customer,
Location
}
public class TicketExplorerFilter : ObservableObject
{
public TicketExplorerFilter()
{
FilterValues = new List<string>();
}
private readonly string[] _filterTypes = { Resources.OnlyOpenTickets, Resources.AllTickets, Resources.Account, Resources.Table };
public int FilterTypeIndex
{
get { return (int)FilterType; }
set
{
FilterType = (FilterType)value;
FilterValue = "";
RaisePropertyChanged("IsTextBoxEnabled");
}
}
public bool IsTextBoxEnabled { get { return FilterType != FilterType.OpenTickets; } }
public string[] FilterTypes { get { return _filterTypes; } }
public FilterType FilterType { get; set; }
private string _filterValue;
public string FilterValue
{
get { return _filterValue; }
set
{
_filterValue = value;
RaisePropertyChanged("FilterValue");
}
}
public List<string> FilterValues { get; set; }
public Expression<Func<Ticket, bool>> GetExpression()
{
Expression<Func<Ticket, bool>> result = null;
if (FilterType == FilterType.OpenTickets)
result = x => !x.IsPaid;
if (FilterType == FilterType.Location)
{
if (FilterValue == "*")
result = x => !string.IsNullOrEmpty(x.LocationName);
else if (!string.IsNullOrEmpty(FilterValue))
result = x => x.LocationName.ToLower() == FilterValue.ToLower();
else result = x => string.IsNullOrEmpty(x.LocationName);
}
if (FilterType == FilterType.Customer)
{
if (FilterValue == "*")
result = x => !string.IsNullOrEmpty(x.CustomerName);
else if (!string.IsNullOrEmpty(FilterValue))
result = x => x.CustomerName.ToLower().Contains(FilterValue.ToLower());
else
result = x => string.IsNullOrEmpty(x.CustomerName);
}
return result;
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.TicketModule/TicketExplorerFilter.cs | C# | gpl3 | 2,681 |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Events;
using Samba.Domain.Models.Menus;
using Samba.Domain.Models.Tickets;
using Samba.Presentation.Common;
using Samba.Presentation.Common.Services;
using Samba.Presentation.ViewModels;
using Samba.Services;
namespace Samba.Modules.TicketModule
{
public class MenuItemSelectorViewModel : ObservableObject
{
private ScreenMenu _currentScreenMenu;
private readonly DelegateCommand<ScreenMenuItemData> _addMenuItemCommand;
public ObservableCollection<ScreenMenuItemButton> MostUsedMenuItems { get; set; }
public ObservableCollection<ScreenCategoryButton> Categories { get; set; }
public ObservableCollection<ScreenMenuItemButton> MenuItems { get; set; }
public ObservableCollection<ScreenSubCategoryButton> SubCategories { get; set; }
public DelegateCommand<ScreenMenuCategory> CategoryCommand { get; set; }
public DelegateCommand<ScreenMenuItem> MenuItemCommand { get; set; }
public DelegateCommand<string> TypeValueCommand { get; set; }
public DelegateCommand<string> FindTableCommand { get; set; }
public DelegateCommand<string> FindMenuItemCommand { get; set; }
public DelegateCommand<string> FindTicketCommand { get; set; }
public ICaptionCommand IncPageNumberCommand { get; set; }
public ICaptionCommand DecPageNumberCommand { get; set; }
public ICaptionCommand SubCategoryCommand { get; set; }
public ScreenMenuCategory MostUsedItemsCategory { get; set; }
private ScreenMenuCategory _selectedCategory;
public ScreenMenuCategory SelectedCategory { get { return _selectedCategory; } set { _selectedCategory = value; RaisePropertyChanged("SelectedCategory"); } }
public string NumeratorValue
{
get { return AppServices.MainDataContext.NumeratorValue; }
set
{
AppServices.MainDataContext.NumeratorValue = value;
FilterMenuItems(AppServices.MainDataContext.NumeratorValue);
RaisePropertyChanged("NumeratorValue");
}
}
public string[] QuickNumeratorValues { get; set; }
public string[] AlphaButtonValues { get; set; }
public bool IsQuickNumeratorVisible { get { return SelectedCategory != null && SelectedCategory.IsQuickNumeratorVisible; } }
public bool IsNumeratorVisible { get { return SelectedCategory != null && SelectedCategory.IsNumeratorVisible; } }
public bool IsPageNumberNavigatorVisible { get { return SelectedCategory != null && SelectedCategory.PageCount > 1; } }
public VerticalAlignment MenuItemsVerticalAlignment { get { return SelectedCategory != null && SelectedCategory.ButtonHeight > 0 ? VerticalAlignment.Top : VerticalAlignment.Stretch; } }
public VerticalAlignment CategoriesVerticalAlignment { get { return Categories != null && Categories.Count > 0 && double.IsNaN(Categories[0].MButtonHeight) ? VerticalAlignment.Stretch : VerticalAlignment.Top; } }
public int CurrentPageNo { get; set; }
public string CurrentTag { get; set; }
public MenuItemSelectorViewModel(DelegateCommand<ScreenMenuItemData> addMenuItemCommand)
{
_addMenuItemCommand = addMenuItemCommand;
CategoryCommand = new DelegateCommand<ScreenMenuCategory>(OnCategoryCommandExecute);
MenuItemCommand = new DelegateCommand<ScreenMenuItem>(OnMenuItemCommandExecute);
TypeValueCommand = new DelegateCommand<string>(OnTypeValueExecute);
FindTableCommand = new DelegateCommand<string>(OnFindTableExecute, CanFindTable);
FindMenuItemCommand = new DelegateCommand<string>(OnFindMenuItemCommand);
FindTicketCommand = new DelegateCommand<string>(OnFindTicketExecute, CanFindTicket);
IncPageNumberCommand = new CaptionCommand<string>(Localization.Properties.Resources.NextPage + " >>", OnIncPageNumber, CanIncPageNumber);
DecPageNumberCommand = new CaptionCommand<string>("<< " + Localization.Properties.Resources.PreviousPage, OnDecPageNumber, CanDecPageNumber);
SubCategoryCommand = new CaptionCommand<ScreenSubCategoryButton>(".", OnSubCategoryCommand);
EventServiceFactory.EventService.GetEvent<GenericEvent<Department>>().Subscribe(OnDepartmentChanged);
EventServiceFactory.EventService.GetEvent<GenericEvent<EventAggregator>>().Subscribe(OnNumeratorReset);
NumeratorValue = "";
SubCategories = new ObservableCollection<ScreenSubCategoryButton>();
}
private bool _filtered;
private void FilterMenuItems(string numeratorValue)
{
if (!string.IsNullOrEmpty(numeratorValue) && Char.IsLower(numeratorValue[0]))
{
_filtered = true;
SubCategories.Clear();
MenuItems.Clear();
var items = Categories.Select(x => x.Category).SelectMany(x => x.ScreenMenuItems).Where(
x => numeratorValue.ToLower().Split(' ').All(y => !string.IsNullOrEmpty(x.Name) && x.Name.ToLower().Contains(y)))
.Select(x => new ScreenMenuItemButton(x, MenuItemCommand, SelectedCategory));
MenuItems.AddRange(items.OrderBy(x => x.FindOrder(numeratorValue)).Take(30));
}
else if (_filtered)
{
_filtered = false;
UpdateMenuButtons(SelectedCategory);
}
}
private void OnNumeratorReset(EventParameters<EventAggregator> obj)
{
if (obj.Topic == EventTopicNames.ResetNumerator)
NumeratorValue = "";
}
private void OnDecPageNumber(string obj)
{
CurrentPageNo--;
UpdateMenuButtons(SelectedCategory);
}
private bool CanDecPageNumber(string arg)
{
return CurrentPageNo > 0;
}
private bool CanIncPageNumber(object arg)
{
return SelectedCategory != null && CurrentPageNo < SelectedCategory.PageCount - 1;
}
private void OnIncPageNumber(object obj)
{
CurrentPageNo++;
UpdateMenuButtons(SelectedCategory);
}
private void OnFindTicketExecute(string obj)
{
if (string.IsNullOrEmpty(NumeratorValue))
{
AppServices.MainDataContext.CurrentWorkPeriod.PublishEvent(EventTopicNames.DisplayTicketExplorer);
}
else
{
AppServices.MainDataContext.OpenTicketFromTicketNumber(NumeratorValue);
if (AppServices.MainDataContext.SelectedTicket != null)
{
if (!AppServices.IsUserPermittedFor(PermissionNames.DisplayOldTickets) && AppServices.MainDataContext.SelectedTicket.Date < AppServices.MainDataContext.CurrentWorkPeriod.StartDate)
AppServices.MainDataContext.CloseTicket();
else
EventServiceFactory.EventService.PublishEvent(EventTopicNames.RefreshSelectedTicket);
}
NumeratorValue = "";
}
}
private static bool CanFindTicket(string arg)
{
return AppServices.MainDataContext.SelectedTicket == null;
}
private static string GetInsertedData(string data, params char[] multiplier)
{
if (!multiplier.Any(x => data.ToLower().Contains(x))) return data;
return data.Substring(data.IndexOf(multiplier.FirstOrDefault(x => data.ToLower().Contains(x))) + 1);
}
private static decimal GetInsertedQuantity(string data, params char[] multiplier)
{
decimal result = 1;
if (multiplier.Any(x => data.ToLower().Contains(x)))
{
decimal.TryParse(
data.Substring(0, data.IndexOf(multiplier.FirstOrDefault(x => data.ToLower().Contains(x)))),
out result);
}
return result;
}
private void OnFindMenuItemCommand(string obj)
{
var insertedData = GetInsertedData(NumeratorValue, 'x', '*');
var quantity = GetInsertedQuantity(NumeratorValue, 'x', '*');
NumeratorValue = "";
if (quantity > 0)
{
var weightBarcodePrefix = AppServices.SettingService.WeightBarcodePrefix;
if (!string.IsNullOrEmpty(weightBarcodePrefix) && insertedData.StartsWith(weightBarcodePrefix))
{
var itemLength = AppServices.SettingService.WeightBarcodeItemLength;
var quantityLength = AppServices.SettingService.WeightBarcodeQuantityLength;
if (itemLength > 0 && quantityLength > 0 && insertedData.Length >= itemLength + quantityLength + weightBarcodePrefix.Length)
{
var bc = insertedData.Substring(weightBarcodePrefix.Length, itemLength);
if (!string.IsNullOrEmpty(AppServices.SettingService.WeightBarcodeItemFormat))
{
int integerValue;
int.TryParse(bc, out integerValue);
if (integerValue > 0)
bc = integerValue.ToString(AppServices.SettingService.WeightBarcodeItemFormat);
}
var qty = insertedData.Substring(weightBarcodePrefix.Length + itemLength, quantityLength);
if (bc.Length > 0 && qty.Length > 0)
{
insertedData = bc;
decimal.TryParse(qty, out quantity);
}
}
}
try
{
var mi = AppServices.DataAccessService.GetMenuItem(insertedData);
if (mi != null)
{
var si = new ScreenMenuItem { MenuItemId = mi.Id, Name = mi.Name };
var data = new ScreenMenuItemData { ScreenMenuItem = si, Quantity = quantity };
_addMenuItemCommand.Execute(data);
}
}
catch (Exception) { }
}
}
private static bool CanFindTable(string arg)
{
return AppServices.MainDataContext.SelectedTicket == null;
}
private void OnFindTableExecute(string obj)
{
if (AppServices.MainDataContext.SelectedTicket == null)
{
AppServices.MainDataContext.OpenTicketFromTableName(NumeratorValue);
if (AppServices.MainDataContext.SelectedTicket != null)
EventServiceFactory.EventService.PublishEvent(EventTopicNames.RefreshSelectedTicket);
}
NumeratorValue = "";
}
private void OnMenuItemCommandExecute(ScreenMenuItem screenMenuItem)
{
decimal selectedMultiplier = 1;
if (!string.IsNullOrEmpty(NumeratorValue) && !_filtered)
decimal.TryParse(NumeratorValue, out selectedMultiplier);
if (IsQuickNumeratorVisible)
NumeratorValue = QuickNumeratorValues[0];
NumeratorValue = "";
if (selectedMultiplier > 0)
{
var data = new ScreenMenuItemData { ScreenMenuItem = screenMenuItem, Quantity = selectedMultiplier };
if (data.Quantity == 1 && screenMenuItem.Quantity > 1)
data.Quantity = screenMenuItem.Quantity;
_addMenuItemCommand.Execute(data);
}
}
private void OnDepartmentChanged(EventParameters<Department> department)
{
if (department.Topic == EventTopicNames.SelectedDepartmentChanged)
{
_currentScreenMenu = department.Value != null
? AppServices.DataAccessService.GetScreenMenu(department.Value.ScreenMenuId)
: null;
Categories = CreateCategoryButtons(_currentScreenMenu);
MostUsedItemsCategory = null;
MostUsedMenuItems = CreateMostUsedMenuItems(_currentScreenMenu);
if (Categories != null && Categories.Count == 1)
{
OnCategoryCommandExecute(Categories[0].Category);
Categories.Clear();
}
RaisePropertyChanged("Categories");
RaisePropertyChanged("CategoriesVerticalAlignment");
RaisePropertyChanged("MostUsedMenuItems");
RaisePropertyChanged("MostUsedItemsCategory");
}
}
private ObservableCollection<ScreenMenuItemButton> CreateMostUsedMenuItems(ScreenMenu screenMenu)
{
if (screenMenu != null)
{
MostUsedItemsCategory = screenMenu.Categories.FirstOrDefault(x => x.MostUsedItemsCategory);
if (MostUsedItemsCategory != null)
{
return new ObservableCollection<ScreenMenuItemButton>(
MostUsedItemsCategory.ScreenMenuItems.OrderBy(x => x.Order).Select(x => new ScreenMenuItemButton(x, MenuItemCommand, MostUsedItemsCategory)));
}
}
return null;
}
private void UpdateMenuButtons(ScreenMenuCategory category)
{
MenuItems = CreateMenuButtons(category, CurrentPageNo, CurrentTag ?? "");
SubCategories.Clear();
SubCategories.AddRange(
AppServices.DataAccessService.GetSubCategories(category, CurrentTag)
.Select(x => new ScreenSubCategoryButton(x, SubCategoryCommand, category.MButtonColor, category.SubButtonHeight)));
if (!string.IsNullOrEmpty(CurrentTag))
{
var backButton = new ScreenSubCategoryButton(CurrentTag.Replace(CurrentTag.Split(',').Last(), "").Trim(new[] { ',', ' ' }), SubCategoryCommand, "Gainsboro", category.SubButtonHeight, true);
SubCategories.Add(backButton);
}
if (Categories != null && MenuItems.Count == 0)
{
if (category.NumeratorType == 2 && SubCategories.Count == 0)
InteractionService.ShowKeyboard();
MenuItems.Clear();
if (category.MaxItems > 0)
{
IEnumerable<ScreenMenuItem> sitems = category.ScreenMenuItems.OrderBy(x => x.Order);
if (SubCategories.Count == 0)
{
sitems = Categories.Select(x => x.Category).SelectMany(x => x.ScreenMenuItems);
}
var items = sitems.Select(x => new ScreenMenuItemButton(x, MenuItemCommand, SelectedCategory));
if (category.SortType == 1) items = items.OrderByDescending(x => x.UsageCount);
MenuItems.AddRange(items.Take(category.MaxItems));
}
}
RaisePropertyChanged("MenuItems");
RaisePropertyChanged("IsPageNumberNavigatorVisible");
RaisePropertyChanged("MenuItemsVerticalAlignment");
}
private void OnSubCategoryCommand(ScreenSubCategoryButton obj)
{
CurrentTag = obj.Name.Trim();
UpdateMenuButtons(SelectedCategory);
}
private void OnCategoryCommandExecute(ScreenMenuCategory category)
{
CurrentPageNo = 0;
CurrentTag = "";
UpdateMenuButtons(category);
if (IsQuickNumeratorVisible)
{
QuickNumeratorValues = string.IsNullOrEmpty(category.NumeratorValues) ? new[] { "1", "2", "3", "4", "5" } : category.NumeratorValues.Split(',');
NumeratorValue = QuickNumeratorValues[0];
}
NumeratorValue = "";
AlphaButtonValues = string.IsNullOrEmpty(category.AlphaButtonValues) ? new string[0] : category.AlphaButtonValues.Split(',');
RaisePropertyChanged("IsQuickNumeratorVisible");
RaisePropertyChanged("IsNumeratorVisible");
RaisePropertyChanged("QuickNumeratorValues");
RaisePropertyChanged("AlphaButtonValues");
RaisePropertyChanged("MenuItemsVerticalAlignment");
}
private ObservableCollection<ScreenMenuItemButton> CreateMenuButtons(ScreenMenuCategory category, int pageNo, string tag)
{
SelectedCategory = category;
var screenMenuItems = AppServices.DataAccessService.GetMenuItems(category, pageNo, tag);
var result = new ObservableCollection<ScreenMenuItemButton>();
var items = screenMenuItems.Select(x => new ScreenMenuItemButton(x, MenuItemCommand, category));
if (category.SortType == 1) items = items.OrderByDescending(x => x.UsageCount);
result.AddRange(items);
return result;
}
private ObservableCollection<ScreenCategoryButton> CreateCategoryButtons(ScreenMenu screenMenu)
{
if (screenMenu != null)
{
if (MenuItems != null) MenuItems.Clear();
_currentScreenMenu = screenMenu;
var result = new ObservableCollection<ScreenCategoryButton>();
foreach (var category in screenMenu.Categories.OrderBy(x => x.Order).Where(x => !x.MostUsedItemsCategory))
{
var sButton = new ScreenCategoryButton(category, CategoryCommand);
result.Add(sButton);
}
if (result.Count > 0)
{
var c = result.First();
if (_selectedCategory != null)
c = result.SingleOrDefault(x => x.Category.Name.ToLower() == _selectedCategory.Name.ToLower());
if (c == null && result.Count > 0) c = result.ElementAt(0);
if (c != null) OnCategoryCommandExecute(c.Category);
}
return result;
}
if (MenuItems != null) MenuItems.Clear();
if (Categories != null) Categories.Clear();
_currentScreenMenu = null;
return Categories;
}
private void OnTypeValueExecute(string obj)
{
if (obj == "\r")
{
if (_filtered && MenuItems.Count == 1)
MenuItemCommand.Execute(MenuItems[0].ScreenMenuItem);
FindMenuItemCommand.Execute("");
}
else if (obj == "\b" && !string.IsNullOrEmpty(NumeratorValue))
NumeratorValue = NumeratorValue.Substring(0, NumeratorValue.Length - 1);
else if (!string.IsNullOrEmpty(obj) && !Char.IsControl(obj[0]))
NumeratorValue = obj == "C" ? "" : Helpers.AddTypedValue(NumeratorValue, obj, "#0.");
}
public bool HandleTextInput(string text)
{
if (SelectedCategory != null)
{
OnTypeValueExecute(text);
return true;
}
return false;
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.TicketModule/MenuItemSelectorViewModel.cs | C# | gpl3 | 20,075 |
using System.Windows.Controls;
using System.ComponentModel.Composition;
using Microsoft.Practices.Prism.Events;
using Samba.Presentation.Common;
namespace Samba.Modules.TicketModule
{
/// <summary>
/// Interaction logic for TicketEditorView.xaml
/// </summary>
///
[Export]
public partial class TicketEditorView : UserControl
{
[ImportingConstructor]
public TicketEditorView(TicketEditorViewModel viewModel)
{
InitializeComponent();
DataContext = viewModel;
EventServiceFactory.EventService.GetEvent<GenericEvent<TicketEditorViewModel>>().Subscribe(
x =>
{
if (x.Topic == EventTopicNames.FocusTicketScreen)
MainTabControl.BackgroundFocus();
});
}
private void UserControl_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
{
e.Handled = ((TicketEditorViewModel)DataContext).HandleTextInput(e.Text);
}
private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
MainTabControl.BackgroundFocus();
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.TicketModule/TicketEditorView.xaml.cs | C# | gpl3 | 1,263 |
using System.Windows.Controls;
using Microsoft.Practices.Prism.Events;
using Samba.Presentation.Common;
using Samba.Presentation.ViewModels;
namespace Samba.Modules.TicketModule
{
/// <summary>
/// Interaction logic for TicketListView.xaml
/// </summary>
public partial class TicketListView : UserControl
{
public TicketListView()
{
InitializeComponent();
EventServiceFactory.EventService.GetEvent<GenericEvent<TicketItemViewModel>>().Subscribe(
x =>
{
if (x.Topic == EventTopicNames.TicketItemAdded)
{
Scroller.ScrollToEnd();
}
});
EventServiceFactory.EventService.GetEvent<GenericEvent<TicketViewModel>>().Subscribe(
x =>
{
if (x.Topic == EventTopicNames.SelectedTicketChanged)
Scroller.ScrollToEnd();
});
EventServiceFactory.EventService.GetEvent<GenericEvent<EventAggregator>>().Subscribe(
x =>
{
if (x.Topic == EventTopicNames.DisplayTicketView || x.Topic == EventTopicNames.RefreshSelectedTicket)
Scroller.ScrollToEnd();
});
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.TicketModule/TicketListView.xaml.cs | C# | gpl3 | 1,395 |
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
namespace Samba.Modules.TicketModule
{
/// <summary>
/// Interaction logic for MenuItemSelectorView.xaml
/// </summary>
public partial class MenuItemSelectorView : UserControl
{
private readonly GridLength _thin = GridLength.Auto;
private readonly GridLength _auto15 = new GridLength(15, GridUnitType.Star);
private readonly GridLength _auto25 = new GridLength(25, GridUnitType.Star);
private readonly GridLength _auto45 = new GridLength(45, GridUnitType.Star);
public MenuItemSelectorView()
{
InitializeComponent();
}
private void ItemsControl_TargetUpdated(object sender, DataTransferEventArgs e)
{
MainGrid.ColumnDefinitions[0].Width = ((ItemsControl)sender).Items.Count == 0 ? _thin : _auto25;
}
private void ItemsControl_TargetUpdated_1(object sender, DataTransferEventArgs e)
{
var sw = DataContext as MenuItemSelectorViewModel;
if (sw == null) return;
NumeratorRow.Height = sw.IsNumeratorVisible ? _auto45 : _thin;
//AlphaButtonsColumn.Width = sw.AlphaButtonValues != null && sw.AlphaButtonValues.Length > 0 ? _auto15 : _thin;
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.TicketModule/MenuItemSelectorView.xaml.cs | C# | gpl3 | 1,391 |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Windows;
using Microsoft.Practices.Prism.Commands;
using Samba.Domain;
using Samba.Domain.Models.Settings;
using Samba.Domain.Models.Tickets;
using Samba.Infrastructure.Settings;
using Samba.Localization.Properties;
using Samba.Presentation.Common;
using Samba.Presentation.Common.Services;
using Samba.Presentation.ViewModels;
using Samba.Services;
namespace Samba.Modules.TicketModule
{
public class PaymentEditorViewModel : ObservableObject
{
private bool _resetAmount;
private readonly ICaptionCommand _manualPrintCommand;
public PaymentEditorViewModel()
{
_manualPrintCommand = new CaptionCommand<PrintJob>(Resources.Print, OnManualPrint, CanManualPrint);
SubmitCashPaymentCommand = new CaptionCommand<string>(Resources.Cash, OnSubmitCashPayment, CanSubmitCashPayment);
SubmitCreditCardPaymentCommand = new CaptionCommand<string>(Resources.CreditCard_r, OnSubmitCreditCardPayment,
CanSubmitCashPayment);
SubmitTicketPaymentCommand = new CaptionCommand<string>(Resources.Voucher_r, OnSubmitTicketPayment, CanSubmitCashPayment);
SubmitAccountPaymentCommand = new CaptionCommand<string>(Resources.AccountBalance_r, OnSubmitAccountPayment, CanSubmitAccountPayment);
ClosePaymentScreenCommand = new CaptionCommand<string>(Resources.Close, OnClosePaymentScreen, CanClosePaymentScreen);
TenderAllCommand = new CaptionCommand<string>(Resources.All, OnTenderAllCommand);
TypeValueCommand = new DelegateCommand<string>(OnTypeValueExecuted);
SetValueCommand = new DelegateCommand<string>(OnSetValue);
DivideValueCommand = new DelegateCommand<string>(OnDivideValue);
SelectMergedItemCommand = new DelegateCommand<MergedItem>(OnMergedItemSelected);
SetDiscountAmountCommand = new CaptionCommand<string>(Resources.Round, OnSetDiscountAmountCommand, CanSetDiscount);
AutoSetDiscountAmountCommand = new CaptionCommand<string>(Resources.Flat, OnAutoSetDiscount, CanAutoSetDiscount);
SetDiscountRateCommand = new CaptionCommand<string>(Resources.DiscountPercentSign, OnSetDiscountRateCommand, CanSetDiscountRate);
MergedItems = new ObservableCollection<MergedItem>();
ReturningAmountVisibility = Visibility.Collapsed;
LastTenderedAmount = "1";
EventServiceFactory.EventService.GetEvent<GenericEvent<CreditCardProcessingResult>>().Subscribe(OnProcessCreditCard);
}
public CaptionCommand<string> SubmitCashPaymentCommand { get; set; }
public CaptionCommand<string> SubmitCreditCardPaymentCommand { get; set; }
public CaptionCommand<string> SubmitTicketPaymentCommand { get; set; }
public CaptionCommand<string> SubmitAccountPaymentCommand { get; set; }
public CaptionCommand<string> ClosePaymentScreenCommand { get; set; }
public CaptionCommand<string> TenderAllCommand { get; set; }
public DelegateCommand<string> TypeValueCommand { get; set; }
public DelegateCommand<string> SetValueCommand { get; set; }
public DelegateCommand<string> DivideValueCommand { get; set; }
public DelegateCommand<MergedItem> SelectMergedItemCommand { get; set; }
public CaptionCommand<string> SetDiscountRateCommand { get; set; }
public CaptionCommand<string> SetDiscountAmountCommand { get; set; }
public CaptionCommand<string> AutoSetDiscountAmountCommand { get; set; }
public ObservableCollection<MergedItem> MergedItems { get; set; }
public string SelectedTicketTitle { get { return SelectedTicket != null ? SelectedTicket.Title : ""; } }
private string _paymentAmount;
public string PaymentAmount
{
get { return _paymentAmount; }
set
{
_paymentAmount = value;
RaisePropertyChanged("PaymentAmount");
}
}
private string _tenderedAmount;
public string TenderedAmount
{
get { return _tenderedAmount; }
set
{
_tenderedAmount = value;
RaisePropertyChanged("TenderedAmount");
}
}
private string _lastTenderedAmount;
public string LastTenderedAmount
{
get { return _lastTenderedAmount; }
set { _lastTenderedAmount = value; RaisePropertyChanged("LastTenderedAmount"); }
}
public string ReturningAmount { get; set; }
private Visibility _returningAmountVisibility;
public Visibility ReturningAmountVisibility { get { return _returningAmountVisibility; } set { _returningAmountVisibility = value; RaisePropertyChanged("ReturningAmountVisibility"); } }
public Visibility PaymentsVisibility
{
get
{
return AppServices.MainDataContext.SelectedTicket != null && AppServices.MainDataContext.SelectedTicket.Payments.Count() > 0
? Visibility.Visible
: Visibility.Collapsed;
}
}
public IEnumerable<CommandButtonViewModel> CommandButtons { get; set; }
private IEnumerable<CommandButtonViewModel> CreateCommandButtons()
{
var result = new List<CommandButtonViewModel>();
result.Add(new CommandButtonViewModel
{
Caption = SetDiscountRateCommand.Caption,
Command = SetDiscountRateCommand
});
result.Add(new CommandButtonViewModel
{
Caption = SetDiscountAmountCommand.Caption,
Command = SetDiscountAmountCommand
});
result.Add(new CommandButtonViewModel
{
Caption = AutoSetDiscountAmountCommand.Caption,
Command = AutoSetDiscountAmountCommand
});
if (SelectedTicket != null)
{
result.AddRange(SelectedTicket.PrintJobButtons.Where(x => x.Model.UseFromPaymentScreen)
.Select(x => new CommandButtonViewModel
{
Caption = x.Caption,
Command = _manualPrintCommand,
Parameter = x.Model
}));
}
return result;
}
private bool CanManualPrint(PrintJob arg)
{
return arg != null && SelectedTicket != null && (!SelectedTicket.IsLocked || SelectedTicket.Model.GetPrintCount(arg.Id) == 0);
}
private void OnManualPrint(PrintJob obj)
{
AppServices.PrintService.ManualPrintTicket(SelectedTicket.Model, obj);
SelectedTicket.PrintJobButtons.Where(x => x.Model.UseFromPaymentScreen).ToList().ForEach(
x => CommandButtons.First(u => u.Parameter == x.Model).Caption = x.Caption);
}
private static bool CanAutoSetDiscount(string arg)
{
return AppServices.MainDataContext.SelectedTicket != null
&& AppServices.MainDataContext.SelectedTicket.GetRemainingAmount() > 0;
}
private bool CanSetDiscount(string arg)
{
if (GetTenderedValue() == 0) return true;
return AppServices.MainDataContext.SelectedTicket != null
&& GetTenderedValue() <= AppServices.MainDataContext.SelectedTicket.GetRemainingAmount()
&& (AppServices.MainDataContext.SelectedTicket.TotalAmount > 0)
&& AppServices.IsUserPermittedFor(PermissionNames.MakeDiscount)
&& AppServices.IsUserPermittedFor(PermissionNames.RoundPayment);
}
private bool CanSetDiscountRate(string arg)
{
if (GetTenderedValue() == 0) return true;
return AppServices.MainDataContext.SelectedTicket != null
&& AppServices.MainDataContext.SelectedTicket.TotalAmount > 0
&& AppServices.MainDataContext.SelectedTicket.GetRemainingAmount() > 0
&& GetTenderedValue() <= 100 && AppServices.IsUserPermittedFor(PermissionNames.MakeDiscount);
}
private bool CanClosePaymentScreen(string arg)
{
return string.IsNullOrEmpty(TenderedAmount) || (SelectedTicket != null && SelectedTicket.Model.GetRemainingAmount() == 0);
}
private void OnTenderAllCommand(string obj)
{
TenderedAmount = PaymentAmount;
_resetAmount = true;
}
private void OnSubmitAccountPayment(string obj)
{
SubmitPayment(PaymentType.Account);
}
private void OnSubmitTicketPayment(string obj)
{
SubmitPayment(PaymentType.Ticket);
}
private void OnSubmitCreditCardPayment(string obj)
{
SubmitPayment(PaymentType.CreditCard);
}
private void OnSubmitCashPayment(string obj)
{
SubmitPayment(PaymentType.Cash);
}
private void OnDivideValue(string obj)
{
decimal tenderedValue = GetTenderedValue();
CancelMergedItems();
_resetAmount = true;
string dc = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
obj = obj.Replace(",", dc);
obj = obj.Replace(".", dc);
decimal value = Convert.ToDecimal(obj);
var remainingTicketAmount = SelectedTicket.Model.GetRemainingAmount();
if (value > 0)
{
var amount = remainingTicketAmount / value;
if (amount > remainingTicketAmount) amount = remainingTicketAmount;
TenderedAmount = amount.ToString("#,#0.00");
}
else
{
value = tenderedValue;
if (value > 0)
{
var amount = remainingTicketAmount / value;
if (amount > remainingTicketAmount) amount = remainingTicketAmount;
TenderedAmount = (amount).ToString("#,#0.00");
}
}
}
private void OnSetValue(string obj)
{
_resetAmount = true;
ReturningAmountVisibility = Visibility.Collapsed;
if (string.IsNullOrEmpty(obj))
{
TenderedAmount = "";
PaymentAmount = "";
CancelMergedItems();
return;
}
var value = Convert.ToDecimal(obj);
if (string.IsNullOrEmpty(TenderedAmount))
TenderedAmount = "0";
var tenderedValue = Convert.ToDecimal(TenderedAmount.Replace(
CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator, ""));
tenderedValue += value;
TenderedAmount = tenderedValue.ToString("#,#0.00");
}
private void OnTypeValueExecuted(string obj)
{
if (_resetAmount) TenderedAmount = "";
_resetAmount = false;
ReturningAmountVisibility = Visibility.Collapsed;
TenderedAmount = Helpers.AddTypedValue(TenderedAmount, obj, "#,#0.");
}
private void OnClosePaymentScreen(string obj)
{
ClosePaymentScreen();
}
private void ClosePaymentScreen()
{
var paidItems = MergedItems.SelectMany(x => x.PaidItems);
SelectedTicket.UpdatePaidItems(paidItems);
AppServices.MainDataContext.SelectedTicket.PublishEvent(EventTopicNames.PaymentSubmitted);
TenderedAmount = "";
ReturningAmount = "";
ReturningAmountVisibility = Visibility.Collapsed;
SelectedTicket = null;
}
private bool CanSubmitAccountPayment(string arg)
{
return AppServices.MainDataContext.SelectedTicket != null
&& AppServices.MainDataContext.SelectedTicket.CustomerId > 0
&& GetTenderedValue() == GetPaymentValue()
&& AppServices.MainDataContext.SelectedTicket.GetRemainingAmount() > 0;
}
private bool CanSubmitCashPayment(string arg)
{
return AppServices.MainDataContext.SelectedTicket != null
&& GetTenderedValue() > 0
&& AppServices.MainDataContext.SelectedTicket.GetRemainingAmount() > 0
&& (AppServices.CurrentTerminal.DepartmentId == 0 ||
!AppServices.MainDataContext
.SelectedTicket
.Payments.Any(x => x.DepartmentId != AppServices.MainDataContext.SelectedDepartment.Id));
}
private decimal GetTenderedValue()
{
decimal result;
decimal.TryParse(TenderedAmount, out result);
return result;
}
private decimal GetPaymentValue()
{
decimal result;
decimal.TryParse(PaymentAmount, out result);
return result;
}
private void SubmitPayment(PaymentType paymentType)
{
if (paymentType == PaymentType.CreditCard && CreditCardProcessingService.CanProcessCreditCards)
{
if (SelectedTicket.Id == 0)
{
var result = AppServices.MainDataContext.CloseTicket();
AppServices.MainDataContext.OpenTicket(result.TicketId);
}
var ccpd = new CreditCardProcessingData
{
TenderedAmount = GetTenderedValue(),
Ticket = AppServices.MainDataContext.SelectedTicket
};
CreditCardProcessingService.Process(ccpd);
return;
}
ProcessPayment(paymentType);
}
private void ProcessPayment(PaymentType paymentType)
{
var tenderedAmount = GetTenderedValue();
var originalTenderedAmount = tenderedAmount;
var remainingTicketAmount = GetPaymentValue();
var returningAmount = 0m;
if (tenderedAmount == 0) tenderedAmount = remainingTicketAmount;
if (tenderedAmount > remainingTicketAmount)
{
returningAmount = tenderedAmount - remainingTicketAmount;
tenderedAmount = remainingTicketAmount;
}
if (tenderedAmount > 0)
{
if (tenderedAmount > AppServices.MainDataContext.SelectedTicket.GetRemainingAmount())
tenderedAmount = AppServices.MainDataContext.SelectedTicket.GetRemainingAmount();
TicketViewModel.AddPaymentToSelectedTicket(tenderedAmount, paymentType);
PaymentAmount = (GetPaymentValue() - tenderedAmount).ToString("#,#0.00");
LastTenderedAmount = tenderedAmount <= AppServices.MainDataContext.SelectedTicket.GetRemainingAmount()
? tenderedAmount.ToString("#,#0.00")
: AppServices.MainDataContext.SelectedTicket.GetRemainingAmount().ToString("#,#0.00");
}
ReturningAmount = string.Format(Resources.ChangeAmount_f, returningAmount.ToString(LocalSettings.DefaultCurrencyFormat));
ReturningAmountVisibility = returningAmount > 0 ? Visibility.Visible : Visibility.Collapsed;
if (returningAmount > 0)
{
RuleExecutor.NotifyEvent(RuleEventNames.ChangeAmountChanged,
new { Ticket = SelectedTicket.Model, TicketAmount = SelectedTicket.Model.TotalAmount, ChangeAmount = returningAmount, TenderedAmount = originalTenderedAmount });
}
if (returningAmount == 0 && AppServices.MainDataContext.SelectedTicket.GetRemainingAmount() == 0)
{
ClosePaymentScreen();
}
else PersistMergedItems();
}
private TicketViewModel _selectedTicket;
public TicketViewModel SelectedTicket
{
get { return _selectedTicket; }
private set
{
_selectedTicket = value;
RaisePropertyChanged("SelectedTicket");
RaisePropertyChanged("SelectedTicketTitle");
}
}
public decimal TicketRemainingValue { get; set; }
private void OnSetDiscountRateCommand(string obj)
{
var tenderedvalue = GetTenderedValue();
if (tenderedvalue == 0 && SelectedTicket.Model.GetDiscountTotal() == 0)
{
InteractionService.UserIntraction.GiveFeedback(Resources.EmptyDiscountRateFeedback);
}
if (tenderedvalue > 0 && SelectedTicket.Model.GetPlainSum() > 0)
{
//var discounts = SelectedTicket.Model.GetDiscountAndRoundingTotal();
//var discountAmount = SelectedTicket.Model.GetRemainingAmount() + discounts-SelectedTicket.Model.CalculateVat()-SelectedTicket.Model.GetTaxServicesTotal();
//discountAmount = discountAmount * (GetTenderedValue() / 100);
//var discountRate = SelectedTicket.Model.GetPlainSum();
//discountRate = (discountAmount * 100) / discountRate;
//discountRate = decimal.Round(discountRate, LocalSettings.Decimals);
SelectedTicket.Model.AddTicketDiscount(DiscountType.Percent, GetTenderedValue(), AppServices.CurrentLoggedInUser.Id);
}
else SelectedTicket.Model.AddTicketDiscount(DiscountType.Percent, 0, AppServices.CurrentLoggedInUser.Id);
PaymentAmount = "";
RefreshValues();
}
private void OnAutoSetDiscount(string obj)
{
if (GetTenderedValue() == 0) return;
if (!AppServices.IsUserPermittedFor(PermissionNames.FixPayment) && GetTenderedValue() > GetPaymentValue()) return;
if (!AppServices.IsUserPermittedFor(PermissionNames.RoundPayment)) return;
SelectedTicket.Model.AddTicketDiscount(DiscountType.Amount, 0, AppServices.CurrentLoggedInUser.Id);
SelectedTicket.Model.AddTicketDiscount(DiscountType.Auto, 0, AppServices.CurrentLoggedInUser.Id);
SelectedTicket.Model.AddTicketDiscount(DiscountType.Amount, AppServices.MainDataContext.SelectedTicket.GetRemainingAmount() - GetTenderedValue(), AppServices.CurrentLoggedInUser.Id);
PaymentAmount = "";
RefreshValues();
}
private void OnSetDiscountAmountCommand(string obj)
{
if (GetTenderedValue() > GetPaymentValue()) return;
SelectedTicket.Model.AddTicketDiscount(DiscountType.Amount, GetTenderedValue(), AppServices.CurrentLoggedInUser.Id);
PaymentAmount = "";
RefreshValues();
}
public void RefreshValues()
{
SelectedTicket.RecalculateTicket();
if (SelectedTicket.Model.GetRemainingAmount() < 0)
{
SelectedTicket.Model.Discounts.Clear();
SelectedTicket.RecalculateTicket();
InteractionService.UserIntraction.GiveFeedback(Resources.AllDiscountsRemoved);
}
if (GetPaymentValue() <= 0)
PaymentAmount = AppServices.MainDataContext.SelectedTicket != null
? AppServices.MainDataContext.SelectedTicket.GetRemainingAmount().ToString("#,#0.00")
: "";
SelectedTicket.Discounts.Clear();
SelectedTicket.Discounts.AddRange(SelectedTicket.Model.Discounts.Select(x => new DiscountViewModel(x)));
RaisePropertyChanged("SelectedTicket");
RaisePropertyChanged("ReturningAmountVisibility");
RaisePropertyChanged("PaymentsVisibility");
RaisePropertyChanged("ReturningAmount");
TenderedAmount = "";
}
public void PrepareMergedItems()
{
MergedItems.Clear();
PaymentAmount = "";
_selectedTotal = 0;
var serviceAmount = SelectedTicket.Model.GetTaxServicesTotal();
var sum = SelectedTicket.Model.GetSumWithoutTax();
if (sum == 0) return;
foreach (var item in SelectedTicket.Model.TicketItems)
{
if (!item.Voided && !item.Gifted)
{
var ticketItem = item;
var price = ticketItem.GetItemPrice();
price += (price * serviceAmount) / sum;
if (!ticketItem.VatIncluded) price += ticketItem.VatAmount;
var mitem = MergedItems.SingleOrDefault(x => x.MenuItemId == ticketItem.MenuItemId && x.Price == price);
if (mitem == null)
{
mitem = new MergedItem { Description = item.MenuItemName + item.GetPortionDesc(), Price = price, MenuItemId = item.MenuItemId };
MergedItems.Add(mitem);
}
mitem.Quantity += item.Quantity;
}
}
foreach (var paidItem in SelectedTicket.Model.PaidItems)
{
var item = paidItem;
var mi = MergedItems.SingleOrDefault(x => x.MenuItemId == item.MenuItemId && x.Price == item.Price);
if (mi != null)
mi.PaidItems.Add(paidItem);
}
}
private decimal _selectedTotal;
private void OnMergedItemSelected(MergedItem obj)
{
if (obj.RemainingQuantity > 0)
{
decimal quantity = 1;
if (GetTenderedValue() > 0) quantity = GetTenderedValue();
if (quantity > obj.RemainingQuantity) quantity = obj.RemainingQuantity;
_selectedTotal += obj.Price * quantity;
if (_selectedTotal > AppServices.MainDataContext.SelectedTicket.GetRemainingAmount())
_selectedTotal = AppServices.MainDataContext.SelectedTicket.GetRemainingAmount();
PaymentAmount = _selectedTotal.ToString("#,#0.00");
TenderedAmount = "";
_resetAmount = true;
obj.IncQuantity(quantity);
AppServices.MainDataContext.SelectedTicket.UpdatePaidItems(obj.MenuItemId);
}
ReturningAmountVisibility = Visibility.Collapsed;
}
private void PersistMergedItems()
{
_selectedTotal = 0;
foreach (var mergedItem in MergedItems)
{
mergedItem.PersistPaidItems();
}
RefreshValues();
AppServices.MainDataContext.SelectedTicket.CancelPaidItems();
}
private void CancelMergedItems()
{
_selectedTotal = 0;
foreach (var mergedItem in MergedItems)
{
mergedItem.CancelPaidItems();
}
RefreshValues();
ReturningAmountVisibility = Visibility.Collapsed;
AppServices.MainDataContext.SelectedTicket.CancelPaidItems();
}
public void CreateButtons()
{
CommandButtons = CreateCommandButtons();
RaisePropertyChanged("CommandButtons");
}
public void Prepare()
{
if (SelectedTicket == null)
{
SelectedTicket = new TicketViewModel(AppServices.MainDataContext.SelectedTicket, AppServices.MainDataContext.SelectedDepartment.IsFastFood);
TicketRemainingValue = AppServices.MainDataContext.SelectedTicket.GetRemainingAmount();
PrepareMergedItems();
RefreshValues();
LastTenderedAmount = PaymentAmount;
CreateButtons();
OnSetValue("");
if (CreditCardProcessingService.ForcePayment(SelectedTicket.Id))
{
TenderedAmount = TicketRemainingValue.ToString("#,#0.00");
SubmitPayment(PaymentType.CreditCard);
}
}
}
private void OnProcessCreditCard(EventParameters<CreditCardProcessingResult> obj)
{
if (obj.Topic == EventTopicNames.PaymentProcessed && AppServices.ActiveAppScreen == AppScreens.Payment)
{
if (obj.Value.ProcessType == ProcessType.Force)
{
SelectedTicket = null;
Prepare();
Debug.Assert(SelectedTicket != null);
PaymentAmount = SelectedTicket.Model.GetRemainingAmount().ToString("#,#0.00");
TenderedAmount = obj.Value.Amount.ToString("#,#0.00");
ProcessPayment(PaymentType.CreditCard);
}
if (obj.Value.ProcessType == ProcessType.PreAuth)
ClosePaymentScreen();
if (obj.Value.ProcessType == ProcessType.Cancel)
AppServices.MainDataContext.SelectedTicket.PublishEvent(EventTopicNames.MakePayment);
}
}
}
public class MergedItem : ObservableObject
{
public int MenuItemId { get; set; }
private decimal _quantity;
public decimal Quantity { get { return _quantity; } set { _quantity = value; RaisePropertyChanged("Quantity"); } }
public string Description { get; set; }
public string Label { get { return GetPaidItemsQuantity() > 0 ? string.Format("{0} ({1:#.##})", Description, GetPaidItemsQuantity()) : Description; } }
public decimal Price { get; set; }
public decimal Total { get { return (Price * Quantity) - PaidItems.Sum(x => x.Price * x.Quantity); } }
public string TotalLabel { get { return Total > 0 ? Total.ToString("#,#0.00") : ""; } }
public List<PaidItem> PaidItems { get; set; }
public List<PaidItem> NewPaidItems { get; set; }
public FontWeight FontWeight { get; set; }
public MergedItem()
{
PaidItems = new List<PaidItem>();
NewPaidItems = new List<PaidItem>();
FontWeight = FontWeights.Normal;
}
private decimal GetPaidItemsQuantity()
{
return PaidItems.Sum(x => x.Quantity) + NewPaidItems.Sum(x => x.Quantity);
}
public decimal RemainingQuantity { get { return Quantity - GetPaidItemsQuantity(); } }
public void IncQuantity(decimal quantity)
{
var pitem = new PaidItem { MenuItemId = MenuItemId, Price = Price };
NewPaidItems.Add(pitem);
pitem.Quantity += quantity;
FontWeight = FontWeights.Bold;
Refresh();
}
public void PersistPaidItems()
{
foreach (var newPaidItem in NewPaidItems)
{
var item = newPaidItem;
var pitem = PaidItems.SingleOrDefault(
x => x.MenuItemId == item.MenuItemId && x.Price == item.Price);
if (pitem != null)
{
pitem.Quantity += newPaidItem.Quantity;
}
else PaidItems.Add(newPaidItem);
}
NewPaidItems.Clear();
FontWeight = FontWeights.Normal;
Refresh();
}
public void CancelPaidItems()
{
NewPaidItems.Clear();
FontWeight = FontWeights.Normal;
Refresh();
}
public void Refresh()
{
RaisePropertyChanged("Label");
RaisePropertyChanged("TotalLabel");
RaisePropertyChanged("FontWeight");
}
}
} | zzgaminginc-pointofssale | Samba.Modules.TicketModule/PaymentEditorViewModel.cs | C# | gpl3 | 28,997 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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 Samba.Modules.TicketModule
{
/// <summary>
/// Interaction logic for TicketExplorerView.xaml
/// </summary>
public partial class TicketExplorerView : UserControl
{
private bool _scrolled;
public TicketExplorerView()
{
InitializeComponent();
}
private void DataGrid_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (!_scrolled)
(DataContext as TicketExplorerViewModel).QueueDisplayTicket();
}
private void DataGrid_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
_scrolled = false;
}
private void DataGrid_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
_scrolled = true;
}
private void DataGrid_PreviewKeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Up || e.Key == Key.Down)
(DataContext as TicketExplorerViewModel).QueueDisplayTicket();
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.TicketModule/TicketExplorerView.xaml.cs | C# | gpl3 | 1,450 |
using System.Windows.Controls;
namespace Samba.Modules.TicketModule
{
/// <summary>
/// Interaction logic for PaymentView.xaml
/// </summary>
public partial class PaymentEditorView : UserControl
{
public PaymentEditorView()
{
InitializeComponent();
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.TicketModule/PaymentEditorView.xaml.cs | C# | gpl3 | 334 |
using System.Windows.Controls;
using System.Windows.Input;
using Samba.Presentation.Common;
using Samba.Services;
namespace Samba.Modules.TicketModule
{
/// <summary>
/// Interaction logic for SelectedTicketItemsView.xaml
/// </summary>
public partial class SelectedTicketItemsView : UserControl
{
public SelectedTicketItemsView()
{
InitializeComponent();
}
private void GroupBox_IsVisibleChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e)
{
if (((Control)sender).IsVisible)
ExtraPropertyName.BackgroundFocus();
}
private void GroupBox_IsVisibleChanged_1(object sender, System.Windows.DependencyPropertyChangedEventArgs e)
{
if (((Control)sender).IsVisible)
TicketNote.BackgroundFocus();
}
private void GroupBox_IsVisibleChanged_2(object sender, System.Windows.DependencyPropertyChangedEventArgs e)
{
if (((Control)sender).IsVisible)
FreeTag.BackgroundFocus();
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.TicketModule/SelectedTicketItemsView.xaml.cs | C# | gpl3 | 1,151 |
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("Samba.Modules.TicketModule")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Samba.Modules.TicketModule")]
[assembly: AssemblyCopyright("Copyright © 2010")]
[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("3b4e20ea-0617-4862-b43b-23312f9d2a21")]
// 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")]
[assembly: InternalsVisibleTo("Samba.Modules.TicketModule.Tests")]
[assembly: InternalsVisibleTo("Samba.Modules.TicketModule.Explorables")]
| zzgaminginc-pointofssale | Samba.Modules.TicketModule/Properties/AssemblyInfo.cs | C# | gpl3 | 1,606 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Samba.Domain.Models.Tickets;
namespace Samba.Modules.TicketModule
{
public class TicketExplorerRowViewModel
{
public TicketExplorerRowViewModel(Ticket model)
{
Model = model;
}
public Ticket Model { get; set; }
public int Id { get { return Model.Id; } }
public string TicketNumber { get { return Model.TicketNumber; } }
public string Location { get { return Model.LocationName; } }
public string Date { get { return Model.Date.ToShortDateString(); } }
public string Customer { get { return Model.CustomerName; } }
public string CreationTime { get { return Model.Date.ToShortTimeString(); } }
public string LastPaymentTime { get { return Model.LastPaymentDate.ToShortTimeString(); } }
public decimal Sum { get { return Model.TotalAmount; } }
public bool IsPaid { get { return Model.IsPaid; } }
public string TimeInfo { get { return CreationTime != LastPaymentTime || IsPaid ? CreationTime + " - " + LastPaymentTime : CreationTime; } }
}
}
| zzgaminginc-pointofssale | Samba.Modules.TicketModule/TicketExplorerRowViewModel.cs | C# | gpl3 | 1,199 |
using Samba.Domain.Models.Menus;
namespace Samba.Modules.TicketModule
{
public class ScreenMenuItemData
{
public ScreenMenuItem ScreenMenuItem { get; set; }
public decimal Quantity { get; set; }
}
}
| zzgaminginc-pointofssale | Samba.Modules.TicketModule/ScreenMenuItemData.cs | C# | gpl3 | 241 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Samba.Modules.TicketModule
{
public class SearchData
{
public string TicketNumber { get; set; }
}
}
| zzgaminginc-pointofssale | Samba.Modules.TicketModule/SearchData.cs | C# | gpl3 | 232 |
using System;
using System.ComponentModel.Composition;
using System.Linq;
using System.Windows.Threading;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.Prism.MefExtensions.Modularity;
using Microsoft.Practices.Prism.Regions;
using Samba.Domain.Models.Customers;
using Samba.Domain.Models.Menus;
using Samba.Domain.Models.Settings;
using Samba.Domain.Models.Tickets;
using Samba.Localization.Properties;
using Samba.Persistance.Data;
using Samba.Presentation.Common;
using Samba.Presentation.Common.Services;
using Samba.Services;
namespace Samba.Modules.TicketModule
{
[ModuleExport(typeof(TicketModule))]
public class TicketModule : ModuleBase
{
readonly IRegionManager _regionManager;
private readonly TicketEditorView _ticketEditorView;
private readonly ICategoryCommand _navigateTicketCommand;
[ImportingConstructor]
public TicketModule(IRegionManager regionManager, TicketEditorView ticketEditorView)
{
_navigateTicketCommand = new CategoryCommand<string>("POS", Resources.Common, "Images/Network.png", OnNavigateTicketCommand, CanNavigateTicket);
_regionManager = regionManager;
_ticketEditorView = ticketEditorView;
PermissionRegistry.RegisterPermission(PermissionNames.AddItemsToLockedTickets, PermissionCategories.Ticket, Resources.CanReleaseTicketLock);
PermissionRegistry.RegisterPermission(PermissionNames.RemoveTicketTag, PermissionCategories.Ticket, Resources.CanRemoveTicketTag);
PermissionRegistry.RegisterPermission(PermissionNames.GiftItems, PermissionCategories.Ticket, Resources.CanGiftItems);
PermissionRegistry.RegisterPermission(PermissionNames.VoidItems, PermissionCategories.Ticket, Resources.CanVoidItems);
PermissionRegistry.RegisterPermission(PermissionNames.MoveTicketItems, PermissionCategories.Ticket, Resources.CanMoveTicketLines);
PermissionRegistry.RegisterPermission(PermissionNames.MergeTickets, PermissionCategories.Ticket, Resources.CanMergeTickets);
PermissionRegistry.RegisterPermission(PermissionNames.DisplayOldTickets, PermissionCategories.Ticket, Resources.CanDisplayOldTickets);
PermissionRegistry.RegisterPermission(PermissionNames.MoveUnlockedTicketItems, PermissionCategories.Ticket, Resources.CanMoveUnlockedTicketLines);
PermissionRegistry.RegisterPermission(PermissionNames.ChangeExtraProperty, PermissionCategories.Ticket, Resources.CanUpdateExtraModifiers);
PermissionRegistry.RegisterPermission(PermissionNames.MakePayment, PermissionCategories.Payment, Resources.CanGetPayment);
PermissionRegistry.RegisterPermission(PermissionNames.MakeFastPayment, PermissionCategories.Payment, Resources.CanGetFastPayment);
PermissionRegistry.RegisterPermission(PermissionNames.MakeDiscount, PermissionCategories.Payment, Resources.CanMakeDiscount);
PermissionRegistry.RegisterPermission(PermissionNames.RoundPayment, PermissionCategories.Payment, Resources.CanRoundTicketTotal);
PermissionRegistry.RegisterPermission(PermissionNames.FixPayment, PermissionCategories.Payment, Resources.CanFlattenTicketTotal);
EventServiceFactory.EventService.GetEvent<GenericEvent<Customer>>().Subscribe(
x =>
{
if (x.Topic == EventTopicNames.CustomerSelectedForTicket || x.Topic == EventTopicNames.PaymentRequestedForTicket)
ActivateTicketEditorView();
}
);
EventServiceFactory.EventService.GetEvent<GenericEvent<EventAggregator>>().Subscribe(
x =>
{
if (x.Topic == EventTopicNames.ActivateTicketView || x.Topic == EventTopicNames.DisplayTicketView)
ActivateTicketEditorView();
});
EventServiceFactory.EventService.GetEvent<GenericEvent<WorkPeriod>>().Subscribe(
x =>
{
if (x.Topic == EventTopicNames.WorkPeriodStatusChanged)
{
if (x.Value.StartDate < x.Value.EndDate)
{
using (var v = WorkspaceFactory.Create())
{
var items = v.All<ScreenMenuItem>().ToList();
using (var vr = WorkspaceFactory.CreateReadOnly())
{
AppServices.ResetCache();
var endDate = AppServices.MainDataContext.LastTwoWorkPeriods.Last().EndDate;
var startDate = endDate.AddDays(-7);
vr.Queryable<TicketItem>()
.Where(y => y.CreatedDateTime >= startDate && y.CreatedDateTime < endDate)
.GroupBy(y => y.MenuItemId)
.ToList().ForEach(
y => items.Where(z => z.MenuItemId == y.Key).ToList().ForEach(z => z.UsageCount = y.Count()));
}
v.CommitChanges();
}
}
}
});
}
private static bool CanNavigateTicket(string arg)
{
return AppServices.MainDataContext.IsCurrentWorkPeriodOpen;
}
private static void OnNavigateTicketCommand(string obj)
{
EventServiceFactory.EventService.PublishEvent(EventTopicNames.ActivateTicketView);
}
private void ActivateTicketEditorView()
{
InteractionService.ClearMouseClickQueue();
_regionManager.Regions[RegionNames.MainRegion].Activate(_ticketEditorView);
}
protected override void OnInitialization()
{
_regionManager.RegisterViewWithRegion(RegionNames.MainRegion, typeof(TicketEditorView));
_regionManager.RegisterViewWithRegion(RegionNames.UserRegion, typeof(DepartmentButtonView));
}
protected override void OnPostInitialization()
{
CommonEventPublisher.PublishNavigationCommandEvent(_navigateTicketCommand);
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.TicketModule/TicketModule.cs | C# | gpl3 | 6,442 |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Windows;
using System.Windows.Media;
using Microsoft.Practices.EnterpriseLibrary.Common.Utility;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Events;
using Samba.Domain;
using Samba.Domain.Models.Customers;
using Samba.Domain.Models.Settings;
using Samba.Domain.Models.Tickets;
using Samba.Infrastructure;
using Samba.Localization.Properties;
using Samba.Persistance.Data;
using Samba.Presentation.Common;
using Samba.Presentation.Common.Interaction;
using Samba.Presentation.Common.Services;
using Samba.Presentation.ViewModels;
using Samba.Services;
namespace Samba.Modules.TicketModule
{
public class TicketListViewModel : ObservableObject
{
private const int OpenTicketListView = 0;
private const int SingleTicketView = 1;
private readonly Timer _timer;
public DelegateCommand<ScreenMenuItemData> AddMenuItemCommand { get; set; }
public CaptionCommand<string> CloseTicketCommand { get; set; }
public DelegateCommand<int?> OpenTicketCommand { get; set; }
public CaptionCommand<string> MakePaymentCommand { get; set; }
public CaptionCommand<string> MakeCashPaymentCommand { get; set; }
public CaptionCommand<string> MakeCreditCardPaymentCommand { get; set; }
public CaptionCommand<string> MakeTicketPaymentCommand { get; set; }
public CaptionCommand<string> SelectTableCommand { get; set; }
public CaptionCommand<string> SelectCustomerCommand { get; set; }
public CaptionCommand<string> PrintTicketCommand { get; set; }
public CaptionCommand<string> PrintInvoiceCommand { get; set; }
public CaptionCommand<string> ShowAllOpenTickets { get; set; }
public CaptionCommand<string> MoveTicketItemsCommand { get; set; }
public ICaptionCommand IncQuantityCommand { get; set; }
public ICaptionCommand DecQuantityCommand { get; set; }
public ICaptionCommand IncSelectionQuantityCommand { get; set; }
public ICaptionCommand DecSelectionQuantityCommand { get; set; }
public ICaptionCommand ShowVoidReasonsCommand { get; set; }
public ICaptionCommand ShowGiftReasonsCommand { get; set; }
public ICaptionCommand ShowTicketTagsCommand { get; set; }
public ICaptionCommand CancelItemCommand { get; set; }
public ICaptionCommand ShowExtraPropertyEditorCommand { get; set; }
public ICaptionCommand EditTicketNoteCommand { get; set; }
public ICaptionCommand RemoveTicketLockCommand { get; set; }
public ICaptionCommand RemoveTicketTagCommand { get; set; }
public ICaptionCommand ChangePriceCommand { get; set; }
public ICaptionCommand PrintJobCommand { get; set; }
public DelegateCommand<TicketTagFilterViewModel> FilterOpenTicketsCommand { get; set; }
private TicketViewModel _selectedTicket;
public TicketViewModel SelectedTicket
{
get
{
if (AppServices.MainDataContext.SelectedTicket == null) _selectedTicket = null;
if (_selectedTicket == null && AppServices.MainDataContext.SelectedTicket != null)
_selectedTicket = new TicketViewModel(AppServices.MainDataContext.SelectedTicket,
AppServices.MainDataContext.SelectedDepartment != null && AppServices.MainDataContext.SelectedDepartment.IsFastFood);
return _selectedTicket;
}
}
private readonly ObservableCollection<TicketItemViewModel> _selectedTicketItems;
public TicketItemViewModel SelectedTicketItem
{
get
{
return SelectedTicket != null && SelectedTicket.SelectedItems.Count == 1 ? SelectedTicket.SelectedItems[0] : null;
}
}
public IEnumerable<PrintJobButton> PrintJobButtons
{
get
{
return SelectedTicket != null
? SelectedTicket.PrintJobButtons.Where(x => x.Model.UseFromPos)
: null;
}
}
public IEnumerable<Department> Departments { get { return AppServices.MainDataContext.Departments; } }
public IEnumerable<Department> PermittedDepartments { get { return AppServices.MainDataContext.PermittedDepartments; } }
public IEnumerable<OpenTicketViewModel> OpenTickets { get; set; }
private IEnumerable<TicketTagFilterViewModel> _openTicketTags;
public IEnumerable<TicketTagFilterViewModel> OpenTicketTags
{
get { return _openTicketTags; }
set
{
_openTicketTags = value;
RaisePropertyChanged("OpenTicketTags");
}
}
private string _selectedTag;
public string SelectedTag
{
get { return !string.IsNullOrEmpty(_selectedTag) ? _selectedTag : SelectedDepartment != null ? SelectedDepartment.DefaultTag : null; }
set { _selectedTag = value; }
}
private int _selectedTicketView;
public int SelectedTicketView
{
get { return _selectedTicketView; }
set
{
StopTimer();
if (value == OpenTicketListView)
{
AppServices.ActiveAppScreen = AppScreens.TicketList;
StartTimer();
}
if (value == SingleTicketView)
{
AppServices.ActiveAppScreen = AppScreens.SingleTicket;
}
_selectedTicketView = value;
RaisePropertyChanged("SelectedTicketView");
}
}
public Department SelectedDepartment
{
get { return AppServices.MainDataContext.SelectedDepartment; }
set
{
if (value != AppServices.MainDataContext.SelectedDepartment)
{
AppServices.MainDataContext.SelectedDepartment = value;
RaisePropertyChanged("SelectedDepartment");
RaisePropertyChanged("SelectedTicket");
SelectedDepartment.PublishEvent(EventTopicNames.SelectedDepartmentChanged);
}
}
}
public bool IsDepartmentSelectorVisible
{
get
{
return PermittedDepartments.Count() > 1 &&
AppServices.IsUserPermittedFor(PermissionNames.ChangeDepartment);
}
}
public bool IsItemsSelected { get { return _selectedTicketItems.Count > 0; } }
public bool IsItemsSelectedAndUnlocked { get { return _selectedTicketItems.Count > 0 && _selectedTicketItems.Where(x => x.IsLocked).Count() == 0; } }
public bool IsItemsSelectedAndLocked { get { return _selectedTicketItems.Count > 0 && _selectedTicketItems.Where(x => !x.IsLocked).Count() == 0; } }
public bool IsNothingSelected { get { return _selectedTicketItems.Count == 0; } }
public bool IsNothingSelectedAndTicketLocked { get { return _selectedTicket != null && _selectedTicketItems.Count == 0 && _selectedTicket.IsLocked; } }
public bool IsNothingSelectedAndTicketTagged { get { return _selectedTicket != null && _selectedTicketItems.Count == 0 && SelectedTicket.IsTagged; } }
public bool IsTicketSelected { get { return SelectedTicket != null && _selectedTicketItems.Count == 0; } }
public bool IsTicketTotalVisible { get { return SelectedTicket != null && SelectedTicket.IsTicketTotalVisible; } }
public bool IsTicketPaymentVisible { get { return SelectedTicket != null && SelectedTicket.IsTicketPaymentVisible; } }
public bool IsTicketRemainingVisible { get { return SelectedTicket != null && SelectedTicket.IsTicketRemainingVisible; } }
public bool IsTicketDiscountVisible { get { return SelectedTicket != null && SelectedTicket.IsTicketDiscountVisible; } }
public bool IsTicketRoundingVisible { get { return SelectedTicket != null && SelectedTicket.IsTicketRoundingVisible; } }
public bool IsTicketVatTotalVisible { get { return SelectedTicket != null && SelectedTicket.IsTicketVatTotalVisible; } }
public bool IsTicketTaxServiceVisible { get { return SelectedTicket != null && SelectedTicket.IsTicketTaxServiceVisible; } }
public bool IsPlainTotalVisible { get { return IsTicketDiscountVisible || IsTicketVatTotalVisible || IsTicketRoundingVisible || IsTicketTaxServiceVisible; } }
public bool IsTableButtonVisible
{
get
{
return ((AppServices.MainDataContext.TableCount > 0 ||
(AppServices.MainDataContext.SelectedDepartment != null
&& AppServices.MainDataContext.SelectedDepartment.IsAlaCarte))
&& IsNothingSelected) &&
((AppServices.MainDataContext.SelectedDepartment != null &&
AppServices.MainDataContext.SelectedDepartment.TableScreenId > 0));
}
}
public bool IsCustomerButtonVisible
{
get
{
return (AppServices.MainDataContext.CustomerCount > 0 ||
(AppServices.MainDataContext.SelectedDepartment != null
&& AppServices.MainDataContext.SelectedDepartment.IsTakeAway))
&& IsNothingSelected;
}
}
public bool CanChangeDepartment
{
get { return SelectedTicket == null && AppServices.MainDataContext.IsCurrentWorkPeriodOpen; }
}
public Brush TicketBackground { get { return SelectedTicket != null && (SelectedTicket.IsLocked || SelectedTicket.IsPaid) ? SystemColors.ControlLightBrush : SystemColors.WindowBrush; } }
public int OpenTicketListViewColumnCount { get { return SelectedDepartment != null ? SelectedDepartment.OpenTicketViewColumnCount : 5; } }
public TicketItemViewModel LastSelectedTicketItem { get; set; }
public IEnumerable<TicketTagButton> TicketTagButtons
{
get
{
return AppServices.MainDataContext.SelectedDepartment != null
? AppServices.MainDataContext.SelectedDepartment.TicketTagGroups
.Where(x => x.ActiveOnPosClient)
.OrderBy(x => x.Order)
.Select(x => new TicketTagButton(x, SelectedTicket))
: null;
}
}
public TicketListViewModel()
{
_timer = new Timer(OnTimer, null, Timeout.Infinite, 1000);
_selectedTicketItems = new ObservableCollection<TicketItemViewModel>();
PrintJobCommand = new CaptionCommand<PrintJob>(Resources.Print, OnPrintJobExecute, CanExecutePrintJob);
AddMenuItemCommand = new DelegateCommand<ScreenMenuItemData>(OnAddMenuItemCommandExecute);
CloseTicketCommand = new CaptionCommand<string>(Resources.CloseTicket_r, OnCloseTicketExecute, CanCloseTicket);
OpenTicketCommand = new DelegateCommand<int?>(OnOpenTicketExecute);
MakePaymentCommand = new CaptionCommand<string>(Resources.GetPayment, OnMakePaymentExecute, CanMakePayment);
MakeCashPaymentCommand = new CaptionCommand<string>(Resources.CashPayment_r, OnMakeCashPaymentExecute, CanMakeFastPayment);
MakeCreditCardPaymentCommand = new CaptionCommand<string>(Resources.CreditCard_r, OnMakeCreditCardPaymentExecute, CanMakeFastPayment);
MakeTicketPaymentCommand = new CaptionCommand<string>(Resources.Voucher_r, OnMakeTicketPaymentExecute, CanMakeFastPayment);
SelectTableCommand = new CaptionCommand<string>(Resources.SelectTable, OnSelectTableExecute, CanSelectTable);
SelectCustomerCommand = new CaptionCommand<string>(Resources.SelectCustomer, OnSelectCustomerExecute, CanSelectCustomer);
ShowAllOpenTickets = new CaptionCommand<string>(Resources.AllTickets_r, OnShowAllOpenTickets);
FilterOpenTicketsCommand = new DelegateCommand<TicketTagFilterViewModel>(OnFilterOpenTicketsExecute);
IncQuantityCommand = new CaptionCommand<string>("+", OnIncQuantityCommand, CanIncQuantity);
DecQuantityCommand = new CaptionCommand<string>("-", OnDecQuantityCommand, CanDecQuantity);
IncSelectionQuantityCommand = new CaptionCommand<string>("(+)", OnIncSelectionQuantityCommand, CanIncSelectionQuantity);
DecSelectionQuantityCommand = new CaptionCommand<string>("(-)", OnDecSelectionQuantityCommand, CanDecSelectionQuantity);
ShowVoidReasonsCommand = new CaptionCommand<string>(Resources.Void, OnShowVoidReasonsExecuted, CanVoidSelectedItems);
ShowGiftReasonsCommand = new CaptionCommand<string>(Resources.Gift, OnShowGiftReasonsExecuted, CanGiftSelectedItems);
ShowTicketTagsCommand = new CaptionCommand<TicketTagGroup>(Resources.Tag, OnShowTicketsTagExecute, CanExecuteShowTicketTags);
CancelItemCommand = new CaptionCommand<string>(Resources.Cancel, OnCancelItemCommand, CanCancelSelectedItems);
MoveTicketItemsCommand = new CaptionCommand<string>(Resources.MoveTicketLine, OnMoveTicketItems, CanMoveTicketItems);
ShowExtraPropertyEditorCommand = new CaptionCommand<string>(Resources.ExtraModifier, OnShowExtraProperty, CanShowExtraProperty);
EditTicketNoteCommand = new CaptionCommand<string>(Resources.TicketNote, OnEditTicketNote, CanEditTicketNote);
RemoveTicketLockCommand = new CaptionCommand<string>(Resources.ReleaseLock, OnRemoveTicketLock, CanRemoveTicketLock);
ChangePriceCommand = new CaptionCommand<string>(Resources.ChangePrice, OnChangePrice, CanChangePrice);
EventServiceFactory.EventService.GetEvent<GenericEvent<LocationData>>().Subscribe(
x =>
{
if (x.Topic == EventTopicNames.LocationSelectedForTicket)
{
if (SelectedTicket != null)
{
var oldLocationName = SelectedTicket.Location;
var ticketsMerged = x.Value.TicketId > 0 && x.Value.TicketId != SelectedTicket.Id;
TicketViewModel.AssignTableToSelectedTicket(x.Value.LocationId);
CloseTicket();
if (!AppServices.CurrentTerminal.AutoLogout)
EventServiceFactory.EventService.PublishEvent(EventTopicNames.ActivateTicketView);
if (!string.IsNullOrEmpty(oldLocationName) || ticketsMerged)
if (ticketsMerged && !string.IsNullOrEmpty(oldLocationName))
InteractionService.UserIntraction.GiveFeedback(string.Format(Resources.TablesMerged_f, oldLocationName, x.Value.Caption));
else if (ticketsMerged)
InteractionService.UserIntraction.GiveFeedback(string.Format(Resources.TicketMergedToTable_f, x.Value.Caption));
else if (oldLocationName != x.Value.LocationName)
InteractionService.UserIntraction.GiveFeedback(string.Format(Resources.TicketMovedToTable_f, oldLocationName, x.Value.Caption));
}
else
{
if (x.Value.TicketId == 0)
{
TicketViewModel.CreateNewTicket();
TicketViewModel.AssignTableToSelectedTicket(x.Value.LocationId);
}
else
{
AppServices.MainDataContext.OpenTicket(x.Value.TicketId);
if (SelectedTicket != null)
{
if (SelectedTicket.Location != x.Value.LocationName)
AppServices.MainDataContext.ResetTableDataForSelectedTicket();
}
}
EventServiceFactory.EventService.PublishEvent(EventTopicNames.DisplayTicketView);
}
}
}
);
EventServiceFactory.EventService.GetEvent<GenericEvent<WorkPeriod>>().Subscribe(
x =>
{
if (x.Topic == EventTopicNames.WorkPeriodStatusChanged)
{
RaisePropertyChanged("CanChangeDepartment");
}
});
EventServiceFactory.EventService.GetEvent<GenericEvent<TicketItemViewModel>>().Subscribe(
x =>
{
if (SelectedTicket != null && x.Topic == EventTopicNames.SelectedItemsChanged)
{
LastSelectedTicketItem = x.Value.Selected ? x.Value : null;
foreach (var item in SelectedTicket.SelectedItems)
{ item.IsLastSelected = item == LastSelectedTicketItem; }
SelectedTicket.PublishEvent(EventTopicNames.SelectedItemsChanged);
}
});
EventServiceFactory.EventService.GetEvent<GenericEvent<TicketTagData>>().Subscribe(
x =>
{
if (x.Topic == EventTopicNames.TagSelectedForSelectedTicket)
{
if (x.Value.Action == 1 && CanCloseTicket(""))
CloseTicketCommand.Execute("");
if (x.Value.Action == 2 && CanMakePayment(""))
MakePaymentCommand.Execute("");
else
{
RefreshVisuals();
}
}
});
EventServiceFactory.EventService.GetEvent<GenericEvent<TicketViewModel>>().Subscribe(
x =>
{
if (x.Topic == EventTopicNames.SelectedItemsChanged)
{
_selectedTicketItems.Clear();
_selectedTicketItems.AddRange(x.Value.SelectedItems);
if (x.Value.SelectedItems.Count == 0) LastSelectedTicketItem = null;
RaisePropertyChanged("IsItemsSelected");
RaisePropertyChanged("IsNothingSelected");
RaisePropertyChanged("IsNothingSelectedAndTicketLocked");
RaisePropertyChanged("IsTableButtonVisible");
RaisePropertyChanged("IsCustomerButtonVisible");
RaisePropertyChanged("IsItemsSelectedAndUnlocked");
RaisePropertyChanged("IsItemsSelectedAndLocked");
RaisePropertyChanged("IsTicketSelected");
}
});
EventServiceFactory.EventService.GetEvent<GenericEvent<Customer>>().Subscribe(
x =>
{
if (x.Topic == EventTopicNames.CustomerSelectedForTicket)
{
if (AppServices.MainDataContext.SelectedTicket == null)
TicketViewModel.CreateNewTicket();
AppServices.MainDataContext.AssignCustomerToSelectedTicket(x.Value);
var lastOrder = Dao.Last<Ticket>(y => y.CustomerId == x.Value.Id);
var lastOderDayCount = lastOrder != null
? Convert.ToInt32(new TimeSpan(DateTime.Now.Ticks - lastOrder.Date.Ticks).TotalDays) : -1;
var lastOderTotal = lastOrder != null
? lastOrder.TotalAmount : -1;
RuleExecutor.NotifyEvent(RuleEventNames.CustomerSelectedForTicket,
new
{
Ticket = AppServices.MainDataContext.SelectedTicket,
CustomerId = x.Value.Id,
CustomerName = x.Value.Name,
x.Value.PhoneNumber,
CustomerNote = x.Value.Note,
CustomerGroupCode = x.Value.GroupCode,
LastOrderTotal = lastOderTotal,
LastOrderDayCount = lastOderDayCount
});
if (!string.IsNullOrEmpty(SelectedTicket.CustomerName) && SelectedTicket.Items.Count > 0)
CloseTicket();
else
{
RefreshVisuals();
SelectedTicketView = SingleTicketView;
}
}
if (x.Topic == EventTopicNames.PaymentRequestedForTicket)
{
AppServices.MainDataContext.AssignCustomerToSelectedTicket(x.Value);
if (!string.IsNullOrEmpty(SelectedTicket.CustomerName) && SelectedTicket.Items.Count > 0)
MakePaymentCommand.Execute("");
else
{
RefreshVisuals();
SelectedTicketView = SingleTicketView;
}
}
});
EventServiceFactory.EventService.GetEvent<GenericEvent<Ticket>>().Subscribe(
x =>
{
_selectedTicket = null;
if (x.Topic == EventTopicNames.PaymentSubmitted)
{
CloseTicket();
}
});
EventServiceFactory.EventService.GetEvent<GenericEvent<EventAggregator>>().Subscribe(
x =>
{
if (SelectedDepartment == null)
UpdateSelectedDepartment(AppServices.CurrentLoggedInUser.UserRole.DepartmentId);
if (x.Topic == EventTopicNames.ActivateTicketView)
{
UpdateSelectedTicketView();
DisplayTickets();
}
if (x.Topic == EventTopicNames.DisplayTicketView)
{
UpdateSelectedTicketView();
RefreshVisuals();
}
if (x.Topic == EventTopicNames.RefreshSelectedTicket)
{
_selectedTicket = null;
RefreshVisuals();
SelectedTicketView = SingleTicketView;
}
});
EventServiceFactory.EventService.GetEvent<GenericEvent<Message>>().Subscribe(
x =>
{
if (AppServices.ActiveAppScreen == AppScreens.TicketList
&& x.Topic == EventTopicNames.MessageReceivedEvent
&& x.Value.Command == Messages.TicketRefreshMessage)
{
RefreshOpenTickets();
RefreshVisuals();
}
});
EventServiceFactory.EventService.GetEvent<GenericEvent<PopupData>>().Subscribe(
x =>
{
if (x.Value.EventMessage == "SelectCustomer")
{
var dep = AppServices.MainDataContext.Departments.FirstOrDefault(y => y.IsTakeAway);
if (dep != null)
{
UpdateSelectedDepartment(dep.Id);
SelectedTicketView = OpenTicketListView;
}
if (SelectedDepartment == null)
SelectedDepartment = AppServices.MainDataContext.Departments.FirstOrDefault();
RefreshVisuals();
}
});
EventServiceFactory.EventService.GetEvent<GenericEvent<CreditCardProcessingResult>>().Subscribe(OnProcessCreditCard);
}
private void OnProcessCreditCard(EventParameters<CreditCardProcessingResult> obj)
{
if (obj.Topic == EventTopicNames.PaymentProcessed && AppServices.ActiveAppScreen != AppScreens.Payment)
{
if (obj.Value.ProcessType == ProcessType.Force)
{
TicketViewModel.AddPaymentToSelectedTicket(AppServices.MainDataContext.SelectedTicket.GetRemainingAmount(), PaymentType.CreditCard);
if (AppServices.MainDataContext.SelectedTicket.GetRemainingAmount() == 0)
CloseTicket();
}
}
}
private void UpdateSelectedTicketView()
{
if (SelectedTicket != null || (SelectedDepartment != null && SelectedDepartment.IsFastFood))
SelectedTicketView = SingleTicketView;
else if (SelectedDepartment != null)
{
SelectedTicketView = OpenTicketListView;
RefreshOpenTickets();
}
}
private bool CanExecuteShowTicketTags(TicketTagGroup arg)
{
return SelectedTicket == null || (SelectedTicket.Model.CanSubmit);
}
private void OnShowTicketsTagExecute(TicketTagGroup tagGroup)
{
if (SelectedTicket != null)
{
_selectedTicket.LastSelectedTicketTag = tagGroup;
_selectedTicket.PublishEvent(EventTopicNames.SelectTicketTag);
}
else if (ShowAllOpenTickets.CanExecute(""))
{
SelectedTag = tagGroup.Name;
RefreshOpenTickets();
if ((OpenTickets != null && OpenTickets.Count() > 0) || OpenTicketTags.Count() > 0)
{
SelectedTicketView = OpenTicketListView;
RaisePropertyChanged("OpenTickets");
}
else InteractionService.UserIntraction.GiveFeedback(string.Format(Resources.NoTicketsFoundForTag, tagGroup.Name));
}
}
private bool CanChangePrice(string arg)
{
return SelectedTicket != null
&& !SelectedTicket.IsLocked
&& SelectedTicket.Model.CanSubmit
&& _selectedTicketItems.Count == 1
&& (_selectedTicketItems[0].Price == 0 || AppServices.IsUserPermittedFor(PermissionNames.ChangeItemPrice));
}
private void OnChangePrice(string obj)
{
decimal price;
decimal.TryParse(AppServices.MainDataContext.NumeratorValue, out price);
if (price <= 0)
{
InteractionService.UserIntraction.GiveFeedback(Resources.ForChangingPriceTypeAPrice);
}
else
{
_selectedTicketItems[0].UpdatePrice(price);
}
_selectedTicket.ClearSelectedItems();
_selectedTicket.RefreshVisuals();
EventServiceFactory.EventService.PublishEvent(EventTopicNames.ResetNumerator);
}
private bool CanExecutePrintJob(PrintJob arg)
{
return arg != null && SelectedTicket != null && (!SelectedTicket.IsLocked || SelectedTicket.Model.GetPrintCount(arg.Id) == 0);
}
private void OnPrintJobExecute(PrintJob printJob)
{
var message = SelectedTicket.GetPrintError();
if (!string.IsNullOrEmpty(message))
{
InteractionService.UserIntraction.GiveFeedback(message);
return;
}
SaveTicketIfNew();
AppServices.PrintService.ManualPrintTicket(SelectedTicket.Model, printJob);
if (printJob.WhenToPrint == (int)WhenToPrintTypes.Paid && !SelectedTicket.IsPaid)
MakePaymentCommand.Execute("");
else if (printJob.CloseTicket)
CloseTicket();
}
private void SaveTicketIfNew()
{
if ((SelectedTicket.Id == 0 || SelectedTicket.Items.Any(x => x.Model.Id == 0)) && SelectedTicket.Items.Count > 0)
{
var result = AppServices.MainDataContext.CloseTicket();
AppServices.MainDataContext.OpenTicket(result.TicketId);
_selectedTicket = null;
}
}
private bool CanRemoveTicketLock(string arg)
{
return SelectedTicket != null && (SelectedTicket.IsLocked) &&
AppServices.IsUserPermittedFor(PermissionNames.AddItemsToLockedTickets);
}
private void OnRemoveTicketLock(string obj)
{
SelectedTicket.IsLocked = false;
SelectedTicket.RefreshVisuals();
}
private void OnMoveTicketItems(string obj)
{
SelectedTicket.FixSelectedItems();
var newTicketId = AppServices.MainDataContext.MoveTicketItems(SelectedTicket.SelectedItems.Select(x => x.Model), 0).TicketId;
OnOpenTicketExecute(newTicketId);
}
private bool CanMoveTicketItems(string arg)
{
return SelectedTicket != null && SelectedTicket.CanMoveSelectedItems();
}
private bool CanEditTicketNote(string arg)
{
return SelectedTicket != null && !SelectedTicket.IsPaid;
}
private void OnEditTicketNote(string obj)
{
SelectedTicket.PublishEvent(EventTopicNames.EditTicketNote);
}
private bool CanShowExtraProperty(string arg)
{
return SelectedTicketItem != null && !SelectedTicketItem.Model.Locked && AppServices.IsUserPermittedFor(PermissionNames.ChangeExtraProperty);
}
private void OnShowExtraProperty(string obj)
{
_selectedTicket.PublishEvent(EventTopicNames.SelectExtraProperty);
}
private void OnDecQuantityCommand(string obj)
{
LastSelectedTicketItem.Quantity--;
_selectedTicket.RefreshVisuals();
}
private void OnIncQuantityCommand(string obj)
{
LastSelectedTicketItem.Quantity++;
_selectedTicket.RefreshVisuals();
}
private bool CanDecQuantity(string arg)
{
return LastSelectedTicketItem != null &&
LastSelectedTicketItem.Quantity > 1 &&
!LastSelectedTicketItem.IsLocked &&
!LastSelectedTicketItem.IsVoided;
}
private bool CanIncQuantity(string arg)
{
return LastSelectedTicketItem != null &&
!LastSelectedTicketItem.IsLocked &&
!LastSelectedTicketItem.IsVoided;
}
private bool CanDecSelectionQuantity(string arg)
{
return LastSelectedTicketItem != null &&
LastSelectedTicketItem.Quantity > 1 &&
LastSelectedTicketItem.IsLocked &&
!LastSelectedTicketItem.IsGifted &&
!LastSelectedTicketItem.IsVoided;
}
private void OnDecSelectionQuantityCommand(string obj)
{
LastSelectedTicketItem.DecSelectedQuantity();
_selectedTicket.RefreshVisuals();
}
private bool CanIncSelectionQuantity(string arg)
{
return LastSelectedTicketItem != null &&
LastSelectedTicketItem.Quantity > 1 &&
LastSelectedTicketItem.IsLocked &&
!LastSelectedTicketItem.IsGifted &&
!LastSelectedTicketItem.IsVoided;
}
private void OnIncSelectionQuantityCommand(string obj)
{
LastSelectedTicketItem.IncSelectedQuantity();
_selectedTicket.RefreshVisuals();
}
private bool CanVoidSelectedItems(string arg)
{
if (_selectedTicket != null && !_selectedTicket.IsLocked && AppServices.IsUserPermittedFor(PermissionNames.VoidItems))
return _selectedTicket.CanVoidSelectedItems();
return false;
}
private void OnShowVoidReasonsExecuted(string obj)
{
_selectedTicket.PublishEvent(EventTopicNames.SelectVoidReason);
}
private void OnShowGiftReasonsExecuted(string obj)
{
_selectedTicket.PublishEvent(EventTopicNames.SelectGiftReason);
}
private bool CanCancelSelectedItems(string arg)
{
if (_selectedTicket != null)
return _selectedTicket.CanCancelSelectedItems();
return false;
}
private void OnCancelItemCommand(string obj)
{
_selectedTicket.CancelSelectedItems();
RefreshSelectedTicket();
}
private bool CanGiftSelectedItems(string arg)
{
if (_selectedTicket != null && !_selectedTicket.IsLocked && AppServices.IsUserPermittedFor(PermissionNames.GiftItems))
return _selectedTicket.CanGiftSelectedItems();
return false;
}
private void OnTimer(object state)
{
if (AppServices.ActiveAppScreen == AppScreens.TicketList && OpenTickets != null)
foreach (var openTicketView in OpenTickets)
{
openTicketView.Refresh();
}
}
private void OnShowAllOpenTickets(string obj)
{
UpdateOpenTickets(null, "", "");
SelectedTicketView = OpenTicketListView;
RaisePropertyChanged("OpenTickets");
}
private void OnFilterOpenTicketsExecute(TicketTagFilterViewModel obj)
{
UpdateOpenTickets(SelectedDepartment, obj.TagGroup, obj.TagValue);
RaisePropertyChanged("OpenTickets");
SelectedTag = null;
}
private string _selectedTicketTitle;
public string SelectedTicketTitle
{
get { return _selectedTicketTitle; }
set { _selectedTicketTitle = value; RaisePropertyChanged("SelectedTicketTitle"); }
}
public void UpdateSelectedTicketTitle()
{
SelectedTicketTitle = SelectedTicket == null || SelectedTicket.Title.Trim() == "#" ? Resources.NewTicket : SelectedTicket.Title;
}
private void OnSelectCustomerExecute(string obj)
{
SelectedDepartment.PublishEvent(EventTopicNames.SelectCustomer);
}
private bool CanSelectCustomer(string arg)
{
return (SelectedTicket == null ||
(SelectedTicket.Items.Count != 0
&& !SelectedTicket.IsLocked
&& SelectedTicket.Model.CanSubmit));
}
private bool CanSelectTable(string arg)
{
if (SelectedTicket != null && !SelectedTicket.IsLocked)
return SelectedTicket.CanChangeTable();
return SelectedTicket == null;
}
private void OnSelectTableExecute(string obj)
{
SelectedDepartment.PublishEvent(EventTopicNames.SelectTable);
}
public string SelectTableButtonCaption
{
get
{
if (SelectedTicket != null && !string.IsNullOrEmpty(SelectedTicket.Location))
return Resources.ChangeTable_r;
return Resources.SelectTable_r;
}
}
public string SelectCustomerButtonCaption
{
get
{
if (SelectedTicket != null && !string.IsNullOrEmpty(SelectedTicket.CustomerName))
return Resources.CustomerInfo_r;
return Resources.SelectCustomer_r;
}
}
private bool CanMakePayment(string arg)
{
if (AppServices.MainDataContext.SelectedDepartment != null && AppServices.CurrentTerminal.DepartmentId > 0
&& AppServices.MainDataContext.SelectedDepartment.Id != AppServices.CurrentTerminal.DepartmentId)
return false;
return SelectedTicket != null
&& (SelectedTicket.TicketPlainTotalValue > 0 || SelectedTicket.Items.Count > 0)
&& AppServices.IsUserPermittedFor(PermissionNames.MakePayment);
}
private void OnMakeCreditCardPaymentExecute(string obj)
{
if (CreditCardProcessingService.CanProcessCreditCards)
{
var ccpd = new CreditCardProcessingData
{
TenderedAmount = AppServices.MainDataContext.SelectedTicket.GetRemainingAmount(),
Ticket = AppServices.MainDataContext.SelectedTicket
};
CreditCardProcessingService.Process(ccpd);
return;
}
TicketViewModel.PaySelectedTicket(PaymentType.CreditCard);
CloseTicket();
}
private void OnMakeTicketPaymentExecute(string obj)
{
TicketViewModel.PaySelectedTicket(PaymentType.Ticket);
CloseTicket();
}
private void OnMakeCashPaymentExecute(string obj)
{
TicketViewModel.PaySelectedTicket(PaymentType.Cash);
CloseTicket();
}
private bool CanMakeFastPayment(string arg)
{
if (AppServices.MainDataContext.SelectedDepartment != null && AppServices.CurrentTerminal.DepartmentId > 0
&& AppServices.MainDataContext.SelectedDepartment.Id != AppServices.CurrentTerminal.DepartmentId) return false;
return SelectedTicket != null && SelectedTicket.TicketRemainingValue > 0 && AppServices.IsUserPermittedFor(PermissionNames.MakeFastPayment);
}
private bool CanCloseTicket(string arg)
{
return SelectedTicket == null || SelectedTicket.CanCloseTicket();
}
private void CloseTicket()
{
if (AppServices.MainDataContext.SelectedDepartment.IsFastFood && !CanCloseTicket(""))
{
SaveTicketIfNew();
RefreshVisuals();
}
else if (CanCloseTicket(""))
CloseTicketCommand.Execute("");
}
public void DisplayTickets()
{
if (SelectedDepartment != null)
{
if (SelectedDepartment.IsAlaCarte)
{
SelectedDepartment.PublishEvent(EventTopicNames.SelectTable);
StopTimer();
RefreshVisuals();
return;
}
if (SelectedDepartment.IsTakeAway)
{
SelectedDepartment.PublishEvent(EventTopicNames.SelectCustomer);
StopTimer();
RefreshVisuals();
return;
}
SelectedTicketView = SelectedDepartment.IsFastFood ? SingleTicketView : OpenTicketListView;
if (SelectedTicket != null)
{
if (!SelectedDepartment.IsFastFood || SelectedTicket.TicketRemainingValue == 0 || !string.IsNullOrEmpty(SelectedTicket.Location))
{
SelectedTicket.ClearSelectedItems();
}
}
}
RefreshOpenTickets();
RefreshVisuals();
}
public bool IsFastPaymentButtonsVisible
{
get
{
if (SelectedTicket != null && SelectedTicket.IsPaid) return false;
if (SelectedTicket != null && !string.IsNullOrEmpty(SelectedTicket.Location)) return false;
if (SelectedTicket != null && !string.IsNullOrEmpty(SelectedTicket.CustomerName)) return false;
if (SelectedTicket != null && SelectedDepartment != null && SelectedDepartment.TicketTagGroups.Any(x => SelectedTicket.IsTaggedWith(x.Name))) return false;
if (SelectedTicket != null && SelectedTicket.TicketRemainingValue == 0) return false;
if (SelectedTicket != null && AppServices.CurrentTerminal.DepartmentId > 0 && SelectedDepartment != null && SelectedDepartment.Id != AppServices.CurrentTerminal.DepartmentId) return false;
return SelectedDepartment != null && SelectedDepartment.IsFastFood;
}
}
public bool IsCloseButtonVisible
{
get { return !IsFastPaymentButtonsVisible; }
}
public void RefreshOpenTickets()
{
UpdateOpenTickets(SelectedDepartment, SelectedTag, "");
SelectedTag = string.Empty;
}
public void UpdateOpenTickets(Department department, string selectedTag, string tagFilter)
{
StopTimer();
Expression<Func<Ticket, bool>> prediction;
if (department != null && string.IsNullOrEmpty(selectedTag))
prediction = x => !x.IsPaid && x.DepartmentId == department.Id;
else
prediction = x => !x.IsPaid;
var shouldWrap = department != null && !department.IsTakeAway;
OpenTickets = Dao.Select(x => new OpenTicketViewModel
{
Id = x.Id,
LastOrderDate = x.LastOrderDate,
TicketNumber = x.TicketNumber,
LocationName = x.LocationName,
CustomerName = x.CustomerName,
RemainingAmount = x.RemainingAmount,
Date = x.Date,
WrapText = shouldWrap,
TicketTag = x.Tag
}, prediction).OrderBy(x => x.LastOrderDate);
if (!string.IsNullOrEmpty(selectedTag))
{
var tagGroup = AppServices.MainDataContext.SelectedDepartment.TicketTagGroups.SingleOrDefault(
x => x.Name == selectedTag);
if (tagGroup != null)
{
var openTickets = GetOpenTickets(OpenTickets, tagGroup, tagFilter);
if (!string.IsNullOrEmpty(tagFilter.Trim()) && tagFilter != "*")
{
if (openTickets.Count() == 1)
{
OpenTicketCommand.Execute(openTickets.ElementAt(0).Id);
}
if (openTickets.Count() == 0)
{
TicketViewModel.CreateNewTicket();
AppServices.MainDataContext.SelectedTicket.SetTagValue(selectedTag, tagFilter);
RefreshSelectedTicket();
RefreshVisuals();
}
}
if (SelectedTicket == null)
{
OpenTicketTags = GetOpenTicketTags(OpenTickets, tagGroup, tagFilter);
OpenTickets = string.IsNullOrEmpty(tagFilter) && OpenTicketTags.Count() > 0 ? null : openTickets;
}
}
}
else
{
OpenTicketTags = null;
}
SelectedTag = selectedTag;
StartTimer();
}
private static IEnumerable<TicketTagFilterViewModel> GetOpenTicketTags(IEnumerable<OpenTicketViewModel> openTickets, TicketTagGroup tagGroup, string tagFilter)
{
var tag = tagGroup.Name.ToLower() + ":";
var cnt = openTickets.Count(x => string.IsNullOrEmpty(x.TicketTag) || !x.TicketTag.ToLower().Contains(tag));
var opt = new List<TicketTagFilterViewModel>();
if (string.IsNullOrEmpty(tagFilter) && tagGroup.TicketTags.Count > 1)
{
opt = openTickets.Where(x => !string.IsNullOrEmpty(x.TicketTag))
.SelectMany(x => x.TicketTag.Split('\r'))
.Where(x => x.ToLower().Contains(tag))
.Distinct()
.Select(x => x.Split(':')).Select(x => new TicketTagFilterViewModel { TagGroup = x[0], TagValue = x[1] }).OrderBy(x => x.TagValue).ToList();
var usedTags = opt.Select(x => x.TagValue);
opt.AddRange(tagGroup.TicketTags.Select(x => x.Name).Where(x => !usedTags.Contains(x)).Select(x => new TicketTagFilterViewModel { TagGroup = tagGroup.Name, ButtonColor = "White", TagValue = x }));
opt.Sort(new AlphanumComparator());
}
if (tagGroup.TicketTags.Count > 1)
{
if (string.IsNullOrEmpty(tagFilter))
opt.Insert(0, new TicketTagFilterViewModel { TagGroup = tagGroup.Name, TagValue = "*", ButtonColor = "Blue" });
else
opt.Insert(0, new TicketTagFilterViewModel { TagGroup = tagGroup.Name, TagValue = "", ButtonColor = "Green" });
if (cnt > 0)
opt.Insert(0, new TicketTagFilterViewModel { Count = cnt, TagGroup = tagGroup.Name, ButtonColor = "Red", TagValue = " " });
}
return opt;
}
private static IEnumerable<OpenTicketViewModel> GetOpenTickets(IEnumerable<OpenTicketViewModel> openTickets, TicketTagGroup tagGroup, string tagFilter)
{
var tag = tagGroup.Name.ToLower() + ":";
IEnumerable<OpenTicketViewModel> result = openTickets.ToList();
if (tagFilter == " ")
{
result = result.Where(x =>
string.IsNullOrEmpty(x.TicketTag) ||
!x.TicketTag.ToLower().Contains(tag));
}
else
{
result = result.Where(x => !string.IsNullOrEmpty(x.TicketTag) && x.TicketTag.ToLower().Contains(tag));
}
if (!string.IsNullOrEmpty(tagFilter.Trim()))
{
if (tagFilter != "*")
{
result = result.Where(x => x.TicketTag.ToLower().Contains((tag + tagFilter + "\r").ToLower()));
}
result.ForEach(x => x.Info = x.TicketTag.Split('\r').Where(y => y.ToLower().StartsWith(tag)).Single().Split(':')[1]);
}
return result;
}
private void StartTimer()
{
if (AppServices.ActiveAppScreen == AppScreens.TicketList)
_timer.Change(60000, 60000);
}
private void StopTimer()
{
_timer.Change(Timeout.Infinite, 60000);
}
private static void OnMakePaymentExecute(string obj)
{
AppServices.MainDataContext.SelectedTicket.PublishEvent(EventTopicNames.MakePayment);
}
private void OnCloseTicketExecute(string obj)
{
if (SelectedTicketItem != null && !SelectedTicketItem.IsLocked)
{
var unselectedItem = AppServices.DataAccessService.GetUnselectedItem(SelectedTicketItem.Model);
if (unselectedItem != null)
{
InteractionService.UserIntraction.GiveFeedback(string.Format(Resources.SelectionRequired_f, unselectedItem.Name));
return;
}
}
if (SelectedTicket.Items.Count > 0 && SelectedTicket.Model.GetRemainingAmount() == 0)
{
var message = SelectedTicket.GetPrintError();
if (!string.IsNullOrEmpty(message))
{
SelectedTicket.ClearSelectedItems();
RefreshVisuals();
InteractionService.UserIntraction.GiveFeedback(message);
return;
}
}
SelectedTicket.ClearSelectedItems();
var result = AppServices.MainDataContext.CloseTicket();
if (!string.IsNullOrEmpty(result.ErrorMessage))
{
InteractionService.UserIntraction.GiveFeedback(result.ErrorMessage);
}
else
{
RuleExecutor.NotifyEvent(RuleEventNames.TicketClosed, new { Ticket = _selectedTicket.Model });
}
_selectedTicket = null;
_selectedTicketItems.Clear();
if (AppServices.CurrentTerminal.AutoLogout)
{
AppServices.LogoutUser(false);
AppServices.CurrentLoggedInUser.PublishEvent(EventTopicNames.UserLoggedOut);
}
else
{
DisplayTickets();
}
AppServices.MessagingService.SendMessage(Messages.TicketRefreshMessage, result.TicketId.ToString());
}
private void OnOpenTicketExecute(int? id)
{
_selectedTicket = null;
_selectedTicketItems.Clear();
AppServices.MainDataContext.OpenTicket(id.GetValueOrDefault(0));
SelectedTicketView = SingleTicketView;
RefreshVisuals();
SelectedTicket.ClearSelectedItems();
SelectedTicket.PublishEvent(EventTopicNames.SelectedTicketChanged);
}
private void RefreshVisuals()
{
UpdateSelectedTicketTitle();
RaisePropertyChanged("SelectedTicket");
RaisePropertyChanged("CanChangeDepartment");
RaisePropertyChanged("IsTicketRemainingVisible");
RaisePropertyChanged("IsTicketPaymentVisible");
RaisePropertyChanged("IsTicketTotalVisible");
RaisePropertyChanged("IsTicketDiscountVisible");
RaisePropertyChanged("IsTicketVatTotalVisible");
RaisePropertyChanged("IsTicketTaxServiceVisible");
RaisePropertyChanged("IsTicketRoundingVisible");
RaisePropertyChanged("IsPlainTotalVisible");
RaisePropertyChanged("IsFastPaymentButtonsVisible");
RaisePropertyChanged("IsCloseButtonVisible");
RaisePropertyChanged("SelectTableButtonCaption");
RaisePropertyChanged("SelectCustomerButtonCaption");
RaisePropertyChanged("OpenTicketListViewColumnCount");
RaisePropertyChanged("IsDepartmentSelectorVisible");
RaisePropertyChanged("TicketBackground");
RaisePropertyChanged("IsTableButtonVisible");
RaisePropertyChanged("IsCustomerButtonVisible");
RaisePropertyChanged("IsNothingSelectedAndTicketLocked");
RaisePropertyChanged("IsNothingSelectedAndTicketTagged");
RaisePropertyChanged("IsTicketSelected");
RaisePropertyChanged("TicketTagButtons");
RaisePropertyChanged("PrintJobButtons");
if (SelectedTicketView == OpenTicketListView)
RaisePropertyChanged("OpenTickets");
}
private void OnAddMenuItemCommandExecute(ScreenMenuItemData obj)
{
if (SelectedTicket == null)
{
TicketViewModel.CreateNewTicket();
RefreshVisuals();
}
Debug.Assert(SelectedTicket != null);
if (SelectedTicket.IsLocked && !AppServices.IsUserPermittedFor(PermissionNames.AddItemsToLockedTickets)) return;
var ti = SelectedTicket.AddNewItem(obj.ScreenMenuItem.MenuItemId, obj.Quantity, obj.ScreenMenuItem.Gift, obj.ScreenMenuItem.DefaultProperties, obj.ScreenMenuItem.ItemPortion);
if (obj.ScreenMenuItem.AutoSelect && ti != null)
{
ti.ItemSelectedCommand.Execute(ti);
}
RefreshSelectedTicket();
}
private void RefreshSelectedTicket()
{
SelectedTicketView = SingleTicketView;
RaisePropertyChanged("SelectedTicket");
RaisePropertyChanged("IsTicketRemainingVisible");
RaisePropertyChanged("IsTicketPaymentVisible");
RaisePropertyChanged("IsTicketTotalVisible");
RaisePropertyChanged("IsTicketDiscountVisible");
RaisePropertyChanged("IsTicketVatTotalVisible");
RaisePropertyChanged("IsTicketTaxServiceVisible");
RaisePropertyChanged("IsTicketRoundingVisible");
RaisePropertyChanged("IsPlainTotalVisible");
RaisePropertyChanged("CanChangeDepartment");
RaisePropertyChanged("TicketBackground");
RaisePropertyChanged("IsTicketSelected");
RaisePropertyChanged("IsFastPaymentButtonsVisible");
RaisePropertyChanged("IsCloseButtonVisible");
}
public void UpdateSelectedDepartment(int departmentId)
{
RaisePropertyChanged("Departments");
RaisePropertyChanged("PermittedDepartments");
SelectedDepartment = departmentId > 0
? Departments.SingleOrDefault(x => x.Id == departmentId)
: null;
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.TicketModule/TicketListViewModel.cs | C# | gpl3 | 54,850 |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Windows.Input;
using Microsoft.Practices.Prism.Commands;
using Samba.Domain.Models.Menus;
using Samba.Domain.Models.Tickets;
using Samba.Infrastructure;
using Samba.Localization.Properties;
using Samba.Persistance.Data;
using Samba.Presentation.Common;
using Samba.Presentation.Common.Services;
using Samba.Presentation.ViewModels;
using Samba.Services;
namespace Samba.Modules.TicketModule
{
public class SelectedTicketItemsViewModel : ObservableObject
{
private bool _showExtraPropertyEditor;
private bool _showTicketNoteEditor;
private bool _showFreeTagEditor;
private bool _removeModifier;
public SelectedTicketItemsViewModel()
{
CloseCommand = new CaptionCommand<string>(Resources.Close, OnCloseCommandExecuted);
SelectReasonCommand = new DelegateCommand<int?>(OnReasonSelected);
SelectTicketTagCommand = new DelegateCommand<TicketTag>(OnTicketTagSelected);
PortionSelectedCommand = new DelegateCommand<MenuItemPortion>(OnPortionSelected);
PropertySelectedCommand = new DelegateCommand<MenuItemProperty>(OnPropertySelected);
PropertyGroupSelectedCommand = new DelegateCommand<MenuItemGroupedPropertyItemViewModel>(OnPropertyGroupSelected);
RemoveModifierCommand = new CaptionCommand<string>(Resources.RemoveModifier, OnRemoveModifier);
UpdateExtraPropertiesCommand = new CaptionCommand<string>(Resources.Update, OnUpdateExtraProperties);
UpdateFreeTagCommand = new CaptionCommand<string>(Resources.AddAndSave, OnUpdateFreeTag, CanUpdateFreeTag);
SelectedItemPortions = new ObservableCollection<MenuItemPortion>();
SelectedItemPropertyGroups = new ObservableCollection<MenuItemPropertyGroup>();
SelectedItemGroupedPropertyItems = new ObservableCollection<MenuItemGroupedPropertyViewModel>();
Reasons = new ObservableCollection<Reason>();
TicketTags = new ObservableCollection<TicketTag>();
EventServiceFactory.EventService.GetEvent<GenericEvent<TicketViewModel>>().Subscribe(OnTicketViewModelEvent);
}
private void OnTicketViewModelEvent(EventParameters<TicketViewModel> obj)
{
if (obj.Topic == EventTopicNames.SelectTicketTag)
{
ResetValues(obj.Value);
_showFreeTagEditor = SelectedTicket.LastSelectedTicketTag.FreeTagging;
List<TicketTag> tags;
if (_showFreeTagEditor)
{
tags = Dao.Query<TicketTagGroup>(x => x.Id == SelectedTicket.LastSelectedTicketTag.Id,
x => x.TicketTags).SelectMany(x => x.TicketTags).OrderBy(x => x.Name).ToList();
}
else
{
tags = AppServices.MainDataContext.SelectedDepartment.TicketTagGroups.Where(
x => x.Name == obj.Value.LastSelectedTicketTag.Name).SelectMany(x => x.TicketTags).ToList();
}
tags.Sort(new AlphanumComparator());
TicketTags.AddRange(tags);
if (SelectedTicket.IsTaggedWith(SelectedTicket.LastSelectedTicketTag.Name)) TicketTags.Add(TicketTag.Empty);
if (TicketTags.Count == 1 && !_showFreeTagEditor) obj.Value.UpdateTag(SelectedTicket.LastSelectedTicketTag, TicketTags[0]);
RaisePropertyChanged("TagColumnCount");
RaisePropertyChanged("IsFreeTagEditorVisible");
RaisePropertyChanged("FilteredTextBoxType");
}
if (obj.Topic == EventTopicNames.SelectVoidReason)
{
ResetValues(obj.Value);
Reasons.AddRange(AppServices.MainDataContext.Reasons.Values.Where(x => x.ReasonType == 0));
if (Reasons.Count == 0) obj.Value.VoidSelectedItems(0);
RaisePropertyChanged("ReasonColumnCount");
}
if (obj.Topic == EventTopicNames.SelectGiftReason)
{
ResetValues(obj.Value);
Reasons.AddRange(AppServices.MainDataContext.Reasons.Values.Where(x => x.ReasonType == 1));
if (Reasons.Count == 0) obj.Value.GiftSelectedItems(0);
RaisePropertyChanged("ReasonColumnCount");
}
if (obj.Topic == EventTopicNames.SelectExtraProperty)
{
ResetValues(obj.Value);
_showExtraPropertyEditor = true;
RaisePropertyChanged("IsExtraPropertyEditorVisible");
RaisePropertyChanged("IsPortionsVisible");
}
if (obj.Topic == EventTopicNames.EditTicketNote)
{
ResetValues(obj.Value);
_showTicketNoteEditor = true;
RaisePropertyChanged("IsTicketNoteEditorVisible");
}
}
private void ResetValues(TicketViewModel selectedTicket)
{
SelectedTicket = null;
SelectedItem = null;
SelectedItemPortions.Clear();
SelectedItemPropertyGroups.Clear();
SelectedItemGroupedPropertyItems.Clear();
Reasons.Clear();
TicketTags.Clear();
_showExtraPropertyEditor = false;
_showTicketNoteEditor = false;
_showFreeTagEditor = false;
_removeModifier = false;
SetSelectedTicket(selectedTicket);
}
public TicketViewModel SelectedTicket { get; private set; }
public TicketItemViewModel SelectedItem { get; private set; }
public ICaptionCommand CloseCommand { get; set; }
public ICaptionCommand RemoveModifierCommand { get; set; }
public ICaptionCommand UpdateExtraPropertiesCommand { get; set; }
public ICaptionCommand UpdateFreeTagCommand { get; set; }
public ICommand SelectReasonCommand { get; set; }
public ICommand SelectTicketTagCommand { get; set; }
public DelegateCommand<MenuItemPortion> PortionSelectedCommand { get; set; }
public ObservableCollection<MenuItemPortion> SelectedItemPortions { get; set; }
public DelegateCommand<MenuItemProperty> PropertySelectedCommand { get; set; }
public ObservableCollection<MenuItemPropertyGroup> SelectedItemPropertyGroups { get; set; }
public ObservableCollection<MenuItemGroupedPropertyViewModel> SelectedItemGroupedPropertyItems { get; set; }
public DelegateCommand<MenuItemGroupedPropertyItemViewModel> PropertyGroupSelectedCommand { get; set; }
public ObservableCollection<Reason> Reasons { get; set; }
public ObservableCollection<TicketTag> TicketTags { get; set; }
public int ReasonColumnCount { get { return Reasons.Count % 7 == 0 ? Reasons.Count / 7 : (Reasons.Count / 7) + 1; } }
public int TagColumnCount { get { return TicketTags.Count % 7 == 0 ? TicketTags.Count / 7 : (TicketTags.Count / 7) + 1; } }
public FilteredTextBox.FilteredTextBoxType FilteredTextBoxType
{
get
{
if (SelectedTicket != null && SelectedTicket.LastSelectedTicketTag != null && SelectedTicket.LastSelectedTicketTag.NumericTags)
return FilteredTextBox.FilteredTextBoxType.Digits;
if (SelectedTicket != null && SelectedTicket.LastSelectedTicketTag != null && SelectedTicket.LastSelectedTicketTag.PriceTags)
return FilteredTextBox.FilteredTextBoxType.Number;
return FilteredTextBox.FilteredTextBoxType.Letters;
}
}
private string _freeTag;
public string FreeTag
{
get { return _freeTag; }
set
{
_freeTag = value;
RaisePropertyChanged("FreeTag");
}
}
public bool IsPortionsVisible
{
get
{
return SelectedItem != null
&& Reasons.Count == 0
&& !SelectedItem.IsVoided
&& !SelectedItem.IsLocked
&& SelectedItemPortions.Count > 0;
}
}
public string RemoveModifierButtonColor { get { return _removeModifier ? "Red" : "Black"; } }
public bool IsRemoveModifierButtonVisible { get { return SelectedItem != null && SelectedItem.Properties.Count > 0; } }
private void OnRemoveModifier(string obj)
{
_removeModifier = !_removeModifier;
RaisePropertyChanged("RemoveModifierButtonColor");
}
private void OnCloseCommandExecuted(string obj)
{
var unselectedItem = SelectedItemPropertyGroups.FirstOrDefault(x => x.ForceValue && SelectedItem.Properties.Count(y => y.Model.PropertyGroupId == x.Id) == 0);
if (unselectedItem != null)
{
InteractionService.UserIntraction.GiveFeedback(string.Format(Resources.SelectionRequired_f, unselectedItem.Name));
return;
}
_showTicketNoteEditor = false;
_showExtraPropertyEditor = false;
_showFreeTagEditor = false;
_removeModifier = false;
FreeTag = string.Empty;
SelectedTicket.ClearSelectedItems();
}
public bool IsFreeTagEditorVisible { get { return _showFreeTagEditor; } }
public bool IsExtraPropertyEditorVisible { get { return _showExtraPropertyEditor && SelectedItem != null; } }
public bool IsTicketNoteEditorVisible { get { return _showTicketNoteEditor; } }
private bool CanUpdateFreeTag(string arg)
{
return !string.IsNullOrEmpty(FreeTag);
}
private void OnUpdateFreeTag(string obj)
{
var cachedTag = AppServices.MainDataContext.SelectedDepartment.TicketTagGroups.Single(
x => x.Id == SelectedTicket.LastSelectedTicketTag.Id);
Debug.Assert(cachedTag != null);
var ctag = cachedTag.TicketTags.SingleOrDefault(x => x.Name.ToLower() == FreeTag.ToLower());
if (ctag == null && cachedTag.SaveFreeTags)
{
using (var workspace = WorkspaceFactory.Create())
{
var tt = workspace.Single<TicketTagGroup>(x => x.Id == SelectedTicket.LastSelectedTicketTag.Id);
Debug.Assert(tt != null);
var tag = tt.TicketTags.SingleOrDefault(x => x.Name.ToLower() == FreeTag.ToLower());
if (tag == null)
{
tag = new TicketTag { Name = FreeTag };
tt.TicketTags.Add(tag);
workspace.Add(tag);
workspace.CommitChanges();
}
}
}
SelectedTicket.UpdateTag(SelectedTicket.LastSelectedTicketTag, new TicketTag { Name = FreeTag });
FreeTag = string.Empty;
}
private void OnUpdateExtraProperties(string obj)
{
SelectedTicket.RefreshVisuals();
_showExtraPropertyEditor = false;
RaisePropertyChanged("IsExtraPropertyEditorVisible");
}
private void OnTicketTagSelected(TicketTag obj)
{
SelectedTicket.UpdateTag(SelectedTicket.LastSelectedTicketTag, obj);
}
private void OnReasonSelected(int? reasonId)
{
var rid = reasonId.GetValueOrDefault(0);
Reason r = AppServices.MainDataContext.Reasons[rid];
if (r.ReasonType == 0)
SelectedTicket.VoidSelectedItems(rid);
if (r.ReasonType == 1)
SelectedTicket.GiftSelectedItems(rid);
}
private void OnPortionSelected(MenuItemPortion obj)
{
SelectedItem.UpdatePortion(obj, AppServices.MainDataContext.SelectedDepartment.PriceTag);
SelectedTicket.RefreshVisuals();
SelectedTicket.RecalculateTicket();
if (SelectedItemPropertyGroups.Count == 0 && SelectedItemGroupedPropertyItems.Count == 0)
SelectedTicket.ClearSelectedItems();
}
private void OnPropertySelected(MenuItemProperty obj)
{
var mig = SelectedItemPropertyGroups.FirstOrDefault(propertyGroup => propertyGroup.Properties.Contains(obj));
Debug.Assert(mig != null);
if (_removeModifier)
{
if (mig.ForceValue && SelectedItem.Properties.Count(x => x.Model.PropertyGroupId == mig.Id) < 2)
InteractionService.UserIntraction.GiveFeedback(string.Format(Resources.SelectionRequired_f, mig.Name));
else
SelectedItem.RemoveProperty(mig, obj);
}
else SelectedItem.ToggleProperty(mig, obj);
SelectedTicket.RefreshVisuals();
SelectedTicket.RecalculateTicket();
if (_removeModifier)
OnRemoveModifier("");
RaisePropertyChanged("IsRemoveModifierButtonVisible");
}
private void OnPropertyGroupSelected(MenuItemGroupedPropertyItemViewModel obj)
{
if (_removeModifier)
{
SelectedItem.RemoveProperty(obj.MenuItemPropertyGroup, obj.CurrentProperty);
obj.UpdateNextProperty(null);
}
else
{
SelectedItem.ToggleProperty(obj.MenuItemPropertyGroup, obj.NextProperty);
obj.UpdateNextProperty(obj.NextProperty);
}
SelectedTicket.RefreshVisuals();
SelectedTicket.RecalculateTicket();
if (_removeModifier)
OnRemoveModifier("");
RaisePropertyChanged("IsRemoveModifierButtonVisible");
}
private void SetSelectedTicket(TicketViewModel ticketViewModel)
{
SelectedTicket = ticketViewModel;
SelectedItem = SelectedTicket.SelectedItems.Count() == 1 ? SelectedTicket.SelectedItems[0] : null;
RaisePropertyChanged("SelectedTicket");
RaisePropertyChanged("SelectedItem");
RaisePropertyChanged("IsTicketNoteEditorVisible");
RaisePropertyChanged("IsExtraPropertyEditorVisible");
RaisePropertyChanged("IsFreeTagEditorVisible");
RaisePropertyChanged("IsPortionsVisible");
RaisePropertyChanged("IsRemoveModifierButtonVisible");
}
public bool ShouldDisplay(TicketViewModel value)
{
ResetValues(value);
if (SelectedItem == null || SelectedItem.Model.Locked) return false;
if (SelectedTicket != null && !SelectedItem.Model.Voided && !SelectedItem.Model.Locked)
{
var id = SelectedItem.Model.MenuItemId;
var mi = AppServices.DataAccessService.GetMenuItem(id);
if (SelectedItem.Model.PortionCount > 1) SelectedItemPortions.AddRange(mi.Portions);
SelectedItemPropertyGroups.AddRange(mi.PropertyGroups.Where(x => string.IsNullOrEmpty(x.GroupTag)));
SelectedItemGroupedPropertyItems.AddRange(mi.PropertyGroups.Where(x => !string.IsNullOrEmpty(x.GroupTag) && x.Properties.Count > 1)
.GroupBy(x => x.GroupTag)
.Select(x => new MenuItemGroupedPropertyViewModel(SelectedItem, x)));
RaisePropertyChanged("IsPortionsVisible");
}
return SelectedItemPortions.Count > 1 || SelectedItemPropertyGroups.Count > 0 || SelectedItemGroupedPropertyItems.Count > 0;
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.TicketModule/SelectedTicketItemsViewModel.cs | C# | gpl3 | 16,218 |
using System.ComponentModel.Composition;
using System.Windows;
using System.Windows.Controls;
using Samba.Domain.Models.Tickets;
using Samba.Presentation.Common;
namespace Samba.Modules.TicketModule
{
/// <summary>
/// Interaction logic for DepartmentButtonView.xaml
/// </summary>
[Export]
public partial class DepartmentButtonView : UserControl
{
[ImportingConstructor]
public DepartmentButtonView(TicketEditorViewModel viewModel)
{
InitializeComponent();
DataContext = viewModel;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
((TicketEditorViewModel)DataContext).TicketListViewModel.SelectedDepartment =
((Button)sender).DataContext as Department;
EventServiceFactory.EventService.PublishEvent(EventTopicNames.ActivateTicketView);
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.TicketModule/DepartmentButtonView.xaml.cs | C# | gpl3 | 942 |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using Samba.Infrastructure.Data.Serializer;
using Samba.Infrastructure.Settings;
using Serialization;
namespace Samba.Infrastructure.Data.Text
{
public class TextFileWorkspace : IWorkspace, IReadOnlyWorkspace
{
private DataStorage _storage = new DataStorage();
private readonly string _fileName;
private readonly bool _asyncSave;
public TextFileWorkspace()
: this(GetDefaultDbFileName(), true)
{
}
private static string GetDefaultDbFileName()
{
return Path.GetDirectoryName(Assembly.GetCallingAssembly().Location) + "\\SambaDB.txt";
}
public TextFileWorkspace(string fileName, bool asyncSave)
{
_fileName = fileName;
_asyncSave = asyncSave;
ReloadAll();
}
private int _tNumber;
[MethodImpl(MethodImplOptions.Synchronized)]
private void PersistAllAsync(object o)
{
LocalSettings.UpdateThreadLanguage();
if (!string.IsNullOrEmpty(o.ToString()) && (int)o != _tNumber) return;
var data = SilverlightSerializer.Serialize(_storage);
File.WriteAllBytes(_fileName, data);
}
public void CommitChanges()
{
if (_asyncSave)
{
_tNumber = new Random(DateTime.Now.Millisecond).Next();
ThreadPool.QueueUserWorkItem(PersistAllAsync, _tNumber);
}
else
PersistAllAsync("");
}
public void Delete<T>(Expression<Func<T, bool>> expression) where T : class
{
foreach (var item in All(expression))
{
Delete(item);
}
}
public void Delete<T>(T item) where T : class
{
var idf = item as IEntity;
if (idf != null)
_storage.Delete<T>(idf.Id);
}
public void DeleteAll<T>() where T : class
{
foreach (var item in All<T>())
{
Delete(item);
}
}
public T Single<T>(Expression<Func<T, bool>> expression) where T : class
{
return _storage.GetItems(expression).FirstOrDefault();
}
public T Last<T>() where T : class,IEntity
{
return _storage.GetItems<T>().LastOrDefault();
}
public IEnumerable<T> All<T>() where T : class
{
return _storage.GetItems<T>();
}
public IEnumerable<T> All<T>(params Expression<Func<T, object>>[] includes) where T : class
{
return _storage.GetItems<T>();
}
public IEnumerable<T> All<T>(Expression<Func<T, bool>> expression) where T : class
{
return _storage.GetItems(expression);
}
public void Add<T>(T item) where T : class
{
_storage.Add(item);
}
public void Add<T>(IEnumerable<T> items) where T : class
{
foreach (var item in items)
{
_storage.Add(item);
}
}
public void Update<T>(T item) where T : class
{
_storage.Update(item);
}
public int Count<T>() where T : class
{
return _storage.GetItems<T>().Count();
}
public void ReloadAll()
{
if (File.Exists(_fileName))
{
try
{
var data = File.ReadAllBytes(_fileName);
_storage = SilverlightSerializer.Deserialize(data) as DataStorage;
}
catch (Exception)
{
_storage = new DataStorage();
}
}
}
public void ResetDatabase()
{
_storage.Clear();
File.Delete(_fileName);
}
public void Refresh(IEnumerable collection)
{
// gerekmiyor...
}
public void Refresh(object item)
{
//gerekmiyor...
}
public void Refresh(object item, string property)
{
//gerekmiyor...
}
public T SingleUc<T>(Expression<Func<T, bool>> expression) where T : class
{
return Single(expression);
}
public IEnumerable<T> Query<T>(params string[] includes) where T : class
{
return All<T>();
}
public void Dispose()
{
// gerekmiyor...
}
public IEnumerable<T> Query<T>(Expression<Func<T, bool>> predictate, params Expression<Func<T, object>>[] includes) where T : class
{
if (predictate != null)
return All(predictate);
return All<T>();
}
public IEnumerable<string> Distinct<T>(Expression<Func<T, string>> expression) where T : class
{
return _storage.GetItems<T>().Select(expression.Compile()).Distinct().Where(x => !string.IsNullOrEmpty(x)).ToList();
}
public TResult Single<TSource, TResult>(int id, Expression<Func<TSource, TResult>> expression) where TSource : class, IEntity
{
return _storage.GetItems<TSource>().Where(x => x.Id == id).Select(expression.Compile()).SingleOrDefault();
}
public T Single<T>(Expression<Func<T, bool>> expression, string[] includes) where T : class
{
return Single(expression);
}
public T Single<T>(Expression<Func<T, bool>> predictate, params Expression<Func<T, object>>[] includes) where T : class
{
return Single(predictate);
}
public IEnumerable<TResult> Select<TSource, TResult>(Expression<Func<TSource, TResult>> expression, Expression<Func<TSource, bool>> prediction) where TSource : class
{
if (prediction != null)
return _storage.GetItems<TSource>().Where(prediction.Compile()).Select(expression.Compile());
return _storage.GetItems<TSource>().Select(expression.Compile());
}
public int Count<T>(Expression<Func<T, bool>> predictate) where T : class
{
if (predictate != null)
return _storage.GetItems<T>().Count(predictate.Compile());
return _storage.GetItems<T>().Count();
}
public decimal Sum<T>(Expression<Func<T, decimal>> selector, Expression<Func<T, bool>> predictate) where T : class
{
if (predictate != null)
return _storage.GetItems<T>().Where(predictate.Compile()).Sum(selector.Compile());
return _storage.GetItems<T>().Sum(selector.Compile());
}
public T Last<T>(Expression<Func<T, bool>> predictate, Expression<Func<T, object>>[] includes) where T : class,IEntity
{
return _storage.GetItems<T>().Last(predictate.Compile());
}
public IEnumerable<T> Last<T>(int recordCount) where T : class,IEntity
{
var coll = _storage.GetItems<T>().AsQueryable();
var count = coll.Count();
return count > recordCount ? coll.Skip(count - recordCount).Take(recordCount) : coll;
}
public IQueryable<T> Queryable<T>() where T : class
{
return _storage.GetItems<T>().AsQueryable();
}
}
}
| zzgaminginc-pointofssale | Samba.Infrastructure.Data/Text/TextFileWorkspace.cs | C# | gpl3 | 7,912 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace Samba.Infrastructure.Data.Text
{
public class DataStorage
{
public Dictionary<string, Dictionary<int, object>> Items { get; set; }
public Dictionary<string, int> Identities { get; set; }
public DataStorage()
{
Items = new Dictionary<string, Dictionary<int, object>>();
Identities = new Dictionary<string, int>();
}
internal bool ContainsKey(Type key)
{
return Items.ContainsKey(key.FullName);
}
internal Dictionary<int, object> GetDataList(Type key)
{
if (!Items.ContainsKey(key.FullName))
{
var subList = new Dictionary<int, object>();
Items.Add(key.FullName, subList);
}
return Items[key.FullName];
}
internal void Clear()
{
Items.Clear();
Identities.Clear();
}
internal T GetById<T>(int id)
{
Dictionary<int, object> list = GetDataList(typeof(T));
if (list.ContainsKey(id)) return (T)list[id];
return default(T);
}
internal IEnumerable<T> GetItems<T>()
{
Dictionary<int, object> list = GetDataList(typeof(T));
return list.Values.Cast<T>();
}
internal void Delete<T>(int id)
{
Dictionary<int, object> list = GetDataList(typeof(T));
list.Remove(id);
}
internal int CreateIdNumber(Type type)
{
lock (Identities)
{
if (!Identities.ContainsKey(type.FullName))
Identities.Add(type.FullName, 0);
Identities[type.FullName]++;
return Identities[type.FullName];
}
}
internal void Add(object o)
{
var list = GetDataList(o.GetType());
var idt = o as IEntity;
if (idt != null)
{
if (idt.Id == 0) idt.Id = CreateIdNumber(idt.GetType());
list.Add(idt.Id, idt);
}
else
{
if (list.ContainsKey(0)) Update(o);
else list.Add(0, o);
}
}
internal void Update(object o)
{
var list = GetDataList(o.GetType());
var idt = o as IEntity;
if (idt != null)
{
if (idt.Id == 0)
{
Add(idt);
return;
}
if (list.ContainsKey(idt.Id))
list[idt.Id] = idt;
}
else if (list.ContainsKey(0))
{
list[0] = o;
}
else list.Add(0, o);
}
internal IList<T> GetItems<T>(Expression<Func<T, bool>> predicate)
{
return GetDataList(typeof(T)).Values.Cast<T>().Where(predicate.Compile()).ToList();
}
}
} | zzgaminginc-pointofssale | Samba.Infrastructure.Data/Text/DataStorage.cs | C# | gpl3 | 3,229 |
// -----------------------------------------------------------------------------------
// Use it as you please, but keep this header.
// Author : Marcus Deecke, 2006
// Web : www.yaowi.com
// Email : code@yaowi.com
// -----------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.IO;
using System.Collections;
using System.Runtime.CompilerServices;
namespace Samba.Infrastructure.Data.Serializer
{
/// <summary>
/// This struct supports the Yaowi Framework infrastructure and is not intended to be used directly from your code.
/// <P>This struct records relevant object information.
/// </summary>
/// <remarks>
/// Strings in a struct? Strings are reference types and structs should not contain types like this. TODO!
/// </remarks>
internal struct ObjectInfo
{
// Members
public string Name;
public string Type;
public string Assembly;
public string Value;
// public bool HasBinaryConstructor;
public string ConstructorParamType;
public string ConstructorParamAssembly;
/// <summary>
/// ToString()
/// </summary>
/// <returns></returns>
public override string ToString()
{
string n = Name;
if (String.IsNullOrEmpty(n))
n = "<Name not set>";
string t = Type;
if (String.IsNullOrEmpty(t))
t = "<Type not set>";
string a = Type;
if (String.IsNullOrEmpty(a))
a = "<Assembly not set>";
return n + "; " + t + "; " + a;
}
/// <summary>
/// Determines whether the values are sufficient to create an instance.
/// </summary>
/// <returns></returns>
public bool IsSufficient
{
get
{
// Type and Assembly should be enough
if (String.IsNullOrEmpty(Type) || String.IsNullOrEmpty(Assembly))
return false;
return true;
}
}
}
/// <summary>
/// Helper class storing a Types creation information as well as providing various static methods
/// returning information about types.
/// </summary>
[Serializable]
public class TypeInfo
{
#region Members & Properties
private string typename = null;
private string assemblyname = null;
/// <summary>
/// Gets or sets the Types name.
/// </summary>
public string TypeName
{
get { return typename; }
set { typename = value; }
}
/// <summary>
/// Gets or sets the Assemblys name.
/// </summary>
public string AssemblyName
{
get { return assemblyname; }
set { assemblyname = value; }
}
#endregion Members & Properties
#region Constructors
/// <summary>
/// Constructor.
/// </summary>
public TypeInfo()
{
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="obj"></param>
public TypeInfo(object obj)
{
if (obj == null)
return;
TypeName = obj.GetType().FullName;
AssemblyName = obj.GetType().Assembly.FullName;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="type"></param>
public TypeInfo(Type type)
{
if (type == null)
return;
TypeName = type.FullName;
AssemblyName = type.Assembly.FullName;
}
#endregion Constructors
#region static Helpers
/// <summary>
/// Determines whether a Type is a Collection type.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.Synchronized)]
public static bool IsCollection(Type type)
{
if (typeof(ICollection).IsAssignableFrom(type))
{
return true;
}
return false;
}
/// <summary>
/// Determines whether a Type is a Dictionary type.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.Synchronized)]
public static bool IsDictionary(Type type)
{
if (typeof(IDictionary).IsAssignableFrom(type))
{
return true;
}
return false;
}
/// <summary>
/// Determines whether a Type is a List type.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.Synchronized)]
public static bool IsList(Type type)
{
if (typeof(IList).IsAssignableFrom(type))
{
return true;
}
return false;
}
/// <summary>
/// Determines whether the typename describes an array.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.Synchronized)]
public static bool IsArray(String type)
{
// type.HasElementType
// The simple way
if (type != null && type.EndsWith("[]"))
return true;
return false;
}
/// <summary>
/// Determines whether the Type has a binary constructor.<p>
/// This is seen as an indication that this is binary data.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.Synchronized)]
public static bool HasBinaryConstructor(Type type)
{
ConstructorInfo[] cia = type.GetConstructors();
for (int i = 0; i < cia.Length; i++)
{
ParameterInfo[] pai = cia[i].GetParameters();
if (pai.Length == 1)
{
if (typeof(Stream).IsAssignableFrom(pai[0].ParameterType) ||
typeof(byte[]).IsAssignableFrom(pai[0].ParameterType))
{
return true;
}
}
}
return false;
}
/// <summary>
/// Returns the <code>Type</code> of the constructor with exact one parameter which is
/// either a <code>byte[]</code> or a <code>Stream</code>.<br>
/// A a non-null returnvalue is also an inducator, that the given <code>Type</code>
/// has a constructor with a binary parameter.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.Synchronized)]
public static Type GetBinaryConstructorType(Type type)
{
ConstructorInfo[] cia = type.GetConstructors();
for (int i = 0; i < cia.Length; i++)
{
ParameterInfo[] pai = cia[i].GetParameters();
if (pai.Length == 1)
{
if (typeof(byte[]).IsAssignableFrom(pai[0].ParameterType))
{
return typeof(byte[]);
}
else if (typeof(Stream).IsAssignableFrom(pai[0].ParameterType))
{
return typeof(Stream);
}
}
}
return null;
}
/// <summary>
/// Returns whether the specified <code>Type</code> has a constructor with exact
/// one parameter of <code>byte[]</code>.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.Synchronized)]
public static bool HasByteArrayConstructor(Type type)
{
ConstructorInfo[] cia = type.GetConstructors();
for (int i = 0; i < cia.Length; i++)
{
ParameterInfo[] pai = cia[i].GetParameters();
if(pai.Length == 1)
{
if (typeof(byte[]).IsAssignableFrom(pai[0].ParameterType))
{
return true;
}
}
}
return false;
}
/// <summary>
/// Returns whether the specified <code>Type</code> has a constructor with exact
/// one parameter of <code>Stream</code>.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.Synchronized)]
public static bool HasStreamConstructor(Type type)
{
ConstructorInfo[] cia = type.GetConstructors();
for (int i = 0; i < cia.Length; i++)
{
ParameterInfo[] pai = cia[i].GetParameters();
if (pai.Length == 1)
{
if (typeof(Stream).IsAssignableFrom(pai[0].ParameterType))
{
return true;
}
}
}
return false;
}
#endregion static Helpers
}
}
| zzgaminginc-pointofssale | Samba.Infrastructure.Data/Serializer/XmlSerializationHelpers.cs | C# | gpl3 | 8,439 |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
namespace Samba.Infrastructure.Data.Serializer
{
public static class PropertyComparor
{
public static void ExtractEntities(object item, IDictionary<Type, Dictionary<int, IEntity>> types)
{
var itemName = item.GetType().Name;
if (itemName.Contains("_")) itemName = itemName.Substring(0, itemName.IndexOf("_"));
var properties = item.GetType().GetProperties();
foreach (var property in properties)
{
var value = property.GetValue(item, null);
if (value is IEntity && value.GetType().GetProperty(itemName + "Id") == null)
{
AddEntity(value as IEntity, types);
}
else if (value is IList)
{
var list = value as IList;
Debug.Assert(list != null);
foreach (var listItem in list)
{
if (listItem is IEntity && listItem.GetType().GetProperty(itemName + "Id") == null)
AddEntity(listItem as IEntity, types);
else
{
ExtractEntities(listItem, types);
}
}
}
}
}
private static void AddEntity(IEntity entity, IDictionary<Type, Dictionary<int, IEntity>> types)
{
Debug.Assert(entity != null);
if (!types.ContainsKey(entity.GetType()))
{
types.Add(entity.GetType(), new Dictionary<int, IEntity>());
}
if (!types[entity.GetType()].ContainsKey(entity.Id))
{
types[entity.GetType()].Add(entity.Id, entity);
}
}
public static bool AreEquals(object actual, object expected)
{
try
{
if (!expected.GetType().IsClass) return actual.Equals(expected);
if (expected is string) return actual.ToString() == expected.ToString();
var properties = expected.GetType().GetProperties();
foreach (var property in properties)
{
if (property.GetSetMethod() == null)
continue;
var expectedValue = property.GetValue(expected, null);
var actualValue = property.GetValue(actual, null);
if (actualValue == null) if (expectedValue != null) return false;
if (expectedValue == null) if (actualValue != null) return false;
if (expectedValue == null) continue;
if (actualValue is IList)
{
if (!AssertListsAreEquals((IList)actualValue, (IList)expectedValue))
return false;
}
else if (actualValue.GetType().IsClass)
{
if (AreEquals(actualValue, expectedValue) == false)
return false;
}
else if (!Equals(expectedValue, actualValue))
return false;
}
return true;
}
catch (TargetException)
{
return false;
}
}
private static bool AssertListsAreEquals(ICollection actualList, IList expectedList)
{
if (actualList == null) throw new ArgumentNullException("actualList");
if (actualList.Count != expectedList.Count) return false;
return !actualList.Cast<object>().Where((t, i) => !AreEquals(t, expectedList[i])).Any();
}
public static void ResetIds(object item)
{
var itemName = item.GetType().Name;
if (itemName.Contains("_")) itemName = itemName.Substring(0, itemName.IndexOf("_"));
var properties = item.GetType().GetProperties();
foreach (var property in properties)
{
var value = property.GetValue(item, null);
if (value != null && value.GetType().GetProperty("Id") != null && value.GetType().GetProperty(itemName + "Id") != null)
{
value.GetType().GetProperty("Id").SetValue(value, 0, null);
}
else if (value is IList)
{
var list = value as IList;
Debug.Assert(list != null);
foreach (var listItem in list)
{
if (listItem.GetType().GetProperty("Id") != null && listItem.GetType().GetProperty(itemName + "Id") != null)
listItem.GetType().GetProperty("Id").SetValue(listItem, 0, null);
ResetIds(listItem);
}
}
}
}
}
}
| zzgaminginc-pointofssale | Samba.Infrastructure.Data/Serializer/PropertyComparor.cs | C# | gpl3 | 5,288 |
// -----------------------------------------------------------------------------------
// Use it as you please, but keep this header.
// Author : Marcus Deecke, 2006
// Web : www.yaowi.com
// Email : code@yaowi.com
// -----------------------------------------------------------------------------------
using System;
using System.Diagnostics.Contracts;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Xml;
namespace Samba.Infrastructure.Data.Serializer
{
/// <summary>
/// Deserializes complex objects serialized with the XmlSerializer.
/// </summary>
public class XmlDeserializerHelper : IDisposable
{
private bool ignorecreationerrors = false;
private Hashtable typedictionary = new Hashtable(); // Parsed Types
private Dictionary<string, Assembly> assemblycache = new Dictionary<string, Assembly>(); // Found Assemblies
private Dictionary<string, Assembly> assemblyregister = new Dictionary<string, Assembly>(); // Predefined Assemblies
private Dictionary<Type, TypeConverter> typeConverterCache = new Dictionary<Type, TypeConverter>(); // used TypeConverters
private Dictionary<Type, Dictionary<int, IEntity>> identifyibleCache = new Dictionary<Type, Dictionary<int, IEntity>>();
private IXmlSerializationTag taglib = new XmlSerializationTag();
public IXmlSerializationTag TagLib
{
get { return taglib; }
set { taglib = value; }
}
#region XmlDeserializer Properties
/// <summary>
/// Gets whether the current root node provides a type dictionary.
/// </summary>
protected bool HasTypeDictionary
{
get
{
if (typedictionary != null && typedictionary.Count > 0)
return true;
return false;
}
}
/// <summary>
/// Gets or sets whether creation errors shall be ignored.
/// <br>Creation errors can occur if e.g. a type has no parameterless constructor
/// and an instance cannot be instantiated from String.
/// </summary>
[Description("Gets or sets whether creation errors shall be ignored.")]
public bool IgnoreCreationErrors
{
get { return ignorecreationerrors; }
set { ignorecreationerrors = value; }
}
#endregion XmlDeserializer Properties
#region Deserialize
/// <summary>
/// Deserialzes an object from a xml file.
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public object Deserialize(string filename)
{
XmlDocument doc = new XmlDocument();
doc.Load(filename);
return Deserialize(doc);
}
public object Deserialize(XmlDocument document)
{
XmlNode node = document.SelectSingleNode(taglib.OBJECT_TAG);
return Deserialize(node);
}
public object Deserialize(XmlDocument document, Dictionary<Type, Dictionary<int, IEntity>> cache)
{
identifyibleCache = cache;
XmlNode node = document.SelectSingleNode(taglib.OBJECT_TAG);
return Deserialize(node);
}
/// <summary>
/// Deserializes an Object from the specified XmlNode.
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
public object Deserialize(XmlNode node)
{
// Clear previous collections
Reset();
AddAssemblyRegisterToCache();
XmlNode rootnode = node;
if (!rootnode.Name.Equals(taglib.OBJECT_TAG))
{
rootnode = node.SelectSingleNode(taglib.OBJECT_TAG);
if (rootnode == null)
{
throw new ArgumentException("Invalid node. The specified node or its direct children do not contain a " + taglib.OBJECT_TAG + " tag.", "XmlNode node");
}
}
// Load TypeDictionary
this.typedictionary = ParseTypeDictionary(rootnode);
// Get the Object
object obj = GetObject(rootnode);
if (obj != null)
{
obj = GetProperties(obj, rootnode);
}
else
Console.WriteLine("Object is null");
return obj;
}
/// <summary>
/// Parses the TypeDictionary (if given).
/// </summary>
/// <param name="parentNode"></param>
/// <returns></returns>
/// <remarks>
/// The TypeDictionary is Hashtable in which TypeInfo items are stored.
/// </remarks>
protected Hashtable ParseTypeDictionary(XmlNode parentNode)
{
Hashtable dict = new Hashtable();
XmlNode dictNode = parentNode.SelectSingleNode(taglib.TYPE_DICTIONARY_TAG);
if (dictNode == null)
return dict;
object obj = GetObject(dictNode);
if (obj != null && typeof(Hashtable).IsAssignableFrom(obj.GetType()))
{
dict = (Hashtable)obj;
GetProperties(dict, dictNode);
}
return dict;
}
#endregion Deserialize
#region Properties & values
/// <summary>
/// Reads the properties of the specified node and sets them an the parent object.
/// </summary>
/// <param name="parent"></param>
/// <param name="node"></param>
/// <remarks>
/// This is the central method which is called recursivly!
/// </remarks>
protected object GetProperties(object parent, XmlNode node)
{
if (parent == null)
return parent;
// Get the properties
XmlNodeList nl = node.SelectNodes(taglib.PROPERTIES_TAG + "/" + taglib.PROPERTY_TAG);
// Properties found?
if (nl == null || nl.Count == 0)
{
// No properties found... perhaps a collection?
if (TypeInfo.IsCollection(parent.GetType()))
{
SetCollectionValues((ICollection)parent, node);
}
else
{
// Nothing to do here
return parent;
}
}
// Loop the properties found
foreach (XmlNode prop in nl)
{
// Collect the nodes type information about the property to deserialize
ObjectInfo oi = GetObjectInfo(prop);
// Enough info?
if (oi.IsSufficient && !String.IsNullOrEmpty(oi.Name))
{
object obj = null;
// Create an instance, but note: arrays always need the size for instantiation
if (TypeInfo.IsArray(oi.Type))
{
int c = GetArrayLength(prop);
obj = CreateArrayInstance(oi, c);
}
else
{
obj = CreateInstance(oi);
}
// Process the property's properties (recursive call of this method)
if (obj != null)
{
obj = GetProperties(obj, prop);
}
// Setting the instance (or null) as the property's value
PropertyInfo pi = parent.GetType().GetProperty(oi.Name);
if (obj != null && pi != null)
{
pi.SetValue(parent, obj, null);
}
}
}
var identifyible = parent as IEntity;
if (identifyible != null)
{
var list = GetIdentifyibleTypeList(identifyible.GetType());
if (!list.ContainsKey(identifyible.Id))
{
list.Add(identifyible.Id, identifyible);
return list[identifyible.Id];
}
return list[identifyible.Id];
}
return parent;
}
private Dictionary<int, IEntity> GetIdentifyibleTypeList(Type type)
{
if (!identifyibleCache.ContainsKey(type))
identifyibleCache.Add(type, new Dictionary<int, IEntity>());
return identifyibleCache[type];
}
#region Collections
/// <summary>
/// Sets the entries on an ICollection implementation.
/// </summary>
/// <param name="coll"></param>
/// <param name="parentNode"></param>
protected void SetCollectionValues(ICollection coll, XmlNode parentNode)
{
if (typeof(IDictionary).IsAssignableFrom(coll.GetType()))
{
// IDictionary
SetDictionaryValues((IDictionary)coll, parentNode);
return;
}
else if (typeof(IList).IsAssignableFrom(coll.GetType()))
{
// IList
SetListValues((IList)coll, parentNode);
return;
}
}
/// <summary>
/// Sets the entries on an IList implementation.
/// </summary>
/// <param name="list"></param>
/// <param name="parentNode"></param>
protected void SetListValues(IList list, XmlNode parentNode)
{
// Get the item nodes
XmlNodeList nlitems = parentNode.SelectNodes(taglib.ITEMS_TAG + "/" + taglib.ITEM_TAG);
// Loop them
for (int i = 0; i < nlitems.Count; i++)
{
XmlNode nodeitem = nlitems[i];
// Create an instance
object obj = GetObject(nodeitem);
// Process the properties
obj = GetProperties(obj, nodeitem);
if (list.IsFixedSize)
list[i] = obj;
else
list.Add(obj);
}
}
/// <summary>
/// Sets the entries of an IDictionary implementation.
/// </summary>
/// <param name="coll"></param>
/// <param name="parentNode"></param>
protected void SetDictionaryValues(IDictionary dictionary, XmlNode parentNode)
{
// Get the item nodes
XmlNodeList nlitems = parentNode.SelectNodes(taglib.ITEMS_TAG + "/" + taglib.ITEM_TAG);
// Loop them
for (int i = 0; i < nlitems.Count; i++)
{
XmlNode nodeitem = nlitems[i];
// Retrieve the single property
string path = taglib.PROPERTIES_TAG + "/" + taglib.PROPERTY_TAG + "[@" + taglib.NAME_TAG + "='" + taglib.NAME_ATT_KEY_TAG + "']";
XmlNode nodekey = nodeitem.SelectSingleNode(path);
path = taglib.PROPERTIES_TAG + "/" + taglib.PROPERTY_TAG + "[@" + taglib.NAME_TAG + "='" + taglib.NAME_ATT_VALUE_TAG + "']";
XmlNode nodeval = nodeitem.SelectSingleNode(path);
// Create an instance of the key
object objkey = GetObject(nodekey);
object objval = null;
// Try to get the value
if (nodeval != null)
{
objval = GetObject(nodeval);
}
// Set the entry if the key is not null
if (objkey != null)
{
// Set the entry's value if its is not null and process its properties
if (objval != null)
objval = GetProperties(objval, nodeval);
dictionary.Add(objkey, objval);
}
}
}
#endregion Collections
#endregion Properties & values
#region Creating instances and types
/// <summary>
/// Creates an instance by the contents of the given XmlNode.
/// </summary>
/// <param name="node"></param>
protected object GetObject(XmlNode node)
{
ObjectInfo oi = GetObjectInfo(node);
if (TypeInfo.IsArray(oi.Type))
{
int c = GetArrayLength(node);
return CreateArrayInstance(oi, c);
}
return CreateInstance(oi);
}
/// <summary>
///
/// </summary>
/// <param name="assembly"></param>
/// <returns></returns>
protected Assembly GetAssembly(String assembly)
{
Assembly a = null;
// Cached already?
if (assemblycache.ContainsKey(assembly))
{
return (Assembly)assemblycache[assembly];
}
// Shortnamed, version independent assembly name
int x = assembly.IndexOf(",");
string ass = null;
if (x > 0)
ass = assembly.Substring(0, x);
// Cached already?
if (ass != null && assemblycache.ContainsKey(ass))
{
return (Assembly)assemblycache[ass];
}
// Try to get the Type in any way
try
{
String path = Path.GetDirectoryName(assembly);
if (!String.IsNullOrEmpty(path))
{
// Assembly cached already?
if (assemblycache.ContainsKey(assembly))
{
// Cached
a = (Assembly)assemblycache[assembly];
}
else
{
// Not cached, yet
a = Assembly.LoadFrom(path);
assemblycache.Add(assembly, a);
}
}
else
{
try
{
// Try to load the assembly version independent
if (ass != null)
{
// Assembly cached already?
if (assemblycache.ContainsKey(ass))
{
// Cached
a = (Assembly)assemblycache[ass];
}
else
{
// Not cached, yet
a = Assembly.Load(ass);
assemblycache.Add(ass, a);
}
}
else
{
// Assembly cached already?
if (assemblycache.ContainsKey(assembly))
{
// Cached
a = (Assembly)assemblycache[assembly];
}
else
{
// Not cached, yet
a = Assembly.Load(assembly);
assemblycache.Add(assembly, a);
}
}
}
catch
{
// Loading the assembly version independent failed: load it with the given version.
if (assemblycache.ContainsKey(assembly))
{
// Cached
a = (Assembly)assemblycache[assembly];
}
else
{
// Not cached, yet
a = Assembly.Load(assembly);
assemblycache.Add(assembly, a);
}
}
}
}
catch { /* ok, we did not get the Assembly */ }
return a;
}
/// <summary>
/// Creates a type from the specified assembly and type names included in the TypeInfo parameter.
/// <b>In case of failure null will be returned.
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
protected Type CreateType(TypeInfo info)
{
return CreateType(info.AssemblyName, info.TypeName);
}
/// <summary>
/// Creates a type from the specified assembly and type names.
/// <b>In case of failure null will be returned.
/// </summary>
/// <param name="assembly"></param>
/// <param name="type"></param>
/// <returns></returns>
protected Type CreateType(String assembly, string type)
{
Type t = null;
try
{
Assembly a = GetAssembly(assembly);
if (a != null)
{
t = a.GetType(type);
}
}
catch { /* ok, we did not get the Type */ }
return t;
}
/// <summary>
/// Creates an instance of an Array by the specified ObjectInfo.
/// </summary>
/// <param name="info"></param>
/// <param name="length"></param>
/// <returns></returns>
private Array CreateArrayInstance(ObjectInfo info, int length)
{
Contract.Requires(0 <= info.Type.Length - 2);
Contract.Requires(length >= 0);
// The Type name of an array ends with "[]"
// Exclude this to get the real Type
string typename = info.Type.Substring(0, info.Type.Length - 2);
Type t = CreateType(info.Assembly, typename);
Array arr = Array.CreateInstance(t, length);
return arr;
}
/// <summary>
/// Creates an instance by the specified ObjectInfo.
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
private object CreateInstance(ObjectInfo info)
{
try
{
// Enough information to create an instance?
if (!info.IsSufficient)
return null;
object obj = null;
// Get the Type
Type type = CreateType(info.Assembly, info.Type);
if (type == null)
{
throw new Exception("Assembly or Type not found.");
}
// Ok, we've got the Type, now try to create an instance.
// Is there a binary constructor?
if (!String.IsNullOrEmpty(info.ConstructorParamType))
{
Object ctorparam = null;
byte[] barr = null;
if (!String.IsNullOrEmpty(info.Value))
{
barr = System.Convert.FromBase64String(info.Value);
Type ctorparamtype = CreateType(info.ConstructorParamAssembly, info.ConstructorParamType);
// What type of parameter is needed?
if (typeof(Stream).IsAssignableFrom(ctorparamtype))
{
// Stream
ctorparam = new MemoryStream(barr);
}
else if (typeof(byte[]).IsAssignableFrom(ctorparamtype))
{
// byte[]
ctorparam = barr;
}
}
obj = Activator.CreateInstance(type, new object[] { ctorparam });
return obj;
}
// Until now only properties with binary data support constructors with parameters
// Problem: only parameterless constructors or constructors with one parameter
// which can be converted from String are supported.
// Failure Example:
// string s = new string();
// string s = new string("");
// This cannot be compiled, but the follwing works;
// string s = new string("".ToCharArray());
// The TypeConverter provides a way to instantite objects by non-parameterless
// constructors if they can be converted fro String
try
{
TypeConverter tc = GetConverter(type);
if (tc.CanConvertFrom(typeof(string)))
{
obj = tc.ConvertFrom(info.Value);
return obj;
}
}
catch { ; }
obj = Activator.CreateInstance(type);
if (obj == null)
throw new Exception("Instance could not be created.");
return obj;
}
catch (Exception e)
{
string msg = "Creation of an instance failed. Type: " + info.Type + " Assembly: " + info.Assembly + " Cause: " + e.Message;
if (IgnoreCreationErrors)
{
return null;
}
else
throw new Exception(msg, e);
}
}
#endregion Creating instances and types
#region Misc
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
private TypeInfo TranslateTypeByKey(String key)
{
Contract.Requires(key != null);
if (HasTypeDictionary)
{
if (this.typedictionary.ContainsKey(key))
{
TypeInfo ti = (TypeInfo)this.typedictionary[key];
return ti;
}
}
return null;
}
/// <summary>
/// Gets an ObjectInfo instance by the attributes of the specified XmlNode.
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
private ObjectInfo GetObjectInfo(XmlNode node)
{
ObjectInfo oi = new ObjectInfo();
String typekey = GetAttributeValue(node, taglib.TYPE_TAG);
TypeInfo ti = TranslateTypeByKey(typekey);
if (ti != null)
{
oi.Type = ti.TypeName;
oi.Assembly = ti.AssemblyName;
}
// If a TypeDictionary is given, did we find the necessary information to create an instance?
// If not, try to get information by the Node itself
if (!oi.IsSufficient)
{
oi.Type = GetAttributeValue(node, taglib.TYPE_TAG);
oi.Assembly = GetAttributeValue(node, taglib.ASSEMBLY_TAG);
}
// Name and Value
oi.Name = GetAttributeValue(node, taglib.NAME_TAG);
oi.Value = node.InnerText;
// Binary Constructor
ti = GetBinaryConstructorType(node);
if (ti != null)
{
// Binary constructor info given
oi.ConstructorParamType = ti.TypeName;
oi.ConstructorParamAssembly = ti.AssemblyName;
// Make sure to read the value from the binary data Node (setting oi.Value = node.InnerText as above is a bit dirty)
XmlNode datanode = node.SelectSingleNode(taglib.BINARY_DATA_TAG);
if (datanode != null)
{
oi.Value = datanode.InnerText;
}
else
{
datanode = node.SelectSingleNode(taglib.CONSTRUCTOR_TAG);
if (datanode != null)
{
datanode = datanode.SelectSingleNode(taglib.BINARY_DATA_TAG);
if (datanode != null)
{
oi.Value = datanode.InnerText;
}
}
}
}
return oi;
}
/// <summary>
/// Returns the length of the array of a arry-XmlNode.
/// </summary>
/// <param name="parent"></param>
/// <returns></returns>
protected int GetArrayLength(XmlNode parent)
{
XmlNodeList nl = parent.SelectNodes(taglib.ITEMS_TAG + "/" + taglib.ITEM_TAG);
int c = 0;
if (nl != null)
c = nl.Count;
return c;
}
/// <summary>
/// Returns the value or the attribute with the specified name from the given node if it is not null or empty.
/// </summary>
/// <param name="node"></param>
/// <param name="name"></param>
/// <returns></returns>
protected string GetAttributeValue(XmlNode node, string name)
{
if (node == null || String.IsNullOrEmpty(name))
return null;
String val = null;
XmlAttribute att = node.Attributes[name];
if (att != null)
{
val = att.Value;
if (val.Equals(""))
val = null;
}
return val;
}
/// <summary>
///
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
protected TypeInfo GetBinaryConstructorType(XmlNode node)
{
if (node == null)
return null;
XmlNode ctornode = node.SelectSingleNode(taglib.CONSTRUCTOR_TAG);
if (ctornode == null)
return null;
String typekey = GetAttributeValue(ctornode, taglib.TYPE_TAG);
TypeInfo ti = TranslateTypeByKey(typekey);
return ti;
}
/// <summary>
///
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
protected bool HasBinaryConstructor(XmlNode node)
{
if (node == null)
return false;
XmlNode ctornode = node.SelectSingleNode(taglib.CONSTRUCTOR_TAG);
if (ctornode == null)
return false;
XmlNode binnode = ctornode.SelectSingleNode(taglib.BINARY_DATA_TAG);
if (binnode == null)
return false;
return true;
}
/// <summary>
/// Returns the TypeConverter of a Type.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
protected TypeConverter GetConverter(Type type)
{
TypeConverter retConverter = null;
if (!typeConverterCache.TryGetValue(type, out retConverter))
{
retConverter = TypeDescriptor.GetConverter(type);
typeConverterCache[type] = retConverter;
}
return retConverter;
}
/// <summary>
/// Registers an Assembly.
/// </summary>
/// <param name="assembly"></param>
/// <remarks>
/// Register Assemblies which are not known at compile time, e.g. PlugIns or whatever.
/// </remarks>
public void RegisterAssembly(Assembly assembly)
{
string ass = assembly.FullName;
int x = ass.IndexOf(",");
if (x > 0)
ass = ass.Substring(0, x);
assemblyregister[ass] = assembly;
}
/// <summary>
/// Registers a list of assemblies.
/// </summary>
/// <param name="assemblies"></param>
/// <returns></returns>
public int RegisterAssemblies(List<Assembly> assemblies)
{
if (assemblies == null)
return 0;
int cnt = 0;
foreach (Assembly ass in assemblies)
{
this.RegisterAssembly(ass);
cnt++;
}
return cnt;
}
/// <summary>
/// Registers a list of assemblies.
/// </summary>
/// <param name="assemblies"></param>
/// <returns></returns>
public int RegisterAssemblies(Assembly[] assemblies)
{
if (assemblies == null)
return 0;
int cnt = 0;
for (int i = 0; i < assemblies.Length; i++)
{
this.RegisterAssembly(assemblies[i]);
cnt++;
}
return cnt;
}
/// <summary>
/// Adds the assembly register items to the assembly cache.
/// </summary>
protected void AddAssemblyRegisterToCache()
{
if (assemblyregister == null)
return;
Dictionary<string, Assembly>.Enumerator de = assemblyregister.GetEnumerator();
while (de.MoveNext())
{
assemblycache[de.Current.Key] = de.Current.Value;
}
}
/// <summary>
/// Clears the typedictionary collection.
/// </summary>
public void Reset()
{
if (this.typedictionary != null)
this.typedictionary.Clear();
}
/// <summary>
/// Dispose, release references.
/// </summary>
public void Dispose()
{
Reset();
if (this.assemblycache != null)
this.assemblycache.Clear();
if (assemblyregister != null)
assemblyregister.Clear();
if (typeConverterCache != null)
typeConverterCache.Clear();
}
#endregion Misc
}
}
| zzgaminginc-pointofssale | Samba.Infrastructure.Data/Serializer/XmlDeserializerHelper.cs | C# | gpl3 | 31,177 |
namespace Samba.Infrastructure.Data.Serializer
{
/// <summary>
/// This class supports the Yaowi Framework infrastructure and is not intended to be used directly from your code.
/// <P>These constants are used to parse the XmlNodes.
/// </summary>
public class XmlSerializationTag : IXmlSerializationTag
{
private string OBJECT = "object";
private string NAME = "name";
private string TYPE = "type";
private string ASSEMBLY = "assembly";
private string PROPERTIES = "properties";
private string PROPERTY = "property";
private string ITEMS = "items";
private string ITEM = "item";
private string INDEX = "index";
private string NAME_ATT_KEY = "Key";
private string NAME_ATT_VALUE = "Value";
private string TYPE_DICTIONARY = "typedictionary";
private string GENERIC_TYPE_ARGUMENTS = "generictypearguments";
private string CONSTRUCTOR = "constructor";
private string BINARY_DATA = "binarydata";
public virtual string GENERIC_TYPE_ARGUMENTS_TAG
{
get { return GENERIC_TYPE_ARGUMENTS; }
}
public virtual string OBJECT_TAG
{
get { return OBJECT; }
}
public virtual string NAME_TAG
{
get { return NAME; }
}
public virtual string TYPE_TAG
{
get { return TYPE; }
}
public virtual string ASSEMBLY_TAG
{
get { return ASSEMBLY; }
}
public virtual string PROPERTIES_TAG
{
get { return PROPERTIES; }
}
public virtual string PROPERTY_TAG
{
get { return PROPERTY; }
}
public virtual string ITEMS_TAG
{
get { return ITEMS; }
}
public virtual string ITEM_TAG
{
get { return ITEM; }
}
public virtual string INDEX_TAG
{
get { return INDEX; }
}
public virtual string NAME_ATT_KEY_TAG
{
get { return NAME_ATT_KEY; }
}
public virtual string NAME_ATT_VALUE_TAG
{
get { return NAME_ATT_VALUE; }
}
public virtual string TYPE_DICTIONARY_TAG
{
get { return TYPE_DICTIONARY; }
}
public string CONSTRUCTOR_TAG
{
get { return CONSTRUCTOR; }
}
public string BINARY_DATA_TAG
{
get { return BINARY_DATA; }
}
}
}
| zzgaminginc-pointofssale | Samba.Infrastructure.Data/Serializer/XmlSerializationTag.cs | C# | gpl3 | 2,340 |
using System;
using System.Collections.Generic;
namespace Samba.Infrastructure.Data.Serializer
{
public static class ObjectCloner
{
public static T Clone<T>(T item) where T : class
{
using (var serializer = new XmlSerializerHelper { IgnoreSerializableAttribute = true })
{
using (var deserializer = new XmlDeserializerHelper())
{
var dictionary = new Dictionary<Type, Dictionary<int, IEntity>>();
PropertyComparor.ExtractEntities(item, dictionary);
var xmlDocument = serializer.Serialize(item);
var clone = deserializer.Deserialize(xmlDocument, dictionary) as T;
return clone;
}
}
}
public static int DataHash(object item)
{
using (var serializer = new XmlSerializerHelper { IgnoreSerializableAttribute = true })
{
var xmlDoc = serializer.Serialize(item);
return xmlDoc.InnerXml.GetHashCode();
}
}
}
}
| zzgaminginc-pointofssale | Samba.Infrastructure.Data/Serializer/ObjectCloner.cs | C# | gpl3 | 1,153 |
using System;
using System.IO;
using System.Runtime.Serialization;
using System.ComponentModel;
using System.Globalization;
namespace Samba.Infrastructure.Data.Serializer
{
/// <summary>
/// Container for binary data.<p>
/// This class can be used to encapsulate binary data for serialization or transportation purposes.
/// </summary>
[Serializable]
[TypeConverter(typeof(BinaryContainerTypeConverter))]
public class BinaryContainer : ISerializable, IObjectReference
{
private byte[] data = null;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="data"></param>
public BinaryContainer(byte[] data)
{
this.data = data;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="data"></param>
public BinaryContainer(Stream data)
{
BinaryContainerTypeConverter conv = new BinaryContainerTypeConverter();
this.data = conv.ConvertStreamToByteArray(data);
}
/// <summary>
/// Read only property returning the size (length) of the binary data.
/// </summary>
public int Size
{
get {
if (data != null)
return data.Length;
else
return 0;
}
}
/// <summary>
/// Sets the data.
/// </summary>
/// <returns></returns>
public byte[] GetData()
{
return data;
}
/// <summary>
/// Gets the data.
/// </summary>
/// <param name="data"></param>
public void SetData(byte[] data)
{
this.data = data;
}
/// <summary>
/// <see cref="System.Runtime.Serialization.ISerializable.GetObjectData"/>
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.SetType(typeof(byte[]));
}
/// <summary>
/// <see cref="System.Runtime.Serialization.IObjectReference.GetRealObject"/>
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public object GetRealObject(StreamingContext context)
{
return this.data;
}
}
/// <summary>
/// XmlBinaryContainer TypeConverter.<p>
/// Converts the <code>XmlBinaryContainer</code> to or from <code>byte[]</code> and <code>Stream</code>s.
/// </summary>
public class BinaryContainerTypeConverter : TypeConverter
{
/// <summary>
/// <see cref="System.ComponentModel.TypeConverter.CanConvertFrom"/>
/// </summary>
/// <param name="context"></param>
/// <param name="sourceType"></param>
/// <returns></returns>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(byte[]))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
/// <summary>
/// <see cref="System.ComponentModel.TypeConverter.ConvertFrom"/>
/// </summary>
/// <param name="context"></param>
/// <param name="culture"></param>
/// <param name="value"></param>
/// <returns></returns>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is byte[])
{
return new BinaryContainer((byte[])value);
}
else if (value is Stream)
{
return ConvertStreamToByteArray((Stream)value);
}
return base.ConvertFrom(context, culture, value);
}
/// <summary>
/// Converts a <code>Stream</code> into <code>byte[]</code>.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public byte[] ConvertStreamToByteArray(Stream s)
{
if (s == null)
return null;
byte[] bytes = new byte[s.Length];
int numBytesToRead = (int)s.Length;
int numBytesRead = 0;
while (numBytesToRead > 0)
{
// Read may return anything from 0 to numBytesToRead.
int n = s.Read(bytes, numBytesRead, numBytesToRead);
// The end of the Stream is reached.
if (n == 0)
break;
numBytesRead += n;
numBytesToRead -= n;
}
s.Close();
return bytes;
}
/// <summary>
/// <see cref="System.ComponentModel.TypeConverter.CanConvertTo"/>
/// </summary>
/// <param name="context"></param>
/// <param name="destinationType"></param>
/// <returns></returns>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(byte[]))
{
return true;
}
else if (destinationType == typeof(Stream))
{
return true;
}
return base.CanConvertTo(context, destinationType);
}
/// <summary>
/// <see cref="System.ComponentModel.TypeConverter.ConvertTo"/>
/// </summary>
/// <param name="context"></param>
/// <param name="culture"></param>
/// <param name="value"></param>
/// <param name="destinationType"></param>
/// <returns></returns>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(byte[]))
{
return ((BinaryContainer)value).GetData();
}
else if (destinationType == typeof(Stream))
{
return new MemoryStream(((BinaryContainer)value).GetData());
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
}
| zzgaminginc-pointofssale | Samba.Infrastructure.Data/Serializer/BinaryContainer.cs | C# | gpl3 | 5,722 |
namespace Samba.Infrastructure.Data.Serializer
{
public interface IXmlSerializationTag
{
string ASSEMBLY_TAG { get; }
string INDEX_TAG { get; }
string ITEM_TAG { get; }
string ITEMS_TAG { get; }
string NAME_ATT_KEY_TAG { get; }
string NAME_ATT_VALUE_TAG { get; }
string NAME_TAG { get; }
string OBJECT_TAG { get; }
string PROPERTIES_TAG { get; }
string PROPERTY_TAG { get; }
string TYPE_DICTIONARY_TAG { get; }
string TYPE_TAG { get; }
string GENERIC_TYPE_ARGUMENTS_TAG { get; }
string CONSTRUCTOR_TAG { get;}
string BINARY_DATA_TAG { get;}
}
} | zzgaminginc-pointofssale | Samba.Infrastructure.Data/Serializer/IXmlSerializationTag.cs | C# | gpl3 | 630 |
// -----------------------------------------------------------------------------------
// Use it as you please, but keep this header.
// Author : Marcus Deecke, 2006
// Web : www.yaowi.com
// Email : code@yaowi.com
// -----------------------------------------------------------------------------------
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Xml;
namespace Samba.Infrastructure.Data.Serializer
{
/// <summary>
/// Serializes arbitrary objects to XML.
/// </summary>
public class XmlSerializerHelper : IDisposable
{
#region Members
// All serialized objects are registered here
public const string TYPE_KEY_PREFIX = "TK";
private readonly ArrayList _objlist = new ArrayList();
private readonly Hashtable _typedictionary = new Hashtable();
private Type _serializationIgnoredAttributeType;
private IXmlSerializationTag _taglib = new XmlSerializationTag();
private bool _usetypedictionary = true;
#endregion Members
#region Properties
/// <summary>
/// Gets or sets the attribute that, when applied to a property enable its serialization. If null every property is serialized.
/// Even "Type" does not specialize the kind of Type it is obvious that only Attributes can be applied to properties.
/// </summary>
[Description("Gets or sets Attribute Type which marks a property to be ignored.")]
public Type SerializationIgnoredAttributeType
{
get { return _serializationIgnoredAttributeType; }
set { _serializationIgnoredAttributeType = value; }
}
/// <summary>
/// Gets or sets whether errors during serialisation shall be ignored.
/// </summary>
[Description("Gets or sets whether errors during serialisation shall be ignored.")]
public bool IgnoreSerialisationErrors { get; set; }
/// <summary>
/// Gets or sets the dictionary of XML-tags.
/// </summary>
[Description("Gets or sets the dictionary of XML-tags.")]
public IXmlSerializationTag TagLib
{
get { return _taglib; }
set { _taglib = value; }
}
/// <summary>
/// Gets or sets whether a type dictionary is used to store Type information.
/// </summary>
[Description("Gets or sets whether a type dictionary is used to store Type information.")]
public bool UseTypeDictionary
{
get { return _usetypedictionary; }
set { _usetypedictionary = value; }
}
/// <summary>
/// Gets or sets whether the ISerializable Attribute is ignored.
/// </summary>
/// <remarks>
/// Set this property only to true if you know about side effects.
/// </remarks>
[Description("Gets or sets whether the ISerializable Attribute is ignored.")]
public bool IgnoreSerializableAttribute { get; set; }
#endregion Properties
#region Serialize
public void Serialize(object obj, string filename)
{
XmlDocument doc = Serialize(obj);
doc.Save(filename);
}
public XmlDocument Serialize(object obj)
{
var doc = new XmlDocument();
XmlDeclaration xd = doc.CreateXmlDeclaration("1.0", "utf-8", null);
doc.AppendChild(xd);
Serialize(obj, null, doc);
return doc;
}
public void Serialize(object obj, String name, XmlDocument doc)
{
// Reset();
XmlElement root = doc.CreateElement(_taglib.OBJECT_TAG);
XmlComment comment = root.OwnerDocument.CreateComment(" Data section : Don't edit any attributes ! ");
root.AppendChild(comment);
SetObjectInfoAttributes(name, obj.GetType(), root);
if (doc.DocumentElement == null)
doc.AppendChild(root);
else
doc.DocumentElement.AppendChild(root);
Type ctortype = TypeInfo.GetBinaryConstructorType(obj.GetType());
if (ctortype != null)
{
SerializeBinaryObject(obj, ctortype, root);
}
else
{
SerializeProperties(obj, root);
}
WriteTypeDictionary(root);
}
public void Serialize(object obj, String name, XmlNode parent)
{
// Reset();
XmlDocument doc = parent.OwnerDocument;
XmlElement root = doc.CreateElement(_taglib.OBJECT_TAG);
parent.AppendChild(root);
XmlComment comment = root.OwnerDocument.CreateComment(" Data section : Don't edit any attributes ! ");
root.AppendChild(comment);
SetObjectInfoAttributes(name, obj.GetType(), root);
Type ctortype = TypeInfo.GetBinaryConstructorType(obj.GetType());
if (ctortype != null)
{
SerializeBinaryObject(obj, ctortype, root);
}
else
{
SerializeProperties(obj, root);
}
WriteTypeDictionary(root);
}
#endregion Serialize
#region ObjectInfo
private static ObjectInfo GetObjectInfo(string name, Type type)
{
return new ObjectInfo { Name = name, Type = type.FullName, Assembly = type.Assembly.FullName }; ;
}
private void SetObjectInfoAttributes(String propertyName, Type type, XmlNode node)
{
var objinfo = new ObjectInfo();
GetObjectInfo(propertyName, type);
if (type != null)
{
objinfo = GetObjectInfo(propertyName, type);
}
// Use of a TypeDictionary?
if (_usetypedictionary)
{
// TypeDictionary
String typekey = GetTypeKey(type);
XmlAttribute att = node.OwnerDocument.CreateAttribute(_taglib.NAME_TAG);
att.Value = objinfo.Name;
node.Attributes.Append(att);
att = node.OwnerDocument.CreateAttribute(_taglib.TYPE_TAG);
att.Value = typekey;
node.Attributes.Append(att);
// The assembly will be set, also, but it's always empty.
att = node.OwnerDocument.CreateAttribute(_taglib.ASSEMBLY_TAG);
att.Value = "";
node.Attributes.Append(att);
}
else
{
// No TypeDictionary
XmlAttribute att = node.OwnerDocument.CreateAttribute(_taglib.NAME_TAG);
att.Value = objinfo.Name;
node.Attributes.Append(att);
att = node.OwnerDocument.CreateAttribute(_taglib.TYPE_TAG);
att.Value = objinfo.Type;
node.Attributes.Append(att);
att = node.OwnerDocument.CreateAttribute(_taglib.ASSEMBLY_TAG);
att.Value = objinfo.Assembly;
node.Attributes.Append(att);
}
}
#endregion ObjectInfo
#region Properties
/// <summary>
/// Returns wether the Property has to be serialized or not (depending on SerializationIgnoredAttributeType).
/// </summary>
/// <param name="pi"></param>
/// <returns></returns>
protected bool CheckPropertyHasToBeSerialized(PropertyInfo pi)
{
if (_serializationIgnoredAttributeType != null)
{
return pi.GetCustomAttributes(_serializationIgnoredAttributeType, true).Length == 0;
}
return true;
}
/// <summary>
/// Serializes the properties an Object and appends them to the specified XmlNode.
/// </summary>
/// <param name="obj"></param>
/// <param name="parent"></param>
protected void SerializeProperties(object obj, XmlNode parent)
{
if (TypeInfo.IsCollection(obj.GetType()))
{
SetCollectionItems(obj, (ICollection)obj, parent);
}
else
{
XmlElement node = parent.OwnerDocument.CreateElement(_taglib.PROPERTIES_TAG);
SetProperties(obj, node);
parent.AppendChild(node);
}
}
protected void SetProperties(object obj, XmlElement node)
{
var piarr = obj.GetType().GetProperties();
Debug.Assert(piarr.Length > 0,
"No property found to serialize for type " + obj.GetType().Name +
"! Current implementation of Ellisys.Util.Serialization.XmlSerializer only work on public properties with get and set");
for (int i = 0; i < piarr.Length; i++)
{
SetProperty(obj, piarr[i], node);
}
//foreach (var pi in piarr)
//{
// SetProperty(obj, pi, node);
//}
}
protected void SetProperty(object obj, PropertyInfo pi, XmlNode parent)
{
_objlist.Add(obj);
var val = pi.GetValue(obj, null);
if (val == null) return;
// If the the value already exists in the list of processed objects/properties
// ignore it o avoid circular calls.
//if (_objlist.Contains(val))
// return;
SetProperty(obj, val, pi, parent);
}
protected void SetProperty(object obj, object value, PropertyInfo pi, XmlNode parent)
{
// object val = value; ??
try
{
// Empty values are ignored (no need to restore null references or empty Strings)
if (value == null || value.Equals(""))
return;
// Get the Type
//Type pt = pi.PropertyType;
Type pt = value.GetType();
// Check whether this property can be serialized and deserialized
if (CheckPropertyHasToBeSerialized(pi) && (pt.IsSerializable || IgnoreSerializableAttribute) &&
(pi.CanWrite) && ((pt.IsPublic) || (pt.IsEnum)))
{
XmlElement prop = parent.OwnerDocument.CreateElement(_taglib.PROPERTY_TAG);
SetObjectInfoAttributes(pi.Name, pt, prop);
// Try to find a constructor for binary data.
// If found remember the parameter's Type.
Type binctortype = TypeInfo.GetBinaryConstructorType(pt);
if (binctortype != null) // a binary contructor was found
{
/*
* b. Trying to handle binary data
*/
SerializeBinaryObject(pi.GetValue(obj, null), binctortype, prop);
}
else if (TypeInfo.IsCollection(pt))
{
/*
* a. Collections ask for a specific handling
*/
SetCollectionItems(obj, (ICollection)value, prop);
}
else
{
/*
* c. "normal" classes
*/
SetXmlElementFromBasicPropertyValue(prop, pt, value, parent);
}
// Append the property node to the paren XmlNode
parent.AppendChild(prop);
}
}
catch (Exception exc)
{
if (!IgnoreSerialisationErrors)
{
throw exc;
}
else
{
// perhaps logging
}
}
}
protected void SetXmlElementFromBasicPropertyValue(XmlElement prop, Type pt, object value, XmlNode parent)
{
// If possible, convert this property to a string
if (pt.IsAssignableFrom(typeof(string)))
{
prop.InnerText = value.ToString();
return;
}
if (value is DateTime)
{
var v = (DateTime)value;
prop.InnerText = v.ToString("o");
return;
}
var tc = TypeDescriptor.GetConverter(pt);
if (tc != null)
{
if (tc.CanConvertFrom(typeof(string)) && tc.CanConvertTo(typeof(string)))
{
prop.InnerText = (string)tc.ConvertTo(value, typeof(string));
return;
}
}
var complexclass = false;
// Holds whether the propertys type is an complex type (the properties of objects have to be iterated, either)
// Get all properties
PropertyInfo[] piarr2 = pt.GetProperties();
XmlElement proplist = null;
Debug.Assert(piarr2.Length > 0,
"No property found to serialize for type " + pt.Name +
"! Current implementation of Ellisys.Util.Serialization.XmlSerializer only work on public properties with get and set");
// Loop all properties
foreach (PropertyInfo pi2 in piarr2)
{
// Check whether this property can be serialized and deserialized
if (CheckPropertyHasToBeSerialized(pi2) &&
(pi2.PropertyType.IsSerializable || IgnoreSerializableAttribute) && (pi2.CanWrite) &&
((pi2.PropertyType.IsPublic) || (pi2.PropertyType.IsEnum)))
{
// Seems to be a complex type
complexclass = true;
// Add a properties parent node
if (proplist == null)
{
proplist = parent.OwnerDocument.CreateElement(_taglib.PROPERTIES_TAG);
prop.AppendChild(proplist);
}
// Set the property (recursive call of this method!)
SetProperty(value, pi2, proplist);
}
}
// Ok, that was not a complex class either
if (!complexclass)
{
// Converting to string was not possible, just set the value by ToString()
prop.InnerText = value.ToString();
}
}
/// <summary>
/// Serializes binary data to a XmlNode.
/// </summary>
/// <param name="obj"></param>
/// <param name="ctorParamType"></param>
/// <param name="parent"></param>
protected void SerializeBinaryObject(Object obj, Type ctorParamType, XmlNode parent)
{
XmlElement proplist = null;
String val = null;
try
{
// If the objact is a Stream or can be converted to a byte[]...
TypeConverter tc = TypeDescriptor.GetConverter(obj.GetType());
if (tc.CanConvertTo(typeof(byte[])) || typeof(Stream).IsAssignableFrom(obj.GetType()))
{
byte[] barr = null;
// Convert to byte[]
if (typeof(Stream).IsAssignableFrom(obj.GetType()))
{
// Convert a Stream to byte[]
var bctc = new BinaryContainerTypeConverter();
barr = bctc.ConvertStreamToByteArray((Stream)obj);
}
else
{
// Convert the object to a byte[]
barr = (byte[])tc.ConvertTo(obj, typeof(byte[]));
}
// Create a constructor node
proplist = parent.OwnerDocument.CreateElement(_taglib.CONSTRUCTOR_TAG);
parent.AppendChild(proplist);
// Set info about the constructor type as attributes
SetObjectInfoAttributes("0", ctorParamType, proplist);
// Create a node for the binary data
XmlNode bindata = proplist.OwnerDocument.CreateElement(_taglib.BINARY_DATA_TAG);
proplist.AppendChild(bindata);
// Set info about the binary data type as attributes (currently it's always byte[])
SetObjectInfoAttributes("0", typeof(byte[]), bindata);
// Convert the byte array to a string so it's easy to store it in XML
val = Convert.ToBase64String(barr, 0, barr.Length);
bindata.InnerText = val;
}
}
catch (Exception exc)
{
if (!IgnoreSerialisationErrors)
{
throw exc;
}
else
{
// perhaps logging
}
}
}
#endregion Properties
#region SetCollectionItems
protected void SetCollectionItems(object obj, ICollection value, XmlNode parent)
{
// Validating the parameters
if (obj == null || value == null || parent == null)
return;
try
{
ICollection coll = value;
XmlElement collnode = parent.OwnerDocument.CreateElement(_taglib.ITEMS_TAG);
parent.AppendChild(collnode);
int cnt = 0;
// What kind of Collection?
if (TypeInfo.IsDictionary(coll.GetType()))
{
// IDictionary
var dict = (IDictionary)coll;
IDictionaryEnumerator de = dict.GetEnumerator();
while (de.MoveNext())
{
XmlElement itemnode = parent.OwnerDocument.CreateElement(_taglib.ITEM_TAG);
collnode.AppendChild(itemnode);
object curr = de.Current;
XmlElement propsnode = parent.OwnerDocument.CreateElement(_taglib.PROPERTIES_TAG);
itemnode.AppendChild(propsnode);
SetProperties(curr, propsnode);
}
}
else
{
// Everything else
IEnumerator ie = coll.GetEnumerator();
while (ie.MoveNext())
{
object obj2 = ie.Current;
XmlElement itemnode = parent.OwnerDocument.CreateElement(_taglib.ITEM_TAG);
if (obj2 != null)
{
SetObjectInfoAttributes(null, obj2.GetType(), itemnode);
}
else
{
SetObjectInfoAttributes(null, null, itemnode);
}
itemnode.Attributes[_taglib.NAME_TAG].Value = "" + cnt;
cnt++;
collnode.AppendChild(itemnode);
if (obj2 == null)
continue;
Type pt = obj2.GetType();
if (TypeInfo.IsCollection(pt))
{
SetCollectionItems(obj, (ICollection)obj2, itemnode);
}
else
{
SetXmlElementFromBasicPropertyValue(itemnode, pt, obj2, parent);
} // IsCollection?
} // Loop collection
} // IsDictionary?
}
catch (Exception exc)
{
if (!IgnoreSerialisationErrors)
{
throw exc;
}
else
{
// perhaps logging
}
}
}
#endregion SetCollectionItems
#region Misc
/// <summary>
/// Dispose, release references.
/// </summary>
public void Dispose()
{
Reset();
}
/// <summary>
/// Builds the Hashtable that will be written to XML as the type dictionary.<P>
/// </summary>
/// <returns></returns>
/// <remarks>
/// While serialization the key of the type dictionary is the Type so it's easy to determine
/// whether a Type is registered already. For deserialization the order is reverse: find a Type
/// for a given key.
/// This methods creates a reversed Hashtable with the Types information stored in TypeInfo instances.
/// </remarks>
protected Hashtable BuildSerializeableTypeDictionary()
{
var ht = new Hashtable();
IDictionaryEnumerator de = _typedictionary.GetEnumerator();
while (de.MoveNext())
{
var type = (Type)de.Entry.Key;
var key = (String)de.Value;
var ti = new TypeInfo(type);
ht.Add(key, ti);
}
return ht;
}
protected string GetTypeKey(object obj)
{
return obj == null ? null : GetTypeKey(obj.GetType());
}
protected string GetTypeKey(Type type)
{
if (type == null)
return null;
if (!_typedictionary.ContainsKey(type))
{
_typedictionary.Add(type, TYPE_KEY_PREFIX + _typedictionary.Count);
}
return (String)_typedictionary[type];
}
protected void WriteTypeDictionary(XmlNode parentNode)
{
var usedict = UseTypeDictionary;
try
{
if (UseTypeDictionary)
{
XmlComment comment =
parentNode.OwnerDocument.CreateComment(
" TypeDictionary : Don't edit anything in this section at all ! ");
parentNode.AppendChild(comment);
XmlElement dictelem = parentNode.OwnerDocument.CreateElement(_taglib.TYPE_DICTIONARY_TAG);
parentNode.AppendChild(dictelem);
Hashtable dict = BuildSerializeableTypeDictionary();
// Temporary set UseTypeDictionary to false, otherwise TypeKeys instead of the
// Type information will be written
UseTypeDictionary = false;
SetObjectInfoAttributes(null, dict.GetType(), dictelem);
SerializeProperties(dict, dictelem);
// Reset UseTypeDictionary
UseTypeDictionary = true;
}
}
catch (Exception e)
{
throw e;
}
finally
{
UseTypeDictionary = usedict;
}
}
/// <summary>
/// Clears the Collections.
/// </summary>
public void Reset()
{
if (_objlist != null)
_objlist.Clear();
if (_typedictionary != null)
_typedictionary.Clear();
}
#endregion Misc
}
} | zzgaminginc-pointofssale | Samba.Infrastructure.Data/Serializer/XmlSerializerHelper.cs | C# | gpl3 | 24,533 |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Norm;
namespace Samba.Infrastructure.Data.MongoDB
{
public class MongoWorkspace : IWorkspace, IReadOnlyWorkspace
{
private readonly IMongo _provider;
public MongoWorkspace(string db)
{
//File.Exists("C:\\Data\\db\\" + db + ".ns");
_provider = Mongo.Create(db);
}
public void Dispose()
{
_provider.Dispose();
}
public void CommitChanges()
{
//throw new NotImplementedException();
}
public void Delete<T>(Expression<Func<T, bool>> expression) where T : class
{
var items = All(expression);
foreach (var item in items)
{
Delete(item);
}
}
public void Delete<T>(T item) where T : class
{
_provider.GetCollection<T>().Delete(item);
}
public void DeleteAll<T>() where T : class
{
_provider.Database.DropCollection(typeof(T).Name);
}
public T Single<T>(Expression<Func<T, bool>> expression) where T : class
{
return _provider.GetCollection<T>().AsQueryable().Where(expression).SingleOrDefault();
}
public T Last<T>() where T : class, IEntity
{
return _provider.GetCollection<T>().AsQueryable().LastOrDefault();
}
public IEnumerable<T> All<T>() where T : class
{
return _provider.GetCollection<T>().AsQueryable();
}
public IEnumerable<T> All<T>(params Expression<Func<T, object>>[] includes) where T : class
{
return _provider.GetCollection<T>().AsQueryable();
}
public IEnumerable<T> All<T>(Expression<Func<T, bool>> expression) where T : class
{
return _provider.GetCollection<T>().AsQueryable().Where(expression);
}
public void Add<T>(T item) where T : class
{
var idt = item as IEntity;
if (idt != null)
{
if (idt.Id == 0) idt.Id = Convert.ToInt32(_provider.GetCollection<T>().GenerateId());
}
_provider.GetCollection<T>().Insert(item);
}
public void Add<T>(IEnumerable<T> items) where T : class
{
foreach (var item in items)
{
Add(item);
}
}
public void Update<T>(T item) where T : class
{
//Guid id = ((dynamic)item).Id;
//_provider.GetCollection<T>().UpdateOne(new { _id = id }, item);
var idf = item as IEntity;
if (idf != null && idf.Id == 0) Add(item);
}
public int Count<T>() where T : class
{
return Convert.ToInt32(_provider.GetCollection<T>().Count());
}
public void ReloadAll()
{
//throw new NotImplementedException();
}
public void ResetDatabase()
{
//throw new NotImplementedException();
}
public void Refresh(IEnumerable collection)
{
//throw new NotImplementedException();
}
public void Refresh(object item)
{
//throw new NotImplementedException();
}
public void Refresh(object item, string property)
{
//throw new NotImplementedException();
}
public IEnumerable<T> Query<T>(Expression<Func<T, bool>> predictate, params Expression<Func<T, object>>[] includes) where T : class
{
//return All(predictate);
if (predictate != null)
return All(predictate);
return All<T>();
}
public IEnumerable<string> Distinct<T>(Expression<Func<T, string>> expression) where T : class
{
return _provider.GetCollection<T>().AsQueryable().Select(expression).Distinct().Where(x => !string.IsNullOrEmpty(x)).ToList();
}
public TResult Single<TSource, TResult>(int id, Expression<Func<TSource, TResult>> expression) where TSource : class, IEntity
{
return _provider.GetCollection<TSource>().AsQueryable().Where(x => x.Id == id).Select(expression).SingleOrDefault();
}
public T Single<T>(Expression<Func<T, bool>> predictate, string[] includes) where T : class
{
return Single(predictate);
}
public T Single<T>(Expression<Func<T, bool>> predictate, params Expression<Func<T, object>>[] includes) where T : class
{
return Single(predictate);
}
public IEnumerable<TResult> Select<TSource, TResult>(Expression<Func<TSource, TResult>> expression, Expression<Func<TSource, bool>> predictate) where TSource : class
{
if (predictate != null)
return _provider.GetCollection<TSource>().AsQueryable().Where(predictate).Select(expression);
return _provider.GetCollection<TSource>().AsQueryable().Select(expression);
}
public int Count<T>(Expression<Func<T, bool>> predictate) where T : class
{
if (predictate != null)
return _provider.GetCollection<T>().AsQueryable().Count(predictate);
return _provider.GetCollection<T>().AsQueryable().Count();
}
public decimal Sum<T>(Expression<Func<T, decimal>> selector, Expression<Func<T, bool>> predictate) where T : class
{
if (predictate != null)
return _provider.GetCollection<T>().AsQueryable().Where(predictate).Sum(selector);
return _provider.GetCollection<T>().AsQueryable().Sum(selector.Compile());
}
public T Last<T>(Expression<Func<T, bool>> predictate, Expression<Func<T, object>>[] includes) where T : class, IEntity
{
return _provider.GetCollection<T>().AsQueryable().Last(predictate);
}
public IEnumerable<T> Last<T>(int recordCount) where T : class,IEntity
{
var coll = _provider.GetCollection<T>().AsQueryable();
var count = coll.Count();
if (count > recordCount)
return coll.Skip(count - recordCount).Take(recordCount);
return coll;
}
public IQueryable<T> Queryable<T>() where T : class
{
return _provider.GetCollection<T>().AsQueryable();
}
}
}
| zzgaminginc-pointofssale | Samba.Infrastructure.Data/MongoDB/MongoWorkspace.cs | C# | gpl3 | 6,757 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace Samba.Infrastructure.Data
{
public interface IReadOnlyWorkspace : IDisposable
{
IEnumerable<T> Query<T>(Expression<Func<T, bool>> predictate, params Expression<Func<T, object>>[] includes) where T : class;
IEnumerable<string> Distinct<T>(Expression<Func<T, string>> expression) where T : class;
TResult Single<TSource, TResult>(int id, Expression<Func<TSource, TResult>> expression) where TSource : class, IEntity;
T Single<T>(Expression<Func<T, bool>> predictate, string[] includes) where T : class;
T Single<T>(Expression<Func<T, bool>> predictate, params Expression<Func<T, object>>[] includes) where T : class;
IEnumerable<TResult> Select<TSource, TResult>(Expression<Func<TSource, TResult>> expression, Expression<Func<TSource, bool>> predictate) where TSource : class;
int Count<T>(Expression<Func<T, bool>> predictate) where T : class;
decimal Sum<T>(Expression<Func<T, decimal>> selector, Expression<Func<T, bool>> predictate) where T : class;
T Last<T>(Expression<Func<T, bool>> predictate, Expression<Func<T, object>>[] includes) where T : class,IEntity;
IEnumerable<T> Last<T>(int recordCount) where T : class,IEntity;
IQueryable<T> Queryable<T>() where T : class;
}
}
| zzgaminginc-pointofssale | Samba.Infrastructure.Data/IReadOnlyWorkspace.cs | C# | gpl3 | 1,414 |
using System.Collections.Generic;
namespace Samba.Infrastructure.Data
{
public interface IRepository<TModel> where TModel : IEntity
{
void Add(TModel item);
void Delete(TModel item);
IEnumerable<TModel> GetAll();
int GetCount();
void SaveChanges();
TModel GetById(int id);
TModel GetByName(string name);
}
} | zzgaminginc-pointofssale | Samba.Infrastructure.Data/IRepository.cs | C# | gpl3 | 395 |
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("Samba.Infrastructure.Data")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Samba.Infrastructure.Data")]
[assembly: AssemblyCopyright("Copyright © 2010")]
[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("1c1d64e0-3f5e-419e-9e41-cf84449f27c8")]
// 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")]
| zzgaminginc-pointofssale | Samba.Infrastructure.Data/Properties/AssemblyInfo.cs | C# | gpl3 | 1,462 |
using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Data.Entity;
using System.Linq.Expressions;
namespace Samba.Infrastructure.Data.SQL
{
public class ReadOnlyEFWorkspace : IReadOnlyWorkspace
{
private readonly CommonDbContext _context;
public ReadOnlyEFWorkspace(CommonDbContext context)
{
_context = context;
}
public IEnumerable<T> Query<T>(Expression<Func<T, bool>> predictate, params Expression<Func<T, object>>[] includes) where T : class
{
if (includes != null && predictate != null)
return includes.Aggregate(_context.ReadOnly<T>(), (current, include) => current.Include(include)).Where(predictate);
if (includes != null)
return includes.Aggregate(_context.ReadOnly<T>(), (current, include) => current.Include(include));
if (predictate != null)
return _context.ReadOnly<T>().Where(predictate);
return _context.ReadOnly<T>();
}
public IEnumerable<string> Distinct<T>(Expression<Func<T, string>> expression) where T : class
{
return _context.ReadOnly<T>().Select(expression).Distinct().Where(x => !string.IsNullOrEmpty(x)).ToList();
}
public T Single<T>(Expression<Func<T, bool>> expression, string[] includes) where T : class
{
if (includes == null || includes.Length < 1)
return _context.ReadOnly<T>().Where(expression).SingleOrDefault();
return includes.Aggregate(_context.ReadOnly<T>() as ObjectQuery<T>,
(current, include) => current.Include(include)).Where(expression).SingleOrDefault();
}
public T Single<T>(Expression<Func<T, bool>> predictate, params Expression<Func<T, object>>[] includes) where T : class
{
return includes.Aggregate(_context.ReadOnly<T>(), (current, include) => current.Include(include)).Where(predictate).SingleOrDefault();
}
public IEnumerable<TResult> Select<TSource, TResult>(Expression<Func<TSource, TResult>> expression, Expression<Func<TSource, bool>> predictate) where TSource : class
{
if (predictate != null)
return _context.ReadOnly<TSource>().Where(predictate).Select(expression);
return _context.ReadOnly<TSource>().Select(expression);
}
public int Count<T>(Expression<Func<T, bool>> predictate) where T : class
{
if (predictate != null)
return _context.ReadOnly<T>().Count(predictate);
return _context.ReadOnly<T>().Count();
}
public decimal Sum<T>(Expression<Func<T, decimal>> selector, Expression<Func<T, bool>> predictate) where T : class
{
try
{
if (predictate != null)
return _context.ReadOnly<T>().Where(predictate).Sum(selector);
return _context.ReadOnly<T>().Sum(selector);
}
catch (InvalidOperationException)
{
return 0;
}
}
public T Last<T>(Expression<Func<T, bool>> predictate, Expression<Func<T, object>>[] includes) where T : class,IEntity
{
return includes.Aggregate(_context.ReadOnly<T>(), (current, include) => current.Include(include))
.Where(predictate)
.OrderByDescending(x => x.Id)
.Take(1)
.FirstOrDefault();
}
public IEnumerable<T> Last<T>(int recordCount) where T : class,IEntity
{
return _context.ReadOnly<T>()
.OrderByDescending(x => x.Id)
.Take(recordCount)
.ToList();
}
public TResult Single<TSource, TResult>(int id, Expression<Func<TSource, TResult>> expression) where TSource : class ,IEntity
{
return _context.ReadOnly<TSource>().Where(x => x.Id == id).Select(expression).SingleOrDefault();
}
public IQueryable<T> Queryable<T>() where T : class
{
return _context.ReadOnly<T>();
}
public void Dispose()
{
_context.Close();
_context.Dispose();
}
}
} | zzgaminginc-pointofssale | Samba.Infrastructure.Data/SQL/ReadOnlyEFWorkspace.cs | C# | gpl3 | 4,452 |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
namespace Samba.Infrastructure.Data.SQL
{
public class EFWorkspace : IWorkspace
{
private readonly CommonDbContext _context;
public EFWorkspace(CommonDbContext context)
{
_context = context;
if (_context.Database.Connection.ConnectionString.EndsWith(".sdf"))
_context.ObjContext().Connection.Open();
}
public void CommitChanges()
{
_context.SaveChanges();
}
public void ResetDatabase()
{
// do nothing.
}
public void Refresh(IEnumerable collection)
{
_context.Refresh(collection);
}
public void Refresh(object item, string property)
{
_context.LoadProperty(item, property);
}
public void Refresh(object item)
{
_context.Refresh(item);
}
public void Delete<T>(Expression<Func<T, bool>> expression) where T : class
{
foreach (var item in _context.Set<T>().Where(expression))
Delete(item);
}
public void Delete<T>(T item) where T : class
{
_context.Set<T>().Remove(item);
}
public void DeleteAll<T>() where T : class
{
foreach (var item in _context.Set<T>())
Delete(item);
}
public T Single<T>(Expression<Func<T, bool>> expression) where T : class
{
return _context.Set<T>().SingleOrDefault(expression);
}
public T Single<T>(Expression<Func<T, bool>> expression, params Expression<Func<T, object>>[] includes) where T : class
{
if (includes == null || includes.Length < 1)
return _context.Trackable<T>().Where(expression).SingleOrDefault();
var result = includes.Aggregate(_context.Trackable<T>(), (current, include) => current.Include(include)).Where(expression);
return result.SingleOrDefault();
}
public T Last<T>() where T : class,IEntity
{
return _context.Set<T>().OrderByDescending(x => x.Id).FirstOrDefault();
}
public IEnumerable<T> All<T>() where T : class
{
return _context.Set<T>().ToList();
}
public IEnumerable<T> All<T>(params Expression<Func<T, object>>[] includes) where T : class
{
return includes.Aggregate(_context.Trackable<T>(), (current, include) => current.Include(include));
}
public IEnumerable<T> All<T>(Expression<Func<T, bool>> expression) where T : class
{
return _context.Set<T>().Where(expression);
}
public void Add<T>(T item) where T : class
{
_context.Set<T>().Add(item);
}
public void Add<T>(IEnumerable<T> items) where T : class
{
foreach (var item in items)
Add(item);
}
public void Update<T>(T item) where T : class
{
var idf = item as IEntity;
if (idf != null && idf.Id == 0)
Add(item);
}
public int Count<T>() where T : class
{
return _context.Set<T>().Count();
}
public void ReloadAll()
{
}
public void Dispose()
{
_context.Dispose();
}
}
}
| zzgaminginc-pointofssale | Samba.Infrastructure.Data/SQL/EFWorkspace.cs | C# | gpl3 | 3,692 |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Objects;
using System.Linq;
using System.Text;
namespace Samba.Infrastructure.Data.SQL
{
public class CommonDbContext : DbContext
{
public CommonDbContext(string name)
: base(name)
{
}
public IQueryable<T> ReadOnly<T>() where T : class
{
ObjectSet<T> result = ObjContext().CreateObjectSet<T>();
result.MergeOption = MergeOption.NoTracking;
return result;
}
public IQueryable<T> Trackable<T>() where T : class
{
return ObjContext().CreateObjectSet<T>();
}
public void Refresh(IEnumerable collection)
{
ObjContext().Refresh(RefreshMode.StoreWins, collection);
}
public void Refresh(object item)
{
ObjContext().Refresh(RefreshMode.StoreWins, item);
}
public void Detach(object item)
{
ObjContext().Detach(item);
}
public void LoadProperty(object item, string propertyName)
{
ObjContext().LoadProperty(item, propertyName);
}
public void Close()
{
ObjContext().Connection.Close();
}
public ObjectContext ObjContext()
{
return ((IObjectContextAdapter)this).ObjectContext;
}
public void AcceptAllChanges()
{
ObjContext().AcceptAllChanges();
}
}
}
| zzgaminginc-pointofssale | Samba.Infrastructure.Data/SQL/CommonDbContext.cs | C# | gpl3 | 1,676 |
namespace Samba.Infrastructure.Data
{
public interface IEntity
{
int Id { get; set; }
string Name { get; set; }
}
}
| zzgaminginc-pointofssale | Samba.Infrastructure.Data/IEntity.cs | C# | gpl3 | 155 |
using System.Collections.Generic;
namespace Samba.Infrastructure.Data
{
public class RepositoryBase<TModel> : IRepository<TModel> where TModel : class,IEntity
{
private readonly IWorkspace _workspace;
public RepositoryBase(IWorkspace workspace)
{
_workspace = workspace;
}
public void Add(TModel item)
{
_workspace.Add(item);
}
public void Delete(TModel item)
{
_workspace.Delete(item);
}
public IEnumerable<TModel> GetAll()
{
return _workspace.All<TModel>();
}
public int GetCount()
{
return _workspace.Count<TModel>();
}
public void SaveChanges()
{
_workspace.CommitChanges();
}
public TModel GetById(int id)
{
return _workspace.Single<TModel>(x => x.Id == id);
}
public TModel GetByName(string name)
{
return _workspace.Single<TModel>(x => x.Name.ToLower() == name.ToLower());
}
}
} | zzgaminginc-pointofssale | Samba.Infrastructure.Data/RepositoryBase.cs | C# | gpl3 | 1,153 |
using System;
using System.Reflection;
namespace Serialization
{
public interface IStorage
{
/// <summary>
/// Starts the serialization process, the serializer should initialize and wait for data
/// </summary>
void StartSerializing();
/// <summary>
/// Called when serialization is complete, should return the data or a key
/// encoded as a byte array that will be used to reinitialize the serializer
/// later
/// </summary>
/// <returns></returns>
void FinishedSerializing();
/// <summary>
/// Called when deserialization is complete, so that resources may be released
/// </summary>
void FinishedDeserializing();
/// <summary>
/// Called when serializing a new object, the Entry parameter may have MustHaveName set
/// when this is true the name must be persisted as is so that the property or field can
/// be set when retrieving the data.
/// If this routine returns TRUE then no further processing is executed and the object
/// is presumed persisted in its entirety
/// </summary>
/// <returns>Normally FALSE. True if the object is already fully persisted</returns>
/// <param name="entry">The item being serialized</param>
bool StartSerializing(Entry entry, int id);
/// <summary>
/// Called when the last information about an object has been written
/// </summary>
/// <param name="entry">The object being written</param>
void FinishSerializing(Entry entry);
/// <summary>
/// Called when deserializing an object. If the Entry parameter has MustHaveName set then
/// the routine should return with the Entry parameter updated with the name and
/// the type of the object in StoredType
/// If the storage is capable of fully recreating the object then this routine should return
/// the fully constructed object, and no further processing will occur. Not this does mean
/// that it must handle its own references for previously seen objects
/// This will be called after DeserializeGetName
/// </summary>
/// <returns>Normally NULL, it may also return a fully depersisted object</returns>
/// <param name="entry"></param>
object StartDeserializing(Entry entry);
/// <summary>
/// Called to allow the storage to retrieve the name of the item being deserialized
/// All entries must be named before a call to StartDeserializing, this enables
/// the system to fill out the property setter and capture default stored type
/// information before deserialization commences
/// </summary>
/// <param name="entry">The entry whose name should be filled in</param>
void DeserializeGetName(Entry entry);
/// <summary>
/// Called when an object has deserialization complete
/// </summary>
/// <param name="entry"></param>
void FinishDeserializing(Entry entry);
/// <summary>
/// Reads a simple type (or array of bytes) from storage
/// </summary>
/// <param name="name">The name of the item</param>
/// <param name="type">The type to be read</param>
/// <returns></returns>
Entry[] ShouldWriteFields(Entry[] fields);
Entry[] ShouldWriteProperties(Entry[] properties);
void StartDeserializing();
#region reading
Entry BeginReadProperty(Entry entry);
void EndReadProeprty();
Entry BeginReadField(Entry entry);
void EndReadField();
int BeginReadProperties();
int BeginReadFields();
void EndReadProperties();
void EndReadFields();
T ReadSimpleValue<T>();
object ReadSimpleValue(Type type);
bool IsMultiDimensionalArray(out int length);
void BeginReadMultiDimensionalArray(out int dimension, out int count);
void EndReadMultiDimensionalArray();
int ReadArrayDimension(int index);
Array ReadSimpleArray(Type elementType, int count);
//int BeginRead();
int BeginReadObject(out bool isReference);
void EndReadObject();
int BeginReadList();
void BeginReadListItem(int index);
void EndReadListItem();
void EndReadList();
int BeginReadDictionary();
void BeginReadDictionaryKeyItem(int index);
void EndReadDictionaryKeyItem();
void BeginReadDictionaryValueItem(int index);
void EndReadDictionaryValueItem();
void EndReadDictionary();
int BeginReadObjectArray();
void BeginReadObjectArrayItem(int index);
void EndReadObjectArrayItem();
void EndReadObjectArray();
#endregion
#region writing
void BeginWriteObject(int id, Type objectType, bool wasSeen);
void EndWriteObject();
void BeginWriteList(int count, Type listType);
void BeginWriteListItem(int index);
void EndWriteListItem();
void EndWriteList();
void BeginWriteObjectArray(int count, Type arrayType);
void BeginWriteObjectArrayItem(int index);
void EndWriteObjectArrayItem();
void EndWriteObjectArray();
void BeginMultiDimensionArray(Type arrayType, int dimensions, int count);
void EndMultiDimensionArray();
void WriteArrayDimension(int index, int count);
void WriteSimpleArray(int count, Array array);
void WriteSimpleValue(object value);
// dictionaries
void BeginWriteDictionary(int count, Type dictionaryType);
void BeginWriteDictionaryKey(int id);
void EndWriteDictionaryKey();
void BeginWriteDictionaryValue(int id);
void EndWriteDictionaryValue();
void EndWriteDictionary();
// properties and fields
void BeginWriteProperties(int count);
void EndWriteProperties();
void BeginWriteProperty(string name, Type type);
void EndWriteProperty();
void BeginWriteFields(int count);
void EndWriteFields();
void BeginWriteField(string name, Type type);
void EndWriteField();
bool SupportsOnDemand { get; }
void BeginOnDemand(int id);
void EndOnDemand();
#endregion
}
} | zzgaminginc-pointofssale | Samba.Infrastructure.Data/BinarySerializer/IStorage.cs | C# | gpl3 | 6,438 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
namespace Serialization
{
public class Entry
{
/// <summary>
/// The name of the item being read or written
/// This should be filled out by the storage when
/// MustHaveName = true and deserializing
/// </summary>
public string Name;
/// <summary>
/// The type of the item being stored or retrieved
/// this should be filled out by the storage when
/// MustHaveName=true and deserializing. Will
/// be filled in when serializing.
/// </summary>
private PropertyInfo _propertyInfo;
private FieldInfo _fieldInfo;
public Type StoredType;
/// <summary>
/// On writing, the value of the object for reference, not needed on
/// deserialization
/// </summary>
public object Value;
/// <summary>
/// Set to indicate that the name provided is that of a field or property
/// and is needed to reset the value later
/// </summary>
public bool MustHaveName;
/// <summary>
/// The type of the object which owns the item being serialized or null
/// if not directly owned. This will always be set on serialization and
/// deserialization when MustHaveName = true and can be used to
/// look up field and property information. Or you can ignore it if
/// you don't need it
/// </summary>
public Type OwningType;
/// <summary>
/// The property info or null, if the value did not
/// come from a property. You might want to use
/// the to look up attributes attached to the property
/// definition
/// </summary>
public PropertyInfo PropertyInfo
{
get { return _propertyInfo; }
set
{
Name = value.Name;
StoredType = value.PropertyType;
_propertyInfo = value;
}
}
/// <summary>
/// The field info or null, if the value did not
/// come from a field. You might want to use it
/// to look up attributes attached to the field definition
/// </summary>
public FieldInfo FieldInfo
{
get
{
return _fieldInfo;
}
set
{
Name = value.Name;
StoredType = value.FieldType;
_fieldInfo = value;
}
}
public GetSet Setter;
}
public class BinarySerializer : IStorage
{
public byte[] Data { get; private set; }
private MemoryStream _myStream;
/// <summary>
/// Used when serializing
/// </summary>
public BinarySerializer()
{
}
/// <summary>
/// Used when deserializaing
/// </summary>
/// <param name="data"></param>
public BinarySerializer(byte[] data)
{
Data = data;
}
#region writing
private BinaryWriter _writer;
private void EncodeType(object item, Type storedType)
{
if (item == null)
{
WriteSimpleValue((ushort)0xFFFE);
return;
}
var itemType = item.GetType().TypeHandle;
//If this isn't a simple type, then this might be a subclass so we need to
//store the type
if (storedType == null || !storedType.Equals(item.GetType()) || SilverlightSerializer.Verbose)
{
//Write the type identifier
var tpId = SilverlightSerializer.GetTypeId(itemType);
WriteSimpleValue(tpId);
}
else
//Write a dummy identifier
WriteSimpleValue((ushort)0xFFFF);
}
public bool StartSerializing(Entry entry, int id)
{
if (entry.MustHaveName)
{
ushort nameID = SilverlightSerializer.GetPropertyDefinitionId(entry.Name);
WriteSimpleValue(nameID);
}
var item = entry.Value ?? new SilverlightSerializer.Nuller();
EncodeType(item, entry.StoredType);
return false;
}
public void StartSerializing()
{
_myStream = new MemoryStream();
_writer = new BinaryWriter(_myStream);
SilverlightSerializer.KtStack.Push(SilverlightSerializer.KnownTypes);
SilverlightSerializer.PiStack.Push(SilverlightSerializer.PropertyIds);
SilverlightSerializer.KnownTypes = new List<RuntimeTypeHandle>();
SilverlightSerializer.PropertyIds = new List<string>();
}
public void FinishedSerializing()
{
_writer.Flush();
_writer.Close();
_myStream.Flush();
var data = _myStream.ToArray();
_myStream.Close();
_myStream = null;
var stream = new MemoryStream();
var outputWr = new BinaryWriter(stream);
outputWr.Write("SerV7");
//New, store the verbose property
outputWr.Write(SilverlightSerializer.Verbose);
outputWr.Write(SilverlightSerializer.KnownTypes.Count);
foreach (var kt in SilverlightSerializer.KnownTypes.Select(Type.GetTypeFromHandle))
{
outputWr.Write(kt.AssemblyQualifiedName);
}
outputWr.Write(SilverlightSerializer.PropertyIds.Count);
foreach (var pi in SilverlightSerializer.PropertyIds)
{
outputWr.Write(pi);
}
outputWr.Write(data.Length);
outputWr.Write(data);
outputWr.Flush();
outputWr.Close();
stream.Flush();
Data = stream.ToArray();
stream.Close();
_writer = null;
_reader = null;
SilverlightSerializer.KnownTypes = SilverlightSerializer.KtStack.Pop();
SilverlightSerializer.PropertyIds = SilverlightSerializer.PiStack.Pop();
}
public bool SupportsOnDemand
{
get { return false; }
}
public void BeginOnDemand(int id) { }
public void EndOnDemand() { }
public void BeginWriteObject(int id, Type objectType, bool wasSeen)
{
if (wasSeen)
{
WriteSimpleValue('S');
WriteSimpleValue(id);
}
else
{
WriteSimpleValue('O');
}
}
public void BeginWriteProperties(int count)
{
WriteSimpleValue((byte)count);
}
public void BeginWriteFields(int count)
{
WriteSimpleValue((byte)count);
}
public void WriteSimpleValue(object value)
{
SilverlightSerializer.WriteValue(_writer, value);
}
public void BeginWriteList(int count, Type listType)
{
WriteSimpleValue(count);
}
public void BeginWriteDictionary(int count, Type dictionaryType)
{
WriteSimpleValue(count);
}
public void WriteSimpleArray(int count, Array array)
{
WriteSimpleValue(count);
var elementType = array.GetType().GetElementType();
if (elementType == typeof(byte))
{
WriteSimpleValue((byte[])array);
}
else if (elementType.IsPrimitive)
{
var ba = new byte[Buffer.ByteLength(array)];
Buffer.BlockCopy(array, 0, ba, 0, ba.Length);
WriteSimpleValue(ba);
}
else
{
for (int i = 0; i < count; i++)
{
WriteSimpleValue(array.GetValue(i));
}
}
}
public void BeginMultiDimensionArray(Type arrayType, int dimensions, int count)
{
WriteSimpleValue(-1);
WriteSimpleValue(dimensions);
WriteSimpleValue(count);
}
public void WriteArrayDimension(int dimension, int count)
{
WriteSimpleValue(count);
}
public void BeginWriteObjectArray(int count, Type arrayType)
{
WriteSimpleValue(count);
}
public Entry[] ShouldWriteFields(Entry[] fields) { return fields; }
public Entry[] ShouldWriteProperties(Entry[] properties) { return properties; }
#endregion writing
#region reading
private BinaryReader _reader;
private Type DecodeType(Type storedType)
{
ushort tid = this.ReadSimpleValue<ushort>();
if (tid == 0xFFFE)
{
return null;
}
if (tid != 0xffff)
{
storedType = Type.GetTypeFromHandle(SilverlightSerializer.KnownTypes[tid]);
}
return storedType;
}
public void FinishedDeserializing()
{
_reader.Close();
_myStream.Close();
_reader = null;
_myStream = null;
_writer = null;
SilverlightSerializer.KnownTypes = SilverlightSerializer.KtStack.Pop();
SilverlightSerializer.PropertyIds = SilverlightSerializer.PiStack.Pop();
}
//Gets the name from the stream
public void DeserializeGetName(Entry entry)
{
if (entry.MustHaveName)
{
ushort id = this.ReadSimpleValue<ushort>();
entry.Name = SilverlightSerializer.PropertyIds[id];
}
}
/// <summary>
/// Starts to deserialize the object
/// </summary>
/// <param name="entry"></param>
/// <returns></returns>
public object StartDeserializing(Entry entry)
{
var itemType = DecodeType(entry.StoredType);
entry.StoredType = itemType;
return null;
}
public Entry BeginReadProperty(Entry entry)
{
return entry;
}
public void EndReadProeprty()
{
}
public Entry BeginReadField(Entry entry)
{
return entry;
}
public void EndReadField()
{
}
public void StartDeserializing()
{
SilverlightSerializer.KtStack.Push(SilverlightSerializer.KnownTypes);
SilverlightSerializer.PiStack.Push(SilverlightSerializer.PropertyIds);
var stream = new MemoryStream(Data);
var reader = new BinaryReader(stream);
var version = reader.ReadString();
SilverlightSerializer.currentVersion = int.Parse(version.Substring(4));
if (SilverlightSerializer.currentVersion >= 3)
SilverlightSerializer.Verbose = reader.ReadBoolean();
SilverlightSerializer.PropertyIds = new List<string>();
SilverlightSerializer.KnownTypes = new List<RuntimeTypeHandle>();
var count = reader.ReadInt32();
for (var i = 0; i < count; i++)
{
var typeName = reader.ReadString();
var tp = Type.GetType(typeName);
if (tp == null)
{
var map = new SilverlightSerializer.TypeMappingEventArgs
{
TypeName = typeName
};
SilverlightSerializer.InvokeMapMissingType(map);
tp = map.UseType;
}
if (tp == null)
throw new ArgumentException(string.Format("Cannot reference type {0} in this context", typeName));
SilverlightSerializer.KnownTypes.Add(tp.TypeHandle);
}
count = reader.ReadInt32();
for (var i = 0; i < count; i++)
{
SilverlightSerializer.PropertyIds.Add(reader.ReadString());
}
var data = reader.ReadBytes(reader.ReadInt32());
_myStream = new MemoryStream(data);
_reader = new BinaryReader(_myStream);
reader.Close();
stream.Close();
}
public void FinishDeserializing(Entry entry) { }
public Array ReadSimpleArray(Type elementType, int count)
{
if (count == -1)
{
count = ReadSimpleValue<int>();
}
if (elementType == typeof(byte))
{
return ReadSimpleValue<byte[]>();
}
if (elementType.IsPrimitive && SilverlightSerializer.currentVersion >= 6)
{
var ba = ReadSimpleValue<byte[]>();
var a = Array.CreateInstance(elementType, count);
Buffer.BlockCopy(ba, 0, a, 0, ba.Length);
return a;
}
var result = Array.CreateInstance(elementType, count);
for (var l = 0; l < count; l++)
{
result.SetValue(this.ReadSimpleValue(elementType), l);
}
return result;
}
public int BeginReadProperties()
{
return this.ReadSimpleValue<byte>();
}
public int BeginReadFields()
{
return this.ReadSimpleValue<byte>();
}
public T ReadSimpleValue<T>()
{
return (T)ReadSimpleValue(typeof(T));
}
public object ReadSimpleValue(Type type)
{
SilverlightSerializer.ReadAValue read;
if (!SilverlightSerializer.Readers.TryGetValue(type, out read))
{
return _reader.ReadInt32();
}
return read(_reader);
}
public bool IsMultiDimensionalArray(out int length)
{
var count = ReadSimpleValue<int>();
if (count == -1)
{
length = -1;
return true;
}
length = count;
return false;
}
public int BeginReadDictionary()
{
return ReadSimpleValue<int>(); ;
}
public void EndReadDictionary() { }
public int BeginReadObjectArray()
{
return ReadSimpleValue<int>();
}
public void EndReadObjectArray() { }
public void BeginReadMultiDimensionalArray(out int dimension, out int count)
{
//
//var dimensions = storage.ReadValue<int>("dimensions");
//var totalLength = storage.ReadValue<int>("length");
dimension = ReadSimpleValue<int>();
count = ReadSimpleValue<int>();
}
public void EndReadMultiDimensionalArray() { }
public int ReadArrayDimension(int index)
{
// //.ReadValue<int>("dim_len" + item);
return ReadSimpleValue<int>();
}
public int BeginReadList()
{
return ReadSimpleValue<int>();
}
public void EndReadList() { }
private int _currentObjectID = 0;
public int BeginReadObject(out bool isReference)
{
int result;
char knownType = this.ReadSimpleValue<char>();
if (knownType == 'O')
{
result = _currentObjectID;
_currentObjectID++;
isReference = false;
}
else
{
result = this.ReadSimpleValue<int>();
isReference = true;
}
return result;
}
#endregion reading
#region do nothing methods
public void EndWriteObjectArray() { }
public void EndWriteList() { }
public void EndWriteDictionary() { }
public void BeginWriteDictionaryKey(int id) { }
public void EndWriteDictionaryKey() { }
public void BeginWriteDictionaryValue(int id) { }
public void EndWriteDictionaryValue() { }
public void EndMultiDimensionArray() { }
public void EndReadObject() { }
public void BeginWriteListItem(int index) { }
public void EndWriteListItem() { }
public void BeginWriteObjectArrayItem(int index) { }
public void EndWriteObjectArrayItem() { }
public void EndReadProperties() { }
public void EndReadFields() { }
public void BeginReadListItem(int index) { }
public void EndReadListItem() { }
public void BeginReadDictionaryKeyItem(int index) { }
public void EndReadDictionaryKeyItem() { }
public void BeginReadDictionaryValueItem(int index) { }
public void EndReadDictionaryValueItem() { }
public void BeginReadObjectArrayItem(int index) { }
public void EndReadObjectArrayItem() { }
public void EndWriteObject() { }
public void BeginWriteProperty(string name, Type type) { }
public void EndWriteProperty() { }
public void BeginWriteField(string name, Type type) { }
public void EndWriteField() { }
public void EndWriteProperties() { }
public void EndWriteFields() { }
public void FinishSerializing(Entry entry) { }
#endregion do nothing methods
}
}
| zzgaminginc-pointofssale | Samba.Infrastructure.Data/BinarySerializer/SerializationUnits.cs | C# | gpl3 | 17,639 |
using System.Reflection;
namespace Serialization
{
public abstract class GetSet
{
public PropertyInfo Info;
public string Name;
public FieldInfo FieldInfo;
public object Vanilla;
public bool CollectionType;
public abstract object Get(object item);
public abstract void Set(object item, object value);
}
} | zzgaminginc-pointofssale | Samba.Infrastructure.Data/BinarySerializer/GetSet.cs | C# | gpl3 | 377 |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Serialization
{
public class GetWritableAttributes
{
private static readonly Dictionary<RuntimeTypeHandle, GetSet[][][]> PropertyAccess = new Dictionary<RuntimeTypeHandle, GetSet[][][]>();
/// <summary>
/// Dictionary of all the used objects to check if properties are different
/// to those set during construction
/// </summary>
private static readonly Dictionary<RuntimeTypeHandle, object> Vanilla = new Dictionary<RuntimeTypeHandle, object>();
public static Entry[] GetProperties(object obj)
{
var type = obj.GetType().TypeHandle;
var accessors = GetAccessors(type);
return (from a in accessors[0]
let value = a.Get(obj)
where value != null && (!(value is ICollection) || ((ICollection)value).Count > 0) && !value.Equals(a.Vanilla)
select new Entry()
{
PropertyInfo = a.Info,
MustHaveName = true,
Value = value
}).ToArray();
}
public static Entry[] GetFields(object obj)
{
var type = obj.GetType().TypeHandle;
var accessors = GetAccessors(type);
return (from a in accessors[1]
let value = a.Get(obj)
where value != null && (!(value is ICollection) || ((ICollection)value).Count >0) && !value.Equals(a.Vanilla)
select new Entry()
{
FieldInfo = a.FieldInfo,
MustHaveName = true,
Value = value
}).ToArray();
}
private static object GetVanilla(RuntimeTypeHandle type)
{
object vanilla;
lock (Vanilla)
{
if (!Vanilla.TryGetValue(type, out vanilla))
{
vanilla = SilverlightSerializer.CreateObject(Type.GetTypeFromHandle(type));
Vanilla[type] = vanilla;
}
}
return vanilla;
}
private static GetSet[][] GetAccessors(RuntimeTypeHandle type)
{
lock (PropertyAccess)
{
var index = (SilverlightSerializer.IsChecksum ? 1 : 0) + (SilverlightSerializer.IsChecksum && SilverlightSerializer.IgnoreIds ? 1 : 0);
GetSet[][][] collection;
if (!PropertyAccess.TryGetValue(type, out collection))
{
collection = new GetSet[3][][];
PropertyAccess[type] = collection;
}
var accessors = collection[index];
if (accessors == null)
{
var vanilla = GetVanilla(type);
var acs = new List<GetSet>();
var props = SilverlightSerializer.GetPropertyInfo(type);
foreach (var p in props)
{
var gs = typeof (GetSetGeneric<,>);
var tp = gs.MakeGenericType(new Type[] { Type.GetTypeFromHandle(type), p.PropertyType });
var getSet = (GetSet) Activator.CreateInstance(tp, new object[] {p});
getSet.Vanilla = getSet.Get(vanilla);
acs.Add(getSet);
}
accessors = new GetSet[2][];
accessors[0] = acs.ToArray();
acs.Clear();
var fields = SilverlightSerializer.GetFieldInfo(type);
foreach (var f in fields)
{
var gs = typeof (GetSetGeneric<,>);
var tp = gs.MakeGenericType(new Type[] { Type.GetTypeFromHandle(type), f.FieldType });
var getSet = (GetSet) Activator.CreateInstance(tp, new object[] {f});
getSet.Vanilla = getSet.Get(vanilla);
acs.Add(getSet);
}
accessors[1] = acs.ToArray();
collection[index] = accessors;
}
return accessors;
}
}
}
} | zzgaminginc-pointofssale | Samba.Infrastructure.Data/BinarySerializer/GetWritableAttributes.cs | C# | gpl3 | 4,567 |
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace Serialization
{
public class GetSetGeneric<T, TR> : GetSet
{
public delegate TR GetValue(T obj);
public delegate void SetValue(T obj, TR value);
private readonly GetValue _get;
private readonly SetValue _set;
public GetSetGeneric(PropertyInfo info)
{
MethodInfo getMethod;
MethodInfo setMethod = null;
Name = info.Name;
Info = info;
CollectionType = Info.PropertyType.GetInterface("IEnumerable", true) != null;
getMethod = info.GetGetMethod();
setMethod = info.GetSetMethod();
_get = (GetValue)Delegate.CreateDelegate(typeof(GetValue), getMethod);
if (setMethod != null) _set = (SetValue)Delegate.CreateDelegate(typeof(SetValue), setMethod);
}
public GetSetGeneric(FieldInfo info)
{
MethodInfo getMethod;
MethodInfo setMethod = null;
Name = info.Name;
FieldInfo = info;
_get = new GetValue(GetFieldValue);
_set = new SetValue(SetFieldValue);
CollectionType = FieldInfo.FieldType.GetInterface("IEnumerable", true) != null;
return;
}
public GetSetGeneric(string name)
{
Name = name;
MethodInfo getMethod;
MethodInfo setMethod= null;
var t = typeof(T);
var p = t.GetProperty(name);
if (p == null)
{
FieldInfo = typeof(T).GetField(Name);
_get = new GetValue(GetFieldValue);
_set = new SetValue(SetFieldValue);
CollectionType = FieldInfo.FieldType.GetInterface("IEnumerable", true) != null;
return;
}
Info = p;
CollectionType = Info.PropertyType.GetInterface("IEnumerable", true) != null;
getMethod = p.GetGetMethod();
setMethod = p.GetSetMethod();
_get = (GetValue)Delegate.CreateDelegate(typeof(GetValue), getMethod);
if(setMethod != null) _set = (SetValue)Delegate.CreateDelegate(typeof(SetValue), setMethod);
}
private TR GetFieldValue(T obj)
{
return (TR)FieldInfo.GetValue(obj);
}
private void SetFieldValue(T obj, TR value)
{
FieldInfo.SetValue(obj, value);
}
public override object Get(object item)
{
return _get((T)item);
}
public override void Set(object item, object value)
{
_set((T)item, (TR)value);
}
}
} | zzgaminginc-pointofssale | Samba.Infrastructure.Data/BinarySerializer/GetSetGeneric.cs | C# | gpl3 | 2,727 |
// SilverlightSerializer by Mike Talbot
// http://whydoidoit.com
// email: mike.talbot@alterian.com
// twitter: mike_talbot
//
// This code is free to use, no warranty is offered or implied.
// If you redistribute, please retain this header.
#region
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
#endregion
namespace Serialization
{
/// <summary>
/// Indicates that a property or field should not be serialized
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Class)]
public class DoNotSerialize : Attribute
{
}
/// <summary>
/// Used in checksum mode to flag a property as not being part
/// of the "meaning" of an object - i.e. two objects with the
/// same checksum "mean" the same thing, even if some of the
/// properties are different, those properties would not be
/// relevant to the purpose of the object
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public class DoNotChecksum : Attribute
{
}
/// <summary>
/// Attribute used to flag IDs this can be useful for check object
/// consistence when the serializer is in a mode that does not
/// serialize identifiers
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public class SerializerId : Attribute
{
}
/// <summary>
/// Always use an event to create instances of this type
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class CreateUsingEvent : Attribute
{
}
public interface ISerializeObject
{
object[] Serialize(object target);
object Deserialize(object[] data);
}
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class SerializerAttribute : Attribute
{
internal Type SerializesType;
public SerializerAttribute(Type serializesType)
{
SerializesType = serializesType;
}
}
/// <summary>
/// Silverlight/.NET compatible binary serializer with suppression support
/// produces compact representations, suitable for further compression
/// </summary>
public static class SilverlightSerializer
{
private static readonly Dictionary<RuntimeTypeHandle, IEnumerable<FieldInfo>> FieldLists = new Dictionary<RuntimeTypeHandle, IEnumerable<FieldInfo>>();
private static readonly Dictionary<RuntimeTypeHandle, IEnumerable<PropertyInfo>> PropertyLists = new Dictionary<RuntimeTypeHandle, IEnumerable<PropertyInfo>>();
private static readonly Dictionary<RuntimeTypeHandle, IEnumerable<PropertyInfo>> ChecksumLists = new Dictionary<RuntimeTypeHandle, IEnumerable<PropertyInfo>>();
[ThreadStatic]
internal static List<RuntimeTypeHandle> KnownTypes;
[ThreadStatic]
private static Dictionary<object, int> _seenObjects;
[ThreadStatic]
private static Dictionary<int, object> _loadedObjects;
[ThreadStatic]
internal static List<string> PropertyIds;
[ThreadStatic]
private static Stack<Dictionary<int, object>> _loStack;
[ThreadStatic]
private static Stack<Dictionary<object, int>> _soStack;
[ThreadStatic]
internal static Stack<List<RuntimeTypeHandle>> KtStack;
[ThreadStatic]
internal static Stack<List<string>> PiStack;
[ThreadStatic]
private static bool _isChecksum;
[ThreadStatic]
public static bool IgnoreIds;
[ThreadStatic]
public static bool IsReference;
public static T Copy<T>(T item)
{
return (T)Deserialize(Serialize(item));
}
/// <summary>
/// Arguments for a missing type event
/// </summary>
public class TypeMappingEventArgs : EventArgs
{
/// <summary>
/// The missing types name
/// </summary>
public string TypeName = String.Empty;
/// <summary>
/// Supply a type to use instead
/// </summary>
public Type UseType = null;
}
/// <summary>
/// Arguments for object creation event
/// </summary>
public class ObjectMappingEventArgs : EventArgs
{
/// <summary>
/// The type that cannot be
/// </summary>
public Type TypeToConstruct;
/// <summary>
/// Supply a type to use instead
/// </summary>
public object Instance = null;
}
/// <summary>
/// Event that is fired if a particular type cannot be instantiated
/// </summary>
public static event EventHandler<ObjectMappingEventArgs> CreateType;
internal static void InvokeCreateType(ObjectMappingEventArgs e)
{
EventHandler<ObjectMappingEventArgs> handler = CreateType;
if (handler != null)
handler(null, e);
}
/// <summary>
/// Event that is fired if a particular type cannot be found
/// </summary>
public static event EventHandler<TypeMappingEventArgs> MapMissingType;
internal static void InvokeMapMissingType(TypeMappingEventArgs e)
{
EventHandler<TypeMappingEventArgs> handler = MapMissingType;
if (handler != null)
handler(null, e);
}
/// <summary>
/// Put the serializer into Checksum mode
/// </summary>
public static bool IsChecksum
{
get
{
return _isChecksum;
}
set
{
_isChecksum = value;
}
}
//public static Type SerializerType
//{
// get;
// set;
//}
/// <summary>
/// Deserialize to a type
/// </summary>
/// <param name="array"></param>
/// <returns></returns>
public static T Deserialize<T>(byte[] array) where T : class
{
return Deserialize(array) as T;
}
/// <summary>
/// Deserialize from a stream to a type
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public static T Deserialize<T>(Stream stream) where T : class
{
return Deserialize(stream) as T;
}
/// <summary>
/// Get a checksum for an item. Checksums "should" be different
/// for every object that has a different "meaning". You can
/// flag properties as DoNotChecksum if that helps to keep decorative
/// properties away from the checksum whilst including meaningful ones
/// </summary>
/// <param name="item">The object to checksum</param>
/// <returns>A checksum string, this includes no illegal characters and can be used as a file name</returns>
public static string GetChecksum(object item)
{
if (item == null)
return "";
byte[] checksum = new byte[17];
checksum.Initialize();
var isChecksum = IsChecksum;
IsChecksum = true;
var toBytes = Serialize(item);
IsChecksum = isChecksum;
for (var i = 0; i < toBytes.Length; i++)
{
checksum[i & 15] ^= toBytes[i];
}
return item.GetType().Name + "-" + toBytes.Count().ToString() + "-" + Encode(checksum);
}
private static string Encode(byte[] checksum)
{
var s = Convert.ToBase64String(checksum);
return s.Aggregate("", (current, c) => current + (Char.IsLetterOrDigit(c)
? c
: Char.GetNumericValue(c)));
}
//Holds a reference to the custom serializers
private static readonly Dictionary<Type, ISerializeObject> Serializers = new Dictionary<Type, ISerializeObject>();
//Dictionary to ensure we only scan an assembly once
private static readonly Dictionary<Assembly, bool> Assemblies = new Dictionary<Assembly, bool>();
/// <summary>
/// Register all of the custom serializers in an assembly
/// </summary>
/// <param name="assembly">Leave blank to register the assembly that the method is called from, or pass an assembly</param>
public static void RegisterSerializationAssembly(Assembly assembly = null)
{
if (assembly == null)
assembly = Assembly.GetCallingAssembly();
if (Assemblies.ContainsKey(assembly))
return;
Assemblies[assembly] = true;
ScanAllTypesForAttribute((tp, attr) =>
{
Serializers[((SerializerAttribute)attr).SerializesType] = Activator.CreateInstance(tp) as ISerializeObject;
}, assembly, typeof(SerializerAttribute));
}
//Function to be called when scanning types
internal delegate void ScanTypeFunction(Type type, Attribute attribute);
/// <summary>
/// Scan all of the types in an assembly for a particular attribute
/// </summary>
/// <param name="function">The function to call</param>
/// <param name="assembly">The assembly to scan</param>
/// <param name="attribute">The attribute to look for</param>
internal static void ScanAllTypesForAttribute(ScanTypeFunction function, Assembly assembly, Type attribute = null)
{
try
{
foreach (var tp in assembly.GetTypes())
{
if (attribute != null)
{
var attrs = Attribute.GetCustomAttributes(tp, attribute, false);
if (attrs != null)
{
foreach (var attr in attrs)
function(tp, attr);
}
}
else
function(tp, null);
}
}
catch (Exception)
{
}
}
/// <summary>
/// Write persistence debugging information to the debug output window
/// often used with Verbose
/// </summary>
public static bool IsLoud;
/// <summary>
/// Write all types, even if they are known, often used with Loud mode
/// </summary>
public static bool Verbose;
/// <summary>
/// Caches and returns property info for a type
/// </summary>
/// <param name = "itm">The type that should have its property info returned</param>
/// <returns>An enumeration of PropertyInfo objects</returns>
/// <remarks>
/// It should be noted that the implementation converts the enumeration returned from reflection to an array as this more than double the speed of subsequent reads
/// </remarks>
internal static IEnumerable<PropertyInfo> GetPropertyInfo(RuntimeTypeHandle itm)
{
lock (PropertyLists)
{
IEnumerable<PropertyInfo> ret = null;
if (!IsChecksum)
{
if (!PropertyLists.TryGetValue(itm, out ret))
{
ret = Type.GetTypeFromHandle(itm).GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(p => p.PropertyType.GetCustomAttributes(typeof(DoNotSerialize), true).Count() == 0 && p.GetCustomAttributes(typeof(DoNotSerialize), true).Count() == 0 && !(p.GetIndexParameters().Count() > 0) && (p.GetSetMethod() != null)).ToArray();
PropertyLists[itm] = ret;
}
}
else
{
if (!ChecksumLists.TryGetValue(itm, out ret))
{
ret = Type.GetTypeFromHandle(itm).GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(p => p.PropertyType.GetCustomAttributes(typeof(DoNotSerialize), true).Count() == 0 && p.GetCustomAttributes(typeof(DoNotSerialize), true).Count() == 0 && p.GetCustomAttributes(typeof(DoNotChecksum), true).Count() == 0 && !(p.GetIndexParameters().Count() > 0) && (p.GetSetMethod() != null)).ToArray();
ChecksumLists[itm] = ret;
}
}
return IgnoreIds && ret != null
? ret.Where(p => p.GetCustomAttributes(typeof(SerializerId), true).Count() == 0)
: ret;
}
}
public static IEnumerable<PropertyInfo> GetProperties(Type item)
{
bool tempChecksum = IsChecksum;
bool tempIgnoreIds = IgnoreIds;
IsChecksum = false;
IgnoreIds = false;
IEnumerable<PropertyInfo> result = GetPropertyInfo(item.TypeHandle);
IsChecksum = tempChecksum;
IgnoreIds = tempIgnoreIds;
return result;
}
public static IEnumerable<FieldInfo> GetFields(Type item)
{
bool tempChecksum = IsChecksum;
bool tempIgnoreIds = IgnoreIds;
IsChecksum = false;
IgnoreIds = false;
IEnumerable<FieldInfo> result = GetFieldInfo(item.TypeHandle);
IsChecksum = tempChecksum;
IgnoreIds = tempIgnoreIds;
return result;
}
//static SilverlightSerializer()
//{
// SerializerType = typeof(BinarySerializer);
//}
/// <summary>
/// Caches and returns field info for a type
/// </summary>
/// <param name = "itm">The type that should have its field info returned</param>
/// <returns>An enumeration of FieldInfo objects</returns>
/// <remarks>
/// It should be noted that the implementation converts the enumeration returned from reflection to an array as this more than double the speed of subsequent reads
/// </remarks>
internal static IEnumerable<FieldInfo> GetFieldInfo(RuntimeTypeHandle itm)
{
lock (FieldLists)
{
IEnumerable<FieldInfo> ret = null;
if (FieldLists.ContainsKey(itm))
ret = FieldLists[itm];
else
{
ret = FieldLists[itm] = Type.GetTypeFromHandle(itm).GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetField).Where(p => p.FieldType.GetCustomAttributes(typeof(DoNotSerialize), true).Count() == 0 && p.GetCustomAttributes(typeof(DoNotSerialize), false).Count() == 0).ToArray();
}
return IsChecksum ? ret.Where(p => p.GetCustomAttributes(typeof(DoNotChecksum), true).Count() == 0) : ret;
}
}
/// <summary>
/// Returns a token that represents the name of the property
/// </summary>
/// <param name = "name">The name for which to return a token</param>
/// <returns>A 2 byte token representing the name</returns>
internal static ushort GetPropertyDefinitionId(string name)
{
lock (PropertyIds)
{
var ret = PropertyIds.IndexOf(name);
if (ret >= 0)
return (ushort)ret;
PropertyIds.Add(name);
return (ushort)(PropertyIds.Count - 1);
}
}
[ThreadStatic]
public static int currentVersion;
public static object Deserialize(IStorage storage)
{
bool v = Verbose;
Verbose = false;
CreateStacks();
try
{
KtStack.Push(KnownTypes);
PiStack.Push(PropertyIds);
_loStack.Push(_loadedObjects);
_loadedObjects = new Dictionary<int, object>();
IStorage serializer = storage;
serializer.StartDeserializing();
var ob = DeserializeObject(new Entry()
{
Name = "root"
}, serializer);
serializer.FinishedDeserializing();
return ob;
}
finally
{
IsReference = false;
KnownTypes = KtStack.Pop();
PropertyIds = PiStack.Pop();
_loadedObjects = _loStack.Pop();
Verbose = v;
}
}
/// <summary>
/// Deserializes from a stream, potentially into an existing instance
/// </summary>
/// <param name="inputStream">Stream to deserialize from</param>
/// <param name="instance">Instance to use</param>
/// <returns></returns>
public static object Deserialize(Stream inputStream, object instance = null)
{
// this version always uses the BinarySerializer
var v = Verbose;
CreateStacks();
try
{
KtStack.Push(KnownTypes);
PiStack.Push(PropertyIds);
_loStack.Push(_loadedObjects);
_loadedObjects = new Dictionary<int, object>();
var rw = new BinaryReader(inputStream);
var version = rw.ReadString();
currentVersion = Int32.Parse(version.Substring(4));
if (currentVersion >= 5)
{
inputStream.Position = 0;
BinarySerializer serializer = new BinarySerializer(rw.ReadBytes((int)inputStream.Length));
serializer.StartDeserializing();
var ob = DeserializeObject(new Entry()
{
Name = "root"
}, serializer);
serializer.FinishedDeserializing();
return ob;
}
var count = rw.ReadInt32();
if (currentVersion >= 3)
Verbose = rw.ReadBoolean();
PropertyIds = new List<string>();
KnownTypes = new List<RuntimeTypeHandle>();
for (var i = 0; i < count; i++)
{
var typeName = rw.ReadString();
var tp = Type.GetType(typeName);
if (tp == null)
{
var map = new TypeMappingEventArgs
{
TypeName = typeName
};
InvokeMapMissingType(map);
tp = map.UseType;
}
if (!Verbose)
if (tp == null)
throw new ArgumentException(String.Format("Cannot reference type {0} in this context", typeName));
KnownTypes.Add(tp.TypeHandle);
}
count = rw.ReadInt32();
for (var i = 0; i < count; i++)
{
PropertyIds.Add(rw.ReadString());
}
object obj = OldDeserializeObject(rw, null, instance);
return obj;
}
finally
{
IsReference = false;
KnownTypes = KtStack.Pop();
PropertyIds = PiStack.Pop();
_loadedObjects = _loStack.Pop();
Verbose = v;
}
}
/// <summary>
/// Convert a previously serialized object from a byte array
/// back into a .NET object
/// </summary>
/// <param name = "bytes">The data stream for the object</param>
/// <returns>The rehydrated object represented by the data supplied</returns>
public static object Deserialize(byte[] bytes)
{
using (MemoryStream inputStream = new MemoryStream(bytes))
{
return Deserialize(inputStream);
}
}
/// <summary>
/// Convert a previously serialized object from a byte array
/// back into a .NET object
/// </summary>
/// <param name = "bytes">The data stream for the object</param>
/// <returns>The rehydrated object represented by the data supplied</returns>
public static void DeserializeInto(byte[] bytes, object instance)
{
using (MemoryStream inputStream = new MemoryStream(bytes))
{
Deserialize(inputStream, instance);
}
}
/// <summary>
/// Creates a set of stacks on the current thread
/// </summary>
private static void CreateStacks()
{
if (PiStack == null)
PiStack = new Stack<List<string>>();
if (KtStack == null)
KtStack = new Stack<List<RuntimeTypeHandle>>();
if (_loStack == null)
_loStack = new Stack<Dictionary<int, object>>();
if (_soStack == null)
_soStack = new Stack<Dictionary<object, int>>();
}
#region Old Deserialization
/// <summary>
/// Deserializes an object or primitive from the stream
/// </summary>
/// <param name = "reader">The reader of the binary file</param>
/// <param name = "itemType">The expected type of the item being read (supports compact format)</param>
/// <returns>The value read from the file</returns>
/// <remarks>
/// The function is supplied with the type of the property that the object was stored in (if known) this enables
/// a compact format where types only have to be specified if they differ from the expected one
/// </remarks>
private static object OldDeserializeObject(BinaryReader reader, Type itemType = null, object instance = null)
{
var tpId = (ushort)reader.ReadUInt16();
if (tpId == 0xFFFE)
return null;
IsReference = false;
//Lookup the value type if necessary
if (tpId != 0xffff)
itemType = Type.GetTypeFromHandle(KnownTypes[tpId]);
object obj = null;
if (itemType != null)
{
//Check for custom serialization
if (Serializers.ContainsKey(itemType))
{
//Read the serializer and its data
var serializer = Serializers[itemType];
object[] data = OldDeserializeObject(reader, typeof(object[])) as object[];
return serializer.Deserialize(data);
}
//Check if this is a simple value and read it if so
if (IsSimpleType(itemType))
{
if (itemType.IsEnum)
{
return Enum.Parse(itemType, ReadValue(reader, typeof(int)).ToString(), true);
}
return ReadValue(reader, itemType);
}
}
//See if we should lookup this object or create a new one
var found = reader.ReadChar();
int refItemID;
if (found == 'S') //S is for Seen
{
IsReference = true;
refItemID = reader.ReadInt32();
return _loadedObjects[refItemID];
}
else
{
refItemID = _loadedObjects.Keys.Count;
}
if (itemType != null)
{
//Otherwise create the object
if (itemType.IsArray)
{
int baseCount = reader.ReadInt32();
if (baseCount == -1)
{
return OldDeserializeMultiDimensionArray(itemType, reader, baseCount);
}
else
{
return OldDeserializeArray(itemType, reader, baseCount);
}
}
obj = instance ?? CreateObject(itemType);
_loadedObjects.Add(refItemID, obj);
}
//Check for collection types)
if (obj is IDictionary)
return OldDeserializeDictionary(obj as IDictionary, itemType, reader);
if (obj is IList)
return OldDeserializeList(obj as IList, itemType, reader);
//Otherwise we are serializing an object
return OldDeserializeObjectAndProperties(obj, itemType, reader);
}
/// <summary>
/// Deserializes an array of values
/// </summary>
/// <param name = "itemType">The type of the array</param>
/// <param name = "reader">The reader of the stream</param>
/// <returns>The deserialized array</returns>
/// <remarks>
/// This routine optimizes for arrays of primitives and bytes
/// </remarks>
private static object OldDeserializeArray(Type itemType, BinaryReader reader, int count)
{
// If the count is -1 at this point, then it is being called from the
// deserialization of a multi-dimensional array - so we need
// to read the size of the array
if (count == -1)
{
count = reader.ReadInt32();
}
//Get the expected element type
var elementType = itemType.GetElementType();
//Optimize for byte arrays
if (elementType == typeof(byte))
{
var ret = reader.ReadBytes(count);
_loadedObjects.Add(_loadedObjects.Keys.Count, ret);
return ret;
}
//Create an array of the correct type
var array = Array.CreateInstance(elementType, count);
_loadedObjects.Add(_loadedObjects.Keys.Count, array);
//Check whether the array contains primitives, if it does we don't
//need to store the type of each member
if (IsSimpleType(elementType))
for (var l = 0; l < count; l++)
{
array.SetValue(ReadValue(reader, elementType), l);
}
else
for (var l = 0; l < count; l++)
{
array.SetValue(OldDeserializeObject(reader, elementType), l);
}
return array;
}
/// <summary>
/// Deserializes a multi-dimensional array of values
/// </summary>
/// <param name = "itemType">The type of the array</param>
/// <param name = "reader">The reader of the stream</param>
/// <param name="count">The base size of the multi-dimensional array</param>
/// <returns>The deserialized array</returns>
/// <remarks>
/// This routine deserializes values serialized on a 'row by row' basis, and
/// calls into DeserializeArray to do this
/// </remarks>
private static object OldDeserializeMultiDimensionArray(Type itemType, BinaryReader reader, int count)
{
//Read the number of dimensions the array has
var dimensions = reader.ReadInt32();
var totalLength = reader.ReadInt32();
int rowLength = 0;
// Establish the length of each array element
// and get the total 'row size'
int[] lengths = new int[dimensions];
int[] indices = new int[dimensions];
for (int item = 0; item < dimensions; item++)
{
lengths[item] = reader.ReadInt32();
rowLength += lengths[item];
indices[item] = 0;
}
int cols = lengths[lengths.Length - 1];
//int cols = dimensions == 1 ? 1 : lengths[lengths.Length - 1];
//Get the expected element type
var elementType = itemType.GetElementType();
Array sourceArrays = Array.CreateInstance(elementType, lengths);
OldDeserializeArrayPart(sourceArrays, 0, indices, itemType, reader);
return sourceArrays;
}
private static void OldDeserializeArrayPart(Array sourceArrays, int i, int[] indices, Type itemType, BinaryReader binaryReader)
{
int length = sourceArrays.GetLength(i);
for (var l = 0; l < length; l++)
{
indices[i] = l;
if (i != sourceArrays.Rank - 2)
OldDeserializeArrayPart(sourceArrays, i + 1, indices, itemType, binaryReader);
else
{
Array sourceArray = (Array)OldDeserializeArray(itemType, binaryReader, -1);
int cols = sourceArrays.GetLength(i + 1);
for (int arrayStartIndex = 0; arrayStartIndex < cols; arrayStartIndex++)
{
indices[i + 1] = arrayStartIndex;
sourceArrays.SetValue(sourceArray.GetValue(arrayStartIndex), indices);
}
}
}
}
/// <summary>
/// Deserializes a dictionary from storage, handles generic types with storage optimization
/// </summary>
/// <param name = "o">The newly created dictionary</param>
/// <param name = "itemType">The type of the dictionary</param>
/// <param name = "reader">The binary reader for the current bytes</param>
/// <returns>The dictionary object updated with the values from storage</returns>
private static object OldDeserializeDictionary(IDictionary o, Type itemType, BinaryReader reader)
{
Type keyType = null;
Type valueType = null;
if (itemType.IsGenericType)
{
var types = itemType.GetGenericArguments();
keyType = types[0];
valueType = types[1];
}
var count = reader.ReadInt32();
var list = new List<object>();
for (var i = 0; i < count; i++)
{
list.Add(OldDeserializeObject(reader, keyType));
}
for (var i = 0; i < count; i++)
{
o[list[i]] = OldDeserializeObject(reader, valueType);
}
return o;
}
/// <summary>
/// Deserialize a list from the data stream
/// </summary>
/// <param name = "o">The newly created list</param>
/// <param name = "itemType">The type of the list</param>
/// <param name = "reader">The reader for the current bytes</param>
/// <returns>The list updated with values from the stream</returns>
private static object OldDeserializeList(IList o, Type itemType, BinaryReader reader)
{
Type valueType = null;
if (itemType.IsGenericType)
{
var types = itemType.GetGenericArguments();
valueType = types[0];
}
var count = reader.ReadInt32();
var list = new List<object>();
for (var i = 0; i < count; i++)
{
o.Add(OldDeserializeObject(reader, valueType));
}
return o;
}
/// <summary>
/// Deserializes a class based object that is not a collection, looks for both public properties and fields
/// </summary>
/// <param name = "o">The object being deserialized</param>
/// <param name = "itemType">The type of the object</param>
/// <param name = "reader">The reader for the current stream of bytes</param>
/// <returns>The object updated with values from the stream</returns>
private static object OldDeserializeObjectAndProperties(object o, Type itemType, BinaryReader reader)
{
OldDeserializeProperties(reader, itemType, o);
OldDeserializeFields(reader, itemType, o);
return o;
}
/// <summary>
/// Deserializes the properties of an object from the stream
/// </summary>
/// <param name = "reader">The reader of the bytes in the stream</param>
/// <param name = "itemType">The type of the object</param>
/// <param name = "o">The object to deserialize</param>
private static void OldDeserializeProperties(BinaryReader reader, Type itemType, object o)
{
//Get the number of properties
var propCount = reader.ReadByte();
int length = 0;
if (Verbose)
length = reader.ReadInt32();
if (o == null)
{
reader.BaseStream.Seek(length, SeekOrigin.Current);
return;
}
for (var i = 0; i < propCount; i++)
{
//Get a property name identifier
var propId = reader.ReadUInt16();
//Lookup the name
var propName = PropertyIds[propId];
//Use the name to find the type
var propType = itemType.GetProperty(propName);
//Deserialize the value
var value = OldDeserializeObject(reader, propType != null ? propType.PropertyType : null);
if (propType != null && value != null)
{
try
{
if (propType.PropertyType == typeof(string))
{
propType.SetValue(o, value.ToString(), null);
}
else
propType.SetValue(o, value, null);
}
catch (Exception)
{
//Suppress cases where the old value is no longer compatible with the new property type
}
}
}
}
/// <summary>
/// Deserializes the fields of an object from the stream
/// </summary>
/// <param name = "reader">The reader of the bytes in the stream</param>
/// <param name = "itemType">The type of the object</param>
/// <param name = "o">The object to deserialize</param>
private static void OldDeserializeFields(BinaryReader reader, Type itemType, object o)
{
var fieldCount = reader.ReadByte();
int length = 0;
if (Verbose)
length = reader.ReadInt32();
if (o == null)
{
reader.BaseStream.Seek(length, SeekOrigin.Current);
return;
}
for (var i = 0; i < fieldCount; i++)
{
var fieldId = reader.ReadUInt16();
var fieldName = PropertyIds[fieldId];
var fieldType = itemType.GetField(fieldName);
var value = OldDeserializeObject(reader, fieldType != null ? fieldType.FieldType : null);
if (fieldType != null && value != null)
{
try
{
fieldType.SetValue(o, value);
}
catch (Exception)
{
//Suppress cases where the old value is no longer compatible with the new property type
}
}
}
}
#endregion
#region New Deserialization
/// <summary>
/// Deserializes an object or primitive from the stream
/// </summary>
/// <param name="entry"></param>
/// <param name="storage"></param>
/// <returns>The value read from the file</returns>
/// <remarks>
/// The function is supplied with the type of the property that the object was stored in (if known) this enables
/// a compact format where types only have to be specified if they differ from the expected one
/// </remarks>
private static object DeserializeObject(Entry entry, IStorage storage)
{
//Get a name for the item
storage.DeserializeGetName(entry);
//Update the core info including a property getter
if (entry.MustHaveName) UpdateEntryWithName(entry);
//Start to deserialize
var candidate = storage.StartDeserializing(entry);
if (candidate != null)
{
storage.FinishDeserializing(entry);
return candidate;
}
var itemType = entry.StoredType;
if (itemType == null)
return null;
IsReference = false;
object obj = null;
//Check for custom serialization
if (Serializers.ContainsKey(itemType))
{
//Read the serializer and its data
var serializer = Serializers[itemType];
var data =
(object[])
DeserializeObject(new Entry()
{
Name = "data",
StoredType = typeof(object[])
}, storage);
object result = serializer.Deserialize(data);
storage.FinishDeserializing(entry);
return result;
}
//Check if this is a simple value and read it if so
if (IsSimpleType(itemType))
{
if (itemType.IsEnum)
{
//return Enum.Parse(itemType, storage.ReadValue<int>("value").ToString(), true);
//return Enum.Parse(itemType, storage.ReadSimpleValue<int>().ToString(), true);
//return Convert.ChangeType(storage.ReadSimpleValue(Enum.GetUnderlyingType(itemType)), itemType, System.Globalization.CultureInfo.InvariantCulture);
return Enum.Parse(itemType, storage.ReadSimpleValue(Enum.GetUnderlyingType(itemType)).ToString(), true);
}
return storage.ReadSimpleValue(itemType);
}
//See if we should lookup this object or create a new one
bool isReference;
int objectID = storage.BeginReadObject(out isReference);
if (isReference)
{
IsReference = true;
storage.EndReadObject();
storage.FinishDeserializing(entry);
if (storage.SupportsOnDemand && !_loadedObjects.ContainsKey(objectID))
{
storage.BeginOnDemand(objectID);
_loadedObjects[objectID] = DeserializeObject(entry, storage);
storage.EndOnDemand();
}
return _loadedObjects[objectID];
}
else if (storage.SupportsOnDemand)
{
if (_loadedObjects.ContainsKey(objectID))
{
obj = _loadedObjects[objectID];
storage.EndReadObject();
storage.FinishDeserializing(entry);
return obj;
}
}
//Otherwise create the object
if (itemType.IsArray)
{
int baseCount;
bool isMultiDimensionArray = storage.IsMultiDimensionalArray(out baseCount);
if (isMultiDimensionArray)
{
object result = DeserializeMultiDimensionArray(itemType, storage, objectID);
storage.EndReadObject();
storage.FinishDeserializing(entry);
return result;
}
else
{
object result = DeserializeArray(itemType, storage, baseCount, objectID);
storage.EndReadObject();
storage.FinishDeserializing(entry);
return result;
}
}
obj = entry.Value ?? CreateObject(itemType);
_loadedObjects[objectID] = obj;
//Check for collection types)
if (obj is IDictionary)
{
object result = DeserializeDictionary(obj as IDictionary, itemType, storage);
storage.EndReadObject();
storage.FinishDeserializing(entry);
return result;
}
if (obj is IList)
{
object result = DeserializeList(obj as IList, itemType, storage);
storage.EndReadObject();
storage.FinishDeserializing(entry);
return result;
}
//Otherwise we are serializing an object
object result2 = DeserializeObjectAndProperties(obj, itemType, storage);
storage.EndReadObject();
storage.FinishDeserializing(entry);
//Check for null
if (obj is Nuller)
{
return null;
}
return result2;
}
/// <summary>
/// Deserializes an array of values
/// </summary>
/// <param name = "itemType">The type of the array</param>
/// <param name="storage"></param>
/// <param name="count"></param>
/// <returns>The deserialized array</returns>
/// <remarks>
/// This routine optimizes for arrays of primitives and bytes
/// </remarks>
private static object DeserializeArray(Type itemType, IStorage storage, int count, int objectID)
{
Type elementType = itemType.GetElementType();
Array result = null;
if (IsSimpleType(elementType))
{
result = storage.ReadSimpleArray(elementType, count);
_loadedObjects[objectID] = result;
}
else
{
result = Array.CreateInstance(elementType, count);
_loadedObjects[objectID] = result;
if (count == -1)
{
count = storage.BeginReadObjectArray();
}
for (var l = 0; l < count; l++)
{
storage.BeginReadObjectArrayItem(l);
result.SetValue(DeserializeObject(new Entry()
{
Name = "array_entry" + l,
StoredType = elementType
}, storage), l);
storage.EndReadObjectArrayItem();
}
storage.EndReadObjectArray();
}
return result;
}
/// <summary>
/// Deserializes a multi-dimensional array of values
/// </summary>
/// <param name = "itemType">The type of the array</param>
/// <param name="storage"></param>
/// <param name="count">The base size of the multi-dimensional array</param>
/// <returns>The deserialized array</returns>
/// <remarks>
/// This routine deserializes values serialized on a 'row by row' basis, and
/// calls into DeserializeArray to do this
/// </remarks>
private static object DeserializeMultiDimensionArray(Type itemType, IStorage storage, int objectID)
{
//Read the number of dimensions the array has
//var dimensions = storage.ReadValue<int>("dimensions");
//var totalLength = storage.ReadValue<int>("length");
int dimensions, totalLength, rowLength;
storage.BeginReadMultiDimensionalArray(out dimensions, out totalLength);
rowLength = 0;
// Establish the length of each array element
// and get the total 'row size'
int[] lengths = new int[dimensions];
int[] indices = new int[dimensions];
for (int item = 0; item < dimensions; item++)
{
lengths[item] = storage.ReadArrayDimension(item); //.ReadValue<int>("dim_len" + item);
rowLength += lengths[item];
indices[item] = 0;
}
int cols = lengths[lengths.Length - 1];
//int cols = dimensions == 1 ? 1 : lengths[lengths.Length - 1];
//Get the expected element type
var elementType = itemType.GetElementType();
Array sourceArrays = Array.CreateInstance(elementType, lengths);
DeserializeArrayPart(sourceArrays, 0, indices, itemType, storage, objectID);
return sourceArrays;
}
private static void DeserializeArrayPart(Array sourceArrays, int i, int[] indices, Type itemType, IStorage storage, int objectID)
{
int length = sourceArrays.GetLength(i);
for (var l = 0; l < length; l++)
{
indices[i] = l;
if (i != sourceArrays.Rank - 2)
DeserializeArrayPart(sourceArrays, i + 1, indices, itemType, storage, objectID);
else
{
Array sourceArray = (Array)DeserializeArray(itemType, storage, -1, objectID);
int cols = sourceArrays.GetLength(i + 1);
for (int arrayStartIndex = 0; arrayStartIndex < cols; arrayStartIndex++)
{
indices[i + 1] = arrayStartIndex;
sourceArrays.SetValue(sourceArray.GetValue(arrayStartIndex), indices);
}
}
}
}
/// <summary>
/// Deserializes a dictionary from storage, handles generic types with storage optimization
/// </summary>
/// <param name = "o">The newly created dictionary</param>
/// <param name = "itemType">The type of the dictionary</param>
/// <param name="storage"></param>
/// <returns>The dictionary object updated with the values from storage</returns>
private static object DeserializeDictionary(IDictionary o, Type itemType, IStorage storage)
{
Type keyType = null;
Type valueType = null;
if (itemType.IsGenericType)
{
var types = itemType.GetGenericArguments();
keyType = types[0];
valueType = types[1];
}
//var count = storage.ReadValue<int>("no_items");
//int count = storage.G
//int count = storage.BeginRead();
//int count = storage.GetItemCount<int>();
int count = storage.BeginReadDictionary();
var list = new List<object>();
for (var i = 0; i < count; i++)
{
storage.BeginReadDictionaryKeyItem(i);
list.Add(DeserializeObject(new Entry()
{
Name = "dic_key" + i,
StoredType = keyType
}, storage));
storage.EndReadDictionaryKeyItem();
}
for (var i = 0; i < count; i++)
{
storage.BeginReadDictionaryValueItem(i);
o[list[i]] = DeserializeObject(new Entry()
{
Name = "dic_value" + i,
StoredType = valueType
}, storage);
storage.EndReadDictionaryValueItem();
}
storage.EndReadDictionary();
if (currentVersion >= 7)
DeserializeObjectAndProperties(o, itemType, storage);
return o;
}
/// <summary>
/// Deserialize a list from the data stream
/// </summary>
/// <param name = "o">The newly created list</param>
/// <param name = "itemType">The type of the list</param>
/// <param name="storage"></param>
/// <returns>The list updated with values from the stream</returns>
private static object DeserializeList(IList o, Type itemType, IStorage storage)
{
Type valueType = null;
if (itemType.IsGenericType)
{
var types = itemType.GetGenericArguments();
valueType = types[0];
}
//var count = storage.ReadValue<int>("no_items");
//int count = storage.BeginRead();
int count = storage.BeginReadList();
var list = new List<object>();
for (var i = 0; i < count; i++)
{
storage.BeginReadListItem(i);
o.Add(DeserializeObject(new Entry()
{
Name = "list_item" + i,
StoredType = valueType
}, storage));
storage.EndReadListItem();
}
storage.EndReadList();
if (currentVersion >= 7)
DeserializeObjectAndProperties(o, itemType, storage);
return o;
}
/// <summary>
/// Deserializes a class based object that is not a collection, looks for both public properties and fields
/// </summary>
/// <param name = "o">The object being deserialized</param>
/// <param name = "itemType">The type of the object</param>
/// <param name="storage"></param>
/// <returns>The object updated with values from the stream</returns>
private static object DeserializeObjectAndProperties(object o, Type itemType, IStorage storage)
{
DeserializeProperties(storage, itemType, o);
DeserializeFields(storage, itemType, o);
return o;
}
/// <summary>
/// Deserializes the properties of an object from the stream
/// </summary>
/// <param name="storage"></param>
/// <param name = "itemType">The type of the object</param>
/// <param name = "o">The object to deserialize</param>
private static void DeserializeProperties(IStorage storage, Type itemType, object o)
{
//Get the number of properties
//var propCount = storage.ReadValue<byte>("property_count");
int propCount = storage.BeginReadProperties();
for (var i = 0; i < propCount; i++)
{
//Deserialize the value
Entry entry = storage.BeginReadProperty(new Entry()
{
OwningType = itemType,
MustHaveName = true
});
var value = DeserializeObject(entry, storage);
if (entry.Setter != null && value != null)
{
try
{
entry.Setter.Set(o, value);
}
catch (ArgumentException)
{
try
{
// if the property is nullable enum we need to handle it differently because a straight ChangeType doesn't work
// TODO maybe adjust persistence to have a nullable bit in propertyindex?
Type type = Nullable.GetUnderlyingType(entry.Setter.Info.PropertyType);
if (type != null && type.IsEnum)
{
entry.Setter.Info.SetValue(o, Enum.Parse(type, value.ToString(), true), null);
}
else
{
entry.Setter.Info.SetValue(o, Convert.ChangeType(value, entry.Setter.Info.PropertyType, null), null);
}
}
catch
{
}
}
catch (Exception)
{
//Suppress cases where the old value is no longer compatible with the new property type
}
}
storage.EndReadProeprty();
}
storage.EndReadProperties();
}
/// <summary>
/// Deserializes the fields of an object from the stream
/// </summary>
/// <param name = "reader">The reader of the bytes in the stream</param>
/// <param name = "itemType">The type of the object</param>
/// <param name = "o">The object to deserialize</param>
private static void DeserializeFields(IStorage storage, Type itemType, object o)
{
//var fieldCount = storage.ReadValue<byte>("field_count");
int fieldCount = storage.BeginReadFields();
//int length = 0;
for (var i = 0; i < fieldCount; i++)
{
Entry entry = storage.BeginReadField(new Entry()
{
OwningType = itemType,
MustHaveName = true
});
var value = DeserializeObject(entry, storage);
if (entry.Setter != null && value != null)
{
try
{
entry.Setter.Set(o, value);
}
catch (ArgumentException)
{
try
{
// if the property is nullable enum we need to handle it differently because a straight ChangeType doesn't work
Type type = Nullable.GetUnderlyingType(entry.Setter.FieldInfo.FieldType);
if (type != null && type.IsEnum)
{
entry.Setter.FieldInfo.SetValue(o, Enum.Parse(type, value.ToString(), true));
}
else
{
entry.Setter.FieldInfo.SetValue(o, Convert.ChangeType(value, entry.Setter.FieldInfo.FieldType, null));
}
}
catch
{
}
}
catch (Exception)
{
//Suppress cases where the old value is no longer compatible with the new property type
}
}
storage.EndReadField();
}
storage.EndReadFields();
}
#endregion
public static void Serialize(object item, IStorage storage)
{
bool verbose = Verbose;
Verbose = false;
CreateStacks();
try
{
_soStack.Push(_seenObjects);
_seenObjects = new Dictionary<object, int>();
storage.StartSerializing();
SerializeObject(new Entry()
{
Name = "root",
Value = item
}, storage);
storage.FinishedSerializing();
}
finally
{
_seenObjects = _soStack.Pop();
Verbose = verbose;
}
}
public static void Serialize(object item, Stream outputStream)
{
CreateStacks();
try
{
_soStack.Push(_seenObjects);
_seenObjects = new Dictionary<object, int>();
//var serializer = Activator.CreateInstance(SerializerType) as IStorage;
BinarySerializer serializer = new BinarySerializer();
serializer.StartSerializing();
SerializeObject(new Entry()
{
Name = "root",
Value = item
}, serializer);
serializer.FinishedSerializing();
var outputWr = new BinaryWriter(outputStream);
outputWr.Write(serializer.Data);
}
finally
{
_seenObjects = _soStack.Pop();
}
}
/// <summary>
/// Serialize an object into an array of bytes
/// </summary>
/// <param name = "item">The object to serialize</param>
/// <returns>A byte array representation of the item</returns>
public static byte[] Serialize(object item)
{
using (MemoryStream outputStream = new MemoryStream())
{
Serialize(item, outputStream);
//Reset the verbose mode
return outputStream.ToArray();
}
}
/// <summary>
/// Serialize an object into an array of bytes
/// </summary>
/// <param name = "item">The object to serialize</param>
/// <param name="makeVerbose">Whether the object should be serialized for forwards compatibility</param>
/// <returns>A byte array representation of the item</returns>
public static byte[] Serialize(object item, bool makeVerbose)
{
using (MemoryStream outputStream = new MemoryStream())
{
var v = Verbose;
Verbose = makeVerbose;
Serialize(item, outputStream);
Verbose = v;
//Reset the verbose mode
return outputStream.ToArray();
}
}
#region Serialization
public class Nuller
{
}
private static void SerializeObject(Entry entry, IStorage storage)
{
if (entry.Value == null)
entry.Value = new Nuller();
var item = entry.Value;
if (storage.StartSerializing(entry, _seenObjects.Count))
{
_seenObjects[item] = _seenObjects.Count;
return;
}
var itemType = item.GetType();
//Check for custom serialization
if (Serializers.ContainsKey(itemType))
{
//If we have a custom serializer then use it!
var serializer = Serializers[itemType];
var data = serializer.Serialize(item);
SerializeObject(new Entry()
{
Name = "data",
Value = data,
StoredType = typeof(object[])
}, storage);
return;
}
//Check for simple types again
if (IsSimpleType(itemType))
{
storage.WriteSimpleValue(itemType.IsEnum ? Convert.ChangeType(item, Enum.GetUnderlyingType(itemType), CultureInfo.InvariantCulture) : item);
return;
}
//Check whether this object has been seen
if (_seenObjects.ContainsKey(item))
{
storage.BeginWriteObject(_seenObjects[item], item.GetType(), true);
storage.EndWriteObject();
return;
}
//We are going to serialize an object
_seenObjects[item] = _seenObjects.Count;
storage.BeginWriteObject(_seenObjects[item], item.GetType(), false);
//Check for collection types)
if (item is Array)
{
if (((Array)item).Rank == 1)
{
SerializeArray(item as Array, itemType, storage);
}
else
{
SerializeMultiDimensionArray(item as Array, itemType, storage);
}
storage.EndWriteObject();
return;
}
if (item is IDictionary)
{
SerializeDictionary(item as IDictionary, itemType, storage);
storage.EndWriteObject();
return;
}
if (item is IList)
{
SerializeList(item as IList, itemType, storage);
storage.EndWriteObject();
return;
}
//Otherwise we are serializing an object
SerializeObjectAndProperties(item, itemType, storage);
storage.EndWriteObject();
storage.FinishSerializing(entry);
}
private static void SerializeList(IList item, Type tp, IStorage storage)
{
Type valueType = null;
//Try to optimize the storage of types based on the type of list
if (tp.IsGenericType)
{
var types = tp.GetGenericArguments();
valueType = types[0];
}
//storage.WriteValue("no_items", item.Count);
storage.BeginWriteList(item.Count, item.GetType());
int i = 0;
Entry entry = new Entry();
foreach (var val in item.Cast<object>().ToArray())
{
storage.BeginWriteListItem(i);
entry.Name = "list_item" + i++;
entry.Value = val;
entry.StoredType = valueType;
SerializeObject(entry, storage);
storage.EndWriteListItem();
}
storage.EndWriteList();
SerializeObjectAndProperties(item, tp, storage);
}
private static void SerializeDictionary(IDictionary item, Type tp, IStorage storage)
{
Type keyType = null;
Type valueType = null;
//Try to optimise storage based on the type of dictionary
if (tp.IsGenericType)
{
var types = tp.GetGenericArguments();
keyType = types[0];
valueType = types[1];
}
//storage.WriteValue("no_items", item.Count);
storage.BeginWriteDictionary(item.Count, item.GetType());
//Serialize the pairs
var i = 0;
foreach (var key in item.Keys)
{
storage.BeginWriteDictionaryKey(i);
SerializeObject(new Entry()
{
Name = "dic_key" + i++,
StoredType = keyType,
Value = key
}, storage);
storage.EndWriteDictionaryKey();
}
i = 0;
foreach (var val in item.Values)
{
storage.BeginWriteDictionaryValue(i);
SerializeObject(new Entry()
{
Name = "dic_value" + i++,
StoredType = valueType,
Value = val
}, storage);
storage.EndWriteDictionaryValue();
}
storage.EndWriteDictionary();
SerializeObjectAndProperties(item, tp, storage);
}
private static void SerializeArray(Array item, Type tp, IStorage storage)
{
Type elementType = tp.GetElementType();
//if (propertyType == typeof(byte))
//{
// storage.WriteSimpleArray(item.Length, item);
//}
//else
if (IsSimpleType(elementType))
{
storage.WriteSimpleArray(item.Length, item);
}
else
{
int length = item.Length;
storage.BeginWriteObjectArray(length, item.GetType());
for (int l = 0; l < length; l++)
{
storage.BeginWriteObjectArrayItem(l);
SerializeObject(new Entry()
{
Name = "array_entry" + l,
Value = item.GetValue(l),
StoredType = elementType
}, storage);
storage.EndWriteObjectArrayItem();
}
storage.EndWriteObjectArray();
}
}
private static void SerializeMultiDimensionArray(Array item, Type tp, IStorage storage)
{
// Multi-dimension serializer data is:
// Int32: Ranks
// Int32 (x number of ranks): length of array dimension
int dimensions = item.Rank;
var length = item.GetLength(0);
// Determine the number of cols being populated
var cols = item.GetLength(item.Rank - 1);
// Explicitly write this value, to denote that this is a multi-dimensional array
// so it doesn't break the deserializer when reading values for existing arrays
//storage.WriteValue("no_items", (int)-1);
//storage.WriteValue("dimensions", dimensions);
//storage.WriteValue("length", item.Length);
storage.BeginMultiDimensionArray(item.GetType(), dimensions, length);
Type propertyType = tp.GetElementType();
int[] indicies = new int[dimensions];
// Write out the length of each array, if we are dealing with the first array
for (int arrayStartIndex = 0; arrayStartIndex < dimensions; arrayStartIndex++)
{
indicies[arrayStartIndex] = 0;
//storage.WriteValue("dim_len" + arrayStartIndex, item.GetLength(arrayStartIndex));
storage.WriteArrayDimension(arrayStartIndex, item.GetLength(arrayStartIndex));
}
SerializeArrayPart(item, 0, indicies, storage);
storage.EndMultiDimensionArray();
}
private static void SerializeArrayPart(Array item, int i, int[] indices, IStorage storage)
{
var length = item.GetLength(i);
for (var l = 0; l < length; l++)
{
indices[i] = l;
if (i != item.Rank - 2)
SerializeArrayPart(item, i + 1, indices, storage);
else
{
Type arrayType = item.GetType().GetElementType();
var cols = item.GetLength(i + 1);
var baseArray = Array.CreateInstance(arrayType, cols);
// Convert the whole multi-dimensional array to be 'row' based
// and serialize using the existing code
for (int arrayStartIndex = 0; arrayStartIndex < cols; arrayStartIndex++)
{
indices[i + 1] = arrayStartIndex;
baseArray.SetValue(item.GetValue(indices), arrayStartIndex);
}
SerializeArray(baseArray, baseArray.GetType(), storage);
}
}
}
private static void WriteProperties(Type itemType, object item, IStorage storage)
{
Entry[] propList = storage.ShouldWriteProperties(GetWritableAttributes.GetProperties(item));
storage.BeginWriteProperties(propList.Length);
foreach (Entry entry in propList)
{
storage.BeginWriteProperty(entry.PropertyInfo.Name, entry.PropertyInfo.PropertyType);
SerializeObject(entry, storage);
storage.EndWriteProperty();
}
storage.EndWriteProperties();
}
private static void WriteFields(Type itemType, object item, IStorage storage)
{
Entry[] fieldList = storage.ShouldWriteFields(GetWritableAttributes.GetFields(item));
storage.BeginWriteFields(fieldList.Length);
foreach (Entry entry in fieldList)
{
storage.BeginWriteField(entry.FieldInfo.Name, entry.FieldInfo.FieldType);
SerializeObject(entry, storage);
storage.EndWriteField();
}
storage.EndWriteFields();
}
#endregion
/// <summary>
/// Return whether the type specified is a simple type that can be serialized fast
/// </summary>
/// <param name = "tp">The type to check</param>
/// <returns>True if the type is a simple one and can be serialized directly</returns>
private static bool IsSimpleType(Type tp)
{
return tp.IsPrimitive || tp == typeof(DateTime) || tp == typeof(TimeSpan) || tp == typeof(string) || tp.IsEnum || tp == typeof(Guid) || tp == typeof(decimal);
}
private static void SerializeObjectAndProperties(object item, Type itemType, IStorage storage)
{
WriteProperties(itemType, item, storage);
WriteFields(itemType, item, storage);
}
/// <summary>
/// Create an instance of a type
/// </summary>
/// <param name="itemType">The type to construct</param>
/// <returns></returns>
internal static object CreateObject(Type itemType)
{
try
{
return itemType.IsDefined(typeof(CreateUsingEvent), false) ? CreateInstance(itemType) : Activator.CreateInstance(itemType);
}
catch (Exception)
{
try
{
var constructorInfo = itemType.GetConstructor(new Type[] { });
return constructorInfo != null ? constructorInfo.Invoke(new object[] { }) : CreateInstance(itemType);
}
catch
{
return CreateInstance(itemType);
}
}
}
private static object CreateInstance(Type itemType)
{
//Raise an event to construct the object
var ct = new ObjectMappingEventArgs();
ct.TypeToConstruct = itemType;
InvokeCreateType(ct);
//Check if we created the right thing
if (ct.Instance != null && (ct.Instance.GetType() == itemType || ct.Instance.GetType().IsSubclassOf(itemType)))
{
return ct.Instance;
}
var error = string.Format("Could not construct an object of type '{0}', it must be creatable in this scope and have a default parameterless constructor or you should handle the CreateType event on SilverlightSerializer to construct the object", itemType.FullName);
throw new MissingConstructorException(error);
}
public class MissingConstructorException : Exception
{
public MissingConstructorException(string message)
: base(message)
{
}
}
#region Basic IO
private delegate void WriteAValue(BinaryWriter writer, object value);
public delegate object ReadAValue(BinaryReader reader);
private static readonly Dictionary<Type, WriteAValue> Writers = new Dictionary<Type, WriteAValue>();
public static readonly Dictionary<Type, ReadAValue> Readers = new Dictionary<Type, ReadAValue>();
static SilverlightSerializer()
{
Writers[typeof(string)] = StringWriter;
Writers[typeof(Decimal)] = DecimalWriter;
Writers[typeof(float)] = FloatWriter;
Writers[typeof(byte[])] = ByteArrayWriter;
Writers[typeof(bool)] = BoolWriter;
Writers[typeof(Guid)] = GuidWriter;
Writers[typeof(DateTime)] = DateTimeWriter;
Writers[typeof(TimeSpan)] = TimeSpanWriter;
Writers[typeof(char)] = CharWriter;
Writers[typeof(ushort)] = UShortWriter;
Writers[typeof(double)] = DoubleWriter;
Writers[typeof(ulong)] = ULongWriter;
Writers[typeof(int)] = IntWriter;
Writers[typeof(uint)] = UIntWriter;
Writers[typeof(byte)] = ByteWriter;
Writers[typeof(long)] = LongWriter;
Writers[typeof(short)] = ShortWriter;
Writers[typeof(sbyte)] = SByteWriter;
Readers[typeof(string)] = AStringReader;
Readers[typeof(Decimal)] = DecimalReader;
Readers[typeof(float)] = FloatReader;
Readers[typeof(byte[])] = ByteArrayReader;
Readers[typeof(bool)] = BoolReader;
Readers[typeof(Guid)] = GuidReader;
Readers[typeof(DateTime)] = DateTimeReader;
Readers[typeof(TimeSpan)] = TimeSpanReader;
Readers[typeof(char)] = CharReader;
Readers[typeof(ushort)] = UShortReader;
Readers[typeof(double)] = DoubleReader;
Readers[typeof(ulong)] = ULongReader;
Readers[typeof(int)] = IntReader;
Readers[typeof(uint)] = UIntReader;
Readers[typeof(byte)] = ByteReader;
Readers[typeof(long)] = LongReader;
Readers[typeof(short)] = ShortReader;
Readers[typeof(sbyte)] = SByteReader;
}
private static object ShortReader(BinaryReader reader)
{
return reader.ReadInt16();
}
private static object LongReader(BinaryReader reader)
{
return reader.ReadInt64();
}
private static object GuidReader(BinaryReader reader)
{
return new Guid(reader.ReadString());
}
private static object SByteReader(BinaryReader reader)
{
return reader.ReadSByte();
}
private static object ByteReader(BinaryReader reader)
{
return reader.ReadByte();
}
private static object UIntReader(BinaryReader reader)
{
return reader.ReadUInt32();
}
private static object IntReader(BinaryReader reader)
{
return reader.ReadInt32();
}
private static object ULongReader(BinaryReader reader)
{
return reader.ReadUInt64();
}
private static object DoubleReader(BinaryReader reader)
{
return reader.ReadDouble();
}
private static object UShortReader(BinaryReader reader)
{
return reader.ReadUInt16();
}
private static object CharReader(BinaryReader reader)
{
return reader.ReadChar();
}
private static object FloatReader(BinaryReader reader)
{
return reader.ReadSingle();
}
private static object TimeSpanReader(BinaryReader reader)
{
return new TimeSpan(reader.ReadInt64());
}
private static object DateTimeReader(BinaryReader reader)
{
return new DateTime(reader.ReadInt64());
}
private static object ByteArrayReader(BinaryReader reader)
{
var len = reader.ReadInt32();
return reader.ReadBytes(len);
}
private static object DecimalReader(BinaryReader reader)
{
var array = new int[4];
array[0] = (int)reader.ReadInt32();
array[1] = (int)reader.ReadInt32();
array[2] = (int)reader.ReadInt32();
array[3] = (int)reader.ReadInt32();
return new Decimal(array);
}
private static object BoolReader(BinaryReader reader)
{
return reader.ReadChar() == 'Y';
}
private static object AStringReader(BinaryReader reader)
{
var retString = reader.ReadString();
return retString == "~~NULL~~"
? null
: retString;
}
private static void SByteWriter(BinaryWriter writer, object value)
{
writer.Write((sbyte)value);
}
private static void ShortWriter(BinaryWriter writer, object value)
{
writer.Write((short)value);
}
private static void LongWriter(BinaryWriter writer, object value)
{
writer.Write((long)value);
}
private static void ByteWriter(BinaryWriter writer, object value)
{
writer.Write((byte)value);
}
private static void UIntWriter(BinaryWriter writer, object value)
{
writer.Write((uint)value);
}
private static void IntWriter(BinaryWriter writer, object value)
{
writer.Write((int)value);
}
private static void ULongWriter(BinaryWriter writer, object value)
{
writer.Write((ulong)value);
}
private static void DoubleWriter(BinaryWriter writer, object value)
{
writer.Write((double)value);
}
private static void UShortWriter(BinaryWriter writer, object value)
{
writer.Write((ushort)value);
}
private static void CharWriter(BinaryWriter writer, object value)
{
writer.Write((char)value);
}
private static void TimeSpanWriter(BinaryWriter writer, object value)
{
writer.Write(((TimeSpan)value).Ticks);
}
private static void DateTimeWriter(BinaryWriter writer, object value)
{
writer.Write(((DateTime)value).Ticks);
}
private static void GuidWriter(BinaryWriter writer, object value)
{
writer.Write(value.ToString());
}
private static void BoolWriter(BinaryWriter writer, object value)
{
writer.Write((bool)value
? 'Y'
: 'N');
}
private static void ByteArrayWriter(BinaryWriter writer, object value)
{
var array = value as byte[];
writer.Write((int)array.Length);
writer.Write(array);
}
private static void FloatWriter(BinaryWriter writer, object value)
{
writer.Write((float)value);
}
private static void DecimalWriter(BinaryWriter writer, object value)
{
int[] array = Decimal.GetBits((Decimal)value);
writer.Write(array[0]);
writer.Write(array[1]);
writer.Write(array[2]);
writer.Write(array[3]);
}
private static void StringWriter(BinaryWriter writer, object value)
{
writer.Write((string)value);
}
///// <summary>
///// Write a basic untyped value
///// </summary>
///// <param name = "writer">The writer to commit byte to</param>
///// <param name = "value">The value to write</param>
//internal static void WriteValue(BinaryWriter writer, object value)
//{
// if (value is string)
// writer.Write((string)value);
// else if (value == null)
// writer.Write("~~NULL~~");
// else if (value is bool)
// writer.Write((bool)value
// ? 'Y'
// : 'N');
// else if (value is double)
// writer.Write((double)value);
// else if (value is int)
// writer.Write((int)value);
// else if (value is Guid)
// writer.Write(value.ToString());
// else if (value is DateTime)
// writer.Write(((DateTime)value).Ticks);
// else if (value is TimeSpan)
// writer.Write(((TimeSpan)value).Ticks);
// else if (value is char)
// writer.Write((char)value);
// else if (value is ushort)
// writer.Write((ushort)value);
// else if (value is decimal)
// {
// int[] array = Decimal.GetBits((Decimal)value);
// writer.Write(array[0]);
// writer.Write(array[1]);
// writer.Write(array[2]);
// writer.Write(array[3]);
// }
// else if (value is float)
// writer.Write((float)value);
// else if (value is byte[])
// {
// var array = value as byte[];
// writer.Write((int)array.Length);
// writer.Write(array);
// }
// else if (value is ulong)
// writer.Write((ulong)value);
// else if (value is uint)
// writer.Write((uint)value);
// else if (value is byte)
// writer.Write((byte)value);
// else if (value is long)
// writer.Write((long)value);
// else if (value is short)
// writer.Write((short)value);
// else if (value is sbyte)
// writer.Write((sbyte)value);
// else
// writer.Write((int)value);
//}
///// <summary>
///// Read a basic value from the stream
///// </summary>
///// <param name = "reader">The reader with the stream</param>
///// <param name = "tp">The type to read</param>
///// <returns>The hydrated value</returns>
//internal static object ReadValue(BinaryReader reader, Type tp)
//{
// if (tp == typeof(bool))
// return reader.ReadChar() == 'Y';
// if (tp == typeof(int))
// return reader.ReadInt32();
// if (tp == typeof(double))
// return reader.ReadDouble();
// if (tp == typeof(string))
// {
// var retString = reader.ReadString();
// return retString == "~~NULL~~"
// ? null
// : retString;
// }
// if (tp == typeof(decimal))
// {
// var array = new int[4];
// array[0] = (int)reader.ReadInt32();
// array[1] = (int)reader.ReadInt32();
// array[2] = (int)reader.ReadInt32();
// array[3] = (int)reader.ReadInt32();
// return new Decimal(array);
// }
// if (tp == typeof(byte[]))
// {
// var len = reader.ReadInt32();
// return reader.ReadBytes(len);
// }
// if (tp == typeof(DateTime))
// return new DateTime(reader.ReadInt64());
// if (tp == typeof(TimeSpan))
// return new TimeSpan(reader.ReadInt64());
// if (tp == typeof(float))
// return reader.ReadSingle();
// if (tp == typeof(char))
// return reader.ReadChar();
// if (tp == typeof(ushort))
// return reader.ReadUInt16();
// if (tp == typeof(ulong))
// return reader.ReadUInt64();
// if (tp == typeof(uint))
// return reader.ReadUInt32();
// if (tp == typeof(byte))
// return reader.ReadByte();
// if (tp == typeof(long))
// return reader.ReadInt64();
// if (tp == typeof(short))
// return reader.ReadInt16();
// if (tp == typeof(sbyte))
// return reader.ReadSByte();
// if (tp == typeof(Guid))
// return new Guid(reader.ReadString());
// return reader.ReadInt32();
//}
/// <summary>
/// Write a basic untyped value
/// </summary>
/// <param name = "writer">The writer to commit byte to</param>
/// <param name = "value">The value to write</param>
internal static void WriteValue(BinaryWriter writer, object value)
{
WriteAValue write;
if (!Writers.TryGetValue(value.GetType(), out write))
{
writer.Write((int)value);
return;
}
write(writer, value);
}
/// <summary>
/// Read a basic value from the stream
/// </summary>
/// <param name = "reader">The reader with the stream</param>
/// <param name = "tp">The type to read</param>
/// <returns>The hydrated value</returns>
internal static object ReadValue(BinaryReader reader, Type tp)
{
ReadAValue read;
if (!Readers.TryGetValue(tp, out read))
{
return reader.ReadInt32();
}
return read(reader);
}
#endregion
/// <summary>
/// Logs a type and returns a unique token for it
/// </summary>
/// <param name = "tp">The type to retrieve a token for</param>
/// <returns>A 2 byte token representing the type</returns>
internal static ushort GetTypeId(RuntimeTypeHandle tp)
{
var tpId = KnownTypes.IndexOf(tp);
if (tpId < 0)
{
tpId = KnownTypes.Count;
KnownTypes.Add(tp);
}
return (ushort)tpId;
}
/// <summary>
/// Stores configurations for entries
/// </summary>
private class EntryConfiguration
{
public GetSet Setter;
public Type Type;
}
/// <summary>
/// Cache for property name to item lookups
/// </summary>
private static readonly Dictionary<Type, Dictionary<string, EntryConfiguration>> StoredTypes = new Dictionary<Type, Dictionary<string, EntryConfiguration>>();
/// <summary>
/// Gets a property setter and a standard default type for an entry
/// </summary>
/// <param name="entry"></param>
private static void UpdateEntryWithName(Entry entry)
{
Dictionary<string, EntryConfiguration> configurations;
if (!StoredTypes.TryGetValue(entry.OwningType, out configurations))
{
configurations = new Dictionary<string, EntryConfiguration>();
StoredTypes[entry.OwningType] = configurations;
}
EntryConfiguration entryConfiguration;
if (!configurations.TryGetValue(entry.Name, out entryConfiguration))
{
entryConfiguration = new EntryConfiguration();
var pi = entry.OwningType.GetProperty(entry.Name);
if (pi != null)
{
entryConfiguration.Type = pi.PropertyType;
var gs = typeof(GetSetGeneric<,>);
var tp = gs.MakeGenericType(new Type[] { entry.OwningType, pi.PropertyType });
entryConfiguration.Setter = (GetSet)Activator.CreateInstance(tp, new object[] { pi });
}
else
{
var fi = entry.OwningType.GetField(entry.Name);
if (fi != null)
{
entryConfiguration.Type = fi.FieldType;
var gs = typeof(GetSetGeneric<,>);
var tp = gs.MakeGenericType(new Type[] { entry.OwningType, fi.FieldType });
entryConfiguration.Setter = (GetSet)Activator.CreateInstance(tp, new object[] { fi });
}
}
configurations[entry.Name] = entryConfiguration;
}
entry.StoredType = entryConfiguration.Type;
entry.Setter = entryConfiguration.Setter;
}
}
}
| zzgaminginc-pointofssale | Samba.Infrastructure.Data/BinarySerializer/SilverlightSerializer.cs | C# | gpl3 | 88,146 |
namespace Samba.Infrastructure.Data
{
public interface IOrderable
{
string Name { get; }
int Order { get; set; }
string UserString { get; }
}
}
| zzgaminginc-pointofssale | Samba.Infrastructure.Data/IOrderable.cs | C# | gpl3 | 192 |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace Samba.Infrastructure.Data
{
public interface IWorkspace : IDisposable
{
void CommitChanges();
void Delete<T>(Expression<Func<T, bool>> expression) where T : class;
void Delete<T>(T item) where T : class;
void DeleteAll<T>() where T : class;
T Single<T>(Expression<Func<T, bool>> expression) where T : class;
T Single<T>(Expression<Func<T, bool>> expression, params Expression<Func<T, object>>[] includes) where T : class;
T Last<T>() where T : class, IEntity;
IEnumerable<T> All<T>() where T : class;
IEnumerable<T> All<T>(params Expression<Func<T, object>>[] includes) where T : class;
IEnumerable<T> All<T>(Expression<Func<T, bool>> expression) where T : class;
void Add<T>(T item) where T : class;
void Add<T>(IEnumerable<T> items) where T : class;
void Update<T>(T item) where T : class;
int Count<T>() where T : class;
void ReloadAll();
void ResetDatabase();
void Refresh(IEnumerable collection);
void Refresh(object item);
void Refresh(object item, string property);
}
}
| zzgaminginc-pointofssale | Samba.Infrastructure.Data/IWorkspace.cs | C# | gpl3 | 1,296 |
using System.Linq;
using Samba.Domain.Models.Tables;
using Samba.Localization.Properties;
using Samba.Persistance.Data;
using Samba.Presentation.Common;
using Samba.Presentation.Common.ModelBase;
using Samba.Presentation.Common.Services;
using Samba.Services;
namespace Samba.Modules.TableModule
{
public class TableListViewModel : EntityCollectionViewModelBase<TableEditorViewModel, Table>
{
public ICaptionCommand BatchCreateTables { get; set; }
public TableListViewModel()
{
BatchCreateTables = new CaptionCommand<string>(Resources.AddMultipleTables, OnBatchCreateTablesExecute);
CustomCommands.Add(BatchCreateTables);
}
private void OnBatchCreateTablesExecute(string obj)
{
var values = InteractionService.UserIntraction.GetStringFromUser(
Resources.AddMultipleTables,
Resources.AddMultipleTableHint);
var createdItems = new DataCreationService().BatchCreateTables(values, Workspace);
Workspace.CommitChanges();
foreach (var table in createdItems)
Items.Add(CreateNewViewModel(table));
}
protected override TableEditorViewModel CreateNewViewModel(Table model)
{
return new TableEditorViewModel(model);
}
protected override Table CreateNewModel()
{
return new Table();
}
protected override string CanDeleteItem(Table model)
{
if (model.TicketId > 0) return Resources.DeleteErrorTicketAssignedToTable;
var count = Dao.Count<TableScreen>(x => x.Tables.Any(y => y.Id == model.Id));
if (count > 0) return Resources.DeleteErrorTableUsedInTableView;
return base.CanDeleteItem(model);
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.TableModule/TableListViewModel.cs | C# | gpl3 | 1,883 |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Samba.Domain.Models.Tables;
using Samba.Infrastructure.Data;
using Samba.Localization.Properties;
using Samba.Presentation.Common;
using Samba.Presentation.Common.ModelBase;
using Samba.Presentation.Common.Services;
using Samba.Presentation.ViewModels;
namespace Samba.Modules.TableModule
{
public class TableScreenViewModel : EntityViewModelBase<TableScreen>
{
private IWorkspace _workspace;
public ICaptionCommand SelectTablesCommand { get; set; }
private ObservableCollection<TableScreenItemViewModel> _screenItems;
public ObservableCollection<TableScreenItemViewModel> ScreenItems
{
get { return _screenItems ?? (_screenItems = new ObservableCollection<TableScreenItemViewModel>(Model.Tables.Select(x => new TableScreenItemViewModel(x, Model)))); }
}
public string[] DisplayModes { get { return new[] { Resources.Automatic, Resources.Custom, Resources.Hidden }; } }
public string DisplayMode { get { return DisplayModes[Model.DisplayMode]; } set { Model.DisplayMode = Array.IndexOf(DisplayModes, value); } }
public string BackgroundImage { get { return string.IsNullOrEmpty(Model.BackgroundImage) ? "/Images/empty.png" : Model.BackgroundImage; } set { Model.BackgroundImage = value; } }
public string BackgroundColor { get { return string.IsNullOrEmpty(Model.BackgroundColor) ? "Transparent" : Model.BackgroundColor; } set { Model.BackgroundColor = value; } }
public string TableEmptyColor { get { return Model.TableEmptyColor; } set { Model.TableEmptyColor = value; } }
public string TableFullColor { get { return Model.TableFullColor; } set { Model.TableFullColor = value; } }
public string TableLockedColor { get { return Model.TableLockedColor; } set { Model.TableLockedColor = value; } }
public int PageCount { get { return Model.PageCount; } set { Model.PageCount = value; } }
public int ColumnCount { get { return Model.ColumnCount; } set { Model.ColumnCount = value; } }
public int ButtonHeight { get { return Model.ButtonHeight; } set { Model.ButtonHeight = value; } }
public int NumeratorHeight { get { return Model.NumeratorHeight; } set { Model.NumeratorHeight = value; } }
public string AlphaButtonValues { get { return Model.AlphaButtonValues; } set { Model.AlphaButtonValues = value; } }
public TableScreenViewModel(TableScreen model)
: base(model)
{
SelectTablesCommand = new CaptionCommand<string>(Resources.SelectTable, OnSelectTables);
}
private void OnSelectTables(string obj)
{
IList<IOrderable> values = new List<IOrderable>(_workspace.All<Table>()
.Where(x => ScreenItems.SingleOrDefault(y => y.Model.Id == x.Id) == null));
IList<IOrderable> selectedValues = new List<IOrderable>(ScreenItems.Select(x => x.Model));
IList<IOrderable> choosenValues =
InteractionService.UserIntraction.ChooseValuesFrom(values, selectedValues, Resources.TableList,
string.Format(Resources.SelectTableDialogHint_f, Model.Name), Resources.Table, Resources.Tables);
ScreenItems.Clear();
Model.Tables.Clear();
foreach (Table choosenValue in choosenValues)
{
Model.AddScreenItem(choosenValue);
ScreenItems.Add(new TableScreenItemViewModel(choosenValue, Model));
}
}
public override Type GetViewType()
{
return typeof(TableScreenView);
}
public override string GetModelTypeString()
{
return Resources.TableView;
}
protected override void Initialize(IWorkspace workspace)
{
_workspace = workspace;
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.TableModule/TableScreenViewModel.cs | C# | gpl3 | 4,035 |
using System.Windows.Controls;
namespace Samba.Modules.TableModule
{
/// <summary>
/// Interaction logic for TableEditorView.xaml
/// </summary>
public partial class TableEditorView : UserControl
{
public TableEditorView()
{
InitializeComponent();
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.TableModule/TableEditorView.xaml.cs | C# | gpl3 | 335 |
using System.ComponentModel.Composition;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Samba.Services;
namespace Samba.Modules.TableModule
{
/// <summary>
/// Interaction logic for TableSelectorView.xaml
/// </summary>
[Export]
public partial class TableSelectorView : UserControl
{
[ImportingConstructor]
public TableSelectorView(TableSelectorViewModel viewModel)
{
InitializeComponent();
DataContext = viewModel;
}
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
if (DiagramCanvas.EditingMode == InkCanvasEditingMode.None)
{
if(!AppServices.CurrentLoggedInUser.UserRole.IsAdmin) return;
brd.BorderBrush = Brushes.Red;
miDesignMode.IsChecked = true;
DiagramCanvas.EditingMode = InkCanvasEditingMode.Select;
(DataContext as TableSelectorViewModel).LoadTrackableTables();
}
else
{
brd.BorderBrush = Brushes.Silver;
miDesignMode.IsChecked = false;
DiagramCanvas.EditingMode = InkCanvasEditingMode.None;
(DataContext as TableSelectorViewModel).SaveTrackableTables();
}
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.TableModule/TableSelectorView.xaml.cs | C# | gpl3 | 1,401 |
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.Linq;
using System.Windows;
using Microsoft.Practices.Prism.Commands;
using Samba.Domain.Models.Tables;
using Samba.Domain.Models.Tickets;
using Samba.Infrastructure;
using Samba.Localization.Properties;
using Samba.Presentation.Common;
using Samba.Presentation.Common.Services;
using Samba.Presentation.ViewModels;
using Samba.Services;
namespace Samba.Modules.TableModule
{
[Export]
public class TableSelectorViewModel : ObservableObject
{
public DelegateCommand<TableScreenItemViewModel> TableSelectionCommand { get; set; }
public DelegateCommand<TableScreen> SelectTableCategoryCommand { get; set; }
public ICaptionCommand CloseScreenCommand { get; set; }
public ICaptionCommand EditSelectedTableScreenPropertiesCommand { get; set; }
public ICaptionCommand IncPageNumberCommand { get; set; }
public ICaptionCommand DecPageNumberCommand { get; set; }
public ObservableCollection<IDiagram> Tables { get; set; }
public Ticket SelectedTicket { get { return AppServices.MainDataContext.SelectedTicket; } }
public TableScreen SelectedTableScreen { get { return AppServices.MainDataContext.SelectedTableScreen; } }
public int SelectedDisplayMode
{
get
{
if (SelectedTableScreen == null) return 0;
if (SelectedTableScreen.DisplayMode == 2 && !string.IsNullOrEmpty(SelectedTableScreen.BackgroundImage))
return 1;
return SelectedTableScreen.DisplayMode;
}
set
{
//
}
}
public IEnumerable<TableScreen> TableScreens { get { return AppServices.MainDataContext.TableScreens.Where(x => x.DisplayMode < 2); } }
public bool IsNavigated { get; set; }
public bool CanDesignTables { get { return AppServices.CurrentLoggedInUser.UserRole.IsAdmin; } }
public int CurrentPageNo { get; set; }
public bool IsPageNavigatorVisible { get { return SelectedTableScreen != null && SelectedTableScreen.PageCount > 1; } }
public bool IsFeedbackVisible { get { return !string.IsNullOrEmpty(Feedback); } }
private string _feedback;
public string Feedback
{
get { return _feedback; }
set { _feedback = value; RaisePropertyChanged("Feedback"); RaisePropertyChanged("IsFeedbackVisible"); }
}
private string _feedbackColor;
public string FeedbackColor
{
get { return _feedbackColor; }
set { _feedbackColor = value; RaisePropertyChanged("FeedbackColor"); }
}
private string _feedbackForeground;
public string FeedbackForeground
{
get { return _feedbackForeground; }
set
{
_feedbackForeground = value;
RaisePropertyChanged("FeedbackForeground");
}
}
public VerticalAlignment TablesVerticalAlignment { get { return SelectedTableScreen != null && SelectedTableScreen.ButtonHeight > 0 ? VerticalAlignment.Top : VerticalAlignment.Stretch; } }
public TableSelectorViewModel()
{
SelectTableCategoryCommand = new DelegateCommand<TableScreen>(OnSelectTableCategoryExecuted);
TableSelectionCommand = new DelegateCommand<TableScreenItemViewModel>(OnSelectTableExecuted);
CloseScreenCommand = new CaptionCommand<string>(Resources.Close, OnCloseScreenExecuted);
EditSelectedTableScreenPropertiesCommand = new CaptionCommand<string>(Resources.Properties, OnEditSelectedTableScreenProperties, CanEditSelectedTableScreenProperties);
IncPageNumberCommand = new CaptionCommand<string>(Resources.NextPage + " >>", OnIncPageNumber, CanIncPageNumber);
DecPageNumberCommand = new CaptionCommand<string>("<< " + Resources.PreviousPage, OnDecPageNumber, CanDecPageNumber);
EventServiceFactory.EventService.GetEvent<GenericEvent<Department>>().Subscribe(
x =>
{
if (x.Topic == EventTopicNames.SelectTable)
{
RefreshTables();
}
});
EventServiceFactory.EventService.GetEvent<GenericEvent<Message>>().Subscribe(
x =>
{
if (AppServices.ActiveAppScreen == AppScreens.TableList
&& x.Topic == EventTopicNames.MessageReceivedEvent
&& x.Value.Command == Messages.TicketRefreshMessage)
{
RefreshTables();
}
});
}
public void RefreshTables()
{
if (SelectedTableScreen == null && TableScreens.Count() > 0)
AppServices.MainDataContext.SelectedTableScreen = TableScreens.First();
if (SelectedTableScreen != null)
UpdateTables(SelectedTableScreen.Id);
}
private bool CanDecPageNumber(string arg)
{
return SelectedTableScreen != null && CurrentPageNo > 0;
}
private void OnDecPageNumber(string obj)
{
CurrentPageNo--;
RefreshTables();
}
private bool CanIncPageNumber(string arg)
{
return SelectedTableScreen != null && CurrentPageNo < SelectedTableScreen.PageCount - 1;
}
private void OnIncPageNumber(string obj)
{
CurrentPageNo++;
RefreshTables();
}
private bool CanEditSelectedTableScreenProperties(string arg)
{
return SelectedTableScreen != null;
}
private void OnEditSelectedTableScreenProperties(string obj)
{
if (SelectedTableScreen != null)
InteractionService.UserIntraction.EditProperties(SelectedTableScreen);
}
private void OnCloseScreenExecuted(string obj)
{
EventServiceFactory.EventService.PublishEvent(IsNavigated
? EventTopicNames.ActivateNavigation
: EventTopicNames.DisplayTicketView);
}
private void OnSelectTableCategoryExecuted(TableScreen obj)
{
UpdateTables(obj.Id);
}
private static void OnSelectTableExecuted(TableScreenItemViewModel obj)
{
var location = new LocationData()
{
LocationId = obj.Model.Id,
LocationName = obj.Model.Name,
TicketId = obj.Model.TicketId,
Caption = obj.Caption
};
location.PublishEvent(EventTopicNames.LocationSelectedForTicket);
//if (SelectedTicket != null)
//{
// var oldLocationName = SelectedTicket.LocationName;
// var ticketsMerged = obj.Model.TicketId > 0 && obj.Model.TicketId != SelectedTicket.Id;
// AppServices.MainDataContext.AssignTableToSelectedTicket(obj.Model.Id);
// SelectedTicket.PublishEvent(EventTopicNames.TableSelectedForTicket);
// if (!string.IsNullOrEmpty(oldLocationName) || ticketsMerged)
// if (ticketsMerged && !string.IsNullOrEmpty(oldLocationName))
// InteractionService.UserIntraction.GiveFeedback(string.Format(Resources.TablesMerged_f, oldLocationName, obj.Caption));
// else if (ticketsMerged)
// InteractionService.UserIntraction.GiveFeedback(string.Format(Resources.TicketMergedToTable_f, obj.Caption));
// else if (oldLocationName != obj.Caption)
// InteractionService.UserIntraction.GiveFeedback(string.Format(Resources.TicketMovedToTable_f, oldLocationName, obj.Caption));
//}
//else if (obj.Model.TicketId == 0)
//{
// AppServices.MainDataContext.AssignTableToSelectedTicket(obj.Model.Id);
// obj.UpdateButtonColor();
// SelectedTicket.PublishEvent(EventTopicNames.TicketSelectedFromTableList);
//}
//else
//{
// AppServices.MainDataContext.OpenTicket(obj.Model.TicketId);
// if (SelectedTicket != null && SelectedTicket.LocationName == obj.Model.Name)
// {
// SelectedTicket.PublishEvent(EventTopicNames.TicketSelectedFromTableList);
// }
// else if (SelectedTicket != null)
// {
// AppServices.MainDataContext.ResetTableDataForSelectedTicket();
// SelectedTicket.PublishEvent(EventTopicNames.TicketSelectedFromTableList);
// }
//}
}
private void UpdateTables(int tableScreenId)
{
UpdateMethod2(tableScreenId);
RaisePropertyChanged("TablesVerticalAlignment");
}
private void UpdateMethod2(int tableScreenId)
{
Feedback = "";
var tableData = AppServices.DataAccessService.GetCurrentTables(tableScreenId, CurrentPageNo).OrderBy(x => x.Order);
if (Tables != null && (Tables.Count() == 0 || Tables.Count != tableData.Count() || Tables.First().Caption != tableData.First().Name)) Tables = null;
if (Tables == null)
{
Tables = new ObservableCollection<IDiagram>();
Tables.AddRange(tableData.Select(x => new TableScreenItemViewModel(x, SelectedTableScreen, TableSelectionCommand)));
}
else
{
for (var i = 0; i < tableData.Count(); i++)
{
if (Tables[i] is TableScreenItemViewModel)
((TableScreenItemViewModel)Tables[i]).Model = tableData.ElementAt(i);
}
}
if (SelectedTicket != null && !string.IsNullOrEmpty(SelectedTicket.LocationName))
{
FeedbackColor = "Red";
FeedbackForeground = "White";
Feedback = string.Format(Resources.SelectTableThatYouWantToMoveTicket_f, SelectedTicket.LocationName);
}
else if (SelectedTicket != null)
{
FeedbackColor = "Red";
FeedbackForeground = "White";
Feedback = Resources.SelectTableForTicket;
}
else
{
FeedbackColor = "LightYellow";
FeedbackForeground = "Black";
Feedback = Resources.SelectTableForOperation;
}
RaisePropertyChanged("Tables");
RaisePropertyChanged("TableScreens");
RaisePropertyChanged("SelectedTableScreen");
RaisePropertyChanged("SelectedDisplayMode");
RaisePropertyChanged("IsPageNavigatorVisible");
}
public void LoadTrackableTables()
{
Tables = new ObservableCollection<IDiagram>(
AppServices.MainDataContext.LoadTables(SelectedTableScreen.Name)
.Select<Table, IDiagram>(x => new TableScreenItemViewModel(x, SelectedTableScreen)));
RaisePropertyChanged("Tables");
}
public void SaveTrackableTables()
{
AppServices.MainDataContext.SaveTables();
UpdateTables(SelectedTableScreen.Id);
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.TableModule/TableSelectorViewModel.cs | C# | gpl3 | 12,116 |
using System.ComponentModel.Composition;
using Microsoft.Practices.Prism.MefExtensions.Modularity;
using Microsoft.Practices.Prism.Modularity;
using Microsoft.Practices.Prism.Regions;
using Samba.Domain.Models.Tickets;
using Samba.Localization.Properties;
using Samba.Presentation.Common;
using Samba.Presentation.Common.ModelBase;
using Samba.Services;
namespace Samba.Modules.TableModule
{
[ModuleExport(typeof(TableModule))]
public class TableModule : ModuleBase
{
private readonly IRegionManager _regionManager;
public ICategoryCommand ListTablesCommand { get; set; }
public ICategoryCommand ListTableScreensCommand { get; set; }
public ICategoryCommand NavigateTablesCommand { get; set; }
private TableListViewModel _tableListViewModel;
private readonly TableSelectorView _tableSelectorView;
private TableScreenListViewModel _tableScreenListViewModel;
[ImportingConstructor]
public TableModule(IRegionManager regionManager, TableSelectorView tableSelectorView)
{
_regionManager = regionManager;
_tableSelectorView = tableSelectorView;
ListTablesCommand = new CategoryCommand<string>(Resources.TableList, Resources.Tables, OnListTablesExecute) { Order = 30 };
ListTableScreensCommand = new CategoryCommand<string>(Resources.TableViews, Resources.Tables, OnListTableScreensExecute);
NavigateTablesCommand = new CategoryCommand<string>(Resources.Tables, Resources.Common, "images/Png.png", OnNavigateTables, CanNavigateTables);
}
protected override void OnPostInitialization()
{
CommonEventPublisher.PublishDashboardCommandEvent(ListTablesCommand);
CommonEventPublisher.PublishDashboardCommandEvent(ListTableScreensCommand);
}
protected override void OnInitialization()
{
_regionManager.RegisterViewWithRegion(RegionNames.MainRegion, typeof(TableSelectorView));
PermissionRegistry.RegisterPermission(PermissionNames.OpenTables, PermissionCategories.Navigation, Resources.CanOpenTableList);
PermissionRegistry.RegisterPermission(PermissionNames.ChangeTable, PermissionCategories.Ticket, Resources.CanChangeTable);
EventServiceFactory.EventService.GetEvent<GenericEvent<Department>>().Subscribe(x =>
{
if (x.Topic == EventTopicNames.SelectTable)
{
ActivateTableView();
}
});
EventServiceFactory.EventService.GetEvent<GenericEvent<VisibleViewModelBase>>().Subscribe(
x =>
{
if (x.Topic == EventTopicNames.ViewClosed)
{
if (x.Value == _tableListViewModel)
_tableListViewModel = null;
if (x.Value == _tableScreenListViewModel)
_tableScreenListViewModel = null;
}
}
);
}
private void OnNavigateTables(string obj)
{
ActivateTableView();
((TableSelectorViewModel)_tableSelectorView.DataContext).IsNavigated = true;
((TableSelectorViewModel)_tableSelectorView.DataContext).RefreshTables();
}
private static bool CanNavigateTables(string arg)
{
return
AppServices.IsUserPermittedFor(PermissionNames.OpenTables) &&
AppServices.MainDataContext.IsCurrentWorkPeriodOpen;
}
private void ActivateTableView()
{
AppServices.ActiveAppScreen = AppScreens.TableList;
_regionManager.Regions[RegionNames.MainRegion].Activate(_tableSelectorView);
((TableSelectorViewModel)_tableSelectorView.DataContext).IsNavigated = false;
}
private void OnListTableScreensExecute(string obj)
{
if (_tableScreenListViewModel == null)
_tableScreenListViewModel = new TableScreenListViewModel();
CommonEventPublisher.PublishViewAddedEvent(_tableScreenListViewModel);
}
private void OnListTablesExecute(string obj)
{
if (_tableListViewModel == null)
_tableListViewModel = new TableListViewModel();
CommonEventPublisher.PublishViewAddedEvent(_tableListViewModel);
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.TableModule/TableModule.cs | C# | gpl3 | 4,584 |
using System;
using System.Collections.Generic;
using Samba.Domain.Models.Tables;
using Samba.Infrastructure.Data;
using Samba.Localization.Properties;
using Samba.Persistance.Data;
using Samba.Presentation.Common.ModelBase;
namespace Samba.Modules.TableModule
{
public class TableEditorViewModel : EntityViewModelBase<Table>
{
public TableEditorViewModel(Table model)
: base(model)
{
}
private IEnumerable<string> _categories;
public IEnumerable<string> Categories { get { return _categories ?? (_categories = Dao.Distinct<Table>(x => x.Category)); } }
public string Category { get { return Model.Category; } set { Model.Category = value; } }
public string GroupValue { get { return Model.Category; } }
public override Type GetViewType()
{
return typeof(TableEditorView);
}
public override string GetModelTypeString()
{
return Resources.Table;
}
protected override bool CanSave(string arg)
{
return Model.TicketId <= 0 && base.CanSave(arg);
}
protected override string GetSaveErrorMessage()
{
if (Dao.Single<Table>(x => x.Name.ToLower() == Model.Name.ToLower() && x.Id != Model.Id) != null)
return Resources.SaveErrorDuplicateTableName;
return base.GetSaveErrorMessage();
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.TableModule/TableEditorViewModel.cs | C# | gpl3 | 1,489 |
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("Samba.Modules.TableModule")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Samba.Modules.TableModule")]
[assembly: AssemblyCopyright("Copyright © 2010")]
[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("32cf54c0-2dce-4669-ab77-80c3bfa1da21")]
// 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")]
| zzgaminginc-pointofssale | Samba.Modules.TableModule/Properties/AssemblyInfo.cs | C# | gpl3 | 1,462 |
using System.Windows.Controls;
namespace Samba.Modules.TableModule
{
/// <summary>
/// Interaction logic for TableScreenView.xaml
/// </summary>
public partial class TableScreenView : UserControl
{
public TableScreenView()
{
InitializeComponent();
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.TableModule/TableScreenView.xaml.cs | C# | gpl3 | 333 |
using Samba.Domain.Models.Tables;
using Samba.Domain.Models.Tickets;
using Samba.Localization.Properties;
using Samba.Persistance.Data;
using Samba.Presentation.Common.ModelBase;
namespace Samba.Modules.TableModule
{
public class TableScreenListViewModel : EntityCollectionViewModelBase<TableScreenViewModel, TableScreen>
{
protected override TableScreenViewModel CreateNewViewModel(TableScreen model)
{
return new TableScreenViewModel(model);
}
protected override TableScreen CreateNewModel()
{
return new TableScreen();
}
protected override string CanDeleteItem(TableScreen model)
{
var count = Dao.Count<Department>(x => x.TableScreenId == model.Id);
if (count > 0) return Resources.DeleteErrorTableViewUsedInDepartment;
return base.CanDeleteItem(model);
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.TableModule/TableScreenListViewModel.cs | C# | gpl3 | 942 |
using System.ComponentModel.Composition;
using System.Linq;
using Microsoft.Practices.Prism.MefExtensions.Modularity;
using Microsoft.Practices.Prism.Regions;
using Samba.Domain.Models.Users;
using Samba.Localization.Properties;
using Samba.Presentation.Common;
using Samba.Presentation.Common.ModelBase;
using Samba.Services;
namespace Samba.Modules.UserModule
{
[ModuleExport(typeof(UserModule))]
public class UserModule : ModuleBase
{
private readonly IRegionManager _regionManager;
private UserListViewModel _userListViewModel;
private UserRoleListViewModel _userRolesListViewModel;
public ICategoryCommand ListUsersCommand { get; set; }
public ICategoryCommand ListUserRolesCommand { get; set; }
public ICategoryCommand NavigateLogoutCommand { get; set; }
[ImportingConstructor]
public UserModule(IRegionManager regionManager)
{
ListUserRolesCommand = new CategoryCommand<string>(Resources.UserRoleList, Resources.Users, OnListRoles) { Order = 50 };
ListUsersCommand = new CategoryCommand<string>(Resources.UserList, Resources.Users, OnListUsers);
NavigateLogoutCommand = new CategoryCommand<string>("Logout", Resources.Common, "images/bmp.png", OnNavigateUserLogout) { Order = 99 };
_regionManager = regionManager;
}
private static void OnNavigateUserLogout(string obj)
{
AppServices.CurrentLoggedInUser.PublishEvent(EventTopicNames.UserLoggedOut);
AppServices.LogoutUser();
}
protected override void OnInitialization()
{
_regionManager.RegisterViewWithRegion(RegionNames.RightUserRegion, typeof(LoggedInUserView));
EventServiceFactory.EventService.GetEvent<GenericEvent<string>>().Subscribe(x =>
{
if (x.Topic == EventTopicNames.PinSubmitted)
PinEntered(x.Value);
});
EventServiceFactory.EventService.GetEvent<GenericEvent<VisibleViewModelBase>>().Subscribe(s =>
{
if (s.Topic == EventTopicNames.ViewClosed)
{
if (s.Value == _userListViewModel)
_userListViewModel = null;
if (s.Value == _userRolesListViewModel)
_userRolesListViewModel = null;
}
});
}
protected override void OnPostInitialization()
{
CommonEventPublisher.PublishDashboardCommandEvent(ListUserRolesCommand);
CommonEventPublisher.PublishDashboardCommandEvent(ListUsersCommand);
CommonEventPublisher.PublishNavigationCommandEvent(NavigateLogoutCommand);
}
public void PinEntered(string pin)
{
var u = AppServices.LoginUser(pin);
if (u != User.Nobody)
u.PublishEvent(EventTopicNames.UserLoggedIn);
}
public void OnListUsers(string value)
{
if (_userListViewModel == null)
_userListViewModel = new UserListViewModel();
CommonEventPublisher.PublishViewAddedEvent(_userListViewModel);
}
public void OnListRoles(string value)
{
if (_userRolesListViewModel == null)
_userRolesListViewModel = new UserRoleListViewModel();
CommonEventPublisher.PublishViewAddedEvent(_userRolesListViewModel);
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.UserModule/UserModule.cs | C# | gpl3 | 3,591 |
using System;
using System.Collections.Generic;
using Samba.Domain.Models.Tickets;
using Samba.Domain.Models.Users;
using Samba.Infrastructure.Data;
using Samba.Localization.Properties;
using Samba.Presentation.Common.ModelBase;
using Samba.Services;
using System.Linq;
namespace Samba.Modules.UserModule
{
public class UserRoleViewModel : EntityViewModelBase<UserRole>
{
private IWorkspace _workspace;
public UserRoleViewModel(UserRole role)
: base(role)
{ }
private IEnumerable<PermissionViewModel> _permissions;
public IEnumerable<PermissionViewModel> Permissions
{
get { return _permissions ?? (_permissions = GetPermissions()); }
}
private IEnumerable<PermissionViewModel> GetPermissions()
{
if (Model.Permissions.Count() < PermissionRegistry.PermissionNames.Count)
{
foreach (var pName in PermissionRegistry.PermissionNames.Keys.Where(pName => Model.Permissions.SingleOrDefault(x => x.Name == pName) == null))
{
Model.Permissions.Add(new Permission { Name = pName, Value = 0 });
}
}
return Model.Permissions.Where(x => PermissionRegistry.PermissionNames.ContainsKey(x.Name)).Select(x => new PermissionViewModel(x));
}
private IEnumerable<Department> _departments;
public IEnumerable<Department> Departments
{
get { return _departments ?? (_departments = _workspace.All<Department>()); }
}
public int DepartmentId
{
get { return Model.DepartmentId; }
set { Model.DepartmentId = value; }
}
public bool IsAdmin
{
get { return Model.IsAdmin; }
set { Model.IsAdmin = value; }
}
public override Type GetViewType()
{
return typeof(UserRoleView);
}
public override string GetModelTypeString()
{
return Resources.UserRole;
}
protected override void Initialize(IWorkspace workspace)
{
_workspace = workspace;
}
protected override string GetSaveErrorMessage()
{
if (DepartmentId == 0)
return Resources.SaveErrorSelectDefaultDepartment;
return base.GetSaveErrorMessage();
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.UserModule/UserRoleViewModel.cs | C# | gpl3 | 2,509 |
using System.ComponentModel.Composition;
using Microsoft.Practices.Prism.Commands;
using Samba.Domain.Models.Users;
using Samba.Presentation.Common;
using Samba.Services;
namespace Samba.Modules.UserModule
{
[Export]
public class LoggedInUserViewModel : ObservableObject
{
[ImportingConstructor]
public LoggedInUserViewModel()
{
EventServiceFactory.EventService.GetEvent<GenericEvent<User>>().Subscribe(x =>
{
if (x.Topic == EventTopicNames.UserLoggedIn) UserLoggedIn(x.Value);
if (x.Topic == EventTopicNames.UserLoggedOut) UserLoggedOut(x.Value);
});
LoggedInUser = AppServices.CurrentLoggedInUser;
LogoutUserCommand = new DelegateCommand<User>(x =>
{
if (AppServices.CanNavigate())
{
if (AppServices.IsUserPermittedFor(PermissionNames.OpenNavigation))
{
EventServiceFactory.EventService.PublishEvent(EventTopicNames.ActivateNavigation);
}
else
{
AppServices.CurrentLoggedInUser.PublishEvent(EventTopicNames.UserLoggedOut);
AppServices.LogoutUser();
}
}
});
}
public string LoggedInUserName { get { return LoggedInUser != null ? LoggedInUser.Name : ""; } }
public User LoggedInUser { get; set; }
public DelegateCommand<User> LogoutUserCommand { get; set; }
private void UserLoggedIn(User user)
{
LoggedInUser = user;
RaisePropertyChanged("LoggedInUserName");
}
private void UserLoggedOut(User user)
{
LoggedInUser = User.Nobody;
RaisePropertyChanged("LoggedInUserName");
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.UserModule/LoggedInUserViewModel.cs | C# | gpl3 | 1,967 |
using System.Windows.Controls;
using System.ComponentModel.Composition;
using Microsoft.Practices.Prism.Events;
namespace Samba.Modules.UserModule
{
/// <summary>
/// Interaction logic for LoggedInUserView.xaml
/// </summary>
[Export]
public partial class LoggedInUserView : UserControl
{
private IEventAggregator _eventAggregator;
private LoggedInUserViewModel _viewModel;
[ImportingConstructor]
public LoggedInUserView(LoggedInUserViewModel viewModel,IEventAggregator eventAggregator)
{
InitializeComponent();
DataContext = viewModel;
_eventAggregator = eventAggregator;
_viewModel = viewModel;
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.UserModule/LoggedInUserView.xaml.cs | C# | gpl3 | 763 |
using Samba.Domain.Models.Users;
using Samba.Localization.Properties;
using Samba.Persistance.Data;
using Samba.Presentation.Common.ModelBase;
namespace Samba.Modules.UserModule
{
public class UserRoleListViewModel : EntityCollectionViewModelBase<UserRoleViewModel, UserRole>
{
protected override UserRoleViewModel CreateNewViewModel(UserRole model)
{
return new UserRoleViewModel(model);
}
protected override UserRole CreateNewModel()
{
return new UserRole();
}
protected override string CanDeleteItem(UserRole model)
{
var count = Dao.Count<User>(x => x.UserRole.Id == model.Id);
if (count > 0) return Resources.DeleteErrorThisRoleUsedInAUserAccount;
return base.CanDeleteItem(model);
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.UserModule/UserRoleListViewModel.cs | C# | gpl3 | 878 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Samba.Domain.Models.Users;
using Samba.Localization.Properties;
using Samba.Services;
namespace Samba.Modules.UserModule
{
public class PermissionViewModel
{
private readonly Permission _permission;
public PermissionViewModel(Permission permission)
{
_permission = permission;
}
public string Title { get { return PermissionRegistry.PermissionNames[_permission.Name][1]; } }
public string Category { get { return PermissionRegistry.PermissionNames[_permission.Name][0]; } }
private static readonly string[] _values = new[] { Resources.Yes, Resources.No };
public static string[] Values { get { return _values; } }
public string Value { get { return Values[_permission.Value]; } set { _permission.Value = Values.ToList().IndexOf(value); } }
public bool IsPermitted
{
get { return _permission.Value == (int)PermissionValue.Enabled; }
set
{
if (value)
_permission.Value = (int)PermissionValue.Enabled;
else
_permission.Value = (int)PermissionValue.Disabled;
}
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.UserModule/PermissionViewModel.cs | C# | gpl3 | 1,336 |
using System;
using System.Collections.Generic;
using Samba.Domain.Models.Users;
using Samba.Infrastructure;
using Samba.Infrastructure.Data;
using Samba.Localization.Properties;
using Samba.Presentation.Common;
using Samba.Presentation.Common.ModelBase;
using Samba.Services;
using System.Linq;
namespace Samba.Modules.UserModule
{
public class UserViewModel : EntityViewModelBase<User>
{
private bool _edited;
public UserViewModel(User user)
: base(user)
{
EventServiceFactory.EventService.GetEvent<GenericEvent<UserRole>>().Subscribe(x => RaisePropertyChanged("Roles"));
}
public string PinCode
{
get
{
if (_edited) return Model.PinCode;
return !string.IsNullOrEmpty(Model.PinCode) ? "********" : "";
}
set
{
if (Model.PinCode == null || !Model.PinCode.Contains("*") && !string.IsNullOrEmpty(value))
{
_edited = true;
Model.PinCode = value;
RaisePropertyChanged("PinCode");
}
}
}
public UserRole Role { get { return Model.UserRole; } set { Model.UserRole = value; } }
public IEnumerable<UserRole> Roles { get; private set; }
public override Type GetViewType()
{
return typeof(UserView);
}
public override string GetModelTypeString()
{
return Resources.User;
}
protected override void Initialize(IWorkspace workspace)
{
Roles = workspace.All<UserRole>();
}
protected override string GetSaveErrorMessage()
{
var users = AppServices.Workspace.All<User>(x => x.PinCode == Model.PinCode);
return users.Count() > 1 || (users.Count() == 1 && users.ElementAt(0).Id != Model.Id)
? Resources.SaveErrorThisPinCodeInUse : "";
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.UserModule/UserViewModel.cs | C# | gpl3 | 2,095 |
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("Samba.Modules.UserModule")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Samba.Modules.UserModule")]
[assembly: AssemblyCopyright("Copyright © 2010")]
[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("5423dbba-ae5c-4e09-be0f-a271ae761cfb")]
// 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")]
| zzgaminginc-pointofssale | Samba.Modules.UserModule/Properties/AssemblyInfo.cs | C# | gpl3 | 1,460 |
using System.Windows.Controls;
namespace Samba.Modules.UserModule
{
/// <summary>
/// Interaction logic for UserView.xaml
/// </summary>
public partial class UserView : UserControl
{
public UserView()
{
InitializeComponent();
PasswordTextBox.GotFocus += PasswordTextBoxGotFocus;
}
void PasswordTextBoxGotFocus(object sender, System.Windows.RoutedEventArgs e)
{
if(PasswordTextBox.Text.Contains("*"))
PasswordTextBox.Clear();
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.UserModule/UserView.xaml.cs | C# | gpl3 | 578 |
using System.Windows.Controls;
namespace Samba.Modules.UserModule
{
/// <summary>
/// Interaction logic for UserRoleView.xaml
/// </summary>
public partial class UserRoleView : UserControl
{
public UserRoleView()
{
InitializeComponent();
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.UserModule/UserRoleView.xaml.cs | C# | gpl3 | 323 |
using Samba.Domain.Models.Tickets;
using Samba.Domain.Models.Users;
using Samba.Localization.Properties;
using Samba.Persistance.Data;
using Samba.Presentation.Common.ModelBase;
namespace Samba.Modules.UserModule
{
public class UserListViewModel : EntityCollectionViewModelBase<UserViewModel, User>
{
protected override UserViewModel CreateNewViewModel(User model)
{
return new UserViewModel(model);
}
protected override User CreateNewModel()
{
return new User();
}
protected override string CanDeleteItem(User model)
{
if (model.UserRole.IsAdmin) return Resources.DeleteErrorAdminUser;
if (Workspace.Count<User>() == 1) return Resources.DeleteErrorLastUser;
var ti = Dao.Count<TicketItem>(x => x.CreatingUserId == model.Id || x.ModifiedUserId == model.Id);
if (ti > 0) return Resources.DeleteErrorUserDidTicketOperation;
return base.CanDeleteItem(model);
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.UserModule/UserListViewModel.cs | C# | gpl3 | 1,066 |
using System;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using Samba.Presentation.Common;
namespace Samba.Modules.CustomerModule
{
/// <summary>
/// Interaction logic for CustomerSelectorView.xaml
/// </summary>
[Export]
public partial class CustomerSelectorView : UserControl
{
readonly DependencyPropertyDescriptor _selectedIndexChange = DependencyPropertyDescriptor.FromProperty(Selector.SelectedIndexProperty, typeof(TabControl));
[ImportingConstructor]
public CustomerSelectorView(CustomerSelectorViewModel viewModel)
{
InitializeComponent();
DataContext = viewModel;
_selectedIndexChange.AddValueChanged(MainTabControl, MyTabControlSelectedIndexChanged);
}
private void MyTabControlSelectedIndexChanged(object sender, EventArgs e)
{
if (((TabControl)sender).SelectedIndex == 1)
PhoneNumberTextBox.BackgroundFocus();
}
private void FlexButton_Click(object sender, RoutedEventArgs e)
{
Reset();
}
private void Reset()
{
((CustomerSelectorViewModel)DataContext).RefreshSelectedCustomer();
PhoneNumber.BackgroundFocus();
}
private void HandleKeyDown(KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
e.Handled = true;
if (((CustomerSelectorViewModel)DataContext).SelectCustomerCommand.CanExecute(""))
((CustomerSelectorViewModel)DataContext).SelectCustomerCommand.Execute("");
}
}
private void PhoneNumber_PreviewKeyDown(object sender, KeyEventArgs e)
{
HandleKeyDown(e);
}
private void CustomerName_PreviewKeyDown(object sender, KeyEventArgs e)
{
HandleKeyDown(e);
}
private void Address_PreviewKeyDown(object sender, KeyEventArgs e)
{
HandleKeyDown(e);
}
private void PhoneNumberTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
HandleKeyDown(e);
}
private void TicketNo_PreviewKeyDown(object sender, KeyEventArgs e)
{
if(e.Key == Key.Enter)
{
e.Handled = true;
if (((CustomerSelectorViewModel)DataContext).FindTicketCommand.CanExecute(""))
((CustomerSelectorViewModel)DataContext).FindTicketCommand.Execute("");
}
}
private void PhoneNumber_Loaded(object sender, RoutedEventArgs e)
{
PhoneNumber.BackgroundFocus();
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.CustomerModule/CustomerSelectorView.xaml.cs | C# | gpl3 | 2,927 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Samba.Domain.Models.Customers;
using Samba.Presentation.Common.ModelBase;
namespace Samba.Modules.CustomerModule
{
class CustomerListViewModel : EntityCollectionViewModelBase<CustomerEditorViewModel, Customer>
{
protected override CustomerEditorViewModel CreateNewViewModel(Customer model)
{
return new CustomerEditorViewModel(model);
}
protected override Customer CreateNewModel()
{
return new Customer();
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.CustomerModule/CustomerListViewModel.cs | C# | gpl3 | 616 |
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("Samba.Modules.CustomerModule")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Samba.Modules.CustomerModule")]
[assembly: AssemblyCopyright("Copyright © 2010")]
[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("a41b36a5-b60f-4b61-9455-fa077ac526e5")]
// 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")]
| zzgaminginc-pointofssale | Samba.Modules.CustomerModule/Properties/AssemblyInfo.cs | C# | gpl3 | 1,468 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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 Samba.Modules.CustomerModule
{
/// <summary>
/// Interaction logic for CustomerView.xaml
/// </summary>
public partial class CustomerEditorView : UserControl
{
public CustomerEditorView()
{
InitializeComponent();
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.CustomerModule/CustomerEditorView.xaml.cs | C# | gpl3 | 672 |
using System.ComponentModel.Composition;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.Prism.MefExtensions.Modularity;
using Microsoft.Practices.Prism.Regions;
using Samba.Domain.Models.Customers;
using Samba.Domain.Models.Tickets;
using Samba.Localization.Properties;
using Samba.Persistance.Data;
using Samba.Presentation.Common;
using Samba.Presentation.Common.Interaction;
using Samba.Presentation.Common.ModelBase;
using Samba.Services;
namespace Samba.Modules.CustomerModule
{
[ModuleExport(typeof(CustomerModule))]
public class CustomerModule : ModuleBase
{
private readonly IRegionManager _regionManager;
private readonly CustomerSelectorView _customerSelectorView;
private CustomerListViewModel _customerListViewModel;
public ICategoryCommand ListCustomersCommand { get; set; }
[ImportingConstructor]
public CustomerModule(IRegionManager regionManager, CustomerSelectorView customerSelectorView)
{
_regionManager = regionManager;
_customerSelectorView = customerSelectorView;
ListCustomersCommand = new CategoryCommand<string>(Resources.CustomerList, Resources.Customers, OnCustomerListExecute) { Order = 40 };
PermissionRegistry.RegisterPermission(PermissionNames.MakeAccountTransaction, PermissionCategories.Cash, Resources.CanMakeAccountTransaction);
PermissionRegistry.RegisterPermission(PermissionNames.CreditOrDeptAccount, PermissionCategories.Cash, Resources.CanMakeCreditOrDeptTransaction);
}
private void OnCustomerListExecute(string obj)
{
if (_customerListViewModel == null)
_customerListViewModel = new CustomerListViewModel();
CommonEventPublisher.PublishViewAddedEvent(_customerListViewModel);
}
protected override void OnInitialization()
{
_regionManager.RegisterViewWithRegion(RegionNames.MainRegion, typeof(CustomerSelectorView));
EventServiceFactory.EventService.GetEvent<GenericEvent<VisibleViewModelBase>>().Subscribe(s =>
{
if (s.Topic == EventTopicNames.ViewClosed)
{
if (s.Value == _customerListViewModel)
_customerListViewModel = null;
}
});
EventServiceFactory.EventService.GetEvent<GenericEvent<Department>>().Subscribe(x =>
{
if (x.Topic == EventTopicNames.SelectCustomer)
{
ActivateCustomerView();
((CustomerSelectorViewModel)_customerSelectorView.DataContext).RefreshSelectedCustomer();
}
});
EventServiceFactory.EventService.GetEvent<GenericEvent<EventAggregator>>().Subscribe(x =>
{
if (x.Topic == EventTopicNames.ActivateCustomerView)
{
ActivateCustomerView();
((CustomerSelectorViewModel)_customerSelectorView.DataContext).RefreshSelectedCustomer();
}
});
EventServiceFactory.EventService.GetEvent<GenericEvent<Customer>>().Subscribe(x =>
{
if (x.Topic == EventTopicNames.ActivateCustomerAccount)
{
ActivateCustomerView();
((CustomerSelectorViewModel)_customerSelectorView.DataContext).DisplayCustomerAccount(x.Value);
}
});
EventServiceFactory.EventService.GetEvent<GenericEvent<PopupData>>().Subscribe(
x =>
{
if (x.Topic == EventTopicNames.PopupClicked && x.Value.EventMessage == "SelectCustomer")
{
ActivateCustomerView();
((CustomerSelectorViewModel)_customerSelectorView.DataContext).SearchCustomer(x.Value.DataObject as string);
}
}
);
}
private void ActivateCustomerView()
{
AppServices.ActiveAppScreen = AppScreens.CustomerList;
_regionManager.Regions[RegionNames.MainRegion].Activate(_customerSelectorView);
}
protected override void OnPostInitialization()
{
CommonEventPublisher.PublishDashboardCommandEvent(ListCustomersCommand);
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.CustomerModule/CustomerModule.cs | C# | gpl3 | 4,536 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Samba.Modules.CustomerModule
{
public class CustomerTransactionViewModel
{
public DateTime Date { get; set; }
public string Description { get; set; }
public decimal Receivable { get; set; }
public decimal Liability { get; set; }
public decimal Balance { get; set; }
}
}
| zzgaminginc-pointofssale | Samba.Modules.CustomerModule/CustomerTransactionViewModel.cs | C# | gpl3 | 438 |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Linq;
using System.Timers;
using System.Windows.Input;
using System.Windows.Threading;
using Samba.Domain;
using Samba.Domain.Models.Customers;
using Samba.Domain.Models.Tickets;
using Samba.Domain.Models.Transactions;
using Samba.Localization.Properties;
using Samba.Persistance.Data;
using Samba.Presentation.Common;
using Samba.Presentation.ViewModels;
using Samba.Services;
namespace Samba.Modules.CustomerModule
{
[Export]
public class CustomerSelectorViewModel : ObservableObject
{
private readonly Timer _updateTimer;
public ICaptionCommand CloseScreenCommand { get; set; }
public ICaptionCommand SelectCustomerCommand { get; set; }
public ICaptionCommand CreateCustomerCommand { get; set; }
public ICaptionCommand ResetCustomerCommand { get; set; }
public ICaptionCommand FindTicketCommand { get; set; }
public ICaptionCommand MakePaymentCommand { get; set; }
public ICaptionCommand DisplayCustomerAccountCommand { get; set; }
public ICaptionCommand GetPaymentFromCustomerCommand { get; set; }
public ICaptionCommand MakePaymentToCustomerCommand { get; set; }
public ICaptionCommand AddReceivableCommand { get; set; }
public ICaptionCommand AddLiabilityCommand { get; set; }
public ICaptionCommand CloseAccountScreenCommand { get; set; }
public string PhoneNumberInputMask { get { return AppServices.SettingService.PhoneNumberInputMask; } }
public Ticket SelectedTicket { get { return AppServices.MainDataContext.SelectedTicket; } }
public ObservableCollection<CustomerViewModel> FoundCustomers { get; set; }
public ObservableCollection<CustomerTransactionViewModel> SelectedCustomerTransactions { get; set; }
private int _selectedView;
public int SelectedView
{
get { return _selectedView; }
set { _selectedView = value; RaisePropertyChanged("SelectedView"); }
}
public CustomerViewModel SelectedCustomer { get { return FoundCustomers.Count == 1 ? FoundCustomers[0] : FocusedCustomer; } }
private CustomerViewModel _focusedCustomer;
public CustomerViewModel FocusedCustomer
{
get { return _focusedCustomer; }
set
{
_focusedCustomer = value;
RaisePropertyChanged("FocusedCustomer");
RaisePropertyChanged("SelectedCustomer");
}
}
private string _ticketSearchText;
public string TicketSearchText
{
get { return _ticketSearchText; }
set { _ticketSearchText = value; RaisePropertyChanged("TicketSearchText"); }
}
private string _phoneNumberSearchText;
public string PhoneNumberSearchText
{
get { return string.IsNullOrEmpty(_phoneNumberSearchText) ? null : _phoneNumberSearchText.TrimStart('+', '0'); }
set
{
if (value != _phoneNumberSearchText)
{
_phoneNumberSearchText = value;
RaisePropertyChanged("PhoneNumberSearchText");
ResetTimer();
}
}
}
private string _customerNameSearchText;
public string CustomerNameSearchText
{
get { return _customerNameSearchText; }
set
{
if (value != _customerNameSearchText)
{
_customerNameSearchText = value;
RaisePropertyChanged("CustomerNameSearchText");
ResetTimer();
}
}
}
private string _addressSearchText;
public string AddressSearchText
{
get { return _addressSearchText; }
set
{
if (value != _addressSearchText)
{
_addressSearchText = value;
RaisePropertyChanged("AddressSearchText");
ResetTimer();
}
}
}
public bool IsResetCustomerVisible
{
get
{
return (AppServices.MainDataContext.SelectedTicket != null &&
AppServices.MainDataContext.SelectedTicket.CustomerId > 0);
}
}
public bool IsClearVisible
{
get
{
return (AppServices.MainDataContext.SelectedTicket != null &&
AppServices.MainDataContext.SelectedTicket.CustomerId == 0);
}
}
public bool IsMakePaymentVisible
{
get
{
return (AppServices.MainDataContext.SelectedTicket != null && AppServices.IsUserPermittedFor(PermissionNames.MakePayment));
}
}
private int _activeView;
public int ActiveView
{
get { return _activeView; }
set { _activeView = value; RaisePropertyChanged("ActiveView"); }
}
public string TotalReceivable { get { return SelectedCustomerTransactions.Sum(x => x.Receivable).ToString("#,#0.00"); } }
public string TotalLiability { get { return SelectedCustomerTransactions.Sum(x => x.Liability).ToString("#,#0.00"); } }
public string TotalBalance { get { return SelectedCustomerTransactions.Sum(x => x.Receivable - x.Liability).ToString("#,#0.00"); } }
public CustomerSelectorViewModel()
{
_updateTimer = new Timer(500);
_updateTimer.Elapsed += UpdateTimerElapsed;
FoundCustomers = new ObservableCollection<CustomerViewModel>();
CloseScreenCommand = new CaptionCommand<string>(Resources.Close, OnCloseScreen);
SelectCustomerCommand = new CaptionCommand<string>(Resources.SelectCustomer_r, OnSelectCustomer, CanSelectCustomer);
CreateCustomerCommand = new CaptionCommand<string>(Resources.NewCustomer_r, OnCreateCustomer, CanCreateCustomer);
FindTicketCommand = new CaptionCommand<string>(Resources.FindTicket_r, OnFindTicket, CanFindTicket);
ResetCustomerCommand = new CaptionCommand<string>(Resources.ResetCustomer_r, OnResetCustomer, CanResetCustomer);
MakePaymentCommand = new CaptionCommand<string>(Resources.GetPayment_r, OnMakePayment, CanMakePayment);
DisplayCustomerAccountCommand = new CaptionCommand<string>(Resources.CustomerAccount_r, OnDisplayCustomerAccount, CanSelectCustomer);
MakePaymentToCustomerCommand = new CaptionCommand<string>(Resources.MakePayment_r, OnMakePaymentToCustomerCommand, CanMakePaymentToCustomer);
GetPaymentFromCustomerCommand = new CaptionCommand<string>(Resources.GetPayment_r, OnGetPaymentFromCustomerCommand, CanMakePaymentToCustomer);
AddLiabilityCommand = new CaptionCommand<string>(Resources.AddLiability_r, OnAddLiability, CanAddLiability);
AddReceivableCommand = new CaptionCommand<string>(Resources.AddReceivable_r, OnAddReceivable, CanAddLiability);
CloseAccountScreenCommand = new CaptionCommand<string>(Resources.Close, OnCloseAccountScreen);
SelectedCustomerTransactions = new ObservableCollection<CustomerTransactionViewModel>();
}
private bool CanAddLiability(string arg)
{
return CanSelectCustomer(arg) && AppServices.IsUserPermittedFor(PermissionNames.CreditOrDeptAccount);
}
private bool CanMakePaymentToCustomer(string arg)
{
return CanSelectCustomer(arg) && AppServices.IsUserPermittedFor(PermissionNames.MakeAccountTransaction);
}
private void OnAddReceivable(string obj)
{
SelectedCustomer.Model.PublishEvent(EventTopicNames.AddReceivableAmount);
FoundCustomers.Clear();
}
private void OnAddLiability(string obj)
{
SelectedCustomer.Model.PublishEvent(EventTopicNames.AddLiabilityAmount);
FoundCustomers.Clear();
}
private void OnCloseAccountScreen(string obj)
{
RefreshSelectedCustomer();
}
private void OnGetPaymentFromCustomerCommand(string obj)
{
SelectedCustomer.Model.PublishEvent(EventTopicNames.GetPaymentFromCustomer);
FoundCustomers.Clear();
}
private void OnMakePaymentToCustomerCommand(string obj)
{
SelectedCustomer.Model.PublishEvent(EventTopicNames.MakePaymentToCustomer);
FoundCustomers.Clear();
}
internal void DisplayCustomerAccount(Customer customer)
{
FoundCustomers.Clear();
if (customer != null)
FoundCustomers.Add(new CustomerViewModel(customer));
RaisePropertyChanged("SelectedCustomer");
OnDisplayCustomerAccount("");
}
private void OnDisplayCustomerAccount(string obj)
{
SaveSelectedCustomer();
SelectedCustomerTransactions.Clear();
if (SelectedCustomer != null)
{
var tickets = Dao.Query<Ticket>(x => x.CustomerId == SelectedCustomer.Id && x.LastPaymentDate > SelectedCustomer.AccountOpeningDate, x => x.Payments);
var cashTransactions = Dao.Query<CashTransaction>(x => x.Date > SelectedCustomer.AccountOpeningDate && x.CustomerId == SelectedCustomer.Id);
var accountTransactions = Dao.Query<AccountTransaction>(x => x.Date > SelectedCustomer.AccountOpeningDate && x.CustomerId == SelectedCustomer.Id);
var transactions = new List<CustomerTransactionViewModel>();
transactions.AddRange(tickets.Select(x => new CustomerTransactionViewModel
{
Description = string.Format(Resources.TicketNumber_f, x.TicketNumber),
Date = x.LastPaymentDate,
Receivable = x.GetAccountPaymentAmount() + x.GetAccountRemainingAmount(),
Liability = x.GetAccountPaymentAmount()
}));
transactions.AddRange(cashTransactions.Where(x => x.TransactionType == (int)TransactionType.Income)
.Select(x => new CustomerTransactionViewModel
{
Description = x.Name,
Date = x.Date,
Liability = x.Amount
}));
transactions.AddRange(cashTransactions.Where(x => x.TransactionType == (int)TransactionType.Expense)
.Select(x => new CustomerTransactionViewModel
{
Description = x.Name,
Date = x.Date,
Receivable = x.Amount
}));
transactions.AddRange(accountTransactions.Where(x => x.TransactionType == (int)TransactionType.Liability)
.Select(x => new CustomerTransactionViewModel
{
Description = x.Name,
Date = x.Date,
Liability = x.Amount
}));
transactions.AddRange(accountTransactions.Where(x => x.TransactionType == (int)TransactionType.Receivable)
.Select(x => new CustomerTransactionViewModel
{
Description = x.Name,
Date = x.Date,
Receivable = x.Amount
}));
transactions = transactions.OrderBy(x => x.Date).ToList();
for (var i = 0; i < transactions.Count; i++)
{
transactions[i].Balance = (transactions[i].Receivable - transactions[i].Liability);
if (i > 0) (transactions[i].Balance) += (transactions[i - 1].Balance);
}
SelectedCustomerTransactions.AddRange(transactions);
RaisePropertyChanged("TotalReceivable");
RaisePropertyChanged("TotalLiability");
RaisePropertyChanged("TotalBalance");
}
ActiveView = 1;
}
private bool CanMakePayment(string arg)
{
return SelectedCustomer != null && AppServices.MainDataContext.SelectedTicket != null;
}
private void OnMakePayment(string obj)
{
SelectedCustomer.Model.PublishEvent(EventTopicNames.PaymentRequestedForTicket);
ClearSearchValues();
}
private bool CanResetCustomer(string arg)
{
return AppServices.MainDataContext.SelectedTicket != null &&
AppServices.MainDataContext.SelectedTicket.CanSubmit &&
AppServices.MainDataContext.SelectedTicket.CustomerId > 0;
}
private void OnResetCustomer(string obj)
{
Customer.Null.PublishEvent(EventTopicNames.CustomerSelectedForTicket);
}
private void OnFindTicket(string obj)
{
AppServices.MainDataContext.OpenTicketFromTicketNumber(TicketSearchText);
if (AppServices.MainDataContext.SelectedTicket != null)
EventServiceFactory.EventService.PublishEvent(EventTopicNames.DisplayTicketView);
TicketSearchText = "";
}
private bool CanFindTicket(string arg)
{
return !string.IsNullOrEmpty(TicketSearchText) && SelectedTicket == null;
}
private bool CanCreateCustomer(string arg)
{
return SelectedCustomer == null;
}
private void OnCreateCustomer(string obj)
{
FoundCustomers.Clear();
var c = new Customer
{
Address = AddressSearchText,
Name = CustomerNameSearchText,
PhoneNumber = PhoneNumberSearchText
};
FoundCustomers.Add(new CustomerViewModel(c));
SelectedView = 1;
RaisePropertyChanged("SelectedCustomer");
}
private bool CanSelectCustomer(string arg)
{
return
AppServices.MainDataContext.IsCurrentWorkPeriodOpen
&& SelectedCustomer != null
&& !string.IsNullOrEmpty(SelectedCustomer.PhoneNumber)
&& !string.IsNullOrEmpty(SelectedCustomer.Name)
&& (AppServices.MainDataContext.SelectedTicket == null || AppServices.MainDataContext.SelectedTicket.CustomerId == 0);
}
private void SaveSelectedCustomer()
{
if (!SelectedCustomer.IsNotNew)
{
var ws = WorkspaceFactory.Create();
ws.Add(SelectedCustomer.Model);
ws.CommitChanges();
}
}
private void OnSelectCustomer(string obj)
{
SaveSelectedCustomer();
SelectedCustomer.Model.PublishEvent(EventTopicNames.CustomerSelectedForTicket);
ClearSearchValues();
}
void UpdateTimerElapsed(object sender, ElapsedEventArgs e)
{
_updateTimer.Stop();
UpdateFoundCustomers();
}
private void ResetTimer()
{
_updateTimer.Stop();
if (!string.IsNullOrEmpty(PhoneNumberSearchText)
|| !string.IsNullOrEmpty(CustomerNameSearchText)
|| !string.IsNullOrEmpty(AddressSearchText))
{
_updateTimer.Start();
}
else FoundCustomers.Clear();
}
private void UpdateFoundCustomers()
{
IEnumerable<Customer> result = new List<Customer>();
using (var worker = new BackgroundWorker())
{
worker.DoWork += delegate
{
bool searchPn = string.IsNullOrEmpty(PhoneNumberSearchText);
bool searchCn = string.IsNullOrEmpty(CustomerNameSearchText);
bool searchAd = string.IsNullOrEmpty(AddressSearchText);
result = Dao.Query<Customer>(
x =>
(searchPn || x.PhoneNumber.Contains(PhoneNumberSearchText)) &&
(searchCn || x.Name.ToLower().Contains(CustomerNameSearchText.ToLower())) &&
(searchAd || x.Address.ToLower().Contains(AddressSearchText.ToLower())));
};
worker.RunWorkerCompleted +=
delegate
{
AppServices.MainDispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(
delegate
{
FoundCustomers.Clear();
FoundCustomers.AddRange(result.Select(x => new CustomerViewModel(x)));
if (SelectedCustomer != null && PhoneNumberSearchText == SelectedCustomer.PhoneNumber)
{
SelectedView = 1;
SelectedCustomer.UpdateDetailedInfo();
}
RaisePropertyChanged("SelectedCustomer");
CommandManager.InvalidateRequerySuggested();
}));
};
worker.RunWorkerAsync();
}
}
private void OnCloseScreen(string obj)
{
if (AppServices.MainDataContext.SelectedDepartment != null && AppServices.MainDataContext.IsCurrentWorkPeriodOpen)
EventServiceFactory.EventService.PublishEvent(EventTopicNames.DisplayTicketView);
else
EventServiceFactory.EventService.PublishEvent(EventTopicNames.ActivateNavigation);
SelectedView = 0;
ActiveView = 0;
SelectedCustomerTransactions.Clear();
}
public void RefreshSelectedCustomer()
{
ClearSearchValues();
if (AppServices.MainDataContext.SelectedTicket != null && AppServices.MainDataContext.SelectedTicket.CustomerId > 0)
{
var customer = Dao.SingleWithCache<Customer>(x => x.Id == AppServices.MainDataContext.SelectedTicket.CustomerId);
if (customer != null) FoundCustomers.Add(new CustomerViewModel(customer));
if (SelectedCustomer != null)
{
SelectedView = 1;
SelectedCustomer.UpdateDetailedInfo();
}
}
RaisePropertyChanged("SelectedCustomer");
RaisePropertyChanged("IsClearVisible");
RaisePropertyChanged("IsResetCustomerVisible");
RaisePropertyChanged("IsMakePaymentVisible");
ActiveView = 0;
SelectedCustomerTransactions.Clear();
}
private void ClearSearchValues()
{
FoundCustomers.Clear();
SelectedView = 0;
ActiveView = 0;
PhoneNumberSearchText = "";
AddressSearchText = "";
CustomerNameSearchText = "";
}
public void SearchCustomer(string phoneNumber)
{
ClearSearchValues();
PhoneNumberSearchText = phoneNumber;
UpdateFoundCustomers();
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.CustomerModule/CustomerSelectorViewModel.cs | C# | gpl3 | 20,743 |
using System;
using System.Collections.Generic;
using Samba.Domain.Models.Customers;
using Samba.Localization.Properties;
using Samba.Persistance.Data;
using Samba.Presentation.Common.ModelBase;
using Samba.Services;
namespace Samba.Modules.CustomerModule
{
public class CustomerEditorViewModel : EntityViewModelBase<Customer>
{
public CustomerEditorViewModel(Customer model)
: base(model)
{
}
public override Type GetViewType()
{
return typeof(CustomerEditorView);
}
public override string GetModelTypeString()
{
return Resources.Customer;
}
private IEnumerable<string> _groupCodes;
public IEnumerable<string> GroupCodes { get { return _groupCodes ?? (_groupCodes = Dao.Distinct<Customer>(x => x.GroupCode)); } }
public string GroupValue { get { return Model.GroupCode; } }
public string GroupCode { get { return Model.GroupCode ?? ""; } set { Model.GroupCode = value; } }
public string PhoneNumber { get { return Model.PhoneNumber; } set { Model.PhoneNumber = value; } }
public string Address { get { return Model.Address; } set { Model.Address = value; } }
public string Note { get { return Model.Note; } set { Model.Note = value; } }
public bool InternalAccount { get { return Model.InternalAccount; } set { Model.InternalAccount = value; } }
public string PhoneNumberInputMask { get { return AppServices.SettingService.PhoneNumberInputMask; } }
}
}
| zzgaminginc-pointofssale | Samba.Modules.CustomerModule/CustomerEditorViewModel.cs | C# | gpl3 | 1,593 |
using FluentMigrator;
using Samba.Infrastructure.Settings;
namespace Samba.Persistance.DBMigration
{
[Migration(14)]
public class Migration_014 : Migration
{
public override void Up()
{
Create.Column("DepartmentId").OnTable("TicketItems").AsInt32().WithDefaultValue(0);
Create.Column("DepartmentId").OnTable("Terminals").AsInt32().WithDefaultValue(0);
Create.Column("DepartmentId").OnTable("Payments").AsInt32().WithDefaultValue(0);
if (LocalSettings.ConnectionString.EndsWith(".sdf"))
{
for (var i = 1; i <= 9; i++)
{
Execute.Sql(string.Format("Update TicketItems set DepartmentId = {0} Where TicketId IN (SELECT Id from Tickets where DepartmentId = {0})", i));
Execute.Sql(string.Format("Update Payments set DepartmentId = {0} Where Ticket_Id IN (SELECT Id from Tickets where DepartmentId = {0})", i));
}
}
else
{
Execute.Sql("Update TicketItems set DepartmentId = (Select DepartmentId From Tickets Where Id = TicketItems.TicketId)");
Execute.Sql("Update Payments set DepartmentId = (Select DepartmentId From Tickets Where Id = Payments.Ticket_Id)");
}
}
public override void Down()
{
//do nothing
}
}
} | zzgaminginc-pointofssale | Samba.Persistance.DBMigration/Migration_014.cs | C# | gpl3 | 1,449 |
using FluentMigrator;
namespace Samba.Persistance.DBMigration
{
[Migration(2)]
public class Migration_002 : Migration
{
public override void Up()
{
Create.Column("TerminalTableScreenId").OnTable("Departments").AsInt32().WithDefaultValue(0);
Create.Column("TableScreenId").OnTable("Departments").AsInt32().WithDefaultValue(0);
Create.Column("ScreenMenuId").OnTable("Departments").AsInt32().WithDefaultValue(0);
Create.Column("TerminalScreenMenuId").OnTable("Departments").AsInt32().WithDefaultValue(0);
Create.Column("PageCount").OnTable("ScreenMenuCategories").AsInt32().WithDefaultValue(1);
Create.Column("PageCount").OnTable("TableScreens").AsInt32().WithDefaultValue(1);
Create.Column("ColumnCount").OnTable("TableScreens").AsInt32().WithDefaultValue(0);
Create.Column("ButtonHeight").OnTable("TableScreens").AsInt32().WithDefaultValue(80);
Create.Column("CharsPerLine").OnTable("Printers").AsInt32().WithDefaultValue(42);
Create.Column("CodePage").OnTable("Printers").AsInt32().WithDefaultValue(857);
Rename.Column("AlaCarte").OnTable("Departments").To("IsAlaCarte");
Rename.Column("FastFood").OnTable("Departments").To("IsFastFood");
Rename.Column("TakeAway").OnTable("Departments").To("IsTakeAway");
}
public override void Down()
{
Delete.Column("TerminalTableScreenId").FromTable("Departments");
Delete.Column("TableScreenId").FromTable("Departments");
Delete.Column("ScreenMenuId").FromTable("Departments");
Delete.Column("TerminalScreenMenuId").FromTable("Departments");
Delete.Column("PageCount").FromTable("ScreenMenuCategories");
Delete.Column("PageCount").FromTable("TableScreens");
Delete.Column("ColumnCount").FromTable("TableScreens");
Delete.Column("ButtonHeight").FromTable("TableScreens");
Delete.Column("CodePage").FromTable("Printers");
Delete.Column("CharsPerLine").FromTable("Printers");
Rename.Column("IsAlaCarte").OnTable("Departments").To("AlaCarte");
Rename.Column("IsFastFood").OnTable("Departments").To("FastFood");
Rename.Column("IsTakeAway").OnTable("Departments").To("TakeAway");
}
}
} | zzgaminginc-pointofssale | Samba.Persistance.DBMigration/Migration_002.cs | C# | gpl3 | 2,436 |