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
namespace Samba.Presentation.Common.Behaviors { /// <summary> /// Specifies the <see cref="DialogActivationBehavior"/> class for using the behavior on WPF. /// </summary> public class WindowDialogActivationBehavior : DialogActivationBehavior { /// <summary> /// Creates a wrapper for the WPF <see cref="System.Windows.Window"/>. /// </summary> /// <returns>Instance of the <see cref="System.Windows.Window"/> wrapper.</returns> protected override IWindow CreateWindow() { return new WindowWrapper(); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Behaviors/WindowDialogActivationBehavior.cs
C#
gpl3
618
using System.Windows; using System.Collections.Specialized; using Microsoft.Practices.Prism.Regions; using Microsoft.Practices.Prism.Regions.Behaviors; namespace Samba.Presentation.Common.Behaviors { /// <summary> /// Defines a behavior that creates a Dialog to display the active view of the target <see cref="IRegion"/>. /// </summary> public abstract class DialogActivationBehavior : RegionBehavior, IHostAwareRegionBehavior { /// <summary> /// The key of this behavior /// </summary> public const string BehaviorKey = "DialogActivation"; private IWindow contentDialog; /// <summary> /// Gets or sets the <see cref="DependencyObject"/> that the <see cref="IRegion"/> is attached to. /// </summary> /// <value>A <see cref="DependencyObject"/> that the <see cref="IRegion"/> is attached to. /// This is usually a <see cref="FrameworkElement"/> that is part of the tree.</value> public DependencyObject HostControl { get; set; } /// <summary> /// Performs the logic after the behavior has been attached. /// </summary> protected override void OnAttach() { this.Region.ActiveViews.CollectionChanged += this.ActiveViews_CollectionChanged; } /// <summary> /// Override this method to create an instance of the <see cref="IWindow"/> that /// will be shown when a view is activated. /// </summary> /// <returns> /// An instance of <see cref="IWindow"/> that will be shown when a /// view is activated on the target <see cref="IRegion"/>. /// </returns> protected abstract IWindow CreateWindow(); private void ActiveViews_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Add) { this.CloseContentDialog(); this.PrepareContentDialog(e.NewItems[0]); } else if (e.Action == NotifyCollectionChangedAction.Remove) { this.CloseContentDialog(); } } private Style GetStyleForView() { return this.HostControl.GetValue(RegionPopupBehaviors.ContainerWindowStyleProperty) as Style; } private void PrepareContentDialog(object view) { this.contentDialog = this.CreateWindow(); this.contentDialog.Content = view; this.contentDialog.Owner = this.HostControl; this.contentDialog.Closed += this.ContentDialogClosed; this.contentDialog.Style = this.GetStyleForView(); this.contentDialog.Show(); } private void CloseContentDialog() { if (this.contentDialog != null) { Properties.Settings.Default.DashboardHeight = this.contentDialog.Height; Properties.Settings.Default.DashboardWidth = this.contentDialog.Width; Properties.Settings.Default.Save(); this.contentDialog.Closed -= this.ContentDialogClosed; this.contentDialog.Close(); this.contentDialog.Content = null; this.contentDialog.Owner = null; } } private void ContentDialogClosed(object sender, System.EventArgs e) { this.Region.Deactivate(this.contentDialog.Content); this.CloseContentDialog(); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Behaviors/DialogActivationBehavior.cs
C#
gpl3
3,651
using System; using System.Windows; namespace Samba.Presentation.Common.Behaviors { /// <summary> /// Defines the interface for the Dialogs that are shown by <see cref="DialogActivationBehavior"/>. /// </summary> public interface IWindow { /// <summary> /// Ocurrs when the <see cref="IWindow"/> is closed. /// </summary> event EventHandler Closed; /// <summary> /// Gets or sets the content for the <see cref="IWindow"/>. /// </summary> object Content { get; set; } /// <summary> /// Gets or sets the owner control of the <see cref="IWindow"/>. /// </summary> object Owner { get; set; } /// <summary> /// Gets or sets the <see cref="System.Windows.Style"/> to apply to the <see cref="IWindow"/>. /// </summary> Style Style { get; set; } /// <summary> /// Opens the <see cref="IWindow"/>. /// </summary> void Show(); /// <summary> /// Closes the <see cref="IWindow"/>. /// </summary> void Close(); double Height { get; set; } double Width { get; set; } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Behaviors/IWindow.cs
C#
gpl3
1,243
using System.Linq; using System.Windows; using Microsoft.Practices.Prism.Regions; using Microsoft.Practices.ServiceLocation; using System.ComponentModel; namespace Samba.Presentation.Common.Behaviors { /// <summary> /// Declares the Attached Properties and Behaviors for implementing Popup regions. /// </summary> /// <remarks> /// Although the fastest way is to create a RegionAdapter for a Window and register it with the RegionAdapterMappings, /// this would be conceptually incorrect because we want to create a new popup window everytime a view is added /// (instead of having a Window as a host control and replacing its contents everytime Views are added, as other adapters do). /// This is why we have a different class for this behavior, instead of reusing the <see cref="RegionManager.RegionNameProperty"/> attached property. /// </remarks> public static class RegionPopupBehaviors { /// <summary> /// The name of the Popup <see cref="IRegion"/>. /// </summary> public static readonly DependencyProperty CreatePopupRegionWithNameProperty = DependencyProperty.RegisterAttached("CreatePopupRegionWithName", typeof(string), typeof(RegionPopupBehaviors), new PropertyMetadata(CreatePopupRegionWithNamePropertyChanged)); /// <summary> /// The <see cref="Style"/> to set to the Popup. /// </summary> public static readonly DependencyProperty ContainerWindowStyleProperty = DependencyProperty.RegisterAttached("ContainerWindowStyle", typeof(Style), typeof(RegionPopupBehaviors), null); /// <summary> /// Gets the name of the Popup <see cref="IRegion"/>. /// </summary> /// <param name="owner">Owner of the Popup.</param> /// <returns>The name of the Popup <see cref="IRegion"/>.</returns> public static string GetCreatePopupRegionWithName(DependencyObject owner) { return owner.GetValue(CreatePopupRegionWithNameProperty) as string; } /// <summary> /// Sets the name of the Popup <see cref="IRegion"/>. /// </summary> /// <param name="owner">Owner of the Popup.</param> /// <param name="value">Name of the Popup <see cref="IRegion"/>.</param> public static void SetCreatePopupRegionWithName(DependencyObject owner, string value) { owner.SetValue(CreatePopupRegionWithNameProperty, value); } /// <summary> /// Gets the <see cref="Style"/> for the Popup. /// </summary> /// <param name="owner">Owner of the Popup.</param> /// <returns>The <see cref="Style"/> for the Popup.</returns> public static Style GetContainerWindowStyle(DependencyObject owner) { return owner.GetValue(ContainerWindowStyleProperty) as Style; } /// <summary> /// Sets the <see cref="Style"/> for the Popup. /// </summary> /// <param name="owner">Owner of the Popup.</param> /// <param name="style"><see cref="Style"/> for the Popup.</param> public static void SetContainerWindowStyle(DependencyObject owner, Style style) { owner.SetValue(ContainerWindowStyleProperty, style); } /// <summary> /// Creates a new <see cref="IRegion"/> and registers it in the default <see cref="IRegionManager"/> /// attaching to it a <see cref="DialogActivationBehavior"/> behavior. /// </summary> /// <param name="owner">The owner of the Popup.</param> /// <param name="regionName">The name of the <see cref="IRegion"/>.</param> /// <remarks> /// This method would typically not be called directly, instead the behavior /// should be set through the Attached Property <see cref="CreatePopupRegionWithNameProperty"/>. /// </remarks> public static IRegionManager RegionMngr { get; set; } public static void RegisterNewPopupRegion(DependencyObject owner, string regionName) { // Creates a new region and registers it in the default region manager. // Another option if you need the complete infrastructure with the default region behaviors // is to extend DelayedRegionCreationBehavior overriding the CreateRegion method and create an // instance of it that will be in charge of registering the Region once a RegionManager is // set as an attached property in the Visual Tree. RegionMngr = ServiceLocator.Current.GetAllInstances<IRegionManager>().First(); if (RegionMngr != null) { IRegion region = new SingleActiveRegion(); DialogActivationBehavior behavior; #if SILVERLIGHT behavior = new PopupDialogActivationBehavior(); #else behavior = new WindowDialogActivationBehavior(); #endif behavior.HostControl = owner; region.Behaviors.Add(DialogActivationBehavior.BehaviorKey, behavior); RegionMngr.Regions.Add(regionName, region); } } private static void CreatePopupRegionWithNamePropertyChanged(DependencyObject hostControl, DependencyPropertyChangedEventArgs e) { if (IsInDesignMode(hostControl)) { return; } RegisterNewPopupRegion(hostControl, e.NewValue as string); } private static bool IsInDesignMode(DependencyObject element) { // Due to a known issue in Cider, GetIsInDesignMode attached property value is not enough to know if it's in design mode. return DesignerProperties.GetIsInDesignMode(element) || Application.Current == null || Application.Current.GetType() == typeof(Application); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Behaviors/RegionPopupBehaviors.cs
C#
gpl3
6,042
using System; using System.Windows; namespace Samba.Presentation.Common.Behaviors { /// <summary> /// Defines a wrapper for the <see cref="Window"/> class that implements the <see cref="IWindow"/> interface. /// </summary> public class WindowWrapper : IWindow { private readonly Window _window; /// <summary> /// Initializes a new instance of <see cref="WindowWrapper"/>. /// </summary> public WindowWrapper() { _window = new Window { WindowStartupLocation = WindowStartupLocation.CenterScreen, ShowInTaskbar = false, WindowStyle = WindowStyle.ToolWindow, Title = "Samba!", Height = Properties.Settings.Default.DashboardHeight, Width = Properties.Settings.Default.DashboardWidth }; } /// <summary> /// Ocurrs when the <see cref="Window"/> is closed. /// </summary> public event EventHandler Closed { add { _window.Closed += value; } remove { _window.Closed -= value; } } /// <summary> /// Gets or Sets the content for the <see cref="Window"/>. /// </summary> public object Content { get { return _window.Content; } set { _window.Content = value; } } /// <summary> /// Gets or Sets the <see cref="Window.Owner"/> control of the <see cref="Window"/>. /// </summary> public object Owner { get { return _window.Owner; } set { _window.Owner = value as Window; } } /// <summary> /// Gets or Sets the <see cref="FrameworkElement.Style"/> to apply to the <see cref="Window"/>. /// </summary> public Style Style { get { return _window.Style; } set { _window.Style = value; } } /// <summary> /// Opens the <see cref="Window"/>. /// </summary> public void Show() { _window.Show(); } /// <summary> /// Closes the <see cref="Window"/>. /// </summary> public void Close() { _window.Close(); } public double Height { get { return _window.Height; } set { _window.Height = value; } } public double Width { get { return _window.Width; } set { _window.Width = value; } } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Behaviors/WindowWrapper.Desktop.cs
C#
gpl3
2,692
using System; using System.Windows.Input; using Microsoft.Practices.Prism.Commands; namespace Samba.Presentation.Common.ModelBase { public abstract class VisibleViewModelBase : ViewModelBase { public abstract Type GetViewType(); DelegateCommand<object> _closeCommand; public ICommand CloseCommand { get { return _closeCommand ?? (_closeCommand = new DelegateCommand<object>(OnRequestClose, CanClose)); } } protected virtual bool CanClose(object arg) { return true; } private void PublishClose() { CommonEventPublisher.PublishViewClosedEvent(this); } private void OnRequestClose(object obj) { PublishClose(); } public VisibleViewModelBase CallingView { get; set; } public virtual void OnClosed() { //override if needed } public virtual void OnShown() { //override if needed } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/ModelBase/VisibleViewModelBase.cs
C#
gpl3
1,090
using System; using System.Collections.Generic; using Samba.Localization.Properties; using Samba.Services; namespace Samba.Presentation.Common.ModelBase { public abstract class AbstractEntityCollectionViewModelBase : VisibleViewModelBase { public ICaptionCommand AddItemCommand { get; set; } public ICaptionCommand EditItemCommand { get; set; } public ICaptionCommand DeleteItemCommand { get; set; } public ICaptionCommand DuplicateItemCommand { get; set; } public IList<ICaptionCommand> CustomCommands { get; set; } public string ModelTitle { get; set; } private IEnumerable<ICaptionCommand> _allCommands; public IEnumerable<ICaptionCommand> AllCommands { get { return _allCommands ?? (_allCommands = GetCommands()); } } private IEnumerable<ICaptionCommand> GetCommands() { var result = new List<ICaptionCommand> {AddItemCommand, EditItemCommand, DeleteItemCommand}; result.AddRange(CustomCommands); return result; } protected AbstractEntityCollectionViewModelBase() { ModelTitle = GetModelTitle(); AddItemCommand = new CaptionCommand<object>(string.Format(Resources.Add_f, ModelTitle), OnAddItem, CanAddItem); EditItemCommand = new CaptionCommand<object>(string.Format(Resources.Edit_f, ModelTitle), OnEditItem, CanEditItem); DeleteItemCommand = new CaptionCommand<object>(string.Format(Resources.Delete_f, ModelTitle), OnDeleteItem, CanDeleteItem); DuplicateItemCommand = new CaptionCommand<object>(string.Format(Resources.Clone_f, ModelTitle), OnDuplicateItem, CanDuplicateItem); CustomCommands = new List<ICaptionCommand>(); } public abstract string GetModelTitle(); protected abstract void OnDeleteItem(object obj); protected abstract void OnAddItem(object obj); protected abstract void OnEditItem(object obj); protected abstract bool CanEditItem(object obj); protected abstract bool CanDeleteItem(object obj); protected abstract bool CanDuplicateItem(object arg); protected abstract bool CanAddItem(object obj); protected abstract void OnDuplicateItem(object obj); protected override string GetHeaderInfo() { return string.Format(Resources.List_f, ModelTitle); } public override Type GetViewType() { return typeof(EntityCollectionBaseView); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/ModelBase/AbstractEntityCollectionViewModelBase.cs
C#
gpl3
2,636
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Windows; using System.Linq; using Microsoft.Practices.Prism.Events; using Samba.Infrastructure.Data; using Samba.Infrastructure.Data.Serializer; using Samba.Localization.Properties; using Samba.Persistance.Data; namespace Samba.Presentation.Common.ModelBase { public abstract class EntityCollectionViewModelBase<TViewModel, TModel> : AbstractEntityCollectionViewModelBase, ICountable where TViewModel : EntityViewModelBase<TModel> where TModel : class, IEntity, new() { private readonly IWorkspace _workspace = WorkspaceFactory.Create(); public IWorkspace Workspace { get { return _workspace; } } private ObservableCollection<TViewModel> _items; public ObservableCollection<TViewModel> Items { get { return _items ?? (_items = GetItemsList()); } } protected virtual ObservableCollection<TViewModel> GetItemsList() { return BuildViewModelList(SelectItems()); } protected virtual IEnumerable<TModel> SelectItems() { return _workspace.All<TModel>(); } protected virtual void BeforeDeleteItem(TModel item) { // override if needed. } private void DoDeleteItem(TModel item) { BeforeDeleteItem(item); _workspace.Delete(item); _workspace.CommitChanges(); } protected abstract TViewModel CreateNewViewModel(TModel model); protected abstract TModel CreateNewModel(); private readonly SubscriptionToken _token; private readonly SubscriptionToken _token2; public IList<EntityViewModelBase<TModel>> OpenViewModels { get; set; } protected EntityCollectionViewModelBase() { OpenViewModels = new List<EntityViewModelBase<TModel>>(); _token = EventServiceFactory.EventService.GetEvent<GenericEvent<EntityViewModelBase<TModel>>>().Subscribe(x => { if (x.Topic == EventTopicNames.AddedModelSaved) if (x.Value is TViewModel) Items.Add(x.Value as TViewModel); if (x.Topic == EventTopicNames.ModelAddedOrDeleted) { foreach (var openViewModel in OpenViewModels) { if (!openViewModel.CanSave()) openViewModel.RollbackModel(); } if (x.Value is TViewModel) { _workspace.Update(x.Value.Model); _workspace.CommitChanges(); _workspace.Refresh(x.Value.Model); } } }); _token2 = EventServiceFactory.EventService.GetEvent<GenericEvent<VisibleViewModelBase>>().Subscribe( s => { if (s.Topic == EventTopicNames.ViewClosed) { if (s.Value is EntityViewModelBase<TModel> && OpenViewModels.Contains(s.Value)) OpenViewModels.Remove(s.Value as EntityViewModelBase<TModel>); } }); } private TViewModel _selectedItem; public TViewModel SelectedItem { get { return _selectedItem; } set { _selectedItem = value; RaisePropertyChanged("SelectedItem"); } } public override string GetModelTitle() { return CreateNewViewModel(new TModel()).GetModelTypeString(); } protected virtual string CanDeleteItem(TModel model) { return ""; } protected override bool CanAddItem(object obj) { return true; } protected override bool CanClose(object arg) { return OpenViewModels.Count == 0; } protected override void OnDeleteItem(object obj) { if (MessageBox.Show(string.Format(Resources.DeleteItemConfirmation_f, ModelTitle, SelectedItem.Model.Name), Resources.Confirmation, MessageBoxButton.YesNo) == MessageBoxResult.Yes) { var errorMessage = CanDeleteItem(SelectedItem.Model); if (string.IsNullOrEmpty(errorMessage)) { if (SelectedItem.Model.Id > 0) { DoDeleteItem(SelectedItem.Model); SelectedItem.Model.PublishEvent(EventTopicNames.ModelAddedOrDeleted); } Items.Remove(SelectedItem); } else { MessageBox.Show(errorMessage, Resources.Warning); } } } protected override void OnAddItem(object obj) { VisibleViewModelBase wm = InternalCreateNewViewModel(CreateNewModel()); if (wm is EntityViewModelBase<TModel>) OpenViewModels.Add(wm as EntityViewModelBase<TModel>); wm.PublishEvent(EventTopicNames.ViewAdded); } protected override void OnDuplicateItem(object obj) { var duplicate = ObjectCloner.Clone(SelectedItem.Model); duplicate.Id = 0; duplicate.Name = "_" + duplicate.Name; PropertyComparor.ResetIds(duplicate); VisibleViewModelBase wm = InternalCreateNewViewModel(duplicate); if (wm is EntityViewModelBase<TModel>) OpenViewModels.Add(wm as EntityViewModelBase<TModel>); wm.PublishEvent(EventTopicNames.ViewAdded); } private void ResetIds(object obj) { } protected override bool CanDuplicateItem(object arg) { return SelectedItem != null; } protected override bool CanEditItem(object obj) { return SelectedItem != null; } protected override bool CanDeleteItem(object obj) { return SelectedItem != null && !OpenViewModels.Contains(SelectedItem); } protected override void OnEditItem(object obj) { if (!OpenViewModels.Contains(SelectedItem)) OpenViewModels.Add(SelectedItem); (SelectedItem as VisibleViewModelBase).PublishEvent(EventTopicNames.ViewAdded); } protected ObservableCollection<TViewModel> BuildViewModelList(IEnumerable<TModel> itemsList) { return new ObservableCollection<TViewModel>(itemsList.Select(InternalCreateNewViewModel)); } protected TViewModel InternalCreateNewViewModel(TModel model) { var result = CreateNewViewModel(model); result.Init(_workspace); return result; } protected override void OnDispose() { EventServiceFactory.EventService.GetEvent<GenericEvent<EntityViewModelBase<TModel>>>().Unsubscribe(_token); EventServiceFactory.EventService.GetEvent<GenericEvent<VisibleViewModelBase>>().Unsubscribe(_token2); base.OnDispose(); _workspace.Dispose(); } public int GetCount() { return Items.Count; } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/ModelBase/EntityCollectionViewModelBase.cs
C#
gpl3
7,769
using System.Collections.Generic; using System.ComponentModel; using System.Windows.Data; namespace Samba.Presentation.Common.ModelBase { public abstract class ViewModelBase : ObservableObject { public string HeaderInfo { get { return GetHeaderInfo(); } } protected abstract string GetHeaderInfo(); protected void SetActiveView(IEnumerable<VisibleViewModelBase> views, VisibleViewModelBase wm) { ICollectionView collectionView = CollectionViewSource.GetDefaultView(views); if (collectionView != null && collectionView.Contains(wm)) collectionView.MoveCurrentTo(wm); } protected VisibleViewModelBase GetActiveView(IEnumerable<VisibleViewModelBase> views) { ICollectionView collectionView = CollectionViewSource.GetDefaultView(views); return collectionView.CurrentItem as VisibleViewModelBase; } public void Dispose() { OnDispose(); } protected virtual void OnDispose() { } #if DEBUG /// <summary> /// Useful for ensuring that ViewModel objects are properly garbage collected. /// </summary> ~ViewModelBase() { string msg = string.Format("{0} ({1}) ({2}) Finalized", GetType().Name, HeaderInfo, GetHashCode()); System.Diagnostics.Debug.WriteLine(msg); } #endif } }
zzgaminginc-pointofssale
Samba.Presentation.Common/ModelBase/ViewModelBase.cs
C#
gpl3
1,524
using System.Collections.ObjectModel; namespace Samba.Presentation.Common.ModelBase { public abstract class ModelListViewModelBase : ViewModelBase { public ObservableCollection<VisibleViewModelBase> Views { get; set; } protected ModelListViewModelBase() { Views = new ObservableCollection<VisibleViewModelBase>(); AttachEvents(); } private void AttachEvents() { EventServiceFactory.EventService.GetEvent<GenericEvent<VisibleViewModelBase>>().Subscribe( s => { if (s.Topic == EventTopicNames.ViewClosed) { if (s.Value != null) { if (Views.Contains(s.Value)) Views.Remove(s.Value); if (s.Value.CallingView != null) SetActiveView(Views, s.Value.CallingView); s.Value.OnClosed(); s.Value.CallingView = null; s.Value.Dispose(); } } if (s.Topic == EventTopicNames.ViewAdded && s.Value != null) { s.Value.CallingView = GetActiveView(Views); if (!Views.Contains(s.Value)) Views.Add(s.Value); SetActiveView(Views, s.Value); s.Value.OnShown(); } }); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/ModelBase/ModelListViewModelBase.cs
C#
gpl3
1,670
namespace Samba.Presentation.Common.ModelBase { public interface ICountable { int GetCount(); } }
zzgaminginc-pointofssale
Samba.Presentation.Common/ModelBase/ICountable.cs
C#
gpl3
123
using System; using System.Collections; using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Linq; namespace Samba.Presentation.Common.ModelBase { /// <summary> /// Interaction logic for EntityCollectionBaseView.xaml /// </summary> public partial class EntityCollectionBaseView : UserControl { public EntityCollectionBaseView() { InitializeComponent(); } private void MainGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e) { var bm = (DataContext as AbstractEntityCollectionViewModelBase); if (bm != null && bm.EditItemCommand.CanExecute(null)) bm.EditItemCommand.Execute(null); } private void UserControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { var baseModelView = DataContext as AbstractEntityCollectionViewModelBase; if (baseModelView != null && baseModelView.CustomCommands.Count > 0) { MainGrid.ContextMenu.Items.Add(new Separator()); foreach (var item in ((AbstractEntityCollectionViewModelBase)DataContext).CustomCommands) { MainGrid.ContextMenu.Items.Add( new MenuItem { Command = item, Header = item.Caption }); } } } private void MainGrid_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { if (((ICountable)MainGrid.DataContext).GetCount() < 10) MainGrid.ColumnHeaderHeight = 0; } private void MainGrid_PreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { if (((AbstractEntityCollectionViewModelBase)DataContext).EditItemCommand.CanExecute(null)) ((AbstractEntityCollectionViewModelBase)DataContext).EditItemCommand.Execute(null); } } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/ModelBase/EntityCollectionBaseView.xaml.cs
C#
gpl3
2,129
using System.Collections.Generic; using System.Globalization; using System.Text; using System.Windows; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Validation; using Samba.Infrastructure.Data; using Samba.Localization.Properties; namespace Samba.Presentation.Common.ModelBase { public abstract class EntityViewModelBase<TModel> : VisibleViewModelBase where TModel : class, IEntity { public TModel Model { get; private set; } public ICaptionCommand SaveCommand { get; private set; } private readonly ValidatorFactory _validatorFactory; private IWorkspace _workspace; protected EntityViewModelBase(TModel model) { Model = model; SaveCommand = new CaptionCommand<string>(Resources.Save, OnSave, CanSave); _validatorFactory = EnterpriseLibraryContainer.Current.GetInstance<ValidatorFactory>(); } public string Name { get { return Model.Name; } set { Model.Name = value.Trim(); RaisePropertyChanged("Name"); } } private string _error; private bool _modelSaved; public string Error { get { return _error; } set { _error = value; RaisePropertyChanged("Error"); } } public abstract string GetModelTypeString(); public void Init(IWorkspace workspace) { _modelSaved = false; _workspace = workspace; Initialize(workspace); } protected virtual void Initialize(IWorkspace workspace) { } public override void OnShown() { _modelSaved = false; } public override void OnClosed() { if (!_modelSaved) RollbackModel(); } protected override string GetHeaderInfo() { if (Model.Id > 0) return string.Format(Resources.EditModel_f, GetModelTypeString(), Name); return string.Format(Resources.AddModel_f, GetModelTypeString()); } protected virtual void OnSave(string value) { var errorMessage = GetSaveErrorMessage(); if (CanSave()) { _modelSaved = true; if (Model.Id == 0) { this.PublishEvent(EventTopicNames.AddedModelSaved); } this.PublishEvent(EventTopicNames.ModelAddedOrDeleted); ((VisibleViewModelBase)this).PublishEvent(EventTopicNames.ViewClosed); } else { if (string.IsNullOrEmpty(Name)) errorMessage = string.Format(Resources.EmptyNameError, GetModelTypeString()); MessageBox.Show(errorMessage, Resources.CantSave); } } public bool CanSave() { return !string.IsNullOrEmpty(Name) && string.IsNullOrEmpty(GetSaveErrorMessage()) && CanSave(""); } protected virtual string GetSaveErrorMessage() { return ""; } protected virtual bool CanSave(string arg) { return Validate(); } private bool Validate() { var results = _validatorFactory.CreateValidator(typeof(TModel)).Validate(Model); Error = GetErrors(results); return results.IsValid; } private static string GetErrors(IEnumerable<ValidationResult> results) { var builder = new StringBuilder(); foreach (var result in results) { builder.AppendLine( string.Format( CultureInfo.CurrentCulture, "* {0}", result.Message)); } return builder.ToString(); } public void RollbackModel() { if (Model.Id > 0) { _workspace.Refresh(Model); RaisePropertyChanged("Name"); } } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/ModelBase/EntityViewModelBase.cs
C#
gpl3
4,261
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Reflection; namespace Samba.Presentation.Common { public enum ModuleInitializationStage { PreInitialization, Initialization, PostInitialization, StartUp } public interface IStagedSequenceService<TStageEnum> { void RegisterForStage(Action action, TStageEnum stage); } public class StagedSequenceService<TStageEnum> : IStagedSequenceService<TStageEnum> { private readonly List<Action>[] _stages; public StagedSequenceService() { _stages = new List<Action>[NumberOfEnumValues()]; for (int i = 0; i < _stages.Length; ++i) { _stages[i] = new List<Action>(); } } public virtual void ProcessSequence() { foreach (var stage in _stages) { foreach (var action in stage) { action(); } } } public virtual void RegisterForStage(Action action, TStageEnum stage) { _stages[Convert.ToInt32(stage)].Add(action); } static int NumberOfEnumValues() { return typeof(TStageEnum).GetFields(BindingFlags.Public | BindingFlags.Static).Length; } } public interface IModuleInitializationService : IStagedSequenceService<ModuleInitializationStage> { void Initialize(); } [Export(typeof(IModuleInitializationService))] public class ModuleInitializationService : StagedSequenceService<ModuleInitializationStage>, IModuleInitializationService { public virtual void Initialize() { base.ProcessSequence(); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/IModuleInitializationService.cs
C#
gpl3
1,910
using System.Windows; using System.Windows.Input; using System.Windows.Media; namespace Samba.Presentation.Common { public interface IDiagram { string Caption { get; set; } int X { get; set; } int Y { get; set; } int Height { get; set; } int Width { get; set; } bool IsEnabled { get; set; } string ButtonColor { get; set; } ICommand Command { get; } CornerRadius CornerRadius { get; set; } Transform RenderTransform { get; set; } string HtmlContent { get; set; } bool AutoRefresh { get; set; } bool IsDetailsVisible { get; set; } void EditProperties(); } }
zzgaminginc-pointofssale
Samba.Presentation.Common/IDiagram.cs
C#
gpl3
709
using System; using System.Collections.Generic; using System.Reflection; using Samba.Presentation.Common.ErrorReport.SystemInfo; namespace Samba.Presentation.Common.ErrorReport { public class ExceptionReportGenerator : Disposable { private readonly ExceptionReportInfo _reportInfo; private readonly List<SysInfoResult> _sysInfoResults = new List<SysInfoResult>(); public ExceptionReportGenerator(ExceptionReportInfo reportInfo) { if (reportInfo == null) throw new ExceptionReportGeneratorException("reportInfo cannot be null"); _reportInfo = reportInfo; _reportInfo.ExceptionDate = DateTime.UtcNow; _reportInfo.UserName = Environment.UserName; _reportInfo.MachineName = Environment.MachineName; if (_reportInfo.AppAssembly == null) _reportInfo.AppAssembly = Assembly.GetEntryAssembly() ?? Assembly.GetCallingAssembly(); } public string CreateExceptionReport() { var sysInfoResults = GetOrFetchSysInfoResults(); var reportBuilder = new ExceptionReportBuilder(_reportInfo, sysInfoResults); return reportBuilder.Build(); } internal IList<SysInfoResult> GetOrFetchSysInfoResults() { if (_sysInfoResults.Count == 0) _sysInfoResults.AddRange(CreateSysInfoResults()); return _sysInfoResults.AsReadOnly(); } private static IEnumerable<SysInfoResult> CreateSysInfoResults() { var retriever = new SysInfoRetriever(); var results = new List<SysInfoResult> { retriever.Retrieve(SysInfoQueries.OperatingSystem).Filter( new[] { "CodeSet", "CurrentTimeZone", "FreePhysicalMemory", "OSArchitecture", "OSLanguage", "Version" }), retriever.Retrieve(SysInfoQueries.Machine).Filter( new[] { "Machine", "UserName", "TotalPhysicalMemory", "Manufacturer", "Model" }), }; return results; } protected override void DisposeManagedResources() { _reportInfo.Dispose(); base.DisposeManagedResources(); } } internal class ExceptionReportGeneratorException : Exception { public ExceptionReportGeneratorException(string message) : base(message) { } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/ErrorReport/ExceptionReportGenerator.cs
C#
gpl3
2,365
using System; using System.Collections.Generic; using System.Reflection; namespace Samba.Presentation.Common.ErrorReport { public class ExceptionReportInfo : Disposable { private readonly List<Exception> _exceptions = new List<Exception>(); public Exception MainException { get { return _exceptions.Count > 0 ? _exceptions[0] : null; } set { _exceptions.Clear(); _exceptions.Add(value); } } public IList<Exception> Exceptions { get { return _exceptions.AsReadOnly(); } } public void SetExceptions(IEnumerable<Exception> exceptions) { _exceptions.Clear(); _exceptions.AddRange(exceptions); } public string CustomMessage { get; set; } public string MachineName { get; set; } public string UserName { get; set; } public DateTime ExceptionDate { get; set; } public string UserExplanation { get; set; } public Assembly AppAssembly { get; set; } public bool TakeScreenshot { get; set; } public ExceptionReportInfo() { SetDefaultValues(); } private void SetDefaultValues() { TakeScreenshot = false; } } public static class DefaultLabelMessages { public const string DefaultExplanationLabel = "Please enter a brief explanation of events leading up to this exception"; public const string DefaultContactMessageTop = "The following details can be used to obtain support for this application"; } }
zzgaminginc-pointofssale
Samba.Presentation.Common/ErrorReport/ExceptionReportInfo.cs
C#
gpl3
1,704
using System; using System.Collections.Generic; using System.Management; namespace Samba.Presentation.Common.ErrorReport.SystemInfo { /// <summary> /// Retrieves system information using WMI /// </summary> internal class SysInfoRetriever { private ManagementObjectSearcher _sysInfoSearcher; private SysInfoResult _sysInfoResult; private SysInfoQuery _sysInfoQuery; /// <summary> /// Retrieve system information, using the given SysInfoQuery to determine what information to retrieve /// </summary> /// <param name="sysInfoQuery">the query to determine what information to retrieve</param> /// <returns>a SysInfoResult ie containing the results of the query</returns> public SysInfoResult Retrieve(SysInfoQuery sysInfoQuery) { _sysInfoQuery = sysInfoQuery; _sysInfoSearcher = new ManagementObjectSearcher(string.Format("SELECT * FROM {0}", _sysInfoQuery.QueryText)); _sysInfoResult = new SysInfoResult(_sysInfoQuery.Name); foreach (ManagementObject managementObject in _sysInfoSearcher.Get()) { _sysInfoResult.AddNode(managementObject.GetPropertyValue(_sysInfoQuery.DisplayField).ToString().Trim()); _sysInfoResult.AddChildren(GetChildren(managementObject)); } return _sysInfoResult; } private IEnumerable<SysInfoResult> GetChildren(ManagementBaseObject managementObject) { SysInfoResult childResult = null; ICollection<SysInfoResult> childList = new List<SysInfoResult>(); foreach (var propertyData in managementObject.Properties) { if (childResult == null) { childResult = new SysInfoResult(_sysInfoQuery.Name + "_Child"); childList.Add(childResult); } var nodeValue = string.Format("{0} = {1}", propertyData.Name, Convert.ToString(propertyData.Value)); childResult.Nodes.Add(nodeValue); } return childList; } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/ErrorReport/SystemInfo/SysInfoRetriever.cs
C#
gpl3
2,109
using System.Collections.Generic; using System.Linq; #pragma warning disable 1591 namespace Samba.Presentation.Common.ErrorReport.SystemInfo { public class SysInfoResult { private readonly string _name; private readonly List<string> _nodes = new List<string>(); private readonly List<SysInfoResult> _childResults = new List<SysInfoResult>(); public SysInfoResult(string name) { _name = name; } public void AddNode(string node) { _nodes.Add(node); } public void AddChildren(IEnumerable<SysInfoResult> children) { ChildResults.AddRange(children); } public List<string> Nodes { get { return _nodes; } } private void Clear() { _nodes.Clear(); } private void AddRange(IEnumerable<string> nodes) { _nodes.AddRange(nodes); } public string Name { get { return _name; } } public List<SysInfoResult> ChildResults { get { return _childResults; } } public SysInfoResult Filter(string[] filterStrings) { var filteredNodes = (from node in ChildResults[0].Nodes from filter in filterStrings where node.Contains(filter + " = ") //TODO a little too primitive select node).ToList(); ChildResults[0].Clear(); ChildResults[0].AddRange(filteredNodes); return this; } } } #pragma warning restore 1591
zzgaminginc-pointofssale
Samba.Presentation.Common/ErrorReport/SystemInfo/SysInfoResult.cs
C#
gpl3
1,522
namespace Samba.Presentation.Common.ErrorReport.SystemInfo { internal class SysInfoQuery { private readonly string _name; private readonly bool _useNameAsDisplayField; private readonly string _queryText; public SysInfoQuery(string name, string query, bool useNameAsDisplayField) { _name = name; _useNameAsDisplayField = useNameAsDisplayField; _queryText = query; } public string QueryText { get { return _queryText; } } public string DisplayField { get { return _useNameAsDisplayField ? "Name" : "Caption"; } } public string Name { get { return _name; } } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/ErrorReport/SystemInfo/SysInfoQuery.cs
C#
gpl3
799
using System.Collections.Generic; using System.Text; namespace Samba.Presentation.Common.ErrorReport.SystemInfo { ///<summary> /// Map SysInfoResults to human-readable formats ///</summary> public static class SysInfoResultMapper { /// <summary> /// create a string representation of a list of SysInfoResults, customised specifically (eg 2-level deep) /// </summary> public static string CreateStringList(IEnumerable<SysInfoResult> results) { var stringBuilder = new StringBuilder(); foreach (var result in results) { stringBuilder.AppendLine(result.Name); foreach (var nodeValueParent in result.Nodes) { stringBuilder.AppendLine("-" + nodeValueParent); foreach (var childResult in result.ChildResults) { foreach (var nodeValue in childResult.Nodes) { stringBuilder.AppendLine("--" + nodeValue); } } } stringBuilder.AppendLine(); } return stringBuilder.ToString(); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/ErrorReport/SystemInfo/SysInfoResultMapper.cs
C#
gpl3
1,310
namespace Samba.Presentation.Common.ErrorReport.SystemInfo { internal static class SysInfoQueries { public static readonly SysInfoQuery OperatingSystem = new SysInfoQuery("Operating System", "Win32_OperatingSystem", false); public static readonly SysInfoQuery Machine = new SysInfoQuery("Machine", "Win32_ComputerSystem", true); } }
zzgaminginc-pointofssale
Samba.Presentation.Common/ErrorReport/SystemInfo/SysInfoQueries.cs
C#
gpl3
364
using System; using System.Collections.Generic; using System.Reflection; using System.Text; using Samba.Infrastructure.Settings; using Samba.Presentation.Common.ErrorReport.SystemInfo; namespace Samba.Presentation.Common.ErrorReport { internal class ExceptionReportBuilder { private readonly ExceptionReportInfo _reportInfo; private StringBuilder _stringBuilder; private readonly IEnumerable<SysInfoResult> _sysInfoResults; public ExceptionReportBuilder(ExceptionReportInfo reportInfo) { _reportInfo = reportInfo; } public ExceptionReportBuilder(ExceptionReportInfo reportInfo, IEnumerable<SysInfoResult> sysInfoResults) : this(reportInfo) { _sysInfoResults = sysInfoResults; } public string Build() { _stringBuilder = new StringBuilder().AppendLine("-----------------------------"); BuildGeneralInfo(); BuildExceptionInfo(); BuildAssemblyInfo(); BuildSysInfo(); return _stringBuilder.ToString(); } private void BuildGeneralInfo() { _stringBuilder.AppendLine("[General Info]") .AppendLine() .AppendLine("Application: SambaPOS") .AppendLine("Version: " + LocalSettings.AppVersion) .AppendLine("Region: " + LocalSettings.CurrentLanguage) .AppendLine("DB: " + LocalSettings.DatabaseLabel) .AppendLine("Machine: " + _reportInfo.MachineName) .AppendLine("User: " + _reportInfo.UserName) .AppendLine("Date: " + _reportInfo.ExceptionDate.ToShortDateString()) .AppendLine("Time: " + _reportInfo.ExceptionDate.ToShortTimeString()) .AppendLine(); _stringBuilder.AppendLine("User Explanation:") .AppendLine() .AppendFormat("{0} said \"{1}\"", _reportInfo.UserName, _reportInfo.UserExplanation) .AppendLine().AppendLine("-----------------------------").AppendLine(); } private void BuildExceptionInfo() { for (var index = 0; index < _reportInfo.Exceptions.Count; index++) { var exception = _reportInfo.Exceptions[index]; _stringBuilder.AppendLine(string.Format("[Exception Info {0}]", index + 1)) .AppendLine() .AppendLine(ExceptionHierarchyToString(exception)) .AppendLine().AppendLine("-----------------------------").AppendLine(); } } private void BuildAssemblyInfo() { _stringBuilder.AppendLine("[Assembly Info]") .AppendLine() .AppendLine(CreateReferencesString(_reportInfo.AppAssembly)) .AppendLine("-----------------------------").AppendLine(); } private void BuildSysInfo() { _stringBuilder.AppendLine("[System Info]").AppendLine(); _stringBuilder.Append(SysInfoResultMapper.CreateStringList(_sysInfoResults)); _stringBuilder.AppendLine("-----------------------------").AppendLine(); } public static string CreateReferencesString(Assembly assembly) { var stringBuilder = new StringBuilder(); foreach (var assemblyName in assembly.GetReferencedAssemblies()) { stringBuilder.AppendLine(string.Format("{0}, Version={1}", assemblyName.Name, assemblyName.Version)); } return stringBuilder.ToString(); } private static string ExceptionHierarchyToString(Exception exception) { var currentException = exception; var stringBuilder = new StringBuilder(); var count = 0; while (currentException != null) { if (count++ == 0) stringBuilder.AppendLine("Top-level Exception"); else stringBuilder.AppendLine("Inner Exception " + (count - 1)); stringBuilder.AppendLine("Type: " + currentException.GetType()) .AppendLine("Message: " + currentException.Message) .AppendLine("Source: " + currentException.Source); if (currentException.StackTrace != null) stringBuilder.AppendLine("Stack Trace: " + currentException.StackTrace.Trim()); stringBuilder.AppendLine(); currentException = currentException.InnerException; } var exceptionString = stringBuilder.ToString(); return exceptionString.TrimEnd(); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/ErrorReport/ExceptionReportBuilder.cs
C#
gpl3
4,990
using System; using System.Windows; namespace Samba.Presentation.Common.ErrorReport { public static class ExceptionReporter { public static void Show(params Exception[] exceptions) { if (exceptions == null) return; try { var viewModel = new ErrorReportViewModel(exceptions); var view = new ErrorReportView { DataContext = viewModel }; view.ShowDialog(); } catch (Exception internalException) { MessageBox.Show(internalException.Message); } } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/ErrorReport/ExceptionReporter.cs
C#
gpl3
654
using System; using System.Threading; namespace Samba.Presentation.Common.ErrorReport { /// <summary> /// Base class for all classes wanting to implement <see cref="IDisposable"/>. /// </summary> /// <remarks> /// Base on an article by Davy Brion /// <see href="http://davybrion.com/blog/2008/06/disposing-of-the-idisposable-implementation/"/>. /// </remarks> public abstract class Disposable : IDisposable { private int disposed; protected Disposable() { disposed = 0; } public bool IsDisposed { get { return disposed == 1; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (Interlocked.CompareExchange(ref disposed, 1, 0) == 0) { if (disposing) { DisposeManagedResources(); } DisposeUnmanagedResources(); } } protected virtual void DisposeManagedResources() {} protected virtual void DisposeUnmanagedResources() {} ~Disposable() { Dispose(false); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/ErrorReport/Disposable.cs
C#
gpl3
1,349
using System.Windows; namespace Samba.Presentation.Common.ErrorReport { /// <summary> /// Interaction logic for ErrorReportView.xaml /// </summary> public partial class ErrorReportView : Window { public ErrorReportView() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { Close(); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/ErrorReport/ErrorReportView.xaml.cs
C#
gpl3
446
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Reflection; using System.Text; using System.Windows; using Microsoft.Win32; using Samba.Localization.Properties; namespace Samba.Presentation.Common.ErrorReport { class ErrorReportViewModel : ObservableObject { private bool? _dialogResult; public bool? DialogResult { get { return _dialogResult; } set { _dialogResult = value; RaisePropertyChanged("DialogResult"); } } public ExceptionReportInfo Model { get; set; } public ErrorReportViewModel(IEnumerable<Exception> exceptions) { Model = new ExceptionReportInfo { AppAssembly = Assembly.GetCallingAssembly() }; Model.SetExceptions(exceptions); CopyCommand = new CaptionCommand<string>(Resources.Copy, OnCopyCommand); SaveCommand = new CaptionCommand<string>(Resources.Save, OnSaveCommand); SubmitCommand = new CaptionCommand<string>(Resources.Send, OnSubmitCommand); } private void OnSubmitCommand(string obj) { if (string.IsNullOrEmpty(UserMessage)) { if (MessageBox.Show(Resources.ErrorReportWithoutFeedback, Resources.Information, MessageBoxButton.YesNo) == MessageBoxResult.No) return; } DialogResult = false; SubmitError(); } public void SubmitError() { var tempFile = Path.GetTempFileName().Replace(".tmp", ".txt"); SaveReportToFile(tempFile); string queryString = string.Format("from={0}&emaila={1}&file={2}", Uri.EscapeDataString("info@sambapos.com"), Uri.EscapeDataString("SambaPOS Error Report"), Uri.EscapeDataString(tempFile)); var c = new WebClient(); var result = c.UploadFile("http://reports.sambapos.com/file.php?" + queryString, "POST", tempFile); MessageBox.Show(Encoding.ASCII.GetString(result)); } private void OnSaveCommand(string obj) { var sf = new SaveFileDialog() { DefaultExt = ".txt" }; if (sf.ShowDialog() == true) { SaveReportToFile(sf.FileName); } } private void OnCopyCommand(object obj) { Clipboard.SetText(ErrorReportAsText); } public ICaptionCommand CopyCommand { get; set; } public ICaptionCommand SaveCommand { get; set; } public ICaptionCommand SubmitCommand { get; set; } public ICaptionCommand CloseCommand { get; set; } private string _errorReportAsText; public string ErrorReportAsText { get { return _errorReportAsText ?? (_errorReportAsText = GenerateReport()); } set { _errorReportAsText = value; } } public string ErrorMessage { get { return Model.MainException.Message; } } public string UserMessage { get { return Model.UserExplanation; } set { Model.UserExplanation = value; _errorReportAsText = null; RaisePropertyChanged("ErrorReportAsText"); } } private string GenerateReport() { var rg = new ExceptionReportGenerator(Model); return rg.CreateExceptionReport(); } public string GetErrorReport() { _errorReportAsText = null; return ErrorReportAsText; } public void SaveReportToFile(string fileName) { if (string.IsNullOrEmpty(fileName)) return; try { using (var stream = File.OpenWrite(fileName)) { var writer = new StreamWriter(stream); writer.Write(ErrorReportAsText); writer.Flush(); } } catch (Exception exception) { MessageBox.Show(string.Format("Unable to save file '{0}' : {1}", fileName, exception.Message)); } } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/ErrorReport/ErrorReportViewModel.cs
C#
gpl3
4,401
using System; using System.Globalization; using System.Windows; using System.Windows.Controls; namespace Samba.Presentation.Common { /// <summary> /// FilteredTextBox is a class that represent a TecBox which can contains only letters, digits, punctuation, etc.... /// The choice is done by specifying the Type property. /// </summary> public class FilteredTextBox : TextBox { #region Constructors static FilteredTextBox() { //DefaultStyleKeyProperty.OverrideMetadata(typeof(FilteredTextBox), new FrameworkPropertyMetadata((typeof(FilteredTextBox)))); } public FilteredTextBox() : base() { } #endregion #region Properties /// <summary> /// Indicate the type of the filter to apply. /// </summary> public FilteredTextBoxType Type { get { return (FilteredTextBoxType)GetValue(TypeProperty); } set { SetValue(TypeProperty, value); } } public static readonly DependencyProperty TypeProperty = DependencyProperty.Register("Type", typeof(FilteredTextBoxType), typeof(FilteredTextBox), new FrameworkPropertyMetadata(FilteredTextBoxType.Letters)); /// <summary> /// Indicate the label to use to describe the FilteredTextBox. /// </summary> public string LabelInfo { get { return (string)GetValue(LabelInfoProperty); } set { SetValue(LabelInfoProperty, value); } } // Using a DependencyProperty as the backing store for LabelInfo. This enables animation, styling, binding, etc... public static readonly DependencyProperty LabelInfoProperty = DependencyProperty.Register("LabelInfo", typeof(string), typeof(FilteredTextBox), new FrameworkPropertyMetadata(string.Empty)); #endregion /// <summary> /// Enum used to specify the type of the FilteredTextBox. /// </summary> public enum FilteredTextBoxType { Digits, Letters, Punctuation, Symbol, Number } protected override void OnGotFocus(RoutedEventArgs e) { base.OnGotFocus(e); this.SelectAll(); } protected override void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e) { base.OnPreviewTextInput(e); if (e.Text.Length != 1) return; var letterOrDigit = Convert.ToChar(e.Text); var ds = CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator[0]; switch (Type) { case FilteredTextBoxType.Digits: if (!char.IsDigit(letterOrDigit)) { e.Handled = true; } break; case FilteredTextBoxType.Number: if (letterOrDigit == '-' && SelectionStart > 0) e.Handled = true; if (letterOrDigit == ds && Text.Contains(ds.ToString())) e.Handled = true; else if (!char.IsDigit(letterOrDigit) && (letterOrDigit != ds) && (letterOrDigit != '-')) { e.Handled = true; } break; case FilteredTextBoxType.Letters: if (!char.IsLetterOrDigit(letterOrDigit)) { e.Handled = true; } break; case FilteredTextBoxType.Punctuation: if (!char.IsPunctuation(letterOrDigit)) { e.Handled = true; } break; case FilteredTextBoxType.Symbol: if (!char.IsSymbol(letterOrDigit)) { e.Handled = true; } break; default: break; } } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/FilteredTextBox.cs
C#
gpl3
4,331
using Microsoft.Practices.Prism.Modularity; using Microsoft.Practices.ServiceLocation; namespace Samba.Presentation.Common { public abstract class ModuleBase : IModule { public void Initialize() { var moduleLifecycleService = ServiceLocator.Current.GetInstance<IModuleInitializationService>(); moduleLifecycleService.RegisterForStage(OnPreInitialization, ModuleInitializationStage.PreInitialization); moduleLifecycleService.RegisterForStage(OnInitialization, ModuleInitializationStage.Initialization); moduleLifecycleService.RegisterForStage(OnPostInitialization, ModuleInitializationStage.PostInitialization); moduleLifecycleService.RegisterForStage(OnStartUp, ModuleInitializationStage.StartUp); } protected virtual void OnPreInitialization() { } protected virtual void OnInitialization() { } protected virtual void OnPostInitialization() { } protected virtual void OnStartUp() { } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/ModuleBase.cs
C#
gpl3
1,116
using System; using System.Windows; using System.Windows.Controls; namespace Samba.Presentation.Common.Interaction { /// <summary> /// Interaction logic for StringGetterForm.xaml /// </summary> public partial class StringGetterForm : Window { public StringGetterForm() { InitializeComponent(); Width = Properties.Settings.Default.SGWidth; Height = Properties.Settings.Default.SGHeight; } private void Button_Click(object sender, RoutedEventArgs e) { TextBox.Text = ""; Close(); } private void Button_Click_1(object sender, RoutedEventArgs e) { Close(); } private void Window_Activated(object sender, EventArgs e) { TextBox.Focus(); } private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { Properties.Settings.Default.SGHeight = Height; Properties.Settings.Default.SGWidth = Width; } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Interaction/StringGetterForm.xaml.cs
C#
gpl3
1,119
using System; using System.Windows.Media.Effects; using System.Windows; using System.Windows.Media; namespace Samba.Presentation.Common.Interaction.Grayscale { public class GrayscaleEffect : ShaderEffect { private static readonly PixelShader _pixelShader = new PixelShader() { UriSource = new Uri(@"pack://application:,,,/Samba.Presentation.Common;component/Interaction/Grayscale/GrayscaleEffect.ps") }; public GrayscaleEffect() { PixelShader = _pixelShader; UpdateShaderValue(InputProperty); UpdateShaderValue(DesaturationFactorProperty); } public static readonly DependencyProperty InputProperty = RegisterPixelShaderSamplerProperty("Input", typeof(GrayscaleEffect), 0); public Brush Input { get { return (Brush)GetValue(InputProperty); } set { SetValue(InputProperty, value); } } public static readonly DependencyProperty DesaturationFactorProperty = DependencyProperty.Register("DesaturationFactor", typeof(double), typeof(GrayscaleEffect), new UIPropertyMetadata(0.0, PixelShaderConstantCallback(0), CoerceDesaturationFactor)); public double DesaturationFactor { get { return (double)GetValue(DesaturationFactorProperty); } set { SetValue(DesaturationFactorProperty, value); } } private static object CoerceDesaturationFactor(DependencyObject d, object value) { var effect = (GrayscaleEffect)d; var newFactor = (double)value; if (newFactor < 0.0 || newFactor > 1.0) { return effect.DesaturationFactor; } return newFactor; } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Interaction/Grayscale/GrayscaleEffect.cs
C#
gpl3
1,809
using System.Windows; namespace Samba.Presentation.Common.Interaction { /// <summary> /// Interaction logic for ListSorterForm.xaml /// </summary> public partial class ListSorterForm : Window { public ListSorterForm() { InitializeComponent(); Height = Properties.Settings.Default.LSHeight; Width = Properties.Settings.Default.LSWidth; } private void ButtonClick1(object sender, RoutedEventArgs e) { DialogResult = true; Close(); } private void ButtonClick(object sender, RoutedEventArgs e) { DialogResult = false; } private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { Properties.Settings.Default.LSHeight = Height; Properties.Settings.Default.LSWidth = Width; } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Interaction/ListSorterForm.xaml.cs
C#
gpl3
957
using System.ComponentModel; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using PropertyTools.Wpf; using Samba.Presentation.Common.Services; namespace Samba.Presentation.Common.Interaction { /// <summary> /// Interaction logic for PropertyEditorForm.xaml /// </summary> public partial class PropertyEditorForm : Window { private DataGrid _dataGrid; public PropertyEditorForm() { InitializeComponent(); Height = Properties.Settings.Default.PEHeight; Width = Properties.Settings.Default.PEWidth; btnDetails.Visibility = Visibility.Hidden; } private void Button_Click(object sender, RoutedEventArgs e) { Close(); } private void PropertyGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) { if (sender is DataGrid) { _dataGrid = sender as DataGrid; btnDetails.Visibility = Visibility.Visible; } var browsable = ((PropertyDescriptor)e.PropertyDescriptor).Attributes[typeof(BrowsableAttribute)] as BrowsableAttribute; if (browsable != null && !browsable.Browsable) { e.Cancel = true; return; } var displayName = ((PropertyDescriptor)e.PropertyDescriptor).Attributes[typeof(DisplayNameAttribute)] as DisplayNameAttribute; if (displayName != null) { e.Column.Header = displayName.DisplayName; } } private void Window_Closing(object sender, CancelEventArgs e) { Properties.Settings.Default.PEHeight = Height; Properties.Settings.Default.PEWidth = Width; } private void PropertyGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e) { if (e.ChangedButton == MouseButton.Right) { InteractionService.UserIntraction.EditProperties(((DataGrid)sender).SelectedItem); } } private void PropertyGrid_PreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter && Keyboard.IsKeyDown(Key.RightCtrl)) { InteractionService.UserIntraction.EditProperties(((DataGrid)sender).SelectedItem); e.Handled = true; } } private void Button_Click_1(object sender, RoutedEventArgs e) { if (_dataGrid != null && _dataGrid.SelectedItem != null) InteractionService.UserIntraction.EditProperties(_dataGrid.SelectedItem); } private void PropertyGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e) { if (e.EditingElement is TextBox) { ((TextBox)e.EditingElement).Text = ((TextBox)e.EditingElement).Text.Replace("\b", ""); } } private void SimpleGrid_SourceUpdated(object sender, System.Windows.Data.DataTransferEventArgs e) { btnDetails.Visibility = Visibility.Visible; } private void SimpleGrid_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e) { foreach (var selectedItem in (sender as SimpleGrid).SelectedItems) { InteractionService.UserIntraction.EditProperties(selectedItem); e.Handled = true; } } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Interaction/PropertyEditorForm.xaml.cs
C#
gpl3
3,665
using System; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.Windows; using System.Windows.Data; using System.Windows.Media; using System.Windows.Shapes; using PropertyTools.Wpf; using Samba.Presentation.Common.Services; using ColumnDefinition = PropertyTools.Wpf.ColumnDefinition; namespace Samba.Presentation.Common.Interaction { /// <summary> /// Interaction logic for GridEditorForm.xaml /// </summary> public partial class GridEditorForm : Window { public GridEditorForm() { InitializeComponent(); } public void SetList(IList items) { if (items.Count > 0) { MainGrid.ColumnHeaders = new StringCollection(); var itemType = items[0].GetType(); foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(itemType)) { if (!descriptor.IsBrowsable) { continue; } var cd = new ColumnDefinition() { DataField = descriptor.Name }; if (descriptor.PropertyType == typeof(SolidColorBrush)) { var colorDisplayTemplate = new DataTemplate { DataType = typeof(SolidColorBrush) }; var fef = new FrameworkElementFactory(typeof(Rectangle)); fef.SetBinding(Shape.FillProperty, new Binding(descriptor.Name)); fef.SetValue(WidthProperty, 12.0); fef.SetValue(HeightProperty, 12.0); fef.SetValue(MarginProperty, new Thickness(4, 0, 4, 0)); fef.SetValue(Shape.StrokeThicknessProperty, 1.0); fef.SetValue(Shape.StrokeProperty, Brushes.Gainsboro); colorDisplayTemplate.VisualTree = fef; cd.DisplayTemplate = colorDisplayTemplate; var colorEditTemplate = new DataTemplate { DataType = typeof(SolidColorBrush) }; var fefe = new FrameworkElementFactory(typeof(ColorPicker)); fefe.SetBinding(ColorPicker.SelectedColorProperty, new Binding(descriptor.Name) { Converter = new BrushToColorConverter() }); colorEditTemplate.VisualTree = fefe; cd.EditTemplate = colorEditTemplate; } if (descriptor.PropertyType == typeof(string) && descriptor.Name.Contains("Image")) { var colorEditTemplate = new DataTemplate { DataType = typeof(string) }; var fefe = new FrameworkElementFactory(typeof(FilePicker)); fefe.SetBinding(FilePicker.FilePathProperty, new Binding(descriptor.Name)); colorEditTemplate.VisualTree = fefe; cd.EditTemplate = colorEditTemplate; } var displayName = descriptor.DisplayName; if (!String.IsNullOrEmpty(displayName)) cd.Header = descriptor.DisplayName; MainGrid.ColumnDefinitions.Add(cd); } MainGrid.Content = items; } } private void ButtonClick(object sender, RoutedEventArgs e) { foreach (var selectedItem in MainGrid.SelectedItems) { InteractionService.UserIntraction.EditProperties(selectedItem); e.Handled = true; } } private void Button_Click_1(object sender, RoutedEventArgs e) { Close(); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Interaction/GridEditorForm.xaml.cs
C#
gpl3
3,900
using System.Windows; namespace Samba.Presentation.Common.Interaction { /// <summary> /// Interaction logic for FeedbackWindow.xaml /// </summary> public partial class FeedbackWindow : Window { public FeedbackWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { Close(); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Interaction/FeedbackWindow.xaml.cs
C#
gpl3
443
using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Windows; using System.ComponentModel.Composition; using System.Windows.Media; using System.Windows.Media.Effects; using PropertyTools.Wpf; using Samba.Infrastructure.Data; using Samba.Localization.Properties; using Samba.Presentation.Common.Interaction.Grayscale; using Samba.Services; using FlexButton; namespace Samba.Presentation.Common.Interaction { public class CollectionProxy<T> { [WideProperty] public ObservableCollection<T> List { get; set; } public CollectionProxy(IEnumerable<T> list) { List = new ObservableCollection<T>(list); } } public class PopupData { public string Title { get; set; } public string Content { get; set; } public object DataObject { get; set; } public string EventMessage { get; set; } private string _headerColor; public string HeaderColor { get { return _headerColor; } set { _headerColor = value; ContentColor = UpdateContentColor(); } } private string UpdateContentColor() { var color = ((TypeConverter)new ColorConverter()).ConvertFromString(HeaderColor); var result = color is Color ? (Color)color : new Color(); return result.Lerp(Colors.White, 0.80f).ToString(); } public string ContentColor { get; set; } } public class PopupDataViewModel { private readonly IList<PopupData> _popupCache; private readonly ObservableCollection<PopupData> _popupList; public ObservableCollection<PopupData> PopupList { get { return _popupList; } } public CaptionCommand<PopupData> ClickButtonCommand { get; set; } public PopupDataViewModel() { _popupCache = new List<PopupData>(); _popupList = new ObservableCollection<PopupData>(); ClickButtonCommand = new CaptionCommand<PopupData>("Click", OnButtonClick); } private void OnButtonClick(PopupData obj) { if (!string.IsNullOrEmpty(obj.EventMessage)) obj.PublishEvent(EventTopicNames.PopupClicked); _popupList.Remove(obj); } public void Add(string title, string content, object dataObject, string eventMessage, string headerColor) { _popupCache.Add(new PopupData { Title = title, Content = content, DataObject = dataObject, EventMessage = eventMessage, HeaderColor = headerColor }); } public void DisplayPopups() { if (_popupCache.Count == 0) return; foreach (var popupData in _popupCache) { _popupList.Add(popupData); } _popupCache.Clear(); } } [Export(typeof(IUserInteraction))] public class UserInteraction : IUserInteraction { private readonly PopupDataViewModel _popupDataViewModel; private SplashScreenForm _splashScreen; private KeyboardWindow _keyboardWindow; public KeyboardWindow KeyboardWindow { get { return _keyboardWindow ?? (_keyboardWindow = CreateKeyboardWindow()); } set { _keyboardWindow = value; } } private PopupWindow _popupWindow; public UserInteraction() { _popupDataViewModel = new PopupDataViewModel(); RuleActionTypeRegistry.RegisterActionType("ShowMessage", Resources.ShowMessage, new { Message = "" }); RuleActionTypeRegistry.RegisterActionType("DisplayPopup", Resources.DisplayPopup, new { Title = "", Message = "", Color = "" }); EventServiceFactory.EventService.GetEvent<GenericEvent<ActionData>>().Subscribe(x => { if (x.Value.Action.ActionType == "ShowMessage") { var param = x.Value.GetAsString("Message"); if (!string.IsNullOrEmpty(param)) GiveFeedback(param); } if (x.Value.Action.ActionType == "DisplayPopup") { var title = x.Value.GetAsString("Title"); var message = x.Value.GetAsString("Message"); var color = x.Value.GetAsString("Color"); color = string.IsNullOrEmpty(color.Trim()) ? "DarkRed" : color; if (!string.IsNullOrEmpty(message.Trim())) DisplayPopup(title, message, null, "", color); } }); } public PopupWindow PopupWindow { get { return _popupWindow ?? (_popupWindow = CreatePopupWindow()); } } private PopupWindow CreatePopupWindow() { return new PopupWindow { DataContext = _popupDataViewModel }; } private static KeyboardWindow CreateKeyboardWindow() { return new KeyboardWindow(); } public string[] GetStringFromUser(string caption, string description) { return GetStringFromUser(caption, description, ""); } public string[] GetStringFromUser(string caption, string description, string defaultValue) { var form = new StringGetterForm { Title = caption, TextBox = { Text = defaultValue }, DescriptionLabel = { Text = description } }; form.ShowDialog(); var result = new List<string>(); for (int i = 0; i < form.TextBox.LineCount; i++) { string value = form.TextBox.GetLineText(i).Trim('\r', '\n', ' ', '\t'); if (!string.IsNullOrEmpty(value)) { result.Add(value); } } return result.ToArray(); } public IList<IOrderable> ChooseValuesFrom( IList<IOrderable> values, IList<IOrderable> selectedValues, string caption, string description, string singularName, string pluralName) { selectedValues = new ObservableCollection<IOrderable>(selectedValues.OrderBy(x => x.Order)); ReorderItems(selectedValues); var form = new ValueChooserForm(values, selectedValues) { Title = caption, DescriptionLabel = { Content = description }, ValuesLabel = { Content = string.Format(Resources.List_f, singularName) }, SelectedValuesLabel = { Content = string.Format(Resources.Selected_f, pluralName) } }; form.ShowDialog(); ReorderItems(form.SelectedValues); return form.SelectedValues; } public void EditProperties(object item) { var form = new PropertyEditorForm { PropertyEditorControl = { SelectedObject = item } }; form.ShowDialog(); } public void EditProperties<T>(IList<T> items) { var form = new GridEditorForm(); form.SetList(items.ToList()); form.ShowDialog(); } public void SortItems(IEnumerable<IOrderable> list, string caption, string description) { var items = new ObservableCollection<IOrderable>(list.OrderBy(x => x.Order)); ReorderItems(items); var form = new ListSorterForm { MainListBox = { ItemsSource = items }, Title = caption, DescriptionLabel = { Text = description } }; form.ShowDialog(); if (form.DialogResult != null && form.DialogResult.Value) { ReorderItems(items); } } public bool AskQuestion(string question) { return MessageBox.Show(question, "Soru", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.Yes; } public void GiveFeedback(string message) { var window = new FeedbackWindow { MessageText = { Text = message }, Topmost = true }; window.ShowDialog(); } public void ShowKeyboard() { KeyboardWindow.ShowKeyboard(); } public void HideKeyboard() { KeyboardWindow.HideKeyboard(); } public void ToggleKeyboard() { if (KeyboardWindow.IsVisible) HideKeyboard(); else ShowKeyboard(); } public void ToggleSplashScreen() { if (_splashScreen != null) { _splashScreen.Hide(); _splashScreen = null; } else { _splashScreen = new SplashScreenForm(); _splashScreen.Show(); } } public void DisplayPopup(string title, string content, object dataObject, string eventMessage, string headerColor) { _popupDataViewModel.Add(title, content, dataObject, eventMessage, headerColor); PopupWindow.Show(); MethodQueue.Queue("DisplayPopups", DisplayPopups); } private BlurEffect _blurEffect; public BlurEffect BlurEffect { get { return _blurEffect ?? (_blurEffect = new BlurEffect { Radius = 20 }); } } private GrayscaleEffect _grayscaleEffect; public GrayscaleEffect GrayscaleEffect { get { return _grayscaleEffect ?? (_grayscaleEffect = new GrayscaleEffect { DesaturationFactor = 50 }); } } public void BlurMainWindow() { Application.Current.MainWindow.Effect = GrayscaleEffect; ((UIElement)VisualTreeHelper.GetChild(Application.Current.MainWindow, 0)).Effect = BlurEffect; } public void DeblurMainWindow() { Application.Current.MainWindow.Effect = null; ((UIElement)VisualTreeHelper.GetChild(Application.Current.MainWindow, 0)).Effect = null; } public void DisplayPopups() { _popupDataViewModel.DisplayPopups(); } private static void ReorderItems(IEnumerable<IOrderable> list) { var order = 10; foreach (var orderable in list) { orderable.Order = order; order += 10; } } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Interaction/UserInteraction.cs
C#
gpl3
11,199
using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Input; using System.Collections; using System.Collections.ObjectModel; using Samba.Infrastructure; using Samba.Infrastructure.Data; using Samba.Infrastructure.Data.Serializer; namespace Samba.Presentation.Common.Interaction { /// <summary> /// Interaction logic for ValueChooserForm.xaml /// </summary> public partial class ValueChooserForm : Window { private readonly IList<IOrderable> _selectedValues; private readonly IList<IOrderable> _values; public ValueChooserForm(IList<IOrderable> values, IList<IOrderable> selectedValues) { InitializeComponent(); Width = Properties.Settings.Default.VCWidth; Height = Properties.Settings.Default.VCHeight; _selectedValues = selectedValues; SelectedValues = new ObservableCollection<IOrderable>(_selectedValues); _values = values; InitValues(); ValuesListBox.ItemsSource = Values; SelectedValuesListBox.ItemsSource = SelectedValues; SearchTextBox.Focus(); } private void InitValues() { Values = new ObservableCollection<IOrderable>(_values); foreach (var item in SelectedValues) { if (Values.Contains(item)) Values.Remove(item); } } public ObservableCollection<IOrderable> Values { get; set; } public ObservableCollection<IOrderable> SelectedValues { get; set; } private void Button_Click(object sender, RoutedEventArgs e) { Close(); } private void Button_Click_1(object sender, RoutedEventArgs e) { SelectedValues = new ObservableCollection<IOrderable>(_selectedValues); Close(); } private void MoveValuesToSelectedValues() { IList selectedItems = new ArrayList(ValuesListBox.SelectedItems); foreach (IOrderable item in selectedItems) { Values.Remove(item); SelectedValues.Add(item); } } private void MoveSelectedValuesToValues() { IList selectedItems = new ArrayList(SelectedValuesListBox.SelectedItems); foreach (IOrderable item in selectedItems) { Values.Add(item); SelectedValues.Remove(item); } } private void CopySelectedValuesToValues() { IList selectedItems = new ArrayList(SelectedValuesListBox.Items); foreach (IOrderable item in selectedItems) { if (!Values.Contains(item)) Values.Add(ObjectCloner.Clone(item)); } } private void ValuesListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e) { MoveValuesToSelectedValues(); } private void SelectedValuesListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e) { MoveSelectedValuesToValues(); } private void SearchTextBox_Search(object sender, RoutedEventArgs e) { if (!string.IsNullOrEmpty(SearchTextBox.Text)) { Values = new ObservableCollection<IOrderable>(_values.Where(x => x.UserString.ToLower().Contains(SearchTextBox.Text.ToLower()) && !SelectedValues.Contains(x))); } else { InitValues(); } ValuesListBox.ItemsSource = Values; ValuesListBox.SelectedItem = null; } private void SearchTextBox_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter && Keyboard.IsKeyDown(Key.RightCtrl)) { ValuesListBox.SelectAll(); MoveValuesToSelectedValues(); } } private void Window_PreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Escape && string.IsNullOrEmpty(SearchTextBox.Text)) { Close(); } } private void Button_Click_2(object sender, RoutedEventArgs e) { MoveValuesToSelectedValues(); } private void Button_Click_3(object sender, RoutedEventArgs e) { MoveSelectedValuesToValues(); } private void MenuItem_Click(object sender, RoutedEventArgs e) { CopySelectedValuesToValues(); } private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { Properties.Settings.Default.VCHeight = Height; Properties.Settings.Default.VCWidth = Width; } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Interaction/ValueChooserForm.xaml.cs
C#
gpl3
5,042
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.Presentation.Common.Interaction { /// <summary> /// Interaction logic for SplashScreen.xaml /// </summary> public partial class SplashScreenForm : Window { public SplashScreenForm() { InitializeComponent(); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Interaction/SplashScreenForm.xaml.cs
C#
gpl3
672
using System; using System.Windows; using System.Windows.Interop; namespace Samba.Presentation.Common.Interaction { /// <summary> /// Interaction logic for PopupWindow.xaml /// </summary> public partial class PopupWindow : Window { public PopupWindow() { InitializeComponent(); Height = Application.Current.MainWindow.WindowState == WindowState.Normal ? SystemParameters.WorkArea.Bottom : SystemParameters.PrimaryScreenHeight-25; Width = 250; Top = 0; Left = SystemParameters.PrimaryScreenWidth - Width; Show(); } private void Window_Loaded(object sender, RoutedEventArgs e) { SetWindowStyle(); } private void SetWindowStyle() { var hwnd = new WindowInteropHelper(this).Handle; const int gwlExstyle = (-20); const int wsExNoactivate = 0x08000000; const int wsExToolWindow = 0x00000080; NativeWin32.SetWindowLong(hwnd, gwlExstyle, (IntPtr)(wsExNoactivate | wsExToolWindow)); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Interaction/PopupWindow.xaml.cs
C#
gpl3
1,196
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Interop; using System.Windows.Media; namespace Samba.Presentation.Common.Interaction { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class KeyboardWindow : Window { public TextBox TargetTextBox { get; set; } public KeyboardWindow() { InitializeComponent(); Top = Properties.Settings.Default.KeyboardTop; Left = Properties.Settings.Default.KeyboardLeft; Height = Properties.Settings.Default.KeyboardHeight; Width = Properties.Settings.Default.KeyboardWidth; if (Height <= 0) ResetWindowSize(); else if ((Top + Height) > SystemParameters.PrimaryScreenHeight) ResetWindowSize(); else if (Left > Application.Current.MainWindow.Left + Application.Current.MainWindow.Width) ResetWindowSize(); else if (Left < 0) ResetWindowSize(); } private void SetWindowStyle() { var hwnd = new WindowInteropHelper(this).Handle; const int gwlExstyle = (-20); const int wsExNoactivate = 0x08000000; const int wsExToolWindow = 0x00000080; NativeWin32.SetWindowLong(hwnd, gwlExstyle, (IntPtr)(wsExNoactivate | wsExToolWindow)); } private void Window_Loaded(object sender, RoutedEventArgs e) { SetWindowStyle(); var source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle); if (source != null) source.AddHook(WndProc); } public void ResetWindowSize() { if (Application.Current.MainWindow.WindowState == WindowState.Normal) { Height = Application.Current.MainWindow.Height / 2; Width = Application.Current.MainWindow.Width; Top = Application.Current.MainWindow.Top + Height; Left = Application.Current.MainWindow.Left; } else { Height = SystemParameters.PrimaryScreenHeight / 2; Width = SystemParameters.PrimaryScreenWidth; Top = (SystemParameters.PrimaryScreenHeight / 2) * 1; Left = 0; } } private static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { if (msg == UnsafeNativeMethods.WM_MOVING || msg == UnsafeNativeMethods.WM_SIZING) { var m = new System.Windows.Forms.Message { HWnd = hwnd, Msg = msg, WParam = wParam, LParam = lParam, Result = IntPtr.Zero }; UnsafeNativeMethods.ReDrawWindow(m); handled = true; } if (msg == UnsafeNativeMethods.WM_MOUSEACTIVATE) { handled = true; return new IntPtr(UnsafeNativeMethods.MA_NOACTIVATE); } return IntPtr.Zero; } private void Border_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e) { DragMove(); } private void Window_Unloaded(object sender, RoutedEventArgs e) { Properties.Settings.Default.KeyboardHeight = Height; Properties.Settings.Default.KeyboardWidth = Width; Properties.Settings.Default.KeyboardTop = Top; Properties.Settings.Default.KeyboardLeft = Left; } private void Button_Click(object sender, RoutedEventArgs e) { HideKeyboard(); } private void Button_Click_1(object sender, RoutedEventArgs e) { ResetWindowSize(); } private void Window_Activated(object sender, EventArgs e) { TextBox.Focus(); } private Thickness _oldBorderThickness; private Brush _oldBorderBrush; private Brush _oldForeground; private Brush _oldBackground; public void ShowKeyboard() { TargetTextBox = Keyboard.FocusedElement as TextBox; if (TargetTextBox != null) { TextBox.Text = TargetTextBox.Text; TextBox.SelectionStart = TargetTextBox.SelectionStart; TextBox.AcceptsReturn = TargetTextBox.AcceptsReturn; _oldBorderThickness = TargetTextBox.BorderThickness; TargetTextBox.BorderThickness = new Thickness(3); _oldBorderBrush = TargetTextBox.BorderBrush; TargetTextBox.BorderBrush = Brushes.Red; _oldForeground = TargetTextBox.Foreground; TargetTextBox.Foreground = SystemColors.ControlTextBrush; _oldBackground = TargetTextBox.Background; TargetTextBox.Background = SystemColors.ControlBrush; } Show(); if (TargetTextBox != null) { Keyboard.Focus(TextBox); TextBox.SelectAll(); } } public void HideKeyboard() { if (TargetTextBox != null) { TargetTextBox.Text = TextBox.Text; TargetTextBox.SelectionStart = TextBox.SelectionStart; TargetTextBox.BorderThickness = _oldBorderThickness; TargetTextBox.BorderBrush = _oldBorderBrush; TargetTextBox.Foreground = _oldForeground; TargetTextBox.Background = _oldBackground; } TextBox.Text = ""; TargetTextBox = null; Properties.Settings.Default.KeyboardHeight = Height; Properties.Settings.Default.KeyboardWidth = Width; Properties.Settings.Default.KeyboardTop = Top; Properties.Settings.Default.KeyboardLeft = Left; Hide(); } private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e) { if (!TextBox.AcceptsReturn && e.Key == Key.Enter) { e.Handled = true; HideKeyboard(); } if (TargetTextBox != null && e.Key == Key.Tab) { var tb = TargetTextBox; e.Handled = true; HideKeyboard(); Keyboard.Focus(tb); tb.Focus(); tb.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); if (Keyboard.FocusedElement is TextBox) ShowKeyboard(); } } private void Window_Deactivated(object sender, EventArgs e) { HideKeyboard(); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Interaction/KeyboardWindow.xaml.cs
C#
gpl3
7,085
/* * Demo program for ListView Sorting * Created by Li Gao, 2007 * * Modified for demo purposes only. * This program is provided as is and no warranty or support. * Use it as your own risk * */ using System.Collections.Generic; using System.ComponentModel; using System.Collections; namespace Samba.Presentation.Common.ListViewEx { public abstract class ListViewCustomComparer: IComparer { protected Dictionary<string, ListSortDirection> sortColumns = new Dictionary<string, ListSortDirection>(); public void AddSort(string sortColumn, ListSortDirection dir) { if (sortColumns.ContainsKey(sortColumn)) sortColumns.Remove(sortColumn); sortColumns.Add(sortColumn, dir); } public void ClearSort() { sortColumns.Clear(); } protected List<string> GetSortColumnList() { List<string> result = new List<string>(); Stack<string> temp = new Stack<string>(); foreach (string col in sortColumns.Keys) { temp.Push(col); } while (temp.Count > 0) { result.Add(temp.Pop()); } return result; } public abstract int Compare(object x, object y); } }
zzgaminginc-pointofssale
Samba.Presentation.Common/ListViewEx/ListViewCustomComparer.cs
C#
gpl3
1,461
/* * Demo program for ListView Sorting * Created by Li Gao, 2007 * * Modified for demo purposes only. * This program is provided as is and no warranty or support. * Use it as your own risk * */ using System; using System.Collections; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.ComponentModel; namespace Samba.Presentation.Common.ListViewEx { static public class ListViewSorter { public static DependencyProperty CustomSorterProperty = DependencyProperty.RegisterAttached( "CustomSorter", typeof(IComparer), typeof(ListViewSorter)); public static IComparer GetCustomSorter(DependencyObject obj) { return (IComparer)obj.GetValue(CustomSorterProperty); } public static void SetCustomSorter(DependencyObject obj, IComparer value) { obj.SetValue(CustomSorterProperty, value); } public static DependencyProperty SortBindingMemberProperty = DependencyProperty.RegisterAttached( "SortBindingMember", typeof(BindingBase), typeof(ListViewSorter)); public static BindingBase GetSortBindingMember(DependencyObject obj) { return (BindingBase)obj.GetValue(SortBindingMemberProperty); } public static void SetSortBindingMember(DependencyObject obj, BindingBase value) { obj.SetValue(SortBindingMemberProperty, value); } public readonly static DependencyProperty IsListviewSortableProperty = DependencyProperty.RegisterAttached( "IsListviewSortable", typeof(Boolean), typeof(ListViewSorter), new FrameworkPropertyMetadata(false, new PropertyChangedCallback (OnRegisterSortableGrid))); public static Boolean GetIsListviewSortable(DependencyObject obj) { //return true; return (Boolean)obj.GetValue(IsListviewSortableProperty); } public static void SetIsListviewSortable(DependencyObject obj, Boolean value) { obj.SetValue(IsListviewSortableProperty, value); } private static GridViewColumnHeader _lastHeaderClicked = null; private static ListSortDirection _lastDirection = ListSortDirection.Ascending; private static ListView lv = null; private static void OnRegisterSortableGrid(DependencyObject obj, DependencyPropertyChangedEventArgs args) { ListView grid = obj as ListView; if (grid != null) { lv = grid; RegisterSortableGridView(grid, args); } } private static void RegisterSortableGridView(ListView grid, DependencyPropertyChangedEventArgs args) { if (args.NewValue is Boolean && (Boolean)args.NewValue) { grid.AddHandler(GridViewColumnHeader.ClickEvent, new RoutedEventHandler(GridViewColumnHeaderClickedHandler)); } else { grid.AddHandler(GridViewColumnHeader.ClickEvent, new RoutedEventHandler(GridViewColumnHeaderClickedHandler)); } } private static void GridViewColumnHeaderClickedHandler(object sender, RoutedEventArgs e) { GridViewColumnHeader headerClicked = e.OriginalSource as GridViewColumnHeader; ListSortDirection direction; if (headerClicked != null) { if (headerClicked != _lastHeaderClicked) { direction = ListSortDirection.Ascending; } else { if (_lastDirection == ListSortDirection.Ascending) { direction = ListSortDirection.Descending; } else { direction = ListSortDirection.Ascending; } } string header = String.Empty; try { header = ((Binding)ListViewSorter.GetSortBindingMember(headerClicked.Column)).Path.Path; } catch (Exception ex) { string msg = ex.Message; } if (header == String.Empty) return; Sort(header, direction); string resourceTemplateName = String.Empty; DataTemplate tmpTemplate; //if (_lastHeaderClicked != null) //{ // resourceTemplateName = "HeaderTemplateSortNon"; // tmpTemplate = lv.TryFindResource(resourceTemplateName) as DataTemplate; // _lastHeaderClicked.Column.HeaderTemplate = tmpTemplate; //} switch (direction) { case ListSortDirection.Ascending: resourceTemplateName = "HeaderTemplateSortAsc"; break; case ListSortDirection.Descending: resourceTemplateName = "HeaderTemplateSortDesc"; break; } tmpTemplate = lv.TryFindResource(resourceTemplateName) as DataTemplate; if (tmpTemplate != null) { headerClicked.Column.HeaderTemplate = tmpTemplate; } _lastHeaderClicked = headerClicked; _lastDirection = direction; } } private static void Sort(string sortBy, ListSortDirection direction) { ListCollectionView view = (ListCollectionView ) CollectionViewSource.GetDefaultView(lv.ItemsSource); if (view != null) { try { ListViewCustomComparer sorter = (ListViewCustomComparer)ListViewSorter.GetCustomSorter(lv); if (sorter != null) { // measuring timing of custom sort int tick1 = Environment.TickCount; sorter.AddSort(sortBy, direction); view.CustomSort = sorter; lv.Items.Refresh(); int tick2 = Environment.TickCount; double elapsed1 = (tick2 - tick1)/1000.0; MessageBox.Show(elapsed1.ToString() + " seconds."); } else { //measuring timem of SortDescriptions sort int tick3 = Environment.TickCount; lv.Items.SortDescriptions.Clear(); SortDescription sd = new SortDescription(sortBy, direction); lv.Items.SortDescriptions.Add(sd); lv.Items.Refresh(); int tick4 = Environment.TickCount; double elapsed2 = (tick4 - tick3) / 1000.0; MessageBox.Show(elapsed2.ToString() + " seconds."); } } catch (Exception ex) { string msg = ex.Message; } } } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/ListViewEx/ListViewSorter.cs
C#
gpl3
7,877
/* * Demo program for ListView Sorting * Created by Li Gao, 2007 * * Modified for demo purposes only. * This program is provided as is and no warranty or support. * Use it as your own risk * */ using System; using System.Windows.Data; using System.Globalization; using System.Windows.Controls; using System.Windows.Media; namespace Samba.Presentation.Common.ListViewEx { public sealed class BackgroundConvertor : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { ListViewItem item = (ListViewItem)value; ListView listView = ItemsControl.ItemsControlFromItemContainer(item) as ListView; // Get the index of a ListViewItem int index = listView.ItemContainerGenerator.IndexFromContainer(item); if (index % 2 == 0) { return Brushes.Lavender; } else { return Brushes.White; } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/ListViewEx/BackgroundConverter.cs
C#
gpl3
1,272
using System; using System.ComponentModel; using System.Diagnostics; using Samba.Infrastructure.Data.Serializer; namespace Samba.Presentation.Common { public abstract class ObservableObject : INotifyPropertyChanged { protected void RaisePropertyChanged(string propertyName) { VerifyPropertyName(propertyName); var handler = PropertyChanged; if (handler == null) return; var e = new PropertyChangedEventArgs(propertyName); handler(this, e); } [Conditional("DEBUG")] [DebuggerStepThrough] public void VerifyPropertyName(string propertyName) { if (string.IsNullOrEmpty(propertyName)) return; if (TypeDescriptor.GetProperties(this)[propertyName] != null) return; var msg = "Invalid property name: " + propertyName; if (ThrowOnInvalidPropertyName) throw new ArgumentException(msg); Debug.Fail(msg); } protected virtual bool ThrowOnInvalidPropertyName { get; private set; } public event PropertyChangedEventHandler PropertyChanged; } }
zzgaminginc-pointofssale
Samba.Presentation.Common/ObservableObject.cs
C#
gpl3
1,231
using System; using System.ComponentModel; using System.Globalization; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Interactivity; namespace Samba.Presentation.Common { /// <summary> /// InputMask for Textbox with 2 Properties: <see cref="InputMask"/>, <see cref="PromptChar"/>. /// </summary> public class TextBoxInputMaskBehavior : Behavior<TextBox> { #region DependencyProperties public static readonly DependencyProperty InputMaskProperty = DependencyProperty.Register("InputMask", typeof(string), typeof(TextBoxInputMaskBehavior), null); public string InputMask { get { return (string)GetValue(InputMaskProperty); } set { SetValue(InputMaskProperty, value); } } public static readonly DependencyProperty PromptCharProperty = DependencyProperty.Register("PromptChar", typeof(char), typeof(TextBoxInputMaskBehavior), new PropertyMetadata('_')); public char PromptChar { get { return (char)GetValue(PromptCharProperty); } set { SetValue(PromptCharProperty, value); } } #endregion public MaskedTextProvider Provider { get; private set; } protected override void OnAttached() { base.OnAttached(); AssociatedObject.Loaded += AssociatedObjectLoaded; AssociatedObject.PreviewTextInput += AssociatedObjectPreviewTextInput; AssociatedObject.PreviewKeyDown += AssociatedObjectPreviewKeyDown; DataObject.AddPastingHandler(AssociatedObject, Pasting); } protected override void OnDetaching() { base.OnDetaching(); AssociatedObject.Loaded -= AssociatedObjectLoaded; AssociatedObject.PreviewTextInput -= AssociatedObjectPreviewTextInput; AssociatedObject.PreviewKeyDown -= AssociatedObjectPreviewKeyDown; DataObject.RemovePastingHandler(AssociatedObject, Pasting); } /* Mask Character Accepts Required? 0 Digit (0-9) Required 9 Digit (0-9) or space Optional # Digit (0-9) or space Required L Letter (a-z, A-Z) Required ? Letter (a-z, A-Z) Optional & Any character Required C Any character Optional A Alphanumeric (0-9, a-z, A-Z) Required a Alphanumeric (0-9, a-z, A-Z) Optional Space separator Required . Decimal separator Required , Group (thousands) separator Required : Time separator Required / Date separator Required $ Currency symbol Required In addition, the following characters have special meaning: Mask Character Meaning < All subsequent characters are converted to lower case > All subsequent characters are converted to upper case | Terminates a previous < or > \ Escape: treat the next character in the mask as literal text rather than a mask symbol */ void AssociatedObjectLoaded(object sender, System.Windows.RoutedEventArgs e) { this.Provider = new MaskedTextProvider(InputMask, CultureInfo.CurrentCulture); this.Provider.Set(AssociatedObject.Text); this.Provider.PromptChar = this.PromptChar; AssociatedObject.Text = this.Provider.ToDisplayString(); //seems the only way that the text is formatted correct, when source is updated var textProp = DependencyPropertyDescriptor.FromProperty(TextBox.TextProperty, typeof(TextBox)); if (textProp != null) { textProp.AddValueChanged(AssociatedObject, (s, args) => this.UpdateText()); } } void AssociatedObjectPreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e) { this.TreatSelectedText(); var position = this.GetNextCharacterPosition(AssociatedObject.SelectionStart); if (Keyboard.IsKeyToggled(Key.Insert)) { if (this.Provider.Replace(e.Text, position)) position++; } else { if (this.Provider.InsertAt(e.Text, position)) position++; } position = this.GetNextCharacterPosition(position); this.RefreshText(position); e.Handled = true; } void AssociatedObjectPreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Space)//handle the space { this.TreatSelectedText(); var position = this.GetNextCharacterPosition(AssociatedObject.SelectionStart); if (this.Provider.InsertAt(" ", position)) this.RefreshText(position); e.Handled = true; } if (e.Key == Key.Back)//handle the back space { if (this.TreatSelectedText()) { this.RefreshText(AssociatedObject.SelectionStart); } else { if (AssociatedObject.SelectionStart != 0) { if (this.Provider.RemoveAt(AssociatedObject.SelectionStart - 1)) this.RefreshText(AssociatedObject.SelectionStart - 1); } } e.Handled = true; } if (e.Key == Key.Delete)//handle the delete key { //treat selected text if (this.TreatSelectedText()) { this.RefreshText(AssociatedObject.SelectionStart); } else { if (this.Provider.RemoveAt(AssociatedObject.SelectionStart)) this.RefreshText(AssociatedObject.SelectionStart); } e.Handled = true; } } /// <summary> /// Pasting prüft ob korrekte Daten reingepastet werden /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Pasting(object sender, DataObjectPastingEventArgs e) { if (e.DataObject.GetDataPresent(typeof(string))) { var pastedText = (string)e.DataObject.GetData(typeof(string)); this.TreatSelectedText(); var position = GetNextCharacterPosition(AssociatedObject.SelectionStart); if (this.Provider.InsertAt(pastedText, position)) { this.RefreshText(position); } } e.CancelCommand(); } private void UpdateText() { //check Provider.Text + TextBox.Text if (this.Provider.ToDisplayString().Equals(AssociatedObject.Text)) return; //use provider to format var success = this.Provider.Set(AssociatedObject.Text); //ui and mvvm/codebehind should be in sync this.SetText(success ? this.Provider.ToDisplayString() : AssociatedObject.Text); } /// <summary> /// Falls eine Textauswahl vorliegt wird diese entsprechend behandelt. /// </summary> /// <returns>true Textauswahl behandelt wurde, ansonsten falls </returns> private bool TreatSelectedText() { if (AssociatedObject.SelectionLength > 0) { return this.Provider.RemoveAt(AssociatedObject.SelectionStart, AssociatedObject.SelectionStart + AssociatedObject.SelectionLength - 1); } return false; } private void RefreshText(int position) { SetText(this.Provider.ToDisplayString()); AssociatedObject.SelectionStart = position; } private void SetText(string text) { AssociatedObject.Text = String.IsNullOrWhiteSpace(text) ? String.Empty : text; } private int GetNextCharacterPosition(int startPosition) { var position = this.Provider.FindEditPositionFrom(startPosition, true); if (position == -1) return startPosition; else return position; } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/TextBoxInputMaskBehavior.cs
C#
gpl3
8,924
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; namespace Samba.Infrastructure { [XmlRoot("dictionary")] public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable { public System.Xml.Schema.XmlSchema GetSchema() { return null; } public void ReadXml(System.Xml.XmlReader reader) { var keySerializer = new XmlSerializer(typeof(TKey)); var valueSerializer = new XmlSerializer(typeof(TValue)); var wasEmpty = reader.IsEmptyElement; reader.Read(); if (wasEmpty) return; while (reader.NodeType != System.Xml.XmlNodeType.EndElement) { reader.ReadStartElement("item"); reader.ReadStartElement("key"); var key = (TKey)keySerializer.Deserialize(reader); reader.ReadEndElement(); reader.ReadStartElement("value"); var value = (TValue)valueSerializer.Deserialize(reader); reader.ReadEndElement(); Add(key, value); reader.ReadEndElement(); reader.MoveToContent(); } reader.ReadEndElement(); } public void WriteXml(System.Xml.XmlWriter writer) { var keySerializer = new XmlSerializer(typeof(TKey)); var valueSerializer = new XmlSerializer(typeof(TValue)); foreach (var key in Keys) { writer.WriteStartElement("item"); writer.WriteStartElement("key"); keySerializer.Serialize(writer, key); writer.WriteEndElement(); writer.WriteStartElement("value"); TValue value = this[key]; valueSerializer.Serialize(writer, value); writer.WriteEndElement(); writer.WriteEndElement(); } } } }
zzgaminginc-pointofssale
Samba.Infrastructure/SerializableDictionary.cs
C#
gpl3
2,157
using System; using System.Collections; namespace Samba.Infrastructure { public class MessagingClientObject : MarshalByRefObject, IObserver { private readonly ArrayList _newData = new ArrayList(); public int GetData(out string[] arrData) { arrData = new String[_newData.Count]; _newData.CopyTo(arrData); _newData.Clear(); return arrData.Length; } public bool Update(ISubject sender, string data, short objState) { _newData.Add(data); return true; } public override object InitializeLifetimeService() { return null; } } }
zzgaminginc-pointofssale
Samba.Infrastructure/MessagingClientObject.cs
C#
gpl3
733
using System; using System.Collections.Generic; using System.Text; namespace Samba.Infrastructure { public class AlphanumComparator : IComparer<IStringCompareable> { private enum ChunkType { Alphanumeric, Numeric }; private static bool InChunk(char ch, char otherCh) { var type = ChunkType.Alphanumeric; if (char.IsDigit(otherCh)) { type = ChunkType.Numeric; } return (type != ChunkType.Alphanumeric || !char.IsDigit(ch)) && (type != ChunkType.Numeric || char.IsDigit(ch)); } public int Compare(IStringCompareable x, IStringCompareable y) { return Compare(x.GetStringValue(), y.GetStringValue()); } private static int Compare(object x, object y) { var s1 = x as string; var s2 = y as string; if (s1 == null || s2 == null) { return 0; } int thisMarker = 0; int thatMarker = 0; while ((thisMarker < s1.Length) || (thatMarker < s2.Length)) { if (thisMarker >= s1.Length) { return -1; } if (thatMarker >= s2.Length) { return 1; } var thisCh = s1[thisMarker]; var thatCh = s2[thatMarker]; var thisChunk = new StringBuilder(); var thatChunk = new StringBuilder(); while ((thisMarker < s1.Length) && (thisChunk.Length == 0 || InChunk(thisCh, thisChunk[0]))) { thisChunk.Append(thisCh); thisMarker++; if (thisMarker < s1.Length) { thisCh = s1[thisMarker]; } } while ((thatMarker < s2.Length) && (thatChunk.Length == 0 || InChunk(thatCh, thatChunk[0]))) { thatChunk.Append(thatCh); thatMarker++; if (thatMarker < s2.Length) { thatCh = s2[thatMarker]; } } int result = 0; // If both chunks contain numeric characters, sort them numerically if (char.IsDigit(thisChunk[0]) && char.IsDigit(thatChunk[0])) { int thisNumericChunk = Convert.ToInt32(thisChunk.ToString()); int thatNumericChunk = Convert.ToInt32(thatChunk.ToString()); if (thisNumericChunk < thatNumericChunk) { result = -1; } if (thisNumericChunk > thatNumericChunk) { result = 1; } } else { result = thisChunk.ToString().CompareTo(thatChunk.ToString()); } if (result != 0) { return result; } } return 0; } } }
zzgaminginc-pointofssale
Samba.Infrastructure/AlphanumComparator.cs
C#
gpl3
3,423
namespace Samba.Infrastructure { public interface ISubject { void Attach(IObserver observer); void Detach(IObserver observer); bool Notify(string objType, short objState); } public interface IObserver { bool Update(ISubject sender, string objType, short objState); } }
zzgaminginc-pointofssale
Samba.Infrastructure/Observer.cs
C#
gpl3
345
using System; using System.Threading; namespace Samba.Infrastructure.Cron { public class CronObject { public delegate void CronEvent(CronObject cronObject); public event CronEvent OnCronTrigger; public event CronEvent OnStarted; public event CronEvent OnStopped; public event CronEvent OnThreadAbort; private readonly CronObjectDataContext _cronObjectDataContext; private readonly Guid _id = Guid.NewGuid(); private readonly object _startStopLock = new object(); private readonly EventWaitHandle _wh = new AutoResetEvent(false); private Thread _thread; private bool _isStarted; private bool _isStopRequested; private DateTime _nextCronTrigger; public Guid Id { get { return _id; } } public object Object { get { return _cronObjectDataContext.Object; } } public DateTime LastTigger { get { return _cronObjectDataContext.LastTrigger; } } /// <summary> /// Initializes a new instance of the <see cref="CronObject"/> class. /// </summary> /// <param name="cronObjectDataContext">The cron object data context.</param> public CronObject(CronObjectDataContext cronObjectDataContext) { if (cronObjectDataContext == null) { throw new ArgumentNullException("cronObjectDataContext"); } if (cronObjectDataContext.Object == null) { throw new ArgumentException("cronObjectDataContext.Object"); } if (cronObjectDataContext.CronSchedules == null || cronObjectDataContext.CronSchedules.Count == 0) { throw new ArgumentException("cronObjectDataContext.CronSchedules"); } _cronObjectDataContext = cronObjectDataContext; } /// <summary> /// Starts this instance. /// </summary> /// <returns></returns> public bool Start() { lock (_startStopLock) { // Can't start if already started. // if (_isStarted) { return false; } _isStarted = true; _isStopRequested = false; // This is a long running process. Need to run on a thread // outside the thread pool. // _thread = new Thread(ThreadRoutine); _thread.Start(); } // Raise the started event. // if (OnStarted != null) { OnStarted(this); } return true; } /// <summary> /// Stops this instance. /// </summary> /// <returns></returns> public bool Stop() { lock (_startStopLock) { // Can't stop if not started. // if (!_isStarted) { return false; } _isStarted = false; _isStopRequested = true; // Signal the thread to wake up early // _wh.Set(); // Wait for the thread to join. // if (!_thread.Join(5000)) { _thread.Abort(); // Raise the thread abort event. // if (OnThreadAbort != null) { OnThreadAbort(this); } } } // Raise the stopped event. // if (OnStopped != null) { OnStopped(this); } return true; } /// <summary> /// Cron object thread routine. /// </summary> private void ThreadRoutine() { // Continue until stop is requested. // while (!_isStopRequested) { // Determine the next cron trigger // DetermineNextCronTrigger(out _nextCronTrigger); TimeSpan sleepSpan = _nextCronTrigger - DateTime.Now; if (sleepSpan.TotalMilliseconds < 0) { // Next trigger is in the past. Trigger the right away. // sleepSpan = new TimeSpan(0, 0, 0, 0, 50); } // Wait here for the timespan or until I am triggered // to wake up. // if (!_wh.WaitOne(sleepSpan.TotalMilliseconds < int.MaxValue ? (int)sleepSpan.TotalMilliseconds : int.MaxValue)) { // Timespan is up...raise the trigger event // if (OnCronTrigger != null) { OnCronTrigger(this); } // Update the last trigger time. // _cronObjectDataContext.LastTrigger = DateTime.Now; } } } /// <summary> /// Determines the next cron trigger. /// </summary> /// <param name="nextTrigger">The next trigger.</param> private void DetermineNextCronTrigger(out DateTime nextTrigger) { nextTrigger = DateTime.MaxValue; foreach (CronSchedule cronSchedule in _cronObjectDataContext.CronSchedules) { DateTime thisTrigger; if (cronSchedule.GetNext(LastTigger, out thisTrigger)) { if (thisTrigger < nextTrigger) { nextTrigger = thisTrigger; } } } } } }
zzgaminginc-pointofssale
Samba.Infrastructure/Cron/CronObject.cs
C#
gpl3
6,159
using System; namespace Samba.Infrastructure.Cron { public class CronExpression { public string Minutes { get; set; } public string Hours { get; set; } public string Days { get; set; } public string Months { get; set; } public string DaysOfWeek { get; set; } public CronExpression() : this("*", "*", "*", "*", "*") { } public CronExpression(string minutes, string hours, string days, string months, string daysOfWeek) { if (string.IsNullOrEmpty(minutes)) { throw new ArgumentNullException("minutes"); } if (string.IsNullOrEmpty(hours)) { throw new ArgumentNullException("hours"); } if (string.IsNullOrEmpty(days)) { throw new ArgumentNullException("days"); } if (string.IsNullOrEmpty(months)) { throw new ArgumentNullException("months"); } if (string.IsNullOrEmpty(daysOfWeek)) { throw new ArgumentNullException("daysOfWeek"); } Minutes = minutes; Hours = hours; Days = days; Months = months; DaysOfWeek = daysOfWeek; } public override string ToString() { return Minutes + " " + Hours + " " + Days + " " + Months + " " + DaysOfWeek; } } }
zzgaminginc-pointofssale
Samba.Infrastructure/Cron/CronExpression.cs
C#
gpl3
1,210
namespace Samba.Infrastructure.Cron { public class DaysOfWeekCronEntry : CronEntryBase { public DaysOfWeekCronEntry(string expression) { Initialize(expression, 0, 6); } } }
zzgaminginc-pointofssale
Samba.Infrastructure/Cron/DaysOfWeekCronEntry.cs
C#
gpl3
193
namespace Samba.Infrastructure.Cron { public class MonthsCronEntry : CronEntryBase { public MonthsCronEntry(string expression) { Initialize(expression, 1, 12); } } }
zzgaminginc-pointofssale
Samba.Infrastructure/Cron/MonthsCronEntry.cs
C#
gpl3
186
namespace Samba.Infrastructure.Cron { internal class HoursCronEntry : CronEntryBase { public HoursCronEntry(string expression) { Initialize(expression, 0, 23); } } }
zzgaminginc-pointofssale
Samba.Infrastructure/Cron/HoursCronEntry.cs
C#
gpl3
186
using System; using System.Collections.Generic; namespace Samba.Infrastructure.Cron { public class CronObjectDataContext { public object Object { get; set; } public DateTime LastTrigger { get; set; } public List<CronSchedule> CronSchedules { get; set; } } }
zzgaminginc-pointofssale
Samba.Infrastructure/Cron/CronObjectDataContext.cs
C#
gpl3
278
using System.Collections.Generic; namespace Samba.Infrastructure.Cron { public interface ICronEntry { List<int> Values { get; } string Expression { get; } int MinValue { get; } int MaxValue { get; } /// <summary> /// Gets the first value. /// </summary> /// <value>The first.</value> int First { get; } /// <summary> /// Nexts the specified value. /// </summary> /// <param name="start">The start.</param> /// <returns></returns> int Next(int start); } }
zzgaminginc-pointofssale
Samba.Infrastructure/Cron/ICronEntry.cs
C#
gpl3
514
using System.Collections.Generic; using System.Text; namespace Samba.Infrastructure.Cron { public static class CronBuilder { public enum DayOfWeek { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } ; #region Minutely Triggers public static CronExpression CreateMinutelyTrigger() { var cronExpression = new CronExpression { Minutes = "*", Hours = "*", Days = "*", Months = "*", DaysOfWeek = "*" }; return cronExpression; } #endregion #region Hourly Triggers public static CronExpression CreateHourlyTrigger() { return CreateHourlyTrigger(0); } public static CronExpression CreateHourlyTrigger(int triggerMinute) { CronExpression cronExpression = new CronExpression { Minutes = triggerMinute.ToString(), Hours = "*", Days = "*", Months = "*", DaysOfWeek = "*" }; return cronExpression; } public static CronExpression CreateHourlyTrigger(int[] triggerMinutes) { CronExpression cronExpression = new CronExpression { Minutes = triggerMinutes.ConvertArrayToString(), Hours = "*", Days = "*", Months = "*", DaysOfWeek = "*" }; return cronExpression; } public static CronExpression CreateHourlyTrigger(int firstMinuteToTrigger, int lastMinuteToTrigger) { return CreateHourlyTrigger(firstMinuteToTrigger, lastMinuteToTrigger, 1); } public static CronExpression CreateHourlyTrigger(int firstMinuteToTrigger, int lastMinuteToTrigger, int interval) { string value = firstMinuteToTrigger + "-" + lastMinuteToTrigger; if(interval != 1) { value += "/" + interval; } CronExpression cronExpression = new CronExpression { Minutes = value, Hours = "*", Days = "*", Months = "*", DaysOfWeek = "*" }; return cronExpression; } #endregion #region Daily Triggers public static CronExpression CreateDailyTrigger() { return CreateDailyTrigger(0); } public static CronExpression CreateDailyTrigger(int triggerHour) { CronExpression cronExpression = new CronExpression { Minutes = "0", Hours = triggerHour.ToString(), Days = "*", Months = "*", DaysOfWeek = "*" }; return cronExpression; } public static CronExpression CreateDailyTrigger(int[] triggerHours) { CronExpression cronExpression = new CronExpression { Minutes = "0", Hours = triggerHours.ConvertArrayToString(), Days = "*", Months = "*", DaysOfWeek = "*" }; return cronExpression; } public static CronExpression CreateDailyTrigger(int firstHourToTrigger, int lastHourToTrigger) { return CreateDailyTrigger(firstHourToTrigger, lastHourToTrigger, 1); } public static CronExpression CreateDailyTrigger(int firstHourToTrigger, int lastHourToTrigger, int interval) { string value = firstHourToTrigger + "-" + lastHourToTrigger; if (interval != 1) { value += "/" + interval; } CronExpression cronExpression = new CronExpression { Minutes = "0", Hours = value, Days = "*", Months = "*", DaysOfWeek = "*" }; return cronExpression; } public static CronExpression CreateDailyTrigger(DayOfWeek[] daysOfWeekFilter) { return CreateDailyTrigger(0, daysOfWeekFilter); } public static CronExpression CreateDailyTrigger(int triggerHour, DayOfWeek[] daysOfWeekFilter) { CronExpression cronExpression = new CronExpression { Minutes = "0", Hours = triggerHour.ToString(), Days = "*", Months = "*", DaysOfWeek = daysOfWeekFilter.ConvertArrayToString() }; return cronExpression; } public static CronExpression CreateDailyTrigger(int[] triggerHours, DayOfWeek[] daysOfWeekFilter) { CronExpression cronExpression = new CronExpression { Minutes = "0", Hours = triggerHours.ConvertArrayToString(), Days = "*", Months = "*", DaysOfWeek = daysOfWeekFilter.ConvertArrayToString() }; return cronExpression; } public static CronExpression CreateDailyTrigger(int firstHourToTrigger, int lastHourToTrigger, DayOfWeek[] daysOfWeekFilter) { return CreateDailyTrigger(firstHourToTrigger, lastHourToTrigger, 1, daysOfWeekFilter); } public static CronExpression CreateDailyTrigger(int firstHourToTrigger, int lastHourToTrigger, int interval, DayOfWeek[] daysOfWeekFilter) { string value = firstHourToTrigger + "-" + lastHourToTrigger; if (interval != 1) { value += "/" + interval; } CronExpression cronExpression = new CronExpression { Minutes = "0", Hours = value, Days = "*", Months = "*", DaysOfWeek = daysOfWeekFilter.ConvertArrayToString() }; return cronExpression; } public static CronExpression CreateDailyOnlyWeekDayTrigger() { return CreateDailyOnlyWeekDayTrigger(0); } public static CronExpression CreateDailyOnlyWeekDayTrigger(int triggerHour) { return CreateDailyTrigger(triggerHour, GetWeekDays()); } public static CronExpression CreateDailyOnlyWeekDayTrigger(int[] triggerHours) { return CreateDailyTrigger(triggerHours, GetWeekDays()); } public static CronExpression CreateDailyOnlyWeekDayTrigger(int firstHourToTrigger, int lastHourToTrigger) { return CreateDailyTrigger(firstHourToTrigger, lastHourToTrigger, GetWeekDays()); } public static CronExpression CreateDailyOnlyWeekDayTrigger(int firstHourToTrigger, int lastHourToTrigger, int interval) { return CreateDailyTrigger(firstHourToTrigger, lastHourToTrigger, interval, GetWeekDays()); } public static CronExpression CreateDailyOnlyWeekEndTrigger() { return CreateDailyOnlyWeekEndTrigger(0); } public static CronExpression CreateDailyOnlyWeekEndTrigger(int triggerHour) { return CreateDailyTrigger(triggerHour, GetWeekEndDays()); } public static CronExpression CreateDailyOnlyWeekEndTrigger(int[] triggerHours) { return CreateDailyTrigger(triggerHours, GetWeekEndDays()); } public static CronExpression CreateDailyOnlyWeekEndTrigger(int firstHourToTrigger, int lastHourToTrigger) { return CreateDailyTrigger(firstHourToTrigger, lastHourToTrigger, GetWeekEndDays()); } public static CronExpression CreateDailyOnlyWeekEndTrigger(int firstHourToTrigger, int lastHourToTrigger, int interval) { return CreateDailyTrigger(firstHourToTrigger, lastHourToTrigger, interval, GetWeekEndDays()); } #endregion #region Monthly Triggers public static CronExpression CreateMonthlyTrigger() { return CreateMonthlyTrigger(0); } public static CronExpression CreateMonthlyTrigger(int triggerDay) { CronExpression cronExpression = new CronExpression { Minutes = "0", Hours = "0", Days = triggerDay.ToString(), Months = "*", DaysOfWeek = "*" }; return cronExpression; } public static CronExpression CreateMonthlyTrigger(int[] triggerDays) { CronExpression cronExpression = new CronExpression { Minutes = "0", Hours = "0", Days = triggerDays.ConvertArrayToString(), Months = "*", DaysOfWeek = "*" }; return cronExpression; } public static CronExpression CreateMonthlyTrigger(int firstDayToTrigger, int lastDayToTrigger) { return CreateMonthlyTrigger(firstDayToTrigger, lastDayToTrigger, 1); } public static CronExpression CreateMonthlyTrigger(int firstDayToTrigger, int lastDayToTrigger, int interval) { string value = firstDayToTrigger + "-" + lastDayToTrigger; if (interval != 1) { value += "/" + interval; } CronExpression cronExpression = new CronExpression { Minutes = "0", Hours = "0", Days = value, Months = "*", DaysOfWeek = "*" }; return cronExpression; } #endregion #region Yearly Triggers public static CronExpression CreateYearlyTrigger() { return CreateYearlyTrigger(0); } public static CronExpression CreateYearlyTrigger(int triggerMonth) { CronExpression cronExpression = new CronExpression { Minutes = "0", Hours = "0", Days = "0", Months = triggerMonth.ToString(), DaysOfWeek = "*" }; return cronExpression; } public static CronExpression CreateYearlyTrigger(int[] triggerMonths) { CronExpression cronExpression = new CronExpression { Minutes = "0", Hours = "0", Days = "0", Months = triggerMonths.ConvertArrayToString(), DaysOfWeek = "*" }; return cronExpression; } public static CronExpression CreateYearlyTrigger(int firstMonthToTrigger, int lastMonthToTrigger) { return CreateYearlyTrigger(firstMonthToTrigger, lastMonthToTrigger, 1); } public static CronExpression CreateYearlyTrigger(int firstMonthToTrigger, int lastMonthToTrigger, int interval) { string value = firstMonthToTrigger + "-" + lastMonthToTrigger; if (interval != 1) { value += "/" + interval; } CronExpression cronExpression = new CronExpression { Minutes = "0", Hours = "0", Days = "0", Months = value, DaysOfWeek = "*" }; return cronExpression; } #endregion private static string ConvertArrayToString(this IEnumerable<int> list) { StringBuilder result = new StringBuilder(); List<int> values = new List<int>(list); values.Sort(); for (int i = 0; i < values.Count; i++) { result.Append(values[i].ToString()); if (i != values.Count - 1) { result.Append(","); } } return result.ToString(); } private static string ConvertArrayToString(this DayOfWeek[] list) { StringBuilder result = new StringBuilder(); List<int> values = new List<int>(); for (int i = 0; i < list.Length; i++) { values.Add((int) list[i]); } values.Sort(); for (int i = 0; i < values.Count; i++) { result.Append(values[i].ToString()); if (i != values.Count - 1) { result.Append(","); } } return result.ToString(); } private static DayOfWeek[] GetWeekDays() { return new[] { DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday }; } private static DayOfWeek[] GetWeekEndDays() { return new[] { DayOfWeek.Sunday, DayOfWeek.Saturday }; } } }
zzgaminginc-pointofssale
Samba.Infrastructure/Cron/CronBuilder.cs
C#
gpl3
14,383
namespace Samba.Infrastructure.Cron { public class DaysCronEntry : CronEntryBase { public DaysCronEntry(string expression) { Initialize(expression, 1, 31); } } }
zzgaminginc-pointofssale
Samba.Infrastructure/Cron/DaysCronEntry.cs
C#
gpl3
182
using System.Collections.Generic; namespace Samba.Infrastructure.Cron { public abstract class CronEntryBase : ICronEntry { public static int RolledOver = -1; public List<int> Values { get; private set;} public string Expression { get; private set;} public int MinValue { get; private set; } public int MaxValue { get; private set; } /// <summary> /// Gets the first value. /// </summary> /// <value>The first.</value> public int First { get { return Values[0]; } } /// <summary> /// Nexts the specified value. /// </summary> /// <param name="start">The start.</param> /// <returns></returns> public int Next(int start) { // Find the next value in the list just // after the supplied parameter. // foreach (int value in Values) { if (value >= start) { // Found one...exit early // return value; } } // Did not find one... // return RolledOver; } /// <summary> /// Initializes the specified expression. /// </summary> /// <param name="expression">The expression.</param> /// <param name="minValue">The min value.</param> /// <param name="maxValue">The max value.</param> protected void Initialize(string expression, int minValue, int maxValue) { if(string.IsNullOrEmpty(expression)) { throw new CronEntryException("Expression cannot be null or empty."); } Expression = expression; MinValue = minValue; MaxValue = maxValue; ParseExpression(); } private void ParseExpression() { // line examples: // 5 Just # 5 // 1-10 1,2,3,4,5,6,7,8,9,10 // 2,3,9 2,3,9 // 2,3,5-7 2,3,5,6,7 // 1-10/3 1,4,7,10 // 2,3,4-10/2 2,3,4,6,8,10 // */3 minValue,minValue+3,...<=maxValue // Init return values. // Values = new List<int>(); // Split the individual entries // int commaIndex = Expression.IndexOf(","); if(commaIndex == -1) { // Only one entry // ParseEntry(Expression); } else { // Multiple entries...parse each one. // string[] entrys = Expression.Split(new[] { ',' }); foreach (string entry in entrys) { ParseEntry(entry.Trim()); } } } private void ParseEntry(string entry) { // Ensure the entry is not empty. // if (string.IsNullOrEmpty(entry)) { throw new CronEntryException("Entry is empty."); } // Initialize the indexing information to // add all the values from min to max. // int minUsed = MinValue; int maxUsed = MaxValue; int interval = -1; // Is there an interval specified? // if (entry.IndexOf("/") != -1) { string[] vals = entry.Split('/'); entry = vals[0]; if (string.IsNullOrEmpty(entry)) { throw new CronEntryException("Entry is empty."); } if (!int.TryParse(vals[1], out interval)) { throw new CronEntryException("Found unexpected character. entry=" + entry); } if (interval < 1) { throw new CronEntryException("Interval out of bounds."); } } // Is this a wild card // if (entry[0] == '*' && entry.Length == 1) { // Wild card only. // AddValues(minUsed, maxUsed, interval); } else { // No wild card. // Is this a range? // if (entry.IndexOf("-") != -1) { // Found a range. // string[] vals = entry.Split('-'); if (!int.TryParse(vals[0], out minUsed)) { throw new CronEntryException("Found unexpected character. entry=" + entry); } if (minUsed < MinValue) { throw new CronEntryException("Minimum value less than expected."); } if (!int.TryParse(vals[1], out maxUsed)) { throw new CronEntryException("Found unexpected character. entry=" + entry); } if (maxUsed > MaxValue) { throw new CronEntryException("Maximum value greater than expected."); } if(minUsed>maxUsed) { throw new CronEntryException("Maximum value less than minimum value."); } AddValues(minUsed, maxUsed, interval); } else { // Must be a single number. // if(!int.TryParse(entry, out minUsed)) { throw new CronEntryException("Found unexpected character. entry=" + entry); } if (minUsed < MinValue) { throw new CronEntryException("Value is less than minimum expected."); } if (interval == -1) { // No interval (eg. '5' or '9') // maxUsed = minUsed; if (maxUsed > MaxValue) { throw new CronEntryException("Value is greater than maximum expected."); } AddValues(minUsed, maxUsed, interval); } else { // Interval and a single number // eg. '2/5' --> 2,7,12,17,...<max // maxUsed = MaxValue; AddValues(minUsed, maxUsed, interval); } } } } private void AddValues(int minUsed, int maxUsed, int interval) { if(interval==-1) { // No interval was specified...use 1 // interval = 1; } for (int i = minUsed; i <= maxUsed; i += interval) { if (!Values.Contains(i)) { Values.Add(i); } } } } }
zzgaminginc-pointofssale
Samba.Infrastructure/Cron/CronEntryBase.cs
C#
gpl3
5,384
namespace Samba.Infrastructure.Cron { public class MinutesCronEntry : CronEntryBase { public MinutesCronEntry(string expression) { Initialize(expression, 0, 59); } } }
zzgaminginc-pointofssale
Samba.Infrastructure/Cron/MinutesCronEntry.cs
C#
gpl3
188
using System; namespace Samba.Infrastructure.Cron { public class CronEntryException : Exception { public CronEntryException(string message) : base(message) { } } }
zzgaminginc-pointofssale
Samba.Infrastructure/Cron/CronEntryException.cs
C#
gpl3
189
namespace Samba.Infrastructure { public interface IStringCompareable { string GetStringValue(); } }
zzgaminginc-pointofssale
Samba.Infrastructure/IStringCompareable.cs
C#
gpl3
130
/// Copyright (C) 2010 Douglas Day /// All rights reserved. /// MIT-licensed: http://www.opensource.org/licenses/mit-license.php using System; using System.Security; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace Samba.Infrastructure { public class SecureStringToStringMarshaler : IDisposable { private SecureString _secureString; private GCHandle _gch; public SecureString SecureString { get { return _secureString; } set { _secureString = value; UpdateStringValue(); } } public string String { get; protected set; } public SecureStringToStringMarshaler() { } public SecureStringToStringMarshaler(SecureString ss) { SecureString = ss; } void UpdateStringValue() { Deallocate(); unsafe { if (SecureString != null) { int length = SecureString.Length; String = new string('\0', length); _gch = new GCHandle(); // Create a CER (Contrained Execution Region) RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { // Pin our string, disallowing the garbage collector from // moving it around. _gch = GCHandle.Alloc(String, GCHandleType.Pinned); } IntPtr stringPtr = IntPtr.Zero; RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup( delegate { // Create a CER (Contrained Execution Region) RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { stringPtr = Marshal.SecureStringToBSTR(SecureString); } // Copy the SecureString content to our pinned string char* pString = (char*)stringPtr; char* pInsecureString = (char*)_gch.AddrOfPinnedObject(); for (int index = 0; index < length; index++) { pInsecureString[index] = pString[index]; } }, delegate { if (stringPtr != IntPtr.Zero) { // Free the SecureString BSTR that was generated Marshal.ZeroFreeBSTR(stringPtr); } }, null); } } } void Deallocate() { if (_gch.IsAllocated) { unsafe { // Determine the length of the string int length = String.Length; // Zero each character of the string. char* pInsecureString = (char*)_gch.AddrOfPinnedObject(); for (int index = 0; index < length; index++) { pInsecureString[index] = '\0'; } // Free the handle so the garbage collector // can dispose of it properly. _gch.Free(); } } } public void Dispose() { Deallocate(); } } }
zzgaminginc-pointofssale
Samba.Infrastructure/SecureStringToStringMarshaller.cs
C#
gpl3
4,001
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")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Samba.Infrastructure")] [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("00cc7b0d-d9bc-4742-8243-13a12aaaa653")] // 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.Infrastructure.Explorables")]
zzgaminginc-pointofssale
Samba.Infrastructure/Properties/AssemblyInfo.cs
C#
gpl3
1,520
using System; namespace Samba.Infrastructure { public interface IMessageListener { string Key { get; } void ProcessMessage(string message); } }
zzgaminginc-pointofssale
Samba.Infrastructure/IMessageListener.cs
C#
gpl3
186
namespace Samba.Infrastructure { public static class Messages { public const string ShutdownRequest = "SHUTDOWN"; public const string PingMessage = "PING"; public const string TicketRefreshMessage = "TICKET_REFRESH"; public const string AutoPrintTicketMessage = "AUTO_PRINT"; public const string ManualPrintTicketMessage = "MANUAL_PRINT"; } }
zzgaminginc-pointofssale
Samba.Infrastructure/Messages.cs
C#
gpl3
409
using System; using System.Collections; using System.Collections.Generic; using System.Net.Sockets; namespace Samba.Infrastructure { public class MessagingServerObject : MarshalByRefObject, ISubject { private readonly IList<IObserver> _clients = new List<IObserver>(); public void SetValue(string clientData) { Notify(clientData, 0); } public void Attach(IObserver client) { Console.WriteLine("observer bağlandı."); _clients.Add(client); } public void Detach(IObserver client) { _clients.Remove(client); } public void Ping() { } public bool Notify(string clientData, short objState) { for (var i = _clients.Count - 1; i >= 0; i--) { try { _clients[i].Update(this, clientData, objState); } catch (Exception) { _clients.RemoveAt(i); } } return true; } public override object InitializeLifetimeService() { return null; } public int GetConnectionCount() { return _clients.Count; } } }
zzgaminginc-pointofssale
Samba.Infrastructure/MessagingServerObject.cs
C#
gpl3
1,387
using System; using System.Collections; using System.Linq; using System.Net.Sockets; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; using System.Threading; using Samba.Infrastructure.Settings; namespace Samba.Infrastructure { public static class MessagingClient { private static TcpChannel _channel; private static MessagingServerObject _serverObject; private static MessagingClientObject _clientObject; private static readonly Timer Timer = new Timer(OnTimerTick, null, Timeout.Infinite, 1000); private static IMessageListener _messageListener; public static bool IsConnected { get; set; } private static void OnTimerTick(object state) { if (_clientObject != null && _messageListener != null && IsConnected) { string[] arrData; _clientObject.GetData(out arrData); foreach (var t in arrData.Distinct()) { _messageListener.ProcessMessage(t); } } } public static void Disconnect() { IsConnected = false; _messageListener = null; try { try { if (_serverObject != null) _serverObject.Detach(_clientObject); } catch (Exception) { } } finally { if (_channel != null) { ChannelServices.UnregisterChannel(_channel); _channel = null; } } } public static int GetConnectionCount() { if (_serverObject != null) { try { return _serverObject.GetConnectionCount(); } catch (Exception) { if (IsConnected) Disconnect(); } } return 0; } public static void SendMessage(string message) { if (_serverObject != null) { try { _serverObject.SetValue(string.Format("{0}", message)); } catch (Exception) { if (IsConnected) Disconnect(); } } } public static bool CanPing() { try { if (_serverObject != null) { _serverObject.Ping(); return true; } return false; } catch (Exception) { if (IsConnected) Disconnect(); return false; } } public static void Reconnect(IMessageListener messageListener) { try { Disconnect(); } catch (SocketException) { } _messageListener = messageListener; Connect(_messageListener); } public static void Connect(IMessageListener messageListener) { Timer.Change(0, Timeout.Infinite); if (messageListener == null) return; if (string.IsNullOrWhiteSpace(LocalSettings.MessagingServerName)) return; _messageListener = messageListener; var serverProv = new BinaryServerFormatterSinkProvider { TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full }; var clientProv = new BinaryClientFormatterSinkProvider(); IDictionary props = new Hashtable(); props["port"] = 0; _channel = new TcpChannel(props, clientProv, serverProv); ChannelServices.RegisterChannel(_channel, false); var url = String.Format("tcp://{0}:{1}/ChatServer", LocalSettings.MessagingServerName, LocalSettings.MessagingServerPort); try { _serverObject = (MessagingServerObject)Activator.GetObject(typeof(MessagingServerObject), url); _clientObject = new MessagingClientObject(); _serverObject.Attach(_clientObject); } catch { HandleError(); return; } IsConnected = true; Timer.Change(0, 1000); } private static void HandleError() { _messageListener = null; _serverObject = null; _clientObject = null; if (_channel != null) { ChannelServices.UnregisterChannel(_channel); _channel = null; } IsConnected = false; } } }
zzgaminginc-pointofssale
Samba.Infrastructure/MessagingClient.cs
C#
gpl3
5,228
using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.IO; using System.Threading; using System.Xml; using System.Xml.Serialization; using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration; namespace Samba.Infrastructure.Settings { public class SettingsObject { public string MajorCurrencyName { get; set; } public string MinorCurrencyName { get; set; } public string PluralCurrencySuffix { get; set; } public int MessagingServerPort { get; set; } public string MessagingServerName { get; set; } public string TerminalName { get; set; } public string ConnectionString { get; set; } public bool StartMessagingClient { get; set; } public string LogoPath { get; set; } public string DefaultHtmlReportHeader { get; set; } public string CurrentLanguage { get; set; } public bool OverrideLanguage { get; set; } public bool OverrideWindowsRegionalSettings { get; set; } public string DefaultCreditCardProcessorName { get; set; } public SerializableDictionary<string, string> CustomSettings { get; set; } public SettingsObject() { CustomSettings = new SerializableDictionary<string, string>(); MessagingServerPort = 8080; ConnectionString = ""; DefaultHtmlReportHeader = @" <style type='text/css'> html { font-family: 'Courier New', monospace; } </style>"; } public void SetCustomValue(string settingName, string settingValue) { if (!CustomSettings.ContainsKey(settingName)) CustomSettings.Add(settingName, settingValue); else CustomSettings[settingName] = settingValue; if (string.IsNullOrEmpty(settingValue)) CustomSettings.Remove(settingName); } public string GetCustomValue(string settingName) { return CustomSettings.ContainsKey(settingName) ? CustomSettings[settingName] : ""; } } public static class LocalSettings { private static SettingsObject _settingsObject; public static int Decimals { get { return 2; } } public static int MessagingServerPort { get { return _settingsObject.MessagingServerPort; } set { _settingsObject.MessagingServerPort = value; } } public static string MessagingServerName { get { return _settingsObject.MessagingServerName; } set { _settingsObject.MessagingServerName = value; } } public static string TerminalName { get { return _settingsObject.TerminalName; } set { _settingsObject.TerminalName = value; } } public static string ConnectionString { get { return _settingsObject.ConnectionString; } set { _settingsObject.ConnectionString = value; } } public static bool StartMessagingClient { get { return _settingsObject.StartMessagingClient; } set { _settingsObject.StartMessagingClient = value; } } public static string LogoPath { get { return _settingsObject.LogoPath; } set { _settingsObject.LogoPath = value; } } public static string DefaultHtmlReportHeader { get { return _settingsObject.DefaultHtmlReportHeader; } set { _settingsObject.DefaultHtmlReportHeader = value; } } public static string MajorCurrencyName { get { return _settingsObject.MajorCurrencyName; } set { _settingsObject.MajorCurrencyName = value; } } public static string MinorCurrencyName { get { return _settingsObject.MinorCurrencyName; } set { _settingsObject.MinorCurrencyName = value; } } public static string PluralCurrencySuffix { get { return _settingsObject.PluralCurrencySuffix; } set { _settingsObject.PluralCurrencySuffix = value; } } public static string DefaultCreditCardProcessorName { get { return _settingsObject.DefaultCreditCardProcessorName; } set { _settingsObject.DefaultCreditCardProcessorName = value; } } private static CultureInfo _cultureInfo; public static string CurrentLanguage { get { return _settingsObject.CurrentLanguage; } set { _cultureInfo = CultureInfo.GetCultureInfo(value); if (_settingsObject.CurrentLanguage != value) { _settingsObject.CurrentLanguage = value; SaveSettings(); } UpdateThreadLanguage(); } } public static bool OverrideWindowsRegionalSettings { get { return _settingsObject.OverrideWindowsRegionalSettings; } set { _settingsObject.OverrideWindowsRegionalSettings = value; } } public static string AppPath { get; set; } public static string DocumentPath { get { return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\SambaPOS2"; } } public static string DataPath { get { return Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\Ozgu Tech\\SambaPOS2"; } } public static string UserPath { get { return Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Ozgu Tech\\SambaPOS2"; } } public static string CommonSettingsFileName { get { return DataPath + "\\SambaSettings.txt"; } } public static string UserSettingsFileName { get { return UserPath + "\\SambaSettings.txt"; } } public static string SettingsFileName { get { return File.Exists(UserSettingsFileName) ? UserSettingsFileName : CommonSettingsFileName; } } public static string DefaultCurrencyFormat { get; set; } public static string CurrencySymbol { get { return CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol; } } public static int DbVersion { get { return 20; } } public static string AppVersion { get { return "2.99"; } } public static IList<string> SupportedLanguages { get { return new[] { "en", "de", "fr", "es", "cs", "ru", "hr", "tr", "pt-BR", "it", "ro", "sq", "zh-CN", "nl-NL", "id", "el" }; } } public static long CurrentDbVersion { get; set; } public static string DatabaseLabel { get { if (ConnectionString.ToLower().Contains(".sdf")) return "CE"; if (ConnectionString.ToLower().Contains("data source")) return "SQ"; if (ConnectionString.ToLower().StartsWith("mongodb://")) return "MG"; return "TX"; } } public static string StartupArguments { get; set; } public static void SaveSettings() { try { var serializer = new XmlSerializer(_settingsObject.GetType()); var writer = new XmlTextWriter(SettingsFileName, null); try { serializer.Serialize(writer, _settingsObject); } finally { writer.Close(); } } catch (UnauthorizedAccessException) { if (!File.Exists(UserSettingsFileName)) { File.Create(UserSettingsFileName).Close(); SaveSettings(); } } } public static void LoadSettings() { _settingsObject = new SettingsObject(); string fileName = SettingsFileName; if (File.Exists(fileName)) { var serializer = new XmlSerializer(_settingsObject.GetType()); var reader = new XmlTextReader(fileName); try { _settingsObject = serializer.Deserialize(reader) as SettingsObject; } finally { reader.Close(); } } } static LocalSettings() { if (!Directory.Exists(DocumentPath)) Directory.CreateDirectory(DocumentPath); if (!Directory.Exists(DataPath)) Directory.CreateDirectory(DataPath); if (!Directory.Exists(UserPath)) Directory.CreateDirectory(UserPath); LoadSettings(); } public static void UpdateThreadLanguage() { if (_cultureInfo != null) { if (OverrideWindowsRegionalSettings) Thread.CurrentThread.CurrentCulture = _cultureInfo; Thread.CurrentThread.CurrentUICulture = _cultureInfo; } } public static void UpdateSetting(string settingName, string settingValue) { _settingsObject.SetCustomValue(settingName, settingValue); SaveSettings(); } public static string ReadSetting(string settingName) { return _settingsObject.GetCustomValue(settingName); } public static void SetTraceLogPath(string prefix) { var logFilePath = DocumentPath + "\\" + prefix + "_trace.log"; var objConfigPath = new ConfigurationFileMap(); var appPath = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; try { objConfigPath.MachineConfigFilename = appPath; var entLibConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); var loggingSettings = (LoggingSettings)entLibConfig.GetSection(LoggingSettings.SectionName); var traceListenerData = loggingSettings.TraceListeners.Get("Flat File Trace Listener"); var objFlatFileTraceListenerData = traceListenerData as FlatFileTraceListenerData; if (objFlatFileTraceListenerData != null) objFlatFileTraceListenerData.FileName = logFilePath; entLibConfig.Save(); } catch (Exception) { } } public static string GetSqlServerConnectionString() { var cs = ConnectionString; 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;"; return cs; } } }
zzgaminginc-pointofssale
Samba.Infrastructure/Settings/LocalSettings.cs
C#
gpl3
11,558
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text.RegularExpressions; namespace Samba.Infrastructure.Printing { public static class AsciiControlChars { /// <summary> /// Usually indicates the end of a string. /// </summary> public const char Nul = (char)0x00; /// <summary> /// Meant to be used for printers. When receiving this code the /// printer moves to the next sheet of paper. /// </summary> public const char FormFeed = (char)0x0C; /// <summary> /// Starts an extended sequence of control codes. /// </summary> public const char Escape = (char)0x1B; /// <summary> /// Advances to the next line. /// </summary> public const char Newline = (char)0x0A; /// <summary> /// Defined to separate tables or different sets of data in a serial /// data storage system. /// </summary> public const char GroupSeparator = (char)0x1D; /// <summary> /// A horizontal tab. /// </summary> public const char HorizontalTab = (char)0x09; /// <summary> /// Returns the carriage to the start of the line. /// </summary> public const char CarriageReturn = (char)0x0D; /// <summary> /// Cancels the operation. /// </summary> public const char Cancel = (char)0x18; /// <summary> /// Indicates that control characters present in the stream should /// be passed through as transmitted and not interpreted as control /// characters. /// </summary> public const char DataLinkEscape = (char)0x10; /// <summary> /// Signals the end of a transmission. /// </summary> public const char EndOfTransmission = (char)0x04; /// <summary> /// In serial storage, signals the separation of two files. /// </summary> public const char FileSeparator = (char)0x1C; } public class PrinterHelper { private static string GetTag(string line) { if (Regex.IsMatch(line, "<[^>]+>")) { var tag = Regex.Match(line, "<[^>]+>").Groups[0].Value; return tag; } return ""; } public static IEnumerable<string> ReplaceChars(IEnumerable<string> lines, string pattern) { if (string.IsNullOrEmpty(pattern)) return lines; var result = new List<string>(lines); var patterns = pattern.Split(';'); foreach (var s in patterns) { var parts = s.Split('='); for (var i = 0; i < result.Count; i++) { result[i] = result[i].Replace(parts[0], parts[1]); } } return result; } public static IEnumerable<string> AlignLines(IEnumerable<string> lines, int maxWidth, bool canBreak) { var columnWidths = CalculateColumnWidths(lines); var result = new List<string>(); for (var i = 0; i < lines.Count(); i++) { var line = lines.ElementAt(i); var lastWidth = 0; if (line.Length > 3 && Char.IsNumber(line[3]) && Char.IsNumber(line[2])) { lastWidth = Convert.ToInt32(line[3].ToString()); } if (line.Length < 4) { result.Add(line); } else if (line.ToLower().StartsWith("<l")) { result.Add(AlignLine(maxWidth, lastWidth, line, LineAlignment.Left, canBreak)); } else if (line.ToLower().StartsWith("<r")) { result.Add(AlignLine(maxWidth, lastWidth, line, LineAlignment.Right, canBreak)); } else if (line.ToLower().StartsWith("<c")) { result.Add(AlignLine(maxWidth, lastWidth, line, LineAlignment.Center, canBreak)); } else if (line.ToLower().StartsWith("<j")) { result.Add(AlignLine(maxWidth, lastWidth, line, LineAlignment.Justify, canBreak, columnWidths[0])); if (i < lines.Count() - 1 && columnWidths.Count > 0 && (!lines.ElementAt(i + 1).ToLower().StartsWith("<j") || lines.ElementAt(i + 1).Split('|').Length != columnWidths[0].Length)) columnWidths.RemoveAt(0); } else if (line.ToLower().StartsWith("<f>")) { var c = line.Contains(">") ? line.Substring(line.IndexOf(">") + 1).Trim() : line.Trim(); if (c.Length == 1) result.Add(c.PadLeft(maxWidth, c[0])); } else result.Add(line); } return result; } private static IList<int[]> CalculateColumnWidths(IEnumerable<string> lines) { var result = new List<int[]>(); var tableNo = 0; foreach (var line in lines) { if (line.ToLower().StartsWith("<j")) { var parts = line.Split('|'); if (tableNo == 0 || parts.Length != result[tableNo - 1].Length) { tableNo = result.Count + 1; result.Add(new int[parts.Length]); } for (int i = 0; i < parts.Length; i++) { if (result[tableNo - 1][i] < parts[i].Length) result[tableNo - 1][i] = parts[i].Length; } } else { tableNo = 0; } } return result; } public static string AlignLine(int maxWidth, int width, string line, LineAlignment alignment, bool canBreak, int[] columnWidths = null) { maxWidth = maxWidth / (width + 1); var tag = GetTag(line); line = line.Replace(tag, ""); switch (alignment) { case LineAlignment.Left: return tag + line.PadRight(maxWidth, ' '); case LineAlignment.Right: return tag + line.PadLeft(maxWidth, ' '); case LineAlignment.Center: return tag + line.PadLeft(((maxWidth + line.Length) / 2), ' ').PadRight(maxWidth, ' '); case LineAlignment.Justify: return tag + JustifyText(maxWidth, line, canBreak, columnWidths); default: return tag + line; } } private static string JustifyText(int maxWidth, string line, bool canBreak, IList<int> columnWidths = null) { var parts = line.Split('|'); if (parts.Length == 1) return line; var text = ""; for (var i = parts.Length - 1; i > 0; i--) { var l = columnWidths != null ? columnWidths[i] : parts[i].Length; parts[i] = parts[i].Trim().PadLeft(l); text = parts[i] + text; } if (!canBreak && parts[0].Length > maxWidth) parts[0] = parts[0].Substring(0, maxWidth); if (canBreak && parts[0].Length + text.Length > maxWidth) { return parts[0].Trim() + "\n" + text.PadLeft(maxWidth); } return parts[0].PadRight(maxWidth - text.Length).Substring(0, maxWidth - text.Length) + text; } public static IntPtr GetPrinter(string szPrinterName) { var di = new DOCINFOA { pDocName = "Samba POS Document", pDataType = "RAW" }; IntPtr hPrinter; if (!OpenPrinter(szPrinterName, out hPrinter, IntPtr.Zero)) BombWin32(); if (!StartDocPrinter(hPrinter, 1, di)) BombWin32(); if (!StartPagePrinter(hPrinter)) BombWin32(); return hPrinter; } public static void EndPrinter(IntPtr hPrinter) { EndPagePrinter(hPrinter); EndDocPrinter(hPrinter); ClosePrinter(hPrinter); } public static void SendBytesToPrinter(string szPrinterName, byte[] pBytes) { var hPrinter = GetPrinter(szPrinterName); int dwWritten; if (!WritePrinter(hPrinter, pBytes, pBytes.Length, out dwWritten)) BombWin32(); EndPrinter(hPrinter); } public static void SendFileToPrinter(string szPrinterName, string szFileName) { var fs = new FileStream(szFileName, FileMode.Open); var len = (int)fs.Length; var bytes = new Byte[len]; fs.Read(bytes, 0, len); SendBytesToPrinter(szPrinterName, bytes); } private static void BombWin32() { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); } [StructLayout(LayoutKind.Sequential)] public class DOCINFOA { public string pDocName; public string pOutputFile; public string pDataType; } [DllImport("winspool.Drv", SetLastError = true)] public static extern bool OpenPrinter(string szPrinter, out IntPtr hPrinter, IntPtr pd); [DllImport("winspool.Drv", SetLastError = true)] public static extern bool ClosePrinter(IntPtr hPrinter); [DllImport("winspool.Drv", SetLastError = true)] public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, DOCINFOA di); [DllImport("winspool.Drv", SetLastError = true)] public static extern bool EndDocPrinter(IntPtr hPrinter); [DllImport("winspool.Drv", SetLastError = true)] public static extern bool StartPagePrinter(IntPtr hPrinter); [DllImport("winspool.Drv", SetLastError = true)] public static extern bool EndPagePrinter(IntPtr hPrinter); [DllImport("winspool.Drv", SetLastError = true)] public static extern bool WritePrinter(IntPtr hPrinter, byte[] pBytes, Int32 dwCount, out Int32 dwWritten); } }
zzgaminginc-pointofssale
Samba.Infrastructure/Printing/PrinterHelper.cs
C#
gpl3
10,842
using System; using System.Collections; using System.Drawing; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace Samba.Infrastructure.Printing { public enum LineAlignment { Left, Center, Right, Justify } internal class BitmapData { public BitArray Dots { get; set; } public int Height { get; set; } public int Width { get; set; } } public class LinePrinter { private readonly string _printerName; private IntPtr _hprinter = IntPtr.Zero; private readonly int _maxChars; private readonly int _codePage; public LinePrinter(string printerName, int maxChars, int codepage) { _maxChars = maxChars; _codePage = codepage; _printerName = printerName; } public void Beep(char times = '\x2', char duration = '\x5') { WriteData((char)0x1B + "B" + times + duration); } public void EnableBold() { WriteData((char)0x1B + "G" + (char)1); } public void DisableBold() { WriteData((char)0x1B + "G" + (char)0); } public void SelectTurkishCodePage() { WriteData((char)0x1B + (char)0x1D + "t" + (char)12); } public void Cut() { WriteData((char)0x1B + "d" + (char)1); WriteData((char)0x1D + "V" + (char)66 + (char)0); } public void WriteLine(string line) { WriteLine(line, 0, 0); } public void WriteLine(string line, int height, int width) { int h = height + (width * 16); WriteData((char)0x1D + "!" + (char)h); //if (alignment != LineAlignment.Justify) // WriteData((char)0x1B + "a" + (char)((int)alignment)); //else //{ // WriteData((char)0x1B + "a" + (char)0); // line = PrinterHelper.AlignLine(_maxChars, width, line, alignment, true); //} WriteData((char)0x1B + "a" + (char)0); WriteData(line + (char)0xA); } public void PrintWindow(string line) { //var chars = "▒▓"; const string tl = "┌"; const string tr = "┐"; const string bl = "└"; const string br = "┘"; const string vl = "│"; const string hl = "─"; const string s = "░"; WriteLine(tl + hl.PadLeft(_maxChars - 2, hl[0]) + tr, 1, 0); string text = vl + line.PadLeft((((_maxChars - 2) + line.Length) / 2), s[0]); WriteLine(text + vl.PadLeft(_maxChars - text.Length, s[0]), 1, 0); WriteLine(bl + hl.PadLeft(_maxChars - 2, hl[0]) + br); } public void PrintFullLine(char lineChar) { WriteLine(lineChar.ToString().PadLeft(_maxChars, lineChar)); } public void PrintCenteredLabel(string label, bool expandLabel) { if (expandLabel) label = ExpandLabel(label); string text = label.PadLeft((((_maxChars) + label.Length) / 2), '░'); WriteLine(text + "░".PadLeft(_maxChars - text.Length, '░'), 1, 0); } private static string ExpandLabel(string label) { string result = ""; for (int i = 0; i < label.Length - 1; i++) { result += label[i] + " "; } result += label[label.Length - 1]; return result; } public void StartDocument() { if (_hprinter == IntPtr.Zero) _hprinter = PrinterHelper.GetPrinter(_printerName); } public void WriteData(byte[] data) { if (_hprinter != IntPtr.Zero) { int dwWritten; if (!PrinterHelper.WritePrinter(_hprinter, data, data.Length, out dwWritten)) BombWin32(); } } public void WriteData(string data) { byte[] pBytes = Encoding.GetEncoding(_codePage).GetBytes(data); WriteData(pBytes); } public void EndDocument() { PrinterHelper.EndPrinter(_hprinter); _hprinter = IntPtr.Zero; } private static void BombWin32() { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); } public void PrintBitmap(string fileName) { if (File.Exists(fileName)) { byte[] data = GetDocument(fileName); WriteData(data); } } private static BitmapData GetBitmapData(string bmpFileName) { using (var bitmap = (Bitmap)Image.FromFile(bmpFileName)) { const int threshold = 127; var index = 0; var dimensions = bitmap.Width * bitmap.Height; var dots = new BitArray(dimensions); for (var y = 0; y < bitmap.Height; y++) { for (var x = 0; x < bitmap.Width; x++) { var color = bitmap.GetPixel(x, y); var luminance = (int)(color.R * 0.3 + color.G * 0.59 + color.B * 0.11); dots[index] = (luminance < threshold); index++; } } return new BitmapData { Dots = dots, Height = bitmap.Height, Width = bitmap.Width }; } } private static void RenderLogo(BinaryWriter bw, string fileName) { var data = GetBitmapData(fileName); var dots = data.Dots; var width = BitConverter.GetBytes(data.Width); bw.Write(AsciiControlChars.Escape); bw.Write('3'); bw.Write((byte)24); int offset = 0; while (offset < data.Height) { bw.Write(AsciiControlChars.Escape); bw.Write('*'); // bit-image mode bw.Write((byte)33); // 24-dot double-density bw.Write(width[0]); // width low byte bw.Write(width[1]); // width high byte for (int x = 0; x < data.Width; ++x) { for (int k = 0; k < 3; ++k) { byte slice = 0; for (int b = 0; b < 8; ++b) { int y = (((offset / 8) + k) * 8) + b; int i = (y * data.Width) + x; bool v = false; if (i < dots.Length) { v = dots[i]; } slice |= (byte)((v ? 1 : 0) << (7 - b)); } bw.Write(slice); } } offset += 24; bw.Write(AsciiControlChars.Newline); } bw.Write(AsciiControlChars.Escape); bw.Write('3'); bw.Write((byte)30); } private static byte[] GetDocument(string fileName) { using (var ms = new MemoryStream()) using (var bw = new BinaryWriter(ms)) { bw.Write(AsciiControlChars.Escape); bw.Write('@'); RenderLogo(bw, fileName); bw.Flush(); return ms.ToArray(); } } public void OpenCashDrawer() { // http://social.msdn.microsoft.com/forums/en-US/netfxbcl/thread/35575dd8-7593-4fe6-9b57-64ad6b5f7ae6/ WriteData(((char)27 + (char)112 + (char)0 + (char)25 + (char)250).ToString()); } public void ExecCommand(string command) { if (!string.IsNullOrEmpty(command)) { var data = command.Trim().Split(',').Select(x => Convert.ToInt32(x)).Aggregate("", (current, i) => current + (char)i); WriteData(data); } } } }
zzgaminginc-pointofssale
Samba.Infrastructure/Printing/LinePrinter.cs
C#
gpl3
8,953
using System.Windows; using System.Windows.Controls; using System.ComponentModel.Composition; using Samba.Presentation.Common; namespace Samba.Modules.DashboardModule { /// <summary> /// Interaction logic for DashboardView.xaml /// </summary> /// [Export] public partial class DashboardView : UserControl { [ImportingConstructor] public DashboardView(DashboardViewModel viewModel) { InitializeComponent(); DataContext = viewModel; Splitter.Height = new GridLength(0); KeyboardPanel.Height = new GridLength(0); } private void UserControl_Unloaded(object sender, RoutedEventArgs e) { CommonEventPublisher.PublishDashboardUnloadedEvent(this); } } }
zzgaminginc-pointofssale
Samba.Modules.DashboardModule/DashboardView.xaml.cs
C#
gpl3
831
using System; using System.Windows.Controls; using System.Windows; using System.Windows.Controls.Primitives; using System.Collections.Specialized; namespace Samba.Modules.DashboardModule { [TemplatePart(Name = "PART_ItemsHolder", Type = typeof(Panel))] public class TabControlEx : TabControl { private Panel _itemsHolder = null; public TabControlEx() : base() { // this is necessary so that we get the initial databound selected item this.ItemContainerGenerator.StatusChanged += ItemContainerGenerator_StatusChanged; } /// <summary> /// if containers are done, generate the selected item /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void ItemContainerGenerator_StatusChanged(object sender, EventArgs e) { if (this.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated) { this.ItemContainerGenerator.StatusChanged -= ItemContainerGenerator_StatusChanged; UpdateSelectedItem(); } } /// <summary> /// get the ItemsHolder and generate any children /// </summary> public override void OnApplyTemplate() { base.OnApplyTemplate(); _itemsHolder = GetTemplateChild("PART_ItemsHolder") as Panel; UpdateSelectedItem(); } protected override void OnItemsSourceChanged(System.Collections.IEnumerable oldValue, System.Collections.IEnumerable newValue) { base.OnItemsSourceChanged(oldValue, newValue); UpdateSelectedItem(); } /// <summary> /// when the items change we remove any generated panel children and add any new ones as necessary /// </summary> /// <param name="e"></param> protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e) { base.OnItemsChanged(e); if (_itemsHolder == null) { return; } switch (e.Action) { case NotifyCollectionChangedAction.Reset: _itemsHolder.Children.Clear(); break; case NotifyCollectionChangedAction.Add: case NotifyCollectionChangedAction.Remove: if (e.OldItems != null) { foreach (var item in e.OldItems) { ContentPresenter cp = FindChildContentPresenter(item); if (cp != null) { _itemsHolder.Children.Remove(cp); } } } // don't do anything with new items because we don't want to // create visuals that aren't being shown UpdateSelectedItem(); break; case NotifyCollectionChangedAction.Replace: throw new NotImplementedException("Replace not implemented yet"); } } /// <summary> /// update the visible child in the ItemsHolder /// </summary> /// <param name="e"></param> protected override void OnSelectionChanged(SelectionChangedEventArgs e) { base.OnSelectionChanged(e); UpdateSelectedItem(); } /// <summary> /// generate a ContentPresenter for the selected item /// </summary> void UpdateSelectedItem() { if (_itemsHolder == null) { return; } // generate a ContentPresenter if necessary TabItem item = GetSelectedTabItem(); if (item != null) { CreateChildContentPresenter(item); } // show the right child foreach (ContentPresenter child in _itemsHolder.Children) { child.Visibility = ((child.Tag as TabItem).IsSelected) ? Visibility.Visible : Visibility.Collapsed; } } /// <summary> /// create the child ContentPresenter for the given item (could be data or a TabItem) /// </summary> /// <param name="item"></param> /// <returns></returns> ContentPresenter CreateChildContentPresenter(object item) { if (item == null) { return null; } ContentPresenter cp = FindChildContentPresenter(item); if (cp != null) { return cp; } // the actual child to be added. cp.Tag is a reference to the TabItem cp = new ContentPresenter(); cp.Content = (item is TabItem) ? (item as TabItem).Content : item; cp.ContentTemplate = this.SelectedContentTemplate; cp.ContentTemplateSelector = this.SelectedContentTemplateSelector; cp.ContentStringFormat = this.SelectedContentStringFormat; cp.Visibility = Visibility.Collapsed; cp.Tag = (item is TabItem) ? item : (this.ItemContainerGenerator.ContainerFromItem(item)); _itemsHolder.Children.Add(cp); return cp; } /// <summary> /// Find the CP for the given object. data could be a TabItem or a piece of data /// </summary> /// <param name="data"></param> /// <returns></returns> ContentPresenter FindChildContentPresenter(object data) { if (data is TabItem) { data = (data as TabItem).Content; } if (data == null) { return null; } if (_itemsHolder == null) { return null; } foreach (ContentPresenter cp in _itemsHolder.Children) { if (cp.Content == data) { return cp; } } return null; } /// <summary> /// copied from TabControl; wish it were protected in that class instead of private /// </summary> /// <returns></returns> protected TabItem GetSelectedTabItem() { object selectedItem = base.SelectedItem; if (selectedItem == null) { return null; } TabItem item = selectedItem as TabItem; if (item == null) { item = base.ItemContainerGenerator.ContainerFromIndex(base.SelectedIndex) as TabItem; } return item; } } }
zzgaminginc-pointofssale
Samba.Modules.DashboardModule/TabControlEx.cs
C#
gpl3
7,114
using System; using System.Linq; using System.Collections.ObjectModel; using System.ComponentModel.Composition; using Samba.Presentation.Common; using Samba.Presentation.Common.ModelBase; using Samba.Presentation.Common.Services; namespace Samba.Modules.DashboardModule { [Export] public class DashboardViewModel : ModelListViewModelBase { public ObservableCollection<DashboardCommandCategory> CategoryView { get { var result = new ObservableCollection<DashboardCommandCategory>( PresentationServices.DashboardCommandCategories.OrderBy(x => x.Order)); return result; } } protected override string GetHeaderInfo() { return "Dashboard"; } public void Refresh() { RaisePropertyChanged("CategoryView"); } } }
zzgaminginc-pointofssale
Samba.Modules.DashboardModule/DashboardViewModel.cs
C#
gpl3
946
using System; using System.ComponentModel.Composition; using System.Windows; using System.Windows.Controls; using Samba.Presentation.Common; using Samba.Presentation.Common.Services; using Samba.Services; namespace Samba.Modules.DashboardModule { /// <summary> /// Interaction logic for KeyboardButtonView.xaml /// </summary> /// [Export] public partial class KeyboardButtonView : UserControl { private readonly DashboardView _dashboardView; private readonly GridLength _gridLength = new GridLength(5); private readonly GridLength _zeroGridLength = new GridLength(0); [ImportingConstructor] public KeyboardButtonView(DashboardView dashboardView) { InitializeComponent(); _dashboardView = dashboardView; } private void Button_Click(object sender, RoutedEventArgs e) { ToggleKeyboard(); } private void ToggleKeyboard() { if (AppServices.ActiveAppScreen == AppScreens.Dashboard) { if (_dashboardView.Splitter.Height == _zeroGridLength) { _dashboardView.Splitter.Height = _gridLength; _dashboardView.KeyboardPanel.Height = GridLength.Auto; } else { _dashboardView.Splitter.Height = _zeroGridLength; _dashboardView.KeyboardPanel.Height = _zeroGridLength; } } else { InteractionService.ToggleKeyboard(); } } } }
zzgaminginc-pointofssale
Samba.Modules.DashboardModule/KeyboardButtonView.xaml.cs
C#
gpl3
1,705
using System; using System.Collections.Generic; using System.Windows.Controls; using System.Windows; using Samba.Presentation.Common.ModelBase; namespace Samba.Modules.DashboardModule { internal class ViewSelector : DataTemplateSelector { private readonly Dictionary<Type, DataTemplate> _templateCache; public ViewSelector() { _templateCache = new Dictionary<Type, DataTemplate>(); } public override DataTemplate SelectTemplate(object item, DependencyObject container) { if (item is VisibleViewModelBase) { if (!_templateCache.ContainsKey(item.GetType())) { var result = new DataTemplate { VisualTree = new FrameworkElementFactory((item as VisibleViewModelBase).GetViewType()) }; _templateCache.Add(item.GetType(), result); } return _templateCache[item.GetType()]; } return base.SelectTemplate(item, container); } } }
zzgaminginc-pointofssale
Samba.Modules.DashboardModule/ViewSelector.cs
C#
gpl3
1,256
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.DashboardModule")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Samba.Modules.DashboardModule")] [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("05679a52-bc18-4a14-97d0-10c4af6e6111")] // 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.DashboardModule/Properties/AssemblyInfo.cs
C#
gpl3
1,470
using System.ComponentModel.Composition; using Microsoft.Practices.Prism.MefExtensions.Modularity; using Microsoft.Practices.Prism.Regions; using Samba.Localization.Properties; using Samba.Presentation.Common; using Samba.Services; namespace Samba.Modules.DashboardModule { [ModuleExport(typeof(DashboardModule))] public class DashboardModule : ModuleBase { private readonly IRegionManager _regionManager; private readonly DashboardView _dashboardView; private readonly ICategoryCommand _navigateDashboardCommand; [ImportingConstructor] public DashboardModule(IRegionManager regionManager, DashboardView dashboardView) { _regionManager = regionManager; _dashboardView = dashboardView; _navigateDashboardCommand = new CategoryCommand<string>(Resources.Management, Resources.Common, "Images/Tools.png", OnNavigateDashboard, CanNavigateDashboard) { Order = 90 }; PermissionRegistry.RegisterPermission(PermissionNames.OpenDashboard, PermissionCategories.Navigation, Resources.CanOpenDashboard); } private static bool CanNavigateDashboard(string arg) { return AppServices.IsUserPermittedFor(PermissionNames.OpenDashboard); } private void OnNavigateDashboard(string obj) { AppServices.ActiveAppScreen = AppScreens.Dashboard; _regionManager.Regions[RegionNames.MainRegion].Activate(_dashboardView); ((DashboardViewModel) _dashboardView.DataContext).Refresh(); } protected override void OnPreInitialization() { _regionManager.RegisterViewWithRegion(RegionNames.MainRegion, typeof(DashboardView)); _regionManager.RegisterViewWithRegion(RegionNames.UserRegion, typeof(KeyboardButtonView)); } protected override void OnPostInitialization() { CommonEventPublisher.PublishNavigationCommandEvent(_navigateDashboardCommand); } } }
zzgaminginc-pointofssale
Samba.Modules.DashboardModule/DashboardModule.cs
C#
gpl3
2,074
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using Samba.Domain.Models.Inventory; using Samba.Infrastructure.Data; using Samba.Localization.Properties; using Samba.Presentation.Common; using Samba.Presentation.Common.ModelBase; using Samba.Services; namespace Samba.Modules.InventoryModule { class PeriodicConsumptionViewModel : EntityViewModelBase<PeriodicConsumption> { public PeriodicConsumptionViewModel(PeriodicConsumption model) : base(model) { UpdateCalculationCommand = new CaptionCommand<string>(Resources.CalculateCost, OnUpdateCalculation); } public ICaptionCommand UpdateCalculationCommand { get; set; } private ObservableCollection<PeriodicConsumptionItemViewModel> _periodicConsumptionItems; public ObservableCollection<PeriodicConsumptionItemViewModel> PeriodicConsumptionItems { get { return _periodicConsumptionItems ?? (_periodicConsumptionItems = new ObservableCollection<PeriodicConsumptionItemViewModel>(Model.PeriodicConsumptionItems.Select(x => new PeriodicConsumptionItemViewModel(x)))); } } private ObservableCollection<CostItemViewModel> _costItems; public ObservableCollection<CostItemViewModel> CostItems { get { return _costItems ?? (_costItems = new ObservableCollection<CostItemViewModel>(Model.CostItems.Select(x => new CostItemViewModel(x)))); } } private PeriodicConsumptionItemViewModel _selectedPeriodicConsumptionItem; public PeriodicConsumptionItemViewModel SelectedPeriodicConsumptionItem { get { return _selectedPeriodicConsumptionItem; } set { _selectedPeriodicConsumptionItem = value; RaisePropertyChanged("SelectedPeriodicConsumptionItem"); } } protected override bool CanSave(string arg) { return !AppServices.MainDataContext.IsCurrentWorkPeriodOpen && _periodicConsumptionItems.Count > 0 && Model.WorkPeriodId == AppServices.MainDataContext.CurrentWorkPeriod.Id && base.CanSave(arg); } private void OnUpdateCalculation(string obj) { UpdateCost(); } public void UpdateCost() { InventoryService.CalculateCost(Model, AppServices.MainDataContext.CurrentWorkPeriod); _costItems = null; RaisePropertyChanged("CostItems"); } public override Type GetViewType() { return typeof(PeriodicConsumptionView); } public override string GetModelTypeString() { return Resources.EndOfDayRecord; } protected override void OnSave(string value) { InventoryService.CalculateCost(Model, AppServices.MainDataContext.CurrentWorkPeriod); base.OnSave(value); } } }
zzgaminginc-pointofssale
Samba.Modules.InventoryModule/PeriodicConsumptionViewModel.cs
C#
gpl3
3,101
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Samba.Domain.Models.Inventory; using Samba.Presentation.Common.ModelBase; namespace Samba.Modules.InventoryModule { class RecipeListViewModel : EntityCollectionViewModelBase<RecipeViewModel, Recipe> { protected override RecipeViewModel CreateNewViewModel(Recipe model) { return new RecipeViewModel(model); } protected override Recipe CreateNewModel() { return new Recipe(); } } }
zzgaminginc-pointofssale
Samba.Modules.InventoryModule/RecipeListViewModel.cs
C#
gpl3
583
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; using Samba.Presentation.Common; namespace Samba.Modules.InventoryModule { /// <summary> /// Interaction logic for PeriodicConsumptionView.xaml /// </summary> public partial class PeriodicConsumptionView : UserControl { public PeriodicConsumptionView() { InitializeComponent(); } private void DataGrid_PreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Insert) { //((TransactionViewModel)DataContext).AddTransactionItemCommand.Execute(""); (sender as DataGrid).GetCell(((DataGrid)sender).Items.Count - 1, 0).Focus(); } } private void DataGrid_PreviewTextInput(object sender, TextCompositionEventArgs e) { var dg = sender as DataGrid; if (dg != null && dg.CurrentColumn is DataGridTemplateColumn) { if (!dg.IsEditing()) dg.BeginEdit(); } } private void DataGrid_PreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e) { var ec = ExtensionServices.GetVisualChild<TextBox>(e.EditingElement as ContentPresenter); if (ec != null) ec.SelectAll(); } private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (e.Source is TabControl) { var tc = sender as TabControl; if (tc == null) return; if (tc.SelectedIndex == 1) ((PeriodicConsumptionViewModel)DataContext).UpdateCost(); } } } }
zzgaminginc-pointofssale
Samba.Modules.InventoryModule/PeriodicConsumptionView.xaml.cs
C#
gpl3
2,120
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Samba.Domain.Models.Inventory; using Samba.Presentation.Common; namespace Samba.Modules.InventoryModule { class PeriodicConsumptionItemViewModel : ObservableObject { public PeriodicConsumptionItemViewModel(PeriodicConsumptionItem model) { Model = model; } public PeriodicConsumptionItem Model { get; set; } public string ItemName { get { return Model.InventoryItem.Name; } } public string UnitName { get { return Model.InventoryItem.TransactionUnitMultiplier > 0 ? Model.InventoryItem.TransactionUnit : Model.InventoryItem.BaseUnit; } } public decimal InStock { get { return Model.InStock; } } public decimal Purchase { get { return Model.Purchase; } } public decimal Cost { get { return Model.Cost; } } public decimal Consumption { get { return Model.Consumption; } } public decimal InventoryPrediction { get { return Model.GetInventoryPrediction(); } } public decimal? PhysicalInventory { get { return Model.PhysicalInventory; } set { Model.PhysicalInventory = value; RaisePropertyChanged("PhysicalInventory"); } } } }
zzgaminginc-pointofssale
Samba.Modules.InventoryModule/PeriodicConsumptionItemViewModel.cs
C#
gpl3
1,369
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Samba.Domain.Models.Inventory; using Samba.Domain.Models.Menus; using Samba.Infrastructure.Data; using Samba.Localization.Properties; using Samba.Persistance.Data; using Samba.Presentation.Common; using Samba.Presentation.Common.ModelBase; using System.Linq; namespace Samba.Modules.InventoryModule { class RecipeViewModel : EntityViewModelBase<Recipe> { public RecipeViewModel(Recipe model) : base(model) { AddInventoryItemCommand = new CaptionCommand<string>(string.Format(Resources.Add_f, Resources.Inventory), OnAddInventoryItem, CanAddInventoryItem); DeleteInventoryItemCommand = new CaptionCommand<string>(string.Format(Resources.Delete_f, Resources.Inventory), OnDeleteInventoryItem, CanDeleteInventoryItem); } public override Type GetViewType() { return typeof(RecipeView); } public override string GetModelTypeString() { return Resources.Recipe; } public ICaptionCommand AddInventoryItemCommand { get; set; } public ICaptionCommand DeleteInventoryItemCommand { get; set; } private ObservableCollection<RecipeItemViewModel> _recipeItems; public ObservableCollection<RecipeItemViewModel> RecipeItems { get { return _recipeItems ?? (_recipeItems = new ObservableCollection<RecipeItemViewModel>(Model.RecipeItems.Select(x => new RecipeItemViewModel(x, _workspace)))); } } private RecipeItemViewModel _selectedRecipeItem; public RecipeItemViewModel SelectedRecipeItem { get { return _selectedRecipeItem; } set { _selectedRecipeItem = value; RaisePropertyChanged("SelectedRecipeItem"); } } private string _selectedMenuItemName; public string SelectedMenuItemName { get { return _selectedMenuItemName; } set { _selectedMenuItemName = value; if (SelectedMenuItem == null || SelectedMenuItem.Name != value) { var mi = _workspace.Single<MenuItem>(x => x.Name.ToLower() == _selectedMenuItemName.ToLower()); SelectedMenuItem = mi; if (mi != null && mi.Portions.Count == 1) Portion = mi.Portions[0]; } RaisePropertyChanged("SelectedMenuItemName"); } } private IEnumerable<string> _menuItemNames; public IEnumerable<string> MenuItemNames { get { return _menuItemNames ?? (_menuItemNames = Dao.Select<MenuItem, string>(x => x.Name, null)); } } private MenuItem _selectedMenuItem; private IWorkspace _workspace; public MenuItem SelectedMenuItem { get { return GetMenuItem(); } set { _selectedMenuItem = value; if (value != null) { SelectedMenuItemName = value.Name; } else Portion = null; RaisePropertyChanged("SelectedMenuItem"); } } private MenuItem GetMenuItem() { if (_selectedMenuItem == null) { if (Model.Portion != null) SelectedMenuItem = _workspace.Single<MenuItem>(x => x.Id == Model.Portion.MenuItemId); } return _selectedMenuItem; } public MenuItemPortion Portion { get { return Model.Portion; } set { Model.Portion = value; RaisePropertyChanged("Portion"); } } public decimal FixedCost { get { return Model.FixedCost; } set { Model.FixedCost = value; } } protected override void Initialize(IWorkspace workspace) { _workspace = workspace; } private void OnDeleteInventoryItem(string obj) { if (SelectedRecipeItem != null) { if (SelectedRecipeItem.Model.Id > 0) _workspace.Delete(SelectedRecipeItem.Model); Model.RecipeItems.Remove(SelectedRecipeItem.Model); RecipeItems.Remove(SelectedRecipeItem); } } private void OnAddInventoryItem(string obj) { var ri = new RecipeItem(); Model.RecipeItems.Add(ri); var riv = new RecipeItemViewModel(ri, _workspace); RecipeItems.Add(riv); SelectedRecipeItem = riv; } private bool CanAddInventoryItem(string arg) { return Portion != null; } private bool CanDeleteInventoryItem(string arg) { return SelectedRecipeItem != null; } protected override string GetSaveErrorMessage() { if (Model.RecipeItems.Any(x => x.InventoryItem == null || x.Quantity == 0)) return Resources.SaveErrorZeroOrNullInventoryLines; if (Model.Portion == null) return Resources.APortionShouldSelected; var count = Dao.Count<Recipe>(x => x.Portion.Id == Model.Portion.Id && x.Id != Model.Id); if (count > 0) return string.Format(Resources.ThereIsAnotherRecipeFor_f, SelectedMenuItem.Name); return base.GetSaveErrorMessage(); } } }
zzgaminginc-pointofssale
Samba.Modules.InventoryModule/RecipeViewModel.cs
C#
gpl3
5,809
using System.Collections.Generic; using Samba.Domain.Models.Inventory; using Samba.Infrastructure.Data; using Samba.Localization.Properties; using Samba.Presentation.Common; using Samba.Services; namespace Samba.Modules.InventoryModule { public class MaterialViewModel : ObservableObject { public InventoryItem Model { get; set; } private readonly IWorkspace _workspace; public MaterialViewModel(InventoryItem model, IWorkspace workspace) { Model = model; _workspace = workspace; } private IEnumerable<string> _inventoryItemNames; public IEnumerable<string> InventoryItemNames { get { return _inventoryItemNames ?? (_inventoryItemNames = AppServices.DataAccessService.GetInventoryItemNames()); } } public string Name { get { return Model != null ? Model.Name : string.Format("- {0} -", Resources.Select); } set { UpdateInventoryItem(value); RaisePropertyChanged("Name"); } } private void UpdateInventoryItem(string name) { Model = _workspace.Single<InventoryItem>(x => x.Name.ToLower() == name.ToLower()); } } }
zzgaminginc-pointofssale
Samba.Modules.InventoryModule/MaterialViewModel.cs
C#
gpl3
1,365
using System; using System.Collections.Generic; using Samba.Domain.Models.Inventory; using Samba.Localization.Properties; using Samba.Persistance.Data; using Samba.Presentation.Common.ModelBase; namespace Samba.Modules.InventoryModule { public class InventoryItemViewModel : EntityViewModelBase<InventoryItem> { public InventoryItemViewModel(InventoryItem model) : base(model) { } public override Type GetViewType() { return typeof(InventoryItemView); } public override string GetModelTypeString() { return Resources.InventoryItem; } private IEnumerable<string> _groupCodes; public IEnumerable<string> GroupCodes { get { return _groupCodes ?? (_groupCodes = Dao.Distinct<InventoryItem>(x => x.GroupCode)); } } public string GroupCode { get { return Model.GroupCode ?? ""; } set { Model.GroupCode = value; } } public string BaseUnit { get { return Model.BaseUnit; } set { Model.BaseUnit = value; RaisePropertyChanged("BaseUnit"); RaisePropertyChanged("PredictionUnit"); } } public string TransactionUnit { get { return Model.TransactionUnit; } set { Model.TransactionUnit = value; RaisePropertyChanged("TransactionUnit"); RaisePropertyChanged("PredictionUnit"); } } public int TransactionUnitMultiplier { get { return Model.TransactionUnitMultiplier; } set { Model.TransactionUnitMultiplier = value; RaisePropertyChanged("TransactionUnitMultiplier"); RaisePropertyChanged("PredictionUnit"); } } public string PredictionUnit { get { return TransactionUnitMultiplier > 0 ? TransactionUnit : BaseUnit; } } public string GroupValue { get { return Model.GroupCode; } } protected override string GetSaveErrorMessage() { if (Dao.Single<InventoryItem>(x => x.Name.ToLower() == Model.Name.ToLower() && x.Id != Model.Id) != null) return string.Format(Resources.SaveErrorDuplicateItemName_f, Resources.InventoryItem); return base.GetSaveErrorMessage(); } } }
zzgaminginc-pointofssale
Samba.Modules.InventoryModule/InventoryItemViewModel.cs
C#
gpl3
2,622
using System.Windows.Controls; namespace Samba.Modules.InventoryModule { /// <summary> /// Interaction logic for InventoryItemView.xaml /// </summary> public partial class InventoryItemView : UserControl { public InventoryItemView() { InitializeComponent(); } } }
zzgaminginc-pointofssale
Samba.Modules.InventoryModule/InventoryItemView.xaml.cs
C#
gpl3
343
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.InventoryModule")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Samba Project")] [assembly: AssemblyProduct("Samba.Modules.InventoryModule")] [assembly: AssemblyCopyright("Copyright © Samba Project")] [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("1fa7320c-3e33-48e4-9fda-2f227b729f5c")] // 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.InventoryModule/Properties/AssemblyInfo.cs
C#
gpl3
1,491
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; using Samba.Presentation.Common; namespace Samba.Modules.InventoryModule { /// <summary> /// Interaction logic for RecipeView.xaml /// </summary> public partial class RecipeView : UserControl { public RecipeView() { InitializeComponent(); } private void DataGrid_PreviewTextInput(object sender, TextCompositionEventArgs e) { var dg = sender as DataGrid; if (dg != null && dg.CurrentColumn is DataGridTemplateColumn) { if (!dg.IsEditing()) dg.BeginEdit(); } } private void DataGrid_PreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Insert) { ((RecipeViewModel)DataContext).AddInventoryItemCommand.Execute(""); (sender as DataGrid).GetCell(((DataGrid)sender).Items.Count - 1, 0).Focus(); } } private void DataGrid_PreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e) { var ec = ExtensionServices.GetVisualChild<TextBox>(e.EditingElement as ContentPresenter); if (ec != null) ec.SelectAll(); } } }
zzgaminginc-pointofssale
Samba.Modules.InventoryModule/RecipeView.xaml.cs
C#
gpl3
1,671
using System.Linq; using Samba.Domain.Models.Inventory; using Samba.Localization.Properties; using Samba.Persistance.Data; using Samba.Presentation.Common.ModelBase; namespace Samba.Modules.InventoryModule { class InventoryItemListViewModel : EntityCollectionViewModelBase<InventoryItemViewModel, InventoryItem> { protected override InventoryItemViewModel CreateNewViewModel(InventoryItem model) { return new InventoryItemViewModel(model); } protected override InventoryItem CreateNewModel() { return new InventoryItem(); } protected override string CanDeleteItem(InventoryItem model) { var item = Dao.Count<PeriodicConsumptionItem>(x => x.InventoryItem.Id == model.Id); if (item > 0) return Resources.DeleteErrorInventoryItemUsedInEndOfDayRecord; var item1 = Dao.Count<RecipeItem>(x => x.InventoryItem.Id == model.Id); if (item1 > 1) return Resources.DeleteErrorProductUsedInReceipt; return base.CanDeleteItem(model); } } }
zzgaminginc-pointofssale
Samba.Modules.InventoryModule/InventoryItemListViewModel.cs
C#
gpl3
1,129
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Samba.Domain.Models.Inventory; using Samba.Infrastructure.Data; using Samba.Persistance.Data; using Samba.Presentation.Common; using Samba.Services; namespace Samba.Modules.InventoryModule { class RecipeItemViewModel : ObservableObject { private readonly IWorkspace _workspace; public RecipeItemViewModel(RecipeItem model, IWorkspace workspace) { Model = model; _workspace = workspace; } public RecipeItem Model { get; set; } public InventoryItem InventoryItem { get { return Model.InventoryItem; } set { Model.InventoryItem = value; } } private IEnumerable<string> _inventoryItemNames; public IEnumerable<string> InventoryItemNames { get { return _inventoryItemNames ?? (_inventoryItemNames = AppServices.DataAccessService.GetInventoryItemNames()); } } public string Name { get { return Model.InventoryItem != null ? Model.InventoryItem.Name : string.Format("- {0} -", Localization.Properties.Resources.Select); } set { UpdateInventoryItem(value); RaisePropertyChanged("Name"); RaisePropertyChanged("UnitName"); } } public string UnitName { get { return Model.InventoryItem != null ? Model.InventoryItem.BaseUnit : ""; } } public decimal Quantity { get { return Model.Quantity; } set { Model.Quantity = value; RaisePropertyChanged("Quantity"); } } private void UpdateInventoryItem(string value) { var i = _workspace.Single<InventoryItem>(x => x.Name.ToLower() == value.ToLower()); InventoryItem = i; } } }
zzgaminginc-pointofssale
Samba.Modules.InventoryModule/RecipeItemViewModel.cs
C#
gpl3
2,096
using System.ComponentModel.Composition; using Microsoft.Practices.Prism.MefExtensions.Modularity; using Microsoft.Practices.Prism.Modularity; using Samba.Domain.Models.Inventory; using Samba.Domain.Models.Settings; using Samba.Localization.Properties; using Samba.Persistance.Data; using Samba.Presentation.Common; using Samba.Presentation.Common.ModelBase; using Samba.Services; namespace Samba.Modules.InventoryModule { [ModuleExport(typeof(InventoryModule))] public class InventoryModule :ModuleBase { private InventoryItemListViewModel _inventoryItemListViewModel; private RecipeListViewModel _recipeListViewModel; private TransactionListViewModel _transactionListViewModel; private PeriodicConsumptionListViewModel _periodicConsumptionListViewModel; public ICategoryCommand ListInventoryItemsCommand { get; set; } public ICategoryCommand ListRecipesCommand { get; set; } public ICategoryCommand ListTransactionsCommand { get; set; } public ICategoryCommand ListPeriodicConsumptionsCommand { get; set; } protected override void OnPostInitialization() { CommonEventPublisher.PublishDashboardCommandEvent(ListInventoryItemsCommand); CommonEventPublisher.PublishDashboardCommandEvent(ListRecipesCommand); CommonEventPublisher.PublishDashboardCommandEvent(ListTransactionsCommand); CommonEventPublisher.PublishDashboardCommandEvent(ListPeriodicConsumptionsCommand); } [ImportingConstructor] public InventoryModule() { ListInventoryItemsCommand = new CategoryCommand<string>(Resources.InventoryItems, Resources.Products, OnListInventoryItems) { Order = 26 }; ListRecipesCommand = new CategoryCommand<string>(Resources.Recipes, Resources.Products, OnListRecipes) { Order = 27 }; ListTransactionsCommand = new CategoryCommand<string>(Resources.Transactions, Resources.Products, OnListTransactions) { Order = 28 }; ListPeriodicConsumptionsCommand = new CategoryCommand<string>(Resources.EndOfDayRecords, Resources.Products, OnListPeriodicConsumptions) { Order = 29 }; EventServiceFactory.EventService.GetEvent<GenericEvent<VisibleViewModelBase>>().Subscribe(s => { if (s.Topic == EventTopicNames.ViewClosed) { if (s.Value == _inventoryItemListViewModel) _inventoryItemListViewModel = null; if (s.Value == _recipeListViewModel) _recipeListViewModel = null; if (s.Value == _transactionListViewModel) _transactionListViewModel = null; if (s.Value == _periodicConsumptionListViewModel) _periodicConsumptionListViewModel = null; } }); EventServiceFactory.EventService.GetEvent<GenericEvent<WorkPeriod>>().Subscribe(OnWorkperiodStatusChanged); } private static void OnWorkperiodStatusChanged(EventParameters<WorkPeriod> obj) { if (obj.Topic == EventTopicNames.WorkPeriodStatusChanged) { using (var ws = WorkspaceFactory.Create()) { if (ws.Count<Recipe>() > 0) { if (!AppServices.MainDataContext.IsCurrentWorkPeriodOpen) { var pc = InventoryService.GetCurrentPeriodicConsumption(ws); if (pc.Id == 0) ws.Add(pc); ws.CommitChanges(); } else { if (AppServices.MainDataContext.PreviousWorkPeriod != null) { var pc = InventoryService.GetPreviousPeriodicConsumption(ws); if (pc != null) { InventoryService.CalculateCost(pc, AppServices.MainDataContext.PreviousWorkPeriod); ws.CommitChanges(); } } } } } } } private void OnListPeriodicConsumptions(string obj) { if (_periodicConsumptionListViewModel == null) _periodicConsumptionListViewModel = new PeriodicConsumptionListViewModel(); CommonEventPublisher.PublishViewAddedEvent(_periodicConsumptionListViewModel); } private void OnListTransactions(string obj) { if (_transactionListViewModel == null) _transactionListViewModel = new TransactionListViewModel(); CommonEventPublisher.PublishViewAddedEvent(_transactionListViewModel); } private void OnListRecipes(string obj) { if (_recipeListViewModel == null) _recipeListViewModel = new RecipeListViewModel(); CommonEventPublisher.PublishViewAddedEvent(_recipeListViewModel); } private void OnListInventoryItems(string obj) { if (_inventoryItemListViewModel == null) _inventoryItemListViewModel = new InventoryItemListViewModel(); CommonEventPublisher.PublishViewAddedEvent(_inventoryItemListViewModel); } } }
zzgaminginc-pointofssale
Samba.Modules.InventoryModule/InventoryModule.cs
C#
gpl3
5,666
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Samba.Domain.Models.Inventory; using Samba.Domain.Models.Menus; using Samba.Persistance.Data; using Samba.Presentation.Common; namespace Samba.Modules.InventoryModule { class CostItemViewModel : ObservableObject { public CostItem Model { get; set; } public CostItemViewModel(CostItem model) { Model = model; } private MenuItem _menuItem; public MenuItem MenuItem { get { return _menuItem ?? (_menuItem = Dao.Single<MenuItem>(x => x.Id == Model.Portion.MenuItemId)); } } public string MenuItemName { get { return MenuItem.Name; } } public string PortionName { get { return Model.Portion.Name; } } public decimal Quantity { get { return Model.Quantity; } } public decimal CostPrediction { get { return Model.CostPrediction; } } public decimal Cost { get { return Model.Cost; } } } }
zzgaminginc-pointofssale
Samba.Modules.InventoryModule/CostItemViewModel.cs
C#
gpl3
1,020
using System; using System.Linq; using Samba.Domain.Models.Inventory; using Samba.Localization.Properties; using Samba.Presentation.Common; using Samba.Presentation.Common.ModelBase; using Samba.Services; namespace Samba.Modules.InventoryModule { class PeriodicConsumptionListViewModel : EntityCollectionViewModelBase<PeriodicConsumptionViewModel, PeriodicConsumption> { protected override PeriodicConsumptionViewModel CreateNewViewModel(PeriodicConsumption model) { return new PeriodicConsumptionViewModel(model); } protected override PeriodicConsumption CreateNewModel() { return new PeriodicConsumption(); } protected override void OnAddItem(object obj) { var pc = InventoryService.GetCurrentPeriodicConsumption(Workspace); VisibleViewModelBase wm = Items.SingleOrDefault(x => x.Name == pc.Name) ?? InternalCreateNewViewModel(pc); wm.PublishEvent(EventTopicNames.ViewAdded); } protected override bool CanAddItem(object obj) { return AppServices.MainDataContext.CurrentWorkPeriod != null; } protected override string CanDeleteItem(PeriodicConsumption model) { if (model.WorkPeriodId != AppServices.MainDataContext.CurrentWorkPeriod.Id || !AppServices.MainDataContext.IsCurrentWorkPeriodOpen) return Resources.CantDeletePastEndOfDayRecords; return base.CanDeleteItem(model); } } }
zzgaminginc-pointofssale
Samba.Modules.InventoryModule/PeriodicConsumptionListViewModel.cs
C#
gpl3
1,593
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Samba.Domain.Models.Inventory; using Samba.Presentation.Common.ModelBase; using Samba.Services; namespace Samba.Modules.InventoryModule { class TransactionListViewModel : EntityCollectionViewModelBase<TransactionViewModel, Transaction> { protected override TransactionViewModel CreateNewViewModel(Transaction model) { return new TransactionViewModel(model); } protected override Transaction CreateNewModel() { return new Transaction(); } protected override bool CanAddItem(object obj) { return AppServices.MainDataContext.CurrentWorkPeriod != null; } } }
zzgaminginc-pointofssale
Samba.Modules.InventoryModule/TransactionListViewModel.cs
C#
gpl3
801
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; using Samba.Presentation.Common; namespace Samba.Modules.InventoryModule { /// <summary> /// Interaction logic for TransactionView.xaml /// </summary> public partial class TransactionView : UserControl { public TransactionView() { InitializeComponent(); } private void DataGrid_PreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Insert) { ((TransactionViewModel)DataContext).AddTransactionItemCommand.Execute(""); (sender as DataGrid).GetCell(((DataGrid)sender).Items.Count - 1, 0).Focus(); } } private void DataGrid_PreviewTextInput(object sender, TextCompositionEventArgs e) { var dg = sender as DataGrid; if (dg != null && dg.CurrentColumn is DataGridTemplateColumn) { if (!dg.IsEditing()) dg.BeginEdit(); } } private void DataGrid_PreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e) { var ec = ExtensionServices.GetVisualChild<TextBox>(e.EditingElement as ContentPresenter); if (ec != null) ec.SelectAll(); } } }
zzgaminginc-pointofssale
Samba.Modules.InventoryModule/TransactionView.xaml.cs
C#
gpl3
1,693
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Samba.Domain.Models.Inventory; using Samba.Infrastructure.Data; using Samba.Persistance.Data; using Samba.Presentation.Common; namespace Samba.Modules.InventoryModule { class TransactionItemViewModel : ObservableObject { private readonly IWorkspace _workspace; public TransactionItemViewModel(TransactionItem model, IWorkspace workspace) { _workspace = workspace; Model = model; } public TransactionItem Model { get; set; } public InventoryItem InventoryItem { get { return Model.InventoryItem; } set { if(value != null) { Model.InventoryItem = value; UnitName = value.TransactionUnitMultiplier > 0 ? value.TransactionUnit : value.BaseUnit; } } } public string Name { get { return Model.InventoryItem != null ? Model.InventoryItem.Name : string.Format("- {0} -", Localization.Properties.Resources.Select); } set { UpdateInventoryItem(value); RaisePropertyChanged("Name"); RaisePropertyChanged("UnitName"); RaisePropertyChanged("UnitNames"); } } public string UnitName { get { return Model.Unit; } set { Model.Unit = value; Model.Multiplier = value == InventoryItem.TransactionUnit ? InventoryItem.TransactionUnitMultiplier : 1; RaisePropertyChanged("UnitName"); } } private IEnumerable<string> _inventoryItemNames; public IEnumerable<string> InventoryItemNames { get { return _inventoryItemNames ?? (_inventoryItemNames = Dao.Select<InventoryItem, string>(x => x.Name, x => !string.IsNullOrEmpty(x.Name))); } } public IEnumerable<string> UnitNames { get { if (Model.InventoryItem != null) { var result = new List<string> { Model.InventoryItem.BaseUnit }; if (Model.InventoryItem.TransactionUnitMultiplier > 0) result.Add(Model.InventoryItem.TransactionUnit); return result; } return new List<string>(); } } public decimal Quantity { get { return Model.Quantity; } set { Model.Quantity = value; RaisePropertyChanged("Quantity"); RaisePropertyChanged("TotalPrice"); } } public decimal Price { get { return Model.Price; } set { Model.Price = value; RaisePropertyChanged("Price"); RaisePropertyChanged("TotalPrice"); } } public decimal TotalPrice { get { return Model.Price * Model.Quantity; } set { Model.Price = (value / Model.Quantity); RaisePropertyChanged("Price"); RaisePropertyChanged("TotalPrice"); } } private void UpdateInventoryItem(string value) { InventoryItem = _workspace.Single<InventoryItem>(x => x.Name.ToLower() == value.ToLower()); } } }
zzgaminginc-pointofssale
Samba.Modules.InventoryModule/TransactionItemViewModel.cs
C#
gpl3
3,817
using System; using System.Collections.ObjectModel; using System.Linq; using Samba.Domain.Models.Inventory; using Samba.Infrastructure.Data; using Samba.Localization.Properties; using Samba.Presentation.Common; using Samba.Presentation.Common.ModelBase; using Samba.Services; namespace Samba.Modules.InventoryModule { class TransactionViewModel : EntityViewModelBase<Transaction> { private IWorkspace _workspace; public TransactionViewModel(Transaction model) : base(model) { AddTransactionItemCommand = new CaptionCommand<string>(string.Format(Resources.Add_f, Resources.Line), OnAddTransactionItem, CanAddTransactionItem); DeleteTransactionItemCommand = new CaptionCommand<string>(string.Format(Resources.Delete_f, Resources.Line), OnDeleteTransactionItem, CanDeleteTransactionItem); } public DateTime Date { get { return Model.Date; } set { Model.Date = value; } } public string DateLabel { get { return string.Format(Resources.DocumentDate_f, Date); } } public string TimeLabel { get { return string.Format(Resources.DocumentTime_f, Date); } } public ICaptionCommand AddTransactionItemCommand { get; set; } public ICaptionCommand DeleteTransactionItemCommand { get; set; } private ObservableCollection<TransactionItemViewModel> _transactionItems; public ObservableCollection<TransactionItemViewModel> TransactionItems { get { return _transactionItems ?? (_transactionItems = GetTransactionItems()); } } private ObservableCollection<TransactionItemViewModel> GetTransactionItems() { if (Model.TransactionItems.Count == 0) AddTransactionItemCommand.Execute(""); return new ObservableCollection<TransactionItemViewModel>( Model.TransactionItems.Select(x => new TransactionItemViewModel(x, _workspace))); } private TransactionItemViewModel _selectedTransactionItem; public TransactionItemViewModel SelectedTransactionItem { get { return _selectedTransactionItem; } set { _selectedTransactionItem = value; RaisePropertyChanged("SelectedTransactionItem"); } } private bool CanDeleteTransactionItem(string arg) { return SelectedTransactionItem != null; } private void OnDeleteTransactionItem(string obj) { if (SelectedTransactionItem.Model.Id > 0) _workspace.Delete(SelectedTransactionItem.Model); Model.TransactionItems.Remove(SelectedTransactionItem.Model); TransactionItems.Remove(SelectedTransactionItem); } private bool CanAddTransactionItem(string arg) { return true; } protected override bool CanSave(string arg) { return AppServices.MainDataContext.IsCurrentWorkPeriodOpen && base.CanSave(arg); } private void OnAddTransactionItem(string obj) { var ti = new TransactionItem(); var tiv = new TransactionItemViewModel(ti, _workspace); Model.TransactionItems.Add(ti); TransactionItems.Add(tiv); SelectedTransactionItem = tiv; } protected override void Initialize(IWorkspace workspace) { _workspace = workspace; } protected override void OnSave(string value) { var modified = false; foreach (var transactionItemViewModel in _transactionItems) { if (transactionItemViewModel.Model.InventoryItem == null || transactionItemViewModel.Quantity == 0) { modified = true; Model.TransactionItems.Remove(transactionItemViewModel.Model); if (transactionItemViewModel.Model.Id > 0) _workspace.Delete(transactionItemViewModel.Model); } } if (modified) _transactionItems = null; base.OnSave(value); } public override Type GetViewType() { return typeof(TransactionView); } public override string GetModelTypeString() { return Resources.TransactionDocument; } } }
zzgaminginc-pointofssale
Samba.Modules.InventoryModule/TransactionViewModel.cs
C#
gpl3
4,597
[Code] var LGPLPage: TOutputMsgMemoWizardPage; LGPLAccept: TNewRadioButton; LGPLRefuse: TNewRadioButton; procedure LGPLPageActivate(Sender: TWizardPage); forward; procedure LGPLAcceptClick(Sender: TObject); forward; procedure LGPL_InitializeWizard(); var LGPLText: AnsiString; begin // Create the page LGPLPage := CreateOutputMsgMemoPage(wpLicense, SetupMessage(msgWizardLicense), SetupMessage(msgLicenseLabel), CustomMessage('LGPLHeader'), ''); // Adjust the memo and add the confirm/refuse options LGPLPage.RichEditViewer.Height := ScaleY(148); LGPLAccept := TNewRadioButton.Create(LGPLPage); LGPLAccept.Left := LGPLPage.RichEditViewer.Left; LGPLAccept.Top := LGPLPage.Surface.ClientHeight - ScaleY(41); LGPLAccept.Width := LGPLPage.RichEditViewer.Width; LGPLAccept.Parent := LGPLPage.Surface; LGPLAccept.Caption := SetupMessage(msgLicenseAccepted); LGPLRefuse := TNewRadioButton.Create(LGPLPage); LGPLRefuse.Left := LGPLPage.RichEditViewer.Left; LGPLRefuse.Top := LGPLPage.Surface.ClientHeight - ScaleY(21); LGPLRefuse.Width := LGPLPage.RichEditViewer.Width; LGPLRefuse.Parent := LGPLPage.Surface; LGPLRefuse.Caption := SetupMessage(msgLicenseNotAccepted); // Set the states and event handlers LGPLPage.OnActivate := @LGPLPageActivate; LGPLAccept.OnClick := @LGPLAcceptClick; LGPLRefuse.OnClick := @LGPLAcceptClick; LGPLRefuse.Checked := true; // Load the LGPL text into the new page ExtractTemporaryFile('license.txt'); LoadStringFromFile(ExpandConstant('{tmp}/license.txt'), LGPLText); LGPLPage.RichEditViewer.RTFText := LGPLText; end; procedure LGPLPageActivate(Sender: TWizardPage); begin WizardForm.NextButton.Enabled := LGPLAccept.Checked; end; procedure LGPLAcceptClick(Sender: TObject); begin WizardForm.NextButton.Enabled := LGPLAccept.Checked; end; [Files] Source: src\gpl-3.0.txt; DestDir: {app}; Flags: ignoreversion Source: src\license.txt; DestDir: {app}; Flags: ignoreversion [CustomMessages] LGPLHeader=Please read the following License Agreement. Some components are licensed under the GNU Lesser General Public License.
zzgaminginc-pointofssale
SambaSetup/scripts/lgpl.iss
Inno Setup
gpl3
2,175
// http://support.microsoft.com/kb/239114 [CustomMessages] jet4sp8_title=Jet 4 en.jet4sp8_size=3.7 MB de.jet4sp8_size=3,7 MB [Run] Filename: "{ini:{tmp}{\}dep.ini,install,jet4sp8}"; Description: "{cm:jet4sp8_title}"; StatusMsg: "{cm:depinstall_status,{cm:jet4sp8_title}}"; Parameters: "/q:a /c:""install /q /l"""; Flags: skipifdoesntexist [Code] const jet4sp8_url = 'http://download.microsoft.com/download/4/3/9/4393c9ac-e69e-458d-9f6d-2fe191c51469/Jet40SP8_9xNT.exe'; procedure jet4sp8(MinVersion: string); begin if (fileversion(ExpandConstant('{sys}{\}msjet40.dll')) < MinVersion) then InstallPackage('jet4sp8', 'jet4sp8.exe', CustomMessage('jet4sp8_title'), CustomMessage('jet4sp8_size'), jet4sp8_url); end;
zzgaminginc-pointofssale
SambaSetup/scripts/old/products/jet4sp8.iss
Inno Setup
gpl3
742
[CustomMessages] wic_title=Windows Imaging Component en.wic_size=1.2 MB de.wic_size=1.2 MB [Code] const wic_url = 'http://download.microsoft.com/download/f/f/1/ff178bb1-da91-48ed-89e5-478a99387d4f/wic_x86_enu.exe'; procedure wic(); var installed: boolean; begin installed := FileExists(GetEnv('windir') + '\system32\windowscodecs.dll'); if not installed then begin InstallPackage('wic', 'wic.exe', CustomMessage('wic_title'), CustomMessage('wic_size'), wic_url); end; end;
zzgaminginc-pointofssale
SambaSetup/scripts/old/products/wic.iss
Inno Setup
gpl3
501