code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using DataGridFilterLibrary.Querying; namespace DataGridFilterLibrary { public class DataGridExtensions { public static DependencyProperty DataGridFilterQueryControllerProperty = DependencyProperty.RegisterAttached("DataGridFilterQueryController", typeof(QueryController), typeof(DataGridExtensions)); public static QueryController GetDataGridFilterQueryController(DependencyObject target) { return (QueryController)target.GetValue(DataGridFilterQueryControllerProperty); } public static void SetDataGridFilterQueryController(DependencyObject target, QueryController value) { target.SetValue(DataGridFilterQueryControllerProperty, value); } public static DependencyProperty ClearFilterCommandProperty = DependencyProperty.RegisterAttached("ClearFilterCommand", typeof(DataGridFilterCommand), typeof(DataGridExtensions)); public static DataGridFilterCommand GetClearFilterCommand(DependencyObject target) { return (DataGridFilterCommand)target.GetValue(ClearFilterCommandProperty); } public static void SetClearFilterCommand(DependencyObject target, DataGridFilterCommand value) { target.SetValue(ClearFilterCommandProperty, value); } public static DependencyProperty IsFilterVisibleProperty = DependencyProperty.RegisterAttached("IsFilterVisible", typeof(bool?), typeof(DataGridExtensions), new FrameworkPropertyMetadata(true)); public static bool? GetIsFilterVisible( DependencyObject target) { return (bool)target.GetValue(IsFilterVisibleProperty); } public static void SetIsFilterVisible( DependencyObject target, bool? value) { target.SetValue(IsFilterVisibleProperty, value); } public static DependencyProperty UseBackgroundWorkerForFilteringProperty = DependencyProperty.RegisterAttached("UseBackgroundWorkerForFiltering", typeof(bool), typeof(DataGridExtensions), new FrameworkPropertyMetadata(false)); public static bool GetUseBackgroundWorkerForFiltering( DependencyObject target) { return (bool)target.GetValue(UseBackgroundWorkerForFilteringProperty); } public static void SetUseBackgroundWorkerForFiltering( DependencyObject target, bool value) { target.SetValue(UseBackgroundWorkerForFilteringProperty, value); } public static DependencyProperty IsClearButtonVisibleProperty = DependencyProperty.RegisterAttached("IsClearButtonVisible", typeof(bool), typeof(DataGridExtensions), new FrameworkPropertyMetadata(true)); public static bool GetIsClearButtonVisible( DependencyObject target) { return (bool)target.GetValue(IsClearButtonVisibleProperty); } public static void SetIsClearButtonVisible( DependencyObject target, bool value) { target.SetValue(IsClearButtonVisibleProperty, value); } } }
zzgaminginc-pointofssale
Lib/DataGridFilterLibrary/DataGridExtensions.cs
C#
gpl3
3,501
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Data; using System.Windows.Controls; namespace DataGridFilterLibrary { /// <summary> /// Code from: http://joemorrison.org/blog/2009/02/17/excedrin-headache-35401281-using-combo-boxes-with-the-wpf-datagrid/ /// fixes issue: /// http://www.codeplex.com/wpf/WorkItem/View.aspx?WorkItemId=8153 /// </summary> public class DataGridComboBoxColumnWithBindingHack : DataGridComboBoxColumn { protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) { FrameworkElement element = base.GenerateEditingElement(cell, dataItem); CopyItemsSource(element); return element; } protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) { FrameworkElement element = base.GenerateElement(cell, dataItem); CopyItemsSource(element); return element; } private void CopyItemsSource(FrameworkElement element) { BindingOperations.SetBinding(element, ComboBox.ItemsSourceProperty, BindingOperations.GetBinding(this, ComboBox.ItemsSourceProperty)); } } }
zzgaminginc-pointofssale
Lib/DataGridFilterLibrary/DataGridComboBoxColumnWithBindingHack.cs
C#
gpl3
1,369
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 System.Collections; using DataGridFilterLibrary.Support; using System.Reflection; using DataGridFilterLibrary.Querying; using System.ComponentModel; using System.Windows.Controls.Primitives; namespace DataGridFilterLibrary { public class DataGridColumnFilter : Control { static DataGridColumnFilter() { DefaultStyleKeyProperty.OverrideMetadata(typeof(DataGridColumnFilter), new FrameworkPropertyMetadata(typeof(DataGridColumnFilter))); } #region Overrides protected override void OnPropertyChanged( DependencyPropertyChangedEventArgs e) { if (e.Property == DataGridItemsSourceProperty && e.OldValue != e.NewValue && AssignedDataGridColumn != null && DataGrid != null && AssignedDataGridColumn is DataGridColumn) { initialize(); FilterCurrentData.IsRefresh = true;//query optimization filed filterCurrentData_FilterChangedEvent(this, EventArgs.Empty);//init query FilterCurrentData.FilterChangedEvent -= new EventHandler<EventArgs>(filterCurrentData_FilterChangedEvent); FilterCurrentData.FilterChangedEvent += new EventHandler<EventArgs>(filterCurrentData_FilterChangedEvent); } base.OnPropertyChanged(e); } #endregion #region Properties public FilterData FilterCurrentData { get { return (FilterData)GetValue(FilterCurrentDataProperty); } set { SetValue(FilterCurrentDataProperty, value); } } public static readonly DependencyProperty FilterCurrentDataProperty = DependencyProperty.Register("FilterCurrentData", typeof(FilterData), typeof(DataGridColumnFilter)); public DataGridColumnHeader AssignedDataGridColumnHeader { get { return (DataGridColumnHeader)GetValue(AssignedDataGridColumnHeaderProperty); } set { SetValue(AssignedDataGridColumnHeaderProperty, value); } } public static readonly DependencyProperty AssignedDataGridColumnHeaderProperty = DependencyProperty.Register("AssignedDataGridColumnHeader", typeof(DataGridColumnHeader), typeof(DataGridColumnFilter)); public DataGridColumn AssignedDataGridColumn { get { return (DataGridColumn)GetValue(AssignedDataGridColumnProperty); } set { SetValue(AssignedDataGridColumnProperty, value); } } public static readonly DependencyProperty AssignedDataGridColumnProperty = DependencyProperty.Register("AssignedDataGridColumn", typeof(DataGridColumn), typeof(DataGridColumnFilter)); public DataGrid DataGrid { get { return (DataGrid)GetValue(DataGridProperty); } set { SetValue(DataGridProperty, value); } } public static readonly DependencyProperty DataGridProperty = DependencyProperty.Register("DataGrid", typeof(DataGrid), typeof(DataGridColumnFilter)); public IEnumerable DataGridItemsSource { get { return (IEnumerable)GetValue(DataGridItemsSourceProperty); } set { SetValue(DataGridItemsSourceProperty, value); } } public static readonly DependencyProperty DataGridItemsSourceProperty = DependencyProperty.Register("DataGridItemsSource", typeof(IEnumerable), typeof(DataGridColumnFilter)); public bool IsFilteringInProgress { get { return (bool)GetValue(IsFilteringInProgressProperty); } set { SetValue(IsFilteringInProgressProperty, value); } } public static readonly DependencyProperty IsFilteringInProgressProperty = DependencyProperty.Register("IsFilteringInProgress", typeof(bool), typeof(DataGridColumnFilter)); public FilterType FilterType { get { return FilterCurrentData != null ? FilterCurrentData.Type : FilterType.Text; } } public bool IsTextFilterControl { get { return (bool)GetValue(IsTextFilterControlProperty); } set { SetValue(IsTextFilterControlProperty, value); } } public static readonly DependencyProperty IsTextFilterControlProperty = DependencyProperty.Register("IsTextFilterControl", typeof(bool), typeof(DataGridColumnFilter)); public bool IsNumericFilterControl { get { return (bool)GetValue(IsNumericFilterControlProperty); } set { SetValue(IsNumericFilterControlProperty, value); } } public static readonly DependencyProperty IsNumericFilterControlProperty = DependencyProperty.Register("IsNumericFilterControl", typeof(bool), typeof(DataGridColumnFilter)); public bool IsNumericBetweenFilterControl { get { return (bool)GetValue(IsNumericBetweenFilterControlProperty); } set { SetValue(IsNumericBetweenFilterControlProperty, value); } } public static readonly DependencyProperty IsNumericBetweenFilterControlProperty = DependencyProperty.Register("IsNumericBetweenFilterControl", typeof(bool), typeof(DataGridColumnFilter)); public bool IsBooleanFilterControl { get { return (bool)GetValue(IsBooleanFilterControlProperty); } set { SetValue(IsBooleanFilterControlProperty, value); } } public static readonly DependencyProperty IsBooleanFilterControlProperty = DependencyProperty.Register("IsBooleanFilterControl", typeof(bool), typeof(DataGridColumnFilter)); public bool IsListFilterControl { get { return (bool)GetValue(IsListFilterControlProperty); } set { SetValue(IsListFilterControlProperty, value); } } public static readonly DependencyProperty IsListFilterControlProperty = DependencyProperty.Register("IsListFilterControl", typeof(bool), typeof(DataGridColumnFilter)); public bool IsDateTimeFilterControl { get { return (bool)GetValue(IsDateTimeFilterControlProperty); } set { SetValue(IsDateTimeFilterControlProperty, value); } } public static readonly DependencyProperty IsDateTimeFilterControlProperty = DependencyProperty.Register("IsDateTimeFilterControl", typeof(bool), typeof(DataGridColumnFilter)); public bool IsDateTimeBetweenFilterControl { get { return (bool)GetValue(IsDateTimeBetweenFilterControlProperty); } set { SetValue(IsDateTimeBetweenFilterControlProperty, value); } } public static readonly DependencyProperty IsDateTimeBetweenFilterControlProperty = DependencyProperty.Register("IsDateTimeBetweenFilterControl", typeof(bool), typeof(DataGridColumnFilter)); public bool IsFirstFilterControl { get { return (bool)GetValue(IsFirstFilterControlProperty); } set { SetValue(IsFirstFilterControlProperty, value); } } public static readonly DependencyProperty IsFirstFilterControlProperty = DependencyProperty.Register("IsFirstFilterControl", typeof(bool), typeof(DataGridColumnFilter)); public bool IsControlInitialized { get { return (bool)GetValue(IsControlInitializedProperty); } set { SetValue(IsControlInitializedProperty, value); } } public static readonly DependencyProperty IsControlInitializedProperty = DependencyProperty.Register("IsControlInitialized", typeof(bool), typeof(DataGridColumnFilter)); #endregion #region Initialization private void initialize() { if (DataGridItemsSource != null && AssignedDataGridColumn != null && DataGrid != null) { initFilterData(); initControlType(); handleListFilterType(); hookUpCommands(); IsControlInitialized = true; } } private void initFilterData() { if (FilterCurrentData == null || !FilterCurrentData.IsTypeInitialized) { string valuePropertyBindingPath = getValuePropertyBindingPath(AssignedDataGridColumn); bool typeInitialized; Type valuePropertyType = getValuePropertyType( valuePropertyBindingPath, getItemSourceElementType(out typeInitialized)); FilterType filterType = getFilterType( valuePropertyType, isComboDataGridColumn(), isBetweenType()); FilterOperator filterOperator = FilterOperator.Undefined; string queryString = String.Empty; string queryStringTo = String.Empty; FilterCurrentData = new FilterData( filterOperator, filterType, valuePropertyBindingPath, valuePropertyType, queryString, queryStringTo, typeInitialized, DataGridColumnExtensions.GetIsCaseSensitiveSearch(AssignedDataGridColumn)); } } private void initControlType() { IsFirstFilterControl = false; IsTextFilterControl = false; IsNumericFilterControl = false; IsBooleanFilterControl = false; IsListFilterControl = false; IsDateTimeFilterControl = false; IsNumericBetweenFilterControl = false; IsDateTimeBetweenFilterControl = false; if (FilterType == FilterType.Text) { IsTextFilterControl = true; } else if (FilterType == FilterType.Numeric) { IsNumericFilterControl = true; } else if (FilterType == FilterType.Boolean) { IsBooleanFilterControl = true; } else if (FilterType == FilterType.List) { IsListFilterControl = true; } else if (FilterType == FilterType.DateTime) { IsDateTimeFilterControl = true; } else if (FilterType == FilterType.NumericBetween) { IsNumericBetweenFilterControl = true; } else if (FilterType == FilterType.DateTimeBetween) { IsDateTimeBetweenFilterControl = true; } } private void handleListFilterType() { if (FilterCurrentData.Type == FilterType.List) { ComboBox comboBox = this.Template.FindName("PART_ComboBoxFilter", this) as ComboBox; DataGridComboBoxColumn column = AssignedDataGridColumn as DataGridComboBoxColumn; if (comboBox != null && column != null) { if (DataGridComboBoxExtensions.GetIsTextFilter(column)) { FilterCurrentData.Type = FilterType.Text; initControlType(); } else //list filter type { Binding columnItemsSourceBinding = null; columnItemsSourceBinding = BindingOperations.GetBinding(column, DataGridComboBoxColumn.ItemsSourceProperty); if (columnItemsSourceBinding == null) { System.Windows.Setter styleSetter = column.EditingElementStyle.Setters.First(s => ((System.Windows.Setter)s).Property == DataGridComboBoxColumn.ItemsSourceProperty) as System.Windows.Setter; if (styleSetter != null) columnItemsSourceBinding = styleSetter.Value as Binding; } comboBox.DisplayMemberPath = column.DisplayMemberPath; comboBox.SelectedValuePath = column.SelectedValuePath; if (columnItemsSourceBinding != null) { BindingOperations.SetBinding(comboBox, ComboBox.ItemsSourceProperty, columnItemsSourceBinding); } comboBox.RequestBringIntoView += new RequestBringIntoViewEventHandler(setComboBindingAndHanldeUnsetValue); } } } } private void setComboBindingAndHanldeUnsetValue(object sender, RequestBringIntoViewEventArgs e) { ComboBox combo = sender as ComboBox; DataGridComboBoxColumn column = AssignedDataGridColumn as DataGridComboBoxColumn; if (column.ItemsSource == null) { if (combo.ItemsSource != null) { IList list = combo.ItemsSource.Cast<object>().ToList(); if (list.Count > 0 && list[0] != DependencyProperty.UnsetValue) { combo.RequestBringIntoView -= new RequestBringIntoViewEventHandler(setComboBindingAndHanldeUnsetValue); list.Insert(0, DependencyProperty.UnsetValue); combo.DisplayMemberPath = column.DisplayMemberPath; combo.SelectedValuePath = column.SelectedValuePath; combo.ItemsSource = list; } } } else { combo.RequestBringIntoView -= new RequestBringIntoViewEventHandler(setComboBindingAndHanldeUnsetValue); IList comboList = null; IList columnList = null; if (combo.ItemsSource != null) { comboList = combo.ItemsSource.Cast<object>().ToList(); } columnList = column.ItemsSource.Cast<object>().ToList(); if (comboList == null || (columnList.Count > 0 && columnList.Count + 1 != comboList.Count)) { columnList = column.ItemsSource.Cast<object>().ToList(); columnList.Insert(0, DependencyProperty.UnsetValue); combo.ItemsSource = columnList; } combo.RequestBringIntoView += new RequestBringIntoViewEventHandler(setComboBindingAndHanldeUnsetValue); } } private string getValuePropertyBindingPath(DataGridColumn column) { string path = String.Empty; if (column is DataGridBoundColumn) { DataGridBoundColumn bc = column as DataGridBoundColumn; path = (bc.Binding as Binding).Path.Path; } else if (column is DataGridTemplateColumn) { DataGridTemplateColumn tc = column as DataGridTemplateColumn; object templateContent = tc.CellTemplate.LoadContent(); if (templateContent != null && templateContent is TextBlock) { TextBlock block = templateContent as TextBlock; BindingExpression binding = block.GetBindingExpression(TextBlock.TextProperty); path = binding.ParentBinding.Path.Path; } } else if (column is DataGridComboBoxColumn) { DataGridComboBoxColumn comboColumn = column as DataGridComboBoxColumn; path = null; Binding binding = ((comboColumn.SelectedValueBinding) as Binding); if (binding == null) { binding = ((comboColumn.SelectedItemBinding) as Binding); } if (binding == null) { binding = comboColumn.SelectedValueBinding as Binding; } if (binding != null) { path = binding.Path.Path; } if (comboColumn.SelectedItemBinding != null && comboColumn.SelectedValueBinding == null) { if (path != null && path.Trim().Length > 0) { if (DataGridComboBoxExtensions.GetIsTextFilter(comboColumn)) { path += "." + comboColumn.DisplayMemberPath; } else { path += "." + comboColumn.SelectedValuePath; } } } } return path; } private Type getValuePropertyType(string path, Type elementType) { Type type = typeof(object); if (elementType != null) { string[] properties = path.Split(".".ToCharArray()[0]); PropertyInfo pi = null; if (properties.Length == 1) { pi = elementType.GetProperty(path); } else { pi = elementType.GetProperty(properties[0]); for (int i = 1; i < properties.Length; i++) { if (pi != null) { pi = pi.PropertyType.GetProperty(properties[i]); } } } if (pi != null) { type = pi.PropertyType; } } return type; } private Type getItemSourceElementType(out bool typeInitialized) { typeInitialized = false; Type elementType = null; IList l = (DataGridItemsSource as IList); if (l != null && l.Count > 0) { object obj = l[0]; if (obj != null) { elementType = l[0].GetType(); typeInitialized = true; } else { elementType = typeof(object); } } if (l == null) { ListCollectionView lw = (DataGridItemsSource as ListCollectionView); if (lw != null && lw.Count > 0) { object obj = lw.CurrentItem; if (obj != null) { elementType = lw.CurrentItem.GetType(); typeInitialized = true; } else { elementType = typeof(object); } } } return elementType; } private FilterType getFilterType( Type valuePropertyType, bool isAssignedDataGridColumnComboDataGridColumn, bool isBetweenType) { FilterType filterType; if (isAssignedDataGridColumnComboDataGridColumn) { filterType = FilterType.List; } else if (valuePropertyType == typeof(Boolean) || valuePropertyType == typeof(Nullable<Boolean>)) { filterType = FilterType.Boolean; } else if (valuePropertyType == typeof(SByte) || valuePropertyType == typeof(Nullable<SByte>)) { filterType = FilterType.Numeric; } else if (valuePropertyType == typeof(Byte) || valuePropertyType == typeof(Nullable<Byte>)) { filterType = FilterType.Numeric; } else if (valuePropertyType == typeof(Int16) || valuePropertyType == typeof(Nullable<Int16>)) { filterType = FilterType.Numeric; } else if (valuePropertyType == typeof(UInt16) || valuePropertyType == typeof(Nullable<UInt16>)) { filterType = FilterType.Numeric; } else if (valuePropertyType == typeof(Int32) || valuePropertyType == typeof(Nullable<Int32>)) { filterType = FilterType.Numeric; } else if (valuePropertyType == typeof(UInt32) || valuePropertyType == typeof(Nullable<UInt32>)) { filterType = FilterType.Numeric; } else if (valuePropertyType == typeof(Int64) || valuePropertyType == typeof(Nullable<Int64>)) { filterType = FilterType.Numeric; } else if (valuePropertyType == typeof(Single) || valuePropertyType == typeof(Nullable<Single>)) { filterType = FilterType.Numeric; } else if (valuePropertyType == typeof(Int64) || valuePropertyType == typeof(Nullable<Int64>)) { filterType = FilterType.Numeric; } else if (valuePropertyType == typeof(Decimal) || valuePropertyType == typeof(Nullable<Decimal>)) { filterType = FilterType.Numeric; } else if (valuePropertyType == typeof(float) || valuePropertyType == typeof(Nullable<float>)) { filterType = FilterType.Numeric; } else if (valuePropertyType == typeof(Double) || valuePropertyType == typeof(Nullable<Double>)) { filterType = FilterType.Numeric; } else if (valuePropertyType == typeof(Int64) || valuePropertyType == typeof(Nullable<Int64>)) { filterType = FilterType.Numeric; } else if (valuePropertyType == typeof(DateTime) || valuePropertyType == typeof(Nullable<DateTime>)) { filterType = FilterType.DateTime; } else { filterType = FilterType.Text; } if (filterType == FilterType.Numeric && isBetweenType) { filterType = FilterType.NumericBetween; } else if (filterType == FilterType.DateTime && isBetweenType) { filterType = FilterType.DateTimeBetween; } return filterType; } private bool isComboDataGridColumn() { return AssignedDataGridColumn is DataGridComboBoxColumn; } private bool isBetweenType() { return DataGridColumnExtensions.GetIsBetweenFilterControl(AssignedDataGridColumn); } private void hookUpCommands() { if (DataGridExtensions.GetClearFilterCommand(DataGrid) == null) { DataGridExtensions.SetClearFilterCommand( DataGrid, new DataGridFilterCommand(clearQuery)); } } #endregion #region Querying void filterCurrentData_FilterChangedEvent(object sender, EventArgs e) { if (DataGrid != null) { QueryController query = QueryControllerFactory.GetQueryController( DataGrid, FilterCurrentData, DataGridItemsSource); addFilterStateHandlers(query); query.DoQuery(); IsFirstFilterControl = query.IsCurentControlFirstControl; } } private void clearQuery(object parameter) { if (DataGrid != null) { QueryController query = QueryControllerFactory.GetQueryController( DataGrid, FilterCurrentData, DataGridItemsSource); query.ClearFilter(); } } private void addFilterStateHandlers(QueryController query) { query.FilteringStarted -= new EventHandler<EventArgs>(query_FilteringStarted); query.FilteringFinished -= new EventHandler<EventArgs>(query_FilteringFinished); query.FilteringStarted += new EventHandler<EventArgs>(query_FilteringStarted); query.FilteringFinished += new EventHandler<EventArgs>(query_FilteringFinished); } void query_FilteringFinished(object sender, EventArgs e) { if (FilterCurrentData.Equals((sender as QueryController).ColumnFilterData)) { this.IsFilteringInProgress = false; } } void query_FilteringStarted(object sender, EventArgs e) { if (FilterCurrentData.Equals((sender as QueryController).ColumnFilterData)) { this.IsFilteringInProgress = true; } } #endregion } }
zzgaminginc-pointofssale
Lib/DataGridFilterLibrary/DataGridColumnFilter.cs
C#
gpl3
26,229
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DataGridFilterLibrary")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DataGridFilterLibrary")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzgaminginc-pointofssale
Lib/DataGridFilterLibrary/Properties/AssemblyInfo.cs
C#
gpl3
2,288
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Input; namespace DataGridFilterLibrary { public class DataGridFilterCommand : ICommand { private readonly Action<object> action; public DataGridFilterCommand(Action<object> action) { this.action = action; } public void Execute(object parameter) { if (action != null) action(parameter); } public bool CanExecute(object parameter) { return true; } public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } } }
zzgaminginc-pointofssale
Lib/DataGridFilterLibrary/DataGridFilterCommand.cs
C#
gpl3
821
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; namespace DataGridFilterLibrary { public class DataGridComboBoxExtensions { public static DependencyProperty IsTextFilterProperty = DependencyProperty.RegisterAttached("IsTextFilter", typeof(bool), typeof(DataGridComboBoxColumn)); public static bool GetIsTextFilter(DependencyObject target) { return (bool)target.GetValue(IsTextFilterProperty); } public static void SetIsTextFilter(DependencyObject target, bool value) { target.SetValue(IsTextFilterProperty, value); } /// <summary> /// if true ComboBox.IsEditable is true and ComboBox.IsReadOnly is false /// otherwise /// ComboBox.IsEditable is false and ComboBox.IsReadOnly is true /// </summary> public static DependencyProperty UserCanEnterTextProperty = DependencyProperty.RegisterAttached("UserCanEnterText", typeof(bool), typeof(DataGridComboBoxColumn)); public static bool GetUserCanEnterText(DependencyObject target) { return (bool)target.GetValue(UserCanEnterTextProperty); } public static void SetUserCanEnterText(DependencyObject target, bool value) { target.SetValue(UserCanEnterTextProperty, value); } } }
zzgaminginc-pointofssale
Lib/DataGridFilterLibrary/DataGridComboBoxExtensions.cs
C#
gpl3
1,550
using System; using System.Collections.Generic; using System.Linq; using System.Text; using DataGridFilterLibrary.Support; namespace DataGridFilterLibrary.Querying { public class QueryCreator { private List<object> Parameters { get; set; } private readonly Dictionary<string, FilterData> filtersForColumns; private ParameterCounter paramCounter; public QueryCreator( Dictionary<string, FilterData> filtersForColumns) { this.filtersForColumns = filtersForColumns; paramCounter = new ParameterCounter(0); Parameters = new List<object>(); } public void CreateFilter(ref Query query) { StringBuilder filter = new StringBuilder(); foreach (KeyValuePair<string, FilterData> kvp in filtersForColumns) { StringBuilder partialFilter = createSingleFilter(kvp.Value); if (filter.Length > 0 && partialFilter.Length > 0) filter.Append(" AND "); if (partialFilter.Length > 0) { string valuePropertyBindingPath = String.Empty; string[] paths = kvp.Value.ValuePropertyBindingPath.Split(new Char[] { '.' }); foreach (string p in paths) { if (valuePropertyBindingPath != String.Empty) { valuePropertyBindingPath += "."; } valuePropertyBindingPath += p; filter.Append(valuePropertyBindingPath + " != null AND ");//eliminate: Nullable object must have a value and object fererence not set to an object } } filter.Append(partialFilter); } //init query query.FilterString = filter.ToString(); query.QueryParameters = Parameters; } private StringBuilder createSingleFilter(FilterData filterData) { StringBuilder filter = new StringBuilder(); if ( (filterData.Type == FilterType.NumericBetween || filterData.Type == FilterType.DateTimeBetween) && (filterData.QueryString != String.Empty || filterData.QueryStringTo != String.Empty) ) { if (filterData.QueryString != String.Empty) { createFilterExpression( filterData, filterData.QueryString, filter, getOperatorString(FilterOperator.GreaterThanOrEqual)); } if (filterData.QueryStringTo != String.Empty) { if (filter.Length > 0) filter.Append(" AND "); createFilterExpression( filterData, filterData.QueryStringTo, filter, getOperatorString(FilterOperator.LessThanOrEqual)); } } else if (filterData.QueryString != String.Empty && filterData.Operator != FilterOperator.Undefined) { if (filterData.Type == FilterType.Text) { createStringFilterExpression(filterData, filter); } else { createFilterExpression( filterData, filterData.QueryString, filter, getOperatorString(filterData.Operator)); } } return filter; } private void createFilterExpression( FilterData filterData, string queryString, StringBuilder filter, string operatorString) { filter.Append(filterData.ValuePropertyBindingPath); object parameterValue = null; if (trySetParameterValue(out parameterValue, queryString, filterData.ValuePropertyType)) { Parameters.Add(parameterValue); paramCounter.Increment(); filter.Append(" " + operatorString + " @" + paramCounter.ParameterNumber); } else { filter = new StringBuilder();//do not use filter } } private bool trySetParameterValue( out object parameterValue, string stringValue, Type type) { parameterValue = null; bool valueIsSet; try { if (type == typeof(Nullable<DateTime>) || type == typeof(DateTime)) { parameterValue = DateTime.Parse(stringValue); } else if (type == typeof(Enum) || type.BaseType == typeof(Enum)) { Parameters.Add(Enum.Parse(type, stringValue, true)); } else if (type == typeof(Boolean) || type.BaseType == typeof(Boolean)) { parameterValue = Convert.ChangeType(stringValue, typeof(Boolean)); } else if (type == typeof(Decimal) || type.BaseType == typeof(Decimal)) { parameterValue = Convert.ChangeType(stringValue, typeof(Decimal)); } else if (type == typeof(Single) || type.BaseType == typeof(Single)) { parameterValue = Convert.ChangeType(stringValue, typeof(Single)); } else if (type == typeof(int) || type.BaseType == typeof(int)) { parameterValue = Convert.ChangeType(stringValue, typeof(int)); } //new begin else if (type == typeof(String)) { parameterValue = stringValue; } //new end else { parameterValue = Convert.ChangeType(stringValue, typeof(Double));//TODO use "real" number type } valueIsSet = true; } catch (Exception) { valueIsSet = false; } return valueIsSet; } private void createStringFilterExpression( FilterData filterData, StringBuilder filter) { StringFilterExpressionCreator creator = new StringFilterExpressionCreator( paramCounter, filterData, Parameters); string filterExpression = creator.Create(); filter.Append(filterExpression); } private string getOperatorString(FilterOperator filterOperator) { string op; switch (filterOperator) { case FilterOperator.Undefined: op = String.Empty; break; case FilterOperator.LessThan: op = "<"; break; case FilterOperator.LessThanOrEqual: op = "<="; break; case FilterOperator.GreaterThan: op = ">"; break; case FilterOperator.GreaterThanOrEqual: op = ">="; break; case FilterOperator.Equals: op = "="; break; case FilterOperator.Like: op = String.Empty; break; default: op = String.Empty; break; } return op; } } }
zzgaminginc-pointofssale
Lib/DataGridFilterLibrary/Querying/QueryCreator.cs
C#
gpl3
8,107
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Dynamic; using System.Text; using DataGridFilterLibrary.Support; using System.Collections; using System.Windows.Data; using System.ComponentModel; using System.Threading; using System.Diagnostics; using System.Windows.Threading; namespace DataGridFilterLibrary.Querying { public class QueryController { public FilterData ColumnFilterData { get; set; } public IEnumerable ItemsSource { get; set; } private readonly Dictionary<string, FilterData> filtersForColumns; Query query; public Dispatcher CallingThreadDispatcher { get; set; } public bool UseBackgroundWorker { get; set; } private readonly object lockObject; public QueryController() { lockObject = new object(); filtersForColumns = new Dictionary<string, FilterData>(); query = new Query(); } public void DoQuery() { DoQuery(false); } public void DoQuery(bool force) { ColumnFilterData.IsSearchPerformed = false; if (!filtersForColumns.ContainsKey(ColumnFilterData.ValuePropertyBindingPath)) { filtersForColumns.Add(ColumnFilterData.ValuePropertyBindingPath, ColumnFilterData); } else { filtersForColumns[ColumnFilterData.ValuePropertyBindingPath] = ColumnFilterData; } if (isRefresh) { if (filtersForColumns.ElementAt(filtersForColumns.Count - 1).Value.ValuePropertyBindingPath == ColumnFilterData.ValuePropertyBindingPath) { runFiltering(force); } } else if (filteringNeeded) { runFiltering(force); } ColumnFilterData.IsSearchPerformed = true; ColumnFilterData.IsRefresh = false; } public bool IsCurentControlFirstControl { get { return filtersForColumns.Count > 0 ? filtersForColumns.ElementAt(0).Value.ValuePropertyBindingPath == ColumnFilterData.ValuePropertyBindingPath : false; } } public void ClearFilter() { int count = filtersForColumns.Count; for(int i = 0; i < count; i++) { FilterData data = filtersForColumns.ElementAt(i).Value; data.ClearData(); } DoQuery(); } #region Internal private bool isRefresh { get { return (from f in filtersForColumns where f.Value.IsRefresh == true select f).Count() > 0; } } private bool filteringNeeded { get { return (from f in filtersForColumns where f.Value.IsSearchPerformed == false select f).Count() == 1; } } private void runFiltering(bool force) { bool filterChanged; createFilterExpressionsAndFilteredCollection(out filterChanged, force); if (filterChanged || force) { OnFilteringStarted(this, EventArgs.Empty); applayFilter(); } } private void createFilterExpressionsAndFilteredCollection(out bool filterChanged, bool force) { QueryCreator queryCreator = new QueryCreator(filtersForColumns); queryCreator.CreateFilter(ref query); filterChanged = (query.IsQueryChanged || (query.FilterString != String.Empty && isRefresh)); if ((force && query.FilterString != String.Empty) || (query.FilterString != String.Empty && filterChanged)) { IEnumerable collection = ItemsSource as IEnumerable; if (ItemsSource is ICollectionView) { collection = (ItemsSource as ICollectionView).SourceCollection as IEnumerable; } var observable = collection as System.Collections.Specialized.INotifyCollectionChanged; if (observable != null) { observable.CollectionChanged -= observable_CollectionChanged; observable.CollectionChanged += observable_CollectionChanged; } #region Debug #if DEBUG System.Diagnostics.Debug.WriteLine("QUERY STATEMENT: " + query.FilterString); string debugParameters = String.Empty; query.QueryParameters.ForEach(p => { if (debugParameters.Length > 0) debugParameters += ","; debugParameters += p.ToString(); }); System.Diagnostics.Debug.WriteLine("QUERY PARAMETRS: " + debugParameters); #endif #endregion if (query.FilterString != String.Empty) { var result = collection.AsQueryable().Where(query.FilterString, query.QueryParameters.ToArray<object>()); filteredCollection = result.Cast<object>().ToList(); } } else { filteredCollection = null; } query.StoreLastUsedValues(); } private void observable_CollectionChanged( object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { DoQuery(true); } #region Internal Filtering private IList filteredCollection; HashSet<object> filteredCollectionHashSet; void applayFilter() { ICollectionView view = CollectionViewSource.GetDefaultView(ItemsSource); if (filteredCollection != null) { executeFilterAction( new Action(() => { filteredCollectionHashSet = initLookupDictionary(filteredCollection); view.Filter = new Predicate<object>(itemPassesFilter); OnFilteringFinished(this, EventArgs.Empty); }) ); } else { executeFilterAction( new Action(() => { if (view.Filter != null) { view.Filter = null; } OnFilteringFinished(this, EventArgs.Empty); }) ); } } private void executeFilterAction(Action action) { if (UseBackgroundWorker) { BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += delegate(object sender, DoWorkEventArgs e) { lock (lockObject) { executeActionUsingDispatcher(action); } }; worker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e) { if (e.Error != null) { OnFilteringError(this, new FilteringEventArgs(e.Error)); } }; worker.RunWorkerAsync(); } else { try { executeActionUsingDispatcher(action); } catch (Exception e) { OnFilteringError(this, new FilteringEventArgs(e)); } } } private void executeActionUsingDispatcher(Action action) { if (this.CallingThreadDispatcher != null && !this.CallingThreadDispatcher.CheckAccess()) { this.CallingThreadDispatcher.Invoke ( new Action(() => { invoke(action); }) ); } else { invoke(action); } } private static void invoke(Action action) { System.Diagnostics.Trace.WriteLine("------------------ START APPLAY FILTER ------------------------------"); Stopwatch sw = Stopwatch.StartNew(); action.Invoke(); sw.Stop(); System.Diagnostics.Trace.WriteLine("TIME: " + sw.ElapsedMilliseconds); System.Diagnostics.Trace.WriteLine("------------------ STOP APPLAY FILTER ------------------------------"); } private bool itemPassesFilter(object item) { return filteredCollectionHashSet.Contains(item); } #region Helpers private HashSet<object> initLookupDictionary(IList collection) { HashSet<object> dictionary; if (collection != null) { dictionary = new HashSet<object>(collection.Cast<object>()/*.ToList()*/); } else { dictionary = new HashSet<object>(); } return dictionary; } #endregion #endregion #endregion #region Progress Notification public event EventHandler<EventArgs> FilteringStarted; public event EventHandler<EventArgs> FilteringFinished; public event EventHandler<FilteringEventArgs> FilteringError; private void OnFilteringStarted(object sender, EventArgs e) { EventHandler<EventArgs> localEvent = FilteringStarted; if (localEvent != null) localEvent(sender, e); } private void OnFilteringFinished(object sender, EventArgs e) { EventHandler<EventArgs> localEvent = FilteringFinished; if (localEvent != null) localEvent(sender, e); } private void OnFilteringError(object sender, FilteringEventArgs e) { EventHandler<FilteringEventArgs> localEvent = FilteringError; if (localEvent != null) localEvent(sender, e); } #endregion } }
zzgaminginc-pointofssale
Lib/DataGridFilterLibrary/Querying/QueryController.cs
C#
gpl3
10,824
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DataGridFilterLibrary.Querying { public class Query { public Query() { lastFilterString = String.Empty; lastQueryParameters = new List<object>(); } public string FilterString { get; set; } public List<object> QueryParameters { get; set; } private string lastFilterString { get; set; } private List<object> lastQueryParameters { get; set; } public bool IsQueryChanged { get { bool queryChanged = false; if (FilterString != lastFilterString) { queryChanged = true; } else { if (QueryParameters.Count != lastQueryParameters.Count) { queryChanged = true; } else { for (int i = 0; i < QueryParameters.Count; i++) { if (!QueryParameters[i].Equals(lastQueryParameters[i])) { queryChanged = true; break; } } } } return queryChanged; } } public void StoreLastUsedValues() { lastFilterString = FilterString; lastQueryParameters = QueryParameters; } } }
zzgaminginc-pointofssale
Lib/DataGridFilterLibrary/Querying/Query.cs
C#
gpl3
1,742
using System; using System.Collections.Generic; using System.Linq; using System.Text; using DataGridFilterLibrary.Support; namespace DataGridFilterLibrary.Querying { internal class StringFilterExpressionCreator { const string WildcardAnyString = "%"; private enum StringExpressionFunction { Undefined = 0, StartsWith = 1, IndexOf = 2, EndsWith = 3 } FilterData filterData; List<object> paramseters; ParameterCounter paramCounter; internal int ParametarsCrated { get { return paramseters.Count; } } internal StringFilterExpressionCreator( ParameterCounter paramCounter, FilterData filterData, List<object> paramseters) { this.paramCounter = paramCounter; this.filterData = filterData; this.paramseters = paramseters; } internal string Create() { StringBuilder filter = new StringBuilder(); List<string> filterList = parse(this.filterData.QueryString); for (int i = 0; i < filterList.Count; i++) { if (i > 0) filter.Append(" and "); filter.Append(filterList[i]); } return filter.ToString(); } private List<string> parse(string filterString) { string token = null; int i = 0; bool expressionCompleted = false; List<string> filter = new List<string>(); string expressionValue = String.Empty; StringExpressionFunction function = StringExpressionFunction.Undefined; do { token = i < filterString.Length ? filterString[i].ToString() : null; if (token == WildcardAnyString || token == null) { if (expressionValue.StartsWith(WildcardAnyString) && token != null) { function = StringExpressionFunction.IndexOf; expressionCompleted = true; } else if (expressionValue.StartsWith(WildcardAnyString) && token == null) { function = StringExpressionFunction.EndsWith; expressionCompleted = false; } else { function = StringExpressionFunction.StartsWith; if (filterString.Length - 1 > i) expressionCompleted = true; } } if (token == null) { expressionCompleted = true; } expressionValue += token; if (expressionCompleted && function != StringExpressionFunction.Undefined && expressionValue != String.Empty) { string expressionValueCopy = String.Copy(expressionValue); expressionValueCopy = expressionValueCopy.Replace(WildcardAnyString, String.Empty); if (expressionValueCopy != String.Empty) { filter.Add(createFunction(function, expressionValueCopy)); } function = StringExpressionFunction.Undefined; expressionValue = expressionValue.EndsWith(WildcardAnyString) ? WildcardAnyString : String.Empty; expressionCompleted = false; } i++; } while (token != null); return filter; } private string createFunction( StringExpressionFunction function, string value) { StringBuilder filter = new StringBuilder(); paramseters.Add(value); filter.Append(filterData.ValuePropertyBindingPath); if (filterData.ValuePropertyType.IsGenericType && filterData.ValuePropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) { filter.Append(".Value"); } paramCounter.Increment(); paramCounter.Increment(); filter.Append(".ToString()." + function.ToString() + "(@" + (paramCounter.ParameterNumber - 1) + ", @" + (paramCounter.ParameterNumber) + ")"); if (function == StringExpressionFunction.IndexOf) { filter.Append(" != -1 "); } paramseters.Add(filterData.IsCaseSensitiveSearch ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase); return filter.ToString(); } } }
zzgaminginc-pointofssale
Lib/DataGridFilterLibrary/Querying/StringFilterExpressionCreator.cs
C#
gpl3
4,957
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DataGridFilterLibrary.Querying { public class ParameterCounter { public int ParameterNumber { get { return count - 1; } } private int count { get; set; } public void Increment() { count++; } public void Decrement() { count--; } public ParameterCounter() { } public ParameterCounter(int count) { this.count = count; } public override string ToString() { return ParameterNumber.ToString(); } } }
zzgaminginc-pointofssale
Lib/DataGridFilterLibrary/Querying/ParameterCounter.cs
C#
gpl3
734
using System; using System.Collections.Generic; using System.Linq; using System.Text; using DataGridFilterLibrary.Support; using System.Collections; namespace DataGridFilterLibrary.Querying { public class QueryControllerFactory { public static QueryController GetQueryController( System.Windows.Controls.DataGrid dataGrid, FilterData filterData, IEnumerable itemsSource) { QueryController query; query = DataGridExtensions.GetDataGridFilterQueryController(dataGrid); if (query == null) { //clear the filter if exisits begin System.ComponentModel.ICollectionView view = System.Windows.Data.CollectionViewSource.GetDefaultView(dataGrid.ItemsSource); if (view != null) view.Filter = null; //clear the filter if exisits end query = new QueryController(); DataGridExtensions.SetDataGridFilterQueryController(dataGrid, query); } query.ColumnFilterData = filterData; query.ItemsSource = itemsSource; query.CallingThreadDispatcher = dataGrid.Dispatcher; query.UseBackgroundWorker = DataGridExtensions.GetUseBackgroundWorkerForFiltering(dataGrid); return query; } } }
zzgaminginc-pointofssale
Lib/DataGridFilterLibrary/Querying/QueryControllerFactory.cs
C#
gpl3
1,441
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DataGridFilterLibrary.Querying { public class FilteringEventArgs : EventArgs { public Exception Error { get; private set; } public FilteringEventArgs(Exception ex) { Error = ex; } } }
zzgaminginc-pointofssale
Lib/DataGridFilterLibrary/Querying/FilteringEventArgs.cs
C#
gpl3
358
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 DataGridFilterLibrary { /// <summary> /// Follow steps 1a or 1b and then 2 to use this custom control in a XAML file. /// /// Step 1a) Using this custom control in a XAML file that exists in the current project. /// Add this XmlNamespace attribute to the root element of the markup file where it is /// to be used: /// /// xmlns:MyNamespace="clr-namespace:DataGridFilterLibrary" /// /// /// Step 1b) Using this custom control in a XAML file that exists in a different project. /// Add this XmlNamespace attribute to the root element of the markup file where it is /// to be used: /// /// xmlns:MyNamespace="clr-namespace:DataGridFilterLibrary;assembly=DataGridFilterLibrary" /// /// You will also need to add a project reference from the project where the XAML file lives /// to this project and Rebuild to avoid compilation errors: /// /// Right click on the target project in the Solution Explorer and /// "Add Reference"->"Projects"->[Select this project] /// /// /// Step 2) /// Go ahead and use your control in the XAML file. /// /// <MyNamespace:CustomControl1/> /// /// </summary> public class DataGridHeaderFilterControl : Control { static DataGridHeaderFilterControl() { DefaultStyleKeyProperty.OverrideMetadata(typeof(DataGridHeaderFilterControl), new FrameworkPropertyMetadata(typeof(DataGridHeaderFilterControl))); } } }
zzgaminginc-pointofssale
Lib/DataGridFilterLibrary/DataGridHeaderFilterControl.cs
C#
gpl3
1,938
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; namespace DataGridFilterLibrary { public class DataGridColumnExtensions { public static DependencyProperty IsCaseSensitiveSearchProperty = DependencyProperty.RegisterAttached("IsCaseSensitiveSearch", typeof(bool), typeof(DataGridColumn)); public static bool GetIsCaseSensitiveSearch(DependencyObject target) { return (bool)target.GetValue(IsCaseSensitiveSearchProperty); } public static void SetIsCaseSensitiveSearch(DependencyObject target, bool value) { target.SetValue(IsCaseSensitiveSearchProperty, value); } public static DependencyProperty IsBetweenFilterControlProperty = DependencyProperty.RegisterAttached("IsBetweenFilterControl", typeof(bool), typeof(DataGridColumn)); public static bool GetIsBetweenFilterControl(DependencyObject target) { return (bool)target.GetValue(IsBetweenFilterControlProperty); } public static void SetIsBetweenFilterControl(DependencyObject target, bool value) { target.SetValue(IsBetweenFilterControlProperty, value); } public static DependencyProperty DoNotGenerateFilterControlProperty = DependencyProperty.RegisterAttached("DoNotGenerateFilterControl", typeof(bool), typeof(DataGridColumn), new PropertyMetadata(false)); public static bool GetDoNotGenerateFilterControl(DependencyObject target) { return (bool)target.GetValue(DoNotGenerateFilterControlProperty); } public static void SetDoNotGenerateFilterControl(DependencyObject target, bool value) { target.SetValue(DoNotGenerateFilterControlProperty, value); } } }
zzgaminginc-pointofssale
Lib/DataGridFilterLibrary/DataGridColumnExtensions.cs
C#
gpl3
2,001
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text.RegularExpressions; using Samba.Domain.Models.Inventory; using Samba.Domain.Models.Menus; using Samba.Domain.Models.Tables; using Samba.Domain.Models.Tickets; using Samba.Persistance.Data; namespace Samba.Services { public class DataAccessService { public IEnumerable<Table> GetCurrentTables(int tableScreenId, int currentPageNo) { AppServices.MainDataContext.UpdateTables(tableScreenId, currentPageNo); var selectedTableScreen = AppServices.MainDataContext.SelectedTableScreen; if (selectedTableScreen != null) { if (selectedTableScreen.PageCount > 1) { return selectedTableScreen.Tables .OrderBy(x => x.Order) .Skip(selectedTableScreen.ItemCountPerPage * currentPageNo) .Take(selectedTableScreen.ItemCountPerPage); } return selectedTableScreen.Tables; } return new List<Table>(); } public IEnumerable<ScreenMenuItem> GetMenuItems(ScreenMenuCategory category, int currentPageNo, string tag) { var items = category.ScreenMenuItems .Where(x => x.Tag == tag || (string.IsNullOrEmpty(tag) && string.IsNullOrEmpty(x.Tag))); if (category.PageCount > 1) { items = items .Skip(category.ItemCountPerPage * currentPageNo) .Take(category.ItemCountPerPage); } return items.OrderBy(x => x.Order); } public IEnumerable<string> GetSubCategories(ScreenMenuCategory category, string parentTag) { return category.ScreenMenuItems.Where(x => !string.IsNullOrEmpty(x.Tag)) .Select(x => x.Tag) .Distinct() .Where(x => string.IsNullOrEmpty(parentTag) || (x.StartsWith(parentTag) && x != parentTag)) .Select(x => Regex.Replace(x, "^" + parentTag + ",", "")) .Where(x => !x.Contains(",")) .Select(x => !string.IsNullOrEmpty(parentTag) ? parentTag + "," + x : x); } public ScreenMenu GetScreenMenu(int screenMenuId) { return Dao.SingleWithCache<ScreenMenu>(x => x.Id == screenMenuId, x => x.Categories, x => x.Categories.Select(z => z.ScreenMenuItems)); } public MenuItem GetMenuItem(int menuItemId) { return GetMenuItem(x => x.Id == menuItemId); } public MenuItem GetMenuItem(string barcode) { return GetMenuItem(x => x.Barcode == barcode); } public MenuItem GetMenuItemByName(string menuItemName) { return GetMenuItem(x => x.Name == menuItemName); } public MenuItem GetMenuItem(Expression<Func<MenuItem, bool>> expression) { return Dao.SingleWithCache(expression, x => x.VatTemplate, x => x.PropertyGroups.Select(z => z.Properties), x => x.Portions.Select(y => y.Prices)); } public IEnumerable<string> GetInventoryItemNames() { return Dao.Select<InventoryItem, string>(x => x.Name, x => !string.IsNullOrEmpty(x.Name)); } public Table GetTable(string tableName) { return Dao.Single<Table>(x => x.Name == tableName); } public MenuItemPropertyGroup GetUnselectedItem(TicketItem ticketItem) { var mi = GetMenuItem(ticketItem.MenuItemId); return mi.PropertyGroups.FirstOrDefault(x => x.ForceValue && ticketItem.Properties.Count(y => y.PropertyGroupId == x.Id) == 0); } } }
zzgaminginc-pointofssale
Samba.Services/DataAccessService.cs
C#
gpl3
3,980
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Samba.Domain; using Samba.Domain.Models.Settings; using Samba.Infrastructure.Data; using Samba.Persistance.Data; namespace Samba.Services { public class SettingService { private readonly IDictionary<string, ProgramSetting> _settingCache = new Dictionary<string, ProgramSetting>(); private readonly IDictionary<string, SettingGetter> _customSettingCache = new Dictionary<string, SettingGetter>(); private IWorkspace _workspace; public SettingService() { _workspace = WorkspaceFactory.Create(); if (PhoneNumberInputMask == null) { PhoneNumberInputMask = "(###) ### ####"; SaveChanges(); } else if (PhoneNumberInputMask == "") { PhoneNumberInputMask = "##########"; SaveChanges(); } } public string PhoneNumberInputMask { get { return GetPhoneNumberInputMask().StringValue; } set { GetPhoneNumberInputMask().StringValue = value; } } public string WeightBarcodePrefix { get { return GetWeightBarcodePrefix().StringValue; } set { GetWeightBarcodePrefix().StringValue = value; } } public int WeightBarcodeItemLength { get { return GetWeightBarcodeItemLength().IntegerValue; } set { GetWeightBarcodeItemLength().IntegerValue = value; } } public string WeightBarcodeItemFormat { get { return GetWeightBarcodeItemFormat().StringValue; } set { GetWeightBarcodeItemFormat().StringValue = value; } } public int WeightBarcodeQuantityLength { get { return GetWeightBarcodeQuantityLength().IntegerValue; } set { GetWeightBarcodeQuantityLength().IntegerValue = value; } } public decimal AutoRoundDiscount { get { return GetAutoRoundDiscount().DecimalValue; } set { GetAutoRoundDiscount().DecimalValue = value; } } private SettingGetter _weightBarcodePrefix; private SettingGetter GetWeightBarcodePrefix() { return _weightBarcodePrefix ?? (_weightBarcodePrefix = GetSetting("WeightBarcodePrefix")); } private SettingGetter _autoRoundDiscount; private SettingGetter GetAutoRoundDiscount() { return _autoRoundDiscount ?? (_autoRoundDiscount = GetSetting("AutoRoundDiscount")); } private SettingGetter _weightBarcodeQuantityLength; private SettingGetter GetWeightBarcodeQuantityLength() { return _weightBarcodeQuantityLength ?? (_weightBarcodeQuantityLength = GetSetting("WeightBarcodeQuantityLength")); } private SettingGetter _weightBarcodeItemLength; private SettingGetter GetWeightBarcodeItemLength() { return _weightBarcodeItemLength ?? (_weightBarcodeItemLength = GetSetting("WeightBarcodeItemLength")); } private SettingGetter _weightBarcodeItemFormat; public SettingGetter GetWeightBarcodeItemFormat() { return _weightBarcodeItemFormat ?? (_weightBarcodeItemFormat = GetSetting("WeightBarcodeItemFormat")); } private SettingGetter _phoneNumberInputMask; public SettingGetter GetPhoneNumberInputMask() { return _phoneNumberInputMask ?? (_phoneNumberInputMask = GetSetting("PhoneNumberInputMask")); } public SettingGetter ReadLocalSetting(string settingName) { if (!_customSettingCache.ContainsKey(settingName)) { var p = new ProgramSetting { Name = settingName }; var getter = new SettingGetter(p); _customSettingCache.Add(settingName, getter); } return _customSettingCache[settingName]; } public SettingGetter ReadGlobalSetting(string settingName) { return GetSetting(settingName); } public SettingGetter ReadSetting(string settingName) { if (_customSettingCache.ContainsKey(settingName)) return _customSettingCache[settingName]; if (_settingCache.ContainsKey(settingName)) return new SettingGetter(_settingCache[settingName]); var setting = Dao.Single<ProgramSetting>(x => x.Name == settingName); //_workspace.Single<ProgramSetting>(x => x.Name == settingName);) return setting != null ? new SettingGetter(setting) : SettingGetter.NullSetting; } public SettingGetter GetSetting(string valueName) { ProgramSetting setting; try { setting = _workspace.Single<ProgramSetting>(x => x.Name == valueName); } catch (Exception) { _workspace.Delete<ProgramSetting>(x => x.Name == valueName); _workspace.CommitChanges(); setting = null; } if (_settingCache.ContainsKey(valueName)) { if (setting == null) setting = _settingCache[valueName]; else _settingCache.Remove(valueName); } if (setting == null) { setting = new ProgramSetting { Name = valueName }; _settingCache.Add(valueName, setting); _workspace.Add(setting); _workspace.CommitChanges(); } return new SettingGetter(setting); } public void SaveChanges() { _workspace.CommitChanges(); _workspace = WorkspaceFactory.Create(); } public void ResetCache() { _workspace = WorkspaceFactory.Create(); _customSettingCache.Clear(); } } }
zzgaminginc-pointofssale
Samba.Services/SettingService.cs
C#
gpl3
6,240
//--------------------------------------------------------------------------- // // File: HtmlFromXamlConverter.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // Description: Prototype for Xaml - Html conversion // //--------------------------------------------------------------------------- using System; using System.Diagnostics; using System.Text; using System.IO; using System.Xml; namespace Samba.Services.HtmlConverter { /// <summary> /// HtmlToXamlConverter is a static class that takes an HTML string /// and converts it into XAML /// </summary> internal static class HtmlFromXamlConverter { // --------------------------------------------------------------------- // // Internal Methods // // --------------------------------------------------------------------- #region Internal Methods /// <summary> /// Main entry point for Xaml-to-Html converter. /// Converts a xaml string into html string. /// </summary> /// <param name="xamlString"> /// Xaml strinng to convert. /// </param> /// <returns> /// Html string produced from a source xaml. /// </returns> internal static string ConvertXamlToHtml(string xamlString) { XmlTextReader xamlReader; StringBuilder htmlStringBuilder; XmlTextWriter htmlWriter; xamlReader = new XmlTextReader(new StringReader(xamlString)); htmlStringBuilder = new StringBuilder(100); htmlWriter = new XmlTextWriter(new StringWriter(htmlStringBuilder)); if (!WriteFlowDocument(xamlReader, htmlWriter)) { return ""; } string htmlString = htmlStringBuilder.ToString(); return htmlString; } #endregion Internal Methods // --------------------------------------------------------------------- // // Private Methods // // --------------------------------------------------------------------- #region Private Methods /// <summary> /// Processes a root level element of XAML (normally it's FlowDocument element). /// </summary> /// <param name="xamlReader"> /// XmlTextReader for a source xaml. /// </param> /// <param name="htmlWriter"> /// XmlTextWriter producing resulting html /// </param> private static bool WriteFlowDocument(XmlTextReader xamlReader, XmlTextWriter htmlWriter) { if (!ReadNextToken(xamlReader)) { // Xaml content is empty - nothing to convert return false; } if (xamlReader.NodeType != XmlNodeType.Element || (xamlReader.Name != "FlowDocument" && xamlReader.Name != "Section")) { // Root FlowDocument elemet is missing return false; } // Create a buffer StringBuilder for collecting css properties for inline STYLE attributes // on every element level (it will be re-initialized on every level). StringBuilder inlineStyle = new StringBuilder(); htmlWriter.WriteStartElement("HTML"); htmlWriter.WriteStartElement("BODY"); WriteFormattingProperties(xamlReader, htmlWriter, inlineStyle); WriteElementContent(xamlReader, htmlWriter, inlineStyle); htmlWriter.WriteEndElement(); htmlWriter.WriteEndElement(); return true; } /// <summary> /// Reads attributes of the current xaml element and converts /// them into appropriate html attributes or css styles. /// </summary> /// <param name="xamlReader"> /// XmlTextReader which is expected to be at XmlNodeType.Element /// (opening element tag) position. /// The reader will remain at the same level after function complete. /// </param> /// <param name="htmlWriter"> /// XmlTextWriter for output html, which is expected to be in /// after WriteStartElement state. /// </param> /// <param name="inlineStyle"> /// String builder for collecting css properties for inline STYLE attribute. /// </param> private static void WriteFormattingProperties(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle) { Debug.Assert(xamlReader.NodeType == XmlNodeType.Element); // Clear string builder for the inline style inlineStyle.Remove(0, inlineStyle.Length); if (!xamlReader.HasAttributes) { return; } bool borderSet = false; while (xamlReader.MoveToNextAttribute()) { string css = null; switch (xamlReader.Name) { // Character fomatting properties // ------------------------------ case "Background": css = "background-color:" + ParseXamlColor(xamlReader.Value) + ";"; break; case "FontFamily": css = "font-family:" + xamlReader.Value + ";"; break; case "FontStyle": css = "font-style:" + xamlReader.Value.ToLower() + ";"; break; case "FontWeight": css = "font-weight:" + xamlReader.Value.ToLower() + ";"; break; case "FontStretch": break; case "FontSize": css = "font-size:" + xamlReader.Value + ";"; break; case "Foreground": css = "color:" + ParseXamlColor(xamlReader.Value) + ";"; break; case "TextDecorations": css = "text-decoration:underline;"; break; case "TextEffects": break; case "Emphasis": break; case "StandardLigatures": break; case "Variants": break; case "Capitals": break; case "Fraction": break; // Paragraph formatting properties // ------------------------------- case "Padding": css = "padding:" + ParseXamlThickness(xamlReader.Value) + ";"; break; case "Margin": css = "margin:" + ParseXamlThickness(xamlReader.Value) + ";"; break; case "BorderThickness": css = "border-width:" + ParseXamlThickness(xamlReader.Value) + ";"; borderSet = true; break; case "BorderBrush": css = "border-color:" + ParseXamlColor(xamlReader.Value) + ";"; borderSet = true; break; case "LineHeight": break; case "TextIndent": css = "text-indent:" + xamlReader.Value + ";"; break; case "TextAlignment": css = "text-align:" + xamlReader.Value + ";"; break; case "IsKeptTogether": break; case "IsKeptWithNext": break; case "ColumnBreakBefore": break; case "PageBreakBefore": break; case "FlowDirection": break; // Table attributes // ---------------- case "Width": css = "width:" + xamlReader.Value + ";"; break; case "ColumnSpan": htmlWriter.WriteAttributeString("COLSPAN", xamlReader.Value); break; case "RowSpan": htmlWriter.WriteAttributeString("ROWSPAN", xamlReader.Value); break; } if (css != null) { inlineStyle.Append(css); } } if (borderSet) { inlineStyle.Append("border-style:solid;mso-element:para-border-div;"); } // Return the xamlReader back to element level xamlReader.MoveToElement(); Debug.Assert(xamlReader.NodeType == XmlNodeType.Element); } private static string ParseXamlColor(string color) { if (color.StartsWith("#")) { // Remove transparancy value color = "#" + color.Substring(3); } return color; } private static string ParseXamlThickness(string thickness) { string[] values = thickness.Split(','); for (int i = 0; i < values.Length; i++) { double value; if (double.TryParse(values[i], out value)) { values[i] = Math.Ceiling(value).ToString(); } else { values[i] = "1"; } } string cssThickness; switch (values.Length) { case 1: cssThickness = thickness; break; case 2: cssThickness = values[1] + " " + values[0]; break; case 4: cssThickness = values[1] + " " + values[2] + " " + values[3] + " " + values[0]; break; default: cssThickness = values[0]; break; } return cssThickness; } /// <summary> /// Reads a content of current xaml element, converts it /// </summary> /// <param name="xamlReader"> /// XmlTextReader which is expected to be at XmlNodeType.Element /// (opening element tag) position. /// </param> /// <param name="htmlWriter"> /// May be null, in which case we are skipping the xaml element; /// witout producing any output to html. /// </param> /// <param name="inlineStyle"> /// StringBuilder used for collecting css properties for inline STYLE attribute. /// </param> private static void WriteElementContent(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle) { Debug.Assert(xamlReader.NodeType == XmlNodeType.Element); bool elementContentStarted = false; if (xamlReader.IsEmptyElement) { if (htmlWriter != null && !elementContentStarted && inlineStyle.Length > 0) { // Output STYLE attribute and clear inlineStyle buffer. htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString()); inlineStyle.Remove(0, inlineStyle.Length); } elementContentStarted = true; } else { while (ReadNextToken(xamlReader) && xamlReader.NodeType != XmlNodeType.EndElement) { switch (xamlReader.NodeType) { case XmlNodeType.Element: if (xamlReader.Name.Contains(".")) { AddComplexProperty(xamlReader, inlineStyle); } else { if (htmlWriter != null && !elementContentStarted && inlineStyle.Length > 0) { // Output STYLE attribute and clear inlineStyle buffer. htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString()); inlineStyle.Remove(0, inlineStyle.Length); } elementContentStarted = true; WriteElement(xamlReader, htmlWriter, inlineStyle); } Debug.Assert(xamlReader.NodeType == XmlNodeType.EndElement || xamlReader.NodeType == XmlNodeType.Element && xamlReader.IsEmptyElement); break; case XmlNodeType.Comment: if (htmlWriter != null) { if (!elementContentStarted && inlineStyle.Length > 0) { htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString()); } htmlWriter.WriteComment(xamlReader.Value); } elementContentStarted = true; break; case XmlNodeType.CDATA: case XmlNodeType.Text: case XmlNodeType.SignificantWhitespace: if (htmlWriter != null) { if (!elementContentStarted && inlineStyle.Length > 0) { htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString()); } htmlWriter.WriteString(xamlReader.Value); } elementContentStarted = true; break; } } Debug.Assert(xamlReader.NodeType == XmlNodeType.EndElement); } } /// <summary> /// Conberts an element notation of complex property into /// </summary> /// <param name="xamlReader"> /// On entry this XmlTextReader must be on Element start tag; /// on exit - on EndElement tag. /// </param> /// <param name="inlineStyle"> /// StringBuilder containing a value for STYLE attribute. /// </param> private static void AddComplexProperty(XmlTextReader xamlReader, StringBuilder inlineStyle) { Debug.Assert(xamlReader.NodeType == XmlNodeType.Element); if (inlineStyle != null && xamlReader.Name.EndsWith(".TextDecorations")) { inlineStyle.Append("text-decoration:underline;"); } // Skip the element representing the complex property WriteElementContent(xamlReader, /*htmlWriter:*/null, /*inlineStyle:*/null); } /// <summary> /// Converts a xaml element into an appropriate html element. /// </summary> /// <param name="xamlReader"> /// On entry this XmlTextReader must be on Element start tag; /// on exit - on EndElement tag. /// </param> /// <param name="htmlWriter"> /// May be null, in which case we are skipping xaml content /// without producing any html output /// </param> /// <param name="inlineStyle"> /// StringBuilder used for collecting css properties for inline STYLE attributes on every level. /// </param> private static void WriteElement(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle) { Debug.Assert(xamlReader.NodeType == XmlNodeType.Element); if (htmlWriter == null) { // Skipping mode; recurse into the xaml element without any output WriteElementContent(xamlReader, /*htmlWriter:*/null, null); } else { string htmlElementName = null; switch (xamlReader.Name) { case "Run": case "Span": htmlElementName = "SPAN"; break; case "InlineUIContainer": htmlElementName = "SPAN"; break; case "Bold": htmlElementName = "B"; break; case "Italic": htmlElementName = "I"; break; case "Paragraph": htmlElementName = "P"; break; case "BlockUIContainer": htmlElementName = "DIV"; break; case "Section": htmlElementName = "DIV"; break; case "Table": htmlElementName = "TABLE"; break; case "TableColumn": htmlElementName = "COL"; break; case "TableRowGroup": htmlElementName = "TBODY"; break; case "TableRow": htmlElementName = "TR"; break; case "TableCell": htmlElementName = "TD"; break; case "List": string marker = xamlReader.GetAttribute("MarkerStyle"); if (marker == null || marker == "None" || marker == "Disc" || marker == "Circle" || marker == "Square" || marker == "Box") { htmlElementName = "UL"; } else { htmlElementName = "OL"; } break; case "ListItem": htmlElementName = "LI"; break; default: htmlElementName = null; // Ignore the element break; } if (htmlWriter != null && htmlElementName != null) { htmlWriter.WriteStartElement(htmlElementName); WriteFormattingProperties(xamlReader, htmlWriter, inlineStyle); WriteElementContent(xamlReader, htmlWriter, inlineStyle); htmlWriter.WriteEndElement(); } else { // Skip this unrecognized xaml element WriteElementContent(xamlReader, /*htmlWriter:*/null, null); } } } // Reader advance helpers // ---------------------- /// <summary> /// Reads several items from xamlReader skipping all non-significant stuff. /// </summary> /// <param name="xamlReader"> /// XmlTextReader from tokens are being read. /// </param> /// <returns> /// True if new token is available; false if end of stream reached. /// </returns> private static bool ReadNextToken(XmlReader xamlReader) { while (xamlReader.Read()) { Debug.Assert(xamlReader.ReadState == ReadState.Interactive, "Reader is expected to be in Interactive state (" + xamlReader.ReadState + ")"); switch (xamlReader.NodeType) { case XmlNodeType.Element: case XmlNodeType.EndElement: case XmlNodeType.None: case XmlNodeType.CDATA: case XmlNodeType.Text: case XmlNodeType.SignificantWhitespace: return true; case XmlNodeType.Whitespace: if (xamlReader.XmlSpace == XmlSpace.Preserve) { return true; } // ignore insignificant whitespace break; case XmlNodeType.EndEntity: case XmlNodeType.EntityReference: // Implement entity reading //xamlReader.ResolveEntity(); //xamlReader.Read(); //ReadChildNodes( parent, parentBaseUri, xamlReader, positionInfo); break; // for now we ignore entities as insignificant stuff case XmlNodeType.Comment: return true; case XmlNodeType.ProcessingInstruction: case XmlNodeType.DocumentType: case XmlNodeType.XmlDeclaration: default: // Ignorable stuff break; } } return false; } #endregion Private Methods // --------------------------------------------------------------------- // // Private Fields // // --------------------------------------------------------------------- #region Private Fields #endregion Private Fields } }
zzgaminginc-pointofssale
Samba.Services/HtmlConverter/HtmlFromXamlConverter.cs
C#
gpl3
22,791
//--------------------------------------------------------------------------- // // File: HtmlSchema.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // Description: Static information about HTML structure // //--------------------------------------------------------------------------- using System.Diagnostics; using System.Collections; using System.Diagnostics.Contracts; namespace Samba.Services.HtmlConverter { /// <summary> /// HtmlSchema class /// maintains static information about HTML structure /// can be used by HtmlParser to check conditions under which an element starts or ends, etc. /// </summary> internal class HtmlSchema { // --------------------------------------------------------------------- // // Constructors // // --------------------------------------------------------------------- #region Constructors /// <summary> /// static constructor, initializes the ArrayLists /// that hold the elements in various sub-components of the schema /// e.g _htmlEmptyElements, etc. /// </summary> static HtmlSchema() { // initializes the list of all html elements InitializeInlineElements(); InitializeBlockElements(); InitializeOtherOpenableElements(); // initialize empty elements list InitializeEmptyElements(); // initialize list of elements closing on the outer element end InitializeElementsClosingOnParentElementEnd(); // initalize list of elements that close when a new element starts InitializeElementsClosingOnNewElementStart(); // Initialize character entities InitializeHtmlCharacterEntities(); } #endregion Constructors; // --------------------------------------------------------------------- // // Internal Methods // // --------------------------------------------------------------------- #region Internal Methods /// <summary> /// returns true when xmlElementName corresponds to empty element /// </summary> /// <param name="xmlElementName"> /// string representing name to test /// </param> internal static bool IsEmptyElement(string xmlElementName) { // convert to lowercase before we check // because element names are not case sensitive return _htmlEmptyElements.Contains(xmlElementName.ToLower()); } /// <summary> /// returns true if xmlElementName represents a block formattinng element. /// It used in an algorithm of transferring inline elements over block elements /// in HtmlParser /// </summary> /// <param name="xmlElementName"></param> /// <returns></returns> internal static bool IsBlockElement(string xmlElementName) { return _htmlBlockElements.Contains(xmlElementName); } /// <summary> /// returns true if the xmlElementName represents an inline formatting element /// </summary> /// <param name="xmlElementName"></param> /// <returns></returns> internal static bool IsInlineElement(string xmlElementName) { return _htmlInlineElements.Contains(xmlElementName); } /// <summary> /// It is a list of known html elements which we /// want to allow to produce bt HTML parser, /// but don'tt want to act as inline, block or no-scope. /// Presence in this list will allow to open /// elements during html parsing, and adding the /// to a tree produced by html parser. /// </summary> internal static bool IsKnownOpenableElement(string xmlElementName) { return _htmlOtherOpenableElements.Contains(xmlElementName); } /// <summary> /// returns true when xmlElementName closes when the outer element closes /// this is true of elements with optional start tags /// </summary> /// <param name="xmlElementName"> /// string representing name to test /// </param> internal static bool ClosesOnParentElementEnd(string xmlElementName) { // convert to lowercase when testing return _htmlElementsClosingOnParentElementEnd.Contains(xmlElementName.ToLower()); } /// <summary> /// returns true if the current element closes when the new element, whose name has just been read, starts /// </summary> /// <param name="currentElementName"> /// string representing current element name /// </param> /// <param name="elementName"></param> /// string representing name of the next element that will start internal static bool ClosesOnNextElementStart(string currentElementName, string nextElementName) { Contract.Requires(currentElementName.Equals(currentElementName.ToLower())); Debug.Assert(currentElementName == currentElementName.ToLower()); switch (currentElementName) { case "colgroup": return _htmlElementsClosingColgroup.Contains(nextElementName) && HtmlSchema.IsBlockElement(nextElementName); case "dd": return _htmlElementsClosingDD.Contains(nextElementName) && HtmlSchema.IsBlockElement(nextElementName); case "dt": return _htmlElementsClosingDT.Contains(nextElementName) && HtmlSchema.IsBlockElement(nextElementName); case "li": return _htmlElementsClosingLI.Contains(nextElementName); case "p": return HtmlSchema.IsBlockElement(nextElementName); case "tbody": return _htmlElementsClosingTbody.Contains(nextElementName); case "tfoot": return _htmlElementsClosingTfoot.Contains(nextElementName); case "thead": return _htmlElementsClosingThead.Contains(nextElementName); case "tr": return _htmlElementsClosingTR.Contains(nextElementName); case "td": return _htmlElementsClosingTD.Contains(nextElementName); case "th": return _htmlElementsClosingTH.Contains(nextElementName); } return false; } /// <summary> /// returns true if the string passed as argument is an Html entity name /// </summary> /// <param name="entityName"> /// string to be tested for Html entity name /// </param> internal static bool IsEntity(string entityName) { Contract.Requires(entityName != null); // we do not convert entity strings to lowercase because these names are case-sensitive); if (_htmlCharacterEntities.Contains(entityName)) { return true; } else { return false; } } /// <summary> /// returns the character represented by the entity name string which is passed as an argument, if the string is an entity name /// as specified in _htmlCharacterEntities, returns the character value of 0 otherwise /// </summary> /// <param name="entityName"> /// string representing entity name whose character value is desired /// </param> internal static char EntityCharacterValue(string entityName) { Contract.Requires(entityName != null); if (_htmlCharacterEntities.Contains(entityName)) { return (char) _htmlCharacterEntities[entityName]; } else { return (char)0; } } #endregion Internal Methods // --------------------------------------------------------------------- // // Internal Properties // // --------------------------------------------------------------------- #region Internal Properties #endregion Internal Indexers // --------------------------------------------------------------------- // // Private Methods // // --------------------------------------------------------------------- #region Private Methods private static void InitializeInlineElements() { _htmlInlineElements = new ArrayList(); _htmlInlineElements.Add("a"); _htmlInlineElements.Add("abbr"); _htmlInlineElements.Add("acronym"); _htmlInlineElements.Add("address"); _htmlInlineElements.Add("b"); _htmlInlineElements.Add("bdo"); // ??? _htmlInlineElements.Add("big"); _htmlInlineElements.Add("button"); _htmlInlineElements.Add("code"); _htmlInlineElements.Add("del"); // deleted text _htmlInlineElements.Add("dfn"); _htmlInlineElements.Add("em"); _htmlInlineElements.Add("font"); _htmlInlineElements.Add("i"); _htmlInlineElements.Add("ins"); // inserted text _htmlInlineElements.Add("kbd"); // text to entered by a user _htmlInlineElements.Add("label"); _htmlInlineElements.Add("legend"); // ??? _htmlInlineElements.Add("q"); // short inline quotation _htmlInlineElements.Add("s"); // strike-through text style _htmlInlineElements.Add("samp"); // Specifies a code sample _htmlInlineElements.Add("small"); _htmlInlineElements.Add("span"); _htmlInlineElements.Add("strike"); _htmlInlineElements.Add("strong"); _htmlInlineElements.Add("sub"); _htmlInlineElements.Add("sup"); _htmlInlineElements.Add("u"); _htmlInlineElements.Add("var"); // indicates an instance of a program variable } private static void InitializeBlockElements() { _htmlBlockElements = new ArrayList(); _htmlBlockElements.Add("blockquote"); _htmlBlockElements.Add("body"); _htmlBlockElements.Add("caption"); _htmlBlockElements.Add("center"); _htmlBlockElements.Add("cite"); _htmlBlockElements.Add("dd"); _htmlBlockElements.Add("dir"); // treat as UL element _htmlBlockElements.Add("div"); _htmlBlockElements.Add("dl"); _htmlBlockElements.Add("dt"); _htmlBlockElements.Add("form"); // Not a block according to XHTML spec _htmlBlockElements.Add("h1"); _htmlBlockElements.Add("h2"); _htmlBlockElements.Add("h3"); _htmlBlockElements.Add("h4"); _htmlBlockElements.Add("h5"); _htmlBlockElements.Add("h6"); _htmlBlockElements.Add("html"); _htmlBlockElements.Add("li"); _htmlBlockElements.Add("menu"); // treat as UL element _htmlBlockElements.Add("ol"); _htmlBlockElements.Add("p"); _htmlBlockElements.Add("pre"); // Renders text in a fixed-width font _htmlBlockElements.Add("table"); _htmlBlockElements.Add("tbody"); _htmlBlockElements.Add("td"); _htmlBlockElements.Add("textarea"); _htmlBlockElements.Add("tfoot"); _htmlBlockElements.Add("th"); _htmlBlockElements.Add("thead"); _htmlBlockElements.Add("tr"); _htmlBlockElements.Add("tt"); _htmlBlockElements.Add("ul"); } /// <summary> /// initializes _htmlEmptyElements with empty elements in HTML 4 spec at /// http://www.w3.org/TR/REC-html40/index/elements.html /// </summary> private static void InitializeEmptyElements() { // Build a list of empty (no-scope) elements // (element not requiring closing tags, and not accepting any content) _htmlEmptyElements = new ArrayList(); _htmlEmptyElements.Add("area"); _htmlEmptyElements.Add("base"); _htmlEmptyElements.Add("basefont"); _htmlEmptyElements.Add("br"); _htmlEmptyElements.Add("col"); _htmlEmptyElements.Add("frame"); _htmlEmptyElements.Add("hr"); _htmlEmptyElements.Add("img"); _htmlEmptyElements.Add("input"); _htmlEmptyElements.Add("isindex"); _htmlEmptyElements.Add("link"); _htmlEmptyElements.Add("meta"); _htmlEmptyElements.Add("param"); } private static void InitializeOtherOpenableElements() { // It is a list of known html elements which we // want to allow to produce bt HTML parser, // but don'tt want to act as inline, block or no-scope. // Presence in this list will allow to open // elements during html parsing, and adding the // to a tree produced by html parser. _htmlOtherOpenableElements = new ArrayList(); _htmlOtherOpenableElements.Add("applet"); _htmlOtherOpenableElements.Add("base"); _htmlOtherOpenableElements.Add("basefont"); _htmlOtherOpenableElements.Add("colgroup"); _htmlOtherOpenableElements.Add("fieldset"); //_htmlOtherOpenableElements.Add("form"); --> treated as block _htmlOtherOpenableElements.Add("frameset"); _htmlOtherOpenableElements.Add("head"); _htmlOtherOpenableElements.Add("iframe"); _htmlOtherOpenableElements.Add("map"); _htmlOtherOpenableElements.Add("noframes"); _htmlOtherOpenableElements.Add("noscript"); _htmlOtherOpenableElements.Add("object"); _htmlOtherOpenableElements.Add("optgroup"); _htmlOtherOpenableElements.Add("option"); _htmlOtherOpenableElements.Add("script"); _htmlOtherOpenableElements.Add("select"); _htmlOtherOpenableElements.Add("style"); _htmlOtherOpenableElements.Add("title"); } /// <summary> /// initializes _htmlElementsClosingOnParentElementEnd with the list of HTML 4 elements for which closing tags are optional /// we assume that for any element for which closing tags are optional, the element closes when it's outer element /// (in which it is nested) does /// </summary> private static void InitializeElementsClosingOnParentElementEnd() { _htmlElementsClosingOnParentElementEnd = new ArrayList(); _htmlElementsClosingOnParentElementEnd.Add("body"); _htmlElementsClosingOnParentElementEnd.Add("colgroup"); _htmlElementsClosingOnParentElementEnd.Add("dd"); _htmlElementsClosingOnParentElementEnd.Add("dt"); _htmlElementsClosingOnParentElementEnd.Add("head"); _htmlElementsClosingOnParentElementEnd.Add("html"); _htmlElementsClosingOnParentElementEnd.Add("li"); _htmlElementsClosingOnParentElementEnd.Add("p"); _htmlElementsClosingOnParentElementEnd.Add("tbody"); _htmlElementsClosingOnParentElementEnd.Add("td"); _htmlElementsClosingOnParentElementEnd.Add("tfoot"); _htmlElementsClosingOnParentElementEnd.Add("thead"); _htmlElementsClosingOnParentElementEnd.Add("th"); _htmlElementsClosingOnParentElementEnd.Add("tr"); } private static void InitializeElementsClosingOnNewElementStart() { _htmlElementsClosingColgroup = new ArrayList(); _htmlElementsClosingColgroup.Add("colgroup"); _htmlElementsClosingColgroup.Add("tr"); _htmlElementsClosingColgroup.Add("thead"); _htmlElementsClosingColgroup.Add("tfoot"); _htmlElementsClosingColgroup.Add("tbody"); _htmlElementsClosingDD = new ArrayList(); _htmlElementsClosingDD.Add("dd"); _htmlElementsClosingDD.Add("dt"); _htmlElementsClosingDT = new ArrayList(); _htmlElementsClosingDD.Add("dd"); _htmlElementsClosingDD.Add("dt"); _htmlElementsClosingLI = new ArrayList(); _htmlElementsClosingLI.Add("li"); _htmlElementsClosingTbody = new ArrayList(); _htmlElementsClosingTbody.Add("tbody"); _htmlElementsClosingTbody.Add("thead"); _htmlElementsClosingTbody.Add("tfoot"); _htmlElementsClosingTR = new ArrayList(); // because if there are rows before a thead, it is assumed to be in tbody, whose start tag is optional // and thead can't come after tbody // however, if we do encounter this, it's probably best to end the row and ignore the thead or treat // it as part of the table _htmlElementsClosingTR.Add("thead"); _htmlElementsClosingTR.Add("tfoot"); _htmlElementsClosingTR.Add("tbody"); _htmlElementsClosingTR.Add("tr"); _htmlElementsClosingTD = new ArrayList(); _htmlElementsClosingTD.Add("td"); _htmlElementsClosingTD.Add("th"); _htmlElementsClosingTD.Add("tr"); _htmlElementsClosingTD.Add("tbody"); _htmlElementsClosingTD.Add("tfoot"); _htmlElementsClosingTD.Add("thead"); _htmlElementsClosingTH = new ArrayList(); _htmlElementsClosingTH.Add("td"); _htmlElementsClosingTH.Add("th"); _htmlElementsClosingTH.Add("tr"); _htmlElementsClosingTH.Add("tbody"); _htmlElementsClosingTH.Add("tfoot"); _htmlElementsClosingTH.Add("thead"); _htmlElementsClosingThead = new ArrayList(); _htmlElementsClosingThead.Add("tbody"); _htmlElementsClosingThead.Add("tfoot"); _htmlElementsClosingTfoot = new ArrayList(); _htmlElementsClosingTfoot.Add("tbody"); // although thead comes before tfoot, we add it because if it is found the tfoot should close // and some recovery processing be done on the thead _htmlElementsClosingTfoot.Add("thead"); } /// <summary> /// initializes _htmlCharacterEntities hashtable with the character corresponding to entity names /// </summary> private static void InitializeHtmlCharacterEntities() { _htmlCharacterEntities = new Hashtable(); _htmlCharacterEntities["Aacute"] = (char)193; _htmlCharacterEntities["aacute"] = (char)225; _htmlCharacterEntities["Acirc"] = (char)194; _htmlCharacterEntities["acirc"] = (char)226; _htmlCharacterEntities["acute"] = (char)180; _htmlCharacterEntities["AElig"] = (char)198; _htmlCharacterEntities["aelig"] = (char)230; _htmlCharacterEntities["Agrave"] = (char)192; _htmlCharacterEntities["agrave"] = (char)224; _htmlCharacterEntities["alefsym"] = (char)8501; _htmlCharacterEntities["Alpha"] = (char)913; _htmlCharacterEntities["alpha"] = (char)945; _htmlCharacterEntities["amp"] = (char)38; _htmlCharacterEntities["and"] = (char)8743; _htmlCharacterEntities["ang"] = (char)8736; _htmlCharacterEntities["Aring"] = (char)197; _htmlCharacterEntities["aring"] = (char)229; _htmlCharacterEntities["asymp"] = (char)8776; _htmlCharacterEntities["Atilde"] = (char)195; _htmlCharacterEntities["atilde"] = (char)227; _htmlCharacterEntities["Auml"] = (char)196; _htmlCharacterEntities["auml"] = (char)228; _htmlCharacterEntities["bdquo"] = (char)8222; _htmlCharacterEntities["Beta"] = (char)914; _htmlCharacterEntities["beta"] = (char)946; _htmlCharacterEntities["brvbar"] = (char)166; _htmlCharacterEntities["bull"] = (char)8226; _htmlCharacterEntities["cap"] = (char)8745; _htmlCharacterEntities["Ccedil"] = (char)199; _htmlCharacterEntities["ccedil"] = (char)231; _htmlCharacterEntities["cent"] = (char)162; _htmlCharacterEntities["Chi"] = (char)935; _htmlCharacterEntities["chi"] = (char)967; _htmlCharacterEntities["circ"] = (char)710; _htmlCharacterEntities["clubs"] = (char)9827; _htmlCharacterEntities["cong"] = (char)8773; _htmlCharacterEntities["copy"] = (char)169; _htmlCharacterEntities["crarr"] = (char)8629; _htmlCharacterEntities["cup"] = (char)8746; _htmlCharacterEntities["curren"] = (char)164; _htmlCharacterEntities["dagger"] = (char)8224; _htmlCharacterEntities["Dagger"] = (char)8225; _htmlCharacterEntities["darr"] = (char)8595; _htmlCharacterEntities["dArr"] = (char)8659; _htmlCharacterEntities["deg"] = (char)176; _htmlCharacterEntities["Delta"] = (char)916; _htmlCharacterEntities["delta"] = (char)948; _htmlCharacterEntities["diams"] = (char)9830; _htmlCharacterEntities["divide"] = (char)247; _htmlCharacterEntities["Eacute"] = (char)201; _htmlCharacterEntities["eacute"] = (char)233; _htmlCharacterEntities["Ecirc"] = (char)202; _htmlCharacterEntities["ecirc"] = (char)234; _htmlCharacterEntities["Egrave"] = (char)200; _htmlCharacterEntities["egrave"] = (char)232; _htmlCharacterEntities["empty"] = (char)8709; _htmlCharacterEntities["emsp"] = (char)8195; _htmlCharacterEntities["ensp"] = (char)8194; _htmlCharacterEntities["Epsilon"] = (char)917; _htmlCharacterEntities["epsilon"] = (char)949; _htmlCharacterEntities["equiv"] = (char)8801; _htmlCharacterEntities["Eta"] = (char)919; _htmlCharacterEntities["eta"] = (char)951; _htmlCharacterEntities["ETH"] = (char)208; _htmlCharacterEntities["eth"] = (char)240; _htmlCharacterEntities["Euml"] = (char)203; _htmlCharacterEntities["euml"] = (char)235; _htmlCharacterEntities["euro"] = (char)8364; _htmlCharacterEntities["exist"] = (char)8707; _htmlCharacterEntities["fnof"] = (char)402; _htmlCharacterEntities["forall"] = (char)8704; _htmlCharacterEntities["frac12"] = (char)189; _htmlCharacterEntities["frac14"] = (char)188; _htmlCharacterEntities["frac34"] = (char)190; _htmlCharacterEntities["frasl"] = (char)8260; _htmlCharacterEntities["Gamma"] = (char)915; _htmlCharacterEntities["gamma"] = (char)947; _htmlCharacterEntities["ge"] = (char)8805; _htmlCharacterEntities["gt"] = (char)62; _htmlCharacterEntities["harr"] = (char)8596; _htmlCharacterEntities["hArr"] = (char)8660; _htmlCharacterEntities["hearts"] = (char)9829; _htmlCharacterEntities["hellip"] = (char)8230; _htmlCharacterEntities["Iacute"] = (char)205; _htmlCharacterEntities["iacute"] = (char)237; _htmlCharacterEntities["Icirc"] = (char)206; _htmlCharacterEntities["icirc"] = (char)238; _htmlCharacterEntities["iexcl"] = (char)161; _htmlCharacterEntities["Igrave"] = (char)204; _htmlCharacterEntities["igrave"] = (char)236; _htmlCharacterEntities["image"] = (char)8465; _htmlCharacterEntities["infin"] = (char)8734; _htmlCharacterEntities["int"] = (char)8747; _htmlCharacterEntities["Iota"] = (char)921; _htmlCharacterEntities["iota"] = (char)953; _htmlCharacterEntities["iquest"] = (char)191; _htmlCharacterEntities["isin"] = (char)8712; _htmlCharacterEntities["Iuml"] = (char)207; _htmlCharacterEntities["iuml"] = (char)239; _htmlCharacterEntities["Kappa"] = (char)922; _htmlCharacterEntities["kappa"] = (char)954; _htmlCharacterEntities["Lambda"] = (char)923; _htmlCharacterEntities["lambda"] = (char)955; _htmlCharacterEntities["lang"] = (char)9001; _htmlCharacterEntities["laquo"] = (char)171; _htmlCharacterEntities["larr"] = (char)8592; _htmlCharacterEntities["lArr"] = (char)8656; _htmlCharacterEntities["lceil"] = (char)8968; _htmlCharacterEntities["ldquo"] = (char)8220; _htmlCharacterEntities["le"] = (char)8804; _htmlCharacterEntities["lfloor"] = (char)8970; _htmlCharacterEntities["lowast"] = (char)8727; _htmlCharacterEntities["loz"] = (char)9674; _htmlCharacterEntities["lrm"] = (char)8206; _htmlCharacterEntities["lsaquo"] = (char)8249; _htmlCharacterEntities["lsquo"] = (char)8216; _htmlCharacterEntities["lt"] = (char)60; _htmlCharacterEntities["macr"] = (char)175; _htmlCharacterEntities["mdash"] = (char)8212; _htmlCharacterEntities["micro"] = (char)181; _htmlCharacterEntities["middot"] = (char)183; _htmlCharacterEntities["minus"] = (char)8722; _htmlCharacterEntities["Mu"] = (char)924; _htmlCharacterEntities["mu"] = (char)956; _htmlCharacterEntities["nabla"] = (char)8711; _htmlCharacterEntities["nbsp"] = (char)160; _htmlCharacterEntities["ndash"] = (char)8211; _htmlCharacterEntities["ne"] = (char)8800; _htmlCharacterEntities["ni"] = (char)8715; _htmlCharacterEntities["not"] = (char)172; _htmlCharacterEntities["notin"] = (char)8713; _htmlCharacterEntities["nsub"] = (char)8836; _htmlCharacterEntities["Ntilde"] = (char)209; _htmlCharacterEntities["ntilde"] = (char)241; _htmlCharacterEntities["Nu"] = (char)925; _htmlCharacterEntities["nu"] = (char)957; _htmlCharacterEntities["Oacute"] = (char)211; _htmlCharacterEntities["ocirc"] = (char)244; _htmlCharacterEntities["OElig"] = (char)338; _htmlCharacterEntities["oelig"] = (char)339; _htmlCharacterEntities["Ograve"] = (char)210; _htmlCharacterEntities["ograve"] = (char)242; _htmlCharacterEntities["oline"] = (char)8254; _htmlCharacterEntities["Omega"] = (char)937; _htmlCharacterEntities["omega"] = (char)969; _htmlCharacterEntities["Omicron"] = (char)927; _htmlCharacterEntities["omicron"] = (char)959; _htmlCharacterEntities["oplus"] = (char)8853; _htmlCharacterEntities["or"] = (char)8744; _htmlCharacterEntities["ordf"] = (char)170; _htmlCharacterEntities["ordm"] = (char)186; _htmlCharacterEntities["Oslash"] = (char)216; _htmlCharacterEntities["oslash"] = (char)248; _htmlCharacterEntities["Otilde"] = (char)213; _htmlCharacterEntities["otilde"] = (char)245; _htmlCharacterEntities["otimes"] = (char)8855; _htmlCharacterEntities["Ouml"] = (char)214; _htmlCharacterEntities["ouml"] = (char)246; _htmlCharacterEntities["para"] = (char)182; _htmlCharacterEntities["part"] = (char)8706; _htmlCharacterEntities["permil"] = (char)8240; _htmlCharacterEntities["perp"] = (char)8869; _htmlCharacterEntities["Phi"] = (char)934; _htmlCharacterEntities["phi"] = (char)966; _htmlCharacterEntities["pi"] = (char)960; _htmlCharacterEntities["piv"] = (char)982; _htmlCharacterEntities["plusmn"] = (char)177; _htmlCharacterEntities["pound"] = (char)163; _htmlCharacterEntities["prime"] = (char)8242; _htmlCharacterEntities["Prime"] = (char)8243; _htmlCharacterEntities["prod"] = (char)8719; _htmlCharacterEntities["prop"] = (char)8733; _htmlCharacterEntities["Psi"] = (char)936; _htmlCharacterEntities["psi"] = (char)968; _htmlCharacterEntities["quot"] = (char)34; _htmlCharacterEntities["radic"] = (char)8730; _htmlCharacterEntities["rang"] = (char)9002; _htmlCharacterEntities["raquo"] = (char)187; _htmlCharacterEntities["rarr"] = (char)8594; _htmlCharacterEntities["rArr"] = (char)8658; _htmlCharacterEntities["rceil"] = (char)8969; _htmlCharacterEntities["rdquo"] = (char)8221; _htmlCharacterEntities["real"] = (char)8476; _htmlCharacterEntities["reg"] = (char)174; _htmlCharacterEntities["rfloor"] = (char)8971; _htmlCharacterEntities["Rho"] = (char)929; _htmlCharacterEntities["rho"] = (char)961; _htmlCharacterEntities["rlm"] = (char)8207; _htmlCharacterEntities["rsaquo"] = (char)8250; _htmlCharacterEntities["rsquo"] = (char)8217; _htmlCharacterEntities["sbquo"] = (char)8218; _htmlCharacterEntities["Scaron"] = (char)352; _htmlCharacterEntities["scaron"] = (char)353; _htmlCharacterEntities["sdot"] = (char)8901; _htmlCharacterEntities["sect"] = (char)167; _htmlCharacterEntities["shy"] = (char)173; _htmlCharacterEntities["Sigma"] = (char)931; _htmlCharacterEntities["sigma"] = (char)963; _htmlCharacterEntities["sigmaf"] = (char)962; _htmlCharacterEntities["sim"] = (char)8764; _htmlCharacterEntities["spades"] = (char)9824; _htmlCharacterEntities["sub"] = (char)8834; _htmlCharacterEntities["sube"] = (char)8838; _htmlCharacterEntities["sum"] = (char)8721; _htmlCharacterEntities["sup"] = (char)8835; _htmlCharacterEntities["sup1"] = (char)185; _htmlCharacterEntities["sup2"] = (char)178; _htmlCharacterEntities["sup3"] = (char)179; _htmlCharacterEntities["supe"] = (char)8839; _htmlCharacterEntities["szlig"] = (char)223; _htmlCharacterEntities["Tau"] = (char)932; _htmlCharacterEntities["tau"] = (char)964; _htmlCharacterEntities["there4"] = (char)8756; _htmlCharacterEntities["Theta"] = (char)920; _htmlCharacterEntities["theta"] = (char)952; _htmlCharacterEntities["thetasym"] = (char)977; _htmlCharacterEntities["thinsp"] = (char)8201; _htmlCharacterEntities["THORN"] = (char)222; _htmlCharacterEntities["thorn"] = (char)254; _htmlCharacterEntities["tilde"] = (char)732; _htmlCharacterEntities["times"] = (char)215; _htmlCharacterEntities["trade"] = (char)8482; _htmlCharacterEntities["Uacute"] = (char)218; _htmlCharacterEntities["uacute"] = (char)250; _htmlCharacterEntities["uarr"] = (char)8593; _htmlCharacterEntities["uArr"] = (char)8657; _htmlCharacterEntities["Ucirc"] = (char)219; _htmlCharacterEntities["ucirc"] = (char)251; _htmlCharacterEntities["Ugrave"] = (char)217; _htmlCharacterEntities["ugrave"] = (char)249; _htmlCharacterEntities["uml"] = (char)168; _htmlCharacterEntities["upsih"] = (char)978; _htmlCharacterEntities["Upsilon"] = (char)933; _htmlCharacterEntities["upsilon"] = (char)965; _htmlCharacterEntities["Uuml"] = (char)220; _htmlCharacterEntities["uuml"] = (char)252; _htmlCharacterEntities["weierp"] = (char)8472; _htmlCharacterEntities["Xi"] = (char)926; _htmlCharacterEntities["xi"] = (char)958; _htmlCharacterEntities["Yacute"] = (char)221; _htmlCharacterEntities["yacute"] = (char)253; _htmlCharacterEntities["yen"] = (char)165; _htmlCharacterEntities["Yuml"] = (char)376; _htmlCharacterEntities["yuml"] = (char)255; _htmlCharacterEntities["Zeta"] = (char)918; _htmlCharacterEntities["zeta"] = (char)950; _htmlCharacterEntities["zwj"] = (char)8205; _htmlCharacterEntities["zwnj"] = (char)8204; } #endregion Private Methods // --------------------------------------------------------------------- // // Private Fields // // --------------------------------------------------------------------- #region Private Fields // html element names // this is an array list now, but we may want to make it a hashtable later for better performance private static ArrayList _htmlInlineElements; private static ArrayList _htmlBlockElements; private static ArrayList _htmlOtherOpenableElements; // list of html empty element names private static ArrayList _htmlEmptyElements; // names of html elements for which closing tags are optional, and close when the outer nested element closes private static ArrayList _htmlElementsClosingOnParentElementEnd; // names of elements that close certain optional closing tag elements when they start // names of elements closing the colgroup element private static ArrayList _htmlElementsClosingColgroup; // names of elements closing the dd element private static ArrayList _htmlElementsClosingDD; // names of elements closing the dt element private static ArrayList _htmlElementsClosingDT; // names of elements closing the li element private static ArrayList _htmlElementsClosingLI; // names of elements closing the tbody element private static ArrayList _htmlElementsClosingTbody; // names of elements closing the td element private static ArrayList _htmlElementsClosingTD; // names of elements closing the tfoot element private static ArrayList _htmlElementsClosingTfoot; // names of elements closing the thead element private static ArrayList _htmlElementsClosingThead; // names of elements closing the th element private static ArrayList _htmlElementsClosingTH; // names of elements closing the tr element private static ArrayList _htmlElementsClosingTR; // html character entities hashtable private static Hashtable _htmlCharacterEntities; #endregion Private Fields } }
zzgaminginc-pointofssale
Samba.Services/HtmlConverter/HtmlSchema.cs
C#
gpl3
36,174
//--------------------------------------------------------------------------- // // File: HtmlTokenType.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // Description: Definition of token types supported by HtmlLexicalAnalyzer // //--------------------------------------------------------------------------- namespace Samba.Services.HtmlConverter { /// <summary> /// types of lexical tokens for html-to-xaml converter /// </summary> internal enum HtmlTokenType { OpeningTagStart, ClosingTagStart, TagEnd, EmptyTagEnd, EqualSign, Name, Atom, // any attribute value not in quotes Text, //text content when accepting text Comment, EOF, } }
zzgaminginc-pointofssale
Samba.Services/HtmlConverter/HtmlTokenType.cs
C#
gpl3
795
//--------------------------------------------------------------------------- // // File: HtmlParser.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // Description: Parser for Html-to-Xaml converter // //--------------------------------------------------------------------------- using System; using System.Diagnostics.Contracts; using System.Xml; using System.Collections.Generic; using System.Text; namespace Samba.Services.HtmlConverter { /// <summary> /// HtmlParser class accepts a string of possibly badly formed Html, parses it and returns a string /// of well-formed Html that is as close to the original string in content as possible /// </summary> internal class HtmlParser { // --------------------------------------------------------------------- // // Constructors // // --------------------------------------------------------------------- #region Constructors /// <summary> /// Constructor. Initializes the _htmlLexicalAnalayzer element with the given input string /// </summary> /// <param name="inputString"> /// string to parsed into well-formed Html /// </param> private HtmlParser(string inputString) { // Create an output xml document _document = new XmlDocument(); // initialize open tag stack _openedElements = new Stack<XmlElement>(); _pendingInlineElements = new Stack<XmlElement>(); // initialize lexical analyzer _htmlLexicalAnalyzer = new HtmlLexicalAnalyzer(inputString); // get first token from input, expecting text _htmlLexicalAnalyzer.GetNextContentToken(); } #endregion Constructors // --------------------------------------------------------------------- // // Internal Methods // // --------------------------------------------------------------------- #region Internal Methods /// <summary> /// Instantiates an HtmlParser element and calls the parsing function on the given input string /// </summary> /// <param name="htmlString"> /// Input string of pssibly badly-formed Html to be parsed into well-formed Html /// </param> /// <returns> /// XmlElement rep /// </returns> internal static XmlElement ParseHtml(string htmlString) { HtmlParser htmlParser = new HtmlParser(htmlString); XmlElement htmlRootElement = htmlParser.ParseHtmlContent(); return htmlRootElement; } // ..................................................................... // // Html Header on Clipboard // // ..................................................................... // Html header structure. // Version:1.0 // StartHTML:000000000 // EndHTML:000000000 // StartFragment:000000000 // EndFragment:000000000 // StartSelection:000000000 // EndSelection:000000000 internal const string HtmlHeader = "Version:1.0\r\nStartHTML:{0:D10}\r\nEndHTML:{1:D10}\r\nStartFragment:{2:D10}\r\nEndFragment:{3:D10}\r\nStartSelection:{4:D10}\r\nEndSelection:{5:D10}\r\n"; internal const string HtmlStartFragmentComment = "<!--StartFragment-->"; internal const string HtmlEndFragmentComment = "<!--EndFragment-->"; /// <summary> /// Extracts Html string from clipboard data by parsing header information in htmlDataString /// </summary> /// <param name="htmlDataString"> /// String representing Html clipboard data. This includes Html header /// </param> /// <returns> /// String containing only the Html data part of htmlDataString, without header /// </returns> internal static string ExtractHtmlFromClipboardData(string htmlDataString) { int startHtmlIndex = htmlDataString.IndexOf("StartHTML:"); if (startHtmlIndex < 0) { return "ERROR: Urecognized html header"; } // which could be wrong assumption. We need to implement more flrxible parsing here startHtmlIndex = Int32.Parse(htmlDataString.Substring(startHtmlIndex + "StartHTML:".Length, "0123456789".Length)); if (startHtmlIndex < 0 || startHtmlIndex > htmlDataString.Length) { return "ERROR: Urecognized html header"; } int endHtmlIndex = htmlDataString.IndexOf("EndHTML:"); if (endHtmlIndex < 0) { return "ERROR: Urecognized html header"; } // which could be wrong assumption. We need to implement more flrxible parsing here endHtmlIndex = Int32.Parse(htmlDataString.Substring(endHtmlIndex + "EndHTML:".Length, "0123456789".Length)); if (endHtmlIndex > htmlDataString.Length) { endHtmlIndex = htmlDataString.Length; } return htmlDataString.Substring(startHtmlIndex, endHtmlIndex - startHtmlIndex); } /// <summary> /// Adds Xhtml header information to Html data string so that it can be placed on clipboard /// </summary> /// <param name="htmlString"> /// Html string to be placed on clipboard with appropriate header /// </param> /// <returns> /// String wrapping htmlString with appropriate Html header /// </returns> internal static string AddHtmlClipboardHeader(string htmlString) { StringBuilder stringBuilder = new StringBuilder(); // each of 6 numbers is represented by "{0:D10}" in the format string // must actually occupy 10 digit positions ("0123456789") int startHTML = HtmlHeader.Length + 6 * ("0123456789".Length - "{0:D10}".Length); int endHTML = startHTML + htmlString.Length; int startFragment = htmlString.IndexOf(HtmlStartFragmentComment, 0); if (startFragment >= 0) { startFragment = startHTML + startFragment + HtmlStartFragmentComment.Length; } else { startFragment = startHTML; } int endFragment = htmlString.IndexOf(HtmlEndFragmentComment, 0); if (endFragment >= 0) { endFragment = startHTML + endFragment; } else { endFragment = endHTML; } // Create HTML clipboard header string stringBuilder.AppendFormat(HtmlHeader, startHTML, endHTML, startFragment, endFragment, startFragment, endFragment); // Append HTML body. stringBuilder.Append(htmlString); return stringBuilder.ToString(); } #endregion Internal Methods // --------------------------------------------------------------------- // // Private methods // // --------------------------------------------------------------------- #region Private Methods private void InvariantAssert(bool condition, string message) { if (!condition) { throw new Exception("Assertion error: " + message); } } /// <summary> /// Parses the stream of html tokens starting /// from the name of top-level element. /// Returns XmlElement representing the top-level /// html element /// </summary> private XmlElement ParseHtmlContent() { // Create artificial root elelemt to be able to group multiple top-level elements // We create "html" element which may be a duplicate of real HTML element, which is ok, as HtmlConverter will swallow it painlessly.. XmlElement htmlRootElement = _document.CreateElement("html", XhtmlNamespace); OpenStructuringElement(htmlRootElement); while (_htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.EOF) { if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.OpeningTagStart) { _htmlLexicalAnalyzer.GetNextTagToken(); if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Name) { string htmlElementName = _htmlLexicalAnalyzer.NextToken.ToLower(); _htmlLexicalAnalyzer.GetNextTagToken(); // Create an element XmlElement htmlElement = _document.CreateElement(htmlElementName, XhtmlNamespace); // Parse element attributes ParseAttributes(htmlElement); if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.EmptyTagEnd || HtmlSchema.IsEmptyElement(htmlElementName)) { // It is an element without content (because of explicit slash or based on implicit knowledge aboout html) AddEmptyElement(htmlElement); } else if (HtmlSchema.IsInlineElement(htmlElementName)) { // Elements known as formatting are pushed to some special // pending stack, which allows them to be transferred // over block tags - by doing this we convert // overlapping tags into normal heirarchical element structure. OpenInlineElement(htmlElement); } else if (HtmlSchema.IsBlockElement(htmlElementName) || HtmlSchema.IsKnownOpenableElement(htmlElementName)) { // This includes no-scope elements OpenStructuringElement(htmlElement); } else { // Do nothing. Skip the whole opening tag. // Ignoring all unknown elements on their start tags. // Thus we will ignore them on closinng tag as well. // Anyway we don't know what to do withthem on conversion to Xaml. } } else { // Otherwise - we skip the angle bracket and continue parsing the content as if it is just text. // Add the following asserion here, right? or output "<" as a text run instead?: // InvariantAssert(false, "Angle bracket without a following name is not expected"); } } else if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.ClosingTagStart) { _htmlLexicalAnalyzer.GetNextTagToken(); if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Name) { string htmlElementName = _htmlLexicalAnalyzer.NextToken.ToLower(); // Skip the name token. Assume that the following token is end of tag, // but do not check this. If it is not true, we simply ignore one token // - this is our recovery from bad xml in this case. _htmlLexicalAnalyzer.GetNextTagToken(); CloseElement(htmlElementName); } } else if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Text) { AddTextContent(_htmlLexicalAnalyzer.NextToken); } else if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Comment) { AddComment(_htmlLexicalAnalyzer.NextToken); } _htmlLexicalAnalyzer.GetNextContentToken(); } // Get rid of the artificial root element if (htmlRootElement.FirstChild is XmlElement && htmlRootElement.FirstChild == htmlRootElement.LastChild && htmlRootElement.FirstChild.LocalName.ToLower() == "html") { htmlRootElement = (XmlElement)htmlRootElement.FirstChild; } return htmlRootElement; } private XmlElement CreateElementCopy(XmlElement htmlElement) { XmlElement htmlElementCopy = _document.CreateElement(htmlElement.LocalName, XhtmlNamespace); for (int i = 0; i < htmlElement.Attributes.Count; i++) { XmlAttribute attribute = htmlElement.Attributes[i]; htmlElementCopy.SetAttribute(attribute.Name, attribute.Value); } return htmlElementCopy; } private void AddEmptyElement(XmlElement htmlEmptyElement) { Contract.Requires(htmlEmptyElement != null); InvariantAssert(_openedElements.Count > 0, "AddEmptyElement: Stack of opened elements cannot be empty, as we have at least one artificial root element"); XmlElement htmlParent = _openedElements.Peek(); htmlParent.AppendChild(htmlEmptyElement); } private void OpenInlineElement(XmlElement htmlInlineElement) { _pendingInlineElements.Push(htmlInlineElement); } // Opens structurig element such as Div or Table etc. private void OpenStructuringElement(XmlElement htmlElement) { // Close all pending inline elements // All block elements are considered as delimiters for inline elements // which forces all inline elements to be closed and re-opened in the following // structural element (if any). // By doing that we guarantee that all inline elements appear only within most nested blocks if (HtmlSchema.IsBlockElement(htmlElement.LocalName)) { while (_openedElements.Count > 0 && HtmlSchema.IsInlineElement(_openedElements.Peek().LocalName)) { XmlElement htmlInlineElement = _openedElements.Pop(); InvariantAssert(_openedElements.Count > 0, "OpenStructuringElement: stack of opened elements cannot become empty here"); _pendingInlineElements.Push(CreateElementCopy(htmlInlineElement)); } } // Add this block element to its parent if (_openedElements.Count > 0) { XmlElement htmlParent = _openedElements.Peek(); // Check some known block elements for auto-closing (LI and P) if (HtmlSchema.ClosesOnNextElementStart(htmlParent.LocalName, htmlElement.LocalName)) { _openedElements.Pop(); htmlParent = _openedElements.Count > 0 ? _openedElements.Peek() : null; } if (htmlParent != null) { // Actually we never expect null - it would mean two top-level P or LI (without a parent). // In such weird case we will loose all paragraphs except the first one... htmlParent.AppendChild(htmlElement); } } // Push it onto a stack _openedElements.Push(htmlElement); } private bool IsElementOpened(string htmlElementName) { foreach (XmlElement openedElement in _openedElements) { if (openedElement.LocalName == htmlElementName) { return true; } } return false; } private void CloseElement(string htmlElementName) { // Check if the element is opened and already added to the parent InvariantAssert(_openedElements.Count > 0, "CloseElement: Stack of opened elements cannot be empty, as we have at least one artificial root element"); // Check if the element is opened and still waiting to be added to the parent if (_pendingInlineElements.Count > 0 && _pendingInlineElements.Peek().LocalName == htmlElementName) { // Closing an empty inline element. XmlElement htmlInlineElement = _pendingInlineElements.Pop(); InvariantAssert(_openedElements.Count > 0, "CloseElement: Stack of opened elements cannot be empty, as we have at least one artificial root element"); XmlElement htmlParent = _openedElements.Peek(); htmlParent.AppendChild(htmlInlineElement); return; } else if (IsElementOpened(htmlElementName)) { while (_openedElements.Count > 1) // we never pop the last element - the artificial root { // Close all unbalanced elements. XmlElement htmlOpenedElement = _openedElements.Pop(); if (htmlOpenedElement.LocalName == htmlElementName) { return; } if (HtmlSchema.IsInlineElement(htmlOpenedElement.LocalName)) { // Unbalances Inlines will be transfered to the next element content _pendingInlineElements.Push(CreateElementCopy(htmlOpenedElement)); } } } // If element was not opened, we simply ignore the unbalanced closing tag return; } private void AddTextContent(string textContent) { OpenPendingInlineElements(); InvariantAssert(_openedElements.Count > 0, "AddTextContent: Stack of opened elements cannot be empty, as we have at least one artificial root element"); XmlElement htmlParent = _openedElements.Peek(); XmlText textNode = _document.CreateTextNode(textContent); htmlParent.AppendChild(textNode); } private void AddComment(string comment) { OpenPendingInlineElements(); InvariantAssert(_openedElements.Count > 0, "AddComment: Stack of opened elements cannot be empty, as we have at least one artificial root element"); XmlElement htmlParent = _openedElements.Peek(); XmlComment xmlComment = _document.CreateComment(comment); htmlParent.AppendChild(xmlComment); } // Moves all inline elements pending for opening to actual document // and adds them to current open stack. private void OpenPendingInlineElements() { if (_pendingInlineElements.Count > 0) { XmlElement htmlInlineElement = _pendingInlineElements.Pop(); OpenPendingInlineElements(); InvariantAssert(_openedElements.Count > 0, "OpenPendingInlineElements: Stack of opened elements cannot be empty, as we have at least one artificial root element"); XmlElement htmlParent = _openedElements.Peek(); htmlParent.AppendChild(htmlInlineElement); _openedElements.Push(htmlInlineElement); } } private void ParseAttributes(XmlElement xmlElement) { while (_htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.EOF && // _htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.TagEnd && // _htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.EmptyTagEnd) { // read next attribute (name=value) if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Name) { string attributeName = _htmlLexicalAnalyzer.NextToken; _htmlLexicalAnalyzer.GetNextEqualSignToken(); _htmlLexicalAnalyzer.GetNextAtomToken(); string attributeValue = _htmlLexicalAnalyzer.NextToken; xmlElement.SetAttribute(attributeName, attributeValue); } _htmlLexicalAnalyzer.GetNextTagToken(); } } #endregion Private Methods // --------------------------------------------------------------------- // // Private Fields // // --------------------------------------------------------------------- #region Private Fields internal const string XhtmlNamespace = "http://www.w3.org/1999/xhtml"; private HtmlLexicalAnalyzer _htmlLexicalAnalyzer; // document from which all elements are created private XmlDocument _document; // stack for open elements Stack<XmlElement> _openedElements; Stack<XmlElement> _pendingInlineElements; #endregion Private Fields } }
zzgaminginc-pointofssale
Samba.Services/HtmlConverter/HtmlParser.cs
C#
gpl3
21,853
//--------------------------------------------------------------------------- // // File: HtmlXamlConverter.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // Description: Prototype for Html - Xaml conversion // //--------------------------------------------------------------------------- using System; using System.Diagnostics.Contracts; using System.Xml; using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Text; namespace Samba.Services.HtmlConverter { // DependencyProperty // TextElement internal static class HtmlCssParser { // ................................................................. // // Processing CSS Attributes // // ................................................................. internal static void GetElementPropertiesFromCssAttributes(XmlElement htmlElement, string elementName, CssStylesheet stylesheet, Hashtable localProperties, List<XmlElement> sourceContext) { string styleFromStylesheet = stylesheet.GetStyle(elementName, sourceContext); string styleInline = HtmlToXamlConverter.GetAttribute(htmlElement, "style"); // Combine styles from stylesheet and from inline attribute. // The order is important - the latter styles will override the former. string style = styleFromStylesheet != null ? styleFromStylesheet : null; if (styleInline != null) { style = style == null ? styleInline : (style + ";" + styleInline); } // Apply local style to current formatting properties if (style != null) { string[] styleValues = style.Split(';'); for (int i = 0; i < styleValues.Length; i++) { string[] styleNameValue; styleNameValue = styleValues[i].Split(':'); if (styleNameValue.Length == 2) { string styleName = styleNameValue[0].Trim().ToLower(); string styleValue = HtmlToXamlConverter.UnQuote(styleNameValue[1].Trim()).ToLower(); int nextIndex = 0; switch (styleName) { case "font": ParseCssFont(styleValue, localProperties); break; case "font-family": ParseCssFontFamily(styleValue, ref nextIndex, localProperties); break; case "font-size": ParseCssSize(styleValue, ref nextIndex, localProperties, "font-size", /*mustBeNonNegative:*/true); break; case "font-style": ParseCssFontStyle(styleValue, ref nextIndex, localProperties); break; case "font-weight": ParseCssFontWeight(styleValue, ref nextIndex, localProperties); break; case "font-variant": ParseCssFontVariant(styleValue, ref nextIndex, localProperties); break; case "line-height": ParseCssSize(styleValue, ref nextIndex, localProperties, "line-height", /*mustBeNonNegative:*/true); break; case "word-spacing": // Implement word-spacing conversion break; case "letter-spacing": // Implement letter-spacing conversion break; case "color": ParseCssColor(styleValue, ref nextIndex, localProperties, "color"); break; case "text-decoration": ParseCssTextDecoration(styleValue, ref nextIndex, localProperties); break; case "text-transform": ParseCssTextTransform(styleValue, ref nextIndex, localProperties); break; case "background-color": ParseCssColor(styleValue, ref nextIndex, localProperties, "background-color"); break; case "background": ParseCssBackground(styleValue, ref nextIndex, localProperties); break; case "text-align": ParseCssTextAlign(styleValue, ref nextIndex, localProperties); break; case "vertical-align": ParseCssVerticalAlign(styleValue, ref nextIndex, localProperties); break; case "text-indent": ParseCssSize(styleValue, ref nextIndex, localProperties, "text-indent", /*mustBeNonNegative:*/false); break; case "width": case "height": ParseCssSize(styleValue, ref nextIndex, localProperties, styleName, /*mustBeNonNegative:*/true); break; case "margin": // top/right/bottom/left ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, styleName); break; case "margin-top": case "margin-right": case "margin-bottom": case "margin-left": ParseCssSize(styleValue, ref nextIndex, localProperties, styleName, /*mustBeNonNegative:*/true); break; case "padding": ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, styleName); break; case "padding-top": case "padding-right": case "padding-bottom": case "padding-left": ParseCssSize(styleValue, ref nextIndex, localProperties, styleName, /*mustBeNonNegative:*/true); break; case "border": ParseCssBorder(styleValue, ref nextIndex, localProperties); break; case "border-style": case "border-width": case "border-color": ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, styleName); break; case "border-top": case "border-right": case "border-left": case "border-bottom": // Parse css border style break; // In our internal notation we intentionally put them at the end - to unify processing in ParseCssRectangleProperty method case "border-top-style": case "border-right-style": case "border-left-style": case "border-bottom-style": case "border-top-color": case "border-right-color": case "border-left-color": case "border-bottom-color": case "border-top-width": case "border-right-width": case "border-left-width": case "border-bottom-width": // Parse css border style break; case "display": // Implement display style conversion break; case "float": ParseCssFloat(styleValue, ref nextIndex, localProperties); break; case "clear": ParseCssClear(styleValue, ref nextIndex, localProperties); break; default: break; } } } } } // ................................................................. // // Parsing CSS - Lexical Helpers // // ................................................................. // Skips whitespaces in style values private static void ParseWhiteSpace(string styleValue, ref int nextIndex) { while (nextIndex < styleValue.Length && Char.IsWhiteSpace(styleValue[nextIndex])) { nextIndex++; } } // Checks if the following character matches to a given word and advances nextIndex // by the word's length in case of success. // Otherwise leaves nextIndex in place (except for possible whitespaces). // Returns true or false depending on success or failure of matching. private static bool ParseWord(string word, string styleValue, ref int nextIndex) { ParseWhiteSpace(styleValue, ref nextIndex); for (int i = 0; i < word.Length; i++) { if (!(nextIndex + i < styleValue.Length && word[i] == styleValue[nextIndex + i])) { return false; } } if (nextIndex + word.Length < styleValue.Length && Char.IsLetterOrDigit(styleValue[nextIndex + word.Length])) { return false; } nextIndex += word.Length; return true; } // CHecks whether the following character sequence matches to one of the given words, // and advances the nextIndex to matched word length. // Returns null in case if there is no match or the word matched. private static string ParseWordEnumeration(string[] words, string styleValue, ref int nextIndex) { for (int i = 0; i < words.Length; i++) { if (ParseWord(words[i], styleValue, ref nextIndex)) { return words[i]; } } return null; } private static void ParseWordEnumeration(string[] words, string styleValue, ref int nextIndex, Hashtable localProperties, string attributeName) { Contract.Requires(attributeName != null); string attributeValue = ParseWordEnumeration(words, styleValue, ref nextIndex); if (attributeValue != null) { localProperties[attributeName] = attributeValue; } } private static string ParseCssSize(string styleValue, ref int nextIndex, bool mustBeNonNegative) { ParseWhiteSpace(styleValue, ref nextIndex); int startIndex = nextIndex; // Parse optional munis sign if (nextIndex < styleValue.Length && styleValue[nextIndex] == '-') { nextIndex++; } if (nextIndex < styleValue.Length && Char.IsDigit(styleValue[nextIndex])) { while (nextIndex < styleValue.Length && (Char.IsDigit(styleValue[nextIndex]) || styleValue[nextIndex] == '.')) { nextIndex++; } string number = styleValue.Substring(startIndex, nextIndex - startIndex); string unit = ParseWordEnumeration(_fontSizeUnits, styleValue, ref nextIndex); if (unit == null) { unit = "px"; // Assuming pixels by default } if (mustBeNonNegative && styleValue[startIndex] == '-') { return "0"; } else { return number + unit; } } return null; } private static void ParseCssSize(string styleValue, ref int nextIndex, Hashtable localValues, string propertyName, bool mustBeNonNegative) { Contract.Requires(propertyName != null); string length = ParseCssSize(styleValue, ref nextIndex, mustBeNonNegative); if (length != null) { localValues[propertyName] = length; } } private static readonly string[] _colors = new string[] { "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown", "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue", "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen", "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen", "darkslateblue", "darkslategray", "darkturquoise", "darkviolet", "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick", "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite", "gold", "goldenrod", "gray", "green", "greenyellow", "honeydew", "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender", "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral", "lightcyan", "lightgoldenrodyellow", "lightgreen", "lightgrey", "lightpink", "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta", "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise", "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin", "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered", "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred", "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", "purple", "red", "rosybrown", "royalblue", "saddlebrown", "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue", "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan", "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white", "whitesmoke", "yellow", "yellowgreen", }; private static readonly string[] _systemColors = new string[] { "activeborder", "activecaption", "appworkspace", "background", "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "captiontext", "graytext", "highlight", "highlighttext", "inactiveborder", "inactivecaption", "inactivecaptiontext", "infobackground", "infotext", "menu", "menutext", "scrollbar", "threeddarkshadow", "threedface", "threedhighlight", "threedlightshadow", "threedshadow", "window", "windowframe", "windowtext", }; private static string ParseCssColor(string styleValue, ref int nextIndex) { // Implement color parsing // rgb(100%,53.5%,10%) // rgb(255,91,26) // #FF5B1A // black | silver | gray | ... | aqua // transparent - for background-color ParseWhiteSpace(styleValue, ref nextIndex); string color = null; if (nextIndex < styleValue.Length) { int startIndex = nextIndex; char character = styleValue[nextIndex]; if (character == '#') { nextIndex++; while (nextIndex < styleValue.Length) { character = Char.ToUpper(styleValue[nextIndex]); if (!('0' <= character && character <= '9' || 'A' <= character && character <= 'F')) { break; } nextIndex++; } if (nextIndex > startIndex + 1) { color = styleValue.Substring(startIndex, nextIndex - startIndex); } } else if (styleValue.Substring(nextIndex, 3).ToLower() == "rbg") { // Implement real rgb() color parsing while (nextIndex < styleValue.Length && styleValue[nextIndex] != ')') { nextIndex++; } if (nextIndex < styleValue.Length) { nextIndex++; // to skip ')' } color = "gray"; // return bogus color } else if (Char.IsLetter(character)) { color = ParseWordEnumeration(_colors, styleValue, ref nextIndex); if (color == null) { color = ParseWordEnumeration(_systemColors, styleValue, ref nextIndex); if (color != null) { // Implement smarter system color converions into real colors color = "black"; } } } } return color; } private static void ParseCssColor(string styleValue, ref int nextIndex, Hashtable localValues, string propertyName) { Contract.Requires(propertyName!=null); string color = ParseCssColor(styleValue, ref nextIndex); if (color != null) { localValues[propertyName] = color; } } // ................................................................. // // Pasring CSS font Property // // ................................................................. // CSS has five font properties: font-family, font-style, font-variant, font-weight, font-size. // An aggregated "font" property lets you specify in one action all the five in combination // with additional line-height property. // // font-family: [<family-name>,]* [<family-name> | <generic-family>] // generic-family: serif | sans-serif | monospace | cursive | fantasy // The list of families sets priorities to choose fonts; // Quotes not allowed around generic-family names // font-style: normal | italic | oblique // font-variant: normal | small-caps // font-weight: normal | bold | bolder | lighter | 100 ... 900 | // Default is "normal", normal==400 // font-size: <absolute-size> | <relative-size> | <length> | <percentage> // absolute-size: xx-small | x-small | small | medium | large | x-large | xx-large // relative-size: larger | smaller // length: <point> | <pica> | <ex> | <em> | <points> | <millimeters> | <centimeters> | <inches> // Default: medium // font: [ <font-style> || <font-variant> || <font-weight ]? <font-size> [ / <line-height> ]? <font-family> private static readonly string[] _fontGenericFamilies = new string[] { "serif", "sans-serif", "monospace", "cursive", "fantasy" }; private static readonly string[] _fontStyles = new string[] { "normal", "italic", "oblique" }; private static readonly string[] _fontVariants = new string[] { "normal", "small-caps" }; private static readonly string[] _fontWeights = new string[] { "normal", "bold", "bolder", "lighter", "100", "200", "300", "400", "500", "600", "700", "800", "900" }; private static readonly string[] _fontAbsoluteSizes = new string[] { "xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large" }; private static readonly string[] _fontRelativeSizes = new string[] { "larger", "smaller" }; private static readonly string[] _fontSizeUnits = new string[] { "px", "mm", "cm", "in", "pt", "pc", "em", "ex", "%" }; // Parses CSS string fontStyle representing a value for css font attribute private static void ParseCssFont(string styleValue, Hashtable localProperties) { int nextIndex = 0; ParseCssFontStyle(styleValue, ref nextIndex, localProperties); ParseCssFontVariant(styleValue, ref nextIndex, localProperties); ParseCssFontWeight(styleValue, ref nextIndex, localProperties); ParseCssSize(styleValue, ref nextIndex, localProperties, "font-size", /*mustBeNonNegative:*/true); ParseWhiteSpace(styleValue, ref nextIndex); if (nextIndex < styleValue.Length && styleValue[nextIndex] == '/') { nextIndex++; ParseCssSize(styleValue, ref nextIndex, localProperties, "line-height", /*mustBeNonNegative:*/true); } ParseCssFontFamily(styleValue, ref nextIndex, localProperties); } private static void ParseCssFontStyle(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_fontStyles, styleValue, ref nextIndex, localProperties, "font-style"); } private static void ParseCssFontVariant(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_fontVariants, styleValue, ref nextIndex, localProperties, "font-variant"); } private static void ParseCssFontWeight(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_fontWeights, styleValue, ref nextIndex, localProperties, "font-weight"); } private static void ParseCssFontFamily(string styleValue, ref int nextIndex, Hashtable localProperties) { string fontFamilyList = null; while (nextIndex < styleValue.Length) { // Try generic-family string fontFamily = ParseWordEnumeration(_fontGenericFamilies, styleValue, ref nextIndex); if (fontFamily == null) { // Try quoted font family name if (nextIndex < styleValue.Length && (styleValue[nextIndex] == '"' || styleValue[nextIndex] == '\'')) { char quote = styleValue[nextIndex]; nextIndex++; int startIndex = nextIndex; while (nextIndex < styleValue.Length && styleValue[nextIndex] != quote) { nextIndex++; } fontFamily = '"' + styleValue.Substring(startIndex, nextIndex - startIndex) + '"'; } if (fontFamily == null) { // Try unquoted font family name int startIndex = nextIndex; while (nextIndex < styleValue.Length && styleValue[nextIndex] != ',' && styleValue[nextIndex] != ';') { nextIndex++; } if (nextIndex > startIndex) { fontFamily = styleValue.Substring(startIndex, nextIndex - startIndex).Trim(); if (fontFamily.Length == 0) { fontFamily = null; } } } } ParseWhiteSpace(styleValue, ref nextIndex); if (nextIndex < styleValue.Length && styleValue[nextIndex] == ',') { nextIndex++; } if (fontFamily != null) { // css font-family can contein a list of names. We only consider the first name from the list. Need a decision what to do with remaining names // fontFamilyList = (fontFamilyList == null) ? fontFamily : fontFamilyList + "," + fontFamily; if (fontFamilyList == null && fontFamily.Length > 0) { if (fontFamily[0] == '"' || fontFamily[0] == '\'') { // Unquote the font family name fontFamily = fontFamily.Substring(1, fontFamily.Length - 2); } else { // Convert generic css family name } fontFamilyList = fontFamily; } } else { break; } } if (fontFamilyList != null) { localProperties["font-family"] = fontFamilyList; } } // ................................................................. // // Pasring CSS list-style Property // // ................................................................. // list-style: [ <list-style-type> || <list-style-position> || <list-style-image> ] private static readonly string[] _listStyleTypes = new string[] { "disc", "circle", "square", "decimal", "lower-roman", "upper-roman", "lower-alpha", "upper-alpha", "none" }; private static readonly string[] _listStylePositions = new string[] { "inside", "outside" }; private static void ParseCssListStyle(string styleValue, Hashtable localProperties) { int nextIndex = 0; while (nextIndex < styleValue.Length) { string listStyleType = ParseCssListStyleType(styleValue, ref nextIndex); if (listStyleType != null) { localProperties["list-style-type"] = listStyleType; } else { string listStylePosition = ParseCssListStylePosition(styleValue, ref nextIndex); if (listStylePosition != null) { localProperties["list-style-position"] = listStylePosition; } else { string listStyleImage = ParseCssListStyleImage(styleValue, ref nextIndex); if (listStyleImage != null) { localProperties["list-style-image"] = listStyleImage; } else { break; } } } } } private static string ParseCssListStyleType(string styleValue, ref int nextIndex) { return ParseWordEnumeration(_listStyleTypes, styleValue, ref nextIndex); } private static string ParseCssListStylePosition(string styleValue, ref int nextIndex) { return ParseWordEnumeration(_listStylePositions, styleValue, ref nextIndex); } private static string ParseCssListStyleImage(string styleValue, ref int nextIndex) { return null; } // ................................................................. // // Pasring CSS text-decorations Property // // ................................................................. private static readonly string[] _textDecorations = new string[] { "none", "underline", "overline", "line-through", "blink" }; private static void ParseCssTextDecoration(string styleValue, ref int nextIndex, Hashtable localProperties) { // Set default text-decorations:none; for (int i = 1; i < _textDecorations.Length; i++) { localProperties["text-decoration-" + _textDecorations[i]] = "false"; } // Parse list of decorations values while (nextIndex < styleValue.Length) { string decoration = ParseWordEnumeration(_textDecorations, styleValue, ref nextIndex); if (decoration == null || decoration == "none") { break; } localProperties["text-decoration-" + decoration] = "true"; } } // ................................................................. // // Pasring CSS text-transform Property // // ................................................................. private static readonly string[] _textTransforms = new string[] { "none", "capitalize", "uppercase", "lowercase" }; private static void ParseCssTextTransform(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_textTransforms, styleValue, ref nextIndex, localProperties, "text-transform"); } // ................................................................. // // Pasring CSS text-align Property // // ................................................................. private static readonly string[] _textAligns = new string[] { "left", "right", "center", "justify" }; private static void ParseCssTextAlign(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_textAligns, styleValue, ref nextIndex, localProperties, "text-align"); } // ................................................................. // // Pasring CSS vertical-align Property // // ................................................................. private static readonly string[] _verticalAligns = new string[] { "baseline", "sub", "super", "top", "text-top", "middle", "bottom", "text-bottom" }; private static void ParseCssVerticalAlign(string styleValue, ref int nextIndex, Hashtable localProperties) { // Parse percentage value for vertical-align style ParseWordEnumeration(_verticalAligns, styleValue, ref nextIndex, localProperties, "vertical-align"); } // ................................................................. // // Pasring CSS float Property // // ................................................................. private static readonly string[] _floats = new string[] { "left", "right", "none" }; private static void ParseCssFloat(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_floats, styleValue, ref nextIndex, localProperties, "float"); } // ................................................................. // // Pasring CSS clear Property // // ................................................................. private static readonly string[] _clears = new string[] { "none", "left", "right", "both" }; private static void ParseCssClear(string styleValue, ref int nextIndex, Hashtable localProperties) { ParseWordEnumeration(_clears, styleValue, ref nextIndex, localProperties, "clear"); } // ................................................................. // // Pasring CSS margin and padding Properties // // ................................................................. // Generic method for parsing any of four-values properties, such as margin, padding, border-width, border-style, border-color private static bool ParseCssRectangleProperty(string styleValue, ref int nextIndex, Hashtable localProperties, string propertyName) { // CSS Spec: // If only one value is set, then the value applies to all four sides; // If two or three values are set, then missinng value(s) are taken fromm the opposite side(s). // The order they are applied is: top/right/bottom/left Debug.Assert(propertyName == "margin" || propertyName == "padding" || propertyName == "border-width" || propertyName == "border-style" || propertyName == "border-color"); string value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true); if (value != null) { localProperties[propertyName + "-top"] = value; localProperties[propertyName + "-bottom"] = value; localProperties[propertyName + "-right"] = value; localProperties[propertyName + "-left"] = value; value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true); if (value != null) { localProperties[propertyName + "-right"] = value; localProperties[propertyName + "-left"] = value; value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true); if (value != null) { localProperties[propertyName + "-bottom"] = value; value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true); if (value != null) { localProperties[propertyName + "-left"] = value; } } } return true; } return false; } // ................................................................. // // Pasring CSS border Properties // // ................................................................. // border: [ <border-width> || <border-style> || <border-color> ] private static void ParseCssBorder(string styleValue, ref int nextIndex, Hashtable localProperties) { while ( ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, "border-width") || ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, "border-style") || ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, "border-color")) { } } // ................................................................. // // Pasring CSS border-style Propertie // // ................................................................. private static readonly string[] _borderStyles = new string[] { "none", "dotted", "dashed", "solid", "double", "groove", "ridge", "inset", "outset" }; private static string ParseCssBorderStyle(string styleValue, ref int nextIndex) { return ParseWordEnumeration(_borderStyles, styleValue, ref nextIndex); } // ................................................................. // // What are these definitions doing here: // // ................................................................. private static string[] _blocks = new string[] { "block", "inline", "list-item", "none" }; // ................................................................. // // Pasring CSS Background Properties // // ................................................................. private static void ParseCssBackground(string styleValue, ref int nextIndex, Hashtable localValues) { // Implement parsing background attribute } } internal class CssStylesheet { // Constructor public CssStylesheet(XmlElement htmlElement) { if (htmlElement != null) { this.DiscoverStyleDefinitions(htmlElement); } } // Recursively traverses an html tree, discovers STYLE elements and creates a style definition table // for further cascading style application public void DiscoverStyleDefinitions(XmlElement htmlElement) { if (htmlElement.LocalName.ToLower() == "link") { return; // Add LINK elements processing for included stylesheets // <LINK href="http://sc.msn.com/global/css/ptnr/orange.css" type=text/css \r\nrel=stylesheet> } if (htmlElement.LocalName.ToLower() != "style") { // This is not a STYLE element. Recurse into it for (XmlNode htmlChildNode = htmlElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling) { if (htmlChildNode is XmlElement) { this.DiscoverStyleDefinitions((XmlElement)htmlChildNode); } } return; } // Add style definitions from this style. // Collect all text from this style definition StringBuilder stylesheetBuffer = new StringBuilder(); for (XmlNode htmlChildNode = htmlElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling) { if (htmlChildNode is XmlText || htmlChildNode is XmlComment) { stylesheetBuffer.Append(RemoveComments(htmlChildNode.Value)); } } // CssStylesheet has the following syntactical structure: // @import declaration; // selector { definition } // where "selector" is one of: ".classname", "tagname" // It can contain comments in the following form: /*...*/ int nextCharacterIndex = 0; while (nextCharacterIndex < stylesheetBuffer.Length) { // Extract selector int selectorStart = nextCharacterIndex; while (nextCharacterIndex < stylesheetBuffer.Length && stylesheetBuffer[nextCharacterIndex] != '{') { // Skip declaration directive starting from @ if (stylesheetBuffer[nextCharacterIndex] == '@') { while (nextCharacterIndex < stylesheetBuffer.Length && stylesheetBuffer[nextCharacterIndex] != ';') { nextCharacterIndex++; } selectorStart = nextCharacterIndex + 1; } nextCharacterIndex++; } if (nextCharacterIndex < stylesheetBuffer.Length) { // Extract definition int definitionStart = nextCharacterIndex; while (nextCharacterIndex < stylesheetBuffer.Length && stylesheetBuffer[nextCharacterIndex] != '}') { nextCharacterIndex++; } // Define a style if (nextCharacterIndex - definitionStart > 2) { this.AddStyleDefinition( stylesheetBuffer.ToString(selectorStart, definitionStart - selectorStart), stylesheetBuffer.ToString(definitionStart + 1, nextCharacterIndex - definitionStart - 2)); } // Skip closing brace if (nextCharacterIndex < stylesheetBuffer.Length) { Debug.Assert(stylesheetBuffer[nextCharacterIndex] == '}'); nextCharacterIndex++; } } } } // Returns a string with all c-style comments replaced by spaces private string RemoveComments(string text) { int commentStart = text.IndexOf("/*"); if (commentStart < 0) { return text; } int commentEnd = text.IndexOf("*/", commentStart + 2); if (commentEnd < 0) { return text.Substring(0, commentStart); } return text.Substring(0, commentStart) + " " + RemoveComments(text.Substring(commentEnd + 2)); } public void AddStyleDefinition(string selector, string definition) { // Notrmalize parameter values selector = selector.Trim().ToLower(); definition = definition.Trim().ToLower(); if (selector.Length == 0 || definition.Length == 0) { return; } if (_styleDefinitions == null) { _styleDefinitions = new List<StyleDefinition>(); } string[] simpleSelectors = selector.Split(','); for (int i = 0; i < simpleSelectors.Length; i++) { string simpleSelector = simpleSelectors[i].Trim(); if (simpleSelector.Length > 0) { _styleDefinitions.Add(new StyleDefinition(simpleSelector, definition)); } } } public string GetStyle(string elementName, List<XmlElement> sourceContext) { Debug.Assert(sourceContext.Count > 0); Debug.Assert(elementName == sourceContext[sourceContext.Count - 1].LocalName); // Add id processing for style selectors if (_styleDefinitions != null) { for (int i = _styleDefinitions.Count - 1; i >= 0; i--) { string selector = _styleDefinitions[i].Selector; string[] selectorLevels = selector.Split(' '); int indexInSelector = selectorLevels.Length - 1; int indexInContext = sourceContext.Count - 1; string selectorLevel = selectorLevels[indexInSelector].Trim(); if (MatchSelectorLevel(selectorLevel, sourceContext[sourceContext.Count - 1])) { return _styleDefinitions[i].Definition; } } } return null; } private bool MatchSelectorLevel(string selectorLevel, XmlElement xmlElement) { if (selectorLevel.Length == 0) { return false; } int indexOfDot = selectorLevel.IndexOf('.'); int indexOfPound = selectorLevel.IndexOf('#'); string selectorClass = null; string selectorId = null; string selectorTag = null; if (indexOfDot >= 0) { if (indexOfDot > 0) { selectorTag = selectorLevel.Substring(0, indexOfDot); } selectorClass = selectorLevel.Substring(indexOfDot + 1); } else if (indexOfPound >= 0) { if (indexOfPound > 0) { selectorTag = selectorLevel.Substring(0, indexOfPound); } selectorId = selectorLevel.Substring(indexOfPound + 1); } else { selectorTag = selectorLevel; } if (selectorTag != null && selectorTag != xmlElement.LocalName) { return false; } if (selectorId != null && HtmlToXamlConverter.GetAttribute(xmlElement, "id") != selectorId) { return false; } if (selectorClass != null && HtmlToXamlConverter.GetAttribute(xmlElement, "class") != selectorClass) { return false; } return true; } private class StyleDefinition { public StyleDefinition(string selector, string definition) { this.Selector = selector; this.Definition = definition; } public string Selector; public string Definition; } private List<StyleDefinition> _styleDefinitions; } }
zzgaminginc-pointofssale
Samba.Services/HtmlConverter/HtmlCssParser.cs
C#
gpl3
47,767
//--------------------------------------------------------------------------- // // File: HtmlLexicalAnalyzer.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // Description: Lexical analyzer for Html-to-Xaml converter // //--------------------------------------------------------------------------- using System; using System.Diagnostics.Contracts; using System.IO; using System.Diagnostics; using System.Text; namespace Samba.Services.HtmlConverter { /// <summary> /// lexical analyzer class /// recognizes tokens as groups of characters separated by arbitrary amounts of whitespace /// also classifies tokens according to type /// </summary> internal class HtmlLexicalAnalyzer { // --------------------------------------------------------------------- // // Constructors // // --------------------------------------------------------------------- #region Constructors /// <summary> /// initializes the _inputStringReader member with the string to be read /// also sets initial values for _nextCharacterCode and _nextTokenType /// </summary> /// <param name="inputTextString"> /// text string to be parsed for xml content /// </param> internal HtmlLexicalAnalyzer(string inputTextString) { Contract.Requires(inputTextString != null); _inputStringReader = new StringReader(inputTextString); _nextCharacterCode = 0; _nextCharacter = ' '; _lookAheadCharacterCode = _inputStringReader.Read(); _lookAheadCharacter = (char)_lookAheadCharacterCode; _previousCharacter = ' '; _ignoreNextWhitespace = true; _nextToken = new StringBuilder(100); _nextTokenType = HtmlTokenType.Text; // read the first character so we have some value for the NextCharacter property this.GetNextCharacter(); } #endregion Constructors // --------------------------------------------------------------------- // // Internal methods // // --------------------------------------------------------------------- #region Internal Methods /// <summary> /// retrieves next recognizable token from input string /// and identifies its type /// if no valid token is found, the output parameters are set to null /// if end of stream is reached without matching any token, token type /// paramter is set to EOF /// </summary> internal void GetNextContentToken() { Debug.Assert(_nextTokenType != HtmlTokenType.EOF); _nextToken.Length = 0; if (this.IsAtEndOfStream) { _nextTokenType = HtmlTokenType.EOF; return; } if (this.IsAtTagStart) { this.GetNextCharacter(); if (this.NextCharacter == '/') { _nextToken.Append("</"); _nextTokenType = HtmlTokenType.ClosingTagStart; // advance this.GetNextCharacter(); _ignoreNextWhitespace = false; // Whitespaces after closing tags are significant } else { _nextTokenType = HtmlTokenType.OpeningTagStart; _nextToken.Append("<"); _ignoreNextWhitespace = true; // Whitespaces after opening tags are insignificant } } else if (this.IsAtDirectiveStart) { // either a comment or CDATA this.GetNextCharacter(); if (_lookAheadCharacter == '[') { // cdata this.ReadDynamicContent(); } else if (_lookAheadCharacter == '-') { this.ReadComment(); } else { // neither a comment nor cdata, should be something like DOCTYPE // skip till the next tag ender this.ReadUnknownDirective(); } } else { // read text content, unless you encounter a tag _nextTokenType = HtmlTokenType.Text; while (!this.IsAtTagStart && !this.IsAtEndOfStream && !this.IsAtDirectiveStart) { if (this.NextCharacter == '<' && !this.IsNextCharacterEntity && _lookAheadCharacter == '?') { // ignore processing directive this.SkipProcessingDirective(); } else { if (this.NextCharacter <= ' ') { // Respect xml:preserve or its equivalents for whitespace processing if (_ignoreNextWhitespace) { // Ignore repeated whitespaces } else { // Treat any control character sequence as one whitespace _nextToken.Append(' '); } _ignoreNextWhitespace = true; // and keep ignoring the following whitespaces } else { _nextToken.Append(this.NextCharacter); _ignoreNextWhitespace = false; } this.GetNextCharacter(); } } } } /// <summary> /// Unconditionally returns a token which is one of: TagEnd, EmptyTagEnd, Name, Atom or EndOfStream /// Does not guarantee token reader advancing. /// </summary> internal void GetNextTagToken() { _nextToken.Length = 0; if (this.IsAtEndOfStream) { _nextTokenType = HtmlTokenType.EOF; return; } this.SkipWhiteSpace(); if (this.NextCharacter == '>' && !this.IsNextCharacterEntity) { // &gt; should not end a tag, so make sure it's not an entity _nextTokenType = HtmlTokenType.TagEnd; _nextToken.Append('>'); this.GetNextCharacter(); } else if (this.NextCharacter == '/' && _lookAheadCharacter == '>') { // could be start of closing of empty tag _nextTokenType = HtmlTokenType.EmptyTagEnd; _nextToken.Append("/>"); this.GetNextCharacter(); this.GetNextCharacter(); _ignoreNextWhitespace = false; // Whitespace after no-scope tags are sifnificant } else if (IsGoodForNameStart(this.NextCharacter)) { _nextTokenType = HtmlTokenType.Name; // starts a name // we allow character entities here // we do not throw exceptions here if end of stream is encountered // just stop and return whatever is in the token // if the parser is not expecting end of file after this it will call // the get next token function and throw an exception while (IsGoodForName(this.NextCharacter) && !this.IsAtEndOfStream) { _nextToken.Append(this.NextCharacter); this.GetNextCharacter(); } } else { // Unexpected type of token for a tag. Reprot one character as Atom, expecting that HtmlParser will ignore it. _nextTokenType = HtmlTokenType.Atom; _nextToken.Append(this.NextCharacter); this.GetNextCharacter(); } } /// <summary> /// Unconditionally returns equal sign token. Even if there is no /// real equal sign in the stream, it behaves as if it were there. /// Does not guarantee token reader advancing. /// </summary> internal void GetNextEqualSignToken() { Debug.Assert(_nextTokenType != HtmlTokenType.EOF); _nextToken.Length = 0; _nextToken.Append('='); _nextTokenType = HtmlTokenType.EqualSign; this.SkipWhiteSpace(); if (this.NextCharacter == '=') { // '=' is not in the list of entities, so no need to check for entities here this.GetNextCharacter(); } } /// <summary> /// Unconditionally returns an atomic value for an attribute /// Even if there is no appropriate token it returns Atom value /// Does not guarantee token reader advancing. /// </summary> internal void GetNextAtomToken() { Debug.Assert(_nextTokenType != HtmlTokenType.EOF); _nextToken.Length = 0; this.SkipWhiteSpace(); _nextTokenType = HtmlTokenType.Atom; if ((this.NextCharacter == '\'' || this.NextCharacter == '"') && !this.IsNextCharacterEntity) { char startingQuote = this.NextCharacter; this.GetNextCharacter(); // Consume all characters between quotes while (!(this.NextCharacter == startingQuote && !this.IsNextCharacterEntity) && !this.IsAtEndOfStream) { _nextToken.Append(this.NextCharacter); this.GetNextCharacter(); } if (this.NextCharacter == startingQuote) { this.GetNextCharacter(); } // complete the quoted value // IE keeps reading until it finds a closing quote or end of file // if end of file, it treats current value as text // if it finds a closing quote at any point within the text, it eats everything between the quotes // however, we could stop when we encounter end of file or an angle bracket of any kind // and assume there was a quote there // so the attribute value may be meaningless but it is never treated as text } else { while (!this.IsAtEndOfStream && !Char.IsWhiteSpace(this.NextCharacter) && this.NextCharacter != '>') { _nextToken.Append(this.NextCharacter); this.GetNextCharacter(); } } } #endregion Internal Methods // --------------------------------------------------------------------- // // Internal Properties // // --------------------------------------------------------------------- #region Internal Properties internal HtmlTokenType NextTokenType { get { return _nextTokenType; } } internal string NextToken { get { return _nextToken.ToString(); } } #endregion Internal Properties // --------------------------------------------------------------------- // // Private methods // // --------------------------------------------------------------------- #region Private Methods /// <summary> /// Advances a reading position by one character code /// and reads the next availbale character from a stream. /// This character becomes available as NextCharacter property. /// </summary> /// <remarks> /// Throws InvalidOperationException if attempted to be called on EndOfStream /// condition. /// </remarks> private void GetNextCharacter() { if (_nextCharacterCode == -1) { throw new InvalidOperationException("GetNextCharacter method called at the end of a stream"); } _previousCharacter = _nextCharacter; _nextCharacter = _lookAheadCharacter; _nextCharacterCode = _lookAheadCharacterCode; // next character not an entity as of now _isNextCharacterEntity = false; this.ReadLookAheadCharacter(); if (_nextCharacter == '&') { if (_lookAheadCharacter == '#') { // numeric entity - parse digits - &#DDDDD; int entityCode; entityCode = 0; this.ReadLookAheadCharacter(); // largest numeric entity is 7 characters for (int i = 0; i < 7 && Char.IsDigit(_lookAheadCharacter); i++) { entityCode = 10 * entityCode + (_lookAheadCharacterCode - (int)'0'); this.ReadLookAheadCharacter(); } if (_lookAheadCharacter == ';') { // correct format - advance this.ReadLookAheadCharacter(); _nextCharacterCode = entityCode; // if this is out of range it will set the character to '?' _nextCharacter = (char)_nextCharacterCode; // as far as we are concerned, this is an entity _isNextCharacterEntity = true; } else { // not an entity, set next character to the current lookahread character // we would have eaten up some digits _nextCharacter = _lookAheadCharacter; _nextCharacterCode = _lookAheadCharacterCode; this.ReadLookAheadCharacter(); _isNextCharacterEntity = false; } } else if (Char.IsLetter(_lookAheadCharacter)) { // entity is written as a string string entity = ""; // maximum length of string entities is 10 characters for (int i = 0; i < 10 && (Char.IsLetter(_lookAheadCharacter) || Char.IsDigit(_lookAheadCharacter)); i++) { entity += _lookAheadCharacter; this.ReadLookAheadCharacter(); } if (_lookAheadCharacter == ';') { // advance this.ReadLookAheadCharacter(); if (HtmlSchema.IsEntity(entity)) { _nextCharacter = HtmlSchema.EntityCharacterValue(entity); _nextCharacterCode = (int)_nextCharacter; _isNextCharacterEntity = true; } else { // just skip the whole thing - invalid entity // move on to the next character _nextCharacter = _lookAheadCharacter; _nextCharacterCode = _lookAheadCharacterCode; this.ReadLookAheadCharacter(); // not an entity _isNextCharacterEntity = false; } } else { // skip whatever we read after the ampersand // set next character and move on _nextCharacter = _lookAheadCharacter; this.ReadLookAheadCharacter(); _isNextCharacterEntity = false; } } } } private void ReadLookAheadCharacter() { if (_lookAheadCharacterCode != -1) { _lookAheadCharacterCode = _inputStringReader.Read(); _lookAheadCharacter = (char)_lookAheadCharacterCode; } } /// <summary> /// skips whitespace in the input string /// leaves the first non-whitespace character available in the NextCharacter property /// this may be the end-of-file character, it performs no checking /// </summary> private void SkipWhiteSpace() { while (true) { if (_nextCharacter == '<' && (_lookAheadCharacter == '?' || _lookAheadCharacter == '!')) { this.GetNextCharacter(); if (_lookAheadCharacter == '[') { // Skip CDATA block and DTDs(?) while (!this.IsAtEndOfStream && !(_previousCharacter == ']' && _nextCharacter == ']' && _lookAheadCharacter == '>')) { this.GetNextCharacter(); } if (_nextCharacter == '>') { this.GetNextCharacter(); } } else { // Skip processing instruction, comments while (!this.IsAtEndOfStream && _nextCharacter != '>') { this.GetNextCharacter(); } if (_nextCharacter == '>') { this.GetNextCharacter(); } } } if (!Char.IsWhiteSpace(this.NextCharacter)) { break; } this.GetNextCharacter(); } } /// <summary> /// checks if a character can be used to start a name /// if this check is true then the rest of the name can be read /// </summary> /// <param name="character"> /// character value to be checked /// </param> /// <returns> /// true if the character can be the first character in a name /// false otherwise /// </returns> private bool IsGoodForNameStart(char character) { return character == '_' || Char.IsLetter(character); } /// <summary> /// checks if a character can be used as a non-starting character in a name /// uses the IsExtender and IsCombiningCharacter predicates to see /// if a character is an extender or a combining character /// </summary> /// <param name="character"> /// character to be checked for validity in a name /// </param> /// <returns> /// true if the character can be a valid part of a name /// </returns> private bool IsGoodForName(char character) { // we are not concerned with escaped characters in names // we assume that character entities are allowed as part of a name return this.IsGoodForNameStart(character) || character == '.' || character == '-' || character == ':' || Char.IsDigit(character) || IsCombiningCharacter(character) || IsExtender(character); } /// <summary> /// identifies a character as being a combining character, permitted in a name /// the list of combining characters in the XML documentation /// </summary> /// <param name="character"> /// character to be checked /// </param> /// <returns> /// true if the character is a combining character, false otherwise /// </returns> private bool IsCombiningCharacter(char character) { return false; } /// <summary> /// identifies a character as being an extender, permitted in a name /// the list of extenders in the XML documentation /// </summary> /// <param name="character"> /// character to be checked /// </param> /// <returns> /// true if the character is an extender, false otherwise /// </returns> private bool IsExtender(char character) { return false; } /// <summary> /// skips dynamic content starting with '<![' and ending with ']>' /// </summary> private void ReadDynamicContent() { // verify that we are at dynamic content, which may include CDATA Debug.Assert(_previousCharacter == '<' && _nextCharacter == '!' && _lookAheadCharacter == '['); // Let's treat this as empty text _nextTokenType = HtmlTokenType.Text; _nextToken.Length = 0; // advance twice, once to get the lookahead character and then to reach the start of the cdata this.GetNextCharacter(); this.GetNextCharacter(); // some directives may start with a <![ and then have some data and they will just end with a ]> // this function is modified to stop at the sequence ]> and not ]]> // this means that CDATA and anything else expressed in their own set of [] within the <! [...]> // directive cannot contain a ]> sequence. However it is doubtful that cdata could contain such // sequence anyway, it probably stops at the first ] while (!(_nextCharacter == ']' && _lookAheadCharacter == '>') && !this.IsAtEndOfStream) { // advance this.GetNextCharacter(); } if (!this.IsAtEndOfStream) { // advance, first to the last > this.GetNextCharacter(); // then advance past it to the next character after processing directive this.GetNextCharacter(); } } /// <summary> /// skips comments starting with '<!-' and ending with '-->' /// NOTE: 10/06/2004: processing changed, will now skip anything starting with /// the "<!-" sequence and ending in "!>" or "->", because in practice many html pages do not /// use the full comment specifying conventions /// </summary> private void ReadComment() { // verify that we are at a comment Debug.Assert(_previousCharacter == '<' && _nextCharacter == '!' && _lookAheadCharacter == '-'); // Initialize a token _nextTokenType = HtmlTokenType.Comment; _nextToken.Length = 0; // advance to the next character, so that to be at the start of comment value this.GetNextCharacter(); // get first '-' this.GetNextCharacter(); // get second '-' this.GetNextCharacter(); // get first character of comment content while (true) { // Read text until end of comment // Note that in many actual html pages comments end with "!>" (while xml standard is "-->") while (!this.IsAtEndOfStream && !(_nextCharacter == '-' && _lookAheadCharacter == '-' || _nextCharacter == '!' && _lookAheadCharacter == '>')) { _nextToken.Append(this.NextCharacter); this.GetNextCharacter(); } // Finish comment reading this.GetNextCharacter(); if (_previousCharacter == '-' && _nextCharacter == '-' && _lookAheadCharacter == '>') { // Standard comment end. Eat it and exit the loop this.GetNextCharacter(); // get '>' break; } else if (_previousCharacter == '!' && _nextCharacter == '>') { // Nonstandard but possible comment end - '!>'. Exit the loop break; } else { // Not an end. Save character and continue continue reading _nextToken.Append(_previousCharacter); continue; } } // Read end of comment combination if (_nextCharacter == '>') { this.GetNextCharacter(); } } /// <summary> /// skips past unknown directives that start with "<!" but are not comments or Cdata /// ignores content of such directives until the next ">" character /// applies to directives such as DOCTYPE, etc that we do not presently support /// </summary> private void ReadUnknownDirective() { // verify that we are at an unknown directive Debug.Assert(_previousCharacter == '<' && _nextCharacter == '!' && !(_lookAheadCharacter == '-' || _lookAheadCharacter == '[')); // Let's treat this as empty text _nextTokenType = HtmlTokenType.Text; _nextToken.Length = 0; // advance to the next character this.GetNextCharacter(); // skip to the first tag end we find while (!(_nextCharacter == '>' && !IsNextCharacterEntity) && !this.IsAtEndOfStream) { this.GetNextCharacter(); } if (!this.IsAtEndOfStream) { // advance past the tag end this.GetNextCharacter(); } } /// <summary> /// skips processing directives starting with the characters '<?' and ending with '?>' /// NOTE: 10/14/2004: IE also ends processing directives with a />, so this function is /// being modified to recognize that condition as well /// </summary> private void SkipProcessingDirective() { // verify that we are at a processing directive Debug.Assert(_nextCharacter == '<' && _lookAheadCharacter == '?'); // advance twice, once to get the lookahead character and then to reach the start of the drective this.GetNextCharacter(); this.GetNextCharacter(); while (!((_nextCharacter == '?' || _nextCharacter == '/') && _lookAheadCharacter == '>') && !this.IsAtEndOfStream) { // advance // we don't need to check for entities here because '?' is not an entity // and even though > is an entity there is no entity processing when reading lookahead character this.GetNextCharacter(); } if (!this.IsAtEndOfStream) { // advance, first to the last > this.GetNextCharacter(); // then advance past it to the next character after processing directive this.GetNextCharacter(); } } #endregion Private Methods // --------------------------------------------------------------------- // // Private Properties // // --------------------------------------------------------------------- #region Private Properties private char NextCharacter { get { return _nextCharacter; } } private bool IsAtEndOfStream { get { return _nextCharacterCode == -1; } } private bool IsAtTagStart { get { return _nextCharacter == '<' && (_lookAheadCharacter == '/' || IsGoodForNameStart(_lookAheadCharacter)) && !_isNextCharacterEntity; } } private bool IsAtTagEnd { // check if at end of empty tag or regular tag get { return (_nextCharacter == '>' || (_nextCharacter == '/' && _lookAheadCharacter == '>')) && !_isNextCharacterEntity; } } private bool IsAtDirectiveStart { get { return (_nextCharacter == '<' && _lookAheadCharacter == '!' && !this.IsNextCharacterEntity); } } private bool IsNextCharacterEntity { // check if next character is an entity get { return _isNextCharacterEntity; } } #endregion Private Properties // --------------------------------------------------------------------- // // Private Fields // // --------------------------------------------------------------------- #region Private Fields // string reader which will move over input text private StringReader _inputStringReader; // next character code read from input that is not yet part of any token // and the character it represents private int _nextCharacterCode; private char _nextCharacter; private int _lookAheadCharacterCode; private char _lookAheadCharacter; private char _previousCharacter; private bool _ignoreNextWhitespace; private bool _isNextCharacterEntity; // store token and type in local variables before copying them to output parameters StringBuilder _nextToken; HtmlTokenType _nextTokenType; #endregion Private Fields } }
zzgaminginc-pointofssale
Samba.Services/HtmlConverter/HtmlLexicalAnalyzer.cs
C#
gpl3
31,206
//--------------------------------------------------------------------------- // // File: HtmlXamlConverter.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // Description: Prototype for Html - Xaml conversion // //--------------------------------------------------------------------------- using System; using System.Diagnostics.Contracts; using System.Xml; using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Windows; using System.Windows.Documents; namespace Samba.Services.HtmlConverter { // DependencyProperty // TextElement /// <summary> /// HtmlToXamlConverter is a static class that takes an HTML string /// and converts it into XAML /// </summary> public static class HtmlToXamlConverter { // --------------------------------------------------------------------- // // Internal Methods // // --------------------------------------------------------------------- #region Internal Methods /// <summary> /// Converts an html string into xaml string. /// </summary> /// <param name="htmlString"> /// Input html which may be badly formated xml. /// </param> /// <param name="asFlowDocument"> /// true indicates that we need a FlowDocument as a root element; /// false means that Section or Span elements will be used /// dependeing on StartFragment/EndFragment comments locations. /// </param> /// <returns> /// Well-formed xml representing XAML equivalent for the input html string. /// </returns> public static string ConvertHtmlToXaml(string htmlString, bool asFlowDocument) { // Create well-formed Xml from Html string XmlElement htmlElement = HtmlParser.ParseHtml(htmlString); // Decide what name to use as a root string rootElementName = asFlowDocument ? HtmlToXamlConverter.Xaml_FlowDocument : HtmlToXamlConverter.Xaml_Section; // Create an XmlDocument for generated xaml XmlDocument xamlTree = new XmlDocument(); XmlElement xamlFlowDocumentElement = xamlTree.CreateElement(null, rootElementName, _xamlNamespace); // Extract style definitions from all STYLE elements in the document CssStylesheet stylesheet = new CssStylesheet(htmlElement); // Source context is a stack of all elements - ancestors of a parentElement List<XmlElement> sourceContext = new List<XmlElement>(10); // Clear fragment parent InlineFragmentParentElement = null; // convert root html element AddBlock(xamlFlowDocumentElement, htmlElement, new Hashtable(), stylesheet, sourceContext); // In case if the selected fragment is inline, extract it into a separate Span wrapper if (!asFlowDocument) { xamlFlowDocumentElement = ExtractInlineFragment(xamlFlowDocumentElement); } // Return a string representing resulting Xaml xamlFlowDocumentElement.SetAttribute("xml:space", "preserve"); string xaml = xamlFlowDocumentElement.OuterXml; return xaml; } /// <summary> /// Returns a value for an attribute by its name (ignoring casing) /// </summary> /// <param name="element"> /// XmlElement in which we are trying to find the specified attribute /// </param> /// <param name="attributeName"> /// String representing the attribute name to be searched for /// </param> /// <returns></returns> public static string GetAttribute(XmlElement element, string attributeName) { attributeName = attributeName.ToLower(); for (int i = 0; i < element.Attributes.Count; i++) { if (element.Attributes[i].Name.ToLower() == attributeName) { return element.Attributes[i].Value; } } return null; } /// <summary> /// Returns string extracted from quotation marks /// </summary> /// <param name="value"> /// String representing value enclosed in quotation marks /// </param> internal static string UnQuote(string value) { Contract.Requires(0 <= (value.Length - 2)); if (value.StartsWith("\"") && value.EndsWith("\"") || value.StartsWith("'") && value.EndsWith("'")) { value = value.Substring(1, value.Length - 2).Trim(); } return value; } #endregion Internal Methods // --------------------------------------------------------------------- // // Private Methods // // --------------------------------------------------------------------- #region Private Methods /// <summary> /// Analyzes the given htmlElement expecting it to be converted /// into some of xaml Block elements and adds the converted block /// to the children collection of xamlParentElement. /// /// Analyzes the given XmlElement htmlElement, recognizes it as some HTML element /// and adds it as a child to a xamlParentElement. /// In some cases several following siblings of the given htmlElement /// will be consumed too (e.g. LIs encountered without wrapping UL/OL, /// which must be collected together and wrapped into one implicit List element). /// </summary> /// <param name="xamlParentElement"> /// Parent xaml element, to which new converted element will be added /// </param> /// <param name="htmlElement"> /// Source html element subject to convert to xaml. /// </param> /// <param name="inheritedProperties"> /// Properties inherited from an outer context. /// </param> /// <param name="stylesheet"></param> /// <param name="sourceContext"></param> /// <returns> /// Last processed html node. Normally it should be the same htmlElement /// as was passed as a paramater, but in some irregular cases /// it could one of its following siblings. /// The caller must use this node to get to next sibling from it. /// </returns> private static XmlNode AddBlock(XmlElement xamlParentElement, XmlNode htmlNode, Hashtable inheritedProperties, CssStylesheet stylesheet, List<XmlElement> sourceContext) { if (htmlNode is XmlComment) { DefineInlineFragmentParent((XmlComment)htmlNode, /*xamlParentElement:*/null); } else if (htmlNode is XmlText) { htmlNode = AddImplicitParagraph(xamlParentElement, htmlNode, inheritedProperties, stylesheet, sourceContext); } else if (htmlNode is XmlElement) { // Identify element name XmlElement htmlElement = (XmlElement)htmlNode; string htmlElementName = htmlElement.LocalName; // Keep the name case-sensitive to check xml names string htmlElementNamespace = htmlElement.NamespaceURI; if (htmlElementNamespace != HtmlParser.XhtmlNamespace) { // Non-html element. skip it // Isn't it too agressive? What if this is just an error in html tag name? // which may produce some garbage though coming from xml fragments. return htmlElement; } // Put source element to the stack sourceContext.Add(htmlElement); // Convert the name to lowercase, because html elements are case-insensitive htmlElementName = htmlElementName.ToLower(); // Switch to an appropriate kind of processing depending on html element name switch (htmlElementName) { // Sections: case "html": case "body": case "div": case "form": // not a block according to xhtml spec case "pre": // Renders text in a fixed-width font case "blockquote": case "caption": case "center": case "cite": AddSection(xamlParentElement, htmlElement, inheritedProperties, stylesheet, sourceContext); break; // Paragraphs: case "p": case "h1": case "h2": case "h3": case "h4": case "h5": case "h6": case "nsrtitle": case "textarea": case "dd": // ??? case "dl": // ??? case "dt": // ??? case "tt": // ??? AddParagraph(xamlParentElement, htmlElement, inheritedProperties, stylesheet, sourceContext); break; case "ol": case "ul": case "dir": // treat as UL element case "menu": // treat as UL element // List element conversion AddList(xamlParentElement, htmlElement, inheritedProperties, stylesheet, sourceContext); break; case "li": // LI outside of OL/UL // Collect all sibling LIs, wrap them into a List and then proceed with the element following the last of LIs htmlNode = AddOrphanListItems(xamlParentElement, htmlElement, inheritedProperties, stylesheet, sourceContext); break; case "img": AddImage(xamlParentElement, htmlElement, inheritedProperties, stylesheet, sourceContext); break; case "table": // hand off to table parsing function which will perform special table syntax checks AddTable(xamlParentElement, htmlElement, inheritedProperties, stylesheet, sourceContext); break; case "tbody": case "tfoot": case "thead": case "tr": case "td": case "th": // Table stuff without table wrapper // parent element is NOT a table. If the parent element is a table they can be processed normally. // we need to compare against the parent element here, we can't just break on a switch goto default; // Thus we will skip this element as unknown, but still recurse into it. case "style": // We already pre-processed all style elements. Ignore it now case "meta": case "head": case "title": case "script": // Ignore these elements break; default: // Wrap a sequence of inlines into an implicit paragraph htmlNode = AddImplicitParagraph(xamlParentElement, htmlElement, inheritedProperties, stylesheet, sourceContext); break; } // Remove the element from the stack Debug.Assert(sourceContext.Count > 0 && sourceContext[sourceContext.Count - 1] == htmlElement); sourceContext.RemoveAt(sourceContext.Count - 1); } // Return last processed node return htmlNode; } // ............................................................. // // Line Breaks // // ............................................................. private static void AddBreak(XmlElement xamlParentElement, string htmlElementName) { // Create new xaml element corresponding to this html element XmlElement xamlLineBreak = xamlParentElement.OwnerDocument.CreateElement(/*prefix:*/null, /*localName:*/HtmlToXamlConverter.Xaml_LineBreak, _xamlNamespace); xamlParentElement.AppendChild(xamlLineBreak); if (htmlElementName == "hr") { XmlText xamlHorizontalLine = xamlParentElement.OwnerDocument.CreateTextNode("----------------------"); xamlParentElement.AppendChild(xamlHorizontalLine); xamlLineBreak = xamlParentElement.OwnerDocument.CreateElement(/*prefix:*/null, /*localName:*/HtmlToXamlConverter.Xaml_LineBreak, _xamlNamespace); xamlParentElement.AppendChild(xamlLineBreak); } } // ............................................................. // // Text Flow Elements // // ............................................................. /// <summary> /// Generates Section or Paragraph element from DIV depending whether it contains any block elements or not /// </summary> /// <param name="xamlParentElement"> /// XmlElement representing Xaml parent to which the converted element should be added /// </param> /// <param name="htmlElement"> /// XmlElement representing Html element to be converted /// </param> /// <param name="inheritedProperties"> /// properties inherited from parent context /// </param> /// <param name="stylesheet"></param> /// <param name="sourceContext"></param> /// true indicates that a content added by this call contains at least one block element /// </param> private static void AddSection(XmlElement xamlParentElement, XmlElement htmlElement, Hashtable inheritedProperties, CssStylesheet stylesheet, List<XmlElement> sourceContext) { // Analyze the content of htmlElement to decide what xaml element to choose - Section or Paragraph. // If this Div has at least one block child then we need to use Section, otherwise use Paragraph bool htmlElementContainsBlocks = false; for (XmlNode htmlChildNode = htmlElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling) { if (htmlChildNode is XmlElement) { string htmlChildName = ((XmlElement)htmlChildNode).LocalName.ToLower(); if (HtmlSchema.IsBlockElement(htmlChildName)) { htmlElementContainsBlocks = true; break; } } } if (!htmlElementContainsBlocks) { // The Div does not contain any block elements, so we can treat it as a Paragraph AddParagraph(xamlParentElement, htmlElement, inheritedProperties, stylesheet, sourceContext); } else { // The Div has some nested blocks, so we treat it as a Section // Create currentProperties as a compilation of local and inheritedProperties, set localProperties Hashtable localProperties; Hashtable currentProperties = GetElementProperties(htmlElement, inheritedProperties, out localProperties, stylesheet, sourceContext); // Create a XAML element corresponding to this html element XmlElement xamlElement = xamlParentElement.OwnerDocument.CreateElement(/*prefix:*/null, /*localName:*/HtmlToXamlConverter.Xaml_Section, _xamlNamespace); ApplyLocalProperties(xamlElement, localProperties, /*isBlock:*/true); // Decide whether we can unwrap this element as not having any formatting significance. if (!xamlElement.HasAttributes) { // This elements is a group of block elements whitout any additional formatting. // We can add blocks directly to xamlParentElement and avoid // creating unnecessary Sections nesting. xamlElement = xamlParentElement; } // Recurse into element subtree for (XmlNode htmlChildNode = htmlElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode != null ? htmlChildNode.NextSibling : null) { htmlChildNode = AddBlock(xamlElement, htmlChildNode, currentProperties, stylesheet, sourceContext); } // Add the new element to the parent. if (xamlElement != xamlParentElement) { xamlParentElement.AppendChild(xamlElement); } } } /// <summary> /// Generates Paragraph element from P, H1-H7, Center etc. /// </summary> /// <param name="xamlParentElement"> /// XmlElement representing Xaml parent to which the converted element should be added /// </param> /// <param name="htmlElement"> /// XmlElement representing Html element to be converted /// </param> /// <param name="inheritedProperties"> /// properties inherited from parent context /// </param> /// <param name="stylesheet"></param> /// <param name="sourceContext"></param> /// true indicates that a content added by this call contains at least one block element /// </param> private static void AddParagraph(XmlElement xamlParentElement, XmlElement htmlElement, Hashtable inheritedProperties, CssStylesheet stylesheet, List<XmlElement> sourceContext) { // Create currentProperties as a compilation of local and inheritedProperties, set localProperties Hashtable localProperties; Hashtable currentProperties = GetElementProperties(htmlElement, inheritedProperties, out localProperties, stylesheet, sourceContext); // Create a XAML element corresponding to this html element XmlElement xamlElement = xamlParentElement.OwnerDocument.CreateElement(/*prefix:*/null, /*localName:*/HtmlToXamlConverter.Xaml_Paragraph, _xamlNamespace); ApplyLocalProperties(xamlElement, localProperties, /*isBlock:*/true); // Recurse into element subtree for (XmlNode htmlChildNode = htmlElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling) { AddInline(xamlElement, htmlChildNode, currentProperties, stylesheet, sourceContext); } // Add the new element to the parent. xamlParentElement.AppendChild(xamlElement); } /// <summary> /// Creates a Paragraph element and adds all nodes starting from htmlNode /// converted to appropriate Inlines. /// </summary> /// <param name="xamlParentElement"> /// XmlElement representing Xaml parent to which the converted element should be added /// </param> /// <param name="htmlNode"> /// XmlNode starting a collection of implicitly wrapped inlines. /// </param> /// <param name="inheritedProperties"> /// properties inherited from parent context /// </param> /// <param name="stylesheet"></param> /// <param name="sourceContext"></param> /// true indicates that a content added by this call contains at least one block element /// </param> /// <returns> /// The last htmlNode added to the implicit paragraph /// </returns> private static XmlNode AddImplicitParagraph(XmlElement xamlParentElement, XmlNode htmlNode, Hashtable inheritedProperties, CssStylesheet stylesheet, List<XmlElement> sourceContext) { // Collect all non-block elements and wrap them into implicit Paragraph XmlElement xamlParagraph = xamlParentElement.OwnerDocument.CreateElement(/*prefix:*/null, /*localName:*/HtmlToXamlConverter.Xaml_Paragraph, _xamlNamespace); XmlNode lastNodeProcessed = null; while (htmlNode != null) { if (htmlNode is XmlComment) { DefineInlineFragmentParent((XmlComment)htmlNode, /*xamlParentElement:*/null); } else if (htmlNode is XmlText) { if (htmlNode.Value.Trim().Length > 0) { AddTextRun(xamlParagraph, htmlNode.Value); } } else if (htmlNode is XmlElement) { string htmlChildName = ((XmlElement)htmlNode).LocalName.ToLower(); if (HtmlSchema.IsBlockElement(htmlChildName)) { // The sequence of non-blocked inlines ended. Stop implicit loop here. break; } else { AddInline(xamlParagraph, (XmlElement)htmlNode, inheritedProperties, stylesheet, sourceContext); } } // Store last processed node to return it at the end lastNodeProcessed = htmlNode; htmlNode = htmlNode.NextSibling; } // Add the Paragraph to the parent // If only whitespaces and commens have been encountered, // then we have nothing to add in implicit paragraph; forget it. if (xamlParagraph.FirstChild != null) { xamlParentElement.AppendChild(xamlParagraph); } // Need to return last processed node return lastNodeProcessed; } // ............................................................. // // Inline Elements // // ............................................................. private static void AddInline(XmlElement xamlParentElement, XmlNode htmlNode, Hashtable inheritedProperties, CssStylesheet stylesheet, List<XmlElement> sourceContext) { if (htmlNode is XmlComment) { DefineInlineFragmentParent((XmlComment)htmlNode, xamlParentElement); } else if (htmlNode is XmlText) { AddTextRun(xamlParentElement, htmlNode.Value); } else if (htmlNode is XmlElement) { XmlElement htmlElement = (XmlElement)htmlNode; // Check whether this is an html element if (htmlElement.NamespaceURI != HtmlParser.XhtmlNamespace) { return; // Skip non-html elements } // Identify element name string htmlElementName = htmlElement.LocalName.ToLower(); // Put source element to the stack sourceContext.Add(htmlElement); switch (htmlElementName) { case "a": AddHyperlink(xamlParentElement, htmlElement, inheritedProperties, stylesheet, sourceContext); break; case "img": AddImage(xamlParentElement, htmlElement, inheritedProperties, stylesheet, sourceContext); break; case "br": case "hr": AddBreak(xamlParentElement, htmlElementName); break; default: if (HtmlSchema.IsInlineElement(htmlElementName) || HtmlSchema.IsBlockElement(htmlElementName)) { // but if it happens to be here, we will treat it as a Span. AddSpanOrRun(xamlParentElement, htmlElement, inheritedProperties, stylesheet, sourceContext); } break; } // Ignore all other elements non-(block/inline/image) // Remove the element from the stack Debug.Assert(sourceContext.Count > 0 && sourceContext[sourceContext.Count - 1] == htmlElement); sourceContext.RemoveAt(sourceContext.Count - 1); } } private static void AddSpanOrRun(XmlElement xamlParentElement, XmlElement htmlElement, Hashtable inheritedProperties, CssStylesheet stylesheet, List<XmlElement> sourceContext) { // Decide what XAML element to use for this inline element. // Check whether it contains any nested inlines bool elementHasChildren = false; for (XmlNode htmlNode = htmlElement.FirstChild; htmlNode != null; htmlNode = htmlNode.NextSibling) { if (htmlNode is XmlElement) { string htmlChildName = ((XmlElement)htmlNode).LocalName.ToLower(); if (HtmlSchema.IsInlineElement(htmlChildName) || HtmlSchema.IsBlockElement(htmlChildName) || htmlChildName == "img" || htmlChildName == "br" || htmlChildName == "hr") { elementHasChildren = true; break; } } } string xamlElementName = elementHasChildren ? HtmlToXamlConverter.Xaml_Span : HtmlToXamlConverter.Xaml_Run; // Create currentProperties as a compilation of local and inheritedProperties, set localProperties Hashtable localProperties; Hashtable currentProperties = GetElementProperties(htmlElement, inheritedProperties, out localProperties, stylesheet, sourceContext); // Create a XAML element corresponding to this html element XmlElement xamlElement = xamlParentElement.OwnerDocument.CreateElement(/*prefix:*/null, /*localName:*/xamlElementName, _xamlNamespace); ApplyLocalProperties(xamlElement, localProperties, /*isBlock:*/false); // Recurse into element subtree for (XmlNode htmlChildNode = htmlElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling) { AddInline(xamlElement, htmlChildNode, currentProperties, stylesheet, sourceContext); } // Add the new element to the parent. xamlParentElement.AppendChild(xamlElement); } // Adds a text run to a xaml tree private static void AddTextRun(XmlElement xamlElement, string textData) { // Remove control characters for (int i = 0; i < textData.Length; i++) { if (Char.IsControl(textData[i])) { textData = textData.Remove(i--, 1); // decrement i to compensate for character removal } } // Replace No-Breaks by spaces (160 is a code of &nbsp; entity in html) // This is a work around the bugg in Avalon which does not render nbsp. textData = textData.Replace((char)160, ' '); if (textData.Length > 0) { xamlElement.AppendChild(xamlElement.OwnerDocument.CreateTextNode(textData)); } } private static void AddHyperlink(XmlElement xamlParentElement, XmlElement htmlElement, Hashtable inheritedProperties, CssStylesheet stylesheet, List<XmlElement> sourceContext) { // Convert href attribute into NavigateUri and TargetName string href = GetAttribute(htmlElement, "href"); if (href == null) { // When href attribute is missing - ignore the hyperlink AddSpanOrRun(xamlParentElement, htmlElement, inheritedProperties, stylesheet, sourceContext); } else { // Create currentProperties as a compilation of local and inheritedProperties, set localProperties Hashtable localProperties; Hashtable currentProperties = GetElementProperties(htmlElement, inheritedProperties, out localProperties, stylesheet, sourceContext); // Create a XAML element corresponding to this html element XmlElement xamlElement = xamlParentElement.OwnerDocument.CreateElement(/*prefix:*/null, /*localName:*/HtmlToXamlConverter.Xaml_Hyperlink, _xamlNamespace); ApplyLocalProperties(xamlElement, localProperties, /*isBlock:*/false); string[] hrefParts = href.Split(new char[] { '#' }); if (hrefParts.Length > 0 && hrefParts[0].Trim().Length > 0) { xamlElement.SetAttribute(HtmlToXamlConverter.Xaml_Hyperlink_NavigateUri, hrefParts[0].Trim()); } if (hrefParts.Length == 2 && hrefParts[1].Trim().Length > 0) { xamlElement.SetAttribute(HtmlToXamlConverter.Xaml_Hyperlink_TargetName, hrefParts[1].Trim()); } // Recurse into element subtree for (XmlNode htmlChildNode = htmlElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling) { AddInline(xamlElement, htmlChildNode, currentProperties, stylesheet, sourceContext); } // Add the new element to the parent. xamlParentElement.AppendChild(xamlElement); } } // Stores a parent xaml element for the case when selected fragment is inline. private static XmlElement InlineFragmentParentElement; // Called when html comment is encountered to store a parent element // for the case when the fragment is inline - to extract it to a separate // Span wrapper after the conversion. private static void DefineInlineFragmentParent(XmlComment htmlComment, XmlElement xamlParentElement) { if (htmlComment.Value == "StartFragment") { InlineFragmentParentElement = xamlParentElement; } else if (htmlComment.Value == "EndFragment") { if (InlineFragmentParentElement == null && xamlParentElement != null) { // Normally this cannot happen if comments produced by correct copying code // in Word or IE, but when it is produced manually then fragment boundary // markers can be inconsistent. In this case StartFragment takes precedence, // but if it is not set, then we get the value from EndFragment marker. InlineFragmentParentElement = xamlParentElement; } } } // Extracts a content of an element stored as InlineFragmentParentElement // into a separate Span wrapper. // the fragment is marked within private static XmlElement ExtractInlineFragment(XmlElement xamlFlowDocumentElement) { if (InlineFragmentParentElement != null) { if (InlineFragmentParentElement.LocalName == HtmlToXamlConverter.Xaml_Span) { xamlFlowDocumentElement = InlineFragmentParentElement; } else { xamlFlowDocumentElement = xamlFlowDocumentElement.OwnerDocument.CreateElement(/*prefix:*/null, /*localName:*/HtmlToXamlConverter.Xaml_Span, _xamlNamespace); while (InlineFragmentParentElement.FirstChild != null) { XmlNode copyNode = InlineFragmentParentElement.FirstChild; InlineFragmentParentElement.RemoveChild(copyNode); xamlFlowDocumentElement.AppendChild(copyNode); } } } return xamlFlowDocumentElement; } // ............................................................. // // Images // // ............................................................. private static void AddImage(XmlElement xamlParentElement, XmlElement htmlElement, Hashtable inheritedProperties, CssStylesheet stylesheet, List<XmlElement> sourceContext) { // Implement images } // ............................................................. // // Lists // // ............................................................. /// <summary> /// Converts Html ul or ol element into Xaml list element. During conversion if the ul/ol element has any children /// that are not li elements, they are ignored and not added to the list element /// </summary> /// <param name="xamlParentElement"> /// XmlElement representing Xaml parent to which the converted element should be added /// </param> /// <param name="htmlListElement"> /// XmlElement representing Html ul/ol element to be converted /// </param> /// <param name="inheritedProperties"> /// properties inherited from parent context /// </param> /// <param name="stylesheet"></param> /// <param name="sourceContext"></param> private static void AddList(XmlElement xamlParentElement, XmlElement htmlListElement, Hashtable inheritedProperties, CssStylesheet stylesheet, List<XmlElement> sourceContext) { string htmlListElementName = htmlListElement.LocalName.ToLower(); Hashtable localProperties; Hashtable currentProperties = GetElementProperties(htmlListElement, inheritedProperties, out localProperties, stylesheet, sourceContext); // Create Xaml List element XmlElement xamlListElement = xamlParentElement.OwnerDocument.CreateElement(null, Xaml_List, _xamlNamespace); // Set default list markers if (htmlListElementName == "ol") { // Ordered list xamlListElement.SetAttribute(HtmlToXamlConverter.Xaml_List_MarkerStyle, Xaml_List_MarkerStyle_Decimal); } else { // Unordered list - all elements other than OL treated as unordered lists xamlListElement.SetAttribute(HtmlToXamlConverter.Xaml_List_MarkerStyle, Xaml_List_MarkerStyle_Disc); } // Apply local properties to list to set marker attribute if specified ApplyLocalProperties(xamlListElement, localProperties, /*isBlock:*/true); // Recurse into list subtree for (XmlNode htmlChildNode = htmlListElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling) { if (htmlChildNode is XmlElement && htmlChildNode.LocalName.ToLower() == "li") { sourceContext.Add((XmlElement)htmlChildNode); AddListItem(xamlListElement, (XmlElement)htmlChildNode, currentProperties, stylesheet, sourceContext); Debug.Assert(sourceContext.Count > 0 && sourceContext[sourceContext.Count - 1] == htmlChildNode); sourceContext.RemoveAt(sourceContext.Count - 1); } else { // Not an li element. Add it to previous ListBoxItem // We need to append the content to the end // of a previous list item. } } // Add the List element to xaml tree - if it is not empty if (xamlListElement.HasChildNodes) { xamlParentElement.AppendChild(xamlListElement); } } /// <summary> /// If li items are found without a parent ul/ol element in Html string, creates xamlListElement as their parent and adds /// them to it. If the previously added node to the same xamlParentElement was a List, adds the elements to that list. /// Otherwise, we create a new xamlListElement and add them to it. Elements are added as long as li elements appear sequentially. /// The first non-li or text node stops the addition. /// </summary> /// <param name="xamlParentElement"> /// Parent element for the list /// </param> /// <param name="htmlLIElement"> /// Start Html li element without parent list /// </param> /// <param name="inheritedProperties"> /// Properties inherited from parent context /// </param> /// <returns> /// XmlNode representing the first non-li node in the input after one or more li's have been processed. /// </returns> private static XmlElement AddOrphanListItems(XmlElement xamlParentElement, XmlElement htmlLIElement, Hashtable inheritedProperties, CssStylesheet stylesheet, List<XmlElement> sourceContext) { Debug.Assert(htmlLIElement.LocalName.ToLower() == "li"); XmlElement lastProcessedListItemElement = null; // Find out the last element attached to the xamlParentElement, which is the previous sibling of this node XmlNode xamlListItemElementPreviousSibling = xamlParentElement.LastChild; XmlElement xamlListElement; if (xamlListItemElementPreviousSibling != null && xamlListItemElementPreviousSibling.LocalName == Xaml_List) { // Previously added Xaml element was a list. We will add the new li to it xamlListElement = (XmlElement)xamlListItemElementPreviousSibling; } else { // No list element near. Create our own. xamlListElement = xamlParentElement.OwnerDocument.CreateElement(null, Xaml_List, _xamlNamespace); xamlParentElement.AppendChild(xamlListElement); } XmlNode htmlChildNode = htmlLIElement; string htmlChildNodeName = htmlChildNode == null ? null : htmlChildNode.LocalName.ToLower(); // Current element properties missed here. //currentProperties = GetElementProperties(htmlLIElement, inheritedProperties, out localProperties, stylesheet); // Add li elements to the parent xamlListElement we created as long as they appear sequentially // Use properties inherited from xamlParentElement for context while (htmlChildNode != null && htmlChildNodeName == "li") { AddListItem(xamlListElement, (XmlElement)htmlChildNode, inheritedProperties, stylesheet, sourceContext); lastProcessedListItemElement = (XmlElement)htmlChildNode; htmlChildNode = htmlChildNode.NextSibling; htmlChildNodeName = htmlChildNode == null ? null : htmlChildNode.LocalName.ToLower(); } return lastProcessedListItemElement; } /// <summary> /// Converts htmlLIElement into Xaml ListItem element, and appends it to the parent xamlListElement /// </summary> /// <param name="xamlListElement"> /// XmlElement representing Xaml List element to which the converted td/th should be added /// </param> /// <param name="htmlLIElement"> /// XmlElement representing Html li element to be converted /// </param> /// <param name="inheritedProperties"> /// Properties inherited from parent context /// </param> private static void AddListItem(XmlElement xamlListElement, XmlElement htmlLIElement, Hashtable inheritedProperties, CssStylesheet stylesheet, List<XmlElement> sourceContext) { // Parameter validation Debug.Assert(xamlListElement != null); Debug.Assert(xamlListElement.LocalName == Xaml_List); Debug.Assert(htmlLIElement != null); Debug.Assert(htmlLIElement.LocalName.ToLower() == "li"); Debug.Assert(inheritedProperties != null); Hashtable localProperties; Hashtable currentProperties = GetElementProperties(htmlLIElement, inheritedProperties, out localProperties, stylesheet, sourceContext); XmlElement xamlListItemElement = xamlListElement.OwnerDocument.CreateElement(null, Xaml_ListItem, _xamlNamespace); // Process children of the ListItem for (XmlNode htmlChildNode = htmlLIElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode != null ? htmlChildNode.NextSibling : null) { htmlChildNode = AddBlock(xamlListItemElement, htmlChildNode, currentProperties, stylesheet, sourceContext); } // Add resulting ListBoxItem to a xaml parent xamlListElement.AppendChild(xamlListItemElement); } // ............................................................. // // Tables // // ............................................................. /// <summary> /// Converts htmlTableElement to a Xaml Table element. Adds tbody elements if they are missing so /// that a resulting Xaml Table element is properly formed. /// </summary> /// <param name="xamlParentElement"> /// Parent xaml element to which a converted table must be added. /// </param> /// <param name="htmlTableElement"> /// XmlElement reprsenting the Html table element to be converted /// </param> /// <param name="inheritedProperties"> /// Hashtable representing properties inherited from parent context. /// </param> private static void AddTable(XmlElement xamlParentElement, XmlElement htmlTableElement, Hashtable inheritedProperties, CssStylesheet stylesheet, List<XmlElement> sourceContext) { // Parameter validation Debug.Assert(htmlTableElement.LocalName.ToLower() == "table"); Debug.Assert(xamlParentElement != null); Debug.Assert(inheritedProperties != null); // Create current properties to be used by children as inherited properties, set local properties Hashtable localProperties; Hashtable currentProperties = GetElementProperties(htmlTableElement, inheritedProperties, out localProperties, stylesheet, sourceContext); // Check if the table contains only one cell - we want to take only its content XmlElement singleCell = GetCellFromSingleCellTable(htmlTableElement); if (singleCell != null) { // Need to push skipped table elements onto sourceContext sourceContext.Add(singleCell); // Add the cell's content directly to parent for (XmlNode htmlChildNode = singleCell.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode != null ? htmlChildNode.NextSibling : null) { htmlChildNode = AddBlock(xamlParentElement, htmlChildNode, currentProperties, stylesheet, sourceContext); } Debug.Assert(sourceContext.Count > 0 && sourceContext[sourceContext.Count - 1] == singleCell); sourceContext.RemoveAt(sourceContext.Count - 1); } else { // Create xamlTableElement XmlElement xamlTableElement = xamlParentElement.OwnerDocument.CreateElement(null, Xaml_Table, _xamlNamespace); // Analyze table structure for column widths and rowspan attributes ArrayList columnStarts = AnalyzeTableStructure(htmlTableElement, stylesheet); // Process COLGROUP & COL elements AddColumnInformation(htmlTableElement, xamlTableElement, columnStarts, currentProperties, stylesheet, sourceContext); // Process table body - TBODY and TR elements XmlNode htmlChildNode = htmlTableElement.FirstChild; while (htmlChildNode != null) { string htmlChildName = htmlChildNode.LocalName.ToLower(); // Process the element if (htmlChildName == "tbody" || htmlChildName == "thead" || htmlChildName == "tfoot") { // Add more special processing for TableHeader and TableFooter XmlElement xamlTableBodyElement = xamlTableElement.OwnerDocument.CreateElement(null, Xaml_TableRowGroup, _xamlNamespace); xamlTableElement.AppendChild(xamlTableBodyElement); sourceContext.Add((XmlElement)htmlChildNode); // Get properties of Html tbody element Hashtable tbodyElementLocalProperties; Hashtable tbodyElementCurrentProperties = GetElementProperties((XmlElement)htmlChildNode, currentProperties, out tbodyElementLocalProperties, stylesheet, sourceContext); // Process children of htmlChildNode, which is tbody, for tr elements AddTableRowsToTableBody(xamlTableBodyElement, htmlChildNode.FirstChild, tbodyElementCurrentProperties, columnStarts, stylesheet, sourceContext); if (xamlTableBodyElement.HasChildNodes) { xamlTableElement.AppendChild(xamlTableBodyElement); // else: if there is no TRs in this TBody, we simply ignore it } Debug.Assert(sourceContext.Count > 0 && sourceContext[sourceContext.Count - 1] == htmlChildNode); sourceContext.RemoveAt(sourceContext.Count - 1); htmlChildNode = htmlChildNode.NextSibling; } else if (htmlChildName == "tr") { // Tbody is not present, but tr element is present. Tr is wrapped in tbody XmlElement xamlTableBodyElement = xamlTableElement.OwnerDocument.CreateElement(null, Xaml_TableRowGroup, _xamlNamespace); // We use currentProperties of xamlTableElement when adding rows since the tbody element is artificially created and has // no properties of its own htmlChildNode = AddTableRowsToTableBody(xamlTableBodyElement, htmlChildNode, currentProperties, columnStarts, stylesheet, sourceContext); if (xamlTableBodyElement.HasChildNodes) { xamlTableElement.AppendChild(xamlTableBodyElement); } } else { // Element is not tbody or tr. Ignore it. htmlChildNode = htmlChildNode.NextSibling; } } if (xamlTableElement.HasChildNodes) { xamlParentElement.AppendChild(xamlTableElement); } } } private static XmlElement GetCellFromSingleCellTable(XmlElement htmlTableElement) { XmlElement singleCell = null; for (XmlNode tableChild = htmlTableElement.FirstChild; tableChild != null; tableChild = tableChild.NextSibling) { string elementName = tableChild.LocalName.ToLower(); if (elementName == "tbody" || elementName == "thead" || elementName == "tfoot") { if (singleCell != null) { return null; } for (XmlNode tbodyChild = tableChild.FirstChild; tbodyChild != null; tbodyChild = tbodyChild.NextSibling) { if (tbodyChild.LocalName.ToLower() == "tr") { if (singleCell != null) { return null; } for (XmlNode trChild = tbodyChild.FirstChild; trChild != null; trChild = trChild.NextSibling) { string cellName = trChild.LocalName.ToLower(); if (cellName == "td" || cellName == "th") { if (singleCell != null) { return null; } singleCell = (XmlElement)trChild; } } } } } else if (tableChild.LocalName.ToLower() == "tr") { if (singleCell != null) { return null; } for (XmlNode trChild = tableChild.FirstChild; trChild != null; trChild = trChild.NextSibling) { string cellName = trChild.LocalName.ToLower(); if (cellName == "td" || cellName == "th") { if (singleCell != null) { return null; } singleCell = (XmlElement)trChild; } } } } return singleCell; } /// <summary> /// Processes the information about table columns - COLGROUP and COL html elements. /// </summary> /// <param name="htmlTableElement"> /// XmlElement representing a source html table. /// </param> /// <param name="xamlTableElement"> /// XmlElement repesenting a resulting xaml table. /// </param> /// <param name="columnStartsAllRows"> /// Array of doubles - column start coordinates. /// Can be null, which means that column size information is not available /// and we must use source colgroup/col information. /// In case wneh it's not null, we will ignore source colgroup/col information. /// </param> /// <param name="currentProperties"></param> /// <param name="stylesheet"></param> /// <param name="sourceContext"></param> private static void AddColumnInformation(XmlElement htmlTableElement, XmlElement xamlTableElement, ArrayList columnStartsAllRows, Hashtable currentProperties, CssStylesheet stylesheet, List<XmlElement> sourceContext) { // Add column information if (columnStartsAllRows != null) { // We have consistent information derived from table cells; use it // The last element in columnStarts represents the end of the table var xamlColumnsElement = xamlTableElement.OwnerDocument.CreateElement(null, "Table.Columns", _xamlNamespace); xamlTableElement.AppendChild(xamlColumnsElement); for (int columnIndex = 0; columnIndex < columnStartsAllRows.Count - 1; columnIndex++) { XmlElement xamlColumnElement; xamlColumnElement = xamlTableElement.OwnerDocument.CreateElement(null, Xaml_TableColumn, _xamlNamespace); xamlColumnElement.SetAttribute(Xaml_Width, ((double)columnStartsAllRows[columnIndex + 1] - (double)columnStartsAllRows[columnIndex]).ToString()); xamlColumnsElement.AppendChild(xamlColumnElement); } } else { // We do not have consistent information from table cells; // Translate blindly colgroups from html. for (XmlNode htmlChildNode = htmlTableElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling) { if (htmlChildNode.LocalName.ToLower() == "colgroup") { AddTableColumnGroup(xamlTableElement, (XmlElement)htmlChildNode, currentProperties, stylesheet, sourceContext); } else if (htmlChildNode.LocalName.ToLower() == "col") { AddTableColumn(xamlTableElement, (XmlElement)htmlChildNode, currentProperties, stylesheet, sourceContext); } else if (htmlChildNode is XmlElement) { // Some element which belongs to table body. Stop column loop. break; } } } } /// <summary> /// Converts htmlColgroupElement into Xaml TableColumnGroup element, and appends it to the parent /// xamlTableElement /// </summary> /// <param name="xamlTableElement"> /// XmlElement representing Xaml Table element to which the converted column group should be added /// </param> /// <param name="htmlColgroupElement"> /// XmlElement representing Html colgroup element to be converted /// <param name="inheritedProperties"> /// Properties inherited from parent context /// </param> private static void AddTableColumnGroup(XmlElement xamlTableElement, XmlElement htmlColgroupElement, Hashtable inheritedProperties, CssStylesheet stylesheet, List<XmlElement> sourceContext) { Hashtable localProperties; Hashtable currentProperties = GetElementProperties(htmlColgroupElement, inheritedProperties, out localProperties, stylesheet, sourceContext); // Process children of colgroup. Colgroup may contain only col elements. for (XmlNode htmlNode = htmlColgroupElement.FirstChild; htmlNode != null; htmlNode = htmlNode.NextSibling) { if (htmlNode is XmlElement && htmlNode.LocalName.ToLower() == "col") { AddTableColumn(xamlTableElement, (XmlElement)htmlNode, currentProperties, stylesheet, sourceContext); } } } /// <summary> /// Converts htmlColElement into Xaml TableColumn element, and appends it to the parent /// xamlTableColumnGroupElement /// </summary> /// <param name="xamlTableElement"></param> /// <param name="htmlColElement"> /// XmlElement representing Html col element to be converted /// </param> /// <param name="inheritedProperties"> /// properties inherited from parent context /// </param> /// <param name="stylesheet"></param> /// <param name="sourceContext"></param> private static void AddTableColumn(XmlElement xamlTableElement, XmlElement htmlColElement, Hashtable inheritedProperties, CssStylesheet stylesheet, List<XmlElement> sourceContext) { Hashtable localProperties; Hashtable currentProperties = GetElementProperties(htmlColElement, inheritedProperties, out localProperties, stylesheet, sourceContext); XmlElement xamlTableColumnElement = xamlTableElement.OwnerDocument.CreateElement(null, Xaml_TableColumn, _xamlNamespace); // Col is an empty element, with no subtree xamlTableElement.AppendChild(xamlTableColumnElement); } /// <summary> /// Adds TableRow elements to xamlTableBodyElement. The rows are converted from Html tr elements that /// may be the children of an Html tbody element or an Html table element with tbody missing /// </summary> /// <param name="xamlTableBodyElement"> /// XmlElement representing Xaml TableRowGroup element to which the converted rows should be added /// </param> /// <param name="htmlTRStartNode"> /// XmlElement representing the first tr child of the tbody element to be read /// </param> /// <param name="currentProperties"> /// Hashtable representing current properties of the tbody element that are generated and applied in the /// AddTable function; to be used as inheritedProperties when adding tr elements /// </param> /// <param name="columnStarts"></param> /// <param name="stylesheet"></param> /// <param name="sourceContext"></param> /// <returns> /// XmlNode representing the current position of the iterator among tr elements /// </returns> private static XmlNode AddTableRowsToTableBody(XmlElement xamlTableBodyElement, XmlNode htmlTRStartNode, Hashtable currentProperties, ArrayList columnStarts, CssStylesheet stylesheet, List<XmlElement> sourceContext) { // Parameter validation Debug.Assert(xamlTableBodyElement.LocalName == Xaml_TableRowGroup); Debug.Assert(currentProperties != null); // Initialize child node for iteratimg through children to the first tr element XmlNode htmlChildNode = htmlTRStartNode; ArrayList activeRowSpans = null; if (columnStarts != null) { activeRowSpans = new ArrayList(); InitializeActiveRowSpans(activeRowSpans, columnStarts.Count); } while (htmlChildNode != null && htmlChildNode.LocalName.ToLower() != "tbody") { if (htmlChildNode.LocalName.ToLower() == "tr") { XmlElement xamlTableRowElement = xamlTableBodyElement.OwnerDocument.CreateElement(null, Xaml_TableRow, _xamlNamespace); sourceContext.Add((XmlElement)htmlChildNode); // Get tr element properties Hashtable trElementLocalProperties; Hashtable trElementCurrentProperties = GetElementProperties((XmlElement)htmlChildNode, currentProperties, out trElementLocalProperties, stylesheet, sourceContext); AddTableCellsToTableRow(xamlTableRowElement, htmlChildNode.FirstChild, trElementCurrentProperties, columnStarts, activeRowSpans, stylesheet, sourceContext); if (xamlTableRowElement.HasChildNodes) { xamlTableBodyElement.AppendChild(xamlTableRowElement); } Debug.Assert(sourceContext.Count > 0 && sourceContext[sourceContext.Count - 1] == htmlChildNode); sourceContext.RemoveAt(sourceContext.Count - 1); // Advance htmlChildNode = htmlChildNode.NextSibling; } else if (htmlChildNode.LocalName.ToLower() == "td") { // Tr element is not present. We create one and add td elements to it XmlElement xamlTableRowElement = xamlTableBodyElement.OwnerDocument.CreateElement(null, Xaml_TableRow, _xamlNamespace); // This is incorrect formatting and the column starts should not be set in this case Debug.Assert(columnStarts == null); htmlChildNode = AddTableCellsToTableRow(xamlTableRowElement, htmlChildNode, currentProperties, columnStarts, activeRowSpans, stylesheet, sourceContext); if (xamlTableRowElement.HasChildNodes) { xamlTableBodyElement.AppendChild(xamlTableRowElement); } } else { // Not a tr or td element. Ignore it. htmlChildNode = htmlChildNode.NextSibling; } } return htmlChildNode; } /// <summary> /// Adds TableCell elements to xamlTableRowElement. /// </summary> /// <param name="xamlTableRowElement"> /// XmlElement representing Xaml TableRow element to which the converted cells should be added /// </param> /// <param name="htmlTDStartNode"> /// XmlElement representing the child of tr or tbody element from which we should start adding td elements /// </param> /// <param name="currentProperties"> /// properties of the current html tr element to which cells are to be added /// </param> /// <returns> /// XmlElement representing the current position of the iterator among the children of the parent Html tbody/tr element /// </returns> private static XmlNode AddTableCellsToTableRow(XmlElement xamlTableRowElement, XmlNode htmlTDStartNode, Hashtable currentProperties, ArrayList columnStarts, ArrayList activeRowSpans, CssStylesheet stylesheet, List<XmlElement> sourceContext) { // parameter validation Debug.Assert(xamlTableRowElement.LocalName == Xaml_TableRow); Debug.Assert(currentProperties != null); if (columnStarts != null) { Debug.Assert(activeRowSpans.Count == columnStarts.Count); } XmlNode htmlChildNode = htmlTDStartNode; double columnStart = 0; double columnWidth = 0; int columnIndex = 0; int columnSpan = 0; while (htmlChildNode != null && htmlChildNode.LocalName.ToLower() != "tr" && htmlChildNode.LocalName.ToLower() != "tbody" && htmlChildNode.LocalName.ToLower() != "thead" && htmlChildNode.LocalName.ToLower() != "tfoot") { if (htmlChildNode.LocalName.ToLower() == "td" || htmlChildNode.LocalName.ToLower() == "th") { XmlElement xamlTableCellElement = xamlTableRowElement.OwnerDocument.CreateElement(null, Xaml_TableCell, _xamlNamespace); sourceContext.Add((XmlElement)htmlChildNode); Hashtable tdElementLocalProperties; Hashtable tdElementCurrentProperties = GetElementProperties((XmlElement)htmlChildNode, currentProperties, out tdElementLocalProperties, stylesheet, sourceContext); // make necessary changes and use them instead. ApplyPropertiesToTableCellElement((XmlElement)htmlChildNode, xamlTableCellElement, tdElementCurrentProperties); if (columnStarts != null) { Debug.Assert(columnIndex < columnStarts.Count - 1); while (columnIndex < activeRowSpans.Count && (int)activeRowSpans[columnIndex] > 0) { activeRowSpans[columnIndex] = (int)activeRowSpans[columnIndex] - 1; Debug.Assert((int)activeRowSpans[columnIndex] >= 0); columnIndex++; } Debug.Assert(columnIndex < columnStarts.Count - 1); columnStart = (double)columnStarts[columnIndex]; columnWidth = GetColumnWidth((XmlElement)htmlChildNode); columnSpan = CalculateColumnSpan(columnIndex, columnWidth, columnStarts); int rowSpan = GetRowSpan((XmlElement)htmlChildNode); // Column cannot have no span Debug.Assert(columnSpan > 0); Debug.Assert(columnIndex + columnSpan < columnStarts.Count); xamlTableCellElement.SetAttribute(Xaml_TableCell_ColumnSpan, columnSpan.ToString()); // Apply row span for (int spannedColumnIndex = columnIndex; spannedColumnIndex < columnIndex + columnSpan; spannedColumnIndex++) { Debug.Assert(spannedColumnIndex < activeRowSpans.Count); activeRowSpans[spannedColumnIndex] = (rowSpan - 1); Debug.Assert((int)activeRowSpans[spannedColumnIndex] >= 0); } columnIndex = columnIndex + columnSpan; } AddDataToTableCell(xamlTableCellElement, htmlChildNode.FirstChild, tdElementCurrentProperties, stylesheet, sourceContext); if (xamlTableCellElement.HasChildNodes) { xamlTableRowElement.AppendChild(xamlTableCellElement); } Debug.Assert(sourceContext.Count > 0 && sourceContext[sourceContext.Count - 1] == htmlChildNode); sourceContext.RemoveAt(sourceContext.Count - 1); htmlChildNode = htmlChildNode.NextSibling; } else { // Not td element. Ignore it. htmlChildNode = htmlChildNode.NextSibling; } } return htmlChildNode; } /// <summary> /// adds table cell data to xamlTableCellElement /// </summary> /// <param name="xamlTableCellElement"> /// XmlElement representing Xaml TableCell element to which the converted data should be added /// </param> /// <param name="htmlDataStartNode"> /// XmlElement representing the start element of data to be added to xamlTableCellElement /// </param> /// <param name="currentProperties"> /// Current properties for the html td/th element corresponding to xamlTableCellElement /// </param> private static void AddDataToTableCell(XmlElement xamlTableCellElement, XmlNode htmlDataStartNode, Hashtable currentProperties, CssStylesheet stylesheet, List<XmlElement> sourceContext) { // Parameter validation Debug.Assert(xamlTableCellElement.LocalName == Xaml_TableCell); Debug.Assert(currentProperties != null); for (XmlNode htmlChildNode = htmlDataStartNode; htmlChildNode != null; htmlChildNode = htmlChildNode != null ? htmlChildNode.NextSibling : null) { // Process a new html element and add it to the td element htmlChildNode = AddBlock(xamlTableCellElement, htmlChildNode, currentProperties, stylesheet, sourceContext); } } /// <summary> /// Performs a parsing pass over a table to read information about column width and rowspan attributes. This information /// is used to determine the starting point of each column. /// </summary> /// <param name="htmlTableElement"> /// XmlElement representing Html table whose structure is to be analyzed /// </param> /// <returns> /// ArrayList of type double which contains the function output. If analysis is successful, this ArrayList contains /// all the points which are the starting position of any column in the table, ordered from left to right. /// In case if analisys was impossible we return null. /// </returns> private static ArrayList AnalyzeTableStructure(XmlElement htmlTableElement, CssStylesheet stylesheet) { // Parameter validation Debug.Assert(htmlTableElement.LocalName.ToLower() == "table"); if (!htmlTableElement.HasChildNodes) { return null; } bool columnWidthsAvailable = true; ArrayList columnStarts = new ArrayList(); ArrayList activeRowSpans = new ArrayList(); Debug.Assert(columnStarts.Count == activeRowSpans.Count); XmlNode htmlChildNode = htmlTableElement.FirstChild; double tableWidth = 0; // Keep track of table width which is the width of its widest row // Analyze tbody and tr elements while (htmlChildNode != null && columnWidthsAvailable) { Debug.Assert(columnStarts.Count == activeRowSpans.Count); switch (htmlChildNode.LocalName.ToLower()) { case "tbody": // Tbody element, we should analyze its children for trows double tbodyWidth = AnalyzeTbodyStructure((XmlElement)htmlChildNode, columnStarts, activeRowSpans, tableWidth, stylesheet); if (tbodyWidth > tableWidth) { // Table width must be increased to supported newly added wide row tableWidth = tbodyWidth; } else if (tbodyWidth == 0) { // Tbody analysis may return 0, probably due to unprocessable format. // We should also fail. columnWidthsAvailable = false; // interrupt the analisys } break; case "tr": // Table row. Analyze column structure within row directly double trWidth = AnalyzeTRStructure((XmlElement)htmlChildNode, columnStarts, activeRowSpans, tableWidth, stylesheet); if (trWidth > tableWidth) { tableWidth = trWidth; } else if (trWidth == 0) { columnWidthsAvailable = false; // interrupt the analisys } break; case "td": // Incorrect formatting, too deep to analyze at this level. Return null. columnWidthsAvailable = false; // interrupt the analisys break; default: // Element should not occur directly in table. Ignore it. break; } htmlChildNode = htmlChildNode.NextSibling; } if (columnWidthsAvailable) { // Add an item for whole table width columnStarts.Add(tableWidth); VerifyColumnStartsAscendingOrder(columnStarts); } else { columnStarts = null; } return columnStarts; } /// <summary> /// Performs a parsing pass over a tbody to read information about column width and rowspan attributes. Information read about width /// attributes is stored in the reference ArrayList parameter columnStarts, which contains a list of all starting /// positions of all columns in the table, ordered from left to right. Row spans are taken into consideration when /// computing column starts /// </summary> /// <param name="htmlTbodyElement"> /// XmlElement representing Html tbody whose structure is to be analyzed /// </param> /// <param name="columnStarts"> /// ArrayList of type double which contains the function output. If analysis fails, this parameter is set to null /// </param> /// <param name="tableWidth"> /// Current width of the table. This is used to determine if a new column when added to the end of table should /// come after the last column in the table or is actually splitting the last column in two. If it is only splitting /// the last column it should inherit row span for that column /// </param> /// <returns> /// Calculated width of a tbody. /// In case of non-analizable column width structure return 0; /// </returns> private static double AnalyzeTbodyStructure(XmlElement htmlTbodyElement, ArrayList columnStarts, ArrayList activeRowSpans, double tableWidth, CssStylesheet stylesheet) { // Parameter validation Debug.Assert(htmlTbodyElement.LocalName.ToLower() == "tbody"); Debug.Assert(columnStarts != null); double tbodyWidth = 0; bool columnWidthsAvailable = true; if (!htmlTbodyElement.HasChildNodes) { return tbodyWidth; } // Set active row spans to 0 - thus ignoring row spans crossing tbody boundaries ClearActiveRowSpans(activeRowSpans); XmlNode htmlChildNode = htmlTbodyElement.FirstChild; // Analyze tr elements while (htmlChildNode != null && columnWidthsAvailable) { switch (htmlChildNode.LocalName.ToLower()) { case "tr": double trWidth = AnalyzeTRStructure((XmlElement)htmlChildNode, columnStarts, activeRowSpans, tbodyWidth, stylesheet); if (trWidth > tbodyWidth) { tbodyWidth = trWidth; } break; case "td": columnWidthsAvailable = false; // interrupt the analisys break; default: break; } htmlChildNode = htmlChildNode.NextSibling; } // Set active row spans to 0 - thus ignoring row spans crossing tbody boundaries ClearActiveRowSpans(activeRowSpans); return columnWidthsAvailable ? tbodyWidth : 0; } /// <summary> /// Performs a parsing pass over a tr element to read information about column width and rowspan attributes. /// </summary> /// <param name="htmlTRElement"> /// XmlElement representing Html tr element whose structure is to be analyzed /// </param> /// <param name="columnStarts"> /// ArrayList of type double which contains the function output. If analysis is successful, this ArrayList contains /// all the points which are the starting position of any column in the tr, ordered from left to right. If analysis fails, /// the ArrayList is set to null /// </param> /// <param name="activeRowSpans"> /// ArrayList representing all columns currently spanned by an earlier row span attribute. These columns should /// not be used for data in this row. The ArrayList actually contains notation for all columns in the table, if the /// active row span is set to 0 that column is not presently spanned but if it is > 0 the column is presently spanned /// </param> /// <param name="tableWidth"> /// Double value representing the current width of the table. /// Return 0 if analisys was insuccessful. /// </param> private static double AnalyzeTRStructure(XmlElement htmlTRElement, ArrayList columnStarts, ArrayList activeRowSpans, double tableWidth, CssStylesheet stylesheet) { double columnWidth; // Parameter validation Debug.Assert(htmlTRElement.LocalName.ToLower() == "tr"); Debug.Assert(columnStarts != null); Debug.Assert(activeRowSpans != null); Debug.Assert(columnStarts.Count == activeRowSpans.Count); if (!htmlTRElement.HasChildNodes) { return 0; } bool columnWidthsAvailable = true; double columnStart = 0; // starting position of current column XmlNode htmlChildNode = htmlTRElement.FirstChild; int columnIndex = 0; double trWidth = 0; // Skip spanned columns to get to real column start if (columnIndex < activeRowSpans.Count) { Debug.Assert((double)columnStarts[columnIndex] >= columnStart); if ((double)columnStarts[columnIndex] == columnStart) { // The new column may be in a spanned area while (columnIndex < activeRowSpans.Count && (int)activeRowSpans[columnIndex] > 0) { activeRowSpans[columnIndex] = (int)activeRowSpans[columnIndex] - 1; Debug.Assert((int)activeRowSpans[columnIndex] >= 0); columnIndex++; columnStart = (double)columnStarts[columnIndex]; } } } while (htmlChildNode != null && columnWidthsAvailable) { Debug.Assert(columnStarts.Count == activeRowSpans.Count); VerifyColumnStartsAscendingOrder(columnStarts); switch (htmlChildNode.LocalName.ToLower()) { case "td": Debug.Assert(columnIndex <= columnStarts.Count); if (columnIndex < columnStarts.Count) { Debug.Assert(columnStart <= (double)columnStarts[columnIndex]); if (columnStart < (double)columnStarts[columnIndex]) { columnStarts.Insert(columnIndex, columnStart); // There can be no row spans now - the column data will appear here // Row spans may appear only during the column analysis activeRowSpans.Insert(columnIndex, 0); } } else { // Column start is greater than all previous starts. Row span must still be 0 because // we are either adding after another column of the same row, in which case it should not inherit // the previous column's span. Otherwise we are adding after the last column of some previous // row, and assuming the table widths line up, we should not be spanned by it. If there is // an incorrect tbale structure where a columns starts in the middle of a row span, we do not // guarantee correct output columnStarts.Add(columnStart); activeRowSpans.Add(0); } columnWidth = GetColumnWidth((XmlElement)htmlChildNode); if (columnWidth != -1) { int nextColumnIndex; int rowSpan = GetRowSpan((XmlElement)htmlChildNode); nextColumnIndex = GetNextColumnIndex(columnIndex, columnWidth, columnStarts, activeRowSpans); if (nextColumnIndex != -1) { // Entire column width can be processed without hitting conflicting row span. This means that // column widths line up and we can process them Debug.Assert(nextColumnIndex <= columnStarts.Count); // Apply row span to affected columns for (int spannedColumnIndex = columnIndex; spannedColumnIndex < nextColumnIndex; spannedColumnIndex++) { activeRowSpans[spannedColumnIndex] = rowSpan - 1; Debug.Assert((int)activeRowSpans[spannedColumnIndex] >= 0); } columnIndex = nextColumnIndex; // Calculate columnsStart for the next cell columnStart = columnStart + columnWidth; if (columnIndex < activeRowSpans.Count) { Debug.Assert((double)columnStarts[columnIndex] >= columnStart); if ((double)columnStarts[columnIndex] == columnStart) { // The new column may be in a spanned area while (columnIndex < activeRowSpans.Count && (int)activeRowSpans[columnIndex] > 0) { activeRowSpans[columnIndex] = (int)activeRowSpans[columnIndex] - 1; Debug.Assert((int)activeRowSpans[columnIndex] >= 0); columnIndex++; columnStart = (double)columnStarts[columnIndex]; } } // else: the new column does not start at the same time as a pre existing column // so we don't have to check it for active row spans, it starts in the middle // of another column which has been checked already by the GetNextColumnIndex function } } else { // Full column width cannot be processed without a pre existing row span. // We cannot analyze widths columnWidthsAvailable = false; } } else { // Incorrect column width, stop processing columnWidthsAvailable = false; } break; default: break; } htmlChildNode = htmlChildNode.NextSibling; } // The width of the tr element is the position at which it's last td element ends, which is calculated in // the columnStart value after each td element is processed if (columnWidthsAvailable) { trWidth = columnStart; } else { trWidth = 0; } return trWidth; } /// <summary> /// Gets row span attribute from htmlTDElement. Returns an integer representing the value of the rowspan attribute. /// Default value if attribute is not specified or if it is invalid is 1 /// </summary> /// <param name="htmlTDElement"> /// Html td element to be searched for rowspan attribute /// </param> private static int GetRowSpan(XmlElement htmlTDElement) { string rowSpanAsString; int rowSpan; rowSpanAsString = GetAttribute((XmlElement)htmlTDElement, "rowspan"); if (rowSpanAsString != null) { if (!Int32.TryParse(rowSpanAsString, out rowSpan)) { // Ignore invalid value of rowspan; treat it as 1 rowSpan = 1; } } else { // No row span, default is 1 rowSpan = 1; } return rowSpan; } /// <summary> /// Gets index at which a column should be inseerted into the columnStarts ArrayList. This is /// decided by the value columnStart. The columnStarts ArrayList is ordered in ascending order. /// Returns an integer representing the index at which the column should be inserted /// </summary> /// <param name="columnStarts"> /// Array list representing starting coordinates of all columns in the table /// </param> /// <param name="columnStart"> /// Starting coordinate of column we wish to insert into columnStart /// </param> /// <param name="columnIndex"> /// Int representing the current column index. This acts as a clue while finding the insertion index. /// If the value of columnStarts at columnIndex is the same as columnStart, then this position alrady exists /// in the array and we can jsut return columnIndex. /// </param> /// <returns></returns> private static int GetNextColumnIndex(int columnIndex, double columnWidth, ArrayList columnStarts, ArrayList activeRowSpans) { double columnStart; int spannedColumnIndex; // Parameter validation Debug.Assert(columnStarts != null); Debug.Assert(0 <= columnIndex && columnIndex <= columnStarts.Count); Debug.Assert(columnWidth > 0); columnStart = (double)columnStarts[columnIndex]; spannedColumnIndex = columnIndex + 1; while (spannedColumnIndex < columnStarts.Count && (double)columnStarts[spannedColumnIndex] < columnStart + columnWidth && spannedColumnIndex != -1) { if ((int)activeRowSpans[spannedColumnIndex] > 0) { // The current column should span this area, but something else is already spanning it // Not analyzable spannedColumnIndex = -1; } else { spannedColumnIndex++; } } return spannedColumnIndex; } /// <summary> /// Used for clearing activeRowSpans array in the beginning/end of each tbody /// </summary> /// <param name="activeRowSpans"> /// ArrayList representing currently active row spans /// </param> private static void ClearActiveRowSpans(ArrayList activeRowSpans) { for (int columnIndex = 0; columnIndex < activeRowSpans.Count; columnIndex++) { activeRowSpans[columnIndex] = 0; } } /// <summary> /// Used for initializing activeRowSpans array in the before adding rows to tbody element /// </summary> /// <param name="activeRowSpans"> /// ArrayList representing currently active row spans /// </param> /// <param name="count"> /// Size to be give to array list /// </param> private static void InitializeActiveRowSpans(ArrayList activeRowSpans, int count) { for (int columnIndex = 0; columnIndex < count; columnIndex++) { activeRowSpans.Add(0); } } /// <summary> /// Calculates width of next TD element based on starting position of current element and it's width, which /// is calculated byt he function /// </summary> /// <param name="htmlTDElement"> /// XmlElement representing Html td element whose width is to be read /// </param> /// <param name="columnStart"> /// Starting position of current column /// </param> private static double GetNextColumnStart(XmlElement htmlTDElement, double columnStart) { double columnWidth; double nextColumnStart; // Parameter validation Debug.Assert(htmlTDElement.LocalName.ToLower() == "td" || htmlTDElement.LocalName.ToLower() == "th"); Debug.Assert(columnStart >= 0); nextColumnStart = -1; // -1 indicates inability to calculate columnStart width columnWidth = GetColumnWidth(htmlTDElement); if (columnWidth == -1) { nextColumnStart = -1; } else { nextColumnStart = columnStart + columnWidth; } return nextColumnStart; } private static double GetColumnWidth(XmlElement htmlTDElement) { string columnWidthAsString; double columnWidth; columnWidthAsString = null; columnWidth = -1; // Get string valkue for the width columnWidthAsString = GetAttribute(htmlTDElement, "width"); if (columnWidthAsString == null) { columnWidthAsString = GetCssAttribute(GetAttribute(htmlTDElement, "style"), "width"); } // We do not allow column width to be 0, if specified as 0 we will fail to record it if (!TryGetLengthValue(columnWidthAsString, out columnWidth) || columnWidth == 0) { columnWidth = -1; } return columnWidth; } /// <summary> /// Calculates column span based the column width and the widths of all other columns. Returns an integer representing /// the column span /// </summary> /// <param name="columnIndex"> /// Index of the current column /// </param> /// <param name="columnWidth"> /// Width of the current column /// </param> /// <param name="columnStarts"> /// ArrayList repsenting starting coordinates of all columns /// </param> private static int CalculateColumnSpan(int columnIndex, double columnWidth, ArrayList columnStarts) { // Current status of column width. Indicates the amount of width that has been scanned already double columnSpanningValue; int columnSpanningIndex; int columnSpan; double subColumnWidth; // Width of the smallest-grain columns in the table Debug.Assert(columnStarts != null); Debug.Assert(columnIndex < columnStarts.Count - 1); Debug.Assert((double)columnStarts[columnIndex] >= 0); Debug.Assert(columnWidth > 0); columnSpanningIndex = columnIndex; columnSpanningValue = 0; columnSpan = 0; subColumnWidth = 0; while (columnSpanningValue < columnWidth && columnSpanningIndex < columnStarts.Count - 1) { subColumnWidth = (double)columnStarts[columnSpanningIndex + 1] - (double)columnStarts[columnSpanningIndex]; Debug.Assert(subColumnWidth > 0); columnSpanningValue += subColumnWidth; columnSpanningIndex++; } // Now, we have either covered the width we needed to cover or reached the end of the table, in which // case the column spans all the columns until the end columnSpan = columnSpanningIndex - columnIndex; Debug.Assert(columnSpan > 0); return columnSpan; } /// <summary> /// Verifies that values in columnStart, which represent starting coordinates of all columns, are arranged /// in ascending order /// </summary> /// <param name="columnStarts"> /// ArrayList representing starting coordinates of all columns /// </param> private static void VerifyColumnStartsAscendingOrder(ArrayList columnStarts) { Debug.Assert(columnStarts != null); double columnStart; columnStart = -0.01; for (int columnIndex = 0; columnIndex < columnStarts.Count; columnIndex++) { Debug.Assert(columnStart < (double)columnStarts[columnIndex]); columnStart = (double)columnStarts[columnIndex]; } } // ............................................................. // // Attributes and Properties // // ............................................................. /// <summary> /// Analyzes local properties of Html element, converts them into Xaml equivalents, and applies them to xamlElement /// </summary> /// <param name="xamlElement"> /// XmlElement representing Xaml element to which properties are to be applied /// </param> /// <param name="localProperties"> /// Hashtable representing local properties of Html element that is converted into xamlElement /// </param> private static void ApplyLocalProperties(XmlElement xamlElement, Hashtable localProperties, bool isBlock) { bool marginSet = false; string marginTop = "0"; string marginBottom = "0"; string marginLeft = "0"; string marginRight = "0"; bool paddingSet = false; string paddingTop = "0"; string paddingBottom = "0"; string paddingLeft = "0"; string paddingRight = "0"; string borderColor = null; bool borderThicknessSet = false; string borderThicknessTop = "0"; string borderThicknessBottom = "0"; string borderThicknessLeft = "0"; string borderThicknessRight = "0"; IDictionaryEnumerator propertyEnumerator = localProperties.GetEnumerator(); while (propertyEnumerator.MoveNext()) { switch ((string)propertyEnumerator.Key) { case "font-family": // Convert from font-family value list into xaml FontFamily value xamlElement.SetAttribute(Xaml_FontFamily, (string)propertyEnumerator.Value); break; case "font-style": xamlElement.SetAttribute(Xaml_FontStyle, (string)propertyEnumerator.Value); break; case "font-variant": // Convert from font-variant into xaml property break; case "font-weight": xamlElement.SetAttribute(Xaml_FontWeight, (string)propertyEnumerator.Value); break; case "font-size": // Convert from css size into FontSize xamlElement.SetAttribute(Xaml_FontSize, (string)propertyEnumerator.Value); break; case "color": SetPropertyValue(xamlElement, TextElement.ForegroundProperty, (string)propertyEnumerator.Value); break; case "background-color": SetPropertyValue(xamlElement, TextElement.BackgroundProperty, (string)propertyEnumerator.Value); break; case "text-decoration-underline": if (!isBlock) { if ((string)propertyEnumerator.Value == "true") { xamlElement.SetAttribute(Xaml_TextDecorations, Xaml_TextDecorations_Underline); } } break; case "text-decoration-none": case "text-decoration-overline": case "text-decoration-line-through": case "text-decoration-blink": // Convert from all other text-decorations values if (!isBlock) { } break; case "text-transform": // Convert from text-transform into xaml property break; case "text-indent": if (isBlock) { xamlElement.SetAttribute(Xaml_TextIndent, (string)propertyEnumerator.Value); } break; case "text-align": if (isBlock) { xamlElement.SetAttribute(Xaml_TextAlignment, (string)propertyEnumerator.Value); } break; case "width": case "height": // Decide what to do with width and height propeties break; case "margin-top": marginSet = true; marginTop = (string)propertyEnumerator.Value; break; case "margin-right": marginSet = true; marginRight = (string)propertyEnumerator.Value; break; case "margin-bottom": marginSet = true; marginBottom = (string)propertyEnumerator.Value; break; case "margin-left": marginSet = true; marginLeft = (string)propertyEnumerator.Value; break; case "padding-top": paddingSet = true; paddingTop = (string)propertyEnumerator.Value; break; case "padding-right": paddingSet = true; paddingRight = (string)propertyEnumerator.Value; break; case "padding-bottom": paddingSet = true; paddingBottom = (string)propertyEnumerator.Value; break; case "padding-left": paddingSet = true; paddingLeft = (string)propertyEnumerator.Value; break; // In our internal notation we intentionally put them at the end - to unify processing in ParseCssRectangleProperty method case "border-color-top": borderColor = (string)propertyEnumerator.Value; break; case "border-color-right": borderColor = (string)propertyEnumerator.Value; break; case "border-color-bottom": borderColor = (string)propertyEnumerator.Value; break; case "border-color-left": borderColor = (string)propertyEnumerator.Value; break; case "border-style-top": case "border-style-right": case "border-style-bottom": case "border-style-left": // Implement conversion from border style break; case "border-width-top": borderThicknessSet = true; borderThicknessTop = (string)propertyEnumerator.Value; break; case "border-width-right": borderThicknessSet = true; borderThicknessRight = (string)propertyEnumerator.Value; break; case "border-width-bottom": borderThicknessSet = true; borderThicknessBottom = (string)propertyEnumerator.Value; break; case "border-width-left": borderThicknessSet = true; borderThicknessLeft = (string)propertyEnumerator.Value; break; case "list-style-type": if (xamlElement.LocalName == Xaml_List) { string markerStyle; switch (((string)propertyEnumerator.Value).ToLower()) { case "disc": markerStyle = HtmlToXamlConverter.Xaml_List_MarkerStyle_Disc; break; case "circle": markerStyle = HtmlToXamlConverter.Xaml_List_MarkerStyle_Circle; break; case "none": markerStyle = HtmlToXamlConverter.Xaml_List_MarkerStyle_None; break; case "square": markerStyle = HtmlToXamlConverter.Xaml_List_MarkerStyle_Square; break; case "box": markerStyle = HtmlToXamlConverter.Xaml_List_MarkerStyle_Box; break; case "lower-latin": markerStyle = HtmlToXamlConverter.Xaml_List_MarkerStyle_LowerLatin; break; case "upper-latin": markerStyle = HtmlToXamlConverter.Xaml_List_MarkerStyle_UpperLatin; break; case "lower-roman": markerStyle = HtmlToXamlConverter.Xaml_List_MarkerStyle_LowerRoman; break; case "upper-roman": markerStyle = HtmlToXamlConverter.Xaml_List_MarkerStyle_UpperRoman; break; case "decimal": markerStyle = HtmlToXamlConverter.Xaml_List_MarkerStyle_Decimal; break; default: markerStyle = HtmlToXamlConverter.Xaml_List_MarkerStyle_Disc; break; } xamlElement.SetAttribute(HtmlToXamlConverter.Xaml_List_MarkerStyle, markerStyle); } break; case "float": case "clear": if (isBlock) { // Convert float and clear properties } break; case "display": break; } } if (isBlock) { if (marginSet) { ComposeThicknessProperty(xamlElement, Xaml_Margin, marginLeft, marginRight, marginTop, marginBottom); } if (paddingSet) { ComposeThicknessProperty(xamlElement, Xaml_Padding, paddingLeft, paddingRight, paddingTop, paddingBottom); } if (borderColor != null) { // We currently ignore possible difference in brush colors on different border sides. Use the last colored side mentioned xamlElement.SetAttribute(Xaml_BorderBrush, borderColor); } if (borderThicknessSet) { ComposeThicknessProperty(xamlElement, Xaml_BorderThickness, borderThicknessLeft, borderThicknessRight, borderThicknessTop, borderThicknessBottom); } } } // Create syntactically optimized four-value Thickness private static void ComposeThicknessProperty(XmlElement xamlElement, string propertyName, string left, string right, string top, string bottom) { // Xaml syntax: // We have a reasonable interpreation for one value (all four edges), two values (horizontal, vertical), // and four values (left, top, right, bottom). // switch (i) { // case 1: return new Thickness(lengths[0]); // case 2: return new Thickness(lengths[0], lengths[1], lengths[0], lengths[1]); // case 4: return new Thickness(lengths[0], lengths[1], lengths[2], lengths[3]); // } string thickness; // We do not accept negative margins if (left[0] == '0' || left[0] == '-') left = "0"; if (right[0] == '0' || right[0] == '-') right = "0"; if (top[0] == '0' || top[0] == '-') top = "0"; if (bottom[0] == '0' || bottom[0] == '-') bottom = "0"; if (left == right && top == bottom) { if (left == top) { thickness = left; } else { thickness = left + "," + top; } } else { thickness = left + "," + top + "," + right + "," + bottom; } // Need safer processing for a thickness value xamlElement.SetAttribute(propertyName, thickness); } private static void SetPropertyValue(XmlElement xamlElement, DependencyProperty property, string stringValue) { System.ComponentModel.TypeConverter typeConverter = System.ComponentModel.TypeDescriptor.GetConverter(property.PropertyType); try { object convertedValue = typeConverter.ConvertFromInvariantString(stringValue); if (convertedValue != null) { xamlElement.SetAttribute(property.Name, stringValue); } } catch (Exception) { } } /// <summary> /// Analyzes the tag of the htmlElement and infers its associated formatted properties. /// After that parses style attribute and adds all inline css styles. /// The resulting style attributes are collected in output parameter localProperties. /// </summary> /// <param name="htmlElement"> /// </param> /// <param name="inheritedProperties"> /// set of properties inherited from ancestor elements. Currently not used in the code. Reserved for the future development. /// </param> /// <param name="localProperties"> /// returns all formatting properties defined by this element - implied by its tag, its attributes, or its css inline style /// </param> /// <param name="stylesheet"></param> /// <param name="sourceContext"></param> /// <returns> /// returns a combination of previous context with local set of properties. /// This value is not used in the current code - inntended for the future development. /// </returns> private static Hashtable GetElementProperties(XmlElement htmlElement, Hashtable inheritedProperties, out Hashtable localProperties, CssStylesheet stylesheet, List<XmlElement> sourceContext) { // Start with context formatting properties Hashtable currentProperties = new Hashtable(); IDictionaryEnumerator propertyEnumerator = inheritedProperties.GetEnumerator(); while (propertyEnumerator.MoveNext()) { currentProperties[propertyEnumerator.Key] = propertyEnumerator.Value; } // Identify element name string elementName = htmlElement.LocalName.ToLower(); string elementNamespace = htmlElement.NamespaceURI; // update current formatting properties depending on element tag localProperties = new Hashtable(); switch (elementName) { // Character formatting case "i": case "italic": case "em": localProperties["font-style"] = "italic"; break; case "b": case "bold": case "strong": case "dfn": localProperties["font-weight"] = "bold"; break; case "u": case "underline": localProperties["text-decoration-underline"] = "true"; break; case "font": string attributeValue = GetAttribute(htmlElement, "face"); if (attributeValue != null) { localProperties["font-family"] = attributeValue; } attributeValue = GetAttribute(htmlElement, "size"); if (attributeValue != null) { double fontSize = double.Parse(attributeValue) * (12.0 / 3.0); if (fontSize < 1.0) { fontSize = 1.0; } else if (fontSize > 1000.0) { fontSize = 1000.0; } localProperties["font-size"] = fontSize.ToString(); } attributeValue = GetAttribute(htmlElement, "color"); if (attributeValue != null) { localProperties["color"] = attributeValue; } break; case "samp": localProperties["font-family"] = "Courier New"; // code sample localProperties["font-size"] = Xaml_FontSize_XXSmall; localProperties["text-align"] = "Left"; break; case "sub": break; case "sup": break; // Hyperlinks case "a": // href, hreflang, urn, methods, rel, rev, title // Set default hyperlink properties break; case "acronym": break; // Paragraph formatting: case "p": // Set default paragraph properties break; case "div": // Set default div properties break; case "pre": localProperties["font-family"] = "Courier New"; // renders text in a fixed-width font localProperties["font-size"] = Xaml_FontSize_XXSmall; localProperties["text-align"] = "Left"; break; case "blockquote": localProperties["margin-left"] = "16"; break; case "h1": localProperties["font-size"] = Xaml_FontSize_XXLarge; break; case "h2": localProperties["font-size"] = Xaml_FontSize_XLarge; break; case "h3": localProperties["font-size"] = Xaml_FontSize_Large; break; case "h4": localProperties["font-size"] = Xaml_FontSize_Medium; break; case "h5": localProperties["font-size"] = Xaml_FontSize_Small; break; case "h6": localProperties["font-size"] = Xaml_FontSize_XSmall; break; // List properties case "ul": localProperties["list-style-type"] = "disc"; break; case "ol": localProperties["list-style-type"] = "decimal"; break; case "table": case "body": case "html": break; } // Override html defaults by css attributes - from stylesheets and inline settings HtmlCssParser.GetElementPropertiesFromCssAttributes(htmlElement, elementName, stylesheet, localProperties, sourceContext); // Combine local properties with context to create new current properties propertyEnumerator = localProperties.GetEnumerator(); while (propertyEnumerator.MoveNext()) { currentProperties[propertyEnumerator.Key] = propertyEnumerator.Value; } return currentProperties; } /// <summary> /// Extracts a value of css attribute from css style definition. /// </summary> /// <param name="cssStyle"> /// Source csll style definition /// </param> /// <param name="attributeName"> /// A name of css attribute to extract /// </param> /// <returns> /// A string rrepresentation of an attribute value if found; /// null if there is no such attribute in a given string. /// </returns> private static string GetCssAttribute(string cssStyle, string attributeName) { // This is poor man's attribute parsing. Replace it by real css parsing if (cssStyle != null) { string[] styleValues; attributeName = attributeName.ToLower(); // Check for width specification in style string styleValues = cssStyle.Split(';'); for (int styleValueIndex = 0; styleValueIndex < styleValues.Length; styleValueIndex++) { string[] styleNameValue; styleNameValue = styleValues[styleValueIndex].Split(':'); if (styleNameValue.Length == 2) { if (styleNameValue[0].Trim().ToLower() == attributeName) { return styleNameValue[1].Trim(); } } } } return null; } /// <summary> /// Converts a length value from string representation to a double. /// </summary> /// <param name="lengthAsString"> /// Source string value of a length. /// </param> /// <param name="length"></param> /// <returns></returns> private static bool TryGetLengthValue(string lengthAsString, out double length) { length = Double.NaN; if (lengthAsString != null) { lengthAsString = lengthAsString.Trim().ToLower(); // We try to convert currentColumnWidthAsString into a double. This will eliminate widths of type "50%", etc. if (lengthAsString.EndsWith("pt")) { lengthAsString = lengthAsString.Substring(0, lengthAsString.Length - 2); if (Double.TryParse(lengthAsString, out length)) { length = (length * 96.0) / 72.0; // convert from points to pixels } else { length = Double.NaN; } } else if (lengthAsString.EndsWith("px")) { lengthAsString = lengthAsString.Substring(0, lengthAsString.Length - 2); if (!Double.TryParse(lengthAsString, out length)) { length = Double.NaN; } } else { if (!Double.TryParse(lengthAsString, out length)) // Assuming pixels { length = Double.NaN; } } } return !Double.IsNaN(length); } // ................................................................. // // Pasring Color Attribute // // ................................................................. private static string GetColorValue(string colorValue) { return colorValue; } /// <summary> /// Applies properties to xamlTableCellElement based on the html td element it is converted from. /// </summary> /// <param name="htmlChildNode"> /// Html td/th element to be converted to xaml /// </param> /// <param name="xamlTableCellElement"> /// XmlElement representing Xaml element for which properties are to be processed /// </param> /// <remarks> /// </remarks> private static void ApplyPropertiesToTableCellElement(XmlElement htmlChildNode, XmlElement xamlTableCellElement, Hashtable localProperties) { // Parameter validation Debug.Assert(htmlChildNode.LocalName.ToLower() == "td" || htmlChildNode.LocalName.ToLower() == "th"); Debug.Assert(xamlTableCellElement.LocalName == Xaml_TableCell); // set default border thickness for xamlTableCellElement to enable gridlines xamlTableCellElement.SetAttribute(Xaml_TableCell_BorderThickness, "1,1,1,1"); xamlTableCellElement.SetAttribute(Xaml_TableCell_BorderBrush, Xaml_Brushes_Black); string rowSpanString = GetAttribute((XmlElement)htmlChildNode, "rowspan"); if (rowSpanString != null) { xamlTableCellElement.SetAttribute(Xaml_TableCell_RowSpan, rowSpanString); } ApplyLocalProperties(xamlTableCellElement, localProperties, true); } #endregion Private Methods // ---------------------------------------------------------------- // // Internal Constants // // ---------------------------------------------------------------- // The constants reprtesent all Xaml names used in a conversion public const string Xaml_FlowDocument = "FlowDocument"; public const string Xaml_Run = "Run"; public const string Xaml_Span = "Span"; public const string Xaml_Hyperlink = "Hyperlink"; public const string Xaml_Hyperlink_NavigateUri = "NavigateUri"; public const string Xaml_Hyperlink_TargetName = "TargetName"; public const string Xaml_Section = "Section"; public const string Xaml_List = "List"; public const string Xaml_List_MarkerStyle = "MarkerStyle"; public const string Xaml_List_MarkerStyle_None = "None"; public const string Xaml_List_MarkerStyle_Decimal = "Decimal"; public const string Xaml_List_MarkerStyle_Disc = "Disc"; public const string Xaml_List_MarkerStyle_Circle = "Circle"; public const string Xaml_List_MarkerStyle_Square = "Square"; public const string Xaml_List_MarkerStyle_Box = "Box"; public const string Xaml_List_MarkerStyle_LowerLatin = "LowerLatin"; public const string Xaml_List_MarkerStyle_UpperLatin = "UpperLatin"; public const string Xaml_List_MarkerStyle_LowerRoman = "LowerRoman"; public const string Xaml_List_MarkerStyle_UpperRoman = "UpperRoman"; public const string Xaml_ListItem = "ListItem"; public const string Xaml_LineBreak = "LineBreak"; public const string Xaml_Paragraph = "Paragraph"; public const string Xaml_Margin = "Margin"; public const string Xaml_Padding = "Padding"; public const string Xaml_BorderBrush = "BorderBrush"; public const string Xaml_BorderThickness = "BorderThickness"; public const string Xaml_Table = "Table"; public const string Xaml_TableColumn = "TableColumn"; public const string Xaml_TableRowGroup = "TableRowGroup"; public const string Xaml_TableRow = "TableRow"; public const string Xaml_TableCell = "TableCell"; public const string Xaml_TableCell_BorderThickness = "BorderThickness"; public const string Xaml_TableCell_BorderBrush = "BorderBrush"; public const string Xaml_TableCell_ColumnSpan = "ColumnSpan"; public const string Xaml_TableCell_RowSpan = "RowSpan"; public const string Xaml_Width = "Width"; public const string Xaml_Brushes_Black = "Black"; public const string Xaml_FontFamily = "FontFamily"; public const string Xaml_FontSize = "FontSize"; public const string Xaml_FontSize_XXLarge = "22pt"; // "XXLarge"; public const string Xaml_FontSize_XLarge = "20pt"; // "XLarge"; public const string Xaml_FontSize_Large = "18pt"; // "Large"; public const string Xaml_FontSize_Medium = "16pt"; // "Medium"; public const string Xaml_FontSize_Small = "12pt"; // "Small"; public const string Xaml_FontSize_XSmall = "10pt"; // "XSmall"; public const string Xaml_FontSize_XXSmall = "8pt"; // "XXSmall"; public const string Xaml_FontWeight = "FontWeight"; public const string Xaml_FontWeight_Bold = "Bold"; public const string Xaml_FontStyle = "FontStyle"; public const string Xaml_Foreground = "Foreground"; public const string Xaml_Background = "Background"; public const string Xaml_TextDecorations = "TextDecorations"; public const string Xaml_TextDecorations_Underline = "Underline"; public const string Xaml_TextIndent = "TextIndent"; public const string Xaml_TextAlignment = "TextAlignment"; // --------------------------------------------------------------------- // // Private Fields // // --------------------------------------------------------------------- #region Private Fields static string _xamlNamespace = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"; #endregion Private Fields } }
zzgaminginc-pointofssale
Samba.Services/HtmlConverter/HtmlToXamlConverter.cs
C#
gpl3
125,977
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using Samba.Domain; using Samba.Domain.Models.Customers; using Samba.Domain.Models.Settings; using Samba.Domain.Models.Tickets; using Samba.Domain.Models.Transactions; using Samba.Localization.Properties; using Samba.Persistance.Data; namespace Samba.Services { public class CashTransactionData { public string Name { get; set; } public DateTime Date { get; set; } public int PaymentType { get; set; } public int TransactionType { get; set; } public decimal Amount { get; set; } public string CustomerName { get; set; } } public class CashService { public dynamic GetCurrentCashOperationData() { if (AppServices.MainDataContext.CurrentWorkPeriod == null) return new[] { 0m, 0m, 0m }; var startDate = AppServices.MainDataContext.CurrentWorkPeriod.StartDate; var cashAmount = Dao.Sum<Payment>(x => x.Amount, x => x.PaymentType == (int)PaymentType.Cash && x.Date > startDate); var creditCardAmount = Dao.Sum<Payment>(x => x.Amount, x => x.PaymentType == (int)PaymentType.CreditCard && x.Date > startDate); var ticketAmount = Dao.Sum<Payment>(x => x.Amount, x => x.PaymentType == (int)PaymentType.Ticket && x.Date > startDate); return new[] { cashAmount, creditCardAmount, ticketAmount }; } public void AddIncome(int customerId, decimal amount, string description, PaymentType paymentType) { AddTransaction(customerId, amount, description, paymentType, TransactionType.Income); } public void AddExpense(int customerId, decimal amount, string description, PaymentType paymentType) { AddTransaction(customerId, amount, description, paymentType, TransactionType.Expense); } public void AddLiability(int customerId, decimal amount, string description) { AddTransaction(customerId, amount, description, 0, TransactionType.Liability); } public void AddReceivable(int customerId, decimal amount, string description) { AddTransaction(customerId, amount, description, 0, TransactionType.Receivable); } public IEnumerable<CashTransaction> GetTransactions(WorkPeriod workPeriod) { Debug.Assert(workPeriod != null); if (workPeriod.StartDate == workPeriod.EndDate) return Dao.Query<CashTransaction>(x => x.Date >= workPeriod.StartDate); return Dao.Query<CashTransaction>(x => x.Date >= workPeriod.StartDate && x.Date < workPeriod.EndDate); } public IEnumerable<CashTransactionData> GetTransactionsWithCustomerData(WorkPeriod workPeriod) { var wp = new WorkPeriod() { StartDate = workPeriod.StartDate, EndDate = workPeriod.EndDate }; if (wp.StartDate == wp.EndDate) wp.EndDate = DateTime.Now; using (var workspace = WorkspaceFactory.CreateReadOnly()) { var lines = from ct in workspace.Queryable<CashTransaction>() join customer in workspace.Queryable<Customer>() on ct.CustomerId equals customer.Id into ctC from customer in ctC.DefaultIfEmpty() where ct.Date >= wp.StartDate && ct.Date < wp.EndDate select new { CashTransaction = ct, Customer = customer }; return lines.ToList().Select(x => new CashTransactionData { Amount = x.CashTransaction.Amount, CustomerName = x.Customer != null ? x.Customer.Name : "", Date = x.CashTransaction.Date, Name = x.CashTransaction.Name, PaymentType = x.CashTransaction.PaymentType, TransactionType = x.CashTransaction.TransactionType }); } } private static void AddTransaction(int customerId, decimal amount, string description, PaymentType paymentType, TransactionType transactionType) { using (var workspace = WorkspaceFactory.Create()) { if (transactionType == TransactionType.Income || transactionType == TransactionType.Expense) { var c = new CashTransaction { Amount = amount, Date = DateTime.Now, Name = description, PaymentType = (int)paymentType, TransactionType = (int)transactionType, UserId = AppServices.CurrentLoggedInUser.Id, CustomerId = customerId }; workspace.Add(c); } else { var c = new AccountTransaction { Amount = amount, Date = DateTime.Now, Name = description, TransactionType = (int)transactionType, UserId = AppServices.CurrentLoggedInUser.Id, CustomerId = customerId }; workspace.Add(c); } workspace.CommitChanges(); } } public static decimal GetAccountBalance(int accountId) { using (var w = WorkspaceFactory.CreateReadOnly()) { var p = w.Queryable<Ticket>().Where(x => x.CustomerId == accountId).SelectMany(x => x.Payments).Where(x => x.PaymentType == 3).Sum(x => (decimal?)x.Amount); //.Sum(x => x.Payments.Where(y => y.PaymentType == 3).Sum(y => y.Amount))); var a = w.Queryable<AccountTransaction>().Where(x => x.CustomerId == accountId).Sum(x => (decimal?)(x.TransactionType == 3 ? x.Amount : 0 - x.Amount)); var t = w.Queryable<CashTransaction>().Where(x => x.CustomerId == accountId).Sum(x => (decimal?)(x.TransactionType == 1 ? x.Amount : 0 - x.Amount)); return p.GetValueOrDefault(0) + a.GetValueOrDefault(0) + t.GetValueOrDefault(0); } //var paymentSum = Dao.Query<Ticket>(x => x.CustomerId == accountId, x => x.Payments).Sum(x => x.Payments.Where(y => y.PaymentType == 3).Sum(y => y.Amount)); //var transactionSum = Dao.Query<CashTransaction>().Where(x => x.CustomerId == accountId).Sum(x => x.TransactionType == 1 ? x.Amount : 0 - x.Amount); //var accountTransactionSum = Dao.Query<AccountTransaction>().Where(x => x.CustomerId == accountId).Sum(x => x.TransactionType == 3 ? x.Amount : 0 - x.Amount); //return paymentSum + transactionSum + accountTransactionSum; } } }
zzgaminginc-pointofssale
Samba.Services/CashService.cs
C#
gpl3
7,757
using System; using System.Collections.Generic; using System.IO; using System.IO.Ports; using System.Linq; using System.Text; namespace Samba.Services { public static class SerialPortService { private static readonly Dictionary<string, SerialPort> Ports = new Dictionary<string, SerialPort>(); public static void WritePort(string portName, byte[] data) { if (!Ports.ContainsKey(portName)) { Ports.Add(portName, new SerialPort(portName)); } var port = Ports[portName]; try { if (!port.IsOpen) port.Open(); if (port.IsOpen) port.Write(data, 0, data.Length); } catch (IOException) { } } public static void WritePort(string portName, string data) { WritePort(portName, Encoding.ASCII.GetBytes(data)); } public static void WritePort(string portName, string data, int codePage) { WritePort(portName, Encoding.GetEncoding(codePage).GetBytes(data)); } public static void ResetCache() { foreach (var key in Ports.Keys) Ports[key].Close(); Ports.Clear(); } internal static void WriteCommand(string portName, string command, int codePage) { if (!string.IsNullOrEmpty(command)) { var data = command.Trim().Split(',').Select(x => Convert.ToInt32(x)).Aggregate("", (current, i) => current + (char)i); WritePort(portName, data, codePage); } } } }
zzgaminginc-pointofssale
Samba.Services/SerialPortService.cs
C#
gpl3
1,742
using System.Collections.Generic; using System.Linq; using System.Printing; using System.Windows.Documents; using Samba.Domain.Models.Settings; using Samba.Domain.Models.Tickets; using Samba.Services.Printing; namespace Samba.Services { public class PrinterService { private LocalPrintServer _printServer; private PrintQueueCollection _printers; internal LocalPrintServer PrintServer { get { return _printServer ?? (_printServer = new LocalPrintServer()); } } internal PrintQueueCollection Printers { get { return _printers ?? (_printers = PrintServer.GetPrintQueues(new[] { EnumeratedPrintQueueTypes.Local, EnumeratedPrintQueueTypes.Connections })); } } internal PrintQueue FindPrinterByName(string printerName) { return Printers.FirstOrDefault(x => x.FullName == printerName); } public IEnumerable<string> GetPrinterNames() { return Printers.Select(printer => printer.FullName).ToList(); } public void ManualPrintTicket(Ticket ticket, PrintJob printer) { AppServices.MainDataContext.UpdateTicketNumber(ticket); if (printer != null) TicketPrinter.ManualPrintTicket(ticket, printer); } public void AutoPrintTicket(Ticket ticket) { TicketPrinter.AutoPrintTicket(ticket); } public void PrintReport(FlowDocument document) { TicketPrinter.PrintReport(document); } public void PrintSlipReport(FlowDocument document) { TicketPrinter.PrintSlipReport(document); } public PrintQueue GetPrinter(string shareName) { return FindPrinterByName(shareName); } public void ExecutePrintJob(PrintJob printJob) { TicketPrinter.ExecutePrintJob(printJob); } public void ResetCache() { _printServer = null; } } }
zzgaminginc-pointofssale
Samba.Services/PrinterService.cs
C#
gpl3
2,484
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using Samba.Domain.Models.Users; namespace Samba.Services { public static class MethodQueue { private static readonly Dictionary<string, Action> MethodList = new Dictionary<string, Action>(); public static void Queue(string key, Action action) { if (!MethodList.ContainsKey(key)) MethodList.Add(key, action); else MethodList[key] = action; } [MethodImpl(MethodImplOptions.Synchronized)] public static void RunQueue() { if (MethodList.Count == 0 || AppServices.CurrentLoggedInUser == User.Nobody || AppServices.MainDataContext.SelectedTicket != null) return; lock (MethodList) { MethodList.Values.ToList().ForEach(x => x.Invoke()); MethodList.Clear(); } } } }
zzgaminginc-pointofssale
Samba.Services/MethodQueue.cs
C#
gpl3
1,035
using System; using System.Data.Entity.Infrastructure; using Samba.Domain.Models.Settings; using Samba.Persistance.Data; namespace Samba.Services { internal static class NumberGenerator { public static int GetNextNumber(int numeratorId) { using (var workspace = WorkspaceFactory.Create()) { var numerator = workspace.Single<Numerator>(x => x.Id == numeratorId); numerator.Number++; try { workspace.CommitChanges(); } catch (DbUpdateConcurrencyException) { return GetNextNumber(numeratorId); } return numerator.Number; } } public static string GetNextString(int numeratorId) { using (var workspace = WorkspaceFactory.Create()) { var numerator = workspace.Single<Numerator>(x => x.Id == numeratorId); numerator.Number++; try { workspace.CommitChanges(); } catch (DbUpdateConcurrencyException) { return GetNextString(numeratorId); } return numerator.GetNumber(); } } } }
zzgaminginc-pointofssale
Samba.Services/NumberGenerator.cs
C#
gpl3
1,419
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using Samba.Localization.Properties; namespace Samba.Services { public static class OpConst { public const string Equal = "="; public const string NotEqual = "!="; public const string Contain = "?"; public const string NotContain = "!?"; public const string Greater = ">"; public const string Less = "<"; public const string Starts = "|<"; public const string Ends = ">|"; } public class RuleConstraintViewModel { public RuleConstraintViewModel() { } public RuleConstraintViewModel(string constraintData) { var parts = constraintData.Split(';'); Name = parts[0]; Operation = parts[1]; if (parts.Count() > 2) Value = parts[2]; } public string Name { get; set; } public string NameDisplay { get { var result = Resources.ResourceManager.GetString(Name); return !string.IsNullOrEmpty(result) ? result + ":" : Name; } } public string Value { get; set; } private IEnumerable<string> _values; public IEnumerable<string> Values { get { return _values ?? (_values = RuleActionTypeRegistry.GetParameterSource(Name)); } } public string Operation { get; set; } public string[] Operations { get; set; } public string GetConstraintData() { return Name + ";" + Operation + ";" + Value; } public static bool IsNumericType(Type type) { if (type == null) { return false; } switch (Type.GetTypeCode(type)) { case TypeCode.Byte: case TypeCode.Decimal: case TypeCode.Double: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.SByte: case TypeCode.Single: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: return true; case TypeCode.Object: if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { return IsNumericType(Nullable.GetUnderlyingType(type)); } return false; } return false; } public bool ValueEquals(object parameterValue) { if (IsNumericType(parameterValue.GetType()) || Operation.Trim() == OpConst.Greater || Operation.Trim() == OpConst.Less) { decimal propertyValue; decimal.TryParse(parameterValue.ToString(), out propertyValue); decimal objectValue; decimal.TryParse(Value, out objectValue); if (objectValue < 0 || propertyValue < 0) return false; if (Operation.Contains(OpConst.NotEqual)) { if (propertyValue.Equals(objectValue)) return false; } else if (Operation.Contains(OpConst.Equal)) { if (!propertyValue.Equals(objectValue)) return false; } else if (Operation.Contains(OpConst.Greater)) { if (propertyValue <= objectValue) return false; } else if (Operation.Contains(OpConst.Less)) { if (propertyValue >= objectValue) return false; } } else { var propertyValue = parameterValue.ToString().ToLower(); var objectValue = Value.ToLower(); if (Operation.Contains(OpConst.NotContain)) { if (propertyValue.Contains(objectValue)) return false; } else if (Operation.Contains(OpConst.Contain)) { if (!propertyValue.Contains(objectValue)) return false; } else if (Operation.Contains(OpConst.Starts)) { if (!propertyValue.StartsWith(objectValue)) return false; } else if (Operation.Contains(OpConst.Ends)) { if (!propertyValue.EndsWith(objectValue)) return false; } else if (Operation.Contains(OpConst.NotEqual)) { if (propertyValue.Equals(objectValue)) return false; } else if (Operation.Contains(OpConst.Equal)) { if (!propertyValue.Equals(objectValue)) return false; } } return true; } } public class RuleActionType { public string ActionType { get; set; } public string ActionName { get; set; } public object ParameterObject { get; set; } } public class RuleEvent { public string EventKey { get; set; } public string EventName { get; set; } public object ParameterObject { get; set; } } public static class RuleActionTypeRegistry { public static IDictionary<string, RuleEvent> RuleEvents = new Dictionary<string, RuleEvent>(); public static IDictionary<string, Func<IEnumerable<string>>> ParameterSource = new Dictionary<string, Func<IEnumerable<string>>>(); public static IEnumerable<string> GetParameterNames(string eventKey) { var po = RuleEvents[eventKey].ParameterObject; return po != null ? po.GetType().GetProperties().Select(x => x.Name) : new List<string>(); } public static void RegisterEvent(string eventKey, string eventName) { RegisterEvent(eventKey, eventName, null); } public static void RegisterEvent(string eventKey, string eventName, object constraintObject) { if (!RuleEvents.ContainsKey(eventKey)) RuleEvents.Add(eventKey, new RuleEvent { EventKey = eventKey, EventName = eventName, ParameterObject = constraintObject }); } public static IDictionary<string, RuleActionType> ActionTypes = new Dictionary<string, RuleActionType>(); public static void RegisterActionType(string actionType, string actionName, object parameterObject = null) { if (!ActionTypes.ContainsKey(actionType)) ActionTypes.Add(actionType, new RuleActionType { ActionName = actionName, ActionType = actionType, ParameterObject = parameterObject }); } public static IEnumerable<RuleConstraintViewModel> GetEventConstraints(string eventName) { var result = new List<RuleConstraintViewModel>(); var obj = RuleEvents[eventName].ParameterObject; if (obj != null) { result.AddRange(obj.GetType().GetProperties().Select( x => new RuleConstraintViewModel { Name = x.Name, Operation = OpConst.Equal, Operations = GetOperations(x.PropertyType) })); } if (!result.Any(x => x.Name == "UserName")) result.Insert(0, new RuleConstraintViewModel { Name = "UserName", Operation = OpConst.Equal, Operations = GetOperations(typeof(string)) }); if (!result.Any(x => x.Name == "DepartmentName")) result.Insert(0, new RuleConstraintViewModel { Name = "DepartmentName", Operation = OpConst.Equal, Operations = GetOperations(typeof(string)) }); if (!result.Any(x => x.Name == "TerminalName")) result.Insert(0, new RuleConstraintViewModel { Name = "TerminalName", Operation = OpConst.Equal, Operations = GetOperations(typeof(string)) }); return result; } private static string[] GetOperations(Type type) { if (RuleConstraintViewModel.IsNumericType(type)) { return new[] { OpConst.Equal, OpConst.NotEqual, OpConst.Greater, OpConst.Less }; } return new[] { OpConst.Equal, OpConst.NotEqual, OpConst.Contain, OpConst.NotContain, OpConst.Starts, OpConst.Ends }; } public static void RegisterParameterSoruce(string parameterName, Func<IEnumerable<string>> action) { ParameterSource.Add(parameterName, action); } public static IEnumerable<string> GetParameterSource(string parameterName) { if (parameterName.StartsWith("Is") && parameterName.Length > 2 && Char.IsUpper(parameterName[2])) return new[] { "True", "False" }; return ParameterSource.ContainsKey(parameterName) ? ParameterSource[parameterName].Invoke() : new List<string>(); } } }
zzgaminginc-pointofssale
Samba.Services/RuleActionTypeRegistry.cs
C#
gpl3
9,745
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Windows; using System.Windows.Threading; using Microsoft.Practices.EnterpriseLibrary.Logging; using Samba.Domain.Models.Settings; using Samba.Domain.Models.Users; using Samba.Infrastructure.Data; using Samba.Infrastructure.Settings; using Samba.Persistance.Data; namespace Samba.Services { public enum AppScreens { LoginScreen, Navigation, SingleTicket, TicketList, Payment, TableList, CustomerList, WorkPeriods, Dashboard, CashView } public static class AppServices { public static Dispatcher MainDispatcher { get; set; } public static AppScreens ActiveAppScreen { get; set; } private static IWorkspace _workspace; public static IWorkspace Workspace { get { return _workspace ?? (_workspace = WorkspaceFactory.Create()); } set { _workspace = value; } } private static MainDataContext _mainDataContext; public static MainDataContext MainDataContext { get { return _mainDataContext ?? (_mainDataContext = new MainDataContext()); } set { _mainDataContext = value; } } private static PrinterService _printService; public static PrinterService PrintService { get { return _printService ?? (_printService = new PrinterService()); } } private static DataAccessService _dataAccessService; public static DataAccessService DataAccessService { get { return _dataAccessService ?? (_dataAccessService = new DataAccessService()); } } private static MessagingService _messagingService; public static MessagingService MessagingService { get { return _messagingService ?? (_messagingService = new MessagingService()); } } private static CashService _cashService; public static CashService CashService { get { return _cashService ?? (_cashService = new CashService()); } } private static SettingService _settingService; public static SettingService SettingService { get { return _settingService ?? (_settingService = new SettingService()); } } private static IEnumerable<Terminal> _terminals; public static IEnumerable<Terminal> Terminals { get { return _terminals ?? (_terminals = Workspace.All<Terminal>()); } } private static Terminal _terminal; public static Terminal CurrentTerminal { get { return _terminal ?? (_terminal = GetCurrentTerminal()); } set { _terminal = value; } } private static User _currentLoggedInUser; public static User CurrentLoggedInUser { get { return _currentLoggedInUser ?? User.Nobody; } private set { _currentLoggedInUser = value; } } public static bool CanNavigate() { return MainDataContext.SelectedTicket == null; } public static bool CanStartApplication() { return LocalSettings.CurrentDbVersion <= 0 || LocalSettings.CurrentDbVersion == LocalSettings.DbVersion; } public static bool CanModifyTicket() { return true; } private static User GetUserByPinCode(string pinCode) { return Workspace.All<User>(x => x.PinCode == pinCode).FirstOrDefault(); } private static LoginStatus CheckPinCodeStatus(string pinCode) { var user = Workspace.Single<User>(x => x.PinCode == pinCode); return user == null ? LoginStatus.PinNotFound : LoginStatus.CanLogin; } private static Terminal GetCurrentTerminal() { if (!string.IsNullOrEmpty(LocalSettings.TerminalName)) { var terminal = Terminals.SingleOrDefault(x => x.Name == LocalSettings.TerminalName); if (terminal != null) return terminal; } var dterminal = Terminals.SingleOrDefault(x => x.IsDefault); return dterminal ?? Terminal.DefaultTerminal; } public static void LogError(Exception e) { MessageBox.Show("Bir sorun tespit ettik.\r\n\r\nProgram çalışmaya devam edecek ancak en kısa zamanda teknik destek almanız önerilir. Lütfen teknik destek için program danışmanınız ile irtibat kurunuz.\r\n\r\nMesaj:\r\n" + e.Message, "Bilgi", MessageBoxButton.OK, MessageBoxImage.Stop); Logger.Write(e, "General"); } public static void LogError(Exception e, string userMessage) { MessageBox.Show(userMessage, "Bilgi", MessageBoxButton.OK, MessageBoxImage.Information); Logger.Write(e, "General"); } public static void Log(string message) { Logger.Write(message, "General", 0, 0, TraceEventType.Verbose); } public static void Log(string message, string category) { Logger.Write(message, category); } public static void ResetCache() { _terminal = null; _terminals = null; MainDataContext.ResetCache(); PrintService.ResetCache(); SettingService.ResetCache(); SerialPortService.ResetCache(); Dao.ResetCache(); Workspace = WorkspaceFactory.Create(); } public static User LoginUser(string pinValue) { Debug.Assert(CurrentLoggedInUser == User.Nobody); CurrentLoggedInUser = CanStartApplication() && CheckPinCodeStatus(pinValue) == LoginStatus.CanLogin ? GetUserByPinCode(pinValue) : User.Nobody; MainDataContext.ResetUserData(); return CurrentLoggedInUser; } public static void LogoutUser(bool resetCache = true) { Debug.Assert(CurrentLoggedInUser != User.Nobody); CurrentLoggedInUser = User.Nobody; if (resetCache) ResetCache(); } public static bool IsUserPermittedFor(string p) { if (CurrentLoggedInUser.UserRole.IsAdmin) return true; if (CurrentLoggedInUser.UserRole.Id == 0) return false; var permission = CurrentLoggedInUser.UserRole.Permissions.SingleOrDefault(x => x.Name == p); if (permission == null) return false; return permission.Value == (int)PermissionValue.Enabled; } } }
zzgaminginc-pointofssale
Samba.Services/AppServices.cs
C#
gpl3
6,811
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using Samba.Domain.Foundation; using Samba.Domain.Models.Menus; using Samba.Domain.Models.Settings; using Samba.Domain.Models.Tables; using Samba.Domain.Models.Tickets; using Samba.Domain.Models.Users; using Samba.Infrastructure.Data; using Samba.Infrastructure.Settings; using Samba.Localization.Properties; using Samba.Persistance.Data; namespace Samba.Services { public class DataCreationService { private readonly IWorkspace _workspace; public DataCreationService() { _workspace = WorkspaceFactory.Create(); } private bool ShouldCreateData() { return _workspace.Count<User>() == 0; } public void CreateData() { CreateDefaultCurrenciesIfNeeded(); if (!ShouldCreateData()) return; var screen = new ScreenMenu(); _workspace.Add(screen); var ticketNumerator = new Numerator { Name = Resources.TicketNumerator }; _workspace.Add(ticketNumerator); var orderNumerator = new Numerator { Name = Resources.OrderNumerator }; _workspace.Add(orderNumerator); _workspace.CommitChanges(); var department = new Department { Name = Resources.Restaurant, ScreenMenuId = screen.Id, TicketNumerator = ticketNumerator, OrderNumerator = orderNumerator, IsAlaCarte = true }; _workspace.Add(department); var role = new UserRole("Admin") { IsAdmin = true, DepartmentId = 1 }; _workspace.Add(role); var u = new User("Administrator", "1234") { UserRole = role }; _workspace.Add(u); var ticketTemplate = new PrinterTemplate(); ticketTemplate.Name = Resources.TicketTemplate; ticketTemplate.HeaderTemplate = Resources.TicketTemplateHeaderValue; ticketTemplate.LineTemplate = Resources.TicketTempleteLineTemplateValue; ticketTemplate.GiftLineTemplate = Resources.TicketTemplateGiftedLineTemplateValue; ticketTemplate.FooterTemplate = Resources.TicketTemplateFooterValue; var kitchenTemplate = new PrinterTemplate(); kitchenTemplate.Name = Resources.KitchenOrderTemplate; kitchenTemplate.HeaderTemplate = Resources.KitchenTemplateHeaderValue; kitchenTemplate.LineTemplate = Resources.KitchenTemplateLineTemplateValue; kitchenTemplate.GiftLineTemplate = Resources.KitchenTemplateLineTemplateValue; kitchenTemplate.VoidedLineTemplate = Resources.KitchenTemplateVoidedLineTemplateValue; kitchenTemplate.FooterTemplate = "<F>-"; var invoiceTemplate = new PrinterTemplate(); invoiceTemplate.Name = Resources.InvoicePrinterTemplate; invoiceTemplate.HeaderTemplate = Resources.InvoiceTemplateHeaderValue; invoiceTemplate.LineTemplate = Resources.InvoiceTemplateLineTemplateValue; invoiceTemplate.VoidedLineTemplate = ""; invoiceTemplate.FooterTemplate = "<F>-"; _workspace.Add(ticketTemplate); _workspace.Add(kitchenTemplate); _workspace.Add(invoiceTemplate); var printer1 = new Printer { Name = Resources.TicketPrinter }; var printer2 = new Printer { Name = Resources.KitchenPrinter }; var printer3 = new Printer { Name = Resources.InvoicePrinter }; _workspace.Add(printer1); _workspace.Add(printer2); _workspace.Add(printer3); var t = new Terminal { IsDefault = true, Name = Resources.Server, SlipReportPrinter = printer1, }; var pm1 = new PrinterMap { Printer = printer1, PrinterTemplate = ticketTemplate }; _workspace.Add(pm1); var pj1 = new PrintJob { Name = Resources.PrintBill, ButtonText = Resources.PrintBill, LocksTicket = true, Order = 0, UseFromPaymentScreen = true, UseFromTerminal = true, UseFromPos = true, WhatToPrint = (int)WhatToPrintTypes.Everything, WhenToPrint = (int)WhenToPrintTypes.Manual }; pj1.PrinterMaps.Add(pm1); _workspace.Add(pj1); var pm2 = new PrinterMap { Printer = printer2, PrinterTemplate = kitchenTemplate }; var pj2 = new PrintJob { Name = Resources.PrintOrdersToKitchenPrinter, ButtonText = "", Order = 1, WhatToPrint = (int)WhatToPrintTypes.NewLines, WhenToPrint = (int)WhenToPrintTypes.NewLinesAdded }; pj2.PrinterMaps.Add(pm2); _workspace.Add(pj2); t.PrintJobs.Add(pj1); t.PrintJobs.Add(pj2); _workspace.Add(t); ImportMenus(screen); ImportTables(department); _workspace.CommitChanges(); _workspace.Dispose(); } private void ImportTables(Department department) { var fileName = string.Format("{0}/Imports/table{1}.txt", LocalSettings.AppPath, "_" + LocalSettings.CurrentLanguage); if (!File.Exists(fileName)) fileName = string.Format("{0}/Imports/table.txt", LocalSettings.AppPath); if (!File.Exists(fileName)) return; var lines = File.ReadAllLines(fileName); var items = BatchCreateTables(lines, _workspace); _workspace.CommitChanges(); var screen = new TableScreen { Name = Resources.AllTables, ColumnCount = 8 }; _workspace.Add(screen); foreach (var table in items) screen.AddScreenItem(table); _workspace.CommitChanges(); department.TableScreenId = screen.Id; } private void ImportMenus(ScreenMenu screenMenu) { var fileName = string.Format("{0}/Imports/menu{1}.txt", LocalSettings.AppPath, "_" + LocalSettings.CurrentLanguage); if (!File.Exists(fileName)) fileName = string.Format("{0}/Imports/menu.txt", LocalSettings.AppPath); if (!File.Exists(fileName)) return; var lines = File.ReadAllLines(fileName, Encoding.UTF8); var items = BatchCreateMenuItems(lines, _workspace); _workspace.CommitChanges(); var groupCodes = items.Select(x => x.GroupCode).Distinct().Where(x => !string.IsNullOrEmpty(x)); foreach (var groupCode in groupCodes) { var code = groupCode; screenMenu.AddCategory(code); screenMenu.AddItemsToCategory(groupCode, items.Where(x => x.GroupCode == code).ToList()); } } public IEnumerable<Table> BatchCreateTables(string[] values, IWorkspace workspace) { IList<Table> result = new List<Table>(); if (values.Length > 0) { var currentCategory = Resources.Common; foreach (var value in values) { if (value.StartsWith("#")) { currentCategory = value.Trim('#', ' '); } else { var tableName = value; var count = Dao.Count<Table>(y => y.Name == tableName.Trim()); if (count == 0) { var table = new Table { Name = value.Trim(), Category = currentCategory }; if (result.Count(x => x.Name.ToLower() == table.Name.ToLower()) == 0) { result.Add(table); workspace.Add(table); } } } } } return result; } public IEnumerable<MenuItem> BatchCreateMenuItems(string[] values, IWorkspace workspace) { var ds = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator; IList<MenuItem> result = new List<MenuItem>(); if (values.Length > 0) { var currentCategory = Resources.Common; foreach (var item in values) { if (item.StartsWith("#")) { currentCategory = item.Trim('#', ' '); } else if (item.Contains(" ")) { IList<string> parts = new List<string>(item.Split(' ')); var price = ConvertToDecimal(parts[parts.Count - 1], ds); parts.RemoveAt(parts.Count - 1); var itemName = string.Join(" ", parts.ToArray()); var mi = MenuItem.Create(); mi.Name = itemName; mi.Portions[0].Price.Amount = price; mi.GroupCode = currentCategory; workspace.Add(mi); workspace.Add(mi.Portions[0]); result.Add(mi); } } } return result; } public IEnumerable<Reason> BatchCreateReasons(string[] values, int reasonType, IWorkspace workspace) { IList<Reason> result = new List<Reason>(); if (values.Length > 0) { foreach (var reason in values.Select(value => new Reason { Name = value, ReasonType = reasonType })) { workspace.Add(reason); result.Add(reason); } } return result; } private static decimal ConvertToDecimal(string priceStr, string decimalSeperator) { try { priceStr = priceStr.Replace(".", decimalSeperator); priceStr = priceStr.Replace(",", decimalSeperator); var price = Convert.ToDecimal(priceStr); return price; } catch (Exception) { return 0; } } private static void CreateDefaultCurrenciesIfNeeded() { LocalSettings.DefaultCurrencyFormat = "C"; } } }
zzgaminginc-pointofssale
Samba.Services/DataCreationService.cs
C#
gpl3
11,165
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Samba.Services")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Samba.Services")] [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("550a7b63-9618-4f7d-95c5-7c1ec0e56bae")] // 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.Services/Properties/AssemblyInfo.cs
C#
gpl3
1,440
using System; using System.IO; using System.Linq; using System.Net; using System.Net.Mail; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Threading; namespace Samba.Services { public static class EMailService { public static void SendEmail(string smtpServerAddress, string smtpUser, string smtpPassword, int smtpPort, string toEmailAddress, string fromEmailAddress, string subject, string body, string fileName, bool deleteFile, bool bypassSslErrors) { var mail = new MailMessage(); var smtpServer = new SmtpClient(smtpServerAddress); try { mail.From = new MailAddress(fromEmailAddress); mail.To.Add(toEmailAddress); mail.Subject = subject; mail.Body = body; if (!string.IsNullOrEmpty(fileName)) fileName.Split(',').ToList().ForEach(x => mail.Attachments.Add(new Attachment(x))); smtpServer.Port = smtpPort; smtpServer.Credentials = new NetworkCredential(smtpUser, smtpPassword); smtpServer.EnableSsl = true; if (bypassSslErrors) ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; }; smtpServer.Send(mail); } catch (Exception e) { AppServices.LogError(e); } finally { if (deleteFile && !string.IsNullOrEmpty(fileName)) { fileName.Split(',').ToList().ForEach( x => { if (File.Exists(x)) { try { File.Delete(x); } catch (Exception) { } } }); } } } public static void SendEMailAsync(string smtpServerAddress, string smtpUser, string smtpPassword, int smtpPort, string toEmailAddress, string fromEmailAddress, string subject, string body, string fileName, bool deleteFile, bool byPassSslErrors) { var thread = new Thread(() => SendEmail(smtpServerAddress, smtpUser, smtpPassword, smtpPort, toEmailAddress, fromEmailAddress, subject, body, fileName, deleteFile, byPassSslErrors)); thread.Start(); } } }
zzgaminginc-pointofssale
Samba.Services/EMailService.cs
C#
gpl3
2,756
using System; using System.Runtime.CompilerServices; using System.Threading; using Samba.Infrastructure; using Samba.Infrastructure.Settings; namespace Samba.Services { internal class MessageData { public string Command { get; set; } public string Value { get; set; } } public class MessagingService { private IMessageListener _messageListener; public bool Reconnecting { get; set; } public bool IsConnected { get { return MessagingClient.IsConnected; } } public int ConnectionCount { get { return GetConnectionCount(); } } public void RegisterMessageListener(IMessageListener listener) { _messageListener = listener; } public bool CanStartMessagingClient() { return _messageListener != null && !MessagingClient.IsConnected; } public void StartMessagingClient() { if (_messageListener != null) { if (!CanStartMessagingClient()) throw new Exception("Mesaj istemcisi başlatılamaz."); MessagingClient.Connect(_messageListener); } } public void SendMessage(string command, string value) { ThreadPool.QueueUserWorkItem(SendMessageAsync, new MessageData { Command = command, Value = value }); } public string FormatMessage(string command, string value) { return string.Format("{0}:<{1}>{2}", _messageListener.Key, command, value); } [MethodImpl(MethodImplOptions.Synchronized)] private void SendMessageAsync(object data) { var mData = data as MessageData; try { if (MessagingClient.IsConnected) { if (mData != null) MessagingClient.SendMessage(FormatMessage(mData.Command, mData.Value)); } else if (LocalSettings.StartMessagingClient && !Reconnecting) Reconnect(); } catch (Exception) { //AppServices.MainDispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action(Reconnect)); } } private static int GetConnectionCount() { try { if (MessagingClient.IsConnected) { return MessagingClient.GetConnectionCount(); } } catch (Exception) { return 0; } return 0; } public bool Connected() { return MessagingClient.CanPing(); } public void Reconnect() { Reconnecting = true; try { MessagingClient.Reconnect(_messageListener); } finally { Reconnecting = false; } } } }
zzgaminginc-pointofssale
Samba.Services/MessagingService.cs
C#
gpl3
3,146
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using Samba.Domain.Models.Actions; using Samba.Domain.Models.Customers; using Samba.Domain.Models.Menus; using Samba.Domain.Models.Settings; using Samba.Domain.Models.Tables; using Samba.Domain.Models.Tickets; using Samba.Domain.Models.Users; using Samba.Infrastructure.Data; using Samba.Infrastructure.Data.Serializer; using Samba.Infrastructure.Settings; using Samba.Localization.Properties; using Samba.Persistance.Data; namespace Samba.Services { public class TicketCommitResult { public int TicketId { get; set; } public string ErrorMessage { get; set; } } public class MainDataContext { private class TicketWorkspace { private IWorkspace _workspace; public Ticket Ticket { get; private set; } public void CreateTicket(Department department) { Debug.Assert(_workspace == null); Debug.Assert(Ticket == null); Debug.Assert(department != null); _workspace = WorkspaceFactory.Create(); Ticket = Ticket.Create(department); } public void OpenTicket(int ticketId) { Debug.Assert(_workspace == null); Debug.Assert(Ticket == null); _workspace = WorkspaceFactory.Create(); if (LocalSettings.DatabaseLabel == "CE") Ticket = _workspace.Single<Ticket>(ticket => ticket.Id == ticketId); else { Ticket = _workspace.Single<Ticket>(ticket => ticket.Id == ticketId, x => x.TicketItems.Select(y => y.Properties), x => x.Payments, x => x.Discounts, x => x.TaxServices); } } public void CommitChanges() { Debug.Assert(_workspace != null); Debug.Assert(Ticket != null); Debug.Assert(Ticket.Id > 0 || Ticket.TicketItems.Count > 0); if (Ticket.Id == 0 && Ticket.TicketNumber != null) _workspace.Add(Ticket); Ticket.LastUpdateTime = DateTime.Now; _workspace.CommitChanges(); } public void Reset() { Debug.Assert(Ticket != null); Debug.Assert(_workspace != null); Ticket = null; _workspace = null; } public Table LoadTable(string locationName) { return _workspace.Single<Table>(x => x.Name == locationName); } public Customer UpdateCustomer(Customer customer) { if (customer == Customer.Null) return Customer.Null; if (customer.Id == 0) { using (var workspace = WorkspaceFactory.Create()) { workspace.Add(customer); workspace.CommitChanges(); } return customer; } var result = _workspace.Single<Customer>( x => x.Id == customer.Id && x.Name == customer.Name && x.Address == customer.Address && x.PhoneNumber == customer.PhoneNumber && x.Note == customer.Note); if (result == null) { result = _workspace.Single<Customer>(x => x.Id == customer.Id); Debug.Assert(result != null); result.Address = customer.Address; result.Name = customer.Name; result.PhoneNumber = customer.PhoneNumber; result.Note = customer.Note; } return result; } public Table GetTableWithId(int tableId) { return _workspace.Single<Table>(x => x.Id == tableId); } public Table GetTicketTable() { Debug.Assert(!string.IsNullOrEmpty(Ticket.LocationName)); Debug.Assert(Ticket != null); return _workspace.Single<Table>(x => x.Name == Ticket.LocationName); } public void ResetTableData(Ticket ticket) { var tables = _workspace.All<Table>(x => x.TicketId == ticket.Id); foreach (var table in tables) { table.TicketId = 0; table.IsTicketLocked = false; } } public void RemoveTicketItems(IEnumerable<TicketItem> selectedItems) { foreach (var ticketItem in selectedItems) { Ticket.TicketItems.Remove(ticketItem); if (Ticket.Id > 0) { ticketItem.Properties.ToList().ForEach(_workspace.Delete); _workspace.Delete(ticketItem); } } } public void RemoveTaxServices(IEnumerable<TaxService> taxServices) { foreach (var taxService in taxServices) { _workspace.Delete(taxService); } } public void AddItemToSelectedTicket(TicketItem model) { _workspace.Add(model); } } public int CustomerCount { get; set; } public int TableCount { get; set; } public string NumeratorValue { get; set; } private IWorkspace _tableWorkspace; private readonly TicketWorkspace _ticketWorkspace = new TicketWorkspace(); private IEnumerable<AppRule> _rules; public IEnumerable<AppRule> Rules { get { return _rules ?? (_rules = Dao.Query<AppRule>(x => x.Actions)); } } private IEnumerable<AppAction> _actions; public IEnumerable<AppAction> Actions { get { return _actions ?? (_actions = Dao.Query<AppAction>()); } } private IEnumerable<TableScreen> _tableScreens; public IEnumerable<TableScreen> TableScreens { get { return _tableScreens ?? (_tableScreens = Dao.Query<TableScreen>(x => x.Tables)); } } private IEnumerable<Department> _departments; public IEnumerable<Department> Departments { get { return _departments ?? (_departments = Dao.Query<Department>(x => x.TicketNumerator, x => x.OrderNumerator, x => x.TaxServiceTemplates, x => x.TicketTagGroups.Select(y => y.Numerator), x => x.TicketTagGroups.Select(y => y.TicketTags))); } } private IEnumerable<Department> _permittedDepartments; public IEnumerable<Department> PermittedDepartments { get { return _permittedDepartments ?? ( _permittedDepartments = Departments.Where( x => AppServices.IsUserPermittedFor(PermissionNames.UseDepartment + x.Id))); } } private IDictionary<int, Reason> _reasons; public IDictionary<int, Reason> Reasons { get { return _reasons ?? (_reasons = Dao.BuildDictionary<Reason>()); } } private IEnumerable<WorkPeriod> _lastTwoWorkPeriods; public IEnumerable<WorkPeriod> LastTwoWorkPeriods { get { return _lastTwoWorkPeriods ?? (_lastTwoWorkPeriods = GetLastTwoWorkPeriods()); } } private IEnumerable<User> _users; public IEnumerable<User> Users { get { return _users ?? (_users = Dao.Query<User>(x => x.UserRole)); } } private IEnumerable<VatTemplate> _vatTemplates; public IEnumerable<VatTemplate> VatTemplates { get { return _vatTemplates ?? (_vatTemplates = Dao.Query<VatTemplate>()); } } private IEnumerable<TaxServiceTemplate> _taxServiceTemplates; public IEnumerable<TaxServiceTemplate> TaxServiceTemplates { get { return _taxServiceTemplates ?? (_taxServiceTemplates = Dao.Query<TaxServiceTemplate>()); } } public WorkPeriod CurrentWorkPeriod { get { return LastTwoWorkPeriods.LastOrDefault(); } } public WorkPeriod PreviousWorkPeriod { get { return LastTwoWorkPeriods.Count() > 1 ? LastTwoWorkPeriods.FirstOrDefault() : null; } } public TableScreen SelectedTableScreen { get; set; } public Ticket SelectedTicket { get { return _ticketWorkspace.Ticket; } } private Department _selectedDepartment; public Department SelectedDepartment { get { return _selectedDepartment; } set { if (value != null && (_selectedDepartment == null || _selectedDepartment.Id != value.Id)) { SelectedTableScreen = TableScreens.FirstOrDefault(x => x.Id == value.TableScreenId); } _selectedDepartment = value; } } public bool IsCurrentWorkPeriodOpen { get { return CurrentWorkPeriod != null && CurrentWorkPeriod.StartDate == CurrentWorkPeriod.EndDate; } } public MainDataContext() { _ticketWorkspace = new TicketWorkspace(); } private static IEnumerable<WorkPeriod> GetLastTwoWorkPeriods() { return Dao.Last<WorkPeriod>(2); } public void ResetUserData() { _permittedDepartments = null; ThreadPool.QueueUserWorkItem(ResetTableCustomerCounts); } private void ResetTableCustomerCounts(object state) { CustomerCount = Dao.Count<Customer>(null); TableCount = Dao.Count<Table>(null); } public void StartWorkPeriod(string description, decimal cashAmount, decimal creditCardAmount, decimal ticketAmount) { using (var workspace = WorkspaceFactory.Create()) { _lastTwoWorkPeriods = null; var latestWorkPeriod = workspace.Last<WorkPeriod>(); if (latestWorkPeriod != null && latestWorkPeriod.StartDate == latestWorkPeriod.EndDate) { return; } var now = DateTime.Now; var newPeriod = new WorkPeriod { StartDate = now, EndDate = now, StartDescription = description, CashAmount = cashAmount, CreditCardAmount = creditCardAmount, TicketAmount = ticketAmount }; workspace.Add(newPeriod); workspace.CommitChanges(); _lastTwoWorkPeriods = null; } } public void StopWorkPeriod(string description) { using (var workspace = WorkspaceFactory.Create()) { var period = workspace.Last<WorkPeriod>(); if (period.EndDate == period.StartDate) { period.EndDate = DateTime.Now; period.EndDescription = description; workspace.CommitChanges(); } _lastTwoWorkPeriods = null; } } public string GetReason(int reasonId) { return Reasons.ContainsKey(reasonId) ? Reasons[reasonId].Name : Resources.UndefinedWithBrackets; } public void UpdateTicketTable(Ticket ticket) { if (string.IsNullOrEmpty(ticket.LocationName)) return; var table = _ticketWorkspace.LoadTable(ticket.LocationName); if (table != null) { if (ticket.IsPaid || ticket.TicketItems.Count == 0) { if (table.TicketId == ticket.Id) { table.TicketId = 0; table.IsTicketLocked = false; } } else { table.TicketId = ticket.Id; table.IsTicketLocked = ticket.Locked; } } else ticket.LocationName = ""; } public void UpdateTableData(TableScreen selectedTableScreen, int pageNo) { var set = selectedTableScreen.Tables.Select(x => x.Id); if (selectedTableScreen.PageCount > 1) { set = selectedTableScreen.Tables .OrderBy(x => x.Order) .Skip(pageNo * selectedTableScreen.ItemCountPerPage) .Take(selectedTableScreen.ItemCountPerPage) .Select(x => x.Id); } var result = Dao.Select<Table, dynamic>(x => new { x.Id, Tid = x.TicketId, Locked = x.IsTicketLocked }, x => set.Contains(x.Id)); foreach (var td in result) { var tid = td.Id; var table = selectedTableScreen.Tables.Single(x => x.Id == tid); table.TicketId = td.Tid; table.IsTicketLocked = td.Locked; } } public void AssignCustomerToTicket(Ticket ticket, Customer customer) { Debug.Assert(ticket != null); ticket.UpdateCustomer(_ticketWorkspace.UpdateCustomer(customer)); } public void AssignCustomerToSelectedTicket(Customer customer) { if (SelectedTicket == null) { CreateNewTicket(); } AssignCustomerToTicket(SelectedTicket, customer); } public void AssignTableToSelectedTicket(int tableId) { if (SelectedTicket == null) { CreateNewTicket(); } var table = _ticketWorkspace.GetTableWithId(tableId); Debug.Assert(SelectedTicket != null); if (!string.IsNullOrEmpty(SelectedTicket.LocationName)) { var oldTable = _ticketWorkspace.GetTicketTable(); if (oldTable.TicketId == SelectedTicket.Id) { oldTable.IsTicketLocked = false; oldTable.TicketId = 0; } } if (table.TicketId > 0 && table.TicketId != SelectedTicket.Id) { MoveTicketItems(SelectedTicket.TicketItems.ToList(), table.TicketId); OpenTicket(table.TicketId); } SelectedTicket.DepartmentId = AppServices.CurrentTerminal.DepartmentId > 0 ? AppServices.CurrentTerminal.DepartmentId : SelectedDepartment.Id; SelectedTicket.LocationName = table.Name; table.TicketId = SelectedTicket.GetRemainingAmount() > 0 ? SelectedTicket.Id : 0; } public void UpdateTables(int tableScreenId, int pageNo) { SelectedTableScreen = null; if (tableScreenId > 0) { SelectedTableScreen = TableScreens.Single(x => x.Id == tableScreenId); AppServices.MainDataContext.UpdateTableData(SelectedTableScreen, pageNo); } } public void OpenTicket(int ticketId) { _ticketWorkspace.OpenTicket(ticketId); } public TicketCommitResult CloseTicket() { var result = new TicketCommitResult(); Debug.Assert(SelectedTicket != null); var changed = false; if (SelectedTicket.Id > 0) { var lup = Dao.Single<Ticket, DateTime>(SelectedTicket.Id, x => x.LastUpdateTime); if (SelectedTicket.LastUpdateTime.CompareTo(lup) != 0) { var currentTicket = Dao.Single<Ticket>(x => x.Id == SelectedTicket.Id, x => x.TicketItems, x => x.Payments); if (currentTicket.LocationName != SelectedTicket.LocationName) { result.ErrorMessage = string.Format(Resources.TicketMovedRetryLastOperation_f, currentTicket.LocationName); changed = true; } if (currentTicket.IsPaid != SelectedTicket.IsPaid) { if (currentTicket.IsPaid) { result.ErrorMessage = Resources.TicketPaidChangesNotSaved; } if (SelectedTicket.IsPaid) { result.ErrorMessage = Resources.TicketChangedRetryLastOperation; } changed = true; } else if (SelectedTicket.RemainingAmount == 0 && currentTicket.TotalAmount != SelectedTicket.TotalAmount) { result.ErrorMessage = Resources.TicketChangedRetryLastOperation; changed = true; } else if (currentTicket.LastPaymentDate != SelectedTicket.LastPaymentDate) { var currentPaymentIds = SelectedTicket.Payments.Select(x => x.Id).Distinct(); var unknownPayments = currentTicket.Payments.Where(x => !currentPaymentIds.Contains(x.Id)).FirstOrDefault(); if (unknownPayments != null) { result.ErrorMessage = Resources.TicketPaidLastChangesNotSaved; changed = true; } } } } if (!string.IsNullOrEmpty(SelectedTicket.LocationName) && SelectedTicket.Id == 0) { var ticketId = Dao.Select<Table, int>(x => x.TicketId, x => x.Name == SelectedTicket.LocationName).FirstOrDefault(); { if (ticketId > 0) { result.ErrorMessage = string.Format(Resources.TableChangedRetryLastOperation_f, SelectedTicket.LocationName); changed = true; } } } var canSumbitTicket = !changed && SelectedTicket.CanSubmit; // Fişi kaydedebilmek için gün sonu yapılmamış ve fişin ödenmemiş olması gerekir. if (canSumbitTicket) { _ticketWorkspace.RemoveTicketItems(SelectedTicket.PopRemovedTicketItems()); _ticketWorkspace.RemoveTaxServices(SelectedTicket.PopRemovedTaxServices()); Recalculate(SelectedTicket); if (!SelectedTicket.IsPaid && SelectedTicket.RemainingAmount == 0 && AppServices.CurrentTerminal.DepartmentId > 0) SelectedTicket.DepartmentId = AppServices.CurrentTerminal.DepartmentId; SelectedTicket.IsPaid = SelectedTicket.RemainingAmount == 0; if (SelectedTicket.TicketItems.Count > 0) { if (SelectedTicket.TicketItems.Where(x => !x.Locked).FirstOrDefault() != null) { SelectedTicket.MergeLinesAndUpdateOrderNumbers(NumberGenerator.GetNextNumber(SelectedDepartment.OrderNumerator.Id)); } if (SelectedTicket.Id == 0) { UpdateTicketNumber(SelectedTicket); SelectedTicket.LastOrderDate = DateTime.Now; _ticketWorkspace.CommitChanges(); } Debug.Assert(!string.IsNullOrEmpty(SelectedTicket.TicketNumber)); Debug.Assert(SelectedTicket.Id > 0); //Otomatik yazdırma AppServices.PrintService.AutoPrintTicket(SelectedTicket); SelectedTicket.LockTicket(); } UpdateTicketTable(SelectedTicket); if (SelectedTicket.Id > 0) // eğer adisyonda satır yoksa ID burada 0 olmalı. _ticketWorkspace.CommitChanges(); Debug.Assert(SelectedTicket.TicketItems.Count(x => x.OrderNumber == 0) == 0); } result.TicketId = SelectedTicket.Id; _ticketWorkspace.Reset(); return result; } public void UpdateTicketNumber(Ticket ticket) { UpdateTicketNumber(ticket, SelectedDepartment.TicketNumerator); } public void UpdateTicketNumber(Ticket ticket, Numerator numerator) { if (numerator == null) numerator = SelectedDepartment.TicketNumerator; if (string.IsNullOrEmpty(ticket.TicketNumber)) ticket.TicketNumber = NumberGenerator.GetNextString(numerator.Id); } public IList<Table> LoadTables(string selectedTableScreen) { if (_tableWorkspace != null) { _tableWorkspace.CommitChanges(); } _tableWorkspace = WorkspaceFactory.Create(); return _tableWorkspace.Single<TableScreen>(x => x.Name == selectedTableScreen).Tables; } public void SaveTables() { if (_tableWorkspace != null) { _tableWorkspace.CommitChanges(); _tableWorkspace = null; _tableScreens = null; } } public void ResetCache() { Debug.Assert(_ticketWorkspace.Ticket == null); if (_tableWorkspace == null) { var selectedDepartment = SelectedDepartment != null ? SelectedDepartment.Id : 0; var selectedTableScreen = SelectedTableScreen != null ? SelectedTableScreen.Id : 0; SelectedTableScreen = null; SelectedDepartment = null; _tableScreens = null; _departments = null; _permittedDepartments = null; _reasons = null; _lastTwoWorkPeriods = null; _users = null; _rules = null; _actions = null; _vatTemplates = null; _taxServiceTemplates = null; if (selectedTableScreen > 0 && TableScreens.Count(x => x.Id == selectedTableScreen) > 0) SelectedTableScreen = TableScreens.Single(x => x.Id == selectedTableScreen); if (selectedDepartment > 0 && Departments.Count(x => x.Id == selectedDepartment) > 0) SelectedDepartment = Departments.Single(x => x.Id == selectedDepartment); } } public void OpenTicketFromTableName(string tableName) { var table = Dao.SingleWithCache<Table>(x => x.Name == tableName); if (table != null) { if (table.TicketId > 0) OpenTicket(table.TicketId); AssignTableToSelectedTicket(table.Id); } } public void OpenTicketFromTicketNumber(string ticketNumber) { Debug.Assert(_ticketWorkspace.Ticket == null); var id = Dao.Select<Ticket, int>(x => x.Id, x => x.TicketNumber == ticketNumber).FirstOrDefault(); if (id > 0) OpenTicket(id); } public string GetUserName(int userId) { return userId > 0 ? Users.Single(x => x.Id == userId).Name : "-"; } public void CreateNewTicket() { var department = SelectedDepartment; if (AppServices.CurrentTerminal.DepartmentId > 0 && AppServices.CurrentTerminal.DepartmentId != department.Id) department = Departments.Single(x => x.Id == AppServices.CurrentTerminal.DepartmentId); _ticketWorkspace.CreateTicket(department); } public TicketCommitResult MoveTicketItems(IEnumerable<TicketItem> selectedItems, int targetTicketId) { var clonedItems = selectedItems.Select(ObjectCloner.Clone).ToList(); _ticketWorkspace.RemoveTicketItems(selectedItems); if (SelectedTicket.TicketItems.Count == 0) { var info = targetTicketId.ToString(); if (targetTicketId > 0) { var tData = Dao.Single<Ticket, dynamic>(targetTicketId, x => new { x.LocationName, x.TicketNumber }); info = tData.LocationName + " - " + tData.TicketNumber; } if (!string.IsNullOrEmpty(SelectedTicket.Note)) SelectedTicket.Note += "\r"; SelectedTicket.Note += SelectedTicket.LocationName + " => " + info; } CloseTicket(); if (targetTicketId == 0) CreateNewTicket(); else OpenTicket(targetTicketId); foreach (var ticketItem in clonedItems) { SelectedTicket.TicketItems.Add(ticketItem); } SelectedTicket.LastOrderDate = DateTime.Now; return CloseTicket(); } public void ResetTableDataForSelectedTicket() { _ticketWorkspace.ResetTableData(SelectedTicket); AppServices.MainDataContext.UpdateTicketTable(SelectedTicket); _ticketWorkspace.CommitChanges(); } public void AddItemToSelectedTicket(TicketItem model) { _ticketWorkspace.AddItemToSelectedTicket(model); } public void Recalculate(Ticket ticket) { ticket.Recalculate(AppServices.SettingService.AutoRoundDiscount, AppServices.CurrentLoggedInUser.Id); } public VatTemplate GetVatTemplate(int menuItemId) { return AppServices.DataAccessService.GetMenuItem(menuItemId).VatTemplate; } } }
zzgaminginc-pointofssale
Samba.Services/MainDataContext.cs
C#
gpl3
27,215
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Samba.Domain; using Samba.Domain.Models.Tickets; using Samba.Infrastructure.Settings; namespace Samba.Services { public enum ProcessType { PreAuth, Force, Cancel } public class CreditCardProcessingResult { public ProcessType ProcessType { get; set; } public decimal Amount { get; set; } } public class CreditCardProcessingData { public Ticket Ticket { get; set; } public decimal TenderedAmount { get; set; } } public interface ICreditCardProcessor { string Name { get; } void EditSettings(); void Process(CreditCardProcessingData creditCardProcessingData); bool ForcePayment(int ticketId); } public static class CreditCardProcessingService { private static IList<ICreditCardProcessor> CreditCardProcessors { get; set; } static CreditCardProcessingService() { CreditCardProcessors = new List<ICreditCardProcessor>(); } public static void RegisterCreditCardProcessor(ICreditCardProcessor processor) { CreditCardProcessors.Add(processor); } public static IEnumerable<ICreditCardProcessor> GetProcessors() { return CreditCardProcessors; } public static ICreditCardProcessor GetDefaultProcessor() { var processorName = LocalSettings.DefaultCreditCardProcessorName; var result = CreditCardProcessors.FirstOrDefault(x => x.Name == processorName); return result; } public static bool CanProcessCreditCards { get { return GetDefaultProcessor() != null; } } public static void Process(CreditCardProcessingData ccpd) { GetDefaultProcessor().Process(ccpd); } public static bool ForcePayment(int ticketId) { return (CanProcessCreditCards && GetDefaultProcessor().ForcePayment(ticketId)); } } }
zzgaminginc-pointofssale
Samba.Services/CreditCardProcessingService.cs
C#
gpl3
2,168
using System; using Samba.Localization.Properties; namespace Samba.Services { public static class PermissionNames { public static string OpenNavigation = "OpenNavigation"; public static string OpenDashboard = "OpenDashboard"; public static string OpenWorkPeriods = "OpenWorkPeriods"; public static string OpenReports = "OpenReports"; public static string OpenTables = "OpenTables"; public static string UseDepartment = "UseDepartment_"; public static string ChangeDepartment = "ChangeDepartment"; public static string AddItemsToLockedTickets = "AddItemsToLockedTickets"; public static string GiftItems = "GiftItems"; public static string MakePayment = "MakePayment"; public static string MakeFastPayment = "MakeFastPayment"; public static string MoveTicketItems = "MoveTicketItems"; public static string MoveUnlockedTicketItems = "MoveUnlockedTicketItems"; public static string VoidItems = "VoidItems"; public static string ChangeExtraProperty = "ChangeExtraProperty"; public static string MakeDiscount = "MakeDiscount"; public static string RoundPayment = "RoundPayment"; public static string FixPayment = "FixPayment"; public static string ChangeTable = "ChangeTable"; public static string NavigateCashView = "NavigateCashView"; public static string ChangeItemPrice = "ChangeItemPrice"; public static string RemoveTicketTag = "RemoveTicketTag"; public static string MergeTickets = "MergeTickets"; public static string ChangeReportDate = "ChangeReportDate"; public static string DisplayOldTickets = "DisplayOldTickets"; public static string MakeCashTransaction = "MakeCashTransaction"; public static string CreditOrDeptAccount = "CreditOrDeptAccount"; public static string MakeAccountTransaction = "MakeAccountTransaction"; public static string CloseActiveWorkPeriods = "CloseActiveWorkPeriod"; } public static class PermissionCategories { public static string Navigation = Resources.NavigationPermissions; public static string Department = Resources.DepartmentPermissions; public static string Ticket = Resources.TicketPermissions; public static string Payment = Resources.SettlePermissions; public static string Report = Resources.ReportPermissions; public static string Cash = Resources.CashPermissions; } }
zzgaminginc-pointofssale
Samba.Services/PermissionNames.cs
C#
gpl3
2,569
using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Samba.Domain.Models.Inventory; using Samba.Domain.Models.Settings; using Samba.Domain.Models.Tickets; using Samba.Infrastructure.Data; using Samba.Persistance.Data; namespace Samba.Services { internal class SalesData { public string MenuItemName { get; set; } public int MenuItemId { get; set; } public string PortionName { get; set; } public decimal Total { get; set; } } public static class InventoryService { private static IEnumerable<TransactionItem> GetTransactionItems() { return Dao.Query<Transaction>(x => x.Date > AppServices.MainDataContext.CurrentWorkPeriod.StartDate, x => x.TransactionItems, x => x.TransactionItems.Select(y => y.InventoryItem)) .SelectMany(x => x.TransactionItems); } private static IEnumerable<TicketItem> GetTicketItemsFromRecipes(WorkPeriod workPeriod) { var recipeItemIds = Dao.Select<Recipe, int>(x => x.Portion.MenuItemId, x => x.Portion != null).Distinct(); var tickets = Dao.Query<Ticket>(x => x.Date > workPeriod.StartDate, x => x.TicketItems, x => x.TicketItems.Select(y => y.Properties)); return tickets.SelectMany(x => x.TicketItems) .Where(x => !x.Voided && recipeItemIds.Contains(x.MenuItemId)); } private static IEnumerable<SalesData> GetSales(WorkPeriod workPeriod) { var ticketItems = GetTicketItemsFromRecipes(workPeriod); var salesData = ticketItems.GroupBy(x => new { x.MenuItemName, x.MenuItemId, x.PortionName }) .Select(x => new SalesData { MenuItemName = x.Key.MenuItemName, MenuItemId = x.Key.MenuItemId, PortionName = x.Key.PortionName, Total = x.Sum(y => y.Quantity) }).ToList(); var properties = ticketItems.SelectMany(x => x.Properties, (ti, pr) => new { Properties = pr, ti.Quantity }) .Where(x => x.Properties.MenuItemId > 0) .GroupBy(x => new { x.Properties.MenuItemId, x.Properties.PortionName }); foreach (var ticketItemProperty in properties) { var tip = ticketItemProperty; var mi = AppServices.DataAccessService.GetMenuItem(tip.Key.MenuItemId); var port = mi.Portions.FirstOrDefault(x => x.Name == tip.Key.PortionName) ?? mi.Portions[0]; var sd = salesData.SingleOrDefault(x => x.MenuItemId == mi.Id && x.MenuItemName == mi.Name && x.PortionName == port.Name) ?? new SalesData(); sd.MenuItemId = mi.Id; sd.MenuItemName = mi.Name; sd.PortionName = port.Name; sd.Total += tip.Sum(x => x.Properties.Quantity * x.Quantity); if (!salesData.Contains(sd)) salesData.Add(sd); } return salesData; } private static void CreatePeriodicConsumptionItems(PeriodicConsumption pc, IWorkspace workspace) { var previousPc = GetPreviousPeriodicConsumption(workspace); var transactionItems = GetTransactionItems(); foreach (var inventoryItem in workspace.All<InventoryItem>()) { var iItem = inventoryItem; var pci = new PeriodicConsumptionItem { InventoryItem = inventoryItem }; pci.UnitMultiplier = pci.InventoryItem.TransactionUnitMultiplier > 0 ? pci.InventoryItem.TransactionUnitMultiplier : 1; pc.PeriodicConsumptionItems.Add(pci); var previousCost = 0m; if (previousPc != null) { var previousPci = previousPc.PeriodicConsumptionItems.SingleOrDefault(x => x.InventoryItem.Id == iItem.Id); if (previousPci != null) pci.InStock = previousPci.PhysicalInventory != null ? previousPci.PhysicalInventory.GetValueOrDefault(0) : previousPci.GetInventoryPrediction(); if (previousPci != null) previousCost = previousPci.Cost * pci.InStock; } var tim = transactionItems.Where(x => x.InventoryItem.Id == iItem.Id); pci.Purchase = tim.Sum(x => x.Quantity * x.Multiplier) / pci.UnitMultiplier; var totalPrice = tim.Sum(x => x.Price * x.Quantity); if (pci.InStock > 0 || pci.Purchase > 0) { pci.Cost = pci.InStock > 0 ? decimal.Round((totalPrice + previousCost)/(pci.InStock + pci.Purchase), 2) : decimal.Round(totalPrice/pci.Purchase, 2); } } } private static void UpdateConsumption(PeriodicConsumption pc, IWorkspace workspace) { var sales = GetSales(AppServices.MainDataContext.CurrentWorkPeriod); foreach (var sale in sales) { var lSale = sale; var recipe = workspace.Single<Recipe>(x => x.Portion.Name == lSale.PortionName && x.Portion.MenuItemId == lSale.MenuItemId); if (recipe != null) { var cost = 0m; foreach (var recipeItem in recipe.RecipeItems.Where(x => x.InventoryItem != null && x.Quantity > 0)) { var item = recipeItem; var pci = pc.PeriodicConsumptionItems.Single(x => x.InventoryItem.Id == item.InventoryItem.Id); pci.Consumption += (item.Quantity * sale.Total) / pci.UnitMultiplier; Debug.Assert(pci.Consumption > 0); cost += recipeItem.Quantity * (pci.Cost / pci.UnitMultiplier); } pc.CostItems.Add(new CostItem { Name = sale.MenuItemName, Portion = recipe.Portion, CostPrediction = cost, Quantity = sale.Total }); } } } private static PeriodicConsumption CreateNewPeriodicConsumption(IWorkspace workspace) { var pc = new PeriodicConsumption { WorkPeriodId = AppServices.MainDataContext.CurrentWorkPeriod.Id, Name = AppServices.MainDataContext.CurrentWorkPeriod.StartDate + " - " + AppServices.MainDataContext.CurrentWorkPeriod.EndDate, StartDate = AppServices.MainDataContext.CurrentWorkPeriod.StartDate, EndDate = AppServices.MainDataContext.CurrentWorkPeriod.EndDate }; CreatePeriodicConsumptionItems(pc, workspace); UpdateConsumption(pc, workspace); CalculateCost(pc, AppServices.MainDataContext.CurrentWorkPeriod); return pc; } public static PeriodicConsumption GetPreviousPeriodicConsumption(IWorkspace workspace) { return AppServices.MainDataContext.PreviousWorkPeriod == null ? null : workspace.Single<PeriodicConsumption>(x => x.WorkPeriodId == AppServices.MainDataContext.PreviousWorkPeriod.Id); } public static PeriodicConsumption GetCurrentPeriodicConsumption(IWorkspace workspace) { var pc = workspace.Single<PeriodicConsumption>(x => x.WorkPeriodId == AppServices.MainDataContext.CurrentWorkPeriod.Id) ?? CreateNewPeriodicConsumption(workspace); return pc; } public static void CalculateCost(PeriodicConsumption pc, WorkPeriod workPeriod) { var sales = GetSales(workPeriod); foreach (var sale in sales) { var lSale = sale; var recipe = Dao.Single<Recipe>(x => x.Portion.Name == lSale.PortionName && x.Portion.MenuItemId == lSale.MenuItemId, x => x.Portion, x => x.RecipeItems, x => x.RecipeItems.Select(y => y.InventoryItem)); if (recipe != null) { var totalcost = recipe.FixedCost; foreach (var recipeItem in recipe.RecipeItems.Where(x => x.InventoryItem != null && x.Quantity > 0)) { var item = recipeItem; var pci = pc.PeriodicConsumptionItems.SingleOrDefault(x => x.InventoryItem.Id == item.InventoryItem.Id); if (pci != null && pci.GetPredictedConsumption() > 0) { var cost = recipeItem.Quantity * (pci.Cost / pci.UnitMultiplier); cost = (pci.GetConsumption() * cost) / pci.GetPredictedConsumption(); totalcost += cost; } } var ci = pc.CostItems.SingleOrDefault(x => x.Portion.Id == recipe.Portion.Id); if (ci != null) ci.Cost = decimal.Round(totalcost, 2); } } } } }
zzgaminginc-pointofssale
Samba.Services/InventoryService.cs
C#
gpl3
9,441
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Documents; using System.Windows.Threading; using Samba.Domain; using Samba.Domain.Models.Menus; using Samba.Domain.Models.Settings; using Samba.Domain.Models.Tickets; using Samba.Infrastructure.Data.Serializer; using Samba.Infrastructure.Settings; using Samba.Localization.Properties; using Samba.Persistance.Data; namespace Samba.Services.Printing { internal class PrinterData { public Printer Printer { get; set; } public PrinterTemplate PrinterTemplate { get; set; } public Ticket Ticket { get; set; } } internal class TicketData { public Ticket Ticket { get; set; } public IEnumerable<TicketItem> TicketItems { get; set; } public PrintJob PrintJob { get; set; } } public static class TicketPrinter { private static PrinterMap GetPrinterMapForItem(IEnumerable<PrinterMap> printerMaps, Ticket ticket, TicketItem ticketItem) { var menuItemGroupCode = Dao.Single<MenuItem, string>(ticketItem.MenuItemId, x => x.GroupCode); var maps = printerMaps; maps = maps.Count(x => !string.IsNullOrEmpty(x.TicketTag) && !string.IsNullOrEmpty(ticket.GetTagValue(x.TicketTag))) > 0 ? maps.Where(x => !string.IsNullOrEmpty(x.TicketTag) && !string.IsNullOrEmpty(ticket.GetTagValue(x.TicketTag))) : maps.Where(x => string.IsNullOrEmpty(x.TicketTag)); maps = maps.Count(x => x.Department != null && x.Department.Id == ticketItem.DepartmentId) > 0 ? maps.Where(x => x.Department != null && x.Department.Id == ticketItem.DepartmentId) : maps.Where(x => x.Department == null); maps = maps.Count(x => x.MenuItemGroupCode == menuItemGroupCode) > 0 ? maps.Where(x => x.MenuItemGroupCode == menuItemGroupCode) : maps.Where(x => x.MenuItemGroupCode == null); maps = maps.Count(x => x.MenuItem != null && x.MenuItem.Id == ticketItem.MenuItemId) > 0 ? maps.Where(x => x.MenuItem != null && x.MenuItem.Id == ticketItem.MenuItemId) : maps.Where(x => x.MenuItem == null); return maps.FirstOrDefault(); } public static void AutoPrintTicket(Ticket ticket) { foreach (var customPrinter in AppServices.CurrentTerminal.PrintJobs.Where(x => !x.UseForPaidTickets)) { if (ShouldAutoPrint(ticket, customPrinter)) ManualPrintTicket(ticket, customPrinter); } } public static void ManualPrintTicket(Ticket ticket, PrintJob customPrinter) { if (customPrinter.LocksTicket) ticket.RequestLock(); ticket.AddPrintJob(customPrinter.Id); PrintOrders(customPrinter, ticket); } private static bool ShouldAutoPrint(Ticket ticket, PrintJob customPrinter) { if (customPrinter.WhenToPrint == (int)WhenToPrintTypes.Manual) return false; if (customPrinter.WhenToPrint == (int)WhenToPrintTypes.Paid) { if (ticket.DidPrintJobExecuted(customPrinter.Id)) return false; if (!ticket.IsPaid) return false; if (!customPrinter.AutoPrintIfCash && !customPrinter.AutoPrintIfCreditCard && !customPrinter.AutoPrintIfTicket) return false; if (customPrinter.AutoPrintIfCash && ticket.Payments.Count(x => x.PaymentType == (int)PaymentType.Cash) > 0) return true; if (customPrinter.AutoPrintIfCreditCard && ticket.Payments.Count(x => x.PaymentType == (int)PaymentType.CreditCard) > 0) return true; if (customPrinter.AutoPrintIfTicket && ticket.Payments.Count(x => x.PaymentType == (int)PaymentType.Ticket) > 0) return true; } if (customPrinter.WhenToPrint == (int)WhenToPrintTypes.NewLinesAdded && ticket.GetUnlockedLines().Count() > 0) return true; return false; } public static void PrintOrders(PrintJob printJob, Ticket ticket) { if (printJob.ExcludeVat) { ticket = ObjectCloner.Clone(ticket); ticket.TicketItems.ToList().ForEach(x => x.VatIncluded = false); } IEnumerable<TicketItem> ti; switch (printJob.WhatToPrint) { case (int)WhatToPrintTypes.NewLines: ti = ticket.GetUnlockedLines(); break; case (int)WhatToPrintTypes.GroupedByBarcode: ti = GroupLinesByValue(ticket, x => x.Barcode ?? "", "1", true); break; case (int)WhatToPrintTypes.GroupedByGroupCode: ti = GroupLinesByValue(ticket, x => x.GroupCode ?? "", Resources.UndefinedWithBrackets); break; case (int)WhatToPrintTypes.GroupedByTag: ti = GroupLinesByValue(ticket, x => x.Tag ?? "", Resources.UndefinedWithBrackets); break; case (int)WhatToPrintTypes.LastLinesByPrinterLineCount: ti = GetLastItems(ticket, printJob); break; case (int)WhatToPrintTypes.LastPaidItems: ti = GetLastPaidItems(ticket).ToList(); ticket = ObjectCloner.Clone(ticket); ticket.TicketItems.Clear(); ticket.PaidItems.Clear(); ticket.Payments.Clear(); ti.ToList().ForEach(x => ticket.TicketItems.Add(x)); break; default: ti = ticket.TicketItems.OrderBy(x => x.Id).ToList(); break; } Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action( delegate { try { InternalPrintOrders(printJob, ticket, ti); } catch (Exception e) { AppServices.LogError(e, string.Format(Resources.PrintingErrorMessage_f, e.Message)); } })); } private static IEnumerable<TicketItem> GetLastPaidItems(Ticket ticket) { var result = ticket.GetPaidItems().Select(x => ticket.TicketItems.First(y => y.MenuItemId == x)).ToList(); result = result.Select(ObjectCloner.Clone).ToList(); foreach (var ticketItem in result) { ticketItem.Quantity = ticket.GetPaidItemQuantity(ticketItem.MenuItemId); } return result; } private static IEnumerable<TicketItem> GetLastItems(Ticket ticket, PrintJob printJob) { if (ticket.TicketItems.Count > 1) { var printer = printJob.PrinterMaps.Count == 1 ? printJob.PrinterMaps[0] : GetPrinterMapForItem(printJob.PrinterMaps, ticket, ticket.TicketItems.Last()); var result = ticket.TicketItems.OrderByDescending(x => x.CreatedDateTime).ToList(); if (printer.Printer.PageHeight > 0) result = result.Take(printer.Printer.PageHeight).ToList(); return result; } return ticket.TicketItems.ToList(); } private static IEnumerable<TicketItem> GroupLinesByValue(Ticket ticket, Func<MenuItem, object> selector, string defaultValue, bool calcDiscounts = false) { var discounts = calcDiscounts ? ticket.GetDiscountAndRoundingTotal() : 0; var di = discounts > 0 ? discounts / ticket.GetPlainSum() : 0; var cache = new Dictionary<string, decimal>(); foreach (var ticketItem in ticket.TicketItems.OrderBy(x => x.Id).ToList()) { var item = ticketItem; var value = selector(AppServices.DataAccessService.GetMenuItem(item.MenuItemId)).ToString(); if (string.IsNullOrEmpty(value)) value = defaultValue; if (!cache.ContainsKey(value)) cache.Add(value, 0); var total = (item.GetTotal()); cache[value] += Decimal.Round(total - (total * di), 2); } return cache.Select(x => new TicketItem { MenuItemName = x.Key, Price = x.Value, Quantity = 1, PortionCount = 1, CurrencyCode = LocalSettings.CurrencySymbol }); } private static void InternalPrintOrders(PrintJob printJob, Ticket ticket, IEnumerable<TicketItem> ticketItems) { if (printJob.PrinterMaps.Count == 1 && printJob.PrinterMaps[0].TicketTag == null && printJob.PrinterMaps[0].MenuItem == null && printJob.PrinterMaps[0].MenuItemGroupCode == null && printJob.PrinterMaps[0].Department == null) { PrintOrderLines(ticket, ticketItems, printJob.PrinterMaps[0]); return; } var ordersCache = new Dictionary<PrinterMap, IList<TicketItem>>(); foreach (var item in ticketItems) { var p = GetPrinterMapForItem(printJob.PrinterMaps, ticket, item); if (p != null) { var lmap = p; var pmap = ordersCache.SingleOrDefault( x => x.Key.Printer == lmap.Printer && x.Key.PrinterTemplate == lmap.PrinterTemplate).Key; if (pmap == null) ordersCache.Add(p, new List<TicketItem>()); else p = pmap; ordersCache[p].Add(item); } } foreach (var order in ordersCache) { PrintOrderLines(ticket, order.Value, order.Key); } } private static void PrintOrderLines(Ticket ticket, IEnumerable<TicketItem> lines, PrinterMap p) { if (p == null) { MessageBox.Show("Yazdırma sırasında bir problem tespit edildi: Yazıcı Haritası null"); AppServices.Log("Yazıcı Haritası NULL problemi tespit edildi."); return; } if (!string.IsNullOrEmpty(p.PrinterTemplate.LineTemplate) && lines.Count() <= 0) return; if (p.Printer == null || string.IsNullOrEmpty(p.Printer.ShareName) || p.PrinterTemplate == null) return; var ticketLines = TicketFormatter.GetFormattedTicket(ticket, lines, p.PrinterTemplate); PrintJobFactory.CreatePrintJob(p.Printer).DoPrint(ticketLines); } public static void PrintReport(FlowDocument document) { var printer = AppServices.CurrentTerminal.ReportPrinter; if (printer == null || string.IsNullOrEmpty(printer.ShareName)) return; PrintJobFactory.CreatePrintJob(printer).DoPrint(document); } public static void PrintSlipReport(FlowDocument document) { var printer = AppServices.CurrentTerminal.SlipReportPrinter; if (printer == null || string.IsNullOrEmpty(printer.ShareName)) return; PrintJobFactory.CreatePrintJob(printer).DoPrint(document); } public static void ExecutePrintJob(PrintJob printJob) { if (printJob.PrinterMaps.Count > 0) { var printerMap = printJob.PrinterMaps[0]; var content = printerMap .PrinterTemplate .HeaderTemplate .Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); if (!string.IsNullOrEmpty(printerMap.Printer.ShareName)) { try { PrintJobFactory.CreatePrintJob(printerMap.Printer).DoPrint(content); } catch (Exception e) { AppServices.LogError(e, string.Format(Resources.PrintingErrorMessage_f, e.Message)); } } } } } }
zzgaminginc-pointofssale
Samba.Services/Printing/TicketPrinter.cs
C#
gpl3
13,078
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Windows; using System.Windows.Documents; using Samba.Domain.Models.Settings; using Samba.Infrastructure.Settings; using Samba.Services.HtmlConverter; namespace Samba.Services.Printing { public class HtmlPrinterJob : AbstractPrintJob { public HtmlPrinterJob(Printer printer) : base(printer) { } public override void DoPrint(FlowDocument document) { DoPrint(PrinterTools.FlowDocumentToSlipPrinterFormat(document, 0)); } public override void DoPrint(string[] lines) { var q = AppServices.PrintService.GetPrinter(Printer.ShareName); var formattedLines = ConvertTagsToHtml(lines); var text = formattedLines.Aggregate("", (current, s) => current + s + "\r\n"); if (!text.ToLower().Contains("<style>")) text = LocalSettings.DefaultHtmlReportHeader + text; var xaml = HtmlToXamlConverter.ConvertHtmlToXaml(text, false); PrintFlowDocument(q, PrinterTools.XamlToFlowDocument(xaml)); } public IEnumerable<string> ConvertTagsToHtml(string[] lines) { var tables = new Dictionary<string, List<string>>(); var lastLine = ""; var tableCount = 0; var list = new List<string>(); foreach (var line in lines) { if (line.StartsWith("<F>") && line.Length > 3) list.Add(string.Format("<span>{0}</span>", line[3].ToString().PadLeft(Printer.CharsPerLine, line[3]))); if (line.StartsWith("<T>")) list.Add(string.Format("<B>{0}</B>", RemoveTag(line))); if (line.StartsWith("<C") && line.Length > 3 && (line[2] == '>' || char.IsDigit(line[2]))) list.Add(string.Format("<Center>{0}</Center>", RemoveTag(line))); if (line.StartsWith("<L") && line.Length > 3 && (line[2] == '>' || char.IsDigit(line[2]))) list.Add(string.Format("<span>{0}</span>", RemoveTag(line))); if (line.StartsWith("<EB>")) list.Add("<B>"); if (line.StartsWith("<DB>")) list.Add("</B>"); if (line.StartsWith("<J") && line.Length > 3 && (line[2] == '>' || char.IsDigit(line[2]))) { if (!lastLine.StartsWith("<J")) { tableCount++; list.Add("tbl" + tableCount); } var tableName = "tbl" + tableCount; if (!tables.ContainsKey(tableName)) tables.Add(tableName, new List<string>()); tables[tableName].Add(RemoveTag(line)); } if (!line.Contains("<")) list.Add(line); lastLine = line; } foreach (var table in tables) { list.InsertRange(list.IndexOf(table.Key), GetTableLines(table.Value, Printer.CharsPerLine)); list.Remove(table.Key); } for (int i = 0; i < list.Count; i++) { list[i] = list[i].TrimEnd(); if ((!list[i].ToLower().EndsWith("<BR>") && RemoveTag(list[i]).Trim().Length > 0) || list[i].Trim().Length == 0) list[i] += "<BR>"; list[i] = list[i].Replace(" ", "&nbsp;"); } return list; } private static IEnumerable<string> GetTableLines(IList<string> lines, int maxWidth) { int colCount = GetColumnCount(lines) + 1; var colWidths = new int[colCount]; for (int i = 0; i < colCount; i++) { colWidths[i] = GetMaxLine(lines, i); } colWidths[colCount - 1] = (maxWidth - colWidths.Sum()) + colWidths[colCount - 1]; if (colWidths[colCount - 1] < 1) colWidths[colCount - 1] = 1; for (int i = 0; i < lines.Count; i++) { lines[i] = string.Format("<span>{0}</span>", GetFormattedLine(lines[i], colWidths)); } return lines; } private static string GetFormattedLine(string s, IList<int> colWidths) { var parts = s.Split('|'); for (int i = 0; i < parts.Length; i++) { if (i == parts.Length - 1) parts[i] = parts[i].PadLeft(colWidths[i]); else parts[i] = parts[i].PadRight(colWidths[i]); } return string.Join("", parts); } private static int GetMaxLine(IEnumerable<string> lines, int columnNo) { var result = 0; foreach (var val in lines) { if (!val.Contains("|")) continue; int start = columnNo > 0 ? val.IndexOf("|", columnNo) : 0; var v = val.Substring(start); if (v.StartsWith("|")) v = v.Substring(1); if (v.Contains("|")) v = v.Substring(0, v.IndexOf("|")); result = v.Length + 1 > result ? v.Length + 1 : result; } return result; } private static int GetColumnCount(IEnumerable<string> value) { return value.Select(item => item.Length - item.Replace("|", "").Length).Aggregate(0, (current, len) => len > current ? len : current); } } }
zzgaminginc-pointofssale
Samba.Services/Printing/HtmlPrinterJob.cs
C#
gpl3
5,820
using System; using System.Linq; using System.Windows.Documents; using Samba.Domain.Models.Settings; using Samba.Infrastructure.Printing; namespace Samba.Services.Printing { public class SlipPrinterJob : AbstractPrintJob { public SlipPrinterJob(Printer printer) : base(printer) { } public override void DoPrint(string[] lines) { lines = PrinterHelper.AlignLines(lines, Printer.CharsPerLine, true).ToArray(); lines = PrinterHelper.ReplaceChars(lines, Printer.ReplacementPattern).ToArray(); var printer = new LinePrinter(Printer.ShareName, Printer.CharsPerLine, Printer.CodePage); printer.StartDocument(); foreach (var s in lines) { SendToPrinter(printer, s); } if (lines.Length >= 2) printer.Cut(); printer.EndDocument(); _lastHeight = 0; _lastWidth = 0; } public override void DoPrint(FlowDocument document) { DoPrint(PrinterTools.FlowDocumentToSlipPrinterFormat(document,Printer.CharsPerLine)); } private static int _lastWidth; private static int _lastHeight; private static void SendToPrinter(LinePrinter printer, string line) { if (!string.IsNullOrEmpty(line.Trim())) { if (line.Length > 3 && Char.IsNumber(line[2]) && Char.IsNumber(line[3])) { _lastHeight = Convert.ToInt32(line[2].ToString()); _lastWidth = Convert.ToInt32(line[3].ToString()); } if (line.StartsWith("<T>")) printer.PrintCenteredLabel(RemoveTag(line), true); else if (line.StartsWith("<L")) printer.WriteLine(RemoveTag(line), _lastHeight, _lastWidth); else if (line.StartsWith("<C")) printer.WriteLine(RemoveTag(line), _lastHeight, _lastWidth); else if (line.StartsWith("<R")) printer.WriteLine(RemoveTag(line), _lastHeight, _lastWidth); else if (line.StartsWith("<J")) printer.WriteLine(RemoveTag(line), _lastHeight, _lastWidth); else if (line.StartsWith("<F") && line.Length > 3) printer.PrintFullLine(line[3]); else if (line.StartsWith("<EB")) printer.EnableBold(); else if (line.StartsWith("<DB")) printer.DisableBold(); else if (line.StartsWith("<BMP")) printer.PrintBitmap(RemoveTag(line)); else if (line.StartsWith("<CUT")) printer.Cut(); else if (line.StartsWith("<BEEP")) printer.Beep(); else if (line.StartsWith("<DRAWER")) printer.OpenCashDrawer(); else if (line.StartsWith("<B")) printer.Beep((char)_lastHeight, (char)_lastWidth); else if (line.StartsWith("<XCT") && line.EndsWith(">")) printer.ExecCommand(line.Substring(4, line.Length - 5)); else printer.WriteLine(line); } } } }
zzgaminginc-pointofssale
Samba.Services/Printing/SlipPrinterJob.cs
C#
gpl3
3,421
using Samba.Domain.Models.Settings; namespace Samba.Services.Printing { public static class PrintJobFactory { public static AbstractPrintJob CreatePrintJob(Printer printer) { if (printer.PrinterType == 1) return new TextPrinterJob(printer); if (printer.PrinterType == 2) return new HtmlPrinterJob(printer); if (printer.PrinterType == 3) return new PortPrinterJob(printer); if (printer.PrinterType == 4) return new DemoPrinterJob(printer); return new SlipPrinterJob(printer); } } }
zzgaminginc-pointofssale
Samba.Services/Printing/PrintJobFactory.cs
C#
gpl3
665
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Text.RegularExpressions; using NCalc; using Samba.Domain.Models.Customers; using Samba.Domain.Models.Menus; using Samba.Domain.Models.Settings; using Samba.Domain.Models.Tickets; using Samba.Infrastructure.Settings; using Samba.Localization.Properties; using Samba.Persistance.Data; namespace Samba.Services.Printing { public class TagData { public TagData(string data, string tag) { data = ReplaceInBracketValues(data, "\r\n", "<newline>", '[', ']'); data = data.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Where(x => x.Contains(tag)).FirstOrDefault(); Tag = tag; DataString = tag; if (string.IsNullOrEmpty(data)) return; StartPos = data.IndexOf(tag); EndPos = StartPos + 1; while (data[EndPos] != '}') { EndPos++; } EndPos++; Length = EndPos - StartPos; DataString = BracketContains(data, '[', ']', Tag) ? GetBracketValue(data, '[', ']') : data.Substring(StartPos, Length); DataString = DataString.Replace("<newline>", "\r\n"); Title = !DataString.StartsWith("[=") ? DataString.Trim('[', ']') : DataString; Title = Title.Replace(Tag, "<value>"); Length = DataString.Length; StartPos = data.IndexOf(DataString); EndPos = StartPos + Length; } public string DataString { get; set; } public string Tag { get; set; } public string Title { get; set; } public int StartPos { get; set; } public int EndPos { get; set; } public int Length { get; set; } public static string ReplaceInBracketValues(string content, string find, string replace, char open, char close) { var result = content; var v1 = GetBracketValue(result, open, close); while (!string.IsNullOrEmpty(v1)) { var value = v1.Replace(find, replace); value = value.Replace(open.ToString(), "<op>"); value = value.Replace(close.ToString(), "<cl>"); result = result.Replace(v1, value); v1 = GetBracketValue(result, open, close); } result = result.Replace("<op>", open.ToString()); result = result.Replace("<cl>", close.ToString()); return result; } public static bool BracketContains(string content, char open, char close, string testValue) { if (!content.Contains(open)) return false; var br = GetBracketValue(content, open, close); return (br.Contains(testValue)) && !br.StartsWith("[="); } public static string GetBracketValue(string content, char open, char close) { var closePass = 1; var start = content.IndexOf(open); var end = start; if (start > -1) { while (end < content.Length - 1 && closePass > 0) { end++; if (content[end] == open && close != open) closePass++; if (content[end] == close) closePass--; } return content.Substring(start, (end - start) + 1); } return string.Empty; } } public static class TicketFormatter { public static string[] GetFormattedTicket(Ticket ticket, IEnumerable<TicketItem> lines, PrinterTemplate template) { if (template.MergeLines) lines = MergeLines(lines); var orderNo = lines.Count() > 0 ? lines.ElementAt(0).OrderNumber : 0; var userNo = lines.Count() > 0 ? lines.ElementAt(0).CreatingUserId : 0; var departmentNo = lines.Count() > 0 ? lines.ElementAt(0).DepartmentId : ticket.DepartmentId; var header = ReplaceDocumentVars(template.HeaderTemplate, ticket, orderNo, userNo, departmentNo); var footer = ReplaceDocumentVars(template.FooterTemplate, ticket, orderNo, userNo, departmentNo); var lns = GetFormattedLines(lines, template); var result = header.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).ToList(); result.AddRange(lns); result.AddRange(footer.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)); return result.ToArray(); } private static IEnumerable<string> GetFormattedLines(IEnumerable<TicketItem> lines, PrinterTemplate template) { if (!string.IsNullOrEmpty(template.GroupTemplate)) { if (template.GroupTemplate.Contains("{PRODUCT GROUP}")) { var groups = lines.GroupBy(GetMenuItemGroup); var result = new List<string>(); foreach (var grp in groups) { var grpSep = template.GroupTemplate.Replace("{PRODUCT GROUP}", grp.Key); result.AddRange(grpSep.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)); result.AddRange(grp.SelectMany(x => FormatLines(template, x).Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))); } return result; } if (template.GroupTemplate.Contains("{PRODUCT TAG}")) { var groups = lines.GroupBy(GetMenuItemTag); var result = new List<string>(); foreach (var grp in groups) { var grpSep = template.GroupTemplate.Replace("{PRODUCT TAG}", grp.Key); result.AddRange(grpSep.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)); result.AddRange(grp.SelectMany(x => FormatLines(template, x).Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))); } return result; } if (template.GroupTemplate.Contains("{ITEM TAG}")) { var groups = lines.GroupBy(x => (x.Tag ?? "").Split('|')[0]); var result = new List<string>(); foreach (var grp in groups) { var grpSep = template.GroupTemplate.Replace("{ITEM TAG}", grp.Key); result.AddRange(grpSep.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)); result.AddRange(grp.SelectMany(x => FormatLines(template, x).Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))); } return result; } if (template.GroupTemplate.Contains("{ORDER NO}")) { var groups = lines.GroupBy(x => x.OrderNumber); var result = new List<string>(); foreach (var grp in groups) { var grpSep = template.GroupTemplate.Replace("{ORDER NO}", grp.Key.ToString()); result.AddRange(grpSep.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)); result.AddRange(grp.SelectMany(x => FormatLines(template, x).Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))); } return result; } } return lines.SelectMany(x => FormatLines(template, x).Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)).ToArray(); } private static IEnumerable<TicketItem> MergeLines(IEnumerable<TicketItem> lines) { var group = lines.Where(x => x.Properties.Count == 0).GroupBy(x => new { x.MenuItemId, x.MenuItemName, x.Voided, x.Gifted, x.Price, x.VatIncluded, x.VatAmount, x.VatTemplateId, x.PortionName, x.PortionCount, x.ReasonId, x.CurrencyCode, x.Tag }); var result = group.Select(x => new TicketItem { MenuItemId = x.Key.MenuItemId, MenuItemName = x.Key.MenuItemName, ReasonId = x.Key.ReasonId, Voided = x.Key.Voided, Gifted = x.Key.Gifted, Price = x.Key.Price, VatAmount = x.Key.VatAmount, VatTemplateId = x.Key.VatTemplateId, VatIncluded = x.Key.VatIncluded, CreatedDateTime = x.Last().CreatedDateTime, CreatingUserId = x.Last().CreatingUserId, OrderNumber = x.Last().OrderNumber, TicketId = x.Last().TicketId, PortionName = x.Key.PortionName, PortionCount = x.Key.PortionCount, CurrencyCode = x.Key.CurrencyCode, Tag = x.Key.Tag, Quantity = x.Sum(y => y.Quantity) }); result = result.Union(lines.Where(x => x.Properties.Count > 0)).OrderBy(x => x.CreatedDateTime); return result; } private static string ReplaceDocumentVars(string document, Ticket ticket, int orderNo, int userNo, int departmentNo) { string result = document; if (string.IsNullOrEmpty(document)) return ""; result = FormatData(result, Resources.TF_TicketDate, () => ticket.Date.ToShortDateString()); result = FormatData(result, Resources.TF_TicketTime, () => ticket.Date.ToShortTimeString()); result = FormatData(result, Resources.TF_DayDate, () => DateTime.Now.ToShortDateString()); result = FormatData(result, Resources.TF_DayTime, () => DateTime.Now.ToShortTimeString()); result = FormatData(result, Resources.TF_UniqueTicketId, () => ticket.Id.ToString()); result = FormatData(result, Resources.TF_TicketNumber, () => ticket.TicketNumber); result = FormatData(result, Resources.TF_LineOrderNumber, orderNo.ToString); result = FormatData(result, Resources.TF_TicketTag, ticket.GetTagData); result = FormatDataIf(true, result, "{DEPARTMENT}", () => GetDepartmentName(departmentNo)); var ticketTagPattern = Resources.TF_OptionalTicketTag + "[^}]+}"; while (Regex.IsMatch(result, ticketTagPattern)) { var value = Regex.Match(result, ticketTagPattern).Groups[0].Value; var tags = ""; try { var tag = value.Trim('{', '}').Split(':')[1]; tags = tag.Split(',').Aggregate(tags, (current, t) => current + (!string.IsNullOrEmpty(ticket.GetTagValue(t.Trim())) ? (t + ": " + ticket.GetTagValue(t.Trim()) + "\r") : "")); result = FormatData(result.Trim('\r'), value, () => tags); } catch (Exception) { result = FormatData(result, value, () => ""); } } const string ticketTag2Pattern = "{TICKETTAG:[^}]+}"; while (Regex.IsMatch(result, ticketTag2Pattern)) { var value = Regex.Match(result, ticketTag2Pattern).Groups[0].Value; var tag = value.Trim('{', '}').Split(':')[1]; var tagValue = ticket.GetTagValue(tag); try { result = FormatData(result, value, () => tagValue); } catch (Exception) { result = FormatData(result, value, () => ""); } } var userName = AppServices.MainDataContext.GetUserName(userNo); var title = ticket.LocationName; if (string.IsNullOrEmpty(ticket.LocationName)) title = userName; result = FormatData(result, Resources.TF_TableOrUserName, () => title); result = FormatData(result, Resources.TF_UserName, () => userName); result = FormatData(result, Resources.TF_TableName, () => ticket.LocationName); result = FormatData(result, Resources.TF_TicketNote, () => ticket.Note ?? ""); result = FormatData(result, Resources.TF_AccountName, () => ticket.CustomerName); result = FormatData(result, "{ACC GROUPCODE}", () => ticket.CustomerGroupCode); if (ticket.CustomerId > 0 && (result.Contains(Resources.TF_AccountAddress) || result.Contains(Resources.TF_AccountPhone) || result.Contains("{ACC NOTE}"))) { var customer = Dao.SingleWithCache<Customer>(x => x.Id == ticket.CustomerId); result = FormatData(result, Resources.TF_AccountAddress, () => customer.Address); result = FormatData(result, Resources.TF_AccountPhone, () => customer.PhoneNumber); result = FormatData(result, "{ACC NOTE}", () => customer.Note); } if (ticket.CustomerId > 0 && result.Contains("{ACC BALANCE}")) { var accBalance = CashService.GetAccountBalance(ticket.CustomerId); result = FormatDataIf(accBalance != 0, result, "{ACC BALANCE}", () => accBalance.ToString("#,#0.00")); } result = RemoveTag(result, Resources.TF_AccountAddress); result = RemoveTag(result, Resources.TF_AccountPhone); var payment = ticket.GetPaymentAmount(); var remaining = ticket.GetRemainingAmount(); var discount = ticket.GetDiscountAndRoundingTotal(); var plainTotal = ticket.GetPlainSum(); var giftAmount = ticket.GetTotalGiftAmount(); var vatAmount = GetTaxTotal(ticket.TicketItems, plainTotal, ticket.GetDiscountTotal()); var taxServicesTotal = ticket.GetTaxServicesTotal(); var ticketPaymentAmount = ticket.GetPaymentAmount(); result = FormatDataIf(vatAmount > 0 || discount > 0 || taxServicesTotal > 0, result, "{PLAIN TOTAL}", () => plainTotal.ToString("#,#0.00")); result = FormatDataIf(discount > 0, result, "{DISCOUNT TOTAL}", () => discount.ToString("#,#0.00")); result = FormatDataIf(vatAmount > 0, result, "{TAX TOTAL}", () => vatAmount.ToString("#,#0.00")); result = FormatDataIf(taxServicesTotal > 0, result, "{SERVICE TOTAL}", () => taxServicesTotal.ToString("#,#0.00")); result = FormatDataIf(vatAmount > 0, result, "{TAX DETAILS}", () => GetTaxDetails(ticket.TicketItems, plainTotal, discount)); result = FormatDataIf(taxServicesTotal > 0, result, "{SERVICE DETAILS}", () => GetServiceDetails(ticket)); result = FormatDataIf(payment > 0, result, Resources.TF_RemainingAmountIfPaid, () => string.Format(Resources.RemainingAmountIfPaidValue_f, payment.ToString("#,#0.00"), remaining.ToString("#,#0.00"))); result = FormatDataIf(discount > 0, result, Resources.TF_DiscountTotalAndTicketTotal, () => string.Format(Resources.DiscountTotalAndTicketTotalValue_f, (plainTotal).ToString("#,#0.00"), discount.ToString("#,#0.00"))); result = FormatDataIf(giftAmount > 0, result, Resources.TF_GiftTotal, () => giftAmount.ToString("#,#0.00")); result = FormatDataIf(discount < 0, result, Resources.TF_IfFlatten, () => string.Format(Resources.IfNegativeDiscountValue_f, discount.ToString("#,#0.00"))); result = FormatData(result, Resources.TF_TicketTotal, () => ticket.GetSum().ToString("#,#0.00")); result = FormatDataIf(ticketPaymentAmount > 0, result, Resources.TF_TicketPaidTotal, () => ticketPaymentAmount.ToString("#,#0.00")); result = FormatData(result, Resources.TF_TicketRemainingAmount, () => ticket.GetRemainingAmount().ToString("#,#0.00")); result = FormatData(result, "{TOTAL TEXT}", () => HumanFriendlyInteger.CurrencyToWritten(ticket.GetSum())); result = FormatData(result, "{TOTALTEXT}", () => HumanFriendlyInteger.CurrencyToWritten(ticket.GetSum(), true)); result = UpdateGlobalValues(result); return result; } private static string UpdateGlobalValues(string data) { data = UpdateSettings(data); data = UpdateExpressions(data); return data; } private static string UpdateSettings(string result) { while (Regex.IsMatch(result, "{SETTING:[^}]+}", RegexOptions.Singleline)) { var match = Regex.Match(result, "{SETTING:([^}]+)}"); var tagName = match.Groups[0].Value; var settingName = match.Groups[1].Value; var tagData = new TagData(result, tagName); var value = !string.IsNullOrEmpty(settingName) ? AppServices.SettingService.ReadSetting(settingName).StringValue : ""; var replace = !string.IsNullOrEmpty(value) ? tagData.Title.Replace("<value>", value) : ""; result = result.Replace(tagData.DataString, replace); } return result; } private static string UpdateExpressions(string data) { while (Regex.IsMatch(data, "\\[=[^\\]]+\\]", RegexOptions.Singleline)) { var match = Regex.Match(data, "\\[=([^\\]]+)\\]"); var tag = match.Groups[0].Value; var expression = match.Groups[1].Value; var e = new Expression(expression); e.EvaluateFunction += delegate(string name, FunctionArgs args) { if (name == "Format" || name == "F") { var fmt = args.Parameters.Length > 1 ? args.Parameters[1].Evaluate().ToString() : "#,#0.00"; args.Result = ((double)args.Parameters[0].Evaluate()).ToString(fmt); } if (name == "ToNumber" || name == "TN") { double d; double.TryParse(args.Parameters[0].Evaluate().ToString(), NumberStyles.Any, CultureInfo.CurrentCulture, out d); args.Result = d; } }; string result; try { result = e.Evaluate().ToString(); } catch (EvaluationException) { result = ""; } data = data.Replace(tag, result); } return data; } private static string GetDepartmentName(int departmentId) { var dep = AppServices.MainDataContext.Departments.SingleOrDefault(x => x.Id == departmentId); return dep != null ? dep.Name : Resources.UndefinedWithBrackets; } private static string GetServiceDetails(Ticket ticket) { var sb = new StringBuilder(); foreach (var taxService in ticket.TaxServices) { var service = taxService; var ts = AppServices.MainDataContext.TaxServiceTemplates.FirstOrDefault(x => x.Id == service.TaxServiceId); var tsTitle = ts != null ? ts.Name : Resources.UndefinedWithBrackets; sb.AppendLine("<J>" + tsTitle + ":|" + service.CalculationAmount.ToString("#,#0.00")); } return string.Join("\r", sb); } private static string GetTaxDetails(IEnumerable<TicketItem> ticketItems, decimal plainSum, decimal discount) { var sb = new StringBuilder(); var groups = ticketItems.Where(x => x.VatTemplateId > 0).GroupBy(x => x.VatTemplateId); foreach (var @group in groups) { var iGroup = @group; var tb = AppServices.MainDataContext.VatTemplates.FirstOrDefault(x => x.Id == iGroup.Key); var tbTitle = tb != null ? tb.Name : Resources.UndefinedWithBrackets; var total = @group.Sum(x => x.GetTotalVatAmount()); if (discount > 0) { total -= (total * discount) / plainSum; } if (total > 0) sb.AppendLine("<J>" + tbTitle + ":|" + total.ToString("#,#0.00")); } return string.Join("\r", sb); } private static decimal GetTaxTotal(IEnumerable<TicketItem> ticketItems, decimal plainSum, decimal discount) { var result = ticketItems.Sum(x => x.GetTotalVatAmount()); if (discount > 0) { result -= (result * discount) / plainSum; } return result; } private static string FormatData(string data, string tag, Func<string> valueFunc) { if (!data.Contains(tag)) return data; var i = 0; while (data.Contains(tag) && i < 99) { var value = valueFunc.Invoke(); var tagData = new TagData(data, tag); if (!string.IsNullOrEmpty(value)) value = !string.IsNullOrEmpty(tagData.Title) && tagData.Title.Contains("<value>") ? tagData.Title.Replace("<value>", value) : tagData.Title + value; var spos = data.IndexOf(tagData.DataString); data = data.Remove(spos, tagData.Length).Insert(spos, value ?? ""); i++; } return data; } private static string FormatDataIf(bool condition, string data, string tag, Func<string> valueFunc) { if (condition && data.Contains(tag)) { Func<string> value = valueFunc.Invoke; data = FormatData(data, tag, value); return data; } return RemoveTag(data, tag); } private static string RemoveTag(string data, string tag) { var i = 0; while (data.Contains(tag) && i < 99) { var tagData = new TagData(data, tag); var spos = data.IndexOf(tagData.DataString); data = data.Remove(spos, tagData.Length); i++; } return data; } private static string FormatLines(PrinterTemplate template, TicketItem ticketItem) { if (ticketItem.Gifted) { if (!string.IsNullOrEmpty(template.GiftLineTemplate)) { return template.GiftLineTemplate.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries) .Aggregate("", (current, s) => current + ReplaceLineVars(s, ticketItem)); } return ""; } if (ticketItem.Voided) { if (!string.IsNullOrEmpty(template.VoidedLineTemplate)) { return template.VoidedLineTemplate.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries) .Aggregate("", (current, s) => current + ReplaceLineVars(s, ticketItem)); } return ""; } if (!string.IsNullOrEmpty(template.LineTemplate)) return template.LineTemplate.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries) .Aggregate("", (current, s) => current + ReplaceLineVars(s, ticketItem)); return ""; } private static string ReplaceLineVars(string line, TicketItem ticketItem) { string result = line; if (ticketItem != null) { result = FormatData(result, Resources.TF_LineItemQuantity, () => ticketItem.Quantity.ToString("#,#0.##")); result = FormatData(result, Resources.TF_LineItemName, () => ticketItem.MenuItemName + ticketItem.GetPortionDesc()); result = FormatData(result, Resources.TF_LineItemPrice, () => ticketItem.Price.ToString("#,#0.00")); result = FormatData(result, Resources.TF_LineItemTotal, () => ticketItem.GetItemPrice().ToString("#,#0.00")); result = FormatData(result, Resources.TF_LineItemTotalAndQuantity, () => ticketItem.GetItemValue().ToString("#,#0.00")); result = FormatData(result, Resources.TF_LineItemPriceCents, () => (ticketItem.Price * 100).ToString("#,##")); result = FormatData(result, Resources.TF_LineItemTotalWithoutGifts, () => ticketItem.GetTotal().ToString("#,#0.00")); result = FormatData(result, Resources.TF_LineOrderNumber, () => ticketItem.OrderNumber.ToString()); result = FormatData(result, Resources.TF_LineGiftOrVoidReason, () => AppServices.MainDataContext.GetReason(ticketItem.ReasonId)); result = FormatData(result, "{MENU ITEM GROUP}", () => GetMenuItemGroup(ticketItem)); result = FormatData(result, "{MENU ITEM TAG}", () => GetMenuItemTag(ticketItem)); result = FormatData(result, "{PRICE TAG}", () => ticketItem.PriceTag); result = FormatData(result, "{ITEM TAG}", () => ticketItem.Tag); while (Regex.IsMatch(result, "{ITEM TAG:[^}]+}", RegexOptions.Singleline)) { var tags = ticketItem.Tag.Split('|'); var match = Regex.Match(result, "{ITEM TAG:([^}]+)}"); var tagName = match.Groups[0].Value; int index; int.TryParse(match.Groups[1].Value, out index); var value = tags.Count() > index ? tags[index].Trim() : ""; result = result.Replace(tagName, value); } if (result.Contains(Resources.TF_LineItemDetails.Substring(0, Resources.TF_LineItemDetails.Length - 1))) { string lineFormat = result; if (ticketItem.Properties.Count > 0) { string label = ""; foreach (var property in ticketItem.Properties) { var itemProperty = property; var lineValue = FormatData(lineFormat, Resources.TF_LineItemDetails, () => itemProperty.Name); lineValue = FormatData(lineValue, Resources.TF_LineItemDetailQuantity, () => itemProperty.Quantity.ToString("#.##")); lineValue = FormatData(lineValue, Resources.TF_LineItemDetailPrice, () => itemProperty.CalculateWithParentPrice ? "" : itemProperty.PropertyPrice.Amount.ToString("#,#0.00")); label += lineValue + "\r\n"; } result = "\r\n" + label; } else result = ""; } result = UpdateGlobalValues(result); result = result.Replace("<", "\r\n<"); } return result; } private static string GetMenuItemGroup(TicketItem ticketItem) { return Dao.SingleWithCache<MenuItem>(x => x.Id == ticketItem.MenuItemId).GroupCode; } private static string GetMenuItemTag(TicketItem ticketItem) { var result = Dao.SingleWithCache<MenuItem>(x => x.Id == ticketItem.MenuItemId).Tag; if (string.IsNullOrEmpty(result)) result = ticketItem.MenuItemName; return result; } } public static class HumanFriendlyInteger { static readonly string[] Ones = new[] { "", Resources.One, Resources.Two, Resources.Three, Resources.Four, Resources.Five, Resources.Six, Resources.Seven, Resources.Eight, Resources.Nine }; static readonly string[] Teens = new[] { Resources.Ten, Resources.Eleven, Resources.Twelve, Resources.Thirteen, Resources.Fourteen, Resources.Fifteen, Resources.Sixteen, Resources.Seventeen, Resources.Eighteen, Resources.Nineteen }; static readonly string[] Tens = new[] { Resources.Twenty, Resources.Thirty, Resources.Forty, Resources.Fifty, Resources.Sixty, Resources.Seventy, Resources.Eighty, Resources.Ninety }; static readonly string[] ThousandsGroups = { "", " " + Resources.Thousand, " " + Resources.Million, " " + Resources.Billion }; private static string FriendlyInteger(int n, string leftDigits, int thousands) { if (n == 0) { return leftDigits; } string friendlyInt = leftDigits; if (friendlyInt.Length > 0) { friendlyInt += " "; } if (n < 10) { friendlyInt += Ones[n]; } else if (n < 20) { friendlyInt += Teens[n - 10]; } else if (n < 100) { friendlyInt += FriendlyInteger(n % 10, Tens[n / 10 - 2], 0); } else if (n < 1000) { var t = Ones[n / 100] + " " + Resources.Hundred; if (n / 100 == 1) t = Resources.OneHundred; friendlyInt += FriendlyInteger(n % 100, t, 0); } else if (n < 10000 && thousands == 0) { var t = Ones[n / 1000] + " " + Resources.Thousand; if (n / 1000 == 1) t = Resources.OneThousand; friendlyInt += FriendlyInteger(n % 1000, t, 0); } else { friendlyInt += FriendlyInteger(n % 1000, FriendlyInteger(n / 1000, "", thousands + 1), 0); } return friendlyInt + ThousandsGroups[thousands]; } public static string CurrencyToWritten(decimal d, bool upper = false) { var result = ""; var fraction = d - Math.Floor(d); var value = d - fraction; if (value > 0) { var start = IntegerToWritten(Convert.ToInt32(value)); if (upper) start = start.Replace(" ", "").ToUpper(); result += string.Format("{0} {1} ", start, LocalSettings.MajorCurrencyName + GetPlural(value)); } if (fraction > 0) { var end = IntegerToWritten(Convert.ToInt32(fraction * 100)); if (upper) end = end.Replace(" ", "").ToUpper(); result += string.Format("{0} {1} ", end, LocalSettings.MinorCurrencyName + GetPlural(fraction)); } return result.Replace(" ", " ").Trim(); } private static string GetPlural(decimal number) { return number == 1 ? "" : LocalSettings.PluralCurrencySuffix; } public static string IntegerToWritten(int n) { if (n == 0) { return Resources.Zero; } if (n < 0) { return Resources.Negative + " " + IntegerToWritten(-n); } return FriendlyInteger(n, "", 0); } } }
zzgaminginc-pointofssale
Samba.Services/Printing/TicketFormatter.cs
C#
gpl3
33,964
using System; using System.Printing; using System.Windows; using System.Windows.Documents; using System.Windows.Xps; using Samba.Domain.Models.Settings; namespace Samba.Services.Printing { public abstract class AbstractPrintJob { protected AbstractPrintJob(Printer printer) { Printer = printer; } public Printer Printer { get; set; } public abstract void DoPrint(string[] lines); public abstract void DoPrint(FlowDocument document); internal static string RemoveTag(string line) { return line.Contains(">") ? line.Substring(line.IndexOf(">") + 1) : line; } internal static void PrintFlowDocument(PrintQueue pq, FlowDocument flowDocument) { if (pq == null) return; // Create a XpsDocumentWriter object, open a Windows common print dialog. // This methods returns a ref parameter that represents information about the dimensions of the printer media. XpsDocumentWriter docWriter = PrintQueue.CreateXpsDocumentWriter(pq); PageImageableArea ia = pq.GetPrintCapabilities().PageImageableArea; PrintTicket pt = pq.UserPrintTicket; if (ia != null) { DocumentPaginator paginator = ((IDocumentPaginatorSource)flowDocument).DocumentPaginator; // Change the PageSize and PagePadding for the document to match the CanvasSize for the printer device. paginator.PageSize = new Size((double)pt.PageMediaSize.Width, (double)pt.PageMediaSize.Height); Thickness pagePadding = flowDocument.PagePadding; flowDocument.PagePadding = new Thickness( Math.Max(ia.OriginWidth, pagePadding.Left), Math.Max(ia.OriginHeight, pagePadding.Top), Math.Max((double)pt.PageMediaSize.Width - (ia.OriginWidth + ia.ExtentWidth), pagePadding.Right), Math.Max((double)pt.PageMediaSize.Height - (ia.OriginHeight + ia.ExtentHeight), pagePadding.Bottom)); flowDocument.ColumnWidth = double.PositiveInfinity; // Send DocumentPaginator to the printer. docWriter.Write(paginator); } } } }
zzgaminginc-pointofssale
Samba.Services/Printing/AbstractPrintJob.cs
C#
gpl3
2,368
using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Windows.Documents; using Samba.Domain.Models.Settings; using Samba.Infrastructure.Printing; namespace Samba.Services.Printing { class DemoPrinterJob : AbstractPrintJob { [DllImport("user32.dll", EntryPoint = "FindWindowEx")] public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow); [DllImport("User32.dll")] public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam); public DemoPrinterJob(Printer printer) : base(printer) { } public override void DoPrint(string[] lines) { Debug.Assert(!string.IsNullOrEmpty(Printer.ShareName)); lines = PrinterHelper.AlignLines(lines, Printer.CharsPerLine, false).ToArray(); lines = PrinterHelper.ReplaceChars(lines, Printer.ReplacementPattern).ToArray(); var text = lines.Aggregate("", (current, s) => current + RemoveTagFmt(s)); if (!IsValidFile(Printer.ShareName) || !SaveToFile(Printer.ShareName, text)) SendToNotepad(Printer, text); } private static bool IsValidFile(string fileName) { fileName = fileName.Trim(); if (fileName == "." || !fileName.Contains(".")) return false; var result = false; try { new FileInfo(fileName); result = true; } catch (ArgumentException) { } catch (PathTooLongException) { } catch (NotSupportedException) { } return result; } private static bool SaveToFile(string fileName, string text) { try { File.WriteAllText(fileName, text); return true; } catch (Exception) { return false; } } private static void SendToNotepad(Printer printer, string text) { var pcs = printer.ShareName.Split('#'); var wname = "Edit"; if (pcs.Length > 1) wname = pcs[1]; var notepads = Process.GetProcessesByName(pcs[0]); if (notepads.Length == 0) notepads = Process.GetProcessesByName("notepad"); if (notepads.Length == 0) return; if (notepads[0] != null) { IntPtr child = FindWindowEx(notepads[0].MainWindowHandle, new IntPtr(0), wname, null); SendMessage(child, 0x000C, 0, text); } } private static string RemoveTagFmt(string s) { var result = RemoveTag(s.Replace("|", " ")); if (!string.IsNullOrEmpty(result)) return result + "\r\n"; return ""; } public override void DoPrint(FlowDocument document) { DoPrint(PrinterTools.FlowDocumentToSlipPrinterFormat(document, Printer.CharsPerLine)); } } }
zzgaminginc-pointofssale
Samba.Services/Printing/DemoPrinterJob.cs
C#
gpl3
3,328
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Documents; using Samba.Domain.Models.Settings; using Samba.Infrastructure.Printing; namespace Samba.Services.Printing { class PortPrinterJob : AbstractPrintJob { public PortPrinterJob(Printer printer) : base(printer) { } public override void DoPrint(string[] lines) { foreach (var line in lines) { var data = line.Contains("<") ? line.Split('<').Where(x => !string.IsNullOrEmpty(x)).Select(x => '<' + x) : line.Split('#'); data = PrinterHelper.AlignLines(data, Printer.CharsPerLine, false); data = PrinterHelper.ReplaceChars(data, Printer.ReplacementPattern); foreach (var s in data) { if (s.Trim().ToLower() == "<w>") { System.Threading.Thread.Sleep(100); } else if (s.ToLower().StartsWith("<lb")) { SerialPortService.WritePort(Printer.ShareName, RemoveTag(s) + "\n\r"); } else if (s.ToLower().StartsWith("<xct")) { var lineData = s.ToLower().Replace("<xct", "").Trim(new[] { ' ', '<', '>' }); SerialPortService.WriteCommand(Printer.ShareName, lineData, Printer.CodePage); } else { SerialPortService.WritePort(Printer.ShareName, RemoveTag(s), Printer.CodePage); } } } } public override void DoPrint(FlowDocument document) { return; } } }
zzgaminginc-pointofssale
Samba.Services/Printing/PortPrinterJob.cs
C#
gpl3
1,896
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Documents; using Samba.Domain.Models.Settings; using Samba.Infrastructure.Printing; namespace Samba.Services.Printing { public class TextPrinterJob : AbstractPrintJob { public TextPrinterJob(Printer printer) : base(printer) { } public override void DoPrint(string[] lines) { var q = AppServices.PrintService.GetPrinter(Printer.ShareName); lines = PrinterHelper.AlignLines(lines, Printer.CharsPerLine, false).ToArray(); var text = lines.Aggregate("", (current, s) => current + RemoveTag(s.Replace("|", "")) + "\r\n"); PrintFlowDocument(q, new FlowDocument(new Paragraph(new Run(text)))); } public override void DoPrint(FlowDocument document) { var q = AppServices.PrintService.GetPrinter(Printer.ShareName); PrintFlowDocument(q, document); } } }
zzgaminginc-pointofssale
Samba.Services/Printing/TextPrinterJob.cs
C#
gpl3
1,038
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Windows; using System.Windows.Documents; using Samba.Infrastructure.Printing; namespace Samba.Services.Printing { internal static class PrinterTools { public static string FlowDocumentToXaml(FlowDocument document) { var tr = new TextRange(document.ContentStart, document.ContentEnd); using (var ms = new MemoryStream()) { tr.Save(ms, DataFormats.Xaml); return Encoding.UTF8.GetString(ms.ToArray()); } } public static FlowDocument XamlToFlowDocument(string text) { var document = new FlowDocument(); using (var stream = new MemoryStream((new UTF8Encoding()).GetBytes(text))) { var txt = new TextRange(document.ContentStart, document.ContentEnd); txt.Load(stream, DataFormats.Xaml); } return document; } private static int _maxWidth; public static string[] FlowDocumentToSlipPrinterFormat(FlowDocument document, int maxWidth) { _maxWidth = maxWidth; var result = new List<string>(); if (document != null) result.AddRange(ReadBlocks(document.Blocks)); return result.ToArray(); } private static IEnumerable<string> ReadBlocks(IEnumerable<Block> blocks) { var result = new List<string>(); foreach (var block in blocks) { result.AddRange(ReadRuns(block)); result.AddRange(ReadTables(block)); } return result; } private static IEnumerable<string> ReadRuns(Block block) { var result = new List<string>(); if (block is Paragraph) { result.AddRange((block as Paragraph).Inlines.OfType<Run>().Select(inline => inline.Text.Trim())); } return result; } private static IEnumerable<string> ReadTables(Block block) { var result = new List<string>(); if (block is Table) result.AddRange(ReadTable(block as Table)); return result; } private static IEnumerable<string> ReadTable(Table table) { var result = new List<string> { " " }; var colLenghts = new int[table.Columns.Count]; var colAlignments = new TextAlignment[table.Columns.Count]; if (table.RowGroups.Count == 0) return result; foreach (var row in table.RowGroups[0].Rows) { for (var i = 0; i < row.Cells.Count; i++) { if (table.RowGroups[0].Rows.Count > 1 && row == table.RowGroups[0].Rows[1]) colAlignments[i] = (row.Cells[i].Blocks.First()).TextAlignment; var value = string.Join(" ", ReadBlocks(row.Cells[i].Blocks)); if (value.Length > colLenghts[i] && row.Cells[0].ColumnSpan == 1) colLenghts[i] = value.Length; } } if (_maxWidth > 0 && colLenghts.Sum() > _maxWidth) { while (colLenghts.Sum() > _maxWidth) colLenghts[GetMaxCol(colLenghts)]--; } foreach (var row in table.RowGroups[0].Rows) { if (row == table.RowGroups[0].Rows[0]) result.Add("<EB>"); var rowValue = ""; for (var i = 0; i < row.Cells.Count; i++) { var values = ReadBlocks(row.Cells[i].Blocks); if (i == row.Cells.Count - 1 && row != table.RowGroups[0].Rows[0]) { var v = string.Join(" ", values).Trim(); if (!string.IsNullOrEmpty(rowValue)) rowValue = rowValue + " | " + v; else rowValue = "<R>" + v; } else { var value = string.Join(" ", values); if (value.Length > colLenghts[i] && row.Cells.Count > 1) value = colLenghts[i] > 0 ? value.Substring(0, colLenghts[i] - 1) : ""; if (i < row.Cells.Count) { value = colAlignments[i] == TextAlignment.Right ? row == table.RowGroups[0].Rows[0] ? value.PadLeft(colLenghts[i]) : " | " + value : value.PadRight(colLenghts[i]); } if (!string.IsNullOrEmpty(rowValue) && !rowValue.EndsWith(" ") && !value.StartsWith(" ")) value = " " + value; rowValue += value; } } if (row == table.RowGroups[0].Rows[0]) { result.Add("<L00>"); result.Add("<C00>" + rowValue); result.Add("<DB>"); result.Add("<F>-"); } else if (rowValue.Contains("|")) result.Add("<J00>" + rowValue); else { result.Add(rowValue); } } return result; } private static int GetMaxCol(IList<int> colLenghts) { var result = 0; for (var i = 1; i < colLenghts.Count; i++) { if (colLenghts[i] > colLenghts[result]) result = i; } return result; } } }
zzgaminginc-pointofssale
Samba.Services/Printing/PrinterTools.cs
C#
gpl3
6,020
using System.Collections.Generic; namespace Samba.Services { public static class PermissionRegistry { public static IDictionary<string, string[]> PermissionNames = new Dictionary<string, string[]>(); public static void RegisterPermission(string permissionName, string permissionCategory, string permissionTitle) { if (!PermissionNames.ContainsKey(permissionName)) PermissionNames.Add(permissionName, new[] { permissionCategory, permissionTitle }); } } }
zzgaminginc-pointofssale
Samba.Services/PermissionRegistry.cs
C#
gpl3
544
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.MessagingServer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Samba.MessagingServer")] [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("d074239b-2d35-4d71-820e-cc37176f2b67")] // 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.MessagingServer/Properties/AssemblyInfo.cs
C#
gpl3
1,454
using System; using System.Collections; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; using System.Windows.Forms; using Samba.Infrastructure; using Samba.MessagingServer.Properties; namespace Samba.MessagingServer { public partial class frmMain : Form { public frmMain() { InitializeComponent(); } private static TcpChannel _channel; private void button1_Click(object sender, EventArgs e) { StartServer(); } private void StartServer() { var port = Convert.ToInt32(edPort.Text); var serverProv = new BinaryServerFormatterSinkProvider { TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full }; var clientProv = new BinaryClientFormatterSinkProvider(); IDictionary props = new Hashtable(); props["port"] = port; _channel = new TcpChannel(props, clientProv, serverProv); ChannelServices.RegisterChannel(_channel, false); RemotingConfiguration.RegisterWellKnownServiceType(typeof(MessagingServerObject), "ChatServer", WellKnownObjectMode.Singleton); lbStatus.Text = Resources.status_working; btnStart.Enabled = false; btnStop.Enabled = true; WindowState = FormWindowState.Minimized; } private void button2_Click(object sender, EventArgs e) { if (_channel != null) { ChannelServices.UnregisterChannel(_channel); _channel = null; lbStatus.Text = Resources.status_stopped; btnStart.Enabled = true; btnStop.Enabled = false; } } private void frmMain_FormClosing(object sender, FormClosingEventArgs e) { if (_channel != null) ChannelServices.UnregisterChannel(_channel); Properties.Settings.Default.Save(); } private void notifyIcon1_DoubleClick(object sender, EventArgs e) { Show(); WindowState = FormWindowState.Normal; } private void frmMain_Resize(object sender, EventArgs e) { if (WindowState == FormWindowState.Minimized) Hide(); else { Show(); } } private void frmMain_Shown(object sender, EventArgs e) { if (Properties.Settings.Default.AutoStartServer) StartServer(); } private void notifyIcon1_Click(object sender, EventArgs e) { Show(); WindowState = FormWindowState.Normal; } } }
zzgaminginc-pointofssale
Samba.MessagingServer/frmMain.cs
C#
gpl3
3,070
using System; using System.Globalization; using System.Threading; using System.Windows.Forms; namespace Samba.MessagingServer { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Thread.CurrentThread.CurrentUICulture = CultureInfo.CurrentCulture; Application.Run(new frmMain()); } } }
zzgaminginc-pointofssale
Samba.MessagingServer/Program.cs
C#
gpl3
595
using System.Collections.ObjectModel; using System.Linq; namespace Samba.Presentation.Common.Services { public static class PresentationServices { private static ApplicationSubTitleViewModel _subTitle; public static ApplicationSubTitleViewModel SubTitle { get { return _subTitle ?? (_subTitle = new ApplicationSubTitleViewModel()); } } public static ObservableCollection<ICategoryCommand> NavigationCommandCategories { get; private set; } public static ObservableCollection<DashboardCommandCategory> DashboardCommandCategories { get; private set; } public static void Initialize() { NavigationCommandCategories = new ObservableCollection<ICategoryCommand>(); DashboardCommandCategories = new ObservableCollection<DashboardCommandCategory>(); EventServiceFactory.EventService.GetEvent<GenericEvent<ICategoryCommand>>().Subscribe(OnNavigationCommandAdded); EventServiceFactory.EventService.GetEvent<GenericEvent<ICategoryCommand>>().Subscribe(OnDashboardCommand); } private static void OnNavigationCommandAdded(EventParameters<ICategoryCommand> obj) { if (obj.Topic == EventTopicNames.NavigationCommandAdded) NavigationCommandCategories.Add(obj.Value); } private static void OnDashboardCommand(EventParameters<ICategoryCommand> result) { if (result.Topic == EventTopicNames.DashboardCommandAdded) { var cat = DashboardCommandCategories.FirstOrDefault(item => item.Category == result.Value.Category); if (cat == null) { cat = new DashboardCommandCategory(result.Value.Category); DashboardCommandCategories.Add(cat); } if (result.Value.Order > cat.Order) cat.Order = result.Value.Order; cat.AddCommand(result.Value); } } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Services/PresentationServices.cs
C#
gpl3
2,090
using System; using System.Collections.Generic; using Samba.Domain.Models.Settings; using Samba.Infrastructure.Cron; using Samba.Persistance.Data; using Samba.Services; namespace Samba.Presentation.Common.Services { public static class TriggerService { private static readonly List<CronObject> CronObjects = new List<CronObject>(); public static void UpdateCronObjects() { CloseTriggers(); var triggers = Dao.Query<Trigger>(); foreach (var trigger in triggers) { var dataContext = new CronObjectDataContext { Object = trigger, LastTrigger = trigger.LastTrigger, CronSchedules = new List<CronSchedule> { CronSchedule.Parse(trigger.Expression) } }; var cronObject = new CronObject(dataContext); cronObject.OnCronTrigger += OnCronTrigger; CronObjects.Add(cronObject); } CronObjects.ForEach(x => x.Start()); } public static void CloseTriggers() { foreach (var cronObject in CronObjects) { cronObject.Stop(); cronObject.OnCronTrigger -= OnCronTrigger; } CronObjects.Clear(); } private static void OnCronTrigger(CronObject cronobject) { using (var workspace = WorkspaceFactory.Create()) { var trigger = workspace.Single<Trigger>(x => x.Id == ((Trigger)cronobject.Object).Id); if (trigger != null) { trigger.LastTrigger = DateTime.Now; workspace.CommitChanges(); if (AppServices.ActiveAppScreen != AppScreens.Dashboard) RuleExecutor.NotifyEvent(RuleEventNames.TriggerExecuted, new { TriggerName = trigger.Name }); } else cronobject.Stop(); } } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Services/TriggerService.cs
C#
gpl3
2,129
namespace Samba.Presentation.Common.Services { public class ApplicationSubTitleViewModel : ObservableObject { public ApplicationSubTitleViewModel() { ApplicationTitleColor = "White"; ApplicationTitleFontSize = 24; } private string _applicationTitle; public string ApplicationTitle { get { return _applicationTitle; } set { _applicationTitle = value; RaisePropertyChanged("ApplicationTitle"); } } private int _applicationTitleFontSize; public int ApplicationTitleFontSize { get { return _applicationTitleFontSize; } set { _applicationTitleFontSize = value; RaisePropertyChanged("ApplicationTitleFontSize"); } } private string _applicationTitleColor; public string ApplicationTitleColor { get { return _applicationTitleColor; } set { _applicationTitleColor = value; RaisePropertyChanged("ApplicationTitleColor"); } } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Services/ApplicationSubTitleViewModel.cs
C#
gpl3
1,263
using System; using System.Runtime.InteropServices; using System.Security; namespace Samba.Presentation.Common.Services { public static class InteractionService { private const uint WM_MOUSEFIRST = 0x200; private const uint WM_MOUSELAST = 0x209; [StructLayout(LayoutKind.Sequential)] public struct NativeMessage { public IntPtr handle; public uint msg; public IntPtr wParam; public IntPtr lParam; public uint time; public System.Drawing.Point p; } [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] [DllImport("User32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern bool PeekMessage(out NativeMessage message, IntPtr handle, uint filterMin, uint filterMax, uint flags); public static void ClearMouseClickQueue() { NativeMessage message; while (PeekMessage(out message, IntPtr.Zero, WM_MOUSEFIRST, WM_MOUSELAST, 1)) { } } public static IUserInteraction UserIntraction { get; set; } public static void ShowKeyboard() { UserIntraction.ShowKeyboard(); } public static void HideKeyboard() { UserIntraction.HideKeyboard(); } public static void ToggleKeyboard() { UserIntraction.ToggleKeyboard(); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Services/InteractionService.cs
C#
gpl3
1,566
using System.Windows.Forms; using UserControl = System.Windows.Controls.UserControl; namespace Samba.Presentation.Common.VirtualKeyboard { /// <summary> /// Interaction logic for KeyboardView.xaml /// </summary> public partial class KeyboardView2 : UserControl { public KeyboardView2() { InitializeComponent(); DataContext = new KeyboardViewModel(); } private void UserControl_IsVisibleChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e) { if (DataContext == null || ((KeyboardViewModel)DataContext).Model == null) return; ((KeyboardViewModel)DataContext).Model.ReleaseKey(Keys.ShiftKey); ((KeyboardViewModel)DataContext).Model.ReleaseKey(Keys.LShiftKey); ((KeyboardViewModel)DataContext).Model.ReleaseKey(Keys.RShiftKey); } public void SendKey(Keys key) { ((KeyboardViewModel)DataContext).Model.SendKey(key); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/VirtualKeyboard/KeyboardView2.xaml.cs
C#
gpl3
1,058
using System.Windows.Forms; using UserControl = System.Windows.Controls.UserControl; namespace Samba.Presentation.Common.VirtualKeyboard { /// <summary> /// Interaction logic for KeyboardView.xaml /// </summary> public partial class KeyboardView : UserControl { public KeyboardView() { InitializeComponent(); DataContext = new KeyboardViewModel(); } private void UserControl_IsVisibleChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e) { if (DataContext == null || ((KeyboardViewModel)DataContext).Model == null) return; ((KeyboardViewModel)DataContext).Model.ReleaseKey(Keys.ShiftKey); ((KeyboardViewModel)DataContext).Model.ReleaseKey(Keys.LShiftKey); ((KeyboardViewModel)DataContext).Model.ReleaseKey(Keys.RShiftKey); } public void SendKey(Keys key) { ((KeyboardViewModel)DataContext).Model.SendKey(key); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/VirtualKeyboard/KeyboardView.xaml.cs
C#
gpl3
1,056
using System; using System.Globalization; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; using System.Windows.Input; namespace Samba.Presentation.Common.VirtualKeyboard { public enum KeyState { FirstSet, SecondSet } public class VKey : ObservableObject { private KeyState _keyState; public KeyState KeyState { get { return _keyState; } set { _keyState = value; RaisePropertyChanged("Caption"); } } public string Caption { get { return KeyState == KeyState.FirstSet ? LowKey : UpKey; } } public string LowKey { get; set; } public string UpKey { get; set; } public Keys VirtualKey { get; set; } public VKey(string lowKey, string upKey, Keys virtualKey) { LowKey = lowKey; UpKey = upKey; VirtualKey = virtualKey; } public VKey(Keys virtualKey) { VirtualKey = virtualKey; try { LowKey = User32Interop.ToUnicode(virtualKey, Keys.None).ToString(); } catch (Exception) { LowKey = " "; } try { UpKey = User32Interop.ToUnicode(virtualKey, Keys.ShiftKey).ToString(); } catch (Exception) { UpKey = " "; } } } public static class User32Interop { public static char ToUnicode(Keys key, Keys modifiers) { var chars = new char[1]; int result = ToUnicode((uint)key, 0, GetKeyState(modifiers), chars, chars.Length, 0); if (result == 1) { return chars[0]; } result = ToUnicode((uint)key, 0, GetKeyState(modifiers), chars, chars.Length, 0); if (result == 1) { return chars[0]; } throw new Exception("Invalid key"); } private const byte HighBit = 0x80; private static byte[] GetKeyState(Keys modifiers) { var keyState = new byte[256]; foreach (Keys key in Enum.GetValues(typeof(Keys))) { if ((modifiers & key) == key) { keyState[(int)key] = HighBit; } } return keyState; } [DllImport("USER32.DLL", CharSet = CharSet.Unicode)] public static extern int ToUnicode(uint virtualKey, uint scanCode, byte[] keyStates, [MarshalAs(UnmanagedType.LPArray)] [Out] char[] chars, int charMaxCount, uint flags); } }
zzgaminginc-pointofssale
Samba.Presentation.Common/VirtualKeyboard/VKey.cs
C#
gpl3
2,769
using Microsoft.Practices.Prism.Commands; namespace Samba.Presentation.Common.VirtualKeyboard { public class KeyboardViewModel { public VKeyboard Model { get; set; } public DelegateCommand<VKey> PressKeyCommand { get; set; } public KeyboardViewModel() { Model = new VKeyboard(); PressKeyCommand = new DelegateCommand<VKey>(OnKeyPress); } private void OnKeyPress(VKey obj) { Model.ProcessKey(obj.VirtualKey); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/VirtualKeyboard/KeyboardViewModel.cs
C#
gpl3
553
using System.Collections.Generic; using System.Runtime.InteropServices; using System.Windows.Forms; namespace Samba.Presentation.Common.VirtualKeyboard { public class VKeyboard { public VKey KeyA { get; set; } public VKey KeyB { get; set; } public VKey KeyC { get; set; } public VKey KeyCTr { get; set; } public VKey KeyD { get; set; } public VKey KeyE { get; set; } public VKey KeyF { get; set; } public VKey KeyG { get; set; } public VKey KeyGTr { get; set; } public VKey KeyH { get; set; } public VKey KeyI { get; set; } public VKey KeyITr { get; set; } public VKey KeyJ { get; set; } public VKey KeyK { get; set; } public VKey KeyL { get; set; } public VKey KeyM { get; set; } public VKey KeyN { get; set; } public VKey KeyO { get; set; } public VKey KeyOTr { get; set; } public VKey KeyP { get; set; } public VKey KeyQ { get; set; } public VKey KeyR { get; set; } public VKey KeyS { get; set; } public VKey KeySTr { get; set; } public VKey KeyT { get; set; } public VKey KeyU { get; set; } public VKey KeyUTr { get; set; } public VKey KeyV { get; set; } public VKey KeyW { get; set; } public VKey KeyX { get; set; } public VKey KeyY { get; set; } public VKey KeyZ { get; set; } public VKey Key1 { get; set; } public VKey Key2 { get; set; } public VKey Key3 { get; set; } public VKey Key4 { get; set; } public VKey Key5 { get; set; } public VKey Key6 { get; set; } public VKey Key7 { get; set; } public VKey Key8 { get; set; } public VKey Key9 { get; set; } public VKey Key0 { get; set; } public VKey KeyDoubleQuote { get; set; } public VKey KeyTab { get; set; } public VKey KeyCaps { get; set; } public VKey KeyShift { get; set; } public VKey KeyStar { get; set; } public VKey KeyDash { get; set; } public VKey KeyBack { get; set; } public VKey KeyEnter { get; set; } public VKey KeyComma { get; set; } public VKey KeyPoint { get; set; } public VKey KeyAt { get; set; } public VKey KeySpace { get; set; } public VKey UpArrow { get; set; } public VKey DownArrow { get; set; } public IList<VKey> VirtualKeys { get; set; } public VKeyboard() { VirtualKeys = new List<VKey>(); KeyA = new VKey(Keys.A); VirtualKeys.Add(KeyA); KeyB = new VKey(Keys.B); VirtualKeys.Add(KeyB); KeyC = new VKey(Keys.C); VirtualKeys.Add(KeyC); KeyCTr = new VKey(Keys.Oem5); VirtualKeys.Add(KeyCTr); KeyD = new VKey(Keys.D); VirtualKeys.Add(KeyD); KeyE = new VKey(Keys.E); VirtualKeys.Add(KeyE); KeyF = new VKey(Keys.F); VirtualKeys.Add(KeyF); KeyG = new VKey(Keys.G); VirtualKeys.Add(KeyG); KeyGTr = new VKey(Keys.Oem4); VirtualKeys.Add(KeyGTr); KeyH = new VKey(Keys.H); VirtualKeys.Add(KeyH); KeyI = new VKey(Keys.I); VirtualKeys.Add(KeyI); KeyITr = new VKey(Keys.Oem7); VirtualKeys.Add(KeyITr); KeyJ = new VKey(Keys.J); VirtualKeys.Add(KeyJ); KeyK = new VKey(Keys.K); VirtualKeys.Add(KeyK); KeyL = new VKey(Keys.L); VirtualKeys.Add(KeyL); KeyM = new VKey(Keys.M); VirtualKeys.Add(KeyM); KeyN = new VKey(Keys.N); VirtualKeys.Add(KeyN); KeyO = new VKey(Keys.O); VirtualKeys.Add(KeyO); KeyOTr = new VKey(Keys.Oem2); VirtualKeys.Add(KeyOTr); KeyP = new VKey(Keys.P); VirtualKeys.Add(KeyP); KeyQ = new VKey(Keys.Q); VirtualKeys.Add(KeyQ); KeyR = new VKey(Keys.R); VirtualKeys.Add(KeyR); KeyS = new VKey(Keys.S); VirtualKeys.Add(KeyS); KeySTr = new VKey(Keys.Oem1); VirtualKeys.Add(KeySTr); KeyT = new VKey(Keys.T); VirtualKeys.Add(KeyT); KeyU = new VKey(Keys.U); VirtualKeys.Add(KeyU); KeyUTr = new VKey(Keys.Oem6); VirtualKeys.Add(KeyUTr); KeyV = new VKey(Keys.V); VirtualKeys.Add(KeyV); KeyW = new VKey(Keys.W); VirtualKeys.Add(KeyW); KeyX = new VKey(Keys.X); VirtualKeys.Add(KeyX); KeyY = new VKey(Keys.Y); VirtualKeys.Add(KeyY); KeyZ = new VKey(Keys.Z); VirtualKeys.Add(KeyZ); Key1 = new VKey(Keys.D1); VirtualKeys.Add(Key1); Key2 = new VKey(Keys.D2); VirtualKeys.Add(Key2); Key3 = new VKey(Keys.D3); VirtualKeys.Add(Key3); Key4 = new VKey(Keys.D4); VirtualKeys.Add(Key4); Key5 = new VKey(Keys.D5); VirtualKeys.Add(Key5); Key6 = new VKey(Keys.D6); VirtualKeys.Add(Key6); Key7 = new VKey(Keys.D7); VirtualKeys.Add(Key7); Key8 = new VKey(Keys.D8); VirtualKeys.Add(Key8); Key9 = new VKey(Keys.D9); VirtualKeys.Add(Key9); Key0 = new VKey(Keys.D0); VirtualKeys.Add(Key0); KeyDoubleQuote = new VKey(Keys.Oem3); VirtualKeys.Add(KeyDoubleQuote); KeyTab = new VKey("Tab", "Tab", Keys.Tab); VirtualKeys.Add(KeyTab); KeyCaps = new VKey("Caps", "Caps", Keys.Capital); VirtualKeys.Add(KeyCaps); KeyShift = new VKey("Shift", "Shift", Keys.Shift); VirtualKeys.Add(KeyShift); KeyStar = new VKey(Keys.Oem8); VirtualKeys.Add(KeyStar); KeyDash = new VKey(Keys.OemMinus); VirtualKeys.Add(KeyDash); KeyBack = new VKey("BackSpace", "BackSpace", Keys.Back); VirtualKeys.Add(KeyBack); KeyEnter = new VKey("Enter", "Enter", Keys.Enter); VirtualKeys.Add(KeyEnter); KeyComma = new VKey(Keys.Oemcomma); VirtualKeys.Add(KeyComma); KeyPoint = new VKey(Keys.OemPeriod); VirtualKeys.Add(KeyPoint); KeyAt = new VKey("@", "€", Keys.Oem1); VirtualKeys.Add(KeyAt); KeySpace = new VKey(" ", "Space", Keys.Space); VirtualKeys.Add(KeySpace); UpArrow = new VKey("Up", "Up", Keys.Up); VirtualKeys.Add(UpArrow); DownArrow = new VKey("Down", "Down", Keys.Down); VirtualKeys.Add(DownArrow); } public void PressKey(Keys keyCode) { var structInput = new INPUT(); structInput.type = 1; structInput.ki.wScan = 0; structInput.ki.time = 0; structInput.ki.dwFlags = 0; structInput.ki.dwExtraInfo = 0; // Key down the actual key-code structInput.ki.wVk = (ushort)keyCode; //VK.SHIFT etc. NativeWin32.SendInput(1, ref structInput, Marshal.SizeOf(structInput)); } public void ReleaseKey(Keys keyCode) { var structInput = new INPUT(); structInput.type = 1; structInput.ki.wScan = 0; structInput.ki.time = 0; structInput.ki.dwFlags = 0; structInput.ki.dwExtraInfo = 0; // Key up the actual key-code structInput.ki.dwFlags = NativeWin32.KEYEVENTF_KEYUP; structInput.ki.wVk = (ushort)keyCode;// (ushort)NativeWin32.VK.SNAPSHOT;//vk; NativeWin32.SendInput(1, ref structInput, Marshal.SizeOf(structInput)); } public void ProcessKey(Keys keyCode) { if (keyCode == Keys.Shift) { ToggleShift(); } else { SendKey(keyCode); if (_shifted) ToggleShift(); } } private bool _shifted; private void ToggleShift() { _shifted = !_shifted; foreach (var virtualKey in VirtualKeys) { virtualKey.KeyState = _shifted ? KeyState.SecondSet : KeyState.FirstSet; } if (_shifted) PressKey(Keys.LShiftKey); else ReleaseKey(Keys.LShiftKey); } public void SendKey(Keys keyCode) { PressKey(keyCode); ReleaseKey(keyCode); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/VirtualKeyboard/VKeyboard.cs
C#
gpl3
8,380
// -- FILE ------------------------------------------------------------------ // name : RangeColumn.cs // created : Jani Giannoudis - 2008.03.27 // language : c# // environment: .NET 3.0 // -------------------------------------------------------------------------- using System; using System.Windows; using System.Windows.Controls; namespace Samba.Presentation.Common.ListViewLM { // ------------------------------------------------------------------------ public sealed class RangeColumn : LayoutColumn { // ---------------------------------------------------------------------- public static readonly DependencyProperty MinWidthProperty = DependencyProperty.RegisterAttached( "MinWidth", typeof( double ), typeof( RangeColumn ) ); // ---------------------------------------------------------------------- public static readonly DependencyProperty MaxWidthProperty = DependencyProperty.RegisterAttached( "MaxWidth", typeof( double ), typeof( RangeColumn ) ); // ---------------------------------------------------------------------- public static readonly DependencyProperty IsFillColumnProperty = DependencyProperty.RegisterAttached( "IsFillColumn", typeof( bool ), typeof( RangeColumn ) ); // ---------------------------------------------------------------------- private RangeColumn() { } // RangeColumn // ---------------------------------------------------------------------- public static double GetMinWidth( DependencyObject obj ) { return (double)obj.GetValue( MinWidthProperty ); } // GetMinWidth // ---------------------------------------------------------------------- public static void SetMinWidth( DependencyObject obj, double minWidth ) { obj.SetValue( MinWidthProperty, minWidth ); } // SetMinWidth // ---------------------------------------------------------------------- public static double GetMaxWidth( DependencyObject obj ) { return (double)obj.GetValue( MaxWidthProperty ); } // GetMaxWidth // ---------------------------------------------------------------------- public static void SetMaxWidth( DependencyObject obj, double maxWidth ) { obj.SetValue( MaxWidthProperty, maxWidth ); } // SetMaxWidth // ---------------------------------------------------------------------- public static bool GetIsFillColumn( DependencyObject obj ) { return (bool)obj.GetValue( IsFillColumnProperty ); } // GetIsFillColumn // ---------------------------------------------------------------------- public static void SetIsFillColumn( DependencyObject obj, bool isFillColumn ) { obj.SetValue( IsFillColumnProperty, isFillColumn ); } // SetIsFillColumn // ---------------------------------------------------------------------- public static bool IsRangeColumn( GridViewColumn column ) { if ( column == null ) { return false; } return HasPropertyValue( column, MinWidthProperty ) || HasPropertyValue( column, MaxWidthProperty ) || HasPropertyValue( column, IsFillColumnProperty ); } // IsRangeColumn // ---------------------------------------------------------------------- public static double? GetRangeMinWidth( GridViewColumn column ) { return GetColumnWidth( column, MinWidthProperty ); } // GetRangeMinWidth // ---------------------------------------------------------------------- public static double? GetRangeMaxWidth( GridViewColumn column ) { return GetColumnWidth( column, MaxWidthProperty ); } // GetRangeMaxWidth // ---------------------------------------------------------------------- public static bool? GetRangeIsFillColumn( GridViewColumn column ) { if ( column == null ) { throw new ArgumentNullException( "column" ); } object value = column.ReadLocalValue( IsFillColumnProperty ); if ( value != null && value.GetType() == IsFillColumnProperty.PropertyType ) { return (bool)value; } return null; } // GetRangeIsFillColumn // ---------------------------------------------------------------------- public static GridViewColumn ApplyWidth( GridViewColumn gridViewColumn, double minWidth, double width, double maxWidth ) { return ApplyWidth( gridViewColumn, minWidth, width, maxWidth, false ); } // ApplyWidth // ---------------------------------------------------------------------- public static GridViewColumn ApplyWidth( GridViewColumn gridViewColumn, double minWidth, double width, double maxWidth, bool isFillColumn ) { SetMinWidth( gridViewColumn, minWidth ); gridViewColumn.Width = width; SetMaxWidth( gridViewColumn, maxWidth ); SetIsFillColumn( gridViewColumn, isFillColumn ); return gridViewColumn; } // ApplyWidth } // class RangeColumn } // namespace Itenso.Windows.Controls.ListViewLayout // -- EOF -------------------------------------------------------------------
zzgaminginc-pointofssale
Samba.Presentation.Common/ListViewLM/RangeColumn.cs
C#
gpl3
5,050
// -- FILE ------------------------------------------------------------------ // name : ImageGridViewColumn.cs // created : Jani Giannoudis - 2008.03.27 // language : c# // environment: .NET 3.0 // -------------------------------------------------------------------------- using System; using System.Globalization; using System.Windows; using System.Windows.Data; using System.Windows.Media; using System.Windows.Controls; namespace Samba.Presentation.Common.ListViewLM { // ------------------------------------------------------------------------ public abstract class ImageGridViewColumn : GridViewColumn, IValueConverter { // ---------------------------------------------------------------------- protected ImageGridViewColumn() : this( Stretch.None ) { } // ImageGridViewColumn // ---------------------------------------------------------------------- protected ImageGridViewColumn( Stretch imageStretch ) { FrameworkElementFactory imageElement = new FrameworkElementFactory( typeof( Image ) ); // image source Binding imageSourceBinding = new Binding(); imageSourceBinding.Converter = this; imageSourceBinding.Mode = BindingMode.OneWay; imageElement.SetBinding( Image.SourceProperty, imageSourceBinding ); // image stretching Binding imageStretchBinding = new Binding(); imageStretchBinding.Source = imageStretch; imageElement.SetBinding( Image.StretchProperty, imageStretchBinding ); DataTemplate template = new DataTemplate(); template.VisualTree = imageElement; CellTemplate = template; } // ImageGridViewColumn // ---------------------------------------------------------------------- protected abstract ImageSource GetImageSource( object value ); // ---------------------------------------------------------------------- object IValueConverter.Convert( object value, Type targetType, object parameter, CultureInfo culture ) { return GetImageSource( value ); } // Convert // ---------------------------------------------------------------------- object IValueConverter.ConvertBack( object value, Type targetType, object parameter, CultureInfo culture ) { throw new NotImplementedException(); } // ConvertBack } // class ImageGridViewColumn } // namespace Itenso.Windows.Controls.ListViewLayout // -- EOF -------------------------------------------------------------------
zzgaminginc-pointofssale
Samba.Presentation.Common/ListViewLM/ImageGridViewColumn.cs
C#
gpl3
2,458
// -- FILE ------------------------------------------------------------------ // name : ProportionalColumn.cs // created : Jani Giannoudis - 2008.03.27 // language : c# // environment: .NET 3.0 // -------------------------------------------------------------------------- using System.Windows; using System.Windows.Controls; namespace Samba.Presentation.Common.ListViewLM { // ------------------------------------------------------------------------ public sealed class ProportionalColumn : LayoutColumn { // ---------------------------------------------------------------------- public static readonly DependencyProperty WidthProperty = DependencyProperty.RegisterAttached( "Width", typeof( double ), typeof( ProportionalColumn ) ); // ---------------------------------------------------------------------- private ProportionalColumn() { } // ProportionalColumn // ---------------------------------------------------------------------- public static double GetWidth( DependencyObject obj ) { return (double)obj.GetValue( WidthProperty ); } // GetWidth // ---------------------------------------------------------------------- public static void SetWidth( DependencyObject obj, double width ) { obj.SetValue( WidthProperty, width ); } // SetWidth // ---------------------------------------------------------------------- public static bool IsProportionalColumn( GridViewColumn column ) { if ( column == null ) { return false; } return HasPropertyValue( column, WidthProperty ); } // IsProportionalColumn // ---------------------------------------------------------------------- public static double? GetProportionalWidth( GridViewColumn column ) { return GetColumnWidth( column, WidthProperty ); } // GetProportionalWidth // ---------------------------------------------------------------------- public static GridViewColumn ApplyWidth( GridViewColumn gridViewColumn, double width ) { SetWidth( gridViewColumn, width ); return gridViewColumn; } // ApplyWidth } // class ProportionalColumn } // namespace Itenso.Windows.Controls.ListViewLayout // -- EOF -------------------------------------------------------------------
zzgaminginc-pointofssale
Samba.Presentation.Common/ListViewLM/ProportionalColumn.cs
C#
gpl3
2,313
// -- FILE ------------------------------------------------------------------ // name : FixedColumn.cs // created : Jani Giannoudis - 2008.03.27 // language : c# // environment: .NET 3.0 // -------------------------------------------------------------------------- using System.Windows; using System.Windows.Controls; namespace Samba.Presentation.Common.ListViewLM { // ------------------------------------------------------------------------ public sealed class FixedColumn : LayoutColumn { // ---------------------------------------------------------------------- public static readonly DependencyProperty WidthProperty = DependencyProperty.RegisterAttached( "Width", typeof( double ), typeof( FixedColumn ) ); // ---------------------------------------------------------------------- private FixedColumn() { } // FixedColumn // ---------------------------------------------------------------------- public static double GetWidth( DependencyObject obj ) { return (double)obj.GetValue( WidthProperty ); } // GetWidth // ---------------------------------------------------------------------- public static void SetWidth( DependencyObject obj, double width ) { obj.SetValue( WidthProperty, width ); } // SetWidth // ---------------------------------------------------------------------- public static bool IsFixedColumn( GridViewColumn column ) { if ( column == null ) { return false; } return HasPropertyValue( column, FixedColumn.WidthProperty ); } // IsFixedColumn // ---------------------------------------------------------------------- public static double? GetFixedWidth( GridViewColumn column ) { return GetColumnWidth( column, FixedColumn.WidthProperty ); } // GetFixedWidth // ---------------------------------------------------------------------- public static GridViewColumn ApplyWidth( GridViewColumn gridViewColumn, double width ) { SetWidth( gridViewColumn, width ); return gridViewColumn; } // ApplyWidth } // class FixedColumn } // namespace Itenso.Windows.Controls.ListViewLayout // -- EOF -------------------------------------------------------------------
zzgaminginc-pointofssale
Samba.Presentation.Common/ListViewLM/FixedColumn.cs
C#
gpl3
2,267
// -- FILE ------------------------------------------------------------------ // name : ConverterGridViewColumn.cs // created : Jani Giannoudis - 2008.03.27 // language : c# // environment: .NET 3.0 // -------------------------------------------------------------------------- using System; using System.Windows.Data; using System.Windows.Controls; using System.Globalization; namespace Samba.Presentation.Common.ListViewLM { // ------------------------------------------------------------------------ public abstract class ConverterGridViewColumn : GridViewColumn, IValueConverter { // ---------------------------------------------------------------------- protected ConverterGridViewColumn( Type bindingType ) { if ( bindingType == null ) { throw new ArgumentNullException( "bindingType" ); } this.bindingType = bindingType; // binding Binding binding = new Binding(); binding.Mode = BindingMode.OneWay; binding.Converter = this; DisplayMemberBinding = binding; } // ConverterGridViewColumn // ---------------------------------------------------------------------- public Type BindingType { get { return this.bindingType; } } // BindingType // ---------------------------------------------------------------------- protected abstract object ConvertValue( object value ); // ---------------------------------------------------------------------- object IValueConverter.Convert( object value, Type targetType, object parameter, CultureInfo culture ) { if ( !bindingType.IsAssignableFrom( value.GetType() ) ) { throw new InvalidOperationException(); } return ConvertValue( value ); } // IValueConverter.Convert // ---------------------------------------------------------------------- object IValueConverter.ConvertBack( object value, Type targetType, object parameter, CultureInfo culture ) { throw new NotImplementedException(); } // IValueConverter.ConvertBack // ---------------------------------------------------------------------- // members private readonly Type bindingType; } // class ConverterGridViewColumn } // namespace Itenso.Windows.Controls.ListViewLayout // -- EOF -------------------------------------------------------------------
zzgaminginc-pointofssale
Samba.Presentation.Common/ListViewLM/ConverterGridViewColumn.cs
C#
gpl3
2,340
// -- FILE ------------------------------------------------------------------ // name : ListViewLayoutManager.cs // created : Jani Giannoudis - 2008.03.27 // language : c# // environment: .NET 3.0 // -------------------------------------------------------------------------- using System; using System.Windows; using System.Windows.Media; using System.Windows.Input; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.ComponentModel; namespace Samba.Presentation.Common.ListViewLM { // ------------------------------------------------------------------------ public class ListViewLayoutManager { // ---------------------------------------------------------------------- public static readonly DependencyProperty EnabledProperty = DependencyProperty.RegisterAttached( "Enabled", typeof( bool ), typeof( ListViewLayoutManager ), new FrameworkPropertyMetadata( new PropertyChangedCallback( OnLayoutManagerEnabledChanged ) ) ); // ---------------------------------------------------------------------- public ListViewLayoutManager( ListView listView ) { if ( listView == null ) { throw new ArgumentNullException( "listView" ); } this.listView = listView; this.listView.Loaded += new RoutedEventHandler( ListViewLoaded ); this.listView.Unloaded += new RoutedEventHandler( ListViewUnloaded ); } // ListViewLayoutManager // ---------------------------------------------------------------------- public ListView ListView { get { return this.listView; } } // ListView // ---------------------------------------------------------------------- public ScrollBarVisibility VerticalScrollBarVisibility { get { return this.verticalScrollBarVisibility; } set { this.verticalScrollBarVisibility = value; } } // VerticalScrollBarVisibility // ---------------------------------------------------------------------- public static void SetEnabled( DependencyObject dependencyObject, bool enabled ) { dependencyObject.SetValue( EnabledProperty, enabled ); } // SetEnabled // ---------------------------------------------------------------------- private void RegisterEvents( DependencyObject start ) { for ( int i = 0; i < VisualTreeHelper.GetChildrenCount( start ); i++ ) { Visual childVisual = VisualTreeHelper.GetChild( start, i ) as Visual; if ( childVisual is Thumb ) { GridViewColumn gridViewColumn = FindParentColumn( childVisual ); if ( gridViewColumn == null ) { continue; } Thumb thumb = childVisual as Thumb; thumb.PreviewMouseMove += new MouseEventHandler( ThumbPreviewMouseMove ); thumb.PreviewMouseLeftButtonDown += new MouseButtonEventHandler( ThumbPreviewMouseLeftButtonDown ); DependencyPropertyDescriptor.FromProperty( GridViewColumn.WidthProperty, typeof( GridViewColumn ) ).AddValueChanged( gridViewColumn, GridColumnWidthChanged ); } else if ( childVisual is GridViewColumnHeader ) { GridViewColumnHeader columnHeader = childVisual as GridViewColumnHeader; columnHeader.SizeChanged += new SizeChangedEventHandler( GridColumnHeaderSizeChanged ); } else if ( this.scrollViewer == null && childVisual is ScrollViewer ) { this.scrollViewer = childVisual as ScrollViewer; this.scrollViewer.ScrollChanged += new ScrollChangedEventHandler( ScrollViewerScrollChanged ); // assume we do the regulation of the horizontal scrollbar this.scrollViewer.HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden; this.scrollViewer.VerticalScrollBarVisibility = this.verticalScrollBarVisibility; } RegisterEvents( childVisual ); // recursive } } // RegisterEvents // ---------------------------------------------------------------------- private void UnregisterEvents( DependencyObject start ) { for ( int i = 0; i < VisualTreeHelper.GetChildrenCount( start ); i++ ) { Visual childVisual = VisualTreeHelper.GetChild( start, i ) as Visual; if ( childVisual is Thumb ) { GridViewColumn gridViewColumn = FindParentColumn( childVisual ); if ( gridViewColumn == null ) { continue; } Thumb thumb = childVisual as Thumb; thumb.PreviewMouseMove -= new MouseEventHandler( ThumbPreviewMouseMove ); thumb.PreviewMouseLeftButtonDown -= new MouseButtonEventHandler( ThumbPreviewMouseLeftButtonDown ); DependencyPropertyDescriptor.FromProperty( GridViewColumn.WidthProperty, typeof( GridViewColumn ) ).RemoveValueChanged( gridViewColumn, GridColumnWidthChanged ); } else if ( childVisual is GridViewColumnHeader ) { GridViewColumnHeader columnHeader = childVisual as GridViewColumnHeader; columnHeader.SizeChanged -= new SizeChangedEventHandler( GridColumnHeaderSizeChanged ); } else if ( this.scrollViewer == null && childVisual is ScrollViewer ) { this.scrollViewer = childVisual as ScrollViewer; this.scrollViewer.ScrollChanged -= new ScrollChangedEventHandler( ScrollViewerScrollChanged ); } UnregisterEvents( childVisual ); // recursive } } // UnregisterEvents // ---------------------------------------------------------------------- private GridViewColumn FindParentColumn( DependencyObject element ) { if ( element == null ) { return null; } while ( element != null ) { if ( element is GridViewColumnHeader ) { return ( (GridViewColumnHeader)element ).Column; } element = VisualTreeHelper.GetParent( element ); } return null; } // FindParentColumn // ---------------------------------------------------------------------- private GridViewColumnHeader FindColumnHeader( DependencyObject start, GridViewColumn gridViewColumn ) { for ( int i = 0; i < VisualTreeHelper.GetChildrenCount( start ); i++ ) { Visual childVisual = VisualTreeHelper.GetChild( start, i ) as Visual; if ( childVisual is GridViewColumnHeader ) { GridViewColumnHeader gridViewHeader = childVisual as GridViewColumnHeader; if ( gridViewHeader != null && gridViewHeader.Column == gridViewColumn ) { return gridViewHeader; } } GridViewColumnHeader childGridViewHeader = FindColumnHeader( childVisual, gridViewColumn ); // recursive if ( childGridViewHeader != null ) { return childGridViewHeader; } } return null; } // FindColumnHeader // ---------------------------------------------------------------------- private void InitColumns() { GridView view = this.listView.View as GridView; if ( view == null ) { return; } foreach ( GridViewColumn gridViewColumn in view.Columns ) { if ( !RangeColumn.IsRangeColumn( gridViewColumn ) ) { continue; } double? minWidth = RangeColumn.GetRangeMinWidth( gridViewColumn ); double? maxWidth = RangeColumn.GetRangeMaxWidth( gridViewColumn ); if ( !minWidth.HasValue && !maxWidth.HasValue ) { continue; } GridViewColumnHeader columnHeader = FindColumnHeader( this.listView, gridViewColumn ); if ( columnHeader == null ) { continue; } double actualWidth = columnHeader.ActualWidth; if ( minWidth.HasValue ) { columnHeader.MinWidth = minWidth.Value; if ( !double.IsInfinity( actualWidth ) && actualWidth < columnHeader.MinWidth ) { gridViewColumn.Width = columnHeader.MinWidth; } } if ( maxWidth.HasValue ) { columnHeader.MaxWidth = maxWidth.Value; if ( !double.IsInfinity( actualWidth ) && actualWidth > columnHeader.MaxWidth ) { gridViewColumn.Width = columnHeader.MaxWidth; } } } } // InitColumns // ---------------------------------------------------------------------- protected virtual void ResizeColumns() { GridView view = this.listView.View as GridView; if ( view == null || view.Columns.Count == 0 ) { return; } // listview width double actualWidth = double.PositiveInfinity; if ( this.scrollViewer != null ) { actualWidth = this.scrollViewer.ViewportWidth; } if ( double.IsInfinity( actualWidth ) ) { actualWidth = this.listView.ActualWidth; } if ( double.IsInfinity( actualWidth ) || actualWidth <= 0 ) { return; } double resizeableRegionCount = 0; double otherColumnsWidth = 0; // determine column sizes foreach ( GridViewColumn gridViewColumn in view.Columns ) { if ( ProportionalColumn.IsProportionalColumn( gridViewColumn ) ) { resizeableRegionCount += ProportionalColumn.GetProportionalWidth( gridViewColumn ).Value; } else { otherColumnsWidth += gridViewColumn.ActualWidth; } } if ( resizeableRegionCount <= 0 ) { // no proportional columns present: commit the regulation to the scroll viewer this.scrollViewer.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto; // search the first fill column GridViewColumn fillColumn = null; for ( int i = 0; i < view.Columns.Count; i++ ) { GridViewColumn gridViewColumn = view.Columns[ i ]; if ( IsFillColumn( gridViewColumn ) ) { fillColumn = gridViewColumn; break; } } if ( fillColumn != null ) { double otherColumnsWithoutFillWidth = otherColumnsWidth - fillColumn.ActualWidth; double fillWidth = actualWidth - otherColumnsWithoutFillWidth; if ( fillWidth > 0 ) { double? minWidth = RangeColumn.GetRangeMinWidth( fillColumn ); double? maxWidth = RangeColumn.GetRangeMaxWidth( fillColumn ); bool setWidth = true; if ( minWidth.HasValue && fillWidth < minWidth.Value ) { setWidth = false; } if ( maxWidth.HasValue && fillWidth > maxWidth.Value ) { setWidth = false; } if ( setWidth ) { this.scrollViewer.HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden; fillColumn.Width = fillWidth; } } } return; } double resizeableColumnsWidth = actualWidth - otherColumnsWidth; if ( resizeableColumnsWidth <= 0 ) { return; // missing space } // resize columns double resizeableRegionWidth = resizeableColumnsWidth / resizeableRegionCount; foreach ( GridViewColumn gridViewColumn in view.Columns ) { if ( ProportionalColumn.IsProportionalColumn( gridViewColumn ) ) { gridViewColumn.Width = ProportionalColumn.GetProportionalWidth( gridViewColumn ).Value * resizeableRegionWidth; } } } // ResizeColumns // ---------------------------------------------------------------------- // returns the delta private double SetRangeColumnToBounds( GridViewColumn gridViewColumn ) { double startWidth = gridViewColumn.Width; double? minWidth = RangeColumn.GetRangeMinWidth( gridViewColumn ); double? maxWidth = RangeColumn.GetRangeMaxWidth( gridViewColumn ); if ( ( minWidth.HasValue && maxWidth.HasValue ) && ( minWidth > maxWidth ) ) { return 0; // invalid case } if ( minWidth.HasValue && gridViewColumn.Width < minWidth.Value ) { gridViewColumn.Width = minWidth.Value; } else if ( maxWidth.HasValue && gridViewColumn.Width > maxWidth.Value ) { gridViewColumn.Width = maxWidth.Value; } return gridViewColumn.Width - startWidth; } // SetRangeColumnToBounds // ---------------------------------------------------------------------- private bool IsFillColumn( GridViewColumn gridViewColumn ) { if ( gridViewColumn == null ) { return false; } GridView view = this.listView.View as GridView; if ( view == null || view.Columns.Count == 0 ) { return false; } bool? isFillCoumn = RangeColumn.GetRangeIsFillColumn( gridViewColumn ); return isFillCoumn.HasValue && isFillCoumn.Value == true; } // IsFillColumn // ---------------------------------------------------------------------- private void DoResizeColumns() { if ( this.resizing ) { return; } this.resizing = true; try { ResizeColumns(); } catch { throw; } finally { this.resizing = false; } } // DoResizeColumns // ---------------------------------------------------------------------- private void ListViewLoaded( object sender, RoutedEventArgs e ) { RegisterEvents( this.listView ); InitColumns(); DoResizeColumns(); this.loaded = true; } // ListViewLoaded // ---------------------------------------------------------------------- private void ListViewUnloaded( object sender, RoutedEventArgs e ) { if ( !this.loaded ) { return; } UnregisterEvents( this.listView ); this.loaded = false; } // ListViewUnloaded // ---------------------------------------------------------------------- private void ThumbPreviewMouseMove( object sender, MouseEventArgs e ) { Thumb thumb = sender as Thumb; GridViewColumn gridViewColumn = FindParentColumn( thumb ); if ( gridViewColumn == null ) { return; } // suppress column resizing for proportional, fixed and range fill columns if ( ProportionalColumn.IsProportionalColumn( gridViewColumn ) || FixedColumn.IsFixedColumn( gridViewColumn ) || IsFillColumn( gridViewColumn ) ) { thumb.Cursor = null; return; } // check range column bounds if ( thumb.IsMouseCaptured && RangeColumn.IsRangeColumn( gridViewColumn ) ) { double? minWidth = RangeColumn.GetRangeMinWidth( gridViewColumn ); double? maxWidth = RangeColumn.GetRangeMaxWidth( gridViewColumn ); if ( ( minWidth.HasValue && maxWidth.HasValue ) && ( minWidth > maxWidth ) ) { return; // invalid case } if ( this.resizeCursor == null ) { this.resizeCursor = thumb.Cursor; // save the resize cursor } if ( minWidth.HasValue && gridViewColumn.Width <= minWidth.Value ) { thumb.Cursor = Cursors.No; } else if ( maxWidth.HasValue && gridViewColumn.Width >= maxWidth.Value ) { thumb.Cursor = Cursors.No; } else { thumb.Cursor = this.resizeCursor; // between valid min/max } } } // ThumbPreviewMouseMove // ---------------------------------------------------------------------- private void ThumbPreviewMouseLeftButtonDown( object sender, MouseButtonEventArgs e ) { Thumb thumb = sender as Thumb; GridViewColumn gridViewColumn = FindParentColumn( thumb ); // suppress column resizing for proportional, fixed and range fill columns if ( ProportionalColumn.IsProportionalColumn( gridViewColumn ) || FixedColumn.IsFixedColumn( gridViewColumn ) || IsFillColumn( gridViewColumn ) ) { e.Handled = true; return; } } // ThumbPreviewMouseLeftButtonDown // ---------------------------------------------------------------------- private void GridColumnWidthChanged( object sender, EventArgs e ) { if ( !this.loaded ) { return; } GridViewColumn gridViewColumn = sender as GridViewColumn; // suppress column resizing for proportional and fixed columns if ( ProportionalColumn.IsProportionalColumn( gridViewColumn ) || FixedColumn.IsFixedColumn( gridViewColumn ) ) { return; } // ensure range column within the bounds if ( RangeColumn.IsRangeColumn( gridViewColumn ) ) { // special case: auto column width - maybe conflicts with min/max range if ( gridViewColumn.Width.Equals( double.NaN ) ) { this.autoSizedColumn = gridViewColumn; return; // handled by the change header size event } // ensure column bounds if ( SetRangeColumnToBounds( gridViewColumn ) != 0 ) { return; } } DoResizeColumns(); } // GridColumnWidthChanged // ---------------------------------------------------------------------- // handle autosized column private void GridColumnHeaderSizeChanged( object sender, SizeChangedEventArgs e ) { if ( this.autoSizedColumn == null ) { return; } GridViewColumnHeader gridViewColumnHeader = sender as GridViewColumnHeader; if ( gridViewColumnHeader.Column == this.autoSizedColumn ) { if ( gridViewColumnHeader.Width.Equals( double.NaN ) ) { // sync column with gridViewColumnHeader.Column.Width = gridViewColumnHeader.ActualWidth; DoResizeColumns(); } this.autoSizedColumn = null; } } // GridColumnHeaderSizeChanged // ---------------------------------------------------------------------- private void ScrollViewerScrollChanged( object sender, ScrollChangedEventArgs e ) { if ( this.loaded && e.ViewportWidthChange != 0 ) { DoResizeColumns(); } } // ScrollViewerScrollChanged // ---------------------------------------------------------------------- private static void OnLayoutManagerEnabledChanged( DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e ) { ListView listView = dependencyObject as ListView; if ( listView != null ) { bool enabled = (bool)e.NewValue; if ( enabled ) { new ListViewLayoutManager( listView ); } } } // OnLayoutManagerEnabledChanged // ---------------------------------------------------------------------- // members private readonly ListView listView; private ScrollViewer scrollViewer; private bool loaded = false; private bool resizing = false; private Cursor resizeCursor; private ScrollBarVisibility verticalScrollBarVisibility = ScrollBarVisibility.Auto; private GridViewColumn autoSizedColumn; } // class ListViewLayoutManager } // namespace Itenso.Windows.Controls.ListViewLayout // -- EOF -------------------------------------------------------------------
zzgaminginc-pointofssale
Samba.Presentation.Common/ListViewLM/ListViewLayoutManager.cs
C#
gpl3
18,300
// -- FILE ------------------------------------------------------------------ // name : LayoutColumn.cs // created : Jani Giannoudis - 2008.03.27 // language : c# // environment: .NET 3.0 // -------------------------------------------------------------------------- using System; using System.Windows; using System.Windows.Controls; namespace Samba.Presentation.Common.ListViewLM { // ------------------------------------------------------------------------ public abstract class LayoutColumn { // ---------------------------------------------------------------------- protected static bool HasPropertyValue( GridViewColumn column, DependencyProperty dp ) { if ( column == null ) { throw new ArgumentNullException( "column" ); } object value = column.ReadLocalValue( dp ); if ( value != null && value.GetType() == dp.PropertyType ) { return true; } return false; } // HasPropertyValue // ---------------------------------------------------------------------- protected static double? GetColumnWidth( GridViewColumn column, DependencyProperty dp ) { if ( column == null ) { throw new ArgumentNullException( "column" ); } object value = column.ReadLocalValue( dp ); if ( value != null && value.GetType() == dp.PropertyType ) { return (double)value; } return null; } // GetColumnWidth } // class LayoutColumn } // namespace Itenso.Windows.Controls.ListViewLayout // -- EOF -------------------------------------------------------------------
zzgaminginc-pointofssale
Samba.Presentation.Common/ListViewLM/LayoutColumn.cs
C#
gpl3
1,594
using System; namespace Samba.Presentation.Common { public static class RuleEventNames { public const string TicketLineCancelled = "TicketLineCancelled"; public const string ModifierSelected = "ModifierSelected"; public const string PortionSelected = "PortionSelected"; public const string ApplicationStarted = "ApplicationStarted"; public const string TicketClosed = "TicketClosed"; public const string ChangeAmountChanged = "ChangeAmountChanged"; public const string TicketLineAdded = "TicketLineAdded"; public const string PaymentReceived = "PaymentReceived"; public const string TicketLocationChanged = "TicketLocationChanged"; public const string TriggerExecuted = "TriggerExecuted"; public const string TicketTotalChanged = "TicketTotalChanged"; public const string TicketTagSelected = "TicketTagSelected"; public const string CustomerSelectedForTicket = "CustomerSelectedForTicket"; public const string TicketCreated = "TicketCreated"; public const string WorkPeriodStarts = "WorkPeriodStarts"; public const string WorkPeriodEnds = "WorkPeriodEnds"; public const string UserLoggedOut = "UserLoggedOut"; public const string UserLoggedIn = "UserLoggedIn"; public const string MessageReceived = "MessageReceived"; } public static class EventTopicNames { public const string PaymentProcessed = "Payment Processed"; public const string FocusTicketScreen = "FocusTicketScreen"; public const string AddLiabilityAmount = "Add Liability Amount"; public const string AddReceivableAmount = "Add Receivable Amount"; public const string LocationSelectedForTicket = "LocationSelectedForTicket"; public const string ExecuteEvent = "ExecuteEvent"; public const string UpdateDepartment = "Update Department"; public const string PopupClicked = "Popup Clicked"; public const string DisplayTicketExplorer = "Display Ticket Explorer"; public const string TagSelectedForSelectedTicket = "Tag Selected"; public const string SelectTicketTag = "Select Ticket Tag"; public const string LogData = "Log Data"; public const string ResetNumerator = "Reset Numerator"; public const string WorkPeriodStatusChanged = "WorkPeriod Status Changed"; public const string BrowseUrl = "Browse Url"; public const string ActivateCustomerAccount = "Activate Customer Account"; public const string ActivateCustomerView = "Activate Customer View"; public const string SelectExtraProperty = "Select Extra Property"; public const string SelectVoidReason = "Select Void Reason"; public const string SelectGiftReason = "Select Gift Reason"; public const string ActivateNavigation = "Activate Navigation"; public const string CustomerSelectedForTicket = "Customer Selected For Ticket"; public const string SelectCustomer = "Select Customer"; public const string NavigationCommandAdded = "Navigation Command Added"; public const string DashboardCommandAdded = "Dashboard Command Added"; public const string SelectedTicketChanged = "Selected Ticket Changed"; public const string TicketItemAdded = "Ticket Item Added"; public const string DashboardClosed = "Dashboard Closed"; public const string MessageReceivedEvent = "Message Received"; public const string ViewAdded = "View Added"; public const string ViewClosed = "View Closed"; public const string PinSubmitted = "Pin Submitted"; public const string UserLoggedIn = "User LoggedIn"; public const string UserLoggedOut = "User LoggedOut"; public const string AddedModelSaved = "ModelSaved"; public const string ModelAddedOrDeleted = "Model Added or Deleted"; public const string MakePayment = "Make Payment"; public const string PaymentSubmitted = "Payment Submitted"; public const string SelectedItemsChanged = "Selected Items Changed"; public const string SelectedDepartmentChanged = "Selected Department Changed"; public const string SelectTable = "Select Table"; public const string FindTable = "Find Table"; public const string ActivateTicketView = "Activate Ticket View"; public const string DisplayTicketView = "Display Ticket View"; public const string RefreshSelectedTicket = "Refresh Selected Ticket"; public const string EditTicketNote = "Edit Ticket Note"; public const string PaymentRequestedForTicket = "Payment Requested For Ticket"; public const string GetPaymentFromCustomer = "Get Payment From Customer"; public const string MakePaymentToCustomer = "Make Payment To Customer"; } }
zzgaminginc-pointofssale
Samba.Presentation.Common/EventTopicNames.cs
C#
gpl3
4,960
using System.Collections.Generic; using Samba.Infrastructure.Data; namespace Samba.Presentation.Common { public interface IUserInteraction { string[] GetStringFromUser(string caption, string description); string[] GetStringFromUser(string caption, string description, string defaultValue); IList<IOrderable> ChooseValuesFrom( IList<IOrderable> values, IList<IOrderable> selectedValues, string caption, string description, string singularName, string pluralName); void EditProperties(object item); void EditProperties<T>(IList<T> item); void SortItems(IEnumerable<IOrderable> list, string caption, string description); bool AskQuestion(string question); void GiveFeedback(string message); void ShowKeyboard(); void HideKeyboard(); void ToggleKeyboard(); void ToggleSplashScreen(); void DisplayPopup(string title, string content, object dataObject, string eventMessage, string headerColor = "DarkRed"); void BlurMainWindow(); void DeblurMainWindow(); } }
zzgaminginc-pointofssale
Samba.Presentation.Common/IUserInteraction.cs
C#
gpl3
1,193
using System; using System.Windows.Input; using Microsoft.Practices.Prism.Commands; namespace Samba.Presentation.Common { public class CaptionCommand<T> : DelegateCommand<T>, ICaptionCommand { public CaptionCommand(string caption, Action<T> executeMethod) : base(executeMethod) { Caption = caption; } public CaptionCommand(string caption, Action<T> executeMethod, Func<T, bool> canExecuteMethod) : base(executeMethod, canExecuteMethod) { Caption = caption; } public string Caption { get; set; } public new event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/CaptionCommand.cs
C#
gpl3
854
using System; using Samba.Infrastructure; namespace Samba.Presentation.Common { public class MessageListener : IMessageListener { public MessageListener() { _key = Guid.NewGuid().ToString("D"); } private readonly string _key; public string Key { get { return _key; } } public void ProcessMessage(string message) { if (!message.Contains(Key)) MessageProcessor.ProcessMessage(message); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/MessageListener.cs
C#
gpl3
565
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Threading; namespace Samba.Presentation.Common { public class KineticBehaviour { #region Friction /// <summary> /// Friction Attached Dependency Property /// </summary> public static readonly DependencyProperty FrictionProperty = DependencyProperty.RegisterAttached("Friction", typeof(double), typeof(KineticBehaviour), new FrameworkPropertyMetadata((double)0.90)); /// <summary> /// Gets the Friction property. This dependency property /// indicates .... /// </summary> public static double GetFriction(DependencyObject d) { return (double)d.GetValue(FrictionProperty); } /// <summary> /// Sets the Friction property. This dependency property /// indicates .... /// </summary> public static void SetFriction(DependencyObject d, double value) { d.SetValue(FrictionProperty, value); } #endregion #region ScrollStartPoint /// <summary> /// ScrollStartPoint Attached Dependency Property /// </summary> private static readonly DependencyProperty ScrollStartPointProperty = DependencyProperty.RegisterAttached("ScrollStartPoint", typeof(Point), typeof(KineticBehaviour), new FrameworkPropertyMetadata((Point)new Point())); /// <summary> /// Gets the ScrollStartPoint property. This dependency property /// indicates .... /// </summary> private static Point GetScrollStartPoint(DependencyObject d) { return (Point)d.GetValue(ScrollStartPointProperty); } /// <summary> /// Sets the ScrollStartPoint property. This dependency property /// indicates .... /// </summary> private static void SetScrollStartPoint(DependencyObject d, Point value) { d.SetValue(ScrollStartPointProperty, value); } #endregion #region ScrollStartOffset /// <summary> /// ScrollStartOffset Attached Dependency Property /// </summary> private static readonly DependencyProperty ScrollStartOffsetProperty = DependencyProperty.RegisterAttached("ScrollStartOffset", typeof(Point), typeof(KineticBehaviour), new FrameworkPropertyMetadata((Point)new Point())); /// <summary> /// Gets the ScrollStartOffset property. This dependency property /// indicates .... /// </summary> private static Point GetScrollStartOffset(DependencyObject d) { return (Point)d.GetValue(ScrollStartOffsetProperty); } /// <summary> /// Sets the ScrollStartOffset property. This dependency property /// indicates .... /// </summary> private static void SetScrollStartOffset(DependencyObject d, Point value) { d.SetValue(ScrollStartOffsetProperty, value); } #endregion #region InertiaProcessor /// <summary> /// InertiaProcessor Attached Dependency Property /// </summary> private static readonly DependencyProperty InertiaProcessorProperty = DependencyProperty.RegisterAttached("InertiaProcessor", typeof(InertiaHandler), typeof(KineticBehaviour), new FrameworkPropertyMetadata((InertiaHandler)null)); /// <summary> /// Gets the InertiaProcessor property. This dependency property /// indicates .... /// </summary> private static InertiaHandler GetInertiaProcessor(DependencyObject d) { return (InertiaHandler)d.GetValue(InertiaProcessorProperty); } /// <summary> /// Sets the InertiaProcessor property. This dependency property /// indicates .... /// </summary> private static void SetInertiaProcessor(DependencyObject d, InertiaHandler value) { d.SetValue(InertiaProcessorProperty, value); } #endregion #region HandleKineticScrolling /// <summary> /// HandleKineticScrolling Attached Dependency Property /// </summary> public static readonly DependencyProperty HandleKineticScrollingProperty = DependencyProperty.RegisterAttached("HandleKineticScrolling", typeof(bool), typeof(KineticBehaviour), new FrameworkPropertyMetadata((bool)false, new PropertyChangedCallback(OnHandleKineticScrollingChanged))); /// <summary> /// Gets the HandleKineticScrolling property. This dependency property /// indicates .... /// </summary> public static bool GetHandleKineticScrolling(DependencyObject d) { return (bool)d.GetValue(HandleKineticScrollingProperty); } /// <summary> /// Sets the HandleKineticScrolling property. This dependency property /// indicates .... /// </summary> public static void SetHandleKineticScrolling(DependencyObject d, bool value) { d.SetValue(HandleKineticScrollingProperty, value); } /// <summary> /// Handles changes to the HandleKineticScrolling property. /// </summary> private static void OnHandleKineticScrollingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { AttachScrollViewer(d, (bool)e.NewValue); } private static void AttachScrollViewer(DependencyObject d, bool newValue) { var scoller = d as ScrollViewer; if (scoller != null) { if (newValue) { scoller.PreviewMouseLeftButtonDown += ScollerPreviewMouseLeftButtonDown; scoller.PreviewMouseLeftButtonUp += ScollerPreviewMouseLeftButtonUp; scoller.PreviewMouseMove += ScollerPreviewMouseMove; SetInertiaProcessor(scoller, new InertiaHandler(scoller)); } else { scoller.PreviewMouseLeftButtonDown -= ScollerPreviewMouseLeftButtonDown; scoller.PreviewMouseLeftButtonUp -= ScollerPreviewMouseLeftButtonUp; scoller.PreviewMouseMove -= ScollerPreviewMouseMove; var inertia = GetInertiaProcessor(scoller); if (inertia != null) inertia.Dispose(); } } else { var sbar = ExtensionServices.GetVisualChild<ScrollViewer>(d); if (sbar != null) AttachScrollViewer(sbar, newValue); else { var visual = d as FrameworkElement; if (visual != null) visual.Loaded += VisualLoaded; } } } static void VisualLoaded(object sender, RoutedEventArgs e) { var fe = sender as FrameworkElement; if (fe != null) { var v = ExtensionServices.GetVisualChild<ScrollViewer>(fe); if (v != null) { AttachScrollViewer(v, true); fe.Loaded -= VisualLoaded; } } } #endregion #region Mouse Events private static bool InRage(double val) { if (val < -5 && val > -20) return true; if (val > 5 && val < 20) return true; return false; } private static bool _previewCapture; private static bool _scrollBarClicked; static void ScollerPreviewMouseMove(object sender, MouseEventArgs e) { var scrollViewer = (ScrollViewer)sender; if (_previewCapture && (scrollViewer.ScrollableHeight > 0 || scrollViewer.ScrollableWidth > 0)) { var currentPoint = e.GetPosition(scrollViewer); if (currentPoint.X > scrollViewer.ViewportWidth) _scrollBarClicked = true; var scrollStartPoint = GetScrollStartPoint(scrollViewer); var delta = new Point(scrollStartPoint.X - currentPoint.X, scrollStartPoint.Y - currentPoint.Y); if (!_scrollBarClicked && (InRage(delta.X) || InRage(delta.Y))) { _previewCapture = false; scrollViewer.CaptureMouse(); } } if (scrollViewer.IsMouseCaptured) { var currentPoint = e.GetPosition(scrollViewer); var scrollStartPoint = GetScrollStartPoint(scrollViewer); // Determine the new amount to scroll. var delta = new Point(scrollStartPoint.X - currentPoint.X, scrollStartPoint.Y - currentPoint.Y); var scrollStartOffset = GetScrollStartOffset(scrollViewer); var scrollTarget = new Point(scrollStartOffset.X + delta.X, scrollStartOffset.Y + delta.Y); var inertiaProcessor = GetInertiaProcessor(scrollViewer); if (inertiaProcessor != null) inertiaProcessor.ScrollTarget = scrollTarget; // Scroll to the new position. scrollViewer.ScrollToHorizontalOffset(scrollTarget.X); scrollViewer.ScrollToVerticalOffset(scrollTarget.Y); } } static void ScollerPreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e) { _previewCapture = false; _scrollBarClicked = false; var scrollViewer = (ScrollViewer)sender; if (scrollViewer.IsMouseCaptured) { scrollViewer.ReleaseMouseCapture(); } } static void ScollerPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { var scrollViewer = (ScrollViewer)sender; if (scrollViewer.IsMouseOver) { // Save starting point, used later when determining how much to scroll. _previewCapture = true; SetScrollStartPoint(scrollViewer, e.GetPosition(scrollViewer)); SetScrollStartOffset(scrollViewer, new Point(scrollViewer.HorizontalOffset, scrollViewer.VerticalOffset)); //scrollViewer.CaptureMouse(); } } #endregion #region Inertia Stuff /// <summary> /// Handles the inertia /// </summary> class InertiaHandler : IDisposable { private Point _previousPoint; private Vector _velocity; readonly ScrollViewer _scroller; readonly DispatcherTimer _animationTimer; private Point _scrollTarget; public Point ScrollTarget { get { return _scrollTarget; } set { _scrollTarget = value; } } public InertiaHandler(ScrollViewer scroller) { this._scroller = scroller; _animationTimer = new DispatcherTimer(); _animationTimer.Interval = new TimeSpan(0, 0, 0, 0, 20); _animationTimer.Tick += HandleWorldTimerTick; _animationTimer.Start(); } private void HandleWorldTimerTick(object sender, EventArgs e) { if (_scroller.IsMouseCaptured) { Point currentPoint = Mouse.GetPosition(_scroller); _velocity = _previousPoint - currentPoint; _previousPoint = currentPoint; } else { if (_velocity.Length > 1) { _scroller.ScrollToHorizontalOffset(ScrollTarget.X); _scroller.ScrollToVerticalOffset(ScrollTarget.Y); _scrollTarget.X += _velocity.X; _scrollTarget.Y += _velocity.Y; _velocity *= KineticBehaviour.GetFriction(_scroller); } } } #region IDisposable Members public void Dispose() { _animationTimer.Stop(); } #endregion } #endregion } }
zzgaminginc-pointofssale
Samba.Presentation.Common/KineticBehaviour.cs
C#
gpl3
13,191
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using Samba.Presentation.Common.Browser; namespace Samba.Presentation.Common { public class DiagramCanvas : InkCanvas { //Just a simple INotifyCollectionChanged collection public ObservableCollection<IDiagram> Source { get { return (ObservableCollection<IDiagram>)GetValue(SourceProperty); } set { SetValue(SourceProperty, value); } } public static readonly DependencyProperty SourceProperty = DependencyProperty.Register("Source", typeof(ObservableCollection<IDiagram>), typeof(DiagramCanvas), new FrameworkPropertyMetadata(new ObservableCollection<IDiagram>(), new PropertyChangedCallback(SourceChanged))); //called when a new value is set (through binding for example) protected static void SourceChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) { //gets the instance that changed the "local" value var instance = sender as DiagramCanvas; //the new collection that will be set var newCollection = args.NewValue as ObservableCollection<IDiagram>; //the previous collection that was set var oldCollection = args.OldValue as ObservableCollection<IDiagram>; if (oldCollection != null) { //removes the CollectionChangedEventHandler from the old collection oldCollection.CollectionChanged -= instance.collection_CollectionChanged; } //clears all the previous children in the collection instance.Children.Clear(); if (newCollection != null) { //adds all the children of the new collection foreach (IDiagram item in newCollection) { AddControl(item, instance); } //adds a new CollectionChangedEventHandler to the new collection newCollection.CollectionChanged += instance.collection_CollectionChanged; } } //append when an Item in the collection is changed protected void collection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { //adds the new items in the children collection foreach (IDiagram item in e.NewItems) { AddControl(item); } } public static ContextMenu ButtonContextMenu { get; set; } protected static void AddControl(IDiagram buttonHolder, InkCanvas parentControl) { if (!string.IsNullOrEmpty(buttonHolder.HtmlContent)) CreateHtmlViewer(buttonHolder, parentControl); else CreateButton(buttonHolder, parentControl); } private static readonly IDictionary<string, BrowserControl> BrowserCache = new Dictionary<string, BrowserControl>(); private static void CreateHtmlViewer(IDiagram buttonHolder, InkCanvas parentControl) { if (!BrowserCache.ContainsKey(buttonHolder.Caption + buttonHolder.HtmlContent)) { var brws = new BrowserControl { DataContext = buttonHolder, ContextMenu = ButtonContextMenu, MinHeight = 10, MinWidth = 10 }; BrowserCache.Add(buttonHolder.Caption + buttonHolder.HtmlContent, brws); } var ret = BrowserCache[buttonHolder.Caption + buttonHolder.HtmlContent]; ret.DataContext = buttonHolder; ret.ContextMenu = ButtonContextMenu; ret.IsToolbarVisible = false; parentControl.Children.Add(ret); ret.AutoRefresh = buttonHolder.AutoRefresh; BindingOperations.ClearAllBindings(ret); var heightBinding = new Binding("Height") { Source = buttonHolder, Mode = BindingMode.TwoWay }; var widthBinding = new Binding("Width") { Source = buttonHolder, Mode = BindingMode.TwoWay }; var xBinding = new Binding("X") { Source = buttonHolder, Mode = BindingMode.TwoWay }; var yBinding = new Binding("Y") { Source = buttonHolder, Mode = BindingMode.TwoWay }; var enabledBinding = new Binding("IsEnabled") { Source = buttonHolder, Mode = BindingMode.OneWay }; var transformBinding = new Binding("RenderTransform") { Source = buttonHolder, Mode = BindingMode.OneWay }; var urlBinding = new Binding("HtmlContent") { Source = buttonHolder, Mode = BindingMode.OneWay }; var detailsVisibilityBinding = new Binding("IsDetailsVisible") { Source = buttonHolder, Mode = BindingMode.TwoWay }; ret.SetBinding(LeftProperty, xBinding); ret.SetBinding(TopProperty, yBinding); ret.SetBinding(HeightProperty, heightBinding); ret.SetBinding(WidthProperty, widthBinding); ret.SetBinding(RenderTransformProperty, transformBinding); ret.SetBinding(IsEnabledProperty, enabledBinding); ret.SetBinding(BrowserControl.IsToolbarVisibleProperty, detailsVisibilityBinding); ret.SetBinding(BrowserControl.ActiveUrlProperty, urlBinding); } private static void CreateButton(IDiagram buttonHolder, InkCanvas parentControl) { var ret = new FlexButton.FlexButton { DataContext = buttonHolder, ContextMenu = ButtonContextMenu }; ret.CommandParameter = buttonHolder; parentControl.Children.Add(ret); var heightBinding = new Binding("Height") { Source = buttonHolder, Mode = BindingMode.TwoWay }; var widthBinding = new Binding("Width") { Source = buttonHolder, Mode = BindingMode.TwoWay }; var xBinding = new Binding("X") { Source = buttonHolder, Mode = BindingMode.TwoWay }; var yBinding = new Binding("Y") { Source = buttonHolder, Mode = BindingMode.TwoWay }; var captionBinding = new Binding("Caption") { Source = buttonHolder, Mode = BindingMode.TwoWay }; var radiusBinding = new Binding("CornerRadius") { Source = buttonHolder, Mode = BindingMode.TwoWay }; var buttonColorBinding = new Binding("ButtonColor") { Source = buttonHolder, Mode = BindingMode.TwoWay }; var commandBinding = new Binding("Command") { Source = buttonHolder, Mode = BindingMode.OneWay }; var enabledBinding = new Binding("IsEnabled") { Source = buttonHolder, Mode = BindingMode.OneWay }; var transformBinding = new Binding("RenderTransform") { Source = buttonHolder, Mode = BindingMode.OneWay }; ret.SetBinding(LeftProperty, xBinding); ret.SetBinding(TopProperty, yBinding); ret.SetBinding(HeightProperty, heightBinding); ret.SetBinding(WidthProperty, widthBinding); ret.SetBinding(ContentControl.ContentProperty, captionBinding); ret.SetBinding(FlexButton.FlexButton.CornerRadiusProperty, radiusBinding); ret.SetBinding(FlexButton.FlexButton.ButtonColorProperty, buttonColorBinding); ret.SetBinding(ButtonBase.CommandProperty, commandBinding); ret.SetBinding(RenderTransformProperty, transformBinding); ret.SetBinding(IsEnabledProperty, enabledBinding); } protected void AddControl(IDiagram buttonHolder) { AddControl(buttonHolder, this); } static DiagramCanvas() { DefaultStyleKeyProperty.OverrideMetadata(typeof(DiagramCanvas), new FrameworkPropertyMetadata(typeof(DiagramCanvas))); ButtonContextMenu = new ContextMenu(); var menuItem = new MenuItem { Header = "Özellikler" }; menuItem.Click += MenuItemClick; ButtonContextMenu.Items.Add(menuItem); } static void MenuItemClick(object sender, RoutedEventArgs e) { ((IDiagram)((Control)((ContextMenu)((MenuItem)sender).Parent).PlacementTarget).DataContext). EditProperties(); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/DiagramCanvas.cs
C#
gpl3
8,681
using System; using System.Drawing; using System.Runtime.InteropServices; namespace Samba.Presentation.Common { public struct KEYBDINPUT { public ushort wVk; public ushort wScan; public uint dwFlags; public long time; public uint dwExtraInfo; }; [StructLayout(LayoutKind.Explicit, Size = 28)] public struct INPUT { [FieldOffset(0)] public uint type; [FieldOffset(4)] public KEYBDINPUT ki; }; [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct InputKeys { public uint type; public uint wVk; public uint wScan; public uint dwFlags; public uint time; public uint dwExtra; } public class NativeWin32 { // public const ushort KEYEVENTF_KEYUP = 0x0002; public const uint INPUT_KEYBOARD = 1; public const uint KEYEVENTF_EXTENDEDKEY = 0x0001; public const uint KEYEVENTF_KEYUP = 0x0002; [DllImport("user32.dll")] public static extern Boolean Keybd_Event(int dwKey, byte bScan, Int32 dwFlags, Int32 dwExtraInfo); [DllImport("user32.dll")] public static extern uint SendInput(uint nInputs, ref INPUT pInputs, int cbSize); [DllImport("User32.DLL", EntryPoint = "SendInput")] public static extern uint SendInput(uint nInputs, InputKeys[] inputs, int cbSize); [DllImport("user32.dll")] public static extern int SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong); [DllImport("user32.dll", SetLastError = true)] public static extern UInt32 GetWindowLong(IntPtr hWnd, int nIndex); } ///<summary> /// Encapsulates the native methods ///</summary> public static class UnsafeNativeMethods { #region Nested type: RECT ///<summary> /// A rectangular windows structure ///</summary> [Serializable, StructLayout(LayoutKind.Sequential)] public struct RECT { ///<summary> /// The horizontal position of the left edge ///</summary> public int Left; ///<summary> /// The vertical position of the top edge ///</summary> public int Top; /// <summary> /// The horizontal position of the right edge /// </summary> public int Right; ///<summary> /// The vertical position of the bottom edge ///</summary> public int Bottom; ///<summary> /// Default constructor ///</summary> ///<param name="left"></param> ///<param name="top"></param> ///<param name="right"></param> ///<param name="bottom"></param> public RECT(int left, int top, int right, int bottom) { Left = left; Top = top; Right = right; Bottom = bottom; } ///<summary> /// The height of the rectangle ///</summary> public int Height { get { return Bottom - Top; } } ///<summary> /// The Width of the rectangle ///</summary> public int Width { get { return Right - Left; } } ///<summary> /// Size of the rectangle ///</summary> public Size Size { get { return new Size(Width, Height); } } ///<summary> /// Position of the rectangle top-left corner ///</summary> public Point Location { get { return new Point(Left, Top); } } ///<summary> /// Handy method for converting to a System.Drawing.Rectangle ///</summary> ///<returns></returns> public Rectangle ToRectangle() { return Rectangle.FromLTRB(Left, Top, Right, Bottom); } ///<summary> /// Convert a rectangle into a RECT ///</summary> ///<param name="rectangle"></param> ///<returns></returns> public static RECT FromRectangle(Rectangle rectangle) { return new RECT(rectangle.Left, rectangle.Top, rectangle.Right, rectangle.Bottom); } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns> /// A 32-bit signed integer that is the hash code for this instance. /// </returns> /// <filterpriority>2</filterpriority> public override int GetHashCode() { return Left ^ ((Top << 13) | (Top >> 0x13)) ^ ((Width << 0x1a) | (Width >> 6)) ^ ((Height << 7) | (Height >> 0x19)); } #region Operator overloads ///<summary> /// implicit conversion to Rectangle ///</summary> ///<param name="rect"></param> ///<returns></returns> public static implicit operator Rectangle(RECT rect) { return rect.ToRectangle(); } ///<summary> /// implicit conversion to RECT ///</summary> ///<param name="rect"></param> ///<returns></returns> public static implicit operator RECT(Rectangle rect) { return FromRectangle(rect); } #endregion ///<summary> /// return true if of the same position and size ///</summary> ///<param name="rect"></param> ///<returns></returns> public bool Equals(RECT rect) { return Top == rect.Top && Left == rect.Left && Bottom == rect.Bottom && Right == rect.Right; } /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <returns> /// true if <paramref name="obj"/> and this instance are the same type and represent the same value; otherwise, false. /// </returns> /// <param name="obj">Another object to compare to. </param><filterpriority>2</filterpriority> public override bool Equals(object obj) { if (obj is RECT) { return Equals((RECT)obj); } return base.Equals(obj); } } #endregion #region Nested type: WINDOWINFO ///<summary> /// Windows information structure ///</summary> [StructLayout(LayoutKind.Sequential)] public struct WINDOWINFO { ///<summary> ///The size of the structure, in bytes. The caller must set this to sizeof(WINDOWINFO). ///</summary> public uint cbSize; ///<summary> ///RECT structure that specifies the coordinates of the window. ///</summary> public RECT rcWindow; ///<summary> ///RECT structure that specifies the coordinates of the client area. ///</summary> public RECT rcClient; ///<summary> ///The window styles ///</summary> public uint dwStyle; /// <summary> /// The extended window styles /// </summary> public uint dwExStyle; /// <summary> /// The window status. If this member is WS_ACTIVECAPTION, the window is active. Otherwise, this member is zero. /// </summary> public uint dwWindowStatus; /// <summary> /// The width of the window border, in pixels. /// </summary> public uint cxWindowBorders; /// <summary> /// The height of the window border, in pixels. /// </summary> public uint cyWindowBorders; /// <summary> /// The window class atom /// </summary> public ushort atomWindowType; /// <summary> /// The Microsoft Windows version of the application that created the window /// </summary> public ushort wCreatorVersion; } #endregion #region Public Methods ///<summary> ///Sends the specified message to a window or windows. It calls ///the window procedure for the specified window and does not ///return until the window procedure has processed the message. ///</summary> ///<param name="hWnd"></param> ///<param name="msg"></param> ///<param name="wParam"></param> ///<param name="lParam"></param> ///<returns></returns> [DllImport("user32.dll")] public static extern int SendMessage(IntPtr hWnd, int msg, int wParam, int lParam); ///<summary> /// Delegates mousedown events to underlying controls ///</summary> ///<returns></returns> [DllImport("user32.dll")] public static extern bool ReleaseCapture(); ///<summary> /// retrieves information about the specified window ///</summary> ///<param name="hwnd"></param> ///<param name="pwi"></param> ///<returns></returns> [DllImport("user32.dll")] public static extern bool GetWindowInfo(IntPtr hwnd, ref WINDOWINFO pwi); /// <summary> /// used to get window process ID /// </summary> /// <param name="hWnd"></param> /// <param name="lpdwProcessId"></param> /// <returns></returns> [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern Int32 GetWindowThreadProcessId(IntPtr hWnd, out Int32 lpdwProcessId); ///<summary> ///used to get window process ID ///</summary> ///<param name="hwnd"></param> ///<returns></returns> public static Int32 GetWindowProcessID(IntPtr hwnd) { Int32 pid; GetWindowThreadProcessId(hwnd, out pid); return pid; } ///<summary> ///Changes the size, position, and Z order of a child, pop-up, or top-level window. ///</summary> ///<param name="hWnd"></param> ///<param name="hWndInsertAfter"></param> ///<param name="X"></param> ///<param name="Y"></param> ///<param name="cx"></param> ///<param name="cy"></param> ///<param name="uFlags"></param> ///<returns></returns> [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags); ///<summary> /// Get the active window ///</summary> ///<returns></returns> [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern IntPtr GetForegroundWindow(); ///<summary> /// Redraw window (for showing the content of the form when moving it) ///</summary> ///<param name="m"></param> public static void ReDrawWindow(System.Windows.Forms.Message m) { RECT rectangle = (RECT)Marshal.PtrToStructure( m.LParam, typeof(RECT)); SetWindowPos(m.HWnd, IntPtr.Zero, rectangle.Left, rectangle.Top, rectangle.Width, rectangle.Height, SWP_NoActivate | SWP_ShowWindow | SWP_NoSendChanging); } #endregion #region Properties ///<summary> ///The HT_CAPTION flag tells the message that the click ///occurred in the caption area (the titlebar) ///</summary> public static int HT_CAPTION { get { return 0x2; } } ///<summary> ///The WM_NCLBUTTONDOWN message is posted when the user presses ///the left mouse button while the cursor is within the ///nonclient area of a window ///</summary> public static int WM_NCLBUTTONDOWN { get { return 0xA1; } } ///<summary> /// Specifies that a window created with this style should be placed above all /// nontopmost windows and stay above them even when the window is deactivated. ///</summary> public static int WS_EX_TopMost { get { return 0x00000008; } } ///<summary> /// The flag tells Windows Xp/2000+ that the window is a layered window ///</summary> public static int WS_EX_Layered { get { return 0x80000; } } /// <summary> /// Windows 2000/XP: A top-level window created with this style does not become the foreground window when the user clicks it. The system does not bring this window to the foreground when the user minimizes or closes the foreground window. /// To activate the window, use the SetActiveWindow or SetForegroundWindow function. /// The window does not appear on the taskbar by default. To force the window to appear on the taskbar, use the WS_EX_APPWINDOW style. /// </summary> public static int WS_EX_NoActivate { get { return 0x08000000; } } /// <summary> /// The flag declares the window as a tool window, therefore it /// does not appear in the Alt-Tab application list /// </summary> public static int WS_EX_ToolWindow { get { return 0x80; } } /// <summary> /// Allows the windows to be transparent to the mouse. /// </summary> public static int WS_EX_Transparent { get { return 0x20; } } /// <summary> /// The WM_MOVING message is sent to a window that the user is moving /// </summary> public static int WM_MOVING { get { return 0x216; } } public static int WM_SIZING { get { return 0x214; } } public const int WM_MOUSEACTIVATE = 0x0021; public const int MA_NOACTIVATE = 3; /// <summary> /// Does not activate the window. If this flag is not set, the /// window is activated and moved to the top of either the /// topmost or non-topmost group . /// </summary> public static int SWP_NoActivate { get { return 0x0010; } } /// <summary> /// Displays the window /// </summary> public static int SWP_ShowWindow { get { return 0x0040; } } /// <summary> /// Prevents the window from receiving the WM_WINDOWPOSCHANGING message /// </summary> public static int SWP_NoSendChanging { get { return 0x0400; } } #endregion } }
zzgaminginc-pointofssale
Samba.Presentation.Common/NativeWin32.cs
C#
gpl3
16,695
using System; namespace Samba.Presentation.Common { public class CategoryCommand<T> : CaptionCommand<T>, ICategoryCommand { public CategoryCommand(string caption, string category, Action<T> executeMethod) : base(caption, executeMethod) { Caption = caption; Category = category; } public CategoryCommand(string caption, string category, Action<T> executeMethod, Func<T, bool> canExecuteMethod) : this(caption, category, "", executeMethod, canExecuteMethod) { } public CategoryCommand(string caption, string category, string imageSource, Action<T> executeMethod) : base(caption, executeMethod) { Category = category; ImageSource = imageSource; } public CategoryCommand(string caption, string category, string imageSource, Action<T> executeMethod, Func<T, bool> canExecuteMethod) : base(caption, executeMethod, canExecuteMethod) { Category = category; ImageSource = imageSource; } public string Category { get; set; } public string ImageSource { get; set; } public int Order { get; set; } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/CategoryCommand.cs
C#
gpl3
1,287
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; namespace Samba.Presentation.Common { public static class DialogCloser { public static readonly DependencyProperty DialogResultProperty = DependencyProperty.RegisterAttached( "DialogResult", typeof(bool?), typeof(DialogCloser), new PropertyMetadata(DialogResultChanged)); private static void DialogResultChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { var window = d as Window; if (window != null) window.DialogResult = e.NewValue as bool?; } public static void SetDialogResult(Window target, bool? value) { target.SetValue(DialogResultProperty, value); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/DialogCloser.cs
C#
gpl3
945
using Microsoft.Practices.Prism.Events; namespace Samba.Presentation.Common { public static class EventServiceFactory { // Singleton instance of the EventAggregator service private static EventAggregator _eventSerice; // Lock (sync) object private static readonly object _syncRoot = new object(); // Factory method public static EventAggregator EventService { get { // Lock execution thread in case of multi-threaded // (concurrent) access. lock (_syncRoot) { return _eventSerice ?? (_eventSerice = new EventAggregator()); // Return singleton instance } // lock } } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/EventServiceFactory.cs
C#
gpl3
836
namespace Samba.Presentation.Common { public static class RegionNames { public const string MainRegion = "MainRegion"; public const string SecondaryRegion = "SecondaryRegion"; public const string UserRegion = "UserRegion"; public const string RightUserRegion = "RightUserRegion"; } }
zzgaminginc-pointofssale
Samba.Presentation.Common/RegionNames.cs
C#
gpl3
341
using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Forms; using System.Windows.Forms.Integration; using System.Windows.Input; using KeyEventArgs = System.Windows.Input.KeyEventArgs; using ToolBar = System.Windows.Controls.ToolBar; namespace Samba.Presentation.Common.Browser { /// <summary> /// Interaction logic for BrowserControl.xaml /// </summary> public partial class BrowserControl { private readonly Dictionary<TabItem, ExtendedWebBrowser> _browserTabs = new Dictionary<TabItem, ExtendedWebBrowser>(); private readonly List<TabItem> _tabQueue = new List<TabItem>(); private string _activeUrl; public string ActiveUrl { get { return _activeUrl; } set { _activeUrl = value; Navigate(_activeUrl); } } private bool _isToolbarVisible; public bool IsToolbarVisible { get { return _isToolbarVisible; } set { _isToolbarVisible = value; UpdateToolbars(this, value); } } public bool AutoRefresh { get; set; } public static readonly DependencyProperty IsToolbarVisibleProperty = DependencyProperty.RegisterAttached("IsToolbarVisible", typeof(bool), typeof(BrowserControl), new UIPropertyMetadata(false, ToolbarVisiblePropertyChanged)); public static bool GetIsToolbarVisible(DependencyObject obj) { return (bool)obj.GetValue(IsToolbarVisibleProperty); } public static void SetIsToolbarVisible(DependencyObject obj, bool value) { obj.SetValue(IsToolbarVisibleProperty, value); } private static void ToolbarVisiblePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var browser = d as BrowserControl; if (browser != null) { browser.IsToolbarVisible = (bool)e.NewValue; } } private static void UpdateToolbars(BrowserControl browser, bool isVisible) { if (isVisible) { browser.MainToolbar.Visibility = Visibility.Visible; browser.tbMain.ItemContainerStyle = new Style(typeof(TabItem)); browser.tbMain.Items.Cast<TabItem>().ToList().ForEach(x => x.Visibility = Visibility.Visible); } else { browser.MainToolbar.Visibility = Visibility.Collapsed; browser.tbMain.ItemContainerStyle = new Style(typeof(TabItem)); browser.tbMain.Items.Cast<TabItem>().ToList().ForEach(x => x.Visibility = Visibility.Collapsed); } } public static readonly DependencyProperty ActiveUrlProperty = DependencyProperty.RegisterAttached("ActiveUrl", typeof(string), typeof(BrowserControl), new UIPropertyMetadata(null, ActiveUrlPropertyChanged)); public static string GetActiveUrl(DependencyObject obj) { return (string)obj.GetValue(ActiveUrlProperty); } public static void SetActiveUrl(DependencyObject obj, string value) { obj.SetValue(ActiveUrlProperty, value); } public static void ActiveUrlPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { BrowserControl browser = o as BrowserControl; if (browser != null && browser.AutoRefresh) { string uri = e.NewValue as string; if (!string.IsNullOrEmpty(uri)) browser.ActiveUrl = uri; } } public BrowserControl() { InitializeComponent(); AutoRefresh = true; Loaded += BrowserControl_Loaded; } private void ControlShown() { edAddress.Focus(); edAddress.SelectAll(); } void BrowserControl_Loaded(object sender, RoutedEventArgs e) { ControlShown(); if (_browserTabs.Count == 0) { CreateNewBrowserTab(); ResizeToolbar(MainToolbar, edAddress); } } private TabItem CreateNewBrowserTab() { var t = new TabItem(); tbMain.Items.Add(t); tbMain.SelectedItem = t; t.Header = "Yeni Sayfa"; var host = new WindowsFormsHost(); var b = new ExtendedWebBrowser { Tag = t, ScriptErrorsSuppressed = true }; host.Child = b; t.Content = host; WrapBrowserEvents(b); _browserTabs.Add(t, b); _tabQueue.Add(t); return t; } private void WrapBrowserEvents(ExtendedWebBrowser browser) { browser.DocumentTitleChanged += browser_DocumentTitleChanged; browser.StartNewWindow += browser_StartNewWindow; browser.StartNewTab += browser_StartNewTab; browser.Quit += browser_Quit; } private void UnWrapBrowserEvents(ExtendedWebBrowser browser) { browser.DocumentTitleChanged -= browser_DocumentTitleChanged; browser.StartNewWindow -= browser_StartNewWindow; browser.StartNewTab -= browser_StartNewTab; browser.Quit -= browser_Quit; } void browser_Quit(object sender, EventArgs e) { //var tab = GetBrowserTab(sender); //CloseTab(tab); } void browser_StartNewWindow(object sender, BrowserExtendedNavigatingEventArgs e) { var index = tbMain.SelectedIndex; var tab = CreateNewBrowserTab(); var page = new BrowserPage(); e.AutomationObject = _browserTabs[tab].ActiveXInstance; tbMain.SelectedIndex = index; tbMain.Items.Remove(tab); page.Closing += page_Closing; page.AssignTab(tab, _browserTabs[tab]); //page.Show(); //e.Cancel = true; //_browserTabs[tab].Navigate(e.Url); //Navigate(e.Url.ToString()); } void page_Closing(object sender, System.ComponentModel.CancelEventArgs e) { CloseTab(((BrowserPage)sender).TabMain.Items[0] as TabItem); } void browser_StartNewTab(object sender, BrowserExtendedNavigatingEventArgs e) { var tab = CreateNewBrowserTab(); e.AutomationObject = _browserTabs[tab].ActiveXInstance; tbMain.ItemContainerStyle = new Style(typeof(TabItem)); tbMain.Items.Cast<TabItem>().ToList().ForEach(x => x.Visibility = Visibility.Visible); } void browser_DocumentTitleChanged(object sender, EventArgs e) { try { var wb = sender as ExtendedWebBrowser; if (wb != null) { string title = wb.DocumentTitle; if (string.IsNullOrEmpty(title)) { title = "(Yeni Sayfa)"; } if (title.Length > 20) { title = title.Substring(0, 20) + "..."; } GetBrowserTab(sender).Header = title; edAddress.Text = wb.Url.ToString(); edAddress.SelectAll(); } } catch (Exception) { } } public void CreateNewTab() { TabItem t = CreateNewBrowserTab(); _browserTabs[t].Navigate(new Uri("about:blank")); ControlShown(); UpdateToolbars(this, IsToolbarVisible || _browserTabs.Count > 1); } private void CloseTab(TabItem tabPage) { if (_tabQueue.IndexOf(tabPage) > 0) tbMain.SelectedItem = _tabQueue[_tabQueue.IndexOf(tabPage) - 1]; UnWrapBrowserEvents(_browserTabs[tabPage]); _browserTabs[tabPage].Dispose(); _browserTabs.Remove(tabPage); tbMain.Items.Remove(tabPage); _tabQueue.Remove(tabPage); } private static TabItem GetBrowserTab(object browser) { return browser is ExtendedWebBrowser ? (browser as ExtendedWebBrowser).Tag as TabItem : null; } private TabItem GetActiveTab() { if (tbMain.Items.Count == 0) { var result = CreateNewBrowserTab(); UpdateToolbars(this, IsToolbarVisible); return result; } return tbMain.SelectedItem as TabItem; } private ExtendedWebBrowser GetActiveBrowser() { return _browserTabs[GetActiveTab()]; } private bool HasActiveBrowser() { return tbMain.Items.Count > 0 && tbMain.SelectedItem != null && _browserTabs.ContainsKey(tbMain.SelectedItem as TabItem) && _browserTabs[tbMain.SelectedItem as TabItem].Url != null; } public void Navigate(string urlString) { TabItem t = GetActiveTab(); if (urlString.ToLower() != "about:blank" && !urlString.StartsWith(Uri.UriSchemeHttp + Uri.SchemeDelimiter) && !urlString.StartsWith(Uri.UriSchemeHttps + Uri.SchemeDelimiter)) if (urlString.Contains(" ") || !urlString.Contains(".")) urlString = "http://www.google.com/search?q=" + urlString; else urlString = Uri.UriSchemeHttp + Uri.SchemeDelimiter + urlString; _browserTabs[t].Navigate(new Uri(urlString)); } private void ActiveBrowserForward() { if (HasActiveBrowser()) { ExtendedWebBrowser b = GetActiveBrowser(); if (b.CanGoForward) b.GoForward(); } } private void ActiveBrowserBack() { if (HasActiveBrowser()) { ExtendedWebBrowser b = GetActiveBrowser(); if (b.CanGoBack) b.GoBack(); } } private void btnBack_Click(object sender, RoutedEventArgs e) { ActiveBrowserBack(); } private void btnForward_Click(object sender, RoutedEventArgs e) { ActiveBrowserForward(); } private void edAddress_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { Navigate(edAddress.Text); edAddress.SelectAll(); } } private void btnAddTab_Click(object sender, RoutedEventArgs e) { CreateNewTab(); } private void btnRemoveTab_Click(object sender, RoutedEventArgs e) { CloseTab(GetActiveTab()); } private void tbMain_SelectionChanged(object sender, SelectionChangedEventArgs e) { edAddress.Text = HasActiveBrowser() ? GetActiveBrowser().Url.ToString() : ""; } private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e) { ResizeToolbar(MainToolbar, edAddress); } public static void ResizeToolbar(ToolBar toolStrip, FrameworkElement resizingItem) { var w = (from FrameworkElement t in toolStrip.Items where t != resizingItem select t.ActualWidth).Sum(); if (((toolStrip.ActualWidth - w) - 50) > 50) resizingItem.Width = (toolStrip.ActualWidth - w) - 50; else resizingItem.Width = 50; } public void RefreshPage() { if (HasActiveBrowser()) { ExtendedWebBrowser b = GetActiveBrowser(); b.Refresh(); } } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Browser/BrowserControl.xaml.cs
C#
gpl3
12,611
//////////////////////////////////////////////////////////////////////////////////// // WinInetAPI.cs // // By Scott McMaster (smcmaste@hotmail.com) // 2/1/2006 // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. //////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections; using System.Runtime.InteropServices; using System.Text.RegularExpressions; using System.Diagnostics; namespace Samba.Presentation.Common.Browser { /// <summary> /// Interop functions we need (i.e. those dealing with the url cache) from wininet.dll. /// </summary> public sealed class WinInetAPI { /// <summary> /// Structure used in various caching APIs. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct INTERNET_CACHE_ENTRY_INFO { public UInt32 dwStructSize; public string lpszSourceUrlName; public string lpszLocalFileName; public UInt32 CacheEntryType; public UInt32 dwUseCount; public UInt32 dwHitRate; public UInt32 dwSizeLow; public UInt32 dwSizeHigh; public Win32API.FILETIME LastModifiedTime; public Win32API.FILETIME ExpireTime; public Win32API.FILETIME LastAccessTime; public Win32API.FILETIME LastSyncTime; public IntPtr lpHeaderInfo; public UInt32 dwHeaderInfoSize; public string lpszFileExtension; public UInt32 dwExemptDelta; }; [DllImport("wininet.dll", SetLastError = true)] private static extern long FindCloseUrlCache(IntPtr hEnumHandle); [DllImport("wininet.dll", SetLastError = true)] private static extern IntPtr FindFirstUrlCacheEntry(string lpszUrlSearchPattern, IntPtr lpFirstCacheEntryInfo, out UInt32 lpdwFirstCacheEntryInfoBufferSize); [DllImport("wininet.dll", SetLastError = true)] private static extern long FindNextUrlCacheEntry(IntPtr hEnumHandle, IntPtr lpNextCacheEntryInfo, out UInt32 lpdwNextCacheEntryInfoBufferSize); [DllImport("wininet.dll", SetLastError = true)] private static extern bool GetUrlCacheEntryInfo(string lpszUrlName, IntPtr lpCacheEntryInfo, out UInt32 lpdwCacheEntryInfoBufferSize); [DllImport("wininet.dll", SetLastError = true)] private static extern long DeleteUrlCacheEntry(string lpszUrlName); [DllImport("wininet.dll", SetLastError = true)] private static extern IntPtr RetrieveUrlCacheEntryStream(string lpszUrlName, IntPtr lpCacheEntryInfo, out UInt32 lpdwCacheEntryInfoBufferSize, long fRandomRead, UInt32 dwReserved); [DllImport("wininet.dll", SetLastError = true)] private static extern IntPtr ReadUrlCacheEntryStream(IntPtr hUrlCacheStream, UInt32 dwLocation, IntPtr lpBuffer, out UInt32 lpdwLen, UInt32 dwReserved); [DllImport("wininet.dll", SetLastError = true)] private static extern long UnlockUrlCacheEntryStream(IntPtr hUrlCacheStream, UInt32 dwReserved); /// <summary> /// Remove an entry from the url cache. /// </summary> /// <param name="url"></param> public static void DeleteFromUrlCache(string url) { long apiResult = DeleteUrlCacheEntry(url); if (apiResult != 0) { return; } int lastError = Marshal.GetLastWin32Error(); if (lastError == Win32API.ERROR_ACCESS_DENIED) { ThrowAccessDenied(url); } else { ThrowFileNotFound(url); } } /// <summary> /// Helper method to throw a standard access denied exception. /// </summary> private static void ThrowAccessDenied(string url) { throw new ApplicationException("Access denied: " + url); } /// <summary> /// Helper method to throw a standard insufficient buffer exception. /// </summary> private static void ThrowInsufficientBuffer(string url) { throw new ApplicationException("Insufficient buffer: " + url); } /// <summary> /// Helper method to throw a standard file not found exception. /// </summary> private static void ThrowFileNotFound(string url) { throw new ApplicationException("File not found: " + url); } /// <summary> /// Helper method to check for standard errors we may see from the WinInet functions. /// </summary> /// <param name="url"></param> private static void CheckLastError(string url, bool ignoreInsufficientBuffer) { int lastError = Marshal.GetLastWin32Error(); if (lastError == Win32API.ERROR_INSUFFICIENT_BUFFER) { if (!ignoreInsufficientBuffer) { ThrowInsufficientBuffer(url); } } else if (lastError == Win32API.ERROR_FILE_NOT_FOUND) { ThrowFileNotFound(url); } else if (lastError == Win32API.ERROR_ACCESS_DENIED) { ThrowAccessDenied(url); } else if (lastError != Win32API.ERROR_SUCCESS) { throw new ApplicationException("Unexpected error, code=" + lastError.ToString()); } } /// <summary> /// More friendly wrapper for the GetUrlCacheEntryInfo API. /// </summary> /// <param name="url"></param> /// <returns></returns> public static INTERNET_CACHE_ENTRY_INFO GetUrlCacheEntryInfo(string url) { Uri u = new Uri(url); url = u.AbsoluteUri; IntPtr buffer = IntPtr.Zero; UInt32 structSize; bool apiResult = GetUrlCacheEntryInfo(url, buffer, out structSize); CheckLastError(url, true); try { buffer = Marshal.AllocHGlobal((int)structSize); apiResult = GetUrlCacheEntryInfo(url, buffer, out structSize); if (apiResult == true) { return (INTERNET_CACHE_ENTRY_INFO)Marshal.PtrToStructure(buffer, typeof(INTERNET_CACHE_ENTRY_INFO)); } CheckLastError(url, false); } finally { if (buffer.ToInt32() > 0) { try { Marshal.FreeHGlobal(buffer); } catch { } } } Debug.Assert(false, "We should either early-return or throw before we get here"); return new INTERNET_CACHE_ENTRY_INFO(); // Make the compiler happy even though we never expect this code to run. } /// <summary> /// More friendly wrapper for the Retrieve/ReadUrlCacheEntryStream APIs. /// </summary> /// <param name="url"></param> /// <returns></returns> public static string RetrieveUrlCacheEntryContents(string url) { IntPtr buffer = IntPtr.Zero; INTERNET_CACHE_ENTRY_INFO info = new INTERNET_CACHE_ENTRY_INFO(); UInt32 structSize; IntPtr hStream = IntPtr.Zero; RetrieveUrlCacheEntryStream(url, buffer, out structSize, 0, 0); CheckLastError(url, true); try { buffer = Marshal.AllocHGlobal((int)structSize); hStream = RetrieveUrlCacheEntryStream(url, buffer, out structSize, 0, 0); CheckLastError(url, true); info = (INTERNET_CACHE_ENTRY_INFO)Marshal.PtrToStructure(buffer, typeof(INTERNET_CACHE_ENTRY_INFO)); uint streamSize = info.dwSizeLow; IntPtr outBuffer = Marshal.AllocHGlobal((int)streamSize); try { IntPtr result = ReadUrlCacheEntryStream(hStream, 0, outBuffer, out streamSize, 0); CheckLastError(url, false); return Marshal.PtrToStringAnsi(outBuffer); } finally { if (outBuffer.ToInt32() > 0) { try { Marshal.FreeHGlobal(outBuffer); } catch { } } } } finally { if (buffer.ToInt32() > 0) { try { Marshal.FreeHGlobal(buffer); } catch { } } if (hStream != IntPtr.Zero) { UInt32 dwReserved = 0; UnlockUrlCacheEntryStream(hStream, dwReserved); } } } /// <summary> /// Friendly wrapper around the FindUrlCacheEntry APIs that gets a list of the entries /// matching the given pattern. /// </summary> /// <param name="urlPattern">The pattern, which is a regular expression applied by this method, since I've never /// seen any evidence that the first parameter to the FindFirstUrlCacheEntry API actually works.</param> /// <returns></returns> public static ArrayList FindUrlCacheEntries(string urlPattern) { ArrayList results = new ArrayList(); IntPtr buffer = IntPtr.Zero; UInt32 structSize; IntPtr hEnum = FindFirstUrlCacheEntry(null, buffer, out structSize); try { if (hEnum == IntPtr.Zero) { int lastError = Marshal.GetLastWin32Error(); if (lastError == Win32API.ERROR_INSUFFICIENT_BUFFER) { buffer = Marshal.AllocHGlobal((int)structSize); hEnum = FindFirstUrlCacheEntry(urlPattern, buffer, out structSize); } else if (lastError == Win32API.ERROR_NO_MORE_ITEMS) { return results; } } INTERNET_CACHE_ENTRY_INFO result = (INTERNET_CACHE_ENTRY_INFO)Marshal.PtrToStructure(buffer, typeof(INTERNET_CACHE_ENTRY_INFO)); try { if (Regex.IsMatch(result.lpszSourceUrlName, urlPattern, RegexOptions.IgnoreCase)) { results.Add(result); } } catch (ArgumentException ae) { throw new ApplicationException("Invalid regular expression, details=" + ae.Message); } if (buffer != IntPtr.Zero) { try { Marshal.FreeHGlobal(buffer); } catch { } buffer = IntPtr.Zero; structSize = 0; } while (true) { long nextResult = FindNextUrlCacheEntry(hEnum, buffer, out structSize); if (nextResult != 1) { int lastError = Marshal.GetLastWin32Error(); if (lastError == Win32API.ERROR_INSUFFICIENT_BUFFER) { buffer = Marshal.AllocHGlobal((int)structSize); nextResult = FindNextUrlCacheEntry(hEnum, buffer, out structSize); } else if (lastError == Win32API.ERROR_NO_MORE_ITEMS) { break; } } result = (INTERNET_CACHE_ENTRY_INFO)Marshal.PtrToStructure(buffer, typeof(INTERNET_CACHE_ENTRY_INFO)); if (Regex.IsMatch(result.lpszSourceUrlName, urlPattern, RegexOptions.IgnoreCase)) { results.Add(result); } if (buffer != IntPtr.Zero) { try { Marshal.FreeHGlobal(buffer); } catch { } buffer = IntPtr.Zero; structSize = 0; } } } finally { if (hEnum != IntPtr.Zero) { FindCloseUrlCache(hEnum); } if (buffer != IntPtr.Zero) { try { Marshal.FreeHGlobal(buffer); } catch { } } } return results; } /// <summary> /// Static class -- can't create. /// </summary> private WinInetAPI() { } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Browser/WinInetAPI.cs
C#
gpl3
13,540
//////////////////////////////////////////////////////////////////////////////////// // Win32API.cs // // By Scott McMaster (smcmaste@hotmail.com) // 2/1/2006 // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. //////////////////////////////////////////////////////////////////////////////////// using System; using System.Runtime.InteropServices; namespace Samba.Presentation.Common.Browser { /// <summary> /// Win32 api functions and definitions we use. /// </summary> public sealed class Win32API { /// <summary> /// From winerror.h. /// </summary> public const int ERROR_SUCCESS = 0; /// <summary> /// From winerror.h. /// </summary> public const int ERROR_FILE_NOT_FOUND = 2; /// <summary> /// From winerror.h. /// </summary> public const int ERROR_ACCESS_DENIED = 5; /// <summary> /// From winerror.h. /// </summary> public const int ERROR_INSUFFICIENT_BUFFER = 122; /// <summary> /// From winerror.h. /// </summary> public const int ERROR_NO_MORE_ITEMS = 259; [StructLayout(LayoutKind.Sequential)] public struct FILETIME { public UInt32 dwLowDateTime; public UInt32 dwHighDateTime; } [StructLayout(LayoutKind.Sequential)] public struct SYSTEMTIME { public UInt16 Year; public UInt16 Month; public UInt16 DayOfWeek; public UInt16 Day; public UInt16 Hour; public UInt16 Minute; public UInt16 Second; public UInt16 Milliseconds; } [DllImport("Kernel32.dll", SetLastError=true)] public static extern long FileTimeToSystemTime(ref FILETIME FileTime, ref SYSTEMTIME SystemTime); [DllImport("kernel32.dll", SetLastError=true)] public static extern long SystemTimeToTzSpecificLocalTime(IntPtr lpTimeZoneInformation, ref SYSTEMTIME lpUniversalTime, out SYSTEMTIME lpLocalTime); /// <summary> /// Helper routine to get a DateTime from a FILETIME. /// </summary> /// <param name="ft"></param> /// <returns></returns> public static DateTime FromFileTime( Win32API.FILETIME ft ) { if( ft.dwHighDateTime == Int32.MaxValue || (ft.dwLowDateTime == 0 && ft.dwHighDateTime == 0) ) { // Not going to fit in the DateTime. In the WinInet APIs, this is // what happens when there is no FILETIME attached to the cache entry. // We're going to use DateTime.MinValue as a marker for this case. return DateTime.MinValue; } Win32API.SYSTEMTIME syst = new Win32API.SYSTEMTIME(); Win32API.SYSTEMTIME systLocal = new Win32API.SYSTEMTIME(); if( 0 == Win32API.FileTimeToSystemTime( ref ft, ref syst ) ) { throw new ApplicationException( "Error calling FileTimeToSystemTime: " + Marshal.GetLastWin32Error() ); } if( 0 == Win32API.SystemTimeToTzSpecificLocalTime( IntPtr.Zero, ref syst, out systLocal ) ) { throw new ApplicationException( "Error calling SystemTimeToTzSpecificLocalTime: " + Marshal.GetLastWin32Error() ); } return new DateTime( systLocal.Year, systLocal.Month, systLocal.Day, systLocal.Hour, systLocal.Minute, systLocal.Second ); } /// <summary> /// Get a string representation of the given FILETIME. /// </summary> /// <param name="ft"></param> /// <returns></returns> public static string ToStringFromFileTime( Win32API.FILETIME ft ) { DateTime dt = FromFileTime( ft ); if( dt == DateTime.MinValue ) { return ""; } return dt.ToString(); } /// <summary> /// Static class -- can't create. /// </summary> private Win32API() { } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Browser/Win32API.cs
C#
gpl3
3,782
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.Browser { /// <summary> /// Interaction logic for BrowserPage.xaml /// </summary> public partial class BrowserPage : Window { private bool _closing; public BrowserPage() { InitializeComponent(); Closing += new System.ComponentModel.CancelEventHandler(BrowserPage_Closing); } void BrowserPage_Closing(object sender, System.ComponentModel.CancelEventArgs e) { _closing = true; } public void AssignTab(TabItem tab, ExtendedWebBrowser browserTab) { TabMain.Items.Add(tab); browserTab.Quit += browserTab_Quit; browserTab.DocumentTitleChanged += browserTab_DocumentTitleChanged; browserTab.WindowSetWidth += browserTab_WindowSetWidth; browserTab.WindowSetHeight += browserTab_WindowSetHeight; browserTab.WindowSetLeft += browserTab_WindowSetLeft; browserTab.WindowsSetTop += browserTab_WindowsSetTop; browserTab.DocumentCompleted += browserTab_DocumentCompleted; } void browserTab_WindowsSetTop(object sender, SizeChangedEventArgs e) { Top = e.Size; } void browserTab_WindowSetLeft(object sender, SizeChangedEventArgs e) { Left = e.Size; } void browserTab_DocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e) { if (!IsVisible) { Show(); (sender as ExtendedWebBrowser).Refresh(); } } void browserTab_DocumentTitleChanged(object sender, EventArgs e) { try { Title = ((ExtendedWebBrowser)sender).DocumentTitle; } catch (Exception) { } } void browserTab_WindowSetHeight(object sender, SizeChangedEventArgs e) { Height = e.Size + 30; } void browserTab_WindowSetWidth(object sender, SizeChangedEventArgs e) { Width = e.Size + 10; } void browserTab_Quit(object sender, EventArgs e) { if (!_closing) Close(); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Browser/BrowserPage.xaml.cs
C#
gpl3
2,756
using System; using System.Runtime.InteropServices; using System.Security; using System.Windows.Forms; using System.Runtime.CompilerServices; namespace Samba.Presentation.Common.Browser { public sealed class HTMLDispIDs { //useful DISPIDs public const int DISPID_UNKNOWN = -1; //The original value -2147418111 was incorrect //0x80010000 = -2147418112 = &H80010000 public const int DISPID_XOBJ_MIN = -2147418112; //0x8001FFFF public const int DISPID_XOBJ_MAX = -2147352577; public const int DISPID_XOBJ_BASE = DISPID_XOBJ_MIN; public const int DISPID_HTMLOBJECT = (DISPID_XOBJ_BASE + 500); public const int DISPID_ELEMENT = (DISPID_HTMLOBJECT + 500); public const int DISPID_SITE = (DISPID_ELEMENT + 1000); public const int DISPID_OBJECT = (DISPID_SITE + 1000); public const int DISPID_STYLE = (DISPID_OBJECT + 1000); public const int DISPID_ATTRS = (DISPID_STYLE + 1000); public const int DISPID_EVENTS = (DISPID_ATTRS + 1000); public const int DISPID_XOBJ_EXPANDO = (DISPID_EVENTS + 1000); public const int DISPID_XOBJ_ORDINAL = (DISPID_XOBJ_EXPANDO + 1000); public const int DISPID_AMBIENT_DLCONTROL = -5512; public const int STDDISPID_XOBJ_ONBLUR = (DISPID_XOBJ_BASE); public const int STDDISPID_XOBJ_ONFOCUS = (DISPID_XOBJ_BASE + 1); public const int STDDISPID_XOBJ_BEFOREUPDATE = (DISPID_XOBJ_BASE + 4); public const int STDDISPID_XOBJ_AFTERUPDATE = (DISPID_XOBJ_BASE + 5); public const int STDDISPID_XOBJ_ONROWEXIT = (DISPID_XOBJ_BASE + 6); public const int STDDISPID_XOBJ_ONROWENTER = (DISPID_XOBJ_BASE + 7); public const int STDDISPID_XOBJ_ONMOUSEOVER = (DISPID_XOBJ_BASE + 8); public const int STDDISPID_XOBJ_ONMOUSEOUT = (DISPID_XOBJ_BASE + 9); public const int STDDISPID_XOBJ_ONHELP = (DISPID_XOBJ_BASE + 10); public const int STDDISPID_XOBJ_ONDRAGSTART = (DISPID_XOBJ_BASE + 11); public const int STDDISPID_XOBJ_ONSELECTSTART = (DISPID_XOBJ_BASE + 12); public const int STDDISPID_XOBJ_ERRORUPDATE = (DISPID_XOBJ_BASE + 13); public const int STDDISPID_XOBJ_ONDATASETCHANGED = (DISPID_XOBJ_BASE + 14); public const int STDDISPID_XOBJ_ONDATAAVAILABLE = (DISPID_XOBJ_BASE + 15); public const int STDDISPID_XOBJ_ONDATASETCOMPLETE = (DISPID_XOBJ_BASE + 16); public const int STDDISPID_XOBJ_ONFILTER = (DISPID_XOBJ_BASE + 17); public const int STDDISPID_XOBJ_ONLOSECAPTURE = (DISPID_XOBJ_BASE + 18); public const int STDDISPID_XOBJ_ONPROPERTYCHANGE = (DISPID_XOBJ_BASE + 19); public const int STDDISPID_XOBJ_ONDRAG = (DISPID_XOBJ_BASE + 20); public const int STDDISPID_XOBJ_ONDRAGEND = (DISPID_XOBJ_BASE + 21); public const int STDDISPID_XOBJ_ONDRAGENTER = (DISPID_XOBJ_BASE + 22); public const int STDDISPID_XOBJ_ONDRAGOVER = (DISPID_XOBJ_BASE + 23); public const int STDDISPID_XOBJ_ONDRAGLEAVE = (DISPID_XOBJ_BASE + 24); public const int STDDISPID_XOBJ_ONDROP = (DISPID_XOBJ_BASE + 25); public const int STDDISPID_XOBJ_ONCUT = (DISPID_XOBJ_BASE + 26); public const int STDDISPID_XOBJ_ONCOPY = (DISPID_XOBJ_BASE + 27); public const int STDDISPID_XOBJ_ONPASTE = (DISPID_XOBJ_BASE + 28); public const int STDDISPID_XOBJ_ONBEFORECUT = (DISPID_XOBJ_BASE + 29); public const int STDDISPID_XOBJ_ONBEFORECOPY = (DISPID_XOBJ_BASE + 30); public const int STDDISPID_XOBJ_ONBEFOREPASTE = (DISPID_XOBJ_BASE + 31); public const int STDDISPID_XOBJ_ONROWSDELETE = (DISPID_XOBJ_BASE + 32); public const int STDDISPID_XOBJ_ONROWSINSERTED = (DISPID_XOBJ_BASE + 33); public const int STDDISPID_XOBJ_ONCELLCHANGE = (DISPID_XOBJ_BASE + 34); public const int STDPROPID_XOBJ_DISABLED = (DISPID_XOBJ_BASE + 0x4C); //+76 public const int DISPID_DEFAULTVALUE = (DISPID_A_FIRST + 83); public const int DISPID_CLICK = (-600); public const int DISPID_DBLCLICK = (-601); public const int DISPID_KEYDOWN = (-602); public const int DISPID_KEYPRESS = (-603); public const int DISPID_KEYUP = (-604); public const int DISPID_MOUSEDOWN = (-605); public const int DISPID_MOUSEMOVE = (-606); public const int DISPID_MOUSEUP = (-607); public const int DISPID_ERROREVENT = (-608); public const int DISPID_READYSTATECHANGE = (-609); public const int DISPID_CLICK_VALUE = (-610); public const int DISPID_RIGHTTOLEFT = (-611); public const int DISPID_TOPTOBOTTOM = (-612); public const int DISPID_THIS = (-613); // Standard dispatch ID constants public const int DISPID_AUTOSIZE = (-500); public const int DISPID_BACKCOLOR = (-501); public const int DISPID_BACKSTYLE = (-502); public const int DISPID_BORDERCOLOR = (-503); public const int DISPID_BORDERSTYLE = (-504); public const int DISPID_BORDERWIDTH = (-505); public const int DISPID_DRAWMODE = (-507); public const int DISPID_DRAWSTYLE = (-508); public const int DISPID_DRAWWIDTH = (-509); public const int DISPID_FILLCOLOR = (-510); public const int DISPID_FILLSTYLE = (-511); public const int DISPID_FONT = (-512); public const int DISPID_FORECOLOR = (-513); public const int DISPID_ENABLED = (-514); public const int DISPID_HWND = (-515); public const int DISPID_TABSTOP = (-516); public const int DISPID_TEXT = (-517); public const int DISPID_CAPTION = (-518); public const int DISPID_BORDERVISIBLE = (-519); public const int DISPID_APPEARANCE = (-520); public const int DISPID_MOUSEPOINTER = (-521); public const int DISPID_MOUSEICON = (-522); public const int DISPID_PICTURE = (-523); public const int DISPID_VALID = (-524); public const int DISPID_READYSTATE = (-525); public const int DISPID_LISTINDEX = (-526); public const int DISPID_SELECTED = (-527); public const int DISPID_LIST = (-528); public const int DISPID_COLUMN = (-529); public const int DISPID_LISTCOUNT = (-531); public const int DISPID_MULTISELECT = (-532); public const int DISPID_MAXLENGTH = (-533); public const int DISPID_PASSWORDCHAR = (-534); public const int DISPID_SCROLLBARS = (-535); public const int DISPID_WORDWRAP = (-536); public const int DISPID_MULTILINE = (-537); public const int DISPID_NUMBEROFROWS = (-538); public const int DISPID_NUMBEROFCOLUMNS = (-539); public const int DISPID_DISPLAYSTYLE = (-540); public const int DISPID_GROUPNAME = (-541); public const int DISPID_IMEMODE = (-542); public const int DISPID_ACCELERATOR = (-543); public const int DISPID_ENTERKEYBEHAVIOR = (-544); public const int DISPID_TABKEYBEHAVIOR = (-545); public const int DISPID_SELTEXT = (-546); public const int DISPID_SELSTART = (-547); public const int DISPID_SELLENGTH = (-548); public const int DISPID_AMBIENT_CODEPAGE = (-725); public const int DISPID_AMBIENT_CHARSET = (-727); public const int DISPID_REFRESH = (-550); public const int DISPID_DOCLICK = (-551); public const int DISPID_ABOUTBOX = (-552); public const int DISPID_ADDITEM = (-553); public const int DISPID_CLEAR = (-554); public const int DISPID_REMOVEITEM = (-555); public const int DISPID_NORMAL_FIRST = 1000; public const int DISPID_ONABORT = (DISPID_NORMAL_FIRST); public const int DISPID_ONCHANGE = (DISPID_NORMAL_FIRST + 1); public const int DISPID_ONERROR = (DISPID_NORMAL_FIRST + 2); public const int DISPID_ONLOAD = (DISPID_NORMAL_FIRST + 3); public const int DISPID_ONSELECT = (DISPID_NORMAL_FIRST + 6); public const int DISPID_ONSUBMIT = (DISPID_NORMAL_FIRST + 7); public const int DISPID_ONUNLOAD = (DISPID_NORMAL_FIRST + 8); public const int DISPID_ONBOUNCE = (DISPID_NORMAL_FIRST + 9); public const int DISPID_ONFINISH = (DISPID_NORMAL_FIRST + 10); public const int DISPID_ONSTART = (DISPID_NORMAL_FIRST + 11); public const int DISPID_ONLAYOUT = (DISPID_NORMAL_FIRST + 13); public const int DISPID_ONSCROLL = (DISPID_NORMAL_FIRST + 14); public const int DISPID_ONRESET = (DISPID_NORMAL_FIRST + 15); public const int DISPID_ONRESIZE = (DISPID_NORMAL_FIRST + 16); public const int DISPID_ONBEFOREUNLOAD = (DISPID_NORMAL_FIRST + 17); public const int DISPID_ONCHANGEFOCUS = (DISPID_NORMAL_FIRST + 18); public const int DISPID_ONCHANGEBLUR = (DISPID_NORMAL_FIRST + 19); public const int DISPID_ONPERSIST = (DISPID_NORMAL_FIRST + 20); public const int DISPID_ONPERSISTSAVE = (DISPID_NORMAL_FIRST + 21); public const int DISPID_ONPERSISTLOAD = (DISPID_NORMAL_FIRST + 22); public const int DISPID_ONCONTEXTMENU = (DISPID_NORMAL_FIRST + 23); public const int DISPID_ONBEFOREPRINT = (DISPID_NORMAL_FIRST + 24); public const int DISPID_ONAFTERPRINT = (DISPID_NORMAL_FIRST + 25); public const int DISPID_ONSTOP = (DISPID_NORMAL_FIRST + 26); public const int DISPID_ONBEFOREEDITFOCUS = (DISPID_NORMAL_FIRST + 27); public const int DISPID_ONMOUSEHOVER = (DISPID_NORMAL_FIRST + 28); public const int DISPID_ONCONTENTREADY = (DISPID_NORMAL_FIRST + 29); public const int DISPID_ONLAYOUTCOMPLETE = (DISPID_NORMAL_FIRST + 30); public const int DISPID_ONPAGE = (DISPID_NORMAL_FIRST + 31); public const int DISPID_ONLINKEDOVERFLOW = (DISPID_NORMAL_FIRST + 32); public const int DISPID_ONMOUSEWHEEL = (DISPID_NORMAL_FIRST + 33); public const int DISPID_ONBEFOREDEACTIVATE = (DISPID_NORMAL_FIRST + 34); public const int DISPID_ONMOVE = (DISPID_NORMAL_FIRST + 35); public const int DISPID_ONCONTROLSELECT = (DISPID_NORMAL_FIRST + 36); public const int DISPID_ONSELECTIONCHANGE = (DISPID_NORMAL_FIRST + 37); public const int DISPID_ONMOVESTART = (DISPID_NORMAL_FIRST + 38); public const int DISPID_ONMOVEEND = (DISPID_NORMAL_FIRST + 39); public const int DISPID_ONRESIZESTART = (DISPID_NORMAL_FIRST + 40); public const int DISPID_ONRESIZEEND = (DISPID_NORMAL_FIRST + 41); public const int DISPID_ONMOUSEENTER = (DISPID_NORMAL_FIRST + 42); public const int DISPID_ONMOUSELEAVE = (DISPID_NORMAL_FIRST + 43); public const int DISPID_ONACTIVATE = (DISPID_NORMAL_FIRST + 44); public const int DISPID_ONDEACTIVATE = (DISPID_NORMAL_FIRST + 45); public const int DISPID_ONMULTILAYOUTCLEANUP = (DISPID_NORMAL_FIRST + 46); public const int DISPID_ONBEFOREACTIVATE = (DISPID_NORMAL_FIRST + 47); public const int DISPID_ONFOCUSIN = (DISPID_NORMAL_FIRST + 48); public const int DISPID_ONFOCUSOUT = (DISPID_NORMAL_FIRST + 49); public const int DISPID_A_UNICODEBIDI = (DISPID_A_FIRST + 118); // Complex Text support for CSS2 unicode-bidi public const int DISPID_A_DIRECTION = (DISPID_A_FIRST + 119); // Complex Text support for CSS2 direction public const int DISPID_EVPROP_ONMOUSEOVER = (DISPID_EVENTS + 0); public const int DISPID_EVMETH_ONMOUSEOVER = STDDISPID_XOBJ_ONMOUSEOVER; public const int DISPID_EVPROP_ONMOUSEOUT = (DISPID_EVENTS + 1); public const int DISPID_EVMETH_ONMOUSEOUT = STDDISPID_XOBJ_ONMOUSEOUT; public const int DISPID_EVPROP_ONMOUSEDOWN = (DISPID_EVENTS + 2); public const int DISPID_EVMETH_ONMOUSEDOWN = DISPID_MOUSEDOWN; public const int DISPID_EVPROP_ONMOUSEUP = (DISPID_EVENTS + 3); public const int DISPID_EVMETH_ONMOUSEUP = DISPID_MOUSEUP; public const int DISPID_EVPROP_ONMOUSEMOVE = (DISPID_EVENTS + 4); public const int DISPID_EVMETH_ONMOUSEMOVE = DISPID_MOUSEMOVE; public const int DISPID_EVPROP_ONKEYDOWN = (DISPID_EVENTS + 5); public const int DISPID_EVMETH_ONKEYDOWN = DISPID_KEYDOWN; public const int DISPID_EVPROP_ONKEYUP = (DISPID_EVENTS + 6); public const int DISPID_EVMETH_ONKEYUP = DISPID_KEYUP; public const int DISPID_EVPROP_ONKEYPRESS = (DISPID_EVENTS + 7); public const int DISPID_EVMETH_ONKEYPRESS = DISPID_KEYPRESS; public const int DISPID_EVPROP_ONCLICK = (DISPID_EVENTS + 8); public const int DISPID_EVMETH_ONCLICK = DISPID_CLICK; public const int DISPID_EVPROP_ONDBLCLICK = (DISPID_EVENTS + 9); public const int DISPID_EVMETH_ONDBLCLICK = DISPID_DBLCLICK; public const int DISPID_EVPROP_ONSELECT = (DISPID_EVENTS + 10); public const int DISPID_EVMETH_ONSELECT = DISPID_ONSELECT; public const int DISPID_EVPROP_ONSUBMIT = (DISPID_EVENTS + 11); public const int DISPID_EVMETH_ONSUBMIT = DISPID_ONSUBMIT; public const int DISPID_EVPROP_ONRESET = (DISPID_EVENTS + 12); public const int DISPID_EVMETH_ONRESET = DISPID_ONRESET; public const int DISPID_EVPROP_ONHELP = (DISPID_EVENTS + 13); public const int DISPID_EVMETH_ONHELP = STDDISPID_XOBJ_ONHELP; public const int DISPID_EVPROP_ONFOCUS = (DISPID_EVENTS + 14); public const int DISPID_EVMETH_ONFOCUS = STDDISPID_XOBJ_ONFOCUS; public const int DISPID_EVPROP_ONBLUR = (DISPID_EVENTS + 15); public const int DISPID_EVMETH_ONBLUR = STDDISPID_XOBJ_ONBLUR; public const int DISPID_EVPROP_ONROWEXIT = (DISPID_EVENTS + 18); public const int DISPID_EVMETH_ONROWEXIT = STDDISPID_XOBJ_ONROWEXIT; public const int DISPID_EVPROP_ONROWENTER = (DISPID_EVENTS + 19); public const int DISPID_EVMETH_ONROWENTER = STDDISPID_XOBJ_ONROWENTER; public const int DISPID_EVPROP_ONBOUNCE = (DISPID_EVENTS + 20); public const int DISPID_EVMETH_ONBOUNCE = DISPID_ONBOUNCE; public const int DISPID_EVPROP_ONBEFOREUPDATE = (DISPID_EVENTS + 21); public const int DISPID_EVMETH_ONBEFOREUPDATE = STDDISPID_XOBJ_BEFOREUPDATE; public const int DISPID_EVPROP_ONAFTERUPDATE = (DISPID_EVENTS + 22); public const int DISPID_EVMETH_ONAFTERUPDATE = STDDISPID_XOBJ_AFTERUPDATE; public const int DISPID_EVPROP_ONBEFOREDRAGOVER = (DISPID_EVENTS + 23); //public const int DISPID_EVMETH_ONBEFOREDRAGOVER = EVENTID_CommonCtrlEvent_BeforeDragOver; public const int DISPID_EVPROP_ONBEFOREDROPORPASTE = (DISPID_EVENTS + 24); //public const int DISPID_EVMETH_ONBEFOREDROPORPASTE = EVENTID_CommonCtrlEvent_BeforeDropOrPaste; public const int DISPID_EVPROP_ONREADYSTATECHANGE = (DISPID_EVENTS + 25); public const int DISPID_EVMETH_ONREADYSTATECHANGE = DISPID_READYSTATECHANGE; public const int DISPID_EVPROP_ONFINISH = (DISPID_EVENTS + 26); public const int DISPID_EVMETH_ONFINISH = DISPID_ONFINISH; public const int DISPID_EVPROP_ONSTART = (DISPID_EVENTS + 27); public const int DISPID_EVMETH_ONSTART = DISPID_ONSTART; public const int DISPID_EVPROP_ONABORT = (DISPID_EVENTS + 28); public const int DISPID_EVMETH_ONABORT = DISPID_ONABORT; public const int DISPID_EVPROP_ONERROR = (DISPID_EVENTS + 29); public const int DISPID_EVMETH_ONERROR = DISPID_ONERROR; public const int DISPID_EVPROP_ONCHANGE = (DISPID_EVENTS + 30); public const int DISPID_EVMETH_ONCHANGE = DISPID_ONCHANGE; public const int DISPID_EVPROP_ONSCROLL = (DISPID_EVENTS + 31); public const int DISPID_EVMETH_ONSCROLL = DISPID_ONSCROLL; public const int DISPID_EVPROP_ONLOAD = (DISPID_EVENTS + 32); public const int DISPID_EVMETH_ONLOAD = DISPID_ONLOAD; public const int DISPID_EVPROP_ONUNLOAD = (DISPID_EVENTS + 33); public const int DISPID_EVMETH_ONUNLOAD = DISPID_ONUNLOAD; public const int DISPID_EVPROP_ONLAYOUT = (DISPID_EVENTS + 34); public const int DISPID_EVMETH_ONLAYOUT = DISPID_ONLAYOUT; public const int DISPID_EVPROP_ONDRAGSTART = (DISPID_EVENTS + 35); public const int DISPID_EVMETH_ONDRAGSTART = STDDISPID_XOBJ_ONDRAGSTART; public const int DISPID_EVPROP_ONRESIZE = (DISPID_EVENTS + 36); public const int DISPID_EVMETH_ONRESIZE = DISPID_ONRESIZE; public const int DISPID_EVPROP_ONSELECTSTART = (DISPID_EVENTS + 37); public const int DISPID_EVMETH_ONSELECTSTART = STDDISPID_XOBJ_ONSELECTSTART; public const int DISPID_EVPROP_ONERRORUPDATE = (DISPID_EVENTS + 38); public const int DISPID_EVMETH_ONERRORUPDATE = STDDISPID_XOBJ_ERRORUPDATE; public const int DISPID_EVPROP_ONBEFOREUNLOAD = (DISPID_EVENTS + 39); // <summary> /// /// </summary> //public const int DISPID_EVMETH_ONBEFOREUNLOAD = DISPID_ONBEFOREUNLOAD; public const int DISPID_EVPROP_ONDATASETCHANGED = (DISPID_EVENTS + 40); public const int DISPID_EVMETH_ONDATASETCHANGED = STDDISPID_XOBJ_ONDATASETCHANGED; public const int DISPID_EVPROP_ONDATAAVAILABLE = (DISPID_EVENTS + 41); public const int DISPID_EVMETH_ONDATAAVAILABLE = STDDISPID_XOBJ_ONDATAAVAILABLE; public const int DISPID_EVPROP_ONDATASETCOMPLETE = (DISPID_EVENTS + 42); public const int DISPID_EVMETH_ONDATASETCOMPLETE = STDDISPID_XOBJ_ONDATASETCOMPLETE; public const int DISPID_EVPROP_ONFILTER = (DISPID_EVENTS + 43); public const int DISPID_EVMETH_ONFILTER = STDDISPID_XOBJ_ONFILTER; public const int DISPID_EVPROP_ONCHANGEFOCUS = (DISPID_EVENTS + 44); public const int DISPID_EVMETH_ONCHANGEFOCUS = DISPID_ONCHANGEFOCUS; public const int DISPID_EVPROP_ONCHANGEBLUR = (DISPID_EVENTS + 45); public const int DISPID_EVMETH_ONCHANGEBLUR = DISPID_ONCHANGEBLUR; public const int DISPID_EVPROP_ONLOSECAPTURE = (DISPID_EVENTS + 46); public const int DISPID_EVMETH_ONLOSECAPTURE = STDDISPID_XOBJ_ONLOSECAPTURE; public const int DISPID_EVPROP_ONPROPERTYCHANGE = (DISPID_EVENTS + 47); public const int DISPID_EVMETH_ONPROPERTYCHANGE = STDDISPID_XOBJ_ONPROPERTYCHANGE; public const int DISPID_EVPROP_ONPERSISTSAVE = (DISPID_EVENTS + 48); public const int DISPID_EVMETH_ONPERSISTSAVE = DISPID_ONPERSISTSAVE; public const int DISPID_EVPROP_ONDRAG = (DISPID_EVENTS + 49); public const int DISPID_EVMETH_ONDRAG = STDDISPID_XOBJ_ONDRAG; public const int DISPID_EVPROP_ONDRAGEND = (DISPID_EVENTS + 50); public const int DISPID_EVMETH_ONDRAGEND = STDDISPID_XOBJ_ONDRAGEND; public const int DISPID_EVPROP_ONDRAGENTER = (DISPID_EVENTS + 51); public const int DISPID_EVMETH_ONDRAGENTER = STDDISPID_XOBJ_ONDRAGENTER; public const int DISPID_EVPROP_ONDRAGOVER = (DISPID_EVENTS + 52); public const int DISPID_EVMETH_ONDRAGOVER = STDDISPID_XOBJ_ONDRAGOVER; public const int DISPID_EVPROP_ONDRAGLEAVE = (DISPID_EVENTS + 53); public const int DISPID_EVMETH_ONDRAGLEAVE = STDDISPID_XOBJ_ONDRAGLEAVE; public const int DISPID_EVPROP_ONDROP = (DISPID_EVENTS + 54); public const int DISPID_EVMETH_ONDROP = STDDISPID_XOBJ_ONDROP; public const int DISPID_EVPROP_ONCUT = (DISPID_EVENTS + 55); public const int DISPID_EVMETH_ONCUT = STDDISPID_XOBJ_ONCUT; public const int DISPID_EVPROP_ONCOPY = (DISPID_EVENTS + 56); public const int DISPID_EVMETH_ONCOPY = STDDISPID_XOBJ_ONCOPY; public const int DISPID_EVPROP_ONPASTE = (DISPID_EVENTS + 57); public const int DISPID_EVMETH_ONPASTE = STDDISPID_XOBJ_ONPASTE; public const int DISPID_EVPROP_ONBEFORECUT = (DISPID_EVENTS + 58); public const int DISPID_EVMETH_ONBEFORECUT = STDDISPID_XOBJ_ONBEFORECUT; public const int DISPID_EVPROP_ONBEFORECOPY = (DISPID_EVENTS + 59); public const int DISPID_EVMETH_ONBEFORECOPY = STDDISPID_XOBJ_ONBEFORECOPY; public const int DISPID_EVPROP_ONBEFOREPASTE = (DISPID_EVENTS + 60); public const int DISPID_EVMETH_ONBEFOREPASTE = STDDISPID_XOBJ_ONBEFOREPASTE; public const int DISPID_EVPROP_ONPERSISTLOAD = (DISPID_EVENTS + 61); public const int DISPID_EVMETH_ONPERSISTLOAD = DISPID_ONPERSISTLOAD; public const int DISPID_EVPROP_ONROWSDELETE = (DISPID_EVENTS + 62); public const int DISPID_EVMETH_ONROWSDELETE = STDDISPID_XOBJ_ONROWSDELETE; public const int DISPID_EVPROP_ONROWSINSERTED = (DISPID_EVENTS + 63); public const int DISPID_EVMETH_ONROWSINSERTED = STDDISPID_XOBJ_ONROWSINSERTED; public const int DISPID_EVPROP_ONCELLCHANGE = (DISPID_EVENTS + 64); public const int DISPID_EVMETH_ONCELLCHANGE = STDDISPID_XOBJ_ONCELLCHANGE; public const int DISPID_EVPROP_ONCONTEXTMENU = (DISPID_EVENTS + 65); public const int DISPID_EVMETH_ONCONTEXTMENU = DISPID_ONCONTEXTMENU; public const int DISPID_EVPROP_ONBEFOREPRINT = (DISPID_EVENTS + 66); public const int DISPID_EVMETH_ONBEFOREPRINT = DISPID_ONBEFOREPRINT; public const int DISPID_EVPROP_ONAFTERPRINT = (DISPID_EVENTS + 67); public const int DISPID_EVMETH_ONAFTERPRINT = DISPID_ONAFTERPRINT; public const int DISPID_EVPROP_ONSTOP = (DISPID_EVENTS + 68); public const int DISPID_EVMETH_ONSTOP = DISPID_ONSTOP; public const int DISPID_EVPROP_ONBEFOREEDITFOCUS = (DISPID_EVENTS + 69); public const int DISPID_EVMETH_ONBEFOREEDITFOCUS = DISPID_ONBEFOREEDITFOCUS; public const int DISPID_EVPROP_ONATTACHEVENT = (DISPID_EVENTS + 70); public const int DISPID_EVPROP_ONMOUSEHOVER = (DISPID_EVENTS + 71); public const int DISPID_EVMETH_ONMOUSEHOVER = DISPID_ONMOUSEHOVER; public const int DISPID_EVPROP_ONCONTENTREADY = (DISPID_EVENTS + 72); public const int DISPID_EVMETH_ONCONTENTREADY = DISPID_ONCONTENTREADY; public const int DISPID_EVPROP_ONLAYOUTCOMPLETE = (DISPID_EVENTS + 73); public const int DISPID_EVMETH_ONLAYOUTCOMPLETE = DISPID_ONLAYOUTCOMPLETE; public const int DISPID_EVPROP_ONPAGE = (DISPID_EVENTS + 74); public const int DISPID_EVMETH_ONPAGE = DISPID_ONPAGE; public const int DISPID_EVPROP_ONLINKEDOVERFLOW = (DISPID_EVENTS + 75); public const int DISPID_EVMETH_ONLINKEDOVERFLOW = DISPID_ONLINKEDOVERFLOW; public const int DISPID_EVPROP_ONMOUSEWHEEL = (DISPID_EVENTS + 76); public const int DISPID_EVMETH_ONMOUSEWHEEL = DISPID_ONMOUSEWHEEL; public const int DISPID_EVPROP_ONBEFOREDEACTIVATE = (DISPID_EVENTS + 77); public const int DISPID_EVMETH_ONBEFOREDEACTIVATE = DISPID_ONBEFOREDEACTIVATE; public const int DISPID_EVPROP_ONMOVE = (DISPID_EVENTS + 78); public const int DISPID_EVMETH_ONMOVE = DISPID_ONMOVE; public const int DISPID_EVPROP_ONCONTROLSELECT = (DISPID_EVENTS + 79); public const int DISPID_EVMETH_ONCONTROLSELECT = DISPID_ONCONTROLSELECT; public const int DISPID_EVPROP_ONSELECTIONCHANGE = (DISPID_EVENTS + 80); public const int DISPID_EVMETH_ONSELECTIONCHANGE = DISPID_ONSELECTIONCHANGE; public const int DISPID_EVPROP_ONMOVESTART = (DISPID_EVENTS + 81); public const int DISPID_EVMETH_ONMOVESTART = DISPID_ONMOVESTART; public const int DISPID_EVPROP_ONMOVEEND = (DISPID_EVENTS + 82); public const int DISPID_EVMETH_ONMOVEEND = DISPID_ONMOVEEND; public const int DISPID_EVPROP_ONRESIZESTART = (DISPID_EVENTS + 83); public const int DISPID_EVMETH_ONRESIZESTART = DISPID_ONRESIZESTART; public const int DISPID_EVPROP_ONRESIZEEND = (DISPID_EVENTS + 84); public const int DISPID_EVMETH_ONRESIZEEND = DISPID_ONRESIZEEND; public const int DISPID_EVPROP_ONMOUSEENTER = (DISPID_EVENTS + 85); public const int DISPID_EVMETH_ONMOUSEENTER = DISPID_ONMOUSEENTER; public const int DISPID_EVPROP_ONMOUSELEAVE = (DISPID_EVENTS + 86); public const int DISPID_EVMETH_ONMOUSELEAVE = DISPID_ONMOUSELEAVE; public const int DISPID_EVPROP_ONACTIVATE = (DISPID_EVENTS + 87); public const int DISPID_EVMETH_ONACTIVATE = DISPID_ONACTIVATE; public const int DISPID_EVPROP_ONDEACTIVATE = (DISPID_EVENTS + 88); public const int DISPID_EVMETH_ONDEACTIVATE = DISPID_ONDEACTIVATE; public const int DISPID_EVPROP_ONMULTILAYOUTCLEANUP = (DISPID_EVENTS + 89); public const int DISPID_EVMETH_ONMULTILAYOUTCLEANUP = DISPID_ONMULTILAYOUTCLEANUP; public const int DISPID_EVPROP_ONBEFOREACTIVATE = (DISPID_EVENTS + 90); public const int DISPID_EVMETH_ONBEFOREACTIVATE = DISPID_ONBEFOREACTIVATE; public const int DISPID_EVPROP_ONFOCUSIN = (DISPID_EVENTS + 91); public const int DISPID_EVMETH_ONFOCUSIN = DISPID_ONFOCUSIN; public const int DISPID_EVPROP_ONFOCUSOUT = (DISPID_EVENTS + 92); public const int DISPID_EVMETH_ONFOCUSOUT = DISPID_ONFOCUSOUT; public const int DISPID_EVMETH_ONBEFOREUNLOAD = DISPID_ONBEFOREUNLOAD; public const int STDPROPID_XOBJ_CONTROLTIPTEXT = (DISPID_XOBJ_BASE + 0x45); public const int DISPID_A_LANGUAGE = (DISPID_A_FIRST + 100); public const int DISPID_A_LANG = (DISPID_A_FIRST + 9); public const int STDPROPID_XOBJ_PARENT = (DISPID_XOBJ_BASE + 0x8); public const int STDPROPID_XOBJ_STYLE = (DISPID_XOBJ_BASE + 0x4A); // DISPIDs for interface IHTMLEventObj4 public const int DISPID_IHTMLEVENTOBJ4_WHEELDELTA = DISPID_EVENTOBJ + 51; public const int DISPID_IHTMLELEMENT_SETATTRIBUTE = DISPID_HTMLOBJECT + 1; public const int DISPID_IHTMLELEMENT_GETATTRIBUTE = DISPID_HTMLOBJECT + 2; public const int DISPID_IHTMLELEMENT_REMOVEATTRIBUTE = DISPID_HTMLOBJECT + 3; public const int DISPID_IHTMLELEMENT_CLASSNAME = DISPID_ELEMENT + 1; public const int DISPID_IHTMLELEMENT_ID = DISPID_ELEMENT + 2; public const int DISPID_IHTMLELEMENT_TAGNAME = DISPID_ELEMENT + 4; public const int DISPID_IHTMLELEMENT_PARENTELEMENT = STDPROPID_XOBJ_PARENT; public const int DISPID_IHTMLELEMENT_STYLE = STDPROPID_XOBJ_STYLE; public const int DISPID_IHTMLELEMENT_ONHELP = DISPID_EVPROP_ONHELP; //-2147412098 public const int DISPID_IHTMLELEMENT_ONCLICK = DISPID_EVPROP_ONCLICK; //-2147412103 public const int DISPID_IHTMLELEMENT_ONDBLCLICK = DISPID_EVPROP_ONDBLCLICK;//-2147412102 public const int DISPID_IHTMLELEMENT_ONKEYDOWN = DISPID_EVPROP_ONKEYDOWN; //-2147412106 public const int DISPID_IHTMLELEMENT_ONKEYUP = DISPID_EVPROP_ONKEYUP; public const int DISPID_IHTMLELEMENT_ONKEYPRESS = DISPID_EVPROP_ONKEYPRESS; //-2147412104 public const int DISPID_IHTMLELEMENT_ONMOUSEOUT = DISPID_EVPROP_ONMOUSEOUT; //-2147412110 public const int DISPID_IHTMLELEMENT_ONMOUSEOVER = DISPID_EVPROP_ONMOUSEOVER; //-2147412111 public const int DISPID_IHTMLELEMENT_ONMOUSEMOVE = DISPID_EVPROP_ONMOUSEMOVE; // -2147412107 public const int DISPID_IHTMLELEMENT_ONMOUSEDOWN = DISPID_EVPROP_ONMOUSEDOWN; public const int DISPID_IHTMLELEMENT_ONMOUSEUP = DISPID_EVPROP_ONMOUSEUP; public const int DISPID_IHTMLELEMENT_DOCUMENT = DISPID_ELEMENT + 18; public const int DISPID_IHTMLELEMENT_TITLE = STDPROPID_XOBJ_CONTROLTIPTEXT; public const int DISPID_IHTMLELEMENT_LANGUAGE = DISPID_A_LANGUAGE; public const int DISPID_IHTMLELEMENT_ONSELECTSTART = DISPID_EVPROP_ONSELECTSTART; public const int DISPID_IHTMLELEMENT_SCROLLINTOVIEW = DISPID_ELEMENT + 19; public const int DISPID_IHTMLELEMENT_CONTAINS = DISPID_ELEMENT + 20; public const int DISPID_IHTMLELEMENT_SOURCEINDEX = DISPID_ELEMENT + 24; public const int DISPID_IHTMLELEMENT_RECORDNUMBER = DISPID_ELEMENT + 25; public const int DISPID_IHTMLELEMENT_LANG = DISPID_A_LANG; public const int DISPID_IHTMLELEMENT_OFFSETLEFT = DISPID_ELEMENT + 8; public const int DISPID_IHTMLELEMENT_OFFSETTOP = DISPID_ELEMENT + 9; public const int DISPID_IHTMLELEMENT_OFFSETWIDTH = DISPID_ELEMENT + 10; public const int DISPID_IHTMLELEMENT_OFFSETHEIGHT = DISPID_ELEMENT + 11; public const int DISPID_IHTMLELEMENT_OFFSETPARENT = DISPID_ELEMENT + 12; public const int DISPID_IHTMLELEMENT_INNERHTML = DISPID_ELEMENT + 26; public const int DISPID_IHTMLELEMENT_INNERTEXT = DISPID_ELEMENT + 27; public const int DISPID_IHTMLELEMENT_OUTERHTML = DISPID_ELEMENT + 28; public const int DISPID_IHTMLELEMENT_OUTERTEXT = DISPID_ELEMENT + 29; public const int DISPID_IHTMLELEMENT_INSERTADJACENTHTML = DISPID_ELEMENT + 30; public const int DISPID_IHTMLELEMENT_INSERTADJACENTTEXT = DISPID_ELEMENT + 31; public const int DISPID_IHTMLELEMENT_PARENTTEXTEDIT = DISPID_ELEMENT + 32; public const int DISPID_IHTMLELEMENT_ISTEXTEDIT = DISPID_ELEMENT + 34; public const int DISPID_IHTMLELEMENT_CLICK = DISPID_ELEMENT + 33; public const int DISPID_IHTMLELEMENT_FILTERS = DISPID_ELEMENT + 35; public const int DISPID_IHTMLELEMENT_ONDRAGSTART = DISPID_EVPROP_ONDRAGSTART; public const int DISPID_IHTMLELEMENT_TOSTRING = DISPID_ELEMENT + 36; public const int DISPID_IHTMLELEMENT_ONBEFOREUPDATE = DISPID_EVPROP_ONBEFOREUPDATE; public const int DISPID_IHTMLELEMENT_ONAFTERUPDATE = DISPID_EVPROP_ONAFTERUPDATE; public const int DISPID_IHTMLELEMENT_ONERRORUPDATE = DISPID_EVPROP_ONERRORUPDATE; public const int DISPID_IHTMLELEMENT_ONROWEXIT = DISPID_EVPROP_ONROWEXIT; public const int DISPID_IHTMLELEMENT_ONROWENTER = DISPID_EVPROP_ONROWENTER; public const int DISPID_IHTMLELEMENT_ONDATASETCHANGED = DISPID_EVPROP_ONDATASETCHANGED; public const int DISPID_IHTMLELEMENT_ONDATAAVAILABLE = DISPID_EVPROP_ONDATAAVAILABLE; public const int DISPID_IHTMLELEMENT_ONDATASETCOMPLETE = DISPID_EVPROP_ONDATASETCOMPLETE; public const int DISPID_IHTMLELEMENT_ONFILTERCHANGE = DISPID_EVPROP_ONFILTER; public const int DISPID_IHTMLELEMENT_CHILDREN = DISPID_ELEMENT + 37; public const int DISPID_IHTMLELEMENT_ALL = DISPID_ELEMENT + 38; // DISPIDs for interface IHTMLElement2 public const int DISPID_IHTMLELEMENT2_SCOPENAME = DISPID_ELEMENT + 39; public const int DISPID_IHTMLELEMENT2_SETCAPTURE = DISPID_ELEMENT + 40; public const int DISPID_IHTMLELEMENT2_RELEASECAPTURE = DISPID_ELEMENT + 41; public const int DISPID_IHTMLELEMENT2_ONLOSECAPTURE = DISPID_EVPROP_ONLOSECAPTURE; public const int DISPID_IHTMLELEMENT2_COMPONENTFROMPOINT = DISPID_ELEMENT + 42; public const int DISPID_IHTMLELEMENT2_DOSCROLL = DISPID_ELEMENT + 43; public const int DISPID_IHTMLELEMENT2_ONSCROLL = DISPID_EVPROP_ONSCROLL; public const int DISPID_IHTMLELEMENT2_ONDRAG = DISPID_EVPROP_ONDRAG; public const int DISPID_IHTMLELEMENT2_ONDRAGEND = DISPID_EVPROP_ONDRAGEND; public const int DISPID_IHTMLELEMENT2_ONDRAGENTER = DISPID_EVPROP_ONDRAGENTER; public const int DISPID_IHTMLELEMENT2_ONDRAGOVER = DISPID_EVPROP_ONDRAGOVER; public const int DISPID_IHTMLELEMENT2_ONDRAGLEAVE = DISPID_EVPROP_ONDRAGLEAVE; public const int DISPID_IHTMLELEMENT2_ONDROP = DISPID_EVPROP_ONDROP; public const int DISPID_IHTMLELEMENT2_ONBEFORECUT = DISPID_EVPROP_ONBEFORECUT; public const int DISPID_IHTMLELEMENT2_ONCUT = DISPID_EVPROP_ONCUT; public const int DISPID_IHTMLELEMENT2_ONBEFORECOPY = DISPID_EVPROP_ONBEFORECOPY; public const int DISPID_IHTMLELEMENT2_ONCOPY = DISPID_EVPROP_ONCOPY; public const int DISPID_IHTMLELEMENT2_ONBEFOREPASTE = DISPID_EVPROP_ONBEFOREPASTE; public const int DISPID_IHTMLELEMENT2_ONPASTE = DISPID_EVPROP_ONPASTE; public const int DISPID_IHTMLELEMENT2_CURRENTSTYLE = DISPID_ELEMENT + 7; public const int DISPID_IHTMLELEMENT2_ONPROPERTYCHANGE = DISPID_EVPROP_ONPROPERTYCHANGE; public const int DISPID_IHTMLELEMENT2_GETCLIENTRECTS = DISPID_ELEMENT + 44; public const int DISPID_IHTMLELEMENT2_GETBOUNDINGCLIENTRECT = DISPID_ELEMENT + 45; public const int DISPID_IHTMLELEMENT2_SETEXPRESSION = DISPID_HTMLOBJECT + 4; public const int DISPID_IHTMLELEMENT2_GETEXPRESSION = DISPID_HTMLOBJECT + 5; public const int DISPID_IHTMLELEMENT2_REMOVEEXPRESSION = DISPID_HTMLOBJECT + 6; //public const int DISPID_IHTMLELEMENT2_TABINDEX = STDPROPID_XOBJ_TABINDEX; public const int DISPID_IHTMLELEMENT2_FOCUS = DISPID_SITE + 0; public const int DISPID_IHTMLELEMENT2_ACCESSKEY = DISPID_SITE + 5; public const int DISPID_IHTMLELEMENT2_ONBLUR = DISPID_EVPROP_ONBLUR; public const int DISPID_IHTMLELEMENT2_ONFOCUS = DISPID_EVPROP_ONFOCUS; public const int DISPID_IHTMLELEMENT2_ONRESIZE = DISPID_EVPROP_ONRESIZE; public const int DISPID_IHTMLELEMENT2_BLUR = DISPID_SITE + 2; public const int DISPID_IHTMLELEMENT2_ADDFILTER = DISPID_SITE + 17; public const int DISPID_IHTMLELEMENT2_REMOVEFILTER = DISPID_SITE + 18; public const int DISPID_IHTMLELEMENT2_CLIENTHEIGHT = DISPID_SITE + 19; public const int DISPID_IHTMLELEMENT2_CLIENTWIDTH = DISPID_SITE + 20; public const int DISPID_IHTMLELEMENT2_CLIENTTOP = DISPID_SITE + 21; public const int DISPID_IHTMLELEMENT2_CLIENTLEFT = DISPID_SITE + 22; public const int DISPID_IHTMLELEMENT2_ATTACHEVENT = DISPID_HTMLOBJECT + 7; public const int DISPID_IHTMLELEMENT2_DETACHEVENT = DISPID_HTMLOBJECT + 8; //public const int DISPID_IHTMLELEMENT2_READYSTATE = DISPID_A_READYSTATE; public const int DISPID_IHTMLELEMENT2_ONREADYSTATECHANGE = DISPID_EVPROP_ONREADYSTATECHANGE; public const int DISPID_IHTMLELEMENT2_ONROWSDELETE = DISPID_EVPROP_ONROWSDELETE; public const int DISPID_IHTMLELEMENT2_ONROWSINSERTED = DISPID_EVPROP_ONROWSINSERTED; public const int DISPID_IHTMLELEMENT2_ONCELLCHANGE = DISPID_EVPROP_ONCELLCHANGE; //public const int DISPID_IHTMLELEMENT2_DIR = DISPID_A_DIR; public const int DISPID_IHTMLELEMENT2_CREATECONTROLRANGE = DISPID_ELEMENT + 56; public const int DISPID_IHTMLELEMENT2_SCROLLHEIGHT = DISPID_ELEMENT + 57; public const int DISPID_IHTMLELEMENT2_SCROLLWIDTH = DISPID_ELEMENT + 58; public const int DISPID_IHTMLELEMENT2_SCROLLTOP = DISPID_ELEMENT + 59; public const int DISPID_IHTMLELEMENT2_SCROLLLEFT = DISPID_ELEMENT + 60; public const int DISPID_IHTMLELEMENT2_CLEARATTRIBUTES = DISPID_ELEMENT + 62; public const int DISPID_IHTMLELEMENT2_MERGEATTRIBUTES = DISPID_ELEMENT + 63; public const int DISPID_IHTMLELEMENT2_ONCONTEXTMENU = DISPID_EVPROP_ONCONTEXTMENU; public const int DISPID_IHTMLELEMENT2_INSERTADJACENTELEMENT = DISPID_ELEMENT + 69; public const int DISPID_IHTMLELEMENT2_APPLYELEMENT = DISPID_ELEMENT + 65; public const int DISPID_IHTMLELEMENT2_GETADJACENTTEXT = DISPID_ELEMENT + 70; public const int DISPID_IHTMLELEMENT2_REPLACEADJACENTTEXT = DISPID_ELEMENT + 71; public const int DISPID_IHTMLELEMENT2_CANHAVECHILDREN = DISPID_ELEMENT + 72; public const int DISPID_IHTMLELEMENT2_ADDBEHAVIOR = DISPID_ELEMENT + 80; public const int DISPID_IHTMLELEMENT2_REMOVEBEHAVIOR = DISPID_ELEMENT + 81; public const int DISPID_IHTMLELEMENT2_RUNTIMESTYLE = DISPID_ELEMENT + 64; public const int DISPID_IHTMLELEMENT2_BEHAVIORURNS = DISPID_ELEMENT + 82; public const int DISPID_IHTMLELEMENT2_TAGURN = DISPID_ELEMENT + 83; public const int DISPID_IHTMLELEMENT2_ONBEFOREEDITFOCUS = DISPID_EVPROP_ONBEFOREEDITFOCUS; public const int DISPID_IHTMLELEMENT2_READYSTATEVALUE = DISPID_ELEMENT + 84; public const int DISPID_IHTMLELEMENT2_GETELEMENTSBYTAGNAME = DISPID_ELEMENT + 85; // DISPIDs for interface IHTMLElementCollection public const int DISPID_IHTMLELEMENTCOLLECTION_TOSTRING = DISPID_COLLECTION + 1; public const int DISPID_IHTMLELEMENTCOLLECTION_LENGTH = DISPID_COLLECTION; public const int DISPID_IHTMLELEMENTCOLLECTION__NEWENUM = DISPID_NEWENUM; public const int DISPID_IHTMLELEMENTCOLLECTION_ITEM = DISPID_VALUE; public const int DISPID_IHTMLELEMENTCOLLECTION_TAGS = DISPID_COLLECTION + 2; // DISPIDs for interface IHTMLEventObj public const int DISPID_EVENTOBJ = DISPID_NORMAL_FIRST; public const int DISPID_IHTMLEVENTOBJ_SRCELEMENT = DISPID_EVENTOBJ + 1; public const int DISPID_IHTMLEVENTOBJ_ALTKEY = DISPID_EVENTOBJ + 2; public const int DISPID_IHTMLEVENTOBJ_CTRLKEY = DISPID_EVENTOBJ + 3; public const int DISPID_IHTMLEVENTOBJ_SHIFTKEY = DISPID_EVENTOBJ + 4; public const int DISPID_IHTMLEVENTOBJ_RETURNVALUE = DISPID_EVENTOBJ + 7; public const int DISPID_IHTMLEVENTOBJ_CANCELBUBBLE = DISPID_EVENTOBJ + 8; public const int DISPID_IHTMLEVENTOBJ_FROMELEMENT = DISPID_EVENTOBJ + 9; public const int DISPID_IHTMLEVENTOBJ_TOELEMENT = DISPID_EVENTOBJ + 10; public const int DISPID_IHTMLEVENTOBJ_KEYCODE = DISPID_EVENTOBJ + 11; public const int DISPID_IHTMLEVENTOBJ_BUTTON = DISPID_EVENTOBJ + 12; public const int DISPID_IHTMLEVENTOBJ_TYPE = DISPID_EVENTOBJ + 13; public const int DISPID_IHTMLEVENTOBJ_QUALIFIER = DISPID_EVENTOBJ + 14; public const int DISPID_IHTMLEVENTOBJ_REASON = DISPID_EVENTOBJ + 15; public const int DISPID_IHTMLEVENTOBJ_X = DISPID_EVENTOBJ + 5; public const int DISPID_IHTMLEVENTOBJ_Y = DISPID_EVENTOBJ + 6; public const int DISPID_IHTMLEVENTOBJ_CLIENTX = DISPID_EVENTOBJ + 20; public const int DISPID_IHTMLEVENTOBJ_CLIENTY = DISPID_EVENTOBJ + 21; public const int DISPID_IHTMLEVENTOBJ_OFFSETX = DISPID_EVENTOBJ + 22; public const int DISPID_IHTMLEVENTOBJ_OFFSETY = DISPID_EVENTOBJ + 23; public const int DISPID_IHTMLEVENTOBJ_SCREENX = DISPID_EVENTOBJ + 24; public const int DISPID_IHTMLEVENTOBJ_SCREENY = DISPID_EVENTOBJ + 25; public const int DISPID_IHTMLEVENTOBJ_SRCFILTER = DISPID_EVENTOBJ + 26; // DISPIDs for interface IHTMLEventObj2 public const int DISPID_IHTMLEVENTOBJ2_SETATTRIBUTE = DISPID_HTMLOBJECT + 1; public const int DISPID_IHTMLEVENTOBJ2_GETATTRIBUTE = DISPID_HTMLOBJECT + 2; public const int DISPID_IHTMLEVENTOBJ2_REMOVEATTRIBUTE = DISPID_HTMLOBJECT + 3; public const int DISPID_IHTMLEVENTOBJ2_PROPERTYNAME = DISPID_EVENTOBJ + 27; public const int DISPID_IHTMLEVENTOBJ2_BOOKMARKS = DISPID_EVENTOBJ + 31; public const int DISPID_IHTMLEVENTOBJ2_RECORDSET = DISPID_EVENTOBJ + 32; public const int DISPID_IHTMLEVENTOBJ2_DATAFLD = DISPID_EVENTOBJ + 33; public const int DISPID_IHTMLEVENTOBJ2_BOUNDELEMENTS = DISPID_EVENTOBJ + 34; public const int DISPID_IHTMLEVENTOBJ2_REPEAT = DISPID_EVENTOBJ + 35; public const int DISPID_IHTMLEVENTOBJ2_SRCURN = DISPID_EVENTOBJ + 36; public const int DISPID_IHTMLEVENTOBJ2_SRCELEMENT = DISPID_EVENTOBJ + 1; public const int DISPID_IHTMLEVENTOBJ2_ALTKEY = DISPID_EVENTOBJ + 2; public const int DISPID_IHTMLEVENTOBJ2_CTRLKEY = DISPID_EVENTOBJ + 3; public const int DISPID_IHTMLEVENTOBJ2_SHIFTKEY = DISPID_EVENTOBJ + 4; public const int DISPID_IHTMLEVENTOBJ2_FROMELEMENT = DISPID_EVENTOBJ + 9; public const int DISPID_IHTMLEVENTOBJ2_TOELEMENT = DISPID_EVENTOBJ + 10; public const int DISPID_IHTMLEVENTOBJ2_BUTTON = DISPID_EVENTOBJ + 12; public const int DISPID_IHTMLEVENTOBJ2_TYPE = DISPID_EVENTOBJ + 13; public const int DISPID_IHTMLEVENTOBJ2_QUALIFIER = DISPID_EVENTOBJ + 14; public const int DISPID_IHTMLEVENTOBJ2_REASON = DISPID_EVENTOBJ + 15; public const int DISPID_IHTMLEVENTOBJ2_X = DISPID_EVENTOBJ + 5; public const int DISPID_IHTMLEVENTOBJ2_Y = DISPID_EVENTOBJ + 6; public const int DISPID_IHTMLEVENTOBJ2_CLIENTX = DISPID_EVENTOBJ + 20; public const int DISPID_IHTMLEVENTOBJ2_CLIENTY = DISPID_EVENTOBJ + 21; public const int DISPID_IHTMLEVENTOBJ2_OFFSETX = DISPID_EVENTOBJ + 22; public const int DISPID_IHTMLEVENTOBJ2_OFFSETY = DISPID_EVENTOBJ + 23; public const int DISPID_IHTMLEVENTOBJ2_SCREENX = DISPID_EVENTOBJ + 24; public const int DISPID_IHTMLEVENTOBJ2_SCREENY = DISPID_EVENTOBJ + 25; public const int DISPID_IHTMLEVENTOBJ2_SRCFILTER = DISPID_EVENTOBJ + 26; public const int DISPID_IHTMLEVENTOBJ2_DATATRANSFER = DISPID_EVENTOBJ + 37; // DISPIDs for interface IHTMLEventObj3 public const int DISPID_IHTMLEVENTOBJ3_CONTENTOVERFLOW = DISPID_EVENTOBJ + 38; public const int DISPID_IHTMLEVENTOBJ3_SHIFTLEFT = DISPID_EVENTOBJ + 39; public const int DISPID_IHTMLEVENTOBJ3_ALTLEFT = DISPID_EVENTOBJ + 40; public const int DISPID_IHTMLEVENTOBJ3_CTRLLEFT = DISPID_EVENTOBJ + 41; public const int DISPID_IHTMLEVENTOBJ3_IMECOMPOSITIONCHANGE = DISPID_EVENTOBJ + 42; public const int DISPID_IHTMLEVENTOBJ3_IMENOTIFYCOMMAND = DISPID_EVENTOBJ + 43; public const int DISPID_IHTMLEVENTOBJ3_IMENOTIFYDATA = DISPID_EVENTOBJ + 44; public const int DISPID_IHTMLEVENTOBJ3_IMEREQUEST = DISPID_EVENTOBJ + 46; public const int DISPID_IHTMLEVENTOBJ3_IMEREQUESTDATA = DISPID_EVENTOBJ + 47; public const int DISPID_IHTMLEVENTOBJ3_KEYBOARDLAYOUT = DISPID_EVENTOBJ + 45; public const int DISPID_IHTMLEVENTOBJ3_BEHAVIORCOOKIE = DISPID_EVENTOBJ + 48; public const int DISPID_IHTMLEVENTOBJ3_BEHAVIORPART = DISPID_EVENTOBJ + 49; public const int DISPID_IHTMLEVENTOBJ3_NEXTPAGE = DISPID_EVENTOBJ + 50; public const int DISPID_A_FIRST = DISPID_ATTRS; public const int DISPID_A_DIR = DISPID_A_FIRST + 117; // DISPIDs for interface IHTMLDocument3 public const int DISPID_IHTMLDOCUMENT3_RELEASECAPTURE = DISPID_OMDOCUMENT + 72; public const int DISPID_IHTMLDOCUMENT3_RECALC = DISPID_OMDOCUMENT + 73; public const int DISPID_IHTMLDOCUMENT3_CREATETEXTNODE = DISPID_OMDOCUMENT + 74; public const int DISPID_IHTMLDOCUMENT3_DOCUMENTELEMENT = DISPID_OMDOCUMENT + 75; public const int DISPID_IHTMLDOCUMENT3_UNIQUEID = DISPID_OMDOCUMENT + 77; public const int DISPID_IHTMLDOCUMENT3_ATTACHEVENT = DISPID_HTMLOBJECT + 7; public const int DISPID_IHTMLDOCUMENT3_DETACHEVENT = DISPID_HTMLOBJECT + 8; public const int DISPID_IHTMLDOCUMENT3_ONROWSDELETE = DISPID_EVPROP_ONROWSDELETE; public const int DISPID_IHTMLDOCUMENT3_ONROWSINSERTED = DISPID_EVPROP_ONROWSINSERTED; public const int DISPID_IHTMLDOCUMENT3_ONCELLCHANGE = DISPID_EVPROP_ONCELLCHANGE; public const int DISPID_IHTMLDOCUMENT3_ONDATASETCHANGED = DISPID_EVPROP_ONDATASETCHANGED; public const int DISPID_IHTMLDOCUMENT3_ONDATAAVAILABLE = DISPID_EVPROP_ONDATAAVAILABLE; public const int DISPID_IHTMLDOCUMENT3_ONDATASETCOMPLETE = DISPID_EVPROP_ONDATASETCOMPLETE; public const int DISPID_IHTMLDOCUMENT3_ONPROPERTYCHANGE = DISPID_EVPROP_ONPROPERTYCHANGE; public const int DISPID_IHTMLDOCUMENT3_DIR = DISPID_A_DIR; public const int DISPID_IHTMLDOCUMENT3_ONCONTEXTMENU = DISPID_EVPROP_ONCONTEXTMENU; public const int DISPID_IHTMLDOCUMENT3_ONSTOP = DISPID_EVPROP_ONSTOP; public const int DISPID_IHTMLDOCUMENT3_CREATEDOCUMENTFRAGMENT = DISPID_OMDOCUMENT + 76; public const int DISPID_IHTMLDOCUMENT3_PARENTDOCUMENT = DISPID_OMDOCUMENT + 78; public const int DISPID_IHTMLDOCUMENT3_ENABLEDOWNLOAD = DISPID_OMDOCUMENT + 79; public const int DISPID_IHTMLDOCUMENT3_BASEURL = DISPID_OMDOCUMENT + 80; public const int DISPID_IHTMLDOCUMENT3_CHILDNODES = DISPID_ELEMENT + 49; public const int DISPID_IHTMLDOCUMENT3_INHERITSTYLESHEETS = DISPID_OMDOCUMENT + 82; public const int DISPID_IHTMLDOCUMENT3_ONBEFOREEDITFOCUS = DISPID_EVPROP_ONBEFOREEDITFOCUS; public const int DISPID_IHTMLDOCUMENT3_GETELEMENTSBYNAME = DISPID_OMDOCUMENT + 86; public const int DISPID_IHTMLDOCUMENT3_GETELEMENTBYID = DISPID_OMDOCUMENT + 88; public const int DISPID_IHTMLDOCUMENT3_GETELEMENTSBYTAGNAME = DISPID_OMDOCUMENT + 87; // DISPIDs for interface IHTMLDocument4 public const int DISPID_OMDOCUMENT = DISPID_NORMAL_FIRST; public const int DISPID_IHTMLDOCUMENT4_FOCUS = DISPID_OMDOCUMENT + 89; public const int DISPID_IHTMLDOCUMENT4_HASFOCUS = DISPID_OMDOCUMENT + 90; public const int DISPID_IHTMLDOCUMENT4_ONSELECTIONCHANGE = DISPID_EVPROP_ONSELECTIONCHANGE; public const int DISPID_IHTMLDOCUMENT4_NAMESPACES = DISPID_OMDOCUMENT + 91; public const int DISPID_IHTMLDOCUMENT4_CREATEDOCUMENTFROMURL = DISPID_OMDOCUMENT + 92; public const int DISPID_IHTMLDOCUMENT4_MEDIA = DISPID_OMDOCUMENT + 93; public const int DISPID_IHTMLDOCUMENT4_CREATEEVENTOBJECT = DISPID_OMDOCUMENT + 94; public const int DISPID_IHTMLDOCUMENT4_FIREEVENT = DISPID_OMDOCUMENT + 95; public const int DISPID_IHTMLDOCUMENT4_CREATERENDERSTYLE = DISPID_OMDOCUMENT + 96; public const int DISPID_IHTMLDOCUMENT4_ONCONTROLSELECT = DISPID_EVPROP_ONCONTROLSELECT; public const int DISPID_IHTMLDOCUMENT4_URLUNENCODED = DISPID_OMDOCUMENT + 97; // DISPIDs for interface IHTMLDocument5 public const int DISPID_IHTMLDOCUMENT5_ONMOUSEWHEEL = DISPID_EVPROP_ONMOUSEWHEEL; public const int DISPID_IHTMLDOCUMENT5_DOCTYPE = DISPID_OMDOCUMENT + 98; public const int DISPID_IHTMLDOCUMENT5_IMPLEMENTATION = DISPID_OMDOCUMENT + 99; public const int DISPID_IHTMLDOCUMENT5_CREATEATTRIBUTE = DISPID_OMDOCUMENT + 100; public const int DISPID_IHTMLDOCUMENT5_CREATECOMMENT = DISPID_OMDOCUMENT + 101; public const int DISPID_IHTMLDOCUMENT5_ONFOCUSIN = DISPID_EVPROP_ONFOCUSIN; public const int DISPID_IHTMLDOCUMENT5_ONFOCUSOUT = DISPID_EVPROP_ONFOCUSOUT; public const int DISPID_IHTMLDOCUMENT5_ONACTIVATE = DISPID_EVPROP_ONACTIVATE; public const int DISPID_IHTMLDOCUMENT5_ONDEACTIVATE = DISPID_EVPROP_ONDEACTIVATE; public const int DISPID_IHTMLDOCUMENT5_ONBEFOREACTIVATE = DISPID_EVPROP_ONBEFOREACTIVATE; public const int DISPID_IHTMLDOCUMENT5_ONBEFOREDEACTIVATE = DISPID_EVPROP_ONBEFOREDEACTIVATE; public const int DISPID_IHTMLDOCUMENT5_COMPATMODE = DISPID_OMDOCUMENT + 102; //DISPIDS for interface IHTMLDocumentEvents2 public const int DISPID_HTMLDOCUMENTEVENTS2_ONHELP = DISPID_EVMETH_ONHELP; public const int DISPID_HTMLDOCUMENTEVENTS2_ONCLICK = DISPID_EVMETH_ONCLICK; public const int DISPID_HTMLDOCUMENTEVENTS2_ONDBLCLICK = DISPID_EVMETH_ONDBLCLICK; public const int DISPID_HTMLDOCUMENTEVENTS2_ONKEYDOWN = DISPID_EVMETH_ONKEYDOWN; public const int DISPID_HTMLDOCUMENTEVENTS2_ONKEYUP = DISPID_EVMETH_ONKEYUP; public const int DISPID_HTMLDOCUMENTEVENTS2_ONKEYPRESS = DISPID_EVMETH_ONKEYPRESS; public const int DISPID_HTMLDOCUMENTEVENTS2_ONMOUSEDOWN = DISPID_EVMETH_ONMOUSEDOWN; public const int DISPID_HTMLDOCUMENTEVENTS2_ONMOUSEMOVE = DISPID_EVMETH_ONMOUSEMOVE; public const int DISPID_HTMLDOCUMENTEVENTS2_ONMOUSEUP = DISPID_EVMETH_ONMOUSEUP; public const int DISPID_HTMLDOCUMENTEVENTS2_ONMOUSEOUT = DISPID_EVMETH_ONMOUSEOUT; public const int DISPID_HTMLDOCUMENTEVENTS2_ONMOUSEOVER = DISPID_EVMETH_ONMOUSEOVER; public const int DISPID_HTMLDOCUMENTEVENTS2_ONREADYSTATECHANGE = DISPID_EVMETH_ONREADYSTATECHANGE; public const int DISPID_HTMLDOCUMENTEVENTS2_ONBEFOREUPDATE = DISPID_EVMETH_ONBEFOREUPDATE; public const int DISPID_HTMLDOCUMENTEVENTS2_ONAFTERUPDATE = DISPID_EVMETH_ONAFTERUPDATE; public const int DISPID_HTMLDOCUMENTEVENTS2_ONROWEXIT = DISPID_EVMETH_ONROWEXIT; public const int DISPID_HTMLDOCUMENTEVENTS2_ONROWENTER = DISPID_EVMETH_ONROWENTER; public const int DISPID_HTMLDOCUMENTEVENTS2_ONDRAGSTART = DISPID_EVMETH_ONDRAGSTART; public const int DISPID_HTMLDOCUMENTEVENTS2_ONSELECTSTART = DISPID_EVMETH_ONSELECTSTART; public const int DISPID_HTMLDOCUMENTEVENTS2_ONERRORUPDATE = DISPID_EVMETH_ONERRORUPDATE; public const int DISPID_HTMLDOCUMENTEVENTS2_ONCONTEXTMENU = DISPID_EVMETH_ONCONTEXTMENU; public const int DISPID_HTMLDOCUMENTEVENTS2_ONSTOP = DISPID_EVMETH_ONSTOP; public const int DISPID_HTMLDOCUMENTEVENTS2_ONROWSDELETE = DISPID_EVMETH_ONROWSDELETE; public const int DISPID_HTMLDOCUMENTEVENTS2_ONROWSINSERTED = DISPID_EVMETH_ONROWSINSERTED; public const int DISPID_HTMLDOCUMENTEVENTS2_ONCELLCHANGE = DISPID_EVMETH_ONCELLCHANGE; public const int DISPID_HTMLDOCUMENTEVENTS2_ONPROPERTYCHANGE = DISPID_EVMETH_ONPROPERTYCHANGE; public const int DISPID_HTMLDOCUMENTEVENTS2_ONDATASETCHANGED = DISPID_EVMETH_ONDATASETCHANGED; public const int DISPID_HTMLDOCUMENTEVENTS2_ONDATAAVAILABLE = DISPID_EVMETH_ONDATAAVAILABLE; public const int DISPID_HTMLDOCUMENTEVENTS2_ONDATASETCOMPLETE = DISPID_EVMETH_ONDATASETCOMPLETE; public const int DISPID_HTMLDOCUMENTEVENTS2_ONBEFOREEDITFOCUS = DISPID_EVMETH_ONBEFOREEDITFOCUS; public const int DISPID_HTMLDOCUMENTEVENTS2_ONSELECTIONCHANGE = DISPID_EVMETH_ONSELECTIONCHANGE; public const int DISPID_HTMLDOCUMENTEVENTS2_ONCONTROLSELECT = DISPID_EVMETH_ONCONTROLSELECT; public const int DISPID_HTMLDOCUMENTEVENTS2_ONMOUSEWHEEL = DISPID_EVMETH_ONMOUSEWHEEL; public const int DISPID_HTMLDOCUMENTEVENTS2_ONFOCUSIN = DISPID_EVMETH_ONFOCUSIN; public const int DISPID_HTMLDOCUMENTEVENTS2_ONFOCUSOUT = DISPID_EVMETH_ONFOCUSOUT; public const int DISPID_HTMLDOCUMENTEVENTS2_ONACTIVATE = DISPID_EVMETH_ONACTIVATE; public const int DISPID_HTMLDOCUMENTEVENTS2_ONDEACTIVATE = DISPID_EVMETH_ONDEACTIVATE; public const int DISPID_HTMLDOCUMENTEVENTS2_ONBEFOREACTIVATE = DISPID_EVMETH_ONBEFOREACTIVATE; public const int DISPID_HTMLDOCUMENTEVENTS2_ONBEFOREDEACTIVATE = DISPID_EVMETH_ONBEFOREDEACTIVATE; // DISPIDs for event set HTMLWindowEvents2 public const int DISPID_HTMLWINDOWEVENTS2_ONLOAD = DISPID_EVMETH_ONLOAD; public const int DISPID_HTMLWINDOWEVENTS2_ONUNLOAD = DISPID_EVMETH_ONUNLOAD; public const int DISPID_HTMLWINDOWEVENTS2_ONHELP = DISPID_EVMETH_ONHELP; public const int DISPID_HTMLWINDOWEVENTS2_ONFOCUS = DISPID_EVMETH_ONFOCUS; public const int DISPID_HTMLWINDOWEVENTS2_ONBLUR = DISPID_EVMETH_ONBLUR; public const int DISPID_HTMLWINDOWEVENTS2_ONERROR = DISPID_EVMETH_ONERROR; public const int DISPID_HTMLWINDOWEVENTS2_ONRESIZE = DISPID_EVMETH_ONRESIZE; public const int DISPID_HTMLWINDOWEVENTS2_ONSCROLL = DISPID_EVMETH_ONSCROLL; public const int DISPID_HTMLWINDOWEVENTS2_ONBEFOREUNLOAD = DISPID_EVMETH_ONBEFOREUNLOAD; public const int DISPID_HTMLWINDOWEVENTS2_ONBEFOREPRINT = DISPID_EVMETH_ONBEFOREPRINT; public const int DISPID_HTMLWINDOWEVENTS2_ONAFTERPRINT = DISPID_EVMETH_ONAFTERPRINT; // DISPIDs for interface IHTMLDOMNode public const int DISPID_IHTMLDOMNODE_NODETYPE = DISPID_ELEMENT + 46; public const int DISPID_IHTMLDOMNODE_PARENTNODE = DISPID_ELEMENT + 47; public const int DISPID_IHTMLDOMNODE_HASCHILDNODES = DISPID_ELEMENT + 48; public const int DISPID_IHTMLDOMNODE_CHILDNODES = DISPID_ELEMENT + 49; public const int DISPID_IHTMLDOMNODE_ATTRIBUTES = DISPID_ELEMENT + 50; public const int DISPID_IHTMLDOMNODE_INSERTBEFORE = DISPID_ELEMENT + 51; public const int DISPID_IHTMLDOMNODE_REMOVECHILD = DISPID_ELEMENT + 52; public const int DISPID_IHTMLDOMNODE_REPLACECHILD = DISPID_ELEMENT + 53; public const int DISPID_IHTMLDOMNODE_CLONENODE = DISPID_ELEMENT + 61; public const int DISPID_IHTMLDOMNODE_REMOVENODE = DISPID_ELEMENT + 66; public const int DISPID_IHTMLDOMNODE_SWAPNODE = DISPID_ELEMENT + 68; public const int DISPID_IHTMLDOMNODE_REPLACENODE = DISPID_ELEMENT + 67; public const int DISPID_IHTMLDOMNODE_APPENDCHILD = DISPID_ELEMENT + 73; public const int DISPID_IHTMLDOMNODE_NODENAME = DISPID_ELEMENT + 74; public const int DISPID_IHTMLDOMNODE_NODEVALUE = DISPID_ELEMENT + 75; public const int DISPID_IHTMLDOMNODE_FIRSTCHILD = DISPID_ELEMENT + 76; public const int DISPID_IHTMLDOMNODE_LASTCHILD = DISPID_ELEMENT + 77; public const int DISPID_IHTMLDOMNODE_PREVIOUSSIBLING = DISPID_ELEMENT + 78; public const int DISPID_IHTMLDOMNODE_NEXTSIBLING = DISPID_ELEMENT + 79; public const int DISPID_COLLECTION_MIN = 1000000; public const int DISPID_COLLECTION_MAX = 2999999; public const int DISPID_COLLECTION = (DISPID_NORMAL_FIRST + 500); public const int DISPID_VALUE = 0; /* The following DISPID is reserved to indicate the param * that is the right-hand-side (or "put" value) of a PropertyPut */ public const int DISPID_PROPERTYPUT = -3; /* DISPID reserved for the standard "NewEnum" method */ public const int DISPID_NEWENUM = -4; // DISPIDs for interface IHTMLDOMChildrenCollection public const int DISPID_IHTMLDOMCHILDRENCOLLECTION_LENGTH = DISPID_COLLECTION; public const int DISPID_IHTMLDOMCHILDRENCOLLECTION__NEWENUM = DISPID_NEWENUM; public const int DISPID_IHTMLDOMCHILDRENCOLLECTION_ITEM = DISPID_VALUE; // DISPIDs for interface IHTMLFramesCollection2 public const int DISPID_IHTMLFRAMESCOLLECTION2_ITEM = 0; public const int DISPID_IHTMLFRAMESCOLLECTION2_LENGTH = 1001; // DISPIDs for interface IHTMLWindow2 public const int DISPID_IHTMLWINDOW2_FRAMES = 1100; public const int DISPID_IHTMLWINDOW2_DEFAULTSTATUS = 1101; public const int DISPID_IHTMLWINDOW2_STATUS = 1102; public const int DISPID_IHTMLWINDOW2_SETTIMEOUT = 1172; public const int DISPID_IHTMLWINDOW2_CLEARTIMEOUT = 1104; public const int DISPID_IHTMLWINDOW2_ALERT = 1105; public const int DISPID_IHTMLWINDOW2_CONFIRM = 1110; public const int DISPID_IHTMLWINDOW2_PROMPT = 1111; public const int DISPID_IHTMLWINDOW2_IMAGE = 1125; public const int DISPID_IHTMLWINDOW2_LOCATION = 14; public const int DISPID_IHTMLWINDOW2_HISTORY = 2; public const int DISPID_IHTMLWINDOW2_CLOSE = 3; public const int DISPID_IHTMLWINDOW2_OPENER = 4; public const int DISPID_IHTMLWINDOW2_NAVIGATOR = 5; public const int DISPID_IHTMLWINDOW2_NAME = 11; public const int DISPID_IHTMLWINDOW2_PARENT = 12; public const int DISPID_IHTMLWINDOW2_OPEN = 13; public const int DISPID_IHTMLWINDOW2_SELF = 20; public const int DISPID_IHTMLWINDOW2_TOP = 21; public const int DISPID_IHTMLWINDOW2_WINDOW = 22; public const int DISPID_IHTMLWINDOW2_NAVIGATE = 25; public const int DISPID_IHTMLWINDOW2_ONFOCUS = DISPID_EVPROP_ONFOCUS; public const int DISPID_IHTMLWINDOW2_ONBLUR = DISPID_EVPROP_ONBLUR; public const int DISPID_IHTMLWINDOW2_ONLOAD = DISPID_EVPROP_ONLOAD; public const int DISPID_IHTMLWINDOW2_ONBEFOREUNLOAD = DISPID_EVPROP_ONBEFOREUNLOAD; public const int DISPID_IHTMLWINDOW2_ONUNLOAD = DISPID_EVPROP_ONUNLOAD; public const int DISPID_IHTMLWINDOW2_ONHELP = DISPID_EVPROP_ONHELP; public const int DISPID_IHTMLWINDOW2_ONERROR = DISPID_EVPROP_ONERROR; public const int DISPID_IHTMLWINDOW2_ONRESIZE = DISPID_EVPROP_ONRESIZE; public const int DISPID_IHTMLWINDOW2_ONSCROLL = DISPID_EVPROP_ONSCROLL; public const int DISPID_IHTMLWINDOW2_DOCUMENT = 1151; public const int DISPID_IHTMLWINDOW2_EVENT = 1152; public const int DISPID_IHTMLWINDOW2__NEWENUM = 1153; public const int DISPID_IHTMLWINDOW2_SHOWMODALDIALOG = 1154; public const int DISPID_IHTMLWINDOW2_SHOWHELP = 1155; public const int DISPID_IHTMLWINDOW2_SCREEN = 1156; public const int DISPID_IHTMLWINDOW2_OPTION = 1157; public const int DISPID_IHTMLWINDOW2_FOCUS = 1158; public const int DISPID_IHTMLWINDOW2_CLOSED = 23; public const int DISPID_IHTMLWINDOW2_BLUR = 1159; public const int DISPID_IHTMLWINDOW2_SCROLL = 1160; public const int DISPID_IHTMLWINDOW2_CLIENTINFORMATION = 1161; public const int DISPID_IHTMLWINDOW2_SETINTERVAL = 1173; public const int DISPID_IHTMLWINDOW2_CLEARINTERVAL = 1163; public const int DISPID_IHTMLWINDOW2_OFFSCREENBUFFERING = 1164; public const int DISPID_IHTMLWINDOW2_EXECSCRIPT = 1165; public const int DISPID_IHTMLWINDOW2_TOSTRING = 1166; public const int DISPID_IHTMLWINDOW2_SCROLLBY = 1167; public const int DISPID_IHTMLWINDOW2_SCROLLTO = 1168; public const int DISPID_IHTMLWINDOW2_MOVETO = 6; public const int DISPID_IHTMLWINDOW2_MOVEBY = 7; public const int DISPID_IHTMLWINDOW2_RESIZETO = 9; public const int DISPID_IHTMLWINDOW2_RESIZEBY = 8; public const int DISPID_IHTMLWINDOW2_EXTERNAL = 1169; // DISPIDS for interface IHtmlAncher public const int DISPID_ANCHOR = DISPID_NORMAL_FIRST; public const int STDPROPID_XOBJ_TABINDEX = DISPID_XOBJ_BASE + 0xF; public const int DISPID_IHTMLANCHORELEMENT_HREF = DISPID_VALUE; public const int DISPID_IHTMLANCHORELEMENT_TARGET = DISPID_ANCHOR + 3; public const int DISPID_IHTMLANCHORELEMENT_REL = DISPID_ANCHOR + 5; public const int DISPID_IHTMLANCHORELEMENT_REV = DISPID_ANCHOR + 6; public const int DISPID_IHTMLANCHORELEMENT_URN = DISPID_ANCHOR + 7; public const int DISPID_IHTMLANCHORELEMENT_METHODS = DISPID_ANCHOR + 8; public const int DISPID_IHTMLANCHORELEMENT_NAME = STDPROPID_XOBJ_NAME; public const int DISPID_IHTMLANCHORELEMENT_HOST = DISPID_ANCHOR + 12; public const int DISPID_IHTMLANCHORELEMENT_HOSTNAME = DISPID_ANCHOR + 13; public const int DISPID_IHTMLANCHORELEMENT_PATHNAME = DISPID_ANCHOR + 14; public const int DISPID_IHTMLANCHORELEMENT_PORT = DISPID_ANCHOR + 15; public const int DISPID_IHTMLANCHORELEMENT_PROTOCOL = DISPID_ANCHOR + 16; public const int DISPID_IHTMLANCHORELEMENT_SEARCH = DISPID_ANCHOR + 17; public const int DISPID_IHTMLANCHORELEMENT_HASH = DISPID_ANCHOR + 18; public const int DISPID_IHTMLANCHORELEMENT_ONBLUR = DISPID_EVPROP_ONBLUR; public const int DISPID_IHTMLANCHORELEMENT_ONFOCUS = DISPID_EVPROP_ONFOCUS; public const int DISPID_IHTMLANCHORELEMENT_ACCESSKEY = DISPID_SITE + 5; public const int DISPID_IHTMLANCHORELEMENT_PROTOCOLLONG = DISPID_ANCHOR + 31; public const int DISPID_IHTMLANCHORELEMENT_MIMETYPE = DISPID_ANCHOR + 30; public const int DISPID_IHTMLANCHORELEMENT_NAMEPROP = DISPID_ANCHOR + 32; public const int DISPID_IHTMLANCHORELEMENT_TABINDEX = STDPROPID_XOBJ_TABINDEX; public const int DISPID_IHTMLANCHORELEMENT_FOCUS = DISPID_SITE + 0; public const int DISPID_IHTMLANCHORELEMENT_BLUR = DISPID_SITE + 2; // DISPIDs for interface IHTMLImgElement public const int DISPID_IMGBASE = DISPID_NORMAL_FIRST; public const int DISPID_IMG = (DISPID_IMGBASE + 1000); public const int DISPID_INPUTIMAGE = (DISPID_IMGBASE + 1000); public const int DISPID_INPUT = (DISPID_TEXTSITE + 1000); public const int DISPID_INPUTTEXTBASE = (DISPID_INPUT + 1000); public const int DISPID_INPUTTEXT = (DISPID_INPUTTEXTBASE + 1000); public const int DISPID_SELECT = DISPID_NORMAL_FIRST; public const int DISPID_A_READYSTATE = (DISPID_A_FIRST + 116); // ready state public const int STDPROPID_XOBJ_CONTROLALIGN = (DISPID_XOBJ_BASE + 0x49); public const int STDPROPID_XOBJ_NAME = (DISPID_XOBJ_BASE + 0x0); public const int STDPROPID_XOBJ_WIDTH = (DISPID_XOBJ_BASE + 0x5); public const int STDPROPID_XOBJ_HEIGHT = (DISPID_XOBJ_BASE + 0x6); public const int DISPID_IHTMLIMGELEMENT_ISMAP = DISPID_IMG + 2; public const int DISPID_IHTMLIMGELEMENT_USEMAP = DISPID_IMG + 8; public const int DISPID_IHTMLIMGELEMENT_MIMETYPE = DISPID_IMG + 10; public const int DISPID_IHTMLIMGELEMENT_FILESIZE = DISPID_IMG + 11; public const int DISPID_IHTMLIMGELEMENT_FILECREATEDDATE = DISPID_IMG + 12; public const int DISPID_IHTMLIMGELEMENT_FILEMODIFIEDDATE = DISPID_IMG + 13; public const int DISPID_IHTMLIMGELEMENT_FILEUPDATEDDATE = DISPID_IMG + 14; public const int DISPID_IHTMLIMGELEMENT_PROTOCOL = DISPID_IMG + 15; public const int DISPID_IHTMLIMGELEMENT_HREF = DISPID_IMG + 16; public const int DISPID_IHTMLIMGELEMENT_NAMEPROP = DISPID_IMG + 17; public const int DISPID_IHTMLIMGELEMENT_BORDER = DISPID_IMGBASE + 4; public const int DISPID_IHTMLIMGELEMENT_VSPACE = DISPID_IMGBASE + 5; public const int DISPID_IHTMLIMGELEMENT_HSPACE = DISPID_IMGBASE + 6; public const int DISPID_IHTMLIMGELEMENT_ALT = DISPID_IMGBASE + 2; public const int DISPID_IHTMLIMGELEMENT_SRC = DISPID_IMGBASE + 3; public const int DISPID_IHTMLIMGELEMENT_LOWSRC = DISPID_IMGBASE + 7; public const int DISPID_IHTMLIMGELEMENT_VRML = DISPID_IMGBASE + 8; public const int DISPID_IHTMLIMGELEMENT_DYNSRC = DISPID_IMGBASE + 9; public const int DISPID_IHTMLIMGELEMENT_READYSTATE = DISPID_A_READYSTATE; public const int DISPID_IHTMLIMGELEMENT_COMPLETE = DISPID_IMGBASE + 10; public const int DISPID_IHTMLIMGELEMENT_LOOP = DISPID_IMGBASE + 11; public const int DISPID_IHTMLIMGELEMENT_ALIGN = STDPROPID_XOBJ_CONTROLALIGN; public const int DISPID_IHTMLIMGELEMENT_ONLOAD = DISPID_EVPROP_ONLOAD; public const int DISPID_IHTMLIMGELEMENT_ONERROR = DISPID_EVPROP_ONERROR; public const int DISPID_IHTMLIMGELEMENT_ONABORT = DISPID_EVPROP_ONABORT; public const int DISPID_IHTMLIMGELEMENT_NAME = STDPROPID_XOBJ_NAME; public const int DISPID_IHTMLIMGELEMENT_WIDTH = STDPROPID_XOBJ_WIDTH; public const int DISPID_IHTMLIMGELEMENT_HEIGHT = STDPROPID_XOBJ_HEIGHT; public const int DISPID_IHTMLIMGELEMENT_START = DISPID_IMGBASE + 13; // DISPIDs for interface IHTMLTxtRange public const int DISPID_RANGE = DISPID_NORMAL_FIRST; public const int DISPID_IHTMLTXTRANGE_HTMLTEXT = DISPID_RANGE + 3; public const int DISPID_IHTMLTXTRANGE_TEXT = DISPID_RANGE + 4; public const int DISPID_IHTMLTXTRANGE_PARENTELEMENT = DISPID_RANGE + 6; public const int DISPID_IHTMLTXTRANGE_DUPLICATE = DISPID_RANGE + 8; public const int DISPID_IHTMLTXTRANGE_INRANGE = DISPID_RANGE + 10; public const int DISPID_IHTMLTXTRANGE_ISEQUAL = DISPID_RANGE + 11; public const int DISPID_IHTMLTXTRANGE_SCROLLINTOVIEW = DISPID_RANGE + 12; public const int DISPID_IHTMLTXTRANGE_COLLAPSE = DISPID_RANGE + 13; public const int DISPID_IHTMLTXTRANGE_EXPAND = DISPID_RANGE + 14; public const int DISPID_IHTMLTXTRANGE_MOVE = DISPID_RANGE + 15; public const int DISPID_IHTMLTXTRANGE_MOVESTART = DISPID_RANGE + 16; public const int DISPID_IHTMLTXTRANGE_MOVEEND = DISPID_RANGE + 17; public const int DISPID_IHTMLTXTRANGE_SELECT = DISPID_RANGE + 24; public const int DISPID_IHTMLTXTRANGE_PASTEHTML = DISPID_RANGE + 26; public const int DISPID_IHTMLTXTRANGE_MOVETOELEMENTTEXT = DISPID_RANGE + 1; public const int DISPID_IHTMLTXTRANGE_SETENDPOINT = DISPID_RANGE + 25; public const int DISPID_IHTMLTXTRANGE_COMPAREENDPOINTS = DISPID_RANGE + 18; public const int DISPID_IHTMLTXTRANGE_FINDTEXT = DISPID_RANGE + 19; public const int DISPID_IHTMLTXTRANGE_MOVETOPOINT = DISPID_RANGE + 20; public const int DISPID_IHTMLTXTRANGE_GETBOOKMARK = DISPID_RANGE + 21; public const int DISPID_IHTMLTXTRANGE_MOVETOBOOKMARK = DISPID_RANGE + 9; public const int DISPID_IHTMLTXTRANGE_QUERYCOMMANDSUPPORTED = DISPID_RANGE + 27; public const int DISPID_IHTMLTXTRANGE_QUERYCOMMANDENABLED = DISPID_RANGE + 28; public const int DISPID_IHTMLTXTRANGE_QUERYCOMMANDSTATE = DISPID_RANGE + 29; public const int DISPID_IHTMLTXTRANGE_QUERYCOMMANDINDETERM = DISPID_RANGE + 30; public const int DISPID_IHTMLTXTRANGE_QUERYCOMMANDTEXT = DISPID_RANGE + 31; public const int DISPID_IHTMLTXTRANGE_QUERYCOMMANDVALUE = DISPID_RANGE + 32; public const int DISPID_IHTMLTXTRANGE_EXECCOMMAND = DISPID_RANGE + 33; public const int DISPID_IHTMLTXTRANGE_EXECCOMMANDSHOWHELP = DISPID_RANGE + 34; // DISPIDs for interface IHTMLDOMAttribute public const int DISPID_DOMATTRIBUTE = DISPID_NORMAL_FIRST; public const int DISPID_IHTMLDOMATTRIBUTE_NODENAME = DISPID_DOMATTRIBUTE; public const int DISPID_IHTMLDOMATTRIBUTE_NODEVALUE = DISPID_DOMATTRIBUTE + 2; public const int DISPID_IHTMLDOMATTRIBUTE_SPECIFIED = DISPID_DOMATTRIBUTE + 1; // DISPIDs for interface IHTMLAttributeCollection public const int DISPID_IHTMLATTRIBUTECOLLECTION_LENGTH = DISPID_COLLECTION; public const int DISPID_IHTMLATTRIBUTECOLLECTION__NEWENUM = DISPID_NEWENUM; public const int DISPID_IHTMLATTRIBUTECOLLECTION_ITEM = DISPID_VALUE; // DISPIDs for interface IHTMLStyleSheetsCollection public const int DISPID_STYLESHEETS_COL = DISPID_NORMAL_FIRST; public const int DISPID_IHTMLSTYLESHEETSCOLLECTION_LENGTH = DISPID_STYLESHEETS_COL + 1; public const int DISPID_IHTMLSTYLESHEETSCOLLECTION__NEWENUM = DISPID_NEWENUM; public const int DISPID_IHTMLSTYLESHEETSCOLLECTION_ITEM = DISPID_VALUE; // DISPIDs for interface IHTMLSelectionObject public const int DISPID_SELECTOBJ = DISPID_NORMAL_FIRST; public const int DISPID_IHTMLSELECTIONOBJECT_CREATERANGE = DISPID_SELECTOBJ + 1; public const int DISPID_IHTMLSELECTIONOBJECT_EMPTY = DISPID_SELECTOBJ + 2; public const int DISPID_IHTMLSELECTIONOBJECT_CLEAR = DISPID_SELECTOBJ + 3; public const int DISPID_IHTMLSELECTIONOBJECT_TYPE = DISPID_SELECTOBJ + 4; // DISPIDS for interface IHTMLBodyElement public const int DISPID_TEXTSITE = DISPID_NORMAL_FIRST; public const int DISPID_BODY = (DISPID_TEXTSITE + 1000); public const int DISPID_IHTMLBODYELEMENT_CREATETEXTRANGE = DISPID_BODY + 13; // DISPIDs for interface IHTMLDOMTextNode public const int DISPID_DOMTEXTNODE = DISPID_NORMAL_FIRST; public const int DISPID_IHTMLDOMTEXTNODE_DATA = DISPID_DOMTEXTNODE; public const int DISPID_IHTMLDOMTEXTNODE_TOSTRING = DISPID_DOMTEXTNODE + 1; public const int DISPID_IHTMLDOMTEXTNODE_LENGTH = DISPID_DOMTEXTNODE + 2; public const int DISPID_IHTMLDOMTEXTNODE_SPLITTEXT = DISPID_DOMTEXTNODE + 3; // DISPIDs for interface IHTMLDOMTextNode2 public const int DISPID_IHTMLDOMTEXTNODE2_SUBSTRINGDATA = DISPID_DOMTEXTNODE + 4; public const int DISPID_IHTMLDOMTEXTNODE2_APPENDDATA = DISPID_DOMTEXTNODE + 5; public const int DISPID_IHTMLDOMTEXTNODE2_INSERTDATA = DISPID_DOMTEXTNODE + 6; public const int DISPID_IHTMLDOMTEXTNODE2_DELETEDATA = DISPID_DOMTEXTNODE + 7; public const int DISPID_IHTMLDOMTEXTNODE2_REPLACEDATA = DISPID_DOMTEXTNODE + 8; // DISPIDs for interface IHTMLDOMAttribute2 public const int DISPID_IHTMLDOMATTRIBUTE2_NAME = DISPID_DOMATTRIBUTE + 3; public const int DISPID_IHTMLDOMATTRIBUTE2_VALUE = DISPID_DOMATTRIBUTE + 4; public const int DISPID_IHTMLDOMATTRIBUTE2_EXPANDO = DISPID_DOMATTRIBUTE + 5; public const int DISPID_IHTMLDOMATTRIBUTE2_NODETYPE = DISPID_DOMATTRIBUTE + 6; public const int DISPID_IHTMLDOMATTRIBUTE2_PARENTNODE = DISPID_DOMATTRIBUTE + 7; public const int DISPID_IHTMLDOMATTRIBUTE2_CHILDNODES = DISPID_DOMATTRIBUTE + 8; public const int DISPID_IHTMLDOMATTRIBUTE2_FIRSTCHILD = DISPID_DOMATTRIBUTE + 9; public const int DISPID_IHTMLDOMATTRIBUTE2_LASTCHILD = DISPID_DOMATTRIBUTE + 10; public const int DISPID_IHTMLDOMATTRIBUTE2_PREVIOUSSIBLING = DISPID_DOMATTRIBUTE + 11; public const int DISPID_IHTMLDOMATTRIBUTE2_NEXTSIBLING = DISPID_DOMATTRIBUTE + 12; public const int DISPID_IHTMLDOMATTRIBUTE2_ATTRIBUTES = DISPID_DOMATTRIBUTE + 13; public const int DISPID_IHTMLDOMATTRIBUTE2_OWNERDOCUMENT = DISPID_DOMATTRIBUTE + 14; public const int DISPID_IHTMLDOMATTRIBUTE2_INSERTBEFORE = DISPID_DOMATTRIBUTE + 15; public const int DISPID_IHTMLDOMATTRIBUTE2_REPLACECHILD = DISPID_DOMATTRIBUTE + 16; public const int DISPID_IHTMLDOMATTRIBUTE2_REMOVECHILD = DISPID_DOMATTRIBUTE + 17; public const int DISPID_IHTMLDOMATTRIBUTE2_APPENDCHILD = DISPID_DOMATTRIBUTE + 18; public const int DISPID_IHTMLDOMATTRIBUTE2_HASCHILDNODES = DISPID_DOMATTRIBUTE + 19; public const int DISPID_IHTMLDOMATTRIBUTE2_CLONENODE = DISPID_DOMATTRIBUTE + 20; public const int DISPID_HEDELEMS = DISPID_NORMAL_FIRST; // DISPIDs for interface IHTMLHeadElement public const int DISPID_IHTMLHEADELEMENT_PROFILE = DISPID_HEDELEMS + 1; public const int DISPID_A_VALUE = DISPID_A_FIRST + 101; // DISPIDs for interface IHTMLTitleElement public const int DISPID_IHTMLTITLEELEMENT_TEXT = DISPID_A_VALUE; // DISPIDs for interface IHTMLMetaElement public const int DISPID_IHTMLMETAELEMENT_HTTPEQUIV = DISPID_HEDELEMS + 1; public const int DISPID_IHTMLMETAELEMENT_CONTENT = DISPID_HEDELEMS + 2; public const int DISPID_IHTMLMETAELEMENT_NAME = STDPROPID_XOBJ_NAME; public const int DISPID_IHTMLMETAELEMENT_URL = DISPID_HEDELEMS + 3; public const int DISPID_IHTMLMETAELEMENT_CHARSET = DISPID_HEDELEMS + 13; // DISPIDs for interface IHTMLMetaElement2 public const int DISPID_IHTMLMETAELEMENT2_SCHEME = DISPID_HEDELEMS + 20; // DISPIDs for interface IHTMLBaseElement public const int DISPID_IHTMLBASEELEMENT_HREF = DISPID_HEDELEMS + 3; public const int DISPID_IHTMLBASEELEMENT_TARGET = DISPID_HEDELEMS + 4; // DISPIDs for interface IHTMLNextIdElement public const int DISPID_IHTMLNEXTIDELEMENT_N = DISPID_HEDELEMS + 12; public const int DISPID_A_COLOR = DISPID_A_FIRST + 2; public const int DISPID_A_FONTFACE = DISPID_A_FIRST + 18; public const int DISPID_A_FONTSIZE = DISPID_A_FIRST + 19; public const int DISPID_A_FONTSTYLE = DISPID_A_FIRST + 24; public const int DISPID_A_FONTVARIANT = DISPID_A_FIRST + 25; public const int DISPID_A_BASEFONT = DISPID_A_FIRST + 26; public const int DISPID_A_FONTWEIGHT = DISPID_A_FIRST + 27; // DISPIDs for interface IHTMLBaseFontElement public const int DISPID_IHTMLBASEFONTELEMENT_COLOR = DISPID_A_COLOR; public const int DISPID_IHTMLBASEFONTELEMENT_FACE = DISPID_A_FONTFACE; public const int DISPID_IHTMLBASEFONTELEMENT_SIZE = DISPID_A_BASEFONT; public const int DISPID_SCRIPT = DISPID_NORMAL_FIRST; // DISPIDs for interface IHTMLScriptElement public const int DISPID_IHTMLSCRIPTELEMENT_SRC = DISPID_SCRIPT + 1; public const int DISPID_IHTMLSCRIPTELEMENT_HTMLFOR = DISPID_SCRIPT + 4; public const int DISPID_IHTMLSCRIPTELEMENT_EVENT = DISPID_SCRIPT + 5; public const int DISPID_IHTMLSCRIPTELEMENT_TEXT = DISPID_SCRIPT + 6; public const int DISPID_IHTMLSCRIPTELEMENT_DEFER = DISPID_SCRIPT + 7; public const int DISPID_IHTMLSCRIPTELEMENT_READYSTATE = DISPID_A_READYSTATE; public const int DISPID_IHTMLSCRIPTELEMENT_ONERROR = DISPID_EVPROP_ONERROR; public const int DISPID_IHTMLSCRIPTELEMENT_TYPE = DISPID_SCRIPT + 9; private const int DISPID_COMMENTPDL = DISPID_NORMAL_FIRST; // DISPIDs for interface IHTMLCommentElement public const int DISPID_IHTMLCOMMENTELEMENT_TEXT = DISPID_COMMENTPDL + 1; public const int DISPID_IHTMLCOMMENTELEMENT_ATOMIC = DISPID_COMMENTPDL + 2; public const int DISPID_TABLE = DISPID_NORMAL_FIRST; public const int DISPID_TABLESECTION = DISPID_NORMAL_FIRST; public const int DISPID_TABLEROW = DISPID_NORMAL_FIRST; public const int DISPID_TABLECOL = DISPID_NORMAL_FIRST; public const int DISPID_A_BACKGROUNDIMAGE = DISPID_A_FIRST + 1; public const int DISPID_A_TABLEBORDERCOLOR = DISPID_A_FIRST + 28; public const int DISPID_A_TABLEBORDERCOLORLIGHT = DISPID_A_FIRST + 29; public const int DISPID_A_TABLEBORDERCOLORDARK = DISPID_A_FIRST + 30; public const int DISPID_A_TABLEVALIGN = DISPID_A_FIRST + 31; //unchecked((int)0x48) public const int STDPROPID_XOBJ_BLOCKALIGN = DISPID_XOBJ_BASE + 0x48; public const int DISPID_TABLECELL = DISPID_TEXTSITE + 1000; public const int DISPID_A_NOWRAP = DISPID_A_FIRST + 5; // DISPIDs for interface IHTMLTable public const int DISPID_IHTMLTABLE_COLS = DISPID_TABLE + 1; public const int DISPID_IHTMLTABLE_BORDER = DISPID_TABLE + 2; public const int DISPID_IHTMLTABLE_FRAME = DISPID_TABLE + 4; public const int DISPID_IHTMLTABLE_RULES = DISPID_TABLE + 3; public const int DISPID_IHTMLTABLE_CELLSPACING = DISPID_TABLE + 5; public const int DISPID_IHTMLTABLE_CELLPADDING = DISPID_TABLE + 6; public const int DISPID_IHTMLTABLE_BACKGROUND = DISPID_A_BACKGROUNDIMAGE; public const int DISPID_IHTMLTABLE_BGCOLOR = DISPID_BACKCOLOR; public const int DISPID_IHTMLTABLE_BORDERCOLOR = DISPID_A_TABLEBORDERCOLOR; public const int DISPID_IHTMLTABLE_BORDERCOLORLIGHT = DISPID_A_TABLEBORDERCOLORLIGHT; public const int DISPID_IHTMLTABLE_BORDERCOLORDARK = DISPID_A_TABLEBORDERCOLORDARK; public const int DISPID_IHTMLTABLE_ALIGN = STDPROPID_XOBJ_CONTROLALIGN; public const int DISPID_IHTMLTABLE_REFRESH = DISPID_TABLE + 15; public const int DISPID_IHTMLTABLE_ROWS = DISPID_TABLE + 16; public const int DISPID_IHTMLTABLE_WIDTH = STDPROPID_XOBJ_WIDTH; public const int DISPID_IHTMLTABLE_HEIGHT = STDPROPID_XOBJ_HEIGHT; public const int DISPID_IHTMLTABLE_DATAPAGESIZE = DISPID_TABLE + 17; public const int DISPID_IHTMLTABLE_NEXTPAGE = DISPID_TABLE + 18; public const int DISPID_IHTMLTABLE_PREVIOUSPAGE = DISPID_TABLE + 19; public const int DISPID_IHTMLTABLE_THEAD = DISPID_TABLE + 20; public const int DISPID_IHTMLTABLE_TFOOT = DISPID_TABLE + 21; public const int DISPID_IHTMLTABLE_TBODIES = DISPID_TABLE + 24; public const int DISPID_IHTMLTABLE_CAPTION = DISPID_TABLE + 25; public const int DISPID_IHTMLTABLE_CREATETHEAD = DISPID_TABLE + 26; public const int DISPID_IHTMLTABLE_DELETETHEAD = DISPID_TABLE + 27; public const int DISPID_IHTMLTABLE_CREATETFOOT = DISPID_TABLE + 28; public const int DISPID_IHTMLTABLE_DELETETFOOT = DISPID_TABLE + 29; public const int DISPID_IHTMLTABLE_CREATECAPTION = DISPID_TABLE + 30; public const int DISPID_IHTMLTABLE_DELETECAPTION = DISPID_TABLE + 31; public const int DISPID_IHTMLTABLE_INSERTROW = DISPID_TABLE + 32; public const int DISPID_IHTMLTABLE_DELETEROW = DISPID_TABLE + 33; public const int DISPID_IHTMLTABLE_READYSTATE = DISPID_A_READYSTATE; public const int DISPID_IHTMLTABLE_ONREADYSTATECHANGE = DISPID_EVPROP_ONREADYSTATECHANGE; // DISPIDs for interface IHTMLTable2 public const int DISPID_IHTMLTABLE2_FIRSTPAGE = DISPID_TABLE + 35; public const int DISPID_IHTMLTABLE2_LASTPAGE = DISPID_TABLE + 36; public const int DISPID_IHTMLTABLE2_CELLS = DISPID_TABLE + 37; public const int DISPID_IHTMLTABLE2_MOVEROW = DISPID_TABLE + 38; // DISPIDs for interface IHTMLTable3 public const int DISPID_IHTMLTABLE3_SUMMARY = DISPID_TABLE + 39; // DISPIDs for interface IHTMLTableCol public const int DISPID_IHTMLTABLECOL_SPAN = DISPID_TABLECOL + 1; public const int DISPID_IHTMLTABLECOL_WIDTH = STDPROPID_XOBJ_WIDTH; public const int DISPID_IHTMLTABLECOL_ALIGN = STDPROPID_XOBJ_BLOCKALIGN; public const int DISPID_IHTMLTABLECOL_VALIGN = DISPID_A_TABLEVALIGN; // DISPIDs for interface IHTMLTableCol2 public const int DISPID_IHTMLTABLECOL2_CH = DISPID_TABLECOL + 2; public const int DISPID_IHTMLTABLECOL2_CHOFF = DISPID_TABLECOL + 3; // DISPIDs for interface IHTMLTableSection public const int DISPID_IHTMLTABLESECTION_ALIGN = STDPROPID_XOBJ_BLOCKALIGN; public const int DISPID_IHTMLTABLESECTION_VALIGN = DISPID_A_TABLEVALIGN; public const int DISPID_IHTMLTABLESECTION_BGCOLOR = DISPID_BACKCOLOR; public const int DISPID_IHTMLTABLESECTION_ROWS = DISPID_TABLESECTION; public const int DISPID_IHTMLTABLESECTION_INSERTROW = DISPID_TABLESECTION + 1; public const int DISPID_IHTMLTABLESECTION_DELETEROW = DISPID_TABLESECTION + 2; // DISPIDs for interface IHTMLTableSection2 public const int DISPID_IHTMLTABLESECTION2_MOVEROW = DISPID_TABLESECTION + 3; // DISPIDs for interface IHTMLTableSection3 public const int DISPID_IHTMLTABLESECTION3_CH = DISPID_TABLESECTION + 4; public const int DISPID_IHTMLTABLESECTION3_CHOFF = DISPID_TABLESECTION + 5; // DISPIDs for interface IHTMLTableRow public const int DISPID_IHTMLTABLEROW_ALIGN = STDPROPID_XOBJ_BLOCKALIGN; public const int DISPID_IHTMLTABLEROW_VALIGN = DISPID_A_TABLEVALIGN; public const int DISPID_IHTMLTABLEROW_BGCOLOR = DISPID_BACKCOLOR; public const int DISPID_IHTMLTABLEROW_BORDERCOLOR = DISPID_A_TABLEBORDERCOLOR; public const int DISPID_IHTMLTABLEROW_BORDERCOLORLIGHT = DISPID_A_TABLEBORDERCOLORLIGHT; public const int DISPID_IHTMLTABLEROW_BORDERCOLORDARK = DISPID_A_TABLEBORDERCOLORDARK; public const int DISPID_IHTMLTABLEROW_ROWINDEX = DISPID_TABLEROW; public const int DISPID_IHTMLTABLEROW_SECTIONROWINDEX = DISPID_TABLEROW + 1; public const int DISPID_IHTMLTABLEROW_CELLS = DISPID_TABLEROW + 2; public const int DISPID_IHTMLTABLEROW_INSERTCELL = DISPID_TABLEROW + 3; public const int DISPID_IHTMLTABLEROW_DELETECELL = DISPID_TABLEROW + 4; // DISPIDs for interface IHTMLTableRow2 public const int DISPID_IHTMLTABLEROW2_HEIGHT = STDPROPID_XOBJ_HEIGHT; // DISPIDs for interface IHTMLTableRow3 public const int DISPID_IHTMLTABLEROW3_CH = DISPID_TABLEROW + 9; public const int DISPID_IHTMLTABLEROW3_CHOFF = DISPID_TABLEROW + 10; // DISPIDs for interface IHTMLTableRowMetrics public const int DISPID_IHTMLTABLEROWMETRICS_CLIENTHEIGHT = DISPID_SITE + 19; public const int DISPID_IHTMLTABLEROWMETRICS_CLIENTWIDTH = DISPID_SITE + 20; public const int DISPID_IHTMLTABLEROWMETRICS_CLIENTTOP = DISPID_SITE + 21; public const int DISPID_IHTMLTABLEROWMETRICS_CLIENTLEFT = DISPID_SITE + 22; // DISPIDs for interface IHTMLTableCell public const int DISPID_IHTMLTABLECELL_ROWSPAN = DISPID_TABLECELL + 1; public const int DISPID_IHTMLTABLECELL_COLSPAN = DISPID_TABLECELL + 2; public const int DISPID_IHTMLTABLECELL_ALIGN = STDPROPID_XOBJ_BLOCKALIGN; public const int DISPID_IHTMLTABLECELL_VALIGN = DISPID_A_TABLEVALIGN; public const int DISPID_IHTMLTABLECELL_BGCOLOR = DISPID_BACKCOLOR; public const int DISPID_IHTMLTABLECELL_NOWRAP = DISPID_A_NOWRAP; public const int DISPID_IHTMLTABLECELL_BACKGROUND = DISPID_A_BACKGROUNDIMAGE; public const int DISPID_IHTMLTABLECELL_BORDERCOLOR = DISPID_A_TABLEBORDERCOLOR; public const int DISPID_IHTMLTABLECELL_BORDERCOLORLIGHT = DISPID_A_TABLEBORDERCOLORLIGHT; public const int DISPID_IHTMLTABLECELL_BORDERCOLORDARK = DISPID_A_TABLEBORDERCOLORDARK; public const int DISPID_IHTMLTABLECELL_WIDTH = STDPROPID_XOBJ_WIDTH; public const int DISPID_IHTMLTABLECELL_HEIGHT = STDPROPID_XOBJ_HEIGHT; public const int DISPID_IHTMLTABLECELL_CELLINDEX = DISPID_TABLECELL + 3; // DISPIDs for interface IHTMLTableCell public const int DISPID_IHTMLTABLECELL2_ABBR = DISPID_TABLECELL + 4; public const int DISPID_IHTMLTABLECELL2_AXIS = DISPID_TABLECELL + 5; public const int DISPID_IHTMLTABLECELL2_CH = DISPID_TABLECELL + 6; public const int DISPID_IHTMLTABLECELL2_CHOFF = DISPID_TABLECELL + 7; public const int DISPID_IHTMLTABLECELL2_HEADERS = DISPID_TABLECELL + 8; public const int DISPID_IHTMLTABLECELL2_SCOPE = DISPID_TABLECELL + 9; // DISPIDs for event set HTMLElementEvents2 public const int DISPID_HTMLELEMENTEVENTS2_ONHELP = DISPID_EVMETH_ONHELP; public const int DISPID_HTMLELEMENTEVENTS2_ONCLICK = DISPID_EVMETH_ONCLICK; public const int DISPID_HTMLELEMENTEVENTS2_ONDBLCLICK = DISPID_EVMETH_ONDBLCLICK; public const int DISPID_HTMLELEMENTEVENTS2_ONKEYPRESS = DISPID_EVMETH_ONKEYPRESS; public const int DISPID_HTMLELEMENTEVENTS2_ONKEYDOWN = DISPID_EVMETH_ONKEYDOWN; public const int DISPID_HTMLELEMENTEVENTS2_ONKEYUP = DISPID_EVMETH_ONKEYUP; public const int DISPID_HTMLELEMENTEVENTS2_ONMOUSEOUT = DISPID_EVMETH_ONMOUSEOUT; public const int DISPID_HTMLELEMENTEVENTS2_ONMOUSEOVER = DISPID_EVMETH_ONMOUSEOVER; public const int DISPID_HTMLELEMENTEVENTS2_ONMOUSEMOVE = DISPID_EVMETH_ONMOUSEMOVE; public const int DISPID_HTMLELEMENTEVENTS2_ONMOUSEDOWN = DISPID_EVMETH_ONMOUSEDOWN; public const int DISPID_HTMLELEMENTEVENTS2_ONMOUSEUP = DISPID_EVMETH_ONMOUSEUP; public const int DISPID_HTMLELEMENTEVENTS2_ONSELECTSTART = DISPID_EVMETH_ONSELECTSTART; public const int DISPID_HTMLELEMENTEVENTS2_ONFILTERCHANGE = DISPID_EVMETH_ONFILTER; public const int DISPID_HTMLELEMENTEVENTS2_ONDRAGSTART = DISPID_EVMETH_ONDRAGSTART; public const int DISPID_HTMLELEMENTEVENTS2_ONBEFOREUPDATE = DISPID_EVMETH_ONBEFOREUPDATE; public const int DISPID_HTMLELEMENTEVENTS2_ONAFTERUPDATE = DISPID_EVMETH_ONAFTERUPDATE; public const int DISPID_HTMLELEMENTEVENTS2_ONERRORUPDATE = DISPID_EVMETH_ONERRORUPDATE; public const int DISPID_HTMLELEMENTEVENTS2_ONROWEXIT = DISPID_EVMETH_ONROWEXIT; public const int DISPID_HTMLELEMENTEVENTS2_ONROWENTER = DISPID_EVMETH_ONROWENTER; public const int DISPID_HTMLELEMENTEVENTS2_ONDATASETCHANGED = DISPID_EVMETH_ONDATASETCHANGED; public const int DISPID_HTMLELEMENTEVENTS2_ONDATAAVAILABLE = DISPID_EVMETH_ONDATAAVAILABLE; public const int DISPID_HTMLELEMENTEVENTS2_ONDATASETCOMPLETE = DISPID_EVMETH_ONDATASETCOMPLETE; public const int DISPID_HTMLELEMENTEVENTS2_ONLOSECAPTURE = DISPID_EVMETH_ONLOSECAPTURE; public const int DISPID_HTMLELEMENTEVENTS2_ONPROPERTYCHANGE = DISPID_EVMETH_ONPROPERTYCHANGE; public const int DISPID_HTMLELEMENTEVENTS2_ONSCROLL = DISPID_EVMETH_ONSCROLL; public const int DISPID_HTMLELEMENTEVENTS2_ONFOCUS = DISPID_EVMETH_ONFOCUS; public const int DISPID_HTMLELEMENTEVENTS2_ONBLUR = DISPID_EVMETH_ONBLUR; public const int DISPID_HTMLELEMENTEVENTS2_ONRESIZE = DISPID_EVMETH_ONRESIZE; public const int DISPID_HTMLELEMENTEVENTS2_ONDRAG = DISPID_EVMETH_ONDRAG; public const int DISPID_HTMLELEMENTEVENTS2_ONDRAGEND = DISPID_EVMETH_ONDRAGEND; public const int DISPID_HTMLELEMENTEVENTS2_ONDRAGENTER = DISPID_EVMETH_ONDRAGENTER; public const int DISPID_HTMLELEMENTEVENTS2_ONDRAGOVER = DISPID_EVMETH_ONDRAGOVER; public const int DISPID_HTMLELEMENTEVENTS2_ONDRAGLEAVE = DISPID_EVMETH_ONDRAGLEAVE; public const int DISPID_HTMLELEMENTEVENTS2_ONDROP = DISPID_EVMETH_ONDROP; public const int DISPID_HTMLELEMENTEVENTS2_ONBEFORECUT = DISPID_EVMETH_ONBEFORECUT; public const int DISPID_HTMLELEMENTEVENTS2_ONCUT = DISPID_EVMETH_ONCUT; public const int DISPID_HTMLELEMENTEVENTS2_ONBEFORECOPY = DISPID_EVMETH_ONBEFORECOPY; public const int DISPID_HTMLELEMENTEVENTS2_ONCOPY = DISPID_EVMETH_ONCOPY; public const int DISPID_HTMLELEMENTEVENTS2_ONBEFOREPASTE = DISPID_EVMETH_ONBEFOREPASTE; public const int DISPID_HTMLELEMENTEVENTS2_ONPASTE = DISPID_EVMETH_ONPASTE; public const int DISPID_HTMLELEMENTEVENTS2_ONCONTEXTMENU = DISPID_EVMETH_ONCONTEXTMENU; public const int DISPID_HTMLELEMENTEVENTS2_ONROWSDELETE = DISPID_EVMETH_ONROWSDELETE; public const int DISPID_HTMLELEMENTEVENTS2_ONROWSINSERTED = DISPID_EVMETH_ONROWSINSERTED; public const int DISPID_HTMLELEMENTEVENTS2_ONCELLCHANGE = DISPID_EVMETH_ONCELLCHANGE; public const int DISPID_HTMLELEMENTEVENTS2_ONREADYSTATECHANGE = DISPID_EVMETH_ONREADYSTATECHANGE; public const int DISPID_HTMLELEMENTEVENTS2_ONLAYOUTCOMPLETE = DISPID_EVMETH_ONLAYOUTCOMPLETE; public const int DISPID_HTMLELEMENTEVENTS2_ONPAGE = DISPID_EVMETH_ONPAGE; public const int DISPID_HTMLELEMENTEVENTS2_ONMOUSEENTER = DISPID_EVMETH_ONMOUSEENTER; public const int DISPID_HTMLELEMENTEVENTS2_ONMOUSELEAVE = DISPID_EVMETH_ONMOUSELEAVE; public const int DISPID_HTMLELEMENTEVENTS2_ONACTIVATE = DISPID_EVMETH_ONACTIVATE; public const int DISPID_HTMLELEMENTEVENTS2_ONDEACTIVATE = DISPID_EVMETH_ONDEACTIVATE; public const int DISPID_HTMLELEMENTEVENTS2_ONBEFOREDEACTIVATE = DISPID_EVMETH_ONBEFOREDEACTIVATE; public const int DISPID_HTMLELEMENTEVENTS2_ONBEFOREACTIVATE = DISPID_EVMETH_ONBEFOREACTIVATE; public const int DISPID_HTMLELEMENTEVENTS2_ONFOCUSIN = DISPID_EVMETH_ONFOCUSIN; public const int DISPID_HTMLELEMENTEVENTS2_ONFOCUSOUT = DISPID_EVMETH_ONFOCUSOUT; public const int DISPID_HTMLELEMENTEVENTS2_ONMOVE = DISPID_EVMETH_ONMOVE; public const int DISPID_HTMLELEMENTEVENTS2_ONCONTROLSELECT = DISPID_EVMETH_ONCONTROLSELECT; public const int DISPID_HTMLELEMENTEVENTS2_ONMOVESTART = DISPID_EVMETH_ONMOVESTART; public const int DISPID_HTMLELEMENTEVENTS2_ONMOVEEND = DISPID_EVMETH_ONMOVEEND; public const int DISPID_HTMLELEMENTEVENTS2_ONRESIZESTART = DISPID_EVMETH_ONRESIZESTART; public const int DISPID_HTMLELEMENTEVENTS2_ONRESIZEEND = DISPID_EVMETH_ONRESIZEEND; public const int DISPID_HTMLELEMENTEVENTS2_ONMOUSEWHEEL = DISPID_EVMETH_ONMOUSEWHEEL; public const int DISPID_HR = DISPID_NORMAL_FIRST; public const int DISPID_IHTMLHRELEMENT_ALIGN = STDPROPID_XOBJ_BLOCKALIGN; public const int DISPID_IHTMLHRELEMENT_COLOR = DISPID_A_COLOR; public const int DISPID_IHTMLHRELEMENT_NOSHADE = DISPID_HR + 1; public const int DISPID_IHTMLHRELEMENT_WIDTH = STDPROPID_XOBJ_WIDTH; public const int DISPID_IHTMLHRELEMENT_SIZE = STDPROPID_XOBJ_HEIGHT; // DISPIDs for interface IHTMLInputElement public const int DISPID_IHTMLINPUTELEMENT_TYPE = DISPID_INPUT; public const int DISPID_IHTMLINPUTELEMENT_VALUE = DISPID_A_VALUE; public const int DISPID_IHTMLINPUTELEMENT_NAME = STDPROPID_XOBJ_NAME; public const int DISPID_IHTMLINPUTELEMENT_STATUS = DISPID_INPUT + 1; public const int DISPID_IHTMLINPUTELEMENT_DISABLED = STDPROPID_XOBJ_DISABLED; public const int DISPID_IHTMLINPUTELEMENT_FORM = DISPID_SITE + 4; public const int DISPID_IHTMLINPUTELEMENT_SIZE = DISPID_INPUT + 2; public const int DISPID_IHTMLINPUTELEMENT_MAXLENGTH = DISPID_INPUT + 3; public const int DISPID_IHTMLINPUTELEMENT_SELECT = DISPID_INPUT + 4; public const int DISPID_IHTMLINPUTELEMENT_ONCHANGE = DISPID_EVPROP_ONCHANGE; public const int DISPID_IHTMLINPUTELEMENT_ONSELECT = DISPID_EVPROP_ONSELECT; public const int DISPID_IHTMLINPUTELEMENT_DEFAULTVALUE = DISPID_DEFAULTVALUE; public const int DISPID_IHTMLINPUTELEMENT_READONLY = DISPID_INPUT + 5; public const int DISPID_IHTMLINPUTELEMENT_CREATETEXTRANGE = DISPID_INPUT + 6; public const int DISPID_IHTMLINPUTELEMENT_INDETERMINATE = DISPID_INPUT + 7; public const int DISPID_IHTMLINPUTELEMENT_DEFAULTCHECKED = DISPID_INPUT + 8; public const int DISPID_IHTMLINPUTELEMENT_CHECKED = DISPID_INPUT + 9; public const int DISPID_IHTMLINPUTELEMENT_BORDER = DISPID_INPUT + 12; public const int DISPID_IHTMLINPUTELEMENT_VSPACE = DISPID_INPUT + 13; public const int DISPID_IHTMLINPUTELEMENT_HSPACE = DISPID_INPUT + 14; public const int DISPID_IHTMLINPUTELEMENT_ALT = DISPID_INPUT + 10; public const int DISPID_IHTMLINPUTELEMENT_SRC = DISPID_INPUT + 11; public const int DISPID_IHTMLINPUTELEMENT_LOWSRC = DISPID_INPUT + 15; public const int DISPID_IHTMLINPUTELEMENT_VRML = DISPID_INPUT + 16; public const int DISPID_IHTMLINPUTELEMENT_DYNSRC = DISPID_INPUT + 17; public const int DISPID_IHTMLINPUTELEMENT_READYSTATE = DISPID_A_READYSTATE; public const int DISPID_IHTMLINPUTELEMENT_COMPLETE = DISPID_INPUT + 18; public const int DISPID_IHTMLINPUTELEMENT_LOOP = DISPID_INPUT + 19; public const int DISPID_IHTMLINPUTELEMENT_ALIGN = STDPROPID_XOBJ_CONTROLALIGN; public const int DISPID_IHTMLINPUTELEMENT_ONLOAD = DISPID_EVPROP_ONLOAD; public const int DISPID_IHTMLINPUTELEMENT_ONERROR = DISPID_EVPROP_ONERROR; public const int DISPID_IHTMLINPUTELEMENT_ONABORT = DISPID_EVPROP_ONABORT; public const int DISPID_IHTMLINPUTELEMENT_WIDTH = STDPROPID_XOBJ_WIDTH; public const int DISPID_IHTMLINPUTELEMENT_HEIGHT = STDPROPID_XOBJ_HEIGHT; public const int DISPID_IHTMLINPUTELEMENT_START = DISPID_INPUT + 20; // DISPIDs for interface IHTMLSelectElement public const int DISPID_IHTMLSELECTELEMENT_SIZE = DISPID_SELECT + 2; public const int DISPID_IHTMLSELECTELEMENT_MULTIPLE = DISPID_SELECT + 3; public const int DISPID_IHTMLSELECTELEMENT_NAME = STDPROPID_XOBJ_NAME; public const int DISPID_IHTMLSELECTELEMENT_OPTIONS = DISPID_SELECT + 5; public const int DISPID_IHTMLSELECTELEMENT_ONCHANGE = DISPID_EVPROP_ONCHANGE; public const int DISPID_IHTMLSELECTELEMENT_SELECTEDINDEX = DISPID_SELECT + 10; public const int DISPID_IHTMLSELECTELEMENT_TYPE = DISPID_SELECT + 12; public const int DISPID_IHTMLSELECTELEMENT_VALUE = DISPID_SELECT + 11; public const int DISPID_IHTMLSELECTELEMENT_DISABLED = STDPROPID_XOBJ_DISABLED; public const int DISPID_IHTMLSELECTELEMENT_FORM = DISPID_SITE + 4; public const int DISPID_IHTMLSELECTELEMENT_ADD = DISPID_COLLECTION + 3; public const int DISPID_IHTMLSELECTELEMENT_REMOVE = DISPID_COLLECTION + 4; public const int DISPID_IHTMLSELECTELEMENT_LENGTH = DISPID_COLLECTION; public const int DISPID_IHTMLSELECTELEMENT__NEWENUM = DISPID_NEWENUM; public const int DISPID_IHTMLSELECTELEMENT_ITEM = DISPID_VALUE; public const int DISPID_IHTMLSELECTELEMENT_TAGS = DISPID_COLLECTION + 2; // DISPIDs for interface IHTMLTextAreaElement public const int DISPID_TEXTAREA = (DISPID_INPUTTEXT + 1000); public const int DISPID_MARQUEE = (DISPID_TEXTAREA + 1000); public const int DISPID_RICHTEXT = (DISPID_MARQUEE + 1000); public const int DISPID_IHTMLTEXTAREAELEMENT_TYPE = DISPID_INPUT; public const int DISPID_IHTMLTEXTAREAELEMENT_VALUE = DISPID_A_VALUE; public const int DISPID_IHTMLTEXTAREAELEMENT_NAME = STDPROPID_XOBJ_NAME; public const int DISPID_IHTMLTEXTAREAELEMENT_STATUS = DISPID_INPUT + 1; public const int DISPID_IHTMLTEXTAREAELEMENT_DISABLED = STDPROPID_XOBJ_DISABLED; public const int DISPID_IHTMLTEXTAREAELEMENT_FORM = DISPID_SITE + 4; public const int DISPID_IHTMLTEXTAREAELEMENT_DEFAULTVALUE = DISPID_DEFAULTVALUE; public const int DISPID_IHTMLTEXTAREAELEMENT_SELECT = DISPID_RICHTEXT + 5; public const int DISPID_IHTMLTEXTAREAELEMENT_ONCHANGE = DISPID_EVPROP_ONCHANGE; public const int DISPID_IHTMLTEXTAREAELEMENT_ONSELECT = DISPID_EVPROP_ONSELECT; public const int DISPID_IHTMLTEXTAREAELEMENT_READONLY = DISPID_RICHTEXT + 4; public const int DISPID_IHTMLTEXTAREAELEMENT_ROWS = DISPID_RICHTEXT + 1; public const int DISPID_IHTMLTEXTAREAELEMENT_COLS = DISPID_RICHTEXT + 2; public const int DISPID_IHTMLTEXTAREAELEMENT_WRAP = DISPID_RICHTEXT + 3; public const int DISPID_IHTMLTEXTAREAELEMENT_CREATETEXTRANGE = DISPID_RICHTEXT + 6; // DISPIDs for interface IHTMLFormElement public const int DISPID_FORM = DISPID_NORMAL_FIRST; public const int DISPID_IHTMLFORMELEMENT_ACTION = DISPID_FORM + 1; public const int DISPID_IHTMLFORMELEMENT_DIR = DISPID_A_DIR; public const int DISPID_IHTMLFORMELEMENT_ENCODING = DISPID_FORM + 3; public const int DISPID_IHTMLFORMELEMENT_METHOD = DISPID_FORM + 4; public const int DISPID_IHTMLFORMELEMENT_ELEMENTS = DISPID_FORM + 5; public const int DISPID_IHTMLFORMELEMENT_TARGET = DISPID_FORM + 6; public const int DISPID_IHTMLFORMELEMENT_NAME = STDPROPID_XOBJ_NAME; public const int DISPID_IHTMLFORMELEMENT_ONSUBMIT = DISPID_EVPROP_ONSUBMIT; public const int DISPID_IHTMLFORMELEMENT_ONRESET = DISPID_EVPROP_ONRESET; public const int DISPID_IHTMLFORMELEMENT_SUBMIT = DISPID_FORM + 9; public const int DISPID_IHTMLFORMELEMENT_RESET = DISPID_FORM + 10; public const int DISPID_IHTMLFORMELEMENT_LENGTH = DISPID_COLLECTION; public const int DISPID_IHTMLFORMELEMENT__NEWENUM = DISPID_NEWENUM; public const int DISPID_IHTMLFORMELEMENT_ITEM = DISPID_VALUE; public const int DISPID_IHTMLFORMELEMENT_TAGS = DISPID_COLLECTION + 2; public const int DISPID_IHTMLCONTROLELEMENT_TABINDEX = STDPROPID_XOBJ_TABINDEX; public const int DISPID_IHTMLCONTROLELEMENT_FOCUS = DISPID_SITE + 0; public const int DISPID_IHTMLCONTROLELEMENT_ACCESSKEY = DISPID_SITE + 5; public const int DISPID_IHTMLCONTROLELEMENT_ONBLUR = DISPID_EVPROP_ONBLUR; public const int DISPID_IHTMLCONTROLELEMENT_ONFOCUS = DISPID_EVPROP_ONFOCUS; public const int DISPID_IHTMLCONTROLELEMENT_ONRESIZE = DISPID_EVPROP_ONRESIZE; public const int DISPID_IHTMLCONTROLELEMENT_BLUR = DISPID_SITE + 2; public const int DISPID_IHTMLCONTROLELEMENT_ADDFILTER = DISPID_SITE + 17; public const int DISPID_IHTMLCONTROLELEMENT_REMOVEFILTER = DISPID_SITE + 18; public const int DISPID_IHTMLCONTROLELEMENT_CLIENTHEIGHT = DISPID_SITE + 19; public const int DISPID_IHTMLCONTROLELEMENT_CLIENTWIDTH = DISPID_SITE + 20; public const int DISPID_IHTMLCONTROLELEMENT_CLIENTTOP = DISPID_SITE + 21; public const int DISPID_IHTMLCONTROLELEMENT_CLIENTLEFT = DISPID_SITE + 22; public const int DISPID_IHTMLCONTROLRANGE_SELECT = DISPID_RANGE + 2; public const int DISPID_IHTMLCONTROLRANGE_ADD = DISPID_RANGE + 3; public const int DISPID_IHTMLCONTROLRANGE_REMOVE = DISPID_RANGE + 4; public const int DISPID_IHTMLCONTROLRANGE_ITEM = DISPID_VALUE; public const int DISPID_IHTMLCONTROLRANGE_SCROLLINTOVIEW = DISPID_RANGE + 6; public const int DISPID_IHTMLCONTROLRANGE_QUERYCOMMANDSUPPORTED = DISPID_RANGE + 7; public const int DISPID_IHTMLCONTROLRANGE_QUERYCOMMANDENABLED = DISPID_RANGE + 8; public const int DISPID_IHTMLCONTROLRANGE_QUERYCOMMANDSTATE = DISPID_RANGE + 9; public const int DISPID_IHTMLCONTROLRANGE_QUERYCOMMANDINDETERM = DISPID_RANGE + 10; public const int DISPID_IHTMLCONTROLRANGE_QUERYCOMMANDTEXT = DISPID_RANGE + 11; public const int DISPID_IHTMLCONTROLRANGE_QUERYCOMMANDVALUE = DISPID_RANGE + 12; public const int DISPID_IHTMLCONTROLRANGE_EXECCOMMAND = DISPID_RANGE + 13; public const int DISPID_IHTMLCONTROLRANGE_EXECCOMMANDSHOWHELP = DISPID_RANGE + 14; public const int DISPID_IHTMLCONTROLRANGE_COMMONPARENTELEMENT = DISPID_RANGE + 15; public const int DISPID_IHTMLCONTROLRANGE_LENGTH = DISPID_RANGE + 5; // DISPIDs for interface IHTMLOptionElement public const int DISPID_OPTION = DISPID_NORMAL_FIRST; public const int DISPID_IHTMLOPTIONELEMENT_SELECTED = DISPID_OPTION + 1; public const int DISPID_IHTMLOPTIONELEMENT_VALUE = DISPID_OPTION + 2; public const int DISPID_IHTMLOPTIONELEMENT_DEFAULTSELECTED = DISPID_OPTION + 3; public const int DISPID_IHTMLOPTIONELEMENT_INDEX = DISPID_OPTION + 5; public const int DISPID_IHTMLOPTIONELEMENT_TEXT = DISPID_OPTION + 4; public const int DISPID_IHTMLOPTIONELEMENT_FORM = DISPID_OPTION + 6; // DISPIDs for interface IHTMLFrameSetElement public const int DISPID_FRAMESET = DISPID_NORMAL_FIRST; public const int DISPID_IHTMLFRAMESETELEMENT_ROWS = DISPID_FRAMESET; public const int DISPID_IHTMLFRAMESETELEMENT_COLS = DISPID_FRAMESET + 1; public const int DISPID_IHTMLFRAMESETELEMENT_BORDER = DISPID_FRAMESET + 2; public const int DISPID_IHTMLFRAMESETELEMENT_BORDERCOLOR = DISPID_FRAMESET + 3; public const int DISPID_IHTMLFRAMESETELEMENT_FRAMEBORDER = DISPID_FRAMESET + 4; public const int DISPID_IHTMLFRAMESETELEMENT_FRAMESPACING = DISPID_FRAMESET + 5; public const int DISPID_IHTMLFRAMESETELEMENT_NAME = STDPROPID_XOBJ_NAME; public const int DISPID_IHTMLFRAMESETELEMENT_ONLOAD = DISPID_EVPROP_ONLOAD; public const int DISPID_IHTMLFRAMESETELEMENT_ONUNLOAD = DISPID_EVPROP_ONUNLOAD; public const int DISPID_IHTMLFRAMESETELEMENT_ONBEFOREUNLOAD = DISPID_EVPROP_ONBEFOREUNLOAD; // DISPIDs for interface IHTMLFrameBase public const int DISPID_FRAMESITE = (DISPID_SITE + 1000); public const int DISPID_FRAME = (DISPID_FRAMESITE + 1000); public const int DISPID_IFRAME = (DISPID_FRAMESITE + 1000); public const int DISPID_IHTMLFRAMEBASE_SRC = DISPID_FRAMESITE + 0; public const int DISPID_IHTMLFRAMEBASE_NAME = STDPROPID_XOBJ_NAME; public const int DISPID_IHTMLFRAMEBASE_BORDER = DISPID_FRAMESITE + 2; public const int DISPID_IHTMLFRAMEBASE_FRAMEBORDER = DISPID_FRAMESITE + 3; public const int DISPID_IHTMLFRAMEBASE_FRAMESPACING = DISPID_FRAMESITE + 4; public const int DISPID_IHTMLFRAMEBASE_MARGINWIDTH = DISPID_FRAMESITE + 5; public const int DISPID_IHTMLFRAMEBASE_MARGINHEIGHT = DISPID_FRAMESITE + 6; public const int DISPID_IHTMLFRAMEBASE_NORESIZE = DISPID_FRAMESITE + 7; public const int DISPID_IHTMLFRAMEBASE_SCROLLING = DISPID_FRAMESITE + 8; // DISPIDs for interface IHTMLFrameBase2 public const int DISPID_A_ALLOWTRANSPARENCY = (DISPID_A_FIRST + 206); public const int DISPID_IHTMLFRAMEBASE2_CONTENTWINDOW = DISPID_FRAMESITE + 9; public const int DISPID_IHTMLFRAMEBASE2_ONLOAD = DISPID_EVPROP_ONLOAD; public const int DISPID_IHTMLFRAMEBASE2_ONREADYSTATECHANGE = DISPID_EVPROP_ONREADYSTATECHANGE; public const int DISPID_IHTMLFRAMEBASE2_READYSTATE = DISPID_A_READYSTATE; public const int DISPID_IHTMLFRAMEBASE2_ALLOWTRANSPARENCY = DISPID_A_ALLOWTRANSPARENCY; // DISPIDs for interface IHTMLHeaderElement public const int DISPID_IHTMLHEADERELEMENT_ALIGN = STDPROPID_XOBJ_BLOCKALIGN; // DISPIDs for interface IHTMLIFrameElement public const int DISPID_IHTMLIFRAMEELEMENT_VSPACE = DISPID_IFRAME + 1; public const int DISPID_IHTMLIFRAMEELEMENT_HSPACE = DISPID_IFRAME + 2; public const int DISPID_IHTMLIFRAMEELEMENT_ALIGN = STDPROPID_XOBJ_CONTROLALIGN; // DISPIDs for interface IHTMLIFrameElement2 public const int DISPID_IHTMLIFRAMEELEMENT2_HEIGHT = STDPROPID_XOBJ_HEIGHT; public const int DISPID_IHTMLIFRAMEELEMENT2_WIDTH = STDPROPID_XOBJ_WIDTH; // DISPIDs for interface IHTMLImageElementFactory public const int DISPID_IHTMLIMAGEELEMENTFACTORY_CREATE = DISPID_VALUE; // DISPIDs for interface IHTMLInputButtonElement public const int DISPID_IHTMLINPUTBUTTONELEMENT_TYPE = DISPID_INPUT; public const int DISPID_IHTMLINPUTBUTTONELEMENT_VALUE = DISPID_A_VALUE; public const int DISPID_IHTMLINPUTBUTTONELEMENT_NAME = STDPROPID_XOBJ_NAME; public const int DISPID_IHTMLINPUTBUTTONELEMENT_STATUS = DISPID_INPUT + 21; public const int DISPID_IHTMLINPUTBUTTONELEMENT_DISABLED = STDPROPID_XOBJ_DISABLED; public const int DISPID_IHTMLINPUTBUTTONELEMENT_FORM = DISPID_SITE + 4; public const int DISPID_IHTMLINPUTBUTTONELEMENT_CREATETEXTRANGE = DISPID_INPUT + 6; // DISPIDs for interface IHTMLInputFileElement public const int DISPID_IHTMLINPUTFILEELEMENT_TYPE = DISPID_INPUT; public const int DISPID_IHTMLINPUTFILEELEMENT_NAME = STDPROPID_XOBJ_NAME; public const int DISPID_IHTMLINPUTFILEELEMENT_STATUS = DISPID_INPUT + 21; public const int DISPID_IHTMLINPUTFILEELEMENT_DISABLED = STDPROPID_XOBJ_DISABLED; public const int DISPID_IHTMLINPUTFILEELEMENT_FORM = DISPID_SITE + 4; public const int DISPID_IHTMLINPUTFILEELEMENT_SIZE = DISPID_INPUT + 2; public const int DISPID_IHTMLINPUTFILEELEMENT_MAXLENGTH = DISPID_INPUT + 3; public const int DISPID_IHTMLINPUTFILEELEMENT_SELECT = DISPID_INPUT + 4; public const int DISPID_IHTMLINPUTFILEELEMENT_ONCHANGE = DISPID_EVPROP_ONCHANGE; public const int DISPID_IHTMLINPUTFILEELEMENT_ONSELECT = DISPID_EVPROP_ONSELECT; public const int DISPID_IHTMLINPUTFILEELEMENT_VALUE = DISPID_A_VALUE; // DISPIDs for interface IHTMLInputHiddenElement public const int DISPID_IHTMLINPUTHIDDENELEMENT_TYPE = DISPID_INPUT; public const int DISPID_IHTMLINPUTHIDDENELEMENT_VALUE = DISPID_A_VALUE; public const int DISPID_IHTMLINPUTHIDDENELEMENT_NAME = STDPROPID_XOBJ_NAME; public const int DISPID_IHTMLINPUTHIDDENELEMENT_STATUS = DISPID_INPUT + 21; public const int DISPID_IHTMLINPUTHIDDENELEMENT_DISABLED = STDPROPID_XOBJ_DISABLED; public const int DISPID_IHTMLINPUTHIDDENELEMENT_FORM = DISPID_SITE + 4; public const int DISPID_IHTMLINPUTHIDDENELEMENT_CREATETEXTRANGE = DISPID_INPUT + 6; // DISPIDs for interface IHTMLInputImage public const int DISPID_IHTMLINPUTIMAGE_TYPE = DISPID_INPUT; public const int DISPID_IHTMLINPUTIMAGE_DISABLED = STDPROPID_XOBJ_DISABLED; public const int DISPID_IHTMLINPUTIMAGE_BORDER = DISPID_INPUT + 12; public const int DISPID_IHTMLINPUTIMAGE_VSPACE = DISPID_INPUT + 13; public const int DISPID_IHTMLINPUTIMAGE_HSPACE = DISPID_INPUT + 14; public const int DISPID_IHTMLINPUTIMAGE_ALT = DISPID_INPUT + 10; public const int DISPID_IHTMLINPUTIMAGE_SRC = DISPID_INPUT + 11; public const int DISPID_IHTMLINPUTIMAGE_LOWSRC = DISPID_INPUT + 15; public const int DISPID_IHTMLINPUTIMAGE_VRML = DISPID_INPUT + 16; public const int DISPID_IHTMLINPUTIMAGE_DYNSRC = DISPID_INPUT + 17; public const int DISPID_IHTMLINPUTIMAGE_READYSTATE = DISPID_A_READYSTATE; public const int DISPID_IHTMLINPUTIMAGE_COMPLETE = DISPID_INPUT + 18; public const int DISPID_IHTMLINPUTIMAGE_LOOP = DISPID_INPUT + 19; public const int DISPID_IHTMLINPUTIMAGE_ALIGN = STDPROPID_XOBJ_CONTROLALIGN; public const int DISPID_IHTMLINPUTIMAGE_ONLOAD = DISPID_EVPROP_ONLOAD; public const int DISPID_IHTMLINPUTIMAGE_ONERROR = DISPID_EVPROP_ONERROR; public const int DISPID_IHTMLINPUTIMAGE_ONABORT = DISPID_EVPROP_ONABORT; public const int DISPID_IHTMLINPUTIMAGE_NAME = STDPROPID_XOBJ_NAME; public const int DISPID_IHTMLINPUTIMAGE_WIDTH = STDPROPID_XOBJ_WIDTH; public const int DISPID_IHTMLINPUTIMAGE_HEIGHT = STDPROPID_XOBJ_HEIGHT; public const int DISPID_IHTMLINPUTIMAGE_START = DISPID_INPUT + 20; // DISPIDs for interface IHTMLInputTextElement public const int DISPID_IHTMLINPUTTEXTELEMENT_TYPE = DISPID_INPUT; public const int DISPID_IHTMLINPUTTEXTELEMENT_VALUE = DISPID_A_VALUE; public const int DISPID_IHTMLINPUTTEXTELEMENT_NAME = STDPROPID_XOBJ_NAME; public const int DISPID_IHTMLINPUTTEXTELEMENT_STATUS = DISPID_INPUT + 21; public const int DISPID_IHTMLINPUTTEXTELEMENT_DISABLED = STDPROPID_XOBJ_DISABLED; public const int DISPID_IHTMLINPUTTEXTELEMENT_FORM = DISPID_SITE + 4; public const int DISPID_IHTMLINPUTTEXTELEMENT_DEFAULTVALUE = DISPID_DEFAULTVALUE; public const int DISPID_IHTMLINPUTTEXTELEMENT_SIZE = DISPID_INPUT + 2; public const int DISPID_IHTMLINPUTTEXTELEMENT_MAXLENGTH = DISPID_INPUT + 3; public const int DISPID_IHTMLINPUTTEXTELEMENT_SELECT = DISPID_INPUT + 4; public const int DISPID_IHTMLINPUTTEXTELEMENT_ONCHANGE = DISPID_EVPROP_ONCHANGE; public const int DISPID_IHTMLINPUTTEXTELEMENT_ONSELECT = DISPID_EVPROP_ONSELECT; public const int DISPID_IHTMLINPUTTEXTELEMENT_READONLY = DISPID_INPUT + 5; public const int DISPID_IHTMLINPUTTEXTELEMENT_CREATETEXTRANGE = DISPID_INPUT + 6; // DISPIDs for interface IHTMLLIElement public const int DISPID_LI = DISPID_NORMAL_FIRST; public const int DISPID_A_LISTTYPE = (DISPID_A_FIRST + 17); public const int DISPID_IHTMLLIELEMENT_TYPE = DISPID_A_LISTTYPE; public const int DISPID_IHTMLLIELEMENT_VALUE = DISPID_LI + 1; // DISPIDs for interface IHTMLAnchorElement2 public const int DISPID_IHTMLANCHORELEMENT2_CHARSET = DISPID_ANCHOR + 23; public const int DISPID_IHTMLANCHORELEMENT2_COORDS = DISPID_ANCHOR + 24; public const int DISPID_IHTMLANCHORELEMENT2_HREFLANG = DISPID_ANCHOR + 25; public const int DISPID_IHTMLANCHORELEMENT2_SHAPE = DISPID_ANCHOR + 26; public const int DISPID_IHTMLANCHORELEMENT2_TYPE = DISPID_ANCHOR + 27; // DISPIDs for interface IHTMLAreaElement public const int DISPID_AREA = DISPID_NORMAL_FIRST; public const int DISPID_IHTMLAREAELEMENT_SHAPE = DISPID_AREA + 1; public const int DISPID_IHTMLAREAELEMENT_COORDS = DISPID_AREA + 2; public const int DISPID_IHTMLAREAELEMENT_HREF = DISPID_VALUE; public const int DISPID_IHTMLAREAELEMENT_TARGET = DISPID_AREA + 4; public const int DISPID_IHTMLAREAELEMENT_ALT = DISPID_AREA + 5; public const int DISPID_IHTMLAREAELEMENT_NOHREF = DISPID_AREA + 6; public const int DISPID_IHTMLAREAELEMENT_HOST = DISPID_AREA + 7; public const int DISPID_IHTMLAREAELEMENT_HOSTNAME = DISPID_AREA + 8; public const int DISPID_IHTMLAREAELEMENT_PATHNAME = DISPID_AREA + 9; public const int DISPID_IHTMLAREAELEMENT_PORT = DISPID_AREA + 10; public const int DISPID_IHTMLAREAELEMENT_PROTOCOL = DISPID_AREA + 11; public const int DISPID_IHTMLAREAELEMENT_SEARCH = DISPID_AREA + 12; public const int DISPID_IHTMLAREAELEMENT_HASH = DISPID_AREA + 13; public const int DISPID_IHTMLAREAELEMENT_ONBLUR = DISPID_EVPROP_ONBLUR; public const int DISPID_IHTMLAREAELEMENT_ONFOCUS = DISPID_EVPROP_ONFOCUS; public const int DISPID_IHTMLAREAELEMENT_TABINDEX = STDPROPID_XOBJ_TABINDEX; public const int DISPID_IHTMLAREAELEMENT_FOCUS = DISPID_SITE + 0; public const int DISPID_IHTMLAREAELEMENT_BLUR = DISPID_SITE + 2; // DISPIDs for interface IHTMLAreasCollection public const int DISPID_IHTMLAREASCOLLECTION_LENGTH = DISPID_COLLECTION; public const int DISPID_IHTMLAREASCOLLECTION__NEWENUM = DISPID_NEWENUM; public const int DISPID_IHTMLAREASCOLLECTION_ITEM = DISPID_VALUE; public const int DISPID_IHTMLAREASCOLLECTION_TAGS = DISPID_COLLECTION + 2; public const int DISPID_IHTMLAREASCOLLECTION_ADD = DISPID_COLLECTION + 3; public const int DISPID_IHTMLAREASCOLLECTION_REMOVE = DISPID_COLLECTION + 4; // DISPIDs for interface IHTMLButtonElement public const int DISPID_BUTTON = (DISPID_RICHTEXT + 1000); public const int DISPID_IHTMLBUTTONELEMENT_TYPE = DISPID_INPUT; public const int DISPID_IHTMLBUTTONELEMENT_VALUE = DISPID_A_VALUE; public const int DISPID_IHTMLBUTTONELEMENT_NAME = STDPROPID_XOBJ_NAME; public const int DISPID_IHTMLBUTTONELEMENT_STATUS = DISPID_BUTTON + 1; public const int DISPID_IHTMLBUTTONELEMENT_DISABLED = STDPROPID_XOBJ_DISABLED; public const int DISPID_IHTMLBUTTONELEMENT_FORM = DISPID_SITE + 4; public const int DISPID_IHTMLBUTTONELEMENT_CREATETEXTRANGE = DISPID_BUTTON + 2; // DISPIDs for interface IHTMLBRElement public const int DISPID_A_CLEAR = (DISPID_A_FIRST + 16); public const int DISPID_IHTMLBRELEMENT_CLEAR = DISPID_A_CLEAR; // DISPIDs for interface IHTMLCurrentStyle public const int DISPID_A_BACKGROUNDPOSX = (DISPID_A_FIRST + 33); public const int DISPID_A_BACKGROUNDPOSY = (DISPID_A_FIRST + 34); public const int DISPID_A_BACKGROUNDREPEAT = (DISPID_A_FIRST + 44); public const int DISPID_A_BACKGROUNDATTACHMENT = (DISPID_A_FIRST + 45); public const int DISPID_A_BACKGROUNDPOSITION = (DISPID_A_FIRST + 46); public const int DISPID_A_WORDSPACING = (DISPID_A_FIRST + 47); public const int DISPID_A_VERTICALALIGN = (DISPID_A_FIRST + 48); public const int DISPID_A_BORDER = (DISPID_A_FIRST + 49); public const int DISPID_A_BORDERTOP = (DISPID_A_FIRST + 50); public const int DISPID_A_BORDERRIGHT = (DISPID_A_FIRST + 51); public const int DISPID_A_BORDERBOTTOM = (DISPID_A_FIRST + 52); public const int DISPID_A_BORDERLEFT = (DISPID_A_FIRST + 53); public const int DISPID_A_BORDERCOLOR = (DISPID_A_FIRST + 54); public const int DISPID_A_BORDERTOPCOLOR = (DISPID_A_FIRST + 55); public const int DISPID_A_BORDERRIGHTCOLOR = (DISPID_A_FIRST + 56); public const int DISPID_A_BORDERBOTTOMCOLOR = (DISPID_A_FIRST + 57); public const int DISPID_A_BORDERLEFTCOLOR = (DISPID_A_FIRST + 58); public const int DISPID_A_BORDERWIDTH = (DISPID_A_FIRST + 59); public const int DISPID_A_BORDERTOPWIDTH = (DISPID_A_FIRST + 60); public const int DISPID_A_BORDERRIGHTWIDTH = (DISPID_A_FIRST + 61); public const int DISPID_A_BORDERBOTTOMWIDTH = (DISPID_A_FIRST + 62); public const int DISPID_A_BORDERLEFTWIDTH = (DISPID_A_FIRST + 63); public const int DISPID_A_BORDERSTYLE = (DISPID_A_FIRST + 64); public const int DISPID_A_BORDERTOPSTYLE = (DISPID_A_FIRST + 65); public const int DISPID_A_BORDERRIGHTSTYLE = (DISPID_A_FIRST + 66); public const int DISPID_A_BORDERBOTTOMSTYLE = (DISPID_A_FIRST + 67); public const int DISPID_A_BORDERLEFTSTYLE = (DISPID_A_FIRST + 68); public const int STDPROPID_XOBJ_LEFT = (DISPID_XOBJ_BASE + 0x3); public const int STDPROPID_XOBJ_TOP = (DISPID_XOBJ_BASE + 0x4); public const int DISPID_A_PADDING = (DISPID_A_FIRST + 11); public const int DISPID_A_PADDINGTOP = (DISPID_A_FIRST + 12); public const int DISPID_A_PADDINGRIGHT = (DISPID_A_FIRST + 13); public const int DISPID_A_PADDINGBOTTOM = (DISPID_A_FIRST + 14); public const int DISPID_A_PADDINGLEFT = (DISPID_A_FIRST + 15); public const int DISPID_A_TEXTDECORATION = (DISPID_A_FIRST + 35); public const int DISPID_A_VISIBILITY = (DISPID_A_FIRST + 80); public const int DISPID_A_ZINDEX = (DISPID_A_FIRST + 91); public const int DISPID_A_CLIP = (DISPID_A_FIRST + 92); public const int DISPID_A_CLIPRECTTOP = (DISPID_A_FIRST + 93); public const int DISPID_A_CLIPRECTRIGHT = (DISPID_A_FIRST + 94); public const int DISPID_A_CLIPRECTBOTTOM = (DISPID_A_FIRST + 95); public const int DISPID_A_CLIPRECTLEFT = (DISPID_A_FIRST + 96); public const int DISPID_A_FONTFACESRC = (DISPID_A_FIRST + 97); public const int DISPID_A_TABLELAYOUT = (DISPID_A_FIRST + 98); public const int DISPID_A_TEXTTRANSFORM = (DISPID_A_FIRST + 4); public const int DISPID_A_LINEHEIGHT = (DISPID_A_FIRST + 6); public const int DISPID_A_TEXTINDENT = (DISPID_A_FIRST + 7); public const int DISPID_A_LETTERSPACING = (DISPID_A_FIRST + 8); public const int DISPID_A_OVERFLOW = (DISPID_A_FIRST + 10); public const int DISPID_A_MARGIN = (DISPID_A_FIRST + 36); public const int DISPID_A_MARGINTOP = (DISPID_A_FIRST + 37); public const int DISPID_A_MARGINRIGHT = (DISPID_A_FIRST + 38); public const int DISPID_A_MARGINBOTTOM = (DISPID_A_FIRST + 39); public const int DISPID_A_MARGINLEFT = (DISPID_A_FIRST + 40); public const int DISPID_A_LISTSTYLETYPE = (DISPID_A_FIRST + 72); public const int DISPID_A_LISTSTYLEPOSITION = (DISPID_A_FIRST + 73); public const int DISPID_A_LISTSTYLEIMAGE = (DISPID_A_FIRST + 74); public const int DISPID_A_LISTSTYLE = (DISPID_A_FIRST + 75); public const int DISPID_A_WHITESPACE = (DISPID_A_FIRST + 76); public const int DISPID_A_PAGEBREAKBEFORE = (DISPID_A_FIRST + 77); public const int DISPID_A_PAGEBREAKAFTER = (DISPID_A_FIRST + 78); public const int DISPID_A_SCROLL = (DISPID_A_FIRST + 79); public const int DISPID_A_CURSOR = (DISPID_A_FIRST + 102); public const int DISPID_A_BORDERCOLLAPSE = (DISPID_A_FIRST + 84); public const int DISPID_A_BEHAVIOR = (DISPID_A_FIRST + 115); // xtags public const int STDPROPID_XOBJ_RIGHT = (DISPID_XOBJ_BASE + 0x4D); public const int STDPROPID_XOBJ_BOTTOM = (DISPID_XOBJ_BASE + 0x4E); public const int DISPID_A_IMEMODE = (DISPID_A_FIRST + 120); public const int DISPID_A_RUBYALIGN = (DISPID_A_FIRST + 121); public const int DISPID_A_RUBYPOSITION = (DISPID_A_FIRST + 122); public const int DISPID_A_RUBYOVERHANG = (DISPID_A_FIRST + 123); //;begin_internal public const int DISPID_INTERNAL_ONBEHAVIOR_CONTENTREADY = (DISPID_A_FIRST + 124); public const int DISPID_INTERNAL_ONBEHAVIOR_DOCUMENTREADY = (DISPID_A_FIRST + 125); public const int DISPID_INTERNAL_CDOMCHILDRENPTRCACHE = (DISPID_A_FIRST + 126); //;end_internal public const int DISPID_A_LAYOUTGRIDCHAR = (DISPID_A_FIRST + 127); public const int DISPID_A_LAYOUTGRIDLINE = (DISPID_A_FIRST + 128); public const int DISPID_A_LAYOUTGRIDMODE = (DISPID_A_FIRST + 129); public const int DISPID_A_LAYOUTGRIDTYPE = (DISPID_A_FIRST + 130); public const int DISPID_A_LAYOUTGRID = (DISPID_A_FIRST + 131); public const int DISPID_A_TEXTAUTOSPACE = (DISPID_A_FIRST + 132); public const int DISPID_A_LINEBREAK = (DISPID_A_FIRST + 133); public const int DISPID_A_WORDBREAK = (DISPID_A_FIRST + 134); public const int DISPID_A_TEXTJUSTIFY = (DISPID_A_FIRST + 135); public const int DISPID_A_TEXTJUSTIFYTRIM = (DISPID_A_FIRST + 136); public const int DISPID_A_TEXTKASHIDA = (DISPID_A_FIRST + 137); public const int DISPID_A_OVERFLOWX = (DISPID_A_FIRST + 139); public const int DISPID_A_OVERFLOWY = (DISPID_A_FIRST + 140); public const int DISPID_A_HTCDISPATCHITEM_VALUE = (DISPID_A_FIRST + 141); public const int DISPID_A_DOCFRAGMENT = (DISPID_A_FIRST + 142); public const int DISPID_A_HTCDD_ELEMENT = (DISPID_A_FIRST + 143); public const int DISPID_A_HTCDD_CREATEEVENTOBJECT = (DISPID_A_FIRST + 144); public const int DISPID_A_URNATOM = (DISPID_A_FIRST + 145); public const int DISPID_A_UNIQUEPEERNUMBER = (DISPID_A_FIRST + 146); public const int DISPID_A_ACCELERATOR = (DISPID_A_FIRST + 147); //;begin_internal public const int DISPID_INTERNAL_ONBEHAVIOR_APPLYSTYLE = (DISPID_A_FIRST + 148); public const int DISPID_INTERNAL_RUNTIMESTYLEAA = (DISPID_A_FIRST + 149); public const int DISPID_A_HTCDISPATCHITEM_VALUE_SCRIPTSONLY = (DISPID_A_FIRST + 150); //;end_internal public const int DISPID_A_EXTENDEDTAGDESC = (DISPID_A_FIRST + 151); public const int DISPID_A_ROTATE = (DISPID_A_FIRST + 152); public const int DISPID_A_ZOOM = (DISPID_A_FIRST + 153); public const int DISPID_A_HTCDD_PROTECTEDELEMENT = (DISPID_A_FIRST + 154); public const int DISPID_A_LAYOUTFLOW = (DISPID_A_FIRST + 155); public const int DISPID_A_HTCDD_ISMARKUPSHARED = (DISPID_A_FIRST + 157); public const int DISPID_A_WORDWRAP = (DISPID_A_FIRST + 158); public const int DISPID_A_TEXTUNDERLINEPOSITION = (DISPID_A_FIRST + 159); public const int DISPID_A_HASLAYOUT = (DISPID_A_FIRST + 160); public const int DISPID_A_MEDIA = (DISPID_A_FIRST + 161); public const int DISPID_A_EDITABLE = (DISPID_A_FIRST + 162); public const int DISPID_A_HIDEFOCUS = (DISPID_A_FIRST + 163); public const int DISPID_A_SCROLLBARBASECOLOR = (DISPID_A_FIRST + 180); public const int DISPID_A_SCROLLBARFACECOLOR = (DISPID_A_FIRST + 181); public const int DISPID_A_SCROLLBAR3DLIGHTCOLOR = (DISPID_A_FIRST + 182); public const int DISPID_A_SCROLLBARSHADOWCOLOR = (DISPID_A_FIRST + 183); public const int DISPID_A_SCROLLBARHIGHLIGHTCOLOR = (DISPID_A_FIRST + 184); public const int DISPID_A_SCROLLBARDARKSHADOWCOLOR = (DISPID_A_FIRST + 185); public const int DISPID_A_SCROLLBARARROWCOLOR = (DISPID_A_FIRST + 186); public const int DISPID_A_SCROLLBARTRACKCOLOR = (DISPID_A_FIRST + 196); public const int DISPID_A_WRITINGMODE = (DISPID_A_FIRST + 192); public const int DISPID_A_FILTER = (DISPID_A_FIRST + 82); public const int DISPID_A_TEXTALIGNLAST = (DISPID_A_FIRST + 203); public const int DISPID_A_TEXTKASHIDASPACE = (DISPID_A_FIRST + 204); public const int DISPID_A_ISBLOCK = (DISPID_A_FIRST + 208); public const int DISPID_A_TEXTOVERFLOW = (DISPID_A_FIRST + 209); //;begin_internal public const int DISPID_INTERNAL_CATTRIBUTECOLLPTRCACHE = (DISPID_A_FIRST + 210); //;end_internal public const int DISPID_A_MINHEIGHT = (DISPID_A_FIRST + 211); //;begin_internal public const int DISPID_INTERNAL_INVOKECONTEXTDOCUMENT = (DISPID_A_FIRST + 212); public const int DISPID_A_POSITION = (DISPID_A_FIRST + 90); public const int DISPID_A_FLOAT = (DISPID_A_FIRST + 70); public const int DISPID_A_DISPLAY = (DISPID_A_FIRST + 71); public const int DISPID_IHTMLCURRENTSTYLE_POSITION = DISPID_A_POSITION; public const int DISPID_IHTMLCURRENTSTYLE_STYLEFLOAT = DISPID_A_FLOAT; public const int DISPID_IHTMLCURRENTSTYLE_COLOR = DISPID_A_COLOR; public const int DISPID_IHTMLCURRENTSTYLE_BACKGROUNDCOLOR = DISPID_BACKCOLOR; public const int DISPID_IHTMLCURRENTSTYLE_FONTFAMILY = DISPID_A_FONTFACE; public const int DISPID_IHTMLCURRENTSTYLE_FONTSTYLE = DISPID_A_FONTSTYLE; public const int DISPID_IHTMLCURRENTSTYLE_FONTVARIANT = DISPID_A_FONTVARIANT; public const int DISPID_IHTMLCURRENTSTYLE_FONTWEIGHT = DISPID_A_FONTWEIGHT; public const int DISPID_IHTMLCURRENTSTYLE_FONTSIZE = DISPID_A_FONTSIZE; public const int DISPID_IHTMLCURRENTSTYLE_BACKGROUNDIMAGE = DISPID_A_BACKGROUNDIMAGE; public const int DISPID_IHTMLCURRENTSTYLE_BACKGROUNDPOSITIONX = DISPID_A_BACKGROUNDPOSX; public const int DISPID_IHTMLCURRENTSTYLE_BACKGROUNDPOSITIONY = DISPID_A_BACKGROUNDPOSY; public const int DISPID_IHTMLCURRENTSTYLE_BACKGROUNDREPEAT = DISPID_A_BACKGROUNDREPEAT; public const int DISPID_IHTMLCURRENTSTYLE_BORDERLEFTCOLOR = DISPID_A_BORDERLEFTCOLOR; public const int DISPID_IHTMLCURRENTSTYLE_BORDERTOPCOLOR = DISPID_A_BORDERTOPCOLOR; public const int DISPID_IHTMLCURRENTSTYLE_BORDERRIGHTCOLOR = DISPID_A_BORDERRIGHTCOLOR; public const int DISPID_IHTMLCURRENTSTYLE_BORDERBOTTOMCOLOR = DISPID_A_BORDERBOTTOMCOLOR; public const int DISPID_IHTMLCURRENTSTYLE_BORDERTOPSTYLE = DISPID_A_BORDERTOPSTYLE; public const int DISPID_IHTMLCURRENTSTYLE_BORDERRIGHTSTYLE = DISPID_A_BORDERRIGHTSTYLE; public const int DISPID_IHTMLCURRENTSTYLE_BORDERBOTTOMSTYLE = DISPID_A_BORDERBOTTOMSTYLE; public const int DISPID_IHTMLCURRENTSTYLE_BORDERLEFTSTYLE = DISPID_A_BORDERLEFTSTYLE; public const int DISPID_IHTMLCURRENTSTYLE_BORDERTOPWIDTH = DISPID_A_BORDERTOPWIDTH; public const int DISPID_IHTMLCURRENTSTYLE_BORDERRIGHTWIDTH = DISPID_A_BORDERRIGHTWIDTH; public const int DISPID_IHTMLCURRENTSTYLE_BORDERBOTTOMWIDTH = DISPID_A_BORDERBOTTOMWIDTH; public const int DISPID_IHTMLCURRENTSTYLE_BORDERLEFTWIDTH = DISPID_A_BORDERLEFTWIDTH; public const int DISPID_IHTMLCURRENTSTYLE_LEFT = STDPROPID_XOBJ_LEFT; public const int DISPID_IHTMLCURRENTSTYLE_TOP = STDPROPID_XOBJ_TOP; public const int DISPID_IHTMLCURRENTSTYLE_WIDTH = STDPROPID_XOBJ_WIDTH; public const int DISPID_IHTMLCURRENTSTYLE_HEIGHT = STDPROPID_XOBJ_HEIGHT; public const int DISPID_IHTMLCURRENTSTYLE_PADDINGLEFT = DISPID_A_PADDINGLEFT; public const int DISPID_IHTMLCURRENTSTYLE_PADDINGTOP = DISPID_A_PADDINGTOP; public const int DISPID_IHTMLCURRENTSTYLE_PADDINGRIGHT = DISPID_A_PADDINGRIGHT; public const int DISPID_IHTMLCURRENTSTYLE_PADDINGBOTTOM = DISPID_A_PADDINGBOTTOM; public const int DISPID_IHTMLCURRENTSTYLE_TEXTALIGN = STDPROPID_XOBJ_BLOCKALIGN; public const int DISPID_IHTMLCURRENTSTYLE_TEXTDECORATION = DISPID_A_TEXTDECORATION; public const int DISPID_IHTMLCURRENTSTYLE_DISPLAY = DISPID_A_DISPLAY; public const int DISPID_IHTMLCURRENTSTYLE_VISIBILITY = DISPID_A_VISIBILITY; public const int DISPID_IHTMLCURRENTSTYLE_ZINDEX = DISPID_A_ZINDEX; public const int DISPID_IHTMLCURRENTSTYLE_LETTERSPACING = DISPID_A_LETTERSPACING; public const int DISPID_IHTMLCURRENTSTYLE_LINEHEIGHT = DISPID_A_LINEHEIGHT; public const int DISPID_IHTMLCURRENTSTYLE_TEXTINDENT = DISPID_A_TEXTINDENT; public const int DISPID_IHTMLCURRENTSTYLE_VERTICALALIGN = DISPID_A_VERTICALALIGN; public const int DISPID_IHTMLCURRENTSTYLE_BACKGROUNDATTACHMENT = DISPID_A_BACKGROUNDATTACHMENT; public const int DISPID_IHTMLCURRENTSTYLE_MARGINTOP = DISPID_A_MARGINTOP; public const int DISPID_IHTMLCURRENTSTYLE_MARGINRIGHT = DISPID_A_MARGINRIGHT; public const int DISPID_IHTMLCURRENTSTYLE_MARGINBOTTOM = DISPID_A_MARGINBOTTOM; public const int DISPID_IHTMLCURRENTSTYLE_MARGINLEFT = DISPID_A_MARGINLEFT; public const int DISPID_IHTMLCURRENTSTYLE_CLEAR = DISPID_A_CLEAR; public const int DISPID_IHTMLCURRENTSTYLE_LISTSTYLETYPE = DISPID_A_LISTSTYLETYPE; public const int DISPID_IHTMLCURRENTSTYLE_LISTSTYLEPOSITION = DISPID_A_LISTSTYLEPOSITION; public const int DISPID_IHTMLCURRENTSTYLE_LISTSTYLEIMAGE = DISPID_A_LISTSTYLEIMAGE; public const int DISPID_IHTMLCURRENTSTYLE_CLIPTOP = DISPID_A_CLIPRECTTOP; public const int DISPID_IHTMLCURRENTSTYLE_CLIPRIGHT = DISPID_A_CLIPRECTRIGHT; public const int DISPID_IHTMLCURRENTSTYLE_CLIPBOTTOM = DISPID_A_CLIPRECTBOTTOM; public const int DISPID_IHTMLCURRENTSTYLE_CLIPLEFT = DISPID_A_CLIPRECTLEFT; public const int DISPID_IHTMLCURRENTSTYLE_OVERFLOW = DISPID_A_OVERFLOW; public const int DISPID_IHTMLCURRENTSTYLE_PAGEBREAKBEFORE = DISPID_A_PAGEBREAKBEFORE; public const int DISPID_IHTMLCURRENTSTYLE_PAGEBREAKAFTER = DISPID_A_PAGEBREAKAFTER; public const int DISPID_IHTMLCURRENTSTYLE_CURSOR = DISPID_A_CURSOR; public const int DISPID_IHTMLCURRENTSTYLE_TABLELAYOUT = DISPID_A_TABLELAYOUT; public const int DISPID_IHTMLCURRENTSTYLE_BORDERCOLLAPSE = DISPID_A_BORDERCOLLAPSE; public const int DISPID_IHTMLCURRENTSTYLE_DIRECTION = DISPID_A_DIRECTION; public const int DISPID_IHTMLCURRENTSTYLE_BEHAVIOR = DISPID_A_BEHAVIOR; public const int DISPID_IHTMLCURRENTSTYLE_GETATTRIBUTE = DISPID_HTMLOBJECT + 2; public const int DISPID_IHTMLCURRENTSTYLE_UNICODEBIDI = DISPID_A_UNICODEBIDI; public const int DISPID_IHTMLCURRENTSTYLE_RIGHT = STDPROPID_XOBJ_RIGHT; public const int DISPID_IHTMLCURRENTSTYLE_BOTTOM = STDPROPID_XOBJ_BOTTOM; public const int DISPID_IHTMLCURRENTSTYLE_IMEMODE = DISPID_A_IMEMODE; public const int DISPID_IHTMLCURRENTSTYLE_RUBYALIGN = DISPID_A_RUBYALIGN; public const int DISPID_IHTMLCURRENTSTYLE_RUBYPOSITION = DISPID_A_RUBYPOSITION; public const int DISPID_IHTMLCURRENTSTYLE_RUBYOVERHANG = DISPID_A_RUBYOVERHANG; public const int DISPID_IHTMLCURRENTSTYLE_TEXTAUTOSPACE = DISPID_A_TEXTAUTOSPACE; public const int DISPID_IHTMLCURRENTSTYLE_LINEBREAK = DISPID_A_LINEBREAK; public const int DISPID_IHTMLCURRENTSTYLE_WORDBREAK = DISPID_A_WORDBREAK; public const int DISPID_IHTMLCURRENTSTYLE_TEXTJUSTIFY = DISPID_A_TEXTJUSTIFY; public const int DISPID_IHTMLCURRENTSTYLE_TEXTJUSTIFYTRIM = DISPID_A_TEXTJUSTIFYTRIM; public const int DISPID_IHTMLCURRENTSTYLE_TEXTKASHIDA = DISPID_A_TEXTKASHIDA; public const int DISPID_IHTMLCURRENTSTYLE_BLOCKDIRECTION = DISPID_A_DIR; public const int DISPID_IHTMLCURRENTSTYLE_LAYOUTGRIDCHAR = DISPID_A_LAYOUTGRIDCHAR; public const int DISPID_IHTMLCURRENTSTYLE_LAYOUTGRIDLINE = DISPID_A_LAYOUTGRIDLINE; public const int DISPID_IHTMLCURRENTSTYLE_LAYOUTGRIDMODE = DISPID_A_LAYOUTGRIDMODE; public const int DISPID_IHTMLCURRENTSTYLE_LAYOUTGRIDTYPE = DISPID_A_LAYOUTGRIDTYPE; public const int DISPID_IHTMLCURRENTSTYLE_BORDERSTYLE = DISPID_A_BORDERSTYLE; public const int DISPID_IHTMLCURRENTSTYLE_BORDERCOLOR = DISPID_A_BORDERCOLOR; public const int DISPID_IHTMLCURRENTSTYLE_BORDERWIDTH = DISPID_A_BORDERWIDTH; public const int DISPID_IHTMLCURRENTSTYLE_PADDING = DISPID_A_PADDING; public const int DISPID_IHTMLCURRENTSTYLE_MARGIN = DISPID_A_MARGIN; public const int DISPID_IHTMLCURRENTSTYLE_ACCELERATOR = DISPID_A_ACCELERATOR; public const int DISPID_IHTMLCURRENTSTYLE_OVERFLOWX = DISPID_A_OVERFLOWX; public const int DISPID_IHTMLCURRENTSTYLE_OVERFLOWY = DISPID_A_OVERFLOWY; public const int DISPID_IHTMLCURRENTSTYLE_TEXTTRANSFORM = DISPID_A_TEXTTRANSFORM; // DISPIDs for interface IHTMLCurrentStyle2 public const int DISPID_IHTMLCURRENTSTYLE2_LAYOUTFLOW = DISPID_A_LAYOUTFLOW; public const int DISPID_IHTMLCURRENTSTYLE2_WORDWRAP = DISPID_A_WORDWRAP; public const int DISPID_IHTMLCURRENTSTYLE2_TEXTUNDERLINEPOSITION = DISPID_A_TEXTUNDERLINEPOSITION; public const int DISPID_IHTMLCURRENTSTYLE2_HASLAYOUT = DISPID_A_HASLAYOUT; public const int DISPID_IHTMLCURRENTSTYLE2_SCROLLBARBASECOLOR = DISPID_A_SCROLLBARBASECOLOR; public const int DISPID_IHTMLCURRENTSTYLE2_SCROLLBARFACECOLOR = DISPID_A_SCROLLBARFACECOLOR; public const int DISPID_IHTMLCURRENTSTYLE2_SCROLLBAR3DLIGHTCOLOR = DISPID_A_SCROLLBAR3DLIGHTCOLOR; public const int DISPID_IHTMLCURRENTSTYLE2_SCROLLBARSHADOWCOLOR = DISPID_A_SCROLLBARSHADOWCOLOR; public const int DISPID_IHTMLCURRENTSTYLE2_SCROLLBARHIGHLIGHTCOLOR = DISPID_A_SCROLLBARHIGHLIGHTCOLOR; public const int DISPID_IHTMLCURRENTSTYLE2_SCROLLBARDARKSHADOWCOLOR = DISPID_A_SCROLLBARDARKSHADOWCOLOR; public const int DISPID_IHTMLCURRENTSTYLE2_SCROLLBARARROWCOLOR = DISPID_A_SCROLLBARARROWCOLOR; public const int DISPID_IHTMLCURRENTSTYLE2_SCROLLBARTRACKCOLOR = DISPID_A_SCROLLBARTRACKCOLOR; public const int DISPID_IHTMLCURRENTSTYLE2_WRITINGMODE = DISPID_A_WRITINGMODE; public const int DISPID_IHTMLCURRENTSTYLE2_ZOOM = DISPID_A_ZOOM; public const int DISPID_IHTMLCURRENTSTYLE2_FILTER = DISPID_A_FILTER; public const int DISPID_IHTMLCURRENTSTYLE2_TEXTALIGNLAST = DISPID_A_TEXTALIGNLAST; public const int DISPID_IHTMLCURRENTSTYLE2_TEXTKASHIDASPACE = DISPID_A_TEXTKASHIDASPACE; public const int DISPID_IHTMLCURRENTSTYLE2_ISBLOCK = DISPID_A_ISBLOCK; // DISPIDs for interface IHTMLCurrentStyle3 public const int DISPID_IHTMLCURRENTSTYLE3_TEXTOVERFLOW = DISPID_A_TEXTOVERFLOW; public const int DISPID_IHTMLCURRENTSTYLE3_MINHEIGHT = DISPID_A_MINHEIGHT; public const int DISPID_IHTMLCURRENTSTYLE3_WORDSPACING = DISPID_A_WORDSPACING; public const int DISPID_IHTMLCURRENTSTYLE3_WHITESPACE = DISPID_A_WHITESPACE; public const int DISPID_IHTMLCOMPUTEDSTYLE = DISPID_NORMAL_FIRST; // DISPIDs for interface IHTMLComputedStyle public const int DISPID_IHTMLCOMPUTEDSTYLE_BOLD = DISPID_IHTMLCOMPUTEDSTYLE + 1; public const int DISPID_IHTMLCOMPUTEDSTYLE_ITALIC = DISPID_IHTMLCOMPUTEDSTYLE + 2; public const int DISPID_IHTMLCOMPUTEDSTYLE_UNDERLINE = DISPID_IHTMLCOMPUTEDSTYLE + 3; public const int DISPID_IHTMLCOMPUTEDSTYLE_OVERLINE = DISPID_IHTMLCOMPUTEDSTYLE + 4; public const int DISPID_IHTMLCOMPUTEDSTYLE_STRIKEOUT = DISPID_IHTMLCOMPUTEDSTYLE + 5; public const int DISPID_IHTMLCOMPUTEDSTYLE_SUBSCRIPT = DISPID_IHTMLCOMPUTEDSTYLE + 6; public const int DISPID_IHTMLCOMPUTEDSTYLE_SUPERSCRIPT = DISPID_IHTMLCOMPUTEDSTYLE + 7; public const int DISPID_IHTMLCOMPUTEDSTYLE_EXPLICITFACE = DISPID_IHTMLCOMPUTEDSTYLE + 8; public const int DISPID_IHTMLCOMPUTEDSTYLE_FONTWEIGHT = DISPID_IHTMLCOMPUTEDSTYLE + 9; public const int DISPID_IHTMLCOMPUTEDSTYLE_FONTSIZE = DISPID_IHTMLCOMPUTEDSTYLE + 10; public const int DISPID_IHTMLCOMPUTEDSTYLE_FONTNAME = DISPID_IHTMLCOMPUTEDSTYLE + 11; public const int DISPID_IHTMLCOMPUTEDSTYLE_HASBGCOLOR = DISPID_IHTMLCOMPUTEDSTYLE + 12; public const int DISPID_IHTMLCOMPUTEDSTYLE_TEXTCOLOR = DISPID_IHTMLCOMPUTEDSTYLE + 13; public const int DISPID_IHTMLCOMPUTEDSTYLE_BACKGROUNDCOLOR = DISPID_IHTMLCOMPUTEDSTYLE + 14; public const int DISPID_IHTMLCOMPUTEDSTYLE_PREFORMATTED = DISPID_IHTMLCOMPUTEDSTYLE + 15; public const int DISPID_IHTMLCOMPUTEDSTYLE_DIRECTION = DISPID_IHTMLCOMPUTEDSTYLE + 16; public const int DISPID_IHTMLCOMPUTEDSTYLE_BLOCKDIRECTION = DISPID_IHTMLCOMPUTEDSTYLE + 17; public const int DISPID_IHTMLCOMPUTEDSTYLE_OL = DISPID_IHTMLCOMPUTEDSTYLE + 18; public const int DISPID_ILINEINFO = DISPID_NORMAL_FIRST; // DISPIDs for interface ILineInfo public const int DISPID_ILINEINFO_X = DISPID_ILINEINFO + 1; public const int DISPID_ILINEINFO_BASELINE = DISPID_ILINEINFO + 2; public const int DISPID_ILINEINFO_TEXTDESCENT = DISPID_ILINEINFO + 3; public const int DISPID_ILINEINFO_TEXTHEIGHT = DISPID_ILINEINFO + 4; public const int DISPID_ILINEINFO_LINEDIRECTION = DISPID_ILINEINFO + 5; // DISPIDs for interface IHTMLRenderStyle public const int DISPID_A_TEXTLINETHROUGHSTYLE = (DISPID_A_FIRST + 166); public const int DISPID_A_TEXTUNDERLINESTYLE = (DISPID_A_FIRST + 167); public const int DISPID_A_TEXTEFFECT = (DISPID_A_FIRST + 168); public const int DISPID_A_TEXTBACKGROUNDCOLOR = (DISPID_A_FIRST + 169); public const int DISPID_A_RENDERINGPRIORITY = (DISPID_A_FIRST + 170); public const int DISPID_A_DEFAULTTEXTSELECTION = (DISPID_A_FIRST + 188); public const int DISPID_A_TEXTDECORATIONCOLOR = (DISPID_A_FIRST + 189); public const int DISPID_A_TEXTCOLOR = (DISPID_A_FIRST + 190); public const int DISPID_A_STYLETEXTDECORATION = (DISPID_A_FIRST + 191); public const int DISPID_IHTMLRENDERSTYLE_TEXTLINETHROUGHSTYLE = DISPID_A_TEXTLINETHROUGHSTYLE; public const int DISPID_IHTMLRENDERSTYLE_TEXTUNDERLINESTYLE = DISPID_A_TEXTUNDERLINESTYLE; public const int DISPID_IHTMLRENDERSTYLE_TEXTEFFECT = DISPID_A_TEXTEFFECT; public const int DISPID_IHTMLRENDERSTYLE_TEXTCOLOR = DISPID_A_TEXTCOLOR; public const int DISPID_IHTMLRENDERSTYLE_TEXTBACKGROUNDCOLOR = DISPID_A_TEXTBACKGROUNDCOLOR; public const int DISPID_IHTMLRENDERSTYLE_TEXTDECORATIONCOLOR = DISPID_A_TEXTDECORATIONCOLOR; public const int DISPID_IHTMLRENDERSTYLE_RENDERINGPRIORITY = DISPID_A_RENDERINGPRIORITY; public const int DISPID_IHTMLRENDERSTYLE_DEFAULTTEXTSELECTION = DISPID_A_DEFAULTTEXTSELECTION; public const int DISPID_IHTMLRENDERSTYLE_TEXTDECORATION = DISPID_A_STYLETEXTDECORATION; public const int DISPID_NAVIGATOR = 1; // DISPIDs for interface IOmNavigator public const int DISPID_IOMNAVIGATOR_APPCODENAME = DISPID_NAVIGATOR; public const int DISPID_IOMNAVIGATOR_APPNAME = DISPID_NAVIGATOR + 1; public const int DISPID_IOMNAVIGATOR_APPVERSION = DISPID_NAVIGATOR + 2; public const int DISPID_IOMNAVIGATOR_USERAGENT = DISPID_NAVIGATOR + 3; public const int DISPID_IOMNAVIGATOR_JAVAENABLED = DISPID_NAVIGATOR + 4; public const int DISPID_IOMNAVIGATOR_TAINTENABLED = DISPID_NAVIGATOR + 5; public const int DISPID_IOMNAVIGATOR_MIMETYPES = DISPID_NAVIGATOR + 6; public const int DISPID_IOMNAVIGATOR_PLUGINS = DISPID_NAVIGATOR + 7; public const int DISPID_IOMNAVIGATOR_COOKIEENABLED = DISPID_NAVIGATOR + 8; public const int DISPID_IOMNAVIGATOR_OPSPROFILE = DISPID_NAVIGATOR + 9; public const int DISPID_IOMNAVIGATOR_TOSTRING = DISPID_NAVIGATOR + 10; public const int DISPID_IOMNAVIGATOR_CPUCLASS = DISPID_NAVIGATOR + 11; public const int DISPID_IOMNAVIGATOR_SYSTEMLANGUAGE = DISPID_NAVIGATOR + 12; public const int DISPID_IOMNAVIGATOR_BROWSERLANGUAGE = DISPID_NAVIGATOR + 13; public const int DISPID_IOMNAVIGATOR_USERLANGUAGE = DISPID_NAVIGATOR + 14; public const int DISPID_IOMNAVIGATOR_PLATFORM = DISPID_NAVIGATOR + 15; public const int DISPID_IOMNAVIGATOR_APPMINORVERSION = DISPID_NAVIGATOR + 16; public const int DISPID_IOMNAVIGATOR_CONNECTIONSPEED = DISPID_NAVIGATOR + 17; public const int DISPID_IOMNAVIGATOR_ONLINE = DISPID_NAVIGATOR + 18; public const int DISPID_IOMNAVIGATOR_USERPROFILE = DISPID_NAVIGATOR + 19; // DISPIDs for interface IHTMLWindow3 public const int DISPID_IHTMLWINDOW3_SCREENLEFT = 1170; public const int DISPID_IHTMLWINDOW3_SCREENTOP = 1171; public const int DISPID_IHTMLWINDOW3_ATTACHEVENT = DISPID_HTMLOBJECT + 7; public const int DISPID_IHTMLWINDOW3_DETACHEVENT = DISPID_HTMLOBJECT + 8; public const int DISPID_IHTMLWINDOW3_SETTIMEOUT = 1103; public const int DISPID_IHTMLWINDOW3_SETINTERVAL = 1162; public const int DISPID_IHTMLWINDOW3_PRINT = 1174; public const int DISPID_IHTMLWINDOW3_ONBEFOREPRINT = DISPID_EVPROP_ONBEFOREPRINT; public const int DISPID_IHTMLWINDOW3_ONAFTERPRINT = DISPID_EVPROP_ONAFTERPRINT; public const int DISPID_IHTMLWINDOW3_CLIPBOARDDATA = 1175; public const int DISPID_IHTMLWINDOW3_SHOWMODELESSDIALOG = 1176; // DISPIDs for interface IHTMLWindow4 public const int DISPID_IHTMLWINDOW4_CREATEPOPUP = 1180; public const int DISPID_IHTMLWINDOW4_FRAMEELEMENT = 1181; // DISPIDs for interface IHTMLPopup public const int DISPID_HTMLPOPUP = 27000; public const int DISPID_IHTMLPOPUP_SHOW = DISPID_HTMLPOPUP + 1; public const int DISPID_IHTMLPOPUP_HIDE = DISPID_HTMLPOPUP + 2; public const int DISPID_IHTMLPOPUP_DOCUMENT = DISPID_HTMLPOPUP + 3; public const int DISPID_IHTMLPOPUP_ISOPEN = DISPID_HTMLPOPUP + 4; } class UnsafeNativeMethods { private UnsafeNativeMethods() { } [ComImport, TypeLibType((short)0x1010), InterfaceType((short)2), Guid("34A715A0-6587-11D0-924A-0020AFC7AC4D")] public interface DWebBrowserEvents2 { [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x66)] void StatusTextChange([In, MarshalAs(UnmanagedType.BStr)] string Text); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x6c)] void ProgressChange([In] int Progress, [In] int ProgressMax); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x69)] void CommandStateChange([In] int Command, [In] bool Enable); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x6a)] void DownloadBegin(); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x68)] void DownloadComplete(); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x71)] void TitleChange([In, MarshalAs(UnmanagedType.BStr)] string Text); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x70)] void PropertyChange([In, MarshalAs(UnmanagedType.BStr)] string szProperty); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(250)] void BeforeNavigate2([In, MarshalAs(UnmanagedType.IDispatch)] object pDisp, [In, MarshalAs(UnmanagedType.Struct)] ref object URL, [In, MarshalAs(UnmanagedType.Struct)] ref object Flags, [In, MarshalAs(UnmanagedType.Struct)] ref object TargetFrameName, [In, MarshalAs(UnmanagedType.Struct)] ref object PostData, [In, MarshalAs(UnmanagedType.Struct)] ref object Headers, [In, Out] ref bool Cancel); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0xfb)] void NewWindow2([In, Out, MarshalAs(UnmanagedType.IDispatch)] ref object ppDisp, [In, Out] ref bool Cancel); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0xfc)] void NavigateComplete2([In, MarshalAs(UnmanagedType.IDispatch)] object pDisp, [In, MarshalAs(UnmanagedType.Struct)] ref object URL); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x103)] void DocumentComplete([In, MarshalAs(UnmanagedType.IDispatch)] object pDisp, [In, MarshalAs(UnmanagedType.Struct)] ref object URL); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0xfd)] void OnQuit(); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0xfe)] void OnVisible([In] bool Visible); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0xff)] void OnToolBar([In] bool ToolBar); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x100)] void OnMenuBar([In] bool MenuBar); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x101)] void OnStatusBar([In] bool StatusBar); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x102)] void OnFullScreen([In] bool FullScreen); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(260)] void OnTheaterMode([In] bool TheaterMode); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x106)] void WindowSetResizable([In] bool Resizable); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x108)] void WindowSetLeft([In] int Left); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x109)] void WindowSetTop([In] int Top); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x10a)] void WindowSetWidth([In] int Width); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x10b)] void WindowSetHeight([In] int Height); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x107)] void WindowClosing([In] bool IsChildWindow, [In, Out] ref bool Cancel); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x10c)] void ClientToHostWindow([In, Out] ref int CX, [In, Out] ref int CY); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x10d)] void SetSecureLockIcon([In] int SecureLockIcon); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(270)] void FileDownload([In, Out] ref bool Cancel); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x10f)] void NavigateError([In, MarshalAs(UnmanagedType.IDispatch)] object pDisp, [In, MarshalAs(UnmanagedType.Struct)] ref object URL, [In, MarshalAs(UnmanagedType.Struct)] ref object Frame, [In, MarshalAs(UnmanagedType.Struct)] ref object StatusCode, [In, Out] ref bool Cancel); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0xe1)] void PrintTemplateInstantiation([In, MarshalAs(UnmanagedType.IDispatch)] object pDisp); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0xe2)] void PrintTemplateTeardown([In, MarshalAs(UnmanagedType.IDispatch)] object pDisp); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0xe3)] void UpdatePageStatus([In, MarshalAs(UnmanagedType.IDispatch)] object pDisp, [In, MarshalAs(UnmanagedType.Struct)] ref object nPage, [In, MarshalAs(UnmanagedType.Struct)] ref object fDone); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x110)] void PrivacyImpactedStateChange([In] bool bImpacted); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x111)] void NewWindow3([In, Out, MarshalAs(UnmanagedType.IDispatch)] ref object ppDisp, [In, Out] ref bool Cancel, [In] uint dwFlags, [In, MarshalAs(UnmanagedType.BStr)] string bstrUrlContext, [In, MarshalAs(UnmanagedType.BStr)] string bstrUrl); } [ComImport, SuppressUnmanagedCodeSecurity, TypeLibType(TypeLibTypeFlags.FOleAutomation | (TypeLibTypeFlags.FDual | TypeLibTypeFlags.FHidden)), Guid("D30C1661-CDAF-11d0-8A3E-00C04FC9E26E")] public interface IWebBrowser2 { [DispId(100)] void GoBack(); [DispId(0x65)] void GoForward(); [DispId(0x66)] void GoHome(); [DispId(0x67)] void GoSearch(); [DispId(0x68)] void Navigate([In] string Url, [In] ref object flags, [In] ref object targetFrameName, [In] ref object postData, [In] ref object headers); [DispId(-550)] void Refresh(); [DispId(0x69)] void Refresh2([In] ref object level); [DispId(0x6a)] void Stop(); [DispId(200)] object Application { [return: MarshalAs(UnmanagedType.IDispatch)] get; } [DispId(0xc9)] object Parent { [return: MarshalAs(UnmanagedType.IDispatch)] get; } [DispId(0xca)] object Container { [return: MarshalAs(UnmanagedType.IDispatch)] get; } [DispId(0xcb)] object Document { [return: MarshalAs(UnmanagedType.IDispatch)] get; } [DispId(0xcc)] bool TopLevelContainer { get; } [DispId(0xcd)] string Type { get; } [DispId(0xce)] int Left { get; set; } [DispId(0xcf)] int Top { get; set; } [DispId(0xd0)] int Width { get; set; } [DispId(0xd1)] int Height { get; set; } [DispId(210)] string LocationName { get; } [DispId(0xd3)] string LocationURL { get; } [DispId(0xd4)] bool Busy { get; } [DispId(300)] void Quit(); [DispId(0x12d)] void ClientToWindow(out int pcx, out int pcy); [DispId(0x12e)] void PutProperty([In] string property, [In] object vtValue); [DispId(0x12f)] object GetProperty([In] string property); [DispId(0)] string Name { get; } [DispId(-515)] int HWND { get; } [DispId(400)] string FullName { get; } [DispId(0x191)] string Path { get; } [DispId(0x192)] bool Visible { get; set; } [DispId(0x193)] bool StatusBar { get; set; } [DispId(0x194)] string StatusText { get; set; } [DispId(0x195)] int ToolBar { get; set; } [DispId(0x196)] bool MenuBar { get; set; } [DispId(0x197)] bool FullScreen { get; set; } [DispId(500)] void Navigate2([In] ref object URL, [In] ref object flags, [In] ref object targetFrameName, [In] ref object postData, [In] ref object headers); [DispId(0x1f5)] NativeMethods.OLECMDF QueryStatusWB([In] NativeMethods.OLECMDID cmdID); [DispId(0x1f6)] void ExecWB([In] NativeMethods.OLECMDID cmdID, [In] NativeMethods.OLECMDEXECOPT cmdexecopt, ref object pvaIn, IntPtr pvaOut); [DispId(0x1f7)] void ShowBrowserBar([In] ref object pvaClsid, [In] ref object pvarShow, [In] ref object pvarSize); [DispId(-525)] WebBrowserReadyState ReadyState { get; } [DispId(550)] bool Offline { get; set; } [DispId(0x227)] bool Silent { get; set; } [DispId(0x228)] bool RegisterAsBrowser { get; set; } [DispId(0x229)] bool RegisterAsDropTarget { get; set; } [DispId(0x22a)] bool TheaterMode { get; set; } [DispId(0x22b)] bool AddressBar { get; set; } [DispId(0x22c)] bool Resizable { get; set; } } [ComVisible(true), ComImport()] [TypeLibType((short)4160)] //TypeLibTypeFlags.FDispatchable [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] [Guid("3050f240-98b5-11cf-bb82-00aa00bdce0b")] public interface IHTMLImgElement { [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_ISMAP)] bool isMap { set; [return: MarshalAs(UnmanagedType.VariantBool)] get; } [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_USEMAP)] string useMap { set; [return: MarshalAs(UnmanagedType.BStr)] get;} [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_MIMETYPE)] string mimeType { [return: MarshalAs(UnmanagedType.BStr)] get;} [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_FILESIZE)] string fileSize { [return: MarshalAs(UnmanagedType.BStr)] get;} [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_FILECREATEDDATE)] string fileCreatedDate { [return: MarshalAs(UnmanagedType.BStr)] get;} [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_FILEMODIFIEDDATE)] string fileModifiedDate { [return: MarshalAs(UnmanagedType.BStr)] get;} [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_FILEUPDATEDDATE)] string fileUpdatedDate { [return: MarshalAs(UnmanagedType.BStr)] get;} [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_PROTOCOL)] string protocol { set; [return: MarshalAs(UnmanagedType.BStr)] get;} [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_HREF)] string href { [return: MarshalAs(UnmanagedType.BStr)] get;} [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_NAMEPROP)] string nameProp { [return: MarshalAs(UnmanagedType.BStr)] get;} [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_BORDER)] object border { set; get; } [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_VSPACE)] int vspace { set; get; } [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_HSPACE)] int hspace { set; get; } [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_ALT)] string alt { set; [return: MarshalAs(UnmanagedType.BStr)] get;} [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_SRC)] string src { set; [return: MarshalAs(UnmanagedType.BStr)] get;} [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_LOWSRC)] string lowsrc { set; [return: MarshalAs(UnmanagedType.BStr)] get;} [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_VRML)] string vrml { set; [return: MarshalAs(UnmanagedType.BStr)] get;} [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_DYNSRC)] string dynsrc { set; [return: MarshalAs(UnmanagedType.BStr)] get;} [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_READYSTATE)] string readyState { [return: MarshalAs(UnmanagedType.BStr)] get;} [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_COMPLETE)] bool complete { [return: MarshalAs(UnmanagedType.VariantBool)] get;} [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_LOOP)] object loop { set; get; } [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_ALIGN)] string align { set; [return: MarshalAs(UnmanagedType.BStr)] get;} [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_ONLOAD)] object onload { set; get; } [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_ONERROR)] object onerror { set; get; } [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_ONABORT)] object onabort { set; get; } [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_NAME)] string name { set; [return: MarshalAs(UnmanagedType.BStr)] get;} [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_WIDTH)] int width { set; get; } [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_HEIGHT)] int height { set; get; } [DispId(HTMLDispIDs.DISPID_IHTMLIMGELEMENT_START)] string start { set; [return: MarshalAs(UnmanagedType.BStr)] get;} } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Browser/UnsafeNativeMethods.cs
C#
gpl3
154,439
using System; namespace Samba.Presentation.Common.Browser { public static class NativeMethods { public enum OLECMDF { // Fields OLECMDF_DEFHIDEONCTXTMENU = 0x20, OLECMDF_ENABLED = 2, OLECMDF_INVISIBLE = 0x10, OLECMDF_LATCHED = 4, OLECMDF_NINCHED = 8, OLECMDF_SUPPORTED = 1 } public enum OLECMDID { // Fields OLECMDID_PAGESETUP = 8, OLECMDID_PRINT = 6, OLECMDID_PRINTPREVIEW = 7, OLECMDID_PROPERTIES = 10, OLECMDID_SAVEAS = 4, // OLECMDID_SHOWSCRIPTERROR = 40 } public enum OLECMDEXECOPT { // Fields OLECMDEXECOPT_DODEFAULT = 0, OLECMDEXECOPT_DONTPROMPTUSER = 2, OLECMDEXECOPT_PROMPTUSER = 1, OLECMDEXECOPT_SHOWHELP = 3 } [Flags] public enum NWMF { NWMF_UNLOADING = 0x00000001, NWMF_USERINITED = 0x00000002, NWMF_FIRST = 0x00000004, NWMF_OVERRIDEKEY = 0x00000008, NWMF_SHOWHELP = 0x00000010, NWMF_HTMLDIALOG = 0x00000020, NWMF_FROMDIALOGCHILD = 0x00000040, NWMF_USERREQUESTED = 0x00000080, NWMF_USERALLOWED = 0x00000100, NWMF_FORCEWINDOW = 0x00010000, NWMF_FORCETAB = 0x00020000, NWMF_SUGGESTWINDOW = 0x00040000, NWMF_SUGGESTTAB = 0x00080000, NWMF_INACTIVETAB = 0x00100000 } //[StructLayout(LayoutKind.Sequential)] //public class POINT //{ // public int x; // public int y; // public POINT() { } // public POINT(int x, int y) // { // this.x = x; // this.y = y; // } //} //[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("B722BCCB-4E68-101B-A2BC-00AA00404770"), ComVisible(true)] //public interface IOleCommandTarget //{ // [return: MarshalAs(UnmanagedType.I4)] // [PreserveSig] // int QueryStatus(ref Guid pguidCmdGroup, int cCmds, [In, Out] NativeMethods.OLECMD prgCmds, [In, Out] IntPtr pCmdText); // [return: MarshalAs(UnmanagedType.I4)] // [PreserveSig] // int Exec(ref Guid pguidCmdGroup, int nCmdID, int nCmdexecopt, [In, MarshalAs(UnmanagedType.LPArray)] object[] pvaIn, ref int pvaOut); //} //[StructLayout(LayoutKind.Sequential)] //public class OLECMD //{ // [MarshalAs(UnmanagedType.U4)] // public int cmdID; // [MarshalAs(UnmanagedType.U4)] // public int cmdf; // public OLECMD() // { // } //} //public const int S_FALSE = 1; //public const int S_OK = 0; } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Browser/NativeMethods.cs
C#
gpl3
3,014
using System; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Windows.Forms; namespace Samba.Presentation.Common.Browser { /// <summary> /// An extended version of the <see cref="WebBrowser"/> control. /// </summary> public class ExtendedWebBrowser : System.Windows.Forms.WebBrowser { /// <summary> /// This method supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// Called by the control when the underlying ActiveX control is created. /// </summary> /// <param name="nativeActiveXObject"></param> [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")] protected override void AttachInterfaces(object nativeActiveXObject) { base.AttachInterfaces(nativeActiveXObject); } /// <summary> /// This method supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// Called by the control when the underlying ActiveX control is discarded. /// </summary> [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")] protected override void DetachInterfaces() { base.DetachInterfaces(); } System.Windows.Forms.AxHost.ConnectionPointCookie cookie; WebBrowserExtendedEvents events; /// <summary> /// This method will be called to give you a chance to create your own event sink /// </summary> [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")] protected override void CreateSink() { // Make sure to call the base class or the normal events won't fire base.CreateSink(); events = new WebBrowserExtendedEvents(this); cookie = new AxHost.ConnectionPointCookie(this.ActiveXInstance, events, typeof(UnsafeNativeMethods.DWebBrowserEvents2)); } /// <summary> /// Detaches the event sink /// </summary> [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")] protected override void DetachSink() { if (null != cookie) { cookie.Disconnect(); cookie = null; } } /// <summary> /// Fires when downloading of a document begins /// </summary> public event EventHandler Downloading; /// <summary> /// Raises the <see cref="Downloading"/> event /// </summary> /// <param name="e">Empty <see cref="EventArgs"/></param> /// <remarks> /// You could start an animation or a notification that downloading is starting /// </remarks> protected void OnDownloading(EventArgs e) { if (Downloading != null) Downloading(this, e); } /// <summary> /// Fires when downloading is completed /// </summary> /// <remarks> /// Here you could start monitoring for script errors. /// </remarks> public event EventHandler DownloadComplete; /// <summary> /// Raises the <see cref="DownloadComplete"/> event /// </summary> /// <param name="e">Empty <see cref="EventArgs"/></param> protected virtual void OnDownloadComplete(EventArgs e) { if (DownloadComplete != null) DownloadComplete(this, e); } /// <summary> /// Fires before navigation occurs in the given object (on either a window or frameset element). /// </summary> public event EventHandler<BrowserExtendedNavigatingEventArgs> StartNavigate; /// <summary> /// Raised when a new window is to be created. Extends DWebBrowserEvents2::NewWindow2 with additional information about the new window. /// </summary> public event EventHandler<BrowserExtendedNavigatingEventArgs> StartNewWindow; public void InvokeStartNewWindow(BrowserExtendedNavigatingEventArgs e) { EventHandler<BrowserExtendedNavigatingEventArgs> handler = StartNewWindow; if (handler != null) handler(this, e); } public event EventHandler<BrowserExtendedNavigatingEventArgs> StartNewTab; public void InvokeStartNewTab(BrowserExtendedNavigatingEventArgs e) { EventHandler<BrowserExtendedNavigatingEventArgs> handler = StartNewTab; if (handler != null) handler(this, e); } public event EventHandler<SizeChangedEventArgs> WindowSetWidth; public void InvokeWindowSetWidth(int e) { EventHandler<SizeChangedEventArgs> handler = WindowSetWidth; if (handler != null) handler(this, new SizeChangedEventArgs(e)); } public event EventHandler<SizeChangedEventArgs> WindowSetHeight; public void InvokeWindowSetHeight(int e) { EventHandler<SizeChangedEventArgs> handler = WindowSetHeight; if (handler != null) handler(this, new SizeChangedEventArgs(e)); } public event EventHandler<SizeChangedEventArgs> WindowsSetTop; public void InvokeWindowsSetTop(int e) { EventHandler<SizeChangedEventArgs> handler = WindowsSetTop; if (handler != null) handler(this, new SizeChangedEventArgs(e)); } public event EventHandler<SizeChangedEventArgs> WindowSetLeft; public void InvokeWindowSetLeft(int e) { EventHandler<SizeChangedEventArgs> handler = WindowSetLeft; if (handler != null) handler(this, new SizeChangedEventArgs(e)); } /// <summary> /// Raises the <see cref="StartNewWindow"/> event /// </summary> /// <exception cref="ArgumentNullException">Thrown when BrowserExtendedNavigatingEventArgs is null</exception> protected void OnStartNewWindow(BrowserExtendedNavigatingEventArgs e, NativeMethods.NWMF flags) { if (e == null) throw new ArgumentNullException("e"); if ((flags & NativeMethods.NWMF.NWMF_SUGGESTWINDOW) == NativeMethods.NWMF.NWMF_SUGGESTWINDOW) { InvokeStartNewWindow(e); } else { InvokeStartNewTab(e); } } private void OnWindowSetTop(int top) { InvokeWindowsSetTop(top); } private void OnWindowSetLeft(int left) { InvokeWindowsSetTop(left); } private void OnWindowSetWidth(int width) { InvokeWindowSetWidth(width); } private void OnWindowSetHeight(int height) { InvokeWindowSetHeight(height); } /// <summary> /// Raises the <see cref="StartNavigate"/> event /// </summary> /// <exception cref="ArgumentNullException">Thrown when BrowserExtendedNavigatingEventArgs is null</exception> protected void OnStartNavigate(BrowserExtendedNavigatingEventArgs e) { if (e == null) throw new ArgumentNullException("e"); if (this.StartNavigate != null) this.StartNavigate(this, e); } public string GetDocumentText() { string result = string.Empty; try { result = Document.Body.InnerHtml; result = DocumentText; } catch (Exception) { } return result; } public event EventHandler BackButtonClicked; public event EventHandler ForwardButtonClicked; #region The Implementation of DWebBrowserEvents2 for firing extra events //This class will capture events from the WebBrowser class WebBrowserExtendedEvents : UnsafeNativeMethods.DWebBrowserEvents2 { public WebBrowserExtendedEvents() { } ExtendedWebBrowser _Browser; public WebBrowserExtendedEvents(ExtendedWebBrowser browser) { _Browser = browser; } #region DWebBrowserEvents2 Members //Implement whichever events you wish public void BeforeNavigate2(object pDisp, ref object URL, ref object flags, ref object targetFrameName, ref object postData, ref object headers, ref bool cancel) { Uri urlUri = new Uri(URL.ToString()); string tFrame = null; if (targetFrameName != null) tFrame = targetFrameName.ToString(); BrowserExtendedNavigatingEventArgs args = new BrowserExtendedNavigatingEventArgs(pDisp, urlUri, tFrame); _Browser.OnStartNavigate(args); cancel = args.Cancel; pDisp = args.AutomationObject; } //The NewWindow2 event, used on Windows XP SP1 and below public void NewWindow2(ref object pDisp, ref bool cancel) { //BrowserExtendedNavigatingEventArgs args = new BrowserExtendedNavigatingEventArgs(pDisp, null, null); //_Browser.OnStartNewWindow(args, 0); //cancel = args.Cancel; //pDisp = args.AutomationObject; } // NewWindow3 event, used on Windows XP SP2 and higher public void NewWindow3(ref object ppDisp, ref bool Cancel, uint dwFlags, string bstrUrlContext, string bstrUrl) { BrowserExtendedNavigatingEventArgs args = new BrowserExtendedNavigatingEventArgs(ppDisp, new Uri(bstrUrl), null); _Browser.OnStartNewWindow(args, (NativeMethods.NWMF)dwFlags); Cancel = args.Cancel; ppDisp = args.AutomationObject; } // Fired when downloading begins public void DownloadBegin() { _Browser.OnDownloading(EventArgs.Empty); } // Fired when downloading is completed public void DownloadComplete() { _Browser.OnDownloadComplete(EventArgs.Empty); } #region Unused events // This event doesn't fire. [DispId(0x00000107)] public void WindowClosing(bool isChildWindow, ref bool cancel) { } public void OnQuit() { } public void StatusTextChange(string text) { } public void ProgressChange(int progress, int progressMax) { } public void TitleChange(string text) { } public void PropertyChange(string szProperty) { } public void NavigateComplete2(object pDisp, ref object URL) { } public void DocumentComplete(object pDisp, ref object URL) { } public void OnVisible(bool visible) { } public void OnToolBar(bool toolBar) { } public void OnMenuBar(bool menuBar) { } public void OnStatusBar(bool statusBar) { } public void OnFullScreen(bool fullScreen) { } public void OnTheaterMode(bool theaterMode) { } public void WindowSetResizable(bool resizable) { } public void WindowSetLeft(int left) { _Browser.OnWindowSetLeft(left); } public void WindowSetTop(int top) { _Browser.OnWindowSetTop(top); } public void WindowSetWidth(int width) { _Browser.OnWindowSetWidth(width); } public void WindowSetHeight(int height) { _Browser.OnWindowSetHeight(height); } public void SetSecureLockIcon(int secureLockIcon) { } public void FileDownload(ref bool cancel) { } public void NavigateError(object pDisp, ref object URL, ref object frame, ref object statusCode, ref bool cancel) { } public void PrintTemplateInstantiation(object pDisp) { } public void PrintTemplateTeardown(object pDisp) { } public void UpdatePageStatus(object pDisp, ref object nPage, ref object fDone) { } public void PrivacyImpactedStateChange(bool bImpacted) { } public void CommandStateChange(int Command, bool Enable) { } public void ClientToHostWindow(ref int CX, ref int CY) { } #endregion #endregion } #endregion #region Raises the Quit event when the browser window is about to be destroyed /// <summary> /// Overridden /// </summary> /// <param name="m">The <see cref="System.Windows.Forms.Message"/> send to this procedure</param> [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")] protected override void WndProc(ref System.Windows.Forms.Message m) { switch (m.Msg) { case (int)WindowsMessages.WM_PARENTNOTIFY: { if (m.WParam.ToInt32() == 131595) { if (ForwardButtonClicked != null) ForwardButtonClicked(this, EventArgs.Empty); return; } else if (m.WParam.ToInt32() == 66059) { if (BackButtonClicked != null) BackButtonClicked(this, EventArgs.Empty); return; } //int lp = m.LParam.ToInt32(); int wp = m.WParam.ToInt32(); int X = wp & 0xFFFF; //int Y = (wp >> 16) & 0xFFFF; if (X == (int)WindowsMessages.WM_DESTROY) this.OnQuit(); return; } case 0x201: // WM_LMOUSEBUTTON case 0x204: case 0x207: case 0x21: base.DefWndProc(ref m); return; } base.WndProc(ref m); } /// <summary> /// A list of all the available window messages /// </summary> enum WindowsMessages { WM_ACTIVATE = 0x6, WM_ACTIVATEAPP = 0x1C, WM_AFXFIRST = 0x360, WM_AFXLAST = 0x37F, WM_APP = 0x8000, WM_ASKCBFORMATNAME = 0x30C, WM_CANCELJOURNAL = 0x4B, WM_CANCELMODE = 0x1F, WM_CAPTURECHANGED = 0x215, WM_CHANGECBCHAIN = 0x30D, WM_CHAR = 0x102, WM_CHARTOITEM = 0x2F, WM_CHILDACTIVATE = 0x22, WM_CLEAR = 0x303, WM_CLOSE = 0x10, WM_COMMAND = 0x111, WM_COMPACTING = 0x41, WM_COMPAREITEM = 0x39, WM_CONTEXTMENU = 0x7B, WM_COPY = 0x301, WM_COPYDATA = 0x4A, WM_CREATE = 0x1, WM_CTLCOLORBTN = 0x135, WM_CTLCOLORDLG = 0x136, WM_CTLCOLOREDIT = 0x133, WM_CTLCOLORLISTBOX = 0x134, WM_CTLCOLORMSGBOX = 0x132, WM_CTLCOLORSCROLLBAR = 0x137, WM_CTLCOLORSTATIC = 0x138, WM_CUT = 0x300, WM_DEADCHAR = 0x103, WM_DELETEITEM = 0x2D, WM_DESTROY = 0x2, WM_DESTROYCLIPBOARD = 0x307, WM_DEVICECHANGE = 0x219, WM_DEVMODECHANGE = 0x1B, WM_DISPLAYCHANGE = 0x7E, WM_DRAWCLIPBOARD = 0x308, WM_DRAWITEM = 0x2B, WM_DROPFILES = 0x233, WM_ENABLE = 0xA, WM_ENDSESSION = 0x16, WM_ENTERIDLE = 0x121, WM_ENTERMENULOOP = 0x211, WM_ENTERSIZEMOVE = 0x231, WM_ERASEBKGND = 0x14, WM_EXITMENULOOP = 0x212, WM_EXITSIZEMOVE = 0x232, WM_FONTCHANGE = 0x1D, WM_GETDLGCODE = 0x87, WM_GETFONT = 0x31, WM_GETHOTKEY = 0x33, WM_GETICON = 0x7F, WM_GETMINMAXINFO = 0x24, WM_GETOBJECT = 0x3D, WM_GETTEXT = 0xD, WM_GETTEXTLENGTH = 0xE, WM_HANDHELDFIRST = 0x358, WM_HANDHELDLAST = 0x35F, WM_HELP = 0x53, WM_HOTKEY = 0x312, WM_HSCROLL = 0x114, WM_HSCROLLCLIPBOARD = 0x30E, WM_ICONERASEBKGND = 0x27, WM_IME_CHAR = 0x286, WM_IME_COMPOSITION = 0x10F, WM_IME_COMPOSITIONFULL = 0x284, WM_IME_CONTROL = 0x283, WM_IME_ENDCOMPOSITION = 0x10E, WM_IME_KEYDOWN = 0x290, WM_IME_KEYLAST = 0x10F, WM_IME_KEYUP = 0x291, WM_IME_NOTIFY = 0x282, WM_IME_REQUEST = 0x288, WM_IME_SELECT = 0x285, WM_IME_SETCONTEXT = 0x281, WM_IME_STARTCOMPOSITION = 0x10D, WM_INITDIALOG = 0x110, WM_INITMENU = 0x116, WM_INITMENUPOPUP = 0x117, WM_INPUTLANGCHANGE = 0x51, WM_INPUTLANGCHANGEREQUEST = 0x50, WM_KEYDOWN = 0x100, WM_KEYFIRST = 0x100, WM_KEYLAST = 0x108, WM_KEYUP = 0x101, WM_KILLFOCUS = 0x8, WM_LBUTTONDBLCLK = 0x203, WM_LBUTTONDOWN = 0x201, WM_LBUTTONUP = 0x202, WM_MBUTTONDBLCLK = 0x209, WM_MBUTTONDOWN = 0x207, WM_MBUTTONUP = 0x208, WM_MDIACTIVATE = 0x222, WM_MDICASCADE = 0x227, WM_MDICREATE = 0x220, WM_MDIDESTROY = 0x221, WM_MDIGETACTIVE = 0x229, WM_MDIICONARRANGE = 0x228, WM_MDIMAXIMIZE = 0x225, WM_MDINEXT = 0x224, WM_MDIREFRESHMENU = 0x234, WM_MDIRESTORE = 0x223, WM_MDISETMENU = 0x230, WM_MDITILE = 0x226, WM_MEASUREITEM = 0x2C, WM_MENUCHAR = 0x120, WM_MENUCOMMAND = 0x126, WM_MENUDRAG = 0x123, WM_MENUGETOBJECT = 0x124, WM_MENURBUTTONUP = 0x122, WM_MENUSELECT = 0x11F, WM_MOUSEACTIVATE = 0x21, WM_MOUSEFIRST = 0x200, WM_MOUSEHOVER = 0x2A1, WM_MOUSELAST = 0x20A, WM_MOUSELEAVE = 0x2A3, WM_MOUSEMOVE = 0x200, WM_MOUSEWHEEL = 0x20A, WM_MOVE = 0x3, WM_MOVING = 0x216, WM_NCACTIVATE = 0x86, WM_NCCALCSIZE = 0x83, WM_NCCREATE = 0x81, WM_NCDESTROY = 0x82, WM_NCHITTEST = 0x84, WM_NCLBUTTONDBLCLK = 0xA3, WM_NCLBUTTONDOWN = 0xA1, WM_NCLBUTTONUP = 0xA2, WM_NCMBUTTONDBLCLK = 0xA9, WM_NCMBUTTONDOWN = 0xA7, WM_NCMBUTTONUP = 0xA8, WM_NCMOUSEHOVER = 0x2A0, WM_NCMOUSELEAVE = 0x2A2, WM_NCMOUSEMOVE = 0xA0, WM_NCPAINT = 0x85, WM_NCRBUTTONDBLCLK = 0xA6, WM_NCRBUTTONDOWN = 0xA4, WM_NCRBUTTONUP = 0xA5, WM_NEXTDLGCTL = 0x28, WM_NEXTMENU = 0x213, WM_NOTIFY = 0x4E, WM_NOTIFYFORMAT = 0x55, WM_NULL = 0x0, WM_PAINT = 0xF, WM_PAINTCLIPBOARD = 0x309, WM_PAINTICON = 0x26, WM_PALETTECHANGED = 0x311, WM_PALETTEISCHANGING = 0x310, WM_PARENTNOTIFY = 0x210, WM_PASTE = 0x302, WM_PENWINFIRST = 0x380, WM_PENWINLAST = 0x38F, WM_POWER = 0x48, WM_PRINT = 0x317, WM_PRINTCLIENT = 0x318, WM_QUERYDRAGICON = 0x37, WM_QUERYENDSESSION = 0x11, WM_QUERYNEWPALETTE = 0x30F, WM_QUERYOPEN = 0x13, WM_QUEUESYNC = 0x23, WM_QUIT = 0x12, WM_RBUTTONDBLCLK = 0x206, WM_RBUTTONDOWN = 0x204, WM_RBUTTONUP = 0x205, WM_RENDERALLFORMATS = 0x306, WM_RENDERFORMAT = 0x305, WM_SETCURSOR = 0x20, WM_SETFOCUS = 0x7, WM_SETFONT = 0x30, WM_SETHOTKEY = 0x32, WM_SETICON = 0x80, WM_SETREDRAW = 0xB, WM_SETTEXT = 0xC, WM_SETTINGCHANGE = 0x1A, WM_SHOWWINDOW = 0x18, WM_SIZE = 0x5, WM_SIZECLIPBOARD = 0x30B, WM_SIZING = 0x214, WM_SPOOLERSTATUS = 0x2A, WM_STYLECHANGED = 0x7D, WM_STYLECHANGING = 0x7C, WM_SYNCPAINT = 0x88, WM_SYSCHAR = 0x106, WM_SYSCOLORCHANGE = 0x15, WM_SYSCOMMAND = 0x112, WM_SYSDEADCHAR = 0x107, WM_SYSKEYDOWN = 0x104, WM_SYSKEYUP = 0x105, WM_TCARD = 0x52, WM_TIMECHANGE = 0x1E, WM_TIMER = 0x113, WM_UNDO = 0x304, WM_UNINITMENUPOPUP = 0x125, WM_USER = 0x400, WM_USERCHANGED = 0x54, WM_VKEYTOITEM = 0x2E, WM_VSCROLL = 0x115, WM_VSCROLLCLIPBOARD = 0x30A, WM_XBUTTONDOWN = 0x020B, WM_WINDOWPOSCHANGED = 0x47, WM_WINDOWPOSCHANGING = 0x46, WM_WININICHANGE = 0x1A } /// <summary> /// Raises the <see cref="Quit"/> event /// </summary> protected void OnQuit() { EventHandler h = Quit; if (null != h) h(this, EventArgs.Empty); } /// <summary> /// Raised when the browser application quits /// </summary> /// <remarks> /// Do not confuse this with DWebBrowserEvents2.Quit... That's something else. /// </remarks> public event EventHandler Quit; #endregion } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Browser/ExtendedWebBrowser.cs
C#
gpl3
23,378
using System; using System.ComponentModel; namespace Samba.Presentation.Common.Browser { /// <summary> /// Used in the new navigation events /// </summary> public class BrowserExtendedNavigatingEventArgs : CancelEventArgs { private Uri _Url; /// <summary> /// The URL to navigate to /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public Uri Url { get { return _Url; } } private string _Frame; /// <summary> /// The name of the frame to navigate to /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string Frame { get { return _Frame; } } /// <summary> /// The pointer to ppDisp /// </summary> public object AutomationObject { get; set; } /// <summary> /// Creates a new instance of WebBrowserExtendedNavigatingEventArgs /// </summary> /// <param name="automation">Pointer to the automation object of the browser</param> /// <param name="url">The URL to go to</param> /// <param name="frame">The name of the frame</param> /// <param name="navigationContext">The new window flags</param> public BrowserExtendedNavigatingEventArgs(object automation, Uri url, string frame) : base() { _Url = url; _Frame = frame; this.AutomationObject = automation; } } public class SizeChangedEventArgs : EventArgs { public int Size { get; set; } public SizeChangedEventArgs(int size) { Size = size; } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Browser/BrowserExtendedNavigatingEventArgs.cs
C#
gpl3
1,905
using System.Windows.Controls; using Samba.Presentation.Common.ModelBase; namespace Samba.Presentation.Common { public static class CommonEventPublisher { public static void PublishDashboardCommandEvent(ICategoryCommand command) { command.PublishEvent(EventTopicNames.DashboardCommandAdded); } public static void PublishNavigationCommandEvent(ICategoryCommand command) { command.PublishEvent(EventTopicNames.NavigationCommandAdded); } public static void PublishViewAddedEvent(VisibleViewModelBase view) { view.PublishEvent(EventTopicNames.ViewAdded,true); } public static void PublishViewClosedEvent(VisibleViewModelBase view) { view.PublishEvent(EventTopicNames.ViewClosed,true); } public static void PublishDashboardUnloadedEvent(UserControl userControl) { userControl.PublishEvent(EventTopicNames.DashboardClosed); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/CommonEventPublisher.cs
C#
gpl3
1,057
using System.Windows.Input; namespace Samba.Presentation.Common { public interface ICaptionCommand : ICommand { string Caption { get; set; } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/ICaptionCommand.cs
C#
gpl3
178
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Samba.Domain.Models.Actions; using Samba.Infrastructure.Data.Serializer; using Samba.Services; namespace Samba.Presentation.Common { public class ActionData { public AppAction Action { get; set; } public string ParameterValues { get; set; } public object DataObject { get; set; } public T GetDataValue<T>(string parameterName) where T : class { var property = DataObject.GetType().GetProperty(parameterName); if (property != null) return property.GetValue(DataObject, null) as T; return null; } public bool GetAsBoolean(string parameterName) { bool result; bool.TryParse(GetAsString(parameterName), out result); return result; } public string GetAsString(string parameterName) { return Action.GetFormattedParameter(parameterName, DataObject, ParameterValues); } public decimal GetAsDecimal(string parameterName) { decimal result; decimal.TryParse(GetAsString(parameterName), out result); return result; } public int GetAsInteger(string parameterName) { int result; int.TryParse(GetAsString(parameterName), out result); return result; } } public static class SettingAccessor { private static readonly IDictionary<string, string> Cache = new Dictionary<string, string>(); public static void ResetCache() { Cache.Clear(); } public static string ReplaceSettings(string value) { if (value == null) return ""; while (Regex.IsMatch(value, "\\{:[^}]+\\}", RegexOptions.Singleline)) { var match = Regex.Match(value, "\\{:([^}]+)\\}"); var tagName = match.Groups[0].Value; var settingName = match.Groups[1].Value; if (!Cache.ContainsKey(settingName)) Cache.Add(settingName, AppServices.SettingService.ReadSetting(settingName).StringValue); var settingValue = Cache[settingName]; value = value.Replace(tagName, settingValue); } return value; } } public static class RuleExecutor { public static void NotifyEvent(string eventName, object dataObject) { SettingAccessor.ResetCache(); var rules = AppServices.MainDataContext.Rules.Where(x => x.EventName == eventName); foreach (var rule in rules.Where(x => string.IsNullOrEmpty(x.EventConstraints) || SatisfiesConditions(x, dataObject))) { foreach (var actionContainer in rule.Actions) { var container = actionContainer; var action = AppServices.MainDataContext.Actions.SingleOrDefault(x => x.Id == container.AppActionId); if (action != null) { var clonedAction = ObjectCloner.Clone(action); var containerParameterValues = container.ParameterValues ?? ""; clonedAction.Parameter = SettingAccessor.ReplaceSettings(clonedAction.Parameter); containerParameterValues = SettingAccessor.ReplaceSettings(containerParameterValues); var data = new ActionData { Action = clonedAction, DataObject = dataObject, ParameterValues = containerParameterValues }; data.PublishEvent(EventTopicNames.ExecuteEvent, true); } } } } private static bool SatisfiesConditions(AppRule appRule, object dataObject) { var constraints = SettingAccessor.ReplaceSettings(appRule.EventConstraints); var conditions = constraints.Split('#') .Select(x => new RuleConstraintViewModel(x)); var parameterNames = dataObject.GetType().GetProperties().Select(x => x.Name); foreach (var condition in conditions) { var parameterName = parameterNames.FirstOrDefault(condition.Name.Equals); if (!string.IsNullOrEmpty(parameterName)) { var property = dataObject.GetType().GetProperty(parameterName); var parameterValue = property.GetValue(dataObject, null) ?? ""; if (!condition.ValueEquals(parameterValue)) return false; } else { if (condition.Name.StartsWith("SN$")) { var settingName = condition.Name.Replace("SN$", ""); while (Regex.IsMatch(settingName, "\\[[^\\]]+\\]")) { var paramvalue = Regex.Match(settingName, "\\[[^\\]]+\\]").Groups[0].Value; var insideValue = paramvalue.Trim(new[] { '[', ']' }); if (parameterNames.Contains(insideValue)) { var v = dataObject.GetType().GetProperty(insideValue).GetValue(dataObject, null).ToString(); settingName = settingName.Replace(paramvalue, v); } else { if (paramvalue == "[Day]") settingName = settingName.Replace(paramvalue, DateTime.Now.Day.ToString()); else if (paramvalue == "[Month]") settingName = settingName.Replace(paramvalue, DateTime.Now.Month.ToString()); else if (paramvalue == "[Year]") settingName = settingName.Replace(paramvalue, DateTime.Now.Year.ToString()); else settingName = settingName.Replace(paramvalue, ""); } } var customSettingValue = AppServices.SettingService.ReadSetting(settingName).StringValue ?? ""; if (!condition.ValueEquals(customSettingValue)) return false; } if (condition.Name == "TerminalName" && !string.IsNullOrEmpty(condition.Value)) { if (!condition.Value.Equals(AppServices.CurrentTerminal.Name)) { return false; } } if (condition.Name == "DepartmentName" && !string.IsNullOrEmpty(condition.Value)) { if (AppServices.MainDataContext.SelectedDepartment == null || !condition.Value.Equals(AppServices.MainDataContext.SelectedDepartment.Name)) { return false; } } if (condition.Name == "UserName" && !string.IsNullOrEmpty(condition.Value)) { if (AppServices.CurrentLoggedInUser == null || !condition.Value.Equals(AppServices.CurrentLoggedInUser.Name)) { return false; } } } } return true; } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/RuleExecutor.cs
C#
gpl3
7,923
using Microsoft.Practices.Prism.Events; namespace Samba.Presentation.Common { public class GenericEvent<TValue> : CompositePresentationEvent<EventParameters<TValue>> { } public class EventParameters<TValue> { public string Topic { get; set; } public TValue Value { get; set; } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/GenericEvent.cs
C#
gpl3
330
using System; using Samba.Services; namespace Samba.Presentation.Common { public class Message { public Message(string rawMessage) { Key = rawMessage.Substring(0, rawMessage.IndexOf(':')); var message = rawMessage.Split(':')[1]; string command = message.Substring(1, message.IndexOf(">") - 1); string data = message.Substring(message.IndexOf(">") + 1); Command = command; Data = data; } public string Key { get; set; } public string Command { get; set; } public string Data { get; set; } public int DataCount { get { return Data.Split('#').Length; } } public string GetData(int index) { string result = ""; if (index < DataCount) { result = Data.Split('#')[index]; } return result; } } public static class MessageProcessor { public static void ProcessMessage(string message) { new Message(message).PublishEvent(EventTopicNames.MessageReceivedEvent); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/MessageProcessor.cs
C#
gpl3
1,192
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Input; using System.Windows.Media; using System.Windows.Threading; namespace Samba.Presentation.Common { delegate void PublishEventDelegate<in TEventSubject>(TEventSubject eventArgs, string eventTopic); public static class ExtensionServices { public static void BackgroundFocus(this UIElement el) { Action a = () => Keyboard.Focus(el); el.Dispatcher.BeginInvoke(DispatcherPriority.Input, a); } public static void BackgroundSelectAll(this TextBox textBox) { Action a = textBox.SelectAll; textBox.Dispatcher.BeginInvoke(DispatcherPriority.Input, a); } public static void _PublishEvent<TEventsubject>(this TEventsubject eventArgs, string eventTopic) { EventServiceFactory.EventService.GetEvent<GenericEvent<TEventsubject>>() .Publish(new EventParameters<TEventsubject> { Topic = eventTopic, Value = eventArgs }); } public static void PublishEvent<TEventsubject>(this TEventsubject eventArgs, string eventTopic) { PublishEvent(eventArgs, eventTopic, false); } public static void PublishEvent<TEventsubject>(this TEventsubject eventArgs, string eventTopic, bool wait) { if (wait) Application.Current.Dispatcher.Invoke(new PublishEventDelegate<TEventsubject>(_PublishEvent), eventArgs, eventTopic); else Application.Current.Dispatcher.BeginInvoke(new PublishEventDelegate<TEventsubject>(_PublishEvent), eventArgs, eventTopic); } public static void AddRange<T>(this ObservableCollection<T> oc, IEnumerable<T> collection) { if (collection == null) { throw new ArgumentNullException("collection"); } foreach (var item in collection) { oc.Add(item); } } private static readonly Action EmptyDelegate = delegate { }; public static void Refresh(this UIElement uiElement) { uiElement.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate); } public static TContainer GetContainerFromIndex<TContainer>(this ItemsControl itemsControl, int index) where TContainer : DependencyObject { return (TContainer) itemsControl.ItemContainerGenerator.ContainerFromIndex(index); } public static bool IsEditing(this DataGrid dataGrid) { return dataGrid.GetEditingRow() != null; } public static DataGridRow GetEditingRow(this DataGrid dataGrid) { var sIndex = dataGrid.SelectedIndex; if (sIndex >= 0) { var selected = dataGrid.GetContainerFromIndex<DataGridRow>(sIndex); if (selected != null && selected.IsEditing) return selected; } for (int i = 0; i < dataGrid.Items.Count; i++) { if (i == sIndex) continue; var item = dataGrid.GetContainerFromIndex<DataGridRow>(i); if (item !=null && item.IsEditing) return item; } return null; } public static DataGridCell GetCell(this DataGrid dataGrid, int row, int column) { DataGridRow rowContainer = GetRow(dataGrid, row); if (rowContainer != null) { var presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer); if (presenter == null) { dataGrid.ScrollIntoView(rowContainer, dataGrid.Columns[column]); presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer); } var cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column); if (cell == null) { dataGrid.ScrollIntoView(rowContainer, dataGrid.Columns[column]); cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column); } return cell; } return null; } public static DataGridRow GetRow(this DataGrid dataGrid, int index) { var row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(index); if (row == null) { dataGrid.ScrollIntoView(dataGrid.Items[index]); row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(index); } return row; } public static T GetVisualChild<T>(DependencyObject parent) where T : DependencyObject { var child = default(T); var numVisuals = VisualTreeHelper.GetChildrenCount(parent); for (var i = 0; i < numVisuals; i++) { var v = VisualTreeHelper.GetChild(parent, i); child = v as T ?? GetVisualChild<T>(v); if (child != null) { break; } } return child; } public static string AsCsv<T>(this IEnumerable<T> items) where T : class { var csvBuilder = new StringBuilder(); var properties = typeof(T).GetProperties(); csvBuilder.AppendLine(string.Join(",", (from a in properties select a.Name).ToArray())); foreach (T item in items) { var line = string.Join(",", properties.Select(p => p.GetValue(item, null).ToCsvValue()).ToArray()); csvBuilder.AppendLine(line); } return csvBuilder.ToString(); } private static string ToCsvValue<T>(this T item) where T : class { if (item is string) { return string.Format("\"{0}\"", item.ToString().Replace("\"", "\\\"")); ; } return string.Format("\"{0}\"", item); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/ExtensionServices.cs
C#
gpl3
6,496
using System; using System.Globalization; namespace Samba.Presentation.Common { public static class Helpers { public static string AddTypedValue(string actualValue, string typedValue, string format) { decimal amnt; bool stringMode = false; decimal.TryParse(actualValue, out amnt); if (amnt == 0) stringMode = true; else { decimal.TryParse(typedValue, out amnt); if (amnt == 0) stringMode = true; } string dc = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator; if (typedValue == "." || typedValue == ",") { actualValue += dc; return actualValue; } if (stringMode) return actualValue + typedValue; string fmt = "0"; string rfmt = format; if (actualValue.Contains(dc)) { int dCount = (actualValue.Length - actualValue.IndexOf(dc)); fmt = "0.".PadRight(dCount + 2, '0'); rfmt = format.PadRight(dCount + rfmt.Length, '0'); } string amount = string.IsNullOrEmpty(actualValue) ? "0" : Convert.ToDecimal(actualValue).ToString(fmt); if (amount.Contains(dc)) amount = amount.Substring(0, amount.Length - 1); amnt = Convert.ToDecimal(amount + typedValue); return (amnt).ToString(rfmt); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/Helpers.cs
C#
gpl3
1,620
using System; using System.ComponentModel; using System.Globalization; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace Samba.Presentation.Common { public class MaskedTextBox : TextBox { #region DependencyProperties public static readonly DependencyProperty UnmaskedTextProperty = DependencyProperty.Register("UnmaskedText", typeof(string), typeof(MaskedTextBox), new UIPropertyMetadata("")); public static readonly DependencyProperty InputMaskProperty = DependencyProperty.Register("InputMask", typeof(string), typeof(MaskedTextBox), null); public static readonly DependencyProperty PromptCharProperty = DependencyProperty.Register("PromptChar", typeof(char), typeof(MaskedTextBox), new PropertyMetadata('_')); public string UnmaskedText { get { return (string)GetValue(UnmaskedTextProperty); } set { SetValue(UnmaskedTextProperty, value); } } public string InputMask { get { return (string)GetValue(InputMaskProperty); } set { SetValue(InputMaskProperty, value); } } public char PromptChar { get { return (char)GetValue(PromptCharProperty); } set { SetValue(PromptCharProperty, value); } } #endregion private MaskedTextProvider _provider; public MaskedTextBox() { Loaded += MaskedTextBoxLoaded; PreviewTextInput += MaskedTextBoxPreviewTextInput; PreviewKeyDown += MaskedTextBoxPreviewKeyDown; } private void MaskedTextBoxPreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Space) { TreatSelectedText(); int position = GetNextCharacterPosition(SelectionStart, true); if (_provider.InsertAt(" ", position)) RefreshText(position); e.Handled = true; } if (e.Key == Key.Back) { TreatSelectedText(); var position = this.GetNextCharacterPosition(SelectionStart, false); e.Handled = true; if (SelectionStart > 0) { if (position == SelectionStart) position = this.GetNextCharacterPosition(position - 1, false); if (_provider.RemoveAt(position)) { position = GetNextCharacterPosition(position, false); } } RefreshText(position); e.Handled = true; } if (e.Key == Key.Delete) { if (TreatSelectedText()) { RefreshText(SelectionStart); } else { if (_provider.RemoveAt(SelectionStart)) RefreshText(SelectionStart); } e.Handled = true; } } private void MaskedTextBoxPreviewTextInput(object sender, TextCompositionEventArgs e) { TreatSelectedText(); int position = GetNextCharacterPosition(SelectionStart, true); if (Keyboard.IsKeyToggled(Key.Insert)) { if (_provider.Replace(e.Text, position)) position++; } else { if (_provider.InsertAt(e.Text, position)) position++; } position = GetNextCharacterPosition(position, true); RefreshText(position); e.Handled = true; } private void MaskedTextBoxLoaded(object sender, RoutedEventArgs e) { _provider = new MaskedTextProvider(InputMask ?? " ", CultureInfo.CurrentCulture); _provider.Set(String.IsNullOrWhiteSpace(UnmaskedText) ? String.Empty : UnmaskedText); _provider.PromptChar = PromptChar; Text = _provider.ToDisplayString(); DependencyPropertyDescriptor textProp = DependencyPropertyDescriptor.FromProperty(TextProperty, typeof(MaskedTextBox)); if (textProp != null) { textProp.AddValueChanged(this, (s, args) => UpdateText()); } DataObject.AddPastingHandler(this, Pasting); } private void Pasting(object sender, DataObjectPastingEventArgs e) { if (e.DataObject.GetDataPresent(typeof(string))) { var pastedText = (string)e.DataObject.GetData(typeof(string)); TreatSelectedText(); int position = GetNextCharacterPosition(SelectionStart, true); if (_provider.InsertAt(pastedText, position)) { RefreshText(position); } } e.CancelCommand(); } private void UpdateText() { if (_provider.ToDisplayString().Equals(Text)) return; bool success = _provider.Set(Text); SetText(success ? _provider.ToDisplayString() : Text, _provider.ToString(false, false)); } private bool TreatSelectedText() { if (SelectionLength > 0) { return _provider.RemoveAt(SelectionStart, SelectionStart + SelectionLength - 1); } return false; } private void RefreshText(int position) { SetText(_provider.ToDisplayString(), _provider.ToString(false, false)); SelectionStart = position; } private void SetText(string text, string unmaskedText) { UnmaskedText = String.IsNullOrWhiteSpace(unmaskedText) ? null : unmaskedText; Text = String.IsNullOrWhiteSpace(text) ? null : text; } private int GetNextCharacterPosition(int startPosition, bool goForward) { var position = _provider.FindEditPositionFrom(startPosition, goForward); return position == -1 ? startPosition : position; } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/MaskedTextBox.cs
C#
gpl3
6,720
using System.Collections.Generic; using System.Linq; namespace Samba.Presentation.Common { public class DashboardCommandCategory { private readonly List<ICategoryCommand> _commands; public int Order { get; set; } public string Category { get; set; } public IEnumerable<ICategoryCommand> Commands { get { return _commands.OrderBy(x => x.Order); } } public DashboardCommandCategory(string category) { Category = category; _commands=new List<ICategoryCommand>(); } public void AddCommand(ICategoryCommand command) { _commands.Add(command); } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/CommandCategory.cs
C#
gpl3
701
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.Presentation.Common")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Samba.Presentation.Common")] [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("c34ab04f-da30-4cdf-a9ad-dad0b31d3a5a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzgaminginc-pointofssale
Samba.Presentation.Common/Properties/AssemblyInfo.cs
C#
gpl3
1,462
using System.Windows; using System.Windows.Controls; namespace Samba.Presentation.Common { public class DataGridContextHelper { static DataGridContextHelper() { DependencyProperty dp = FrameworkElement.DataContextProperty.AddOwner(typeof(DataGridColumn)); FrameworkElement.DataContextProperty.OverrideMetadata(typeof(DataGrid), new FrameworkPropertyMetadata (null, FrameworkPropertyMetadataOptions.Inherits, new PropertyChangedCallback(OnDataContextChanged))); } public static void OnDataContextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { DataGrid grid = d as DataGrid; if (grid != null) { foreach (DataGridColumn col in grid.Columns) { col.SetValue(FrameworkElement.DataContextProperty, e.NewValue); } } } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/DataContextGrid.cs
C#
gpl3
1,020
namespace Samba.Presentation.Common { public interface ICategoryCommand : ICaptionCommand { string Category { get; set; } string ImageSource { get; set; } int Order { get; set; } } }
zzgaminginc-pointofssale
Samba.Presentation.Common/ICategoryCommand.cs
C#
gpl3
231