We have a Till Software which also works with restaurants built on .NET (C#) and Firebird DB. We are having a strange problem recently, the items in an order are duplicating themselves when we go back to the order.
Strangely it's not the case always. It's happening only sometimes. I tried to figure out under what conditions it's happening but it's so random that it doesn't happen for a couple of days and then start duplicating items for the next two days.
The software is so huge that I don't know what code snippets to even post. As it's not happening always and is random I guess it doesn't have to do with the code but with Firebird DB maybe.
The other thing I wanted to mention is that we had a Firebird DB built on a 32-bit machine and when we tried to put it on a 64 - bit machine it didn't work. So, we had to take a backup of the DB on a 32-bit machine and restore it on a 64-bit machine and it worked with the software. I'm thinking does that have something to do with it? but we have another user on 32-bit with no conversion and it's the same case for him as well.
I'll really appreciate any help or guidance on this.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using Till_Library.Till_Controls;
using Till_Library.Till_Interfaces;
using Till_Library.Till_Presenters;
using Till_Library.Till_Types;
namespace Till_Library.Till_Views
{
public partial class viewOrderItems : UserControl
{
private IOrder mIOrder;
private PresenterOrder mPresenterOrder;
private readonly List<OrderGridItemRow> mOrderItemRowList;
private OrderGridItemRow mCurrentItemRow;
private readonly Color paidBckcolour = Color.GreenYellow;
private decimal mTillMode;
private readonly int ITEM_GRID_ROWS;
private int mItemGridStartIdx;
private int mItemGridEndIdx;
private int mLastDisplayedRowIdx;
private int mLastItemCount;
private bool mSplitMode;
public bool mIsRefund;
private RestTable mCurrentTable;
public delegate void TillCustDetailsClickedHandler();
public delegate void TillOrderItemPhoneClickedHandler();
public delegate void TillOrderTableSelectionClickedHandler();
public delegate void TillOrderTableCoverClickedHandler();
public delegate void TillOrderPriceClickedHandler(Point KeyPadLocation);
public delegate void TillOrderQuantityClickedHandler(Point KeyPadLocation);
public delegate void TillOrderItemClickedHandler(bool Option);
public delegate void TillOrderCheckBoxClickedHandler(OrderItemDetails pOrderItemRow);
public viewOrderItems(bool isRefund = false)
{
InitializeComponent();
ITEM_GRID_ROWS = 11;
mItemGridStartIdx = 0;
mItemGridEndIdx = ITEM_GRID_ROWS;
mIsRefund = isRefund;
int CurY = 0;
mIOrder = new IOrder();
mOrderItemRowList = new List<OrderGridItemRow>();
for (int i = 1; i <= ITEM_GRID_ROWS; i++)
{
CreateOrderItemRowControl(i, CurY);
CurY += 36;
}
}
private void CreateOrderItemRowControl(int pIdx, int pCurY)
{
string ItemRowName = "orderGridItemRow" + pIdx;
mOrderItemRowList.Add(new OrderGridItemRow(pIdx));
mOrderItemRowList[pIdx - 1].Name = ItemRowName;
mOrderItemRowList[pIdx - 1].Location = new Point(4, pCurY);
mOrderItemRowList[pIdx - 1].Parent = panItems;
//OrderItemRowList[pIdx - 1].Parent = panel2;
mOrderItemRowList[pIdx - 1].OrderItemClicked += TillOrderItemClicked;
mOrderItemRowList[pIdx - 1].OrderItemPriceClicked += TillOrderItemPriceClicked;
mOrderItemRowList[pIdx - 1].OrderItemPriceLeft += TillOrderItemPriceLeft;
mOrderItemRowList[pIdx - 1].OrderItemQuantityClicked += TillOrderItemQuantityClicked;
mOrderItemRowList[pIdx - 1].OrderCheckBoxClicked += OrderCheckboxClicked;
mOrderItemRowList[pIdx - 1].Visible = true;
mOrderItemRowList[pIdx - 1].SetOrderType(false);
mOrderItemRowList[pIdx - 1].IsRefund(mIsRefund);
}
[Category("Action")]
[Description("Cust Details clicked.")]
public event TillCustDetailsClickedHandler TillCustDetailsClicked;
protected virtual void OnCustDetailsClicked()
{
if (TillCustDetailsClicked != null)
{
//if(mTillMode != 3)
TillCustDetailsClicked(); // Notify Subscribers
}
}
public void AttachInterface(IOrder pIOrder)
{
mIOrder = pIOrder;
}
public void AttachPresenter(PresenterOrder pPresenter)
{
mPresenterOrder = pPresenter;
}
public void AttachOptions(IOptions pIOptions)
{
}
public void AttachTableControl(RestTable pTable)
{
if (pTable != null)
{
mCurrentTable = pTable;
labTableNo.Text = mCurrentTable.Name;
}
else
{
labTableNo.Text = "0";
labTableCovers.Text = "0";
}
}
public void SetTillMode(decimal pTillMode)
{
mTillMode = pTillMode;
if (mTillMode == 2) // Restaurant Mode
{
labTableNo.Visible = true;
labTableNoDesc.Visible = true;
labTableCovers.Visible = true;
labTableCoversDesc.Visible = true;
labCustName.Visible = false;
labCustNameTitle.Visible = false;
}
else if (mTillMode == 3) // Supermarket Mode
{
// This till mode also stops OnCustDetailsClicked() from firing
labTableNo.Visible = false;
labTableNoDesc.Visible = false;
labTableCovers.Visible = false;
labTableCoversDesc.Visible = false;
labCustName.Visible = false;
labCustNameTitle.Visible = false;
panPhone.Visible = false;
}
else // Takeaway Mode (Default)
{
labTableNo.Visible = false;
labTableNoDesc.Visible = false;
labTableCovers.Visible = false;
labTableCoversDesc.Visible = false;
labCustName.Visible = true;
labCustNameTitle.Visible = true;
}
}
public ORDERTYPE GetOrderType()
{
return mIOrder.mCurrentOrderDetails.OrderType;
}
public void DisplayOrder(bool pRecall, bool pMoveToLast = false)
{
mPresenterOrder.AttachOrderView(this);
mPresenterOrder.AttachOrderItemRowList(mOrderItemRowList);
if (mIOrder.mCurrentOrderItems.Count <= 11 && mIOrder.mCurrentOrderItems.Count > mLastItemCount &&
!pRecall && mTillMode == 3)
mPresenterOrder.ProcessPanelDisplayBETA(false);
else
mPresenterOrder.ProcessPanelDisplay(false, pMoveToLast); // time waster
mLastItemCount = mIOrder.mCurrentOrderItems.Count; // Accumulated Quantity Bug Fix & void ln
// DisplayOrderDetails();
}
public void DisplayOrderDetails()
{
labOrderNo.Text = mIOrder.mCurrentOrderDetails.OrderNo.ToString();
labCustNo.Text = mIOrder.mCurrentOrderDetails.OrderCustDetails.CustNo;
labTableNo.Text = mIOrder.mCurrentOrderDetails.OrderTableNo.ToString();
labTableCovers.Text = mIOrder.mCurrentOrderDetails.OrderTableCovers.ToString();
labCustNameTitle.Visible = false;
labCustName.Text = mIOrder.mCurrentOrderDetails.OrderCustDetails.CustName;
if (labCustName.Text != "")
{
labCustNameTitle.Visible = true;
}
//mPresenterOrder.UpdateTotals();
//labDeliveryAmt.Text = mIOrder.mCurrentOrderDetails.OrderDeliveryTotal.ToString("0.00");
//labDiscountAmt.Text = mIOrder.mCurrentOrderDetails.OrderDiscountPerc.ToString()+"%";
if (mIOrder.mCurrentOrderDetails.OrderDeliveryTotal > 0)
{
labDelivery.Text = "Delivery";
labDelivery.Visible = true;
labDeliveryAmt.Text = mIOrder.mCurrentOrderDetails.OrderDeliveryTotal.ToString("0.00");
}
else if (mTillMode == 3 && mIOrder.mCurrentOrderDetails.OrderQty > 0 &&
mIOrder.mCurrentOrderDetails.OrderVAT == 0)
{
labDelivery.Text = "Item Qty";
labDelivery.Visible = true;
labDeliveryAmt.Text = mIOrder.mCurrentOrderDetails.OrderQty.ToString();
}
else if (mIOrder.mCurrentOrderDetails.OrderVAT > 0)
{
labDelivery.Text = "VAT";
labDelivery.Visible = true;
labDeliveryAmt.Text = mIOrder.mCurrentOrderDetails.OrderVAT.ToString("0.00");
labDelivery.Font = new Font(labNetAmt.Font.FontFamily.Name, labNetAmt.Font.Size);
}
else
{
labDelivery.Visible = false;
labDeliveryAmt.Text = string.Empty;
}
if (mTillMode == 3 && mIOrder.mCurrentOrderDetails.OrderQty > 0 && mIOrder.mCurrentOrderDetails.OrderVAT > 0)
{
labDiscount.Text = "Item Qty";
labDiscount.Visible = true;
labDiscountAmt.Text = mIOrder.mCurrentOrderDetails.OrderQty.ToString();
}
else if (mIOrder.mCurrentOrderDetails.OrderDiscountAmt > 0)
{
labDiscount.Text = "Discount";
labDiscount.Visible = true;
labDiscountAmt.Text = mIOrder.mCurrentOrderDetails.OrderDiscountAmt.ToString("0.00");
}
else
{
labDiscount.Visible = false;
labDiscountAmt.Text = string.Empty;
}
double NetAmount = mIOrder.mCurrentOrderDetails.OrderNET;
// +mIOrder._mCurrentOrderDetails.OrderVAT;
if (mIOrder.mCurrentOrderDetails.OptionAddVATToPrice)
{
labNetAmt.Text = NetAmount.ToString("0.00");
labTotalAmt.Text =
(NetAmount + +mIOrder.mCurrentOrderDetails.OrderVAT +
mIOrder.mCurrentOrderDetails.OrderDeliveryTotal - mIOrder.mCurrentOrderDetails.OrderDiscountAmt)
.ToString("0.00");
}
else
{
labNetAmt.Text = (NetAmount - mIOrder.mCurrentOrderDetails.OrderVAT).ToString("0.00");
labTotalAmt.Text =
(NetAmount + mIOrder.mCurrentOrderDetails.OrderDeliveryTotal -
mIOrder.mCurrentOrderDetails.OrderDiscountAmt).ToString("0.00");
}
if (Convert.ToDouble(labTotalAmt.Text) < 0)
labTotalAmt.Text = "0.00";
CheckPaid();
}
public List<OrderGridItemRow> GetOrderItemRowList()
{
return mOrderItemRowList;
}
public IOrder GetIOrder()
{
return mIOrder;
}
public int GetPanelHeight()
{
return panItems.Height;
}
private void CheckPaid()
{
// RP Sets the total box to the local 'paidBckcolour' if the order displaied has been paid for, if not reverts back to default.
if ((mIOrder.mCurrentOrderDetails.OrderPayment >= mIOrder.mCurrentOrderDetails.OrderTotal) &&
mIOrder.mCurrentOrderDetails.OrderTotal != 0)
{
labDeliveryAmt.BackColor = paidBckcolour;
labDiscountAmt.BackColor = paidBckcolour;
labNetAmt.BackColor = paidBckcolour;
labTotalAmt.BackColor = paidBckcolour;
labDelivery.BackColor = paidBckcolour;
labDiscount.BackColor = paidBckcolour;
labNet.BackColor = paidBckcolour;
labTotal.BackColor = paidBckcolour;
}
else
{
labDeliveryAmt.BackColor = Color.WhiteSmoke;
labDiscountAmt.BackColor = Color.WhiteSmoke;
labNetAmt.BackColor = Color.WhiteSmoke;
labTotalAmt.BackColor = Color.WhiteSmoke;
labDelivery.BackColor = Color.WhiteSmoke;
labDiscount.BackColor = Color.WhiteSmoke;
labNet.BackColor = Color.WhiteSmoke;
labTotal.BackColor = Color.WhiteSmoke;
}
}
private void btnOrderItemGridUp_Click(object sender, EventArgs e)
{
// TODO
bool bFirstItem = false;
int OffsetIdx = 0;
int OrderItemRowListCount = mOrderItemRowList.Count;
if (OrderItemRowListCount > 0)
{
for (int i = 0; i < OrderItemRowListCount; i++)
{
if (mOrderItemRowList[i].Top >= 0)
{
OffsetIdx = i;
break;
}
}
}
mItemGridEndIdx = mItemGridStartIdx + OffsetIdx;
mItemGridStartIdx = mItemGridEndIdx - ITEM_GRID_ROWS;
if (mItemGridStartIdx < 0 && mItemGridEndIdx < ITEM_GRID_ROWS &&
(mItemGridStartIdx + mItemGridEndIdx + OffsetIdx < ITEM_GRID_ROWS))
{
bFirstItem = true;
mItemGridEndIdx = ITEM_GRID_ROWS;
}
if (!bFirstItem)
{
int GridRowOffset = mOrderItemRowList[mLastDisplayedRowIdx].Bottom - panItems.Height;
if (OrderItemRowListCount > 0 && GridRowOffset > 0)
{
for (int i = 0; i < OrderItemRowListCount; i++)
{
mOrderItemRowList[i].Location = new Point(1, mOrderItemRowList[i].Top - GridRowOffset);
}
}
}
setItemGridIndex(mItemGridStartIdx, mItemGridEndIdx);
mPresenterOrder.ProcessPanelDisplay(false);
mLastDisplayedRowIdx = mPresenterOrder.mLastDisplayedRowIdx;
mItemGridStartIdx = mPresenterOrder.mItemGridStartIdx;
mItemGridEndIdx = mPresenterOrder.mItemGridEndIdx;
}
private void btnOrderItemGridDown_Click(object sender, EventArgs e)
{
int OffsetIdx = 0;
int OrderItemListCount = mOrderItemRowList.Count;
if (OrderItemListCount > 0)
{
for (int i = 0; i < OrderItemListCount; i++)
{
if (mOrderItemRowList[i].Bottom > panItems.Height)
{
OffsetIdx = i;
break;
}
}
}
if (OffsetIdx == 0)
{
OffsetIdx = ITEM_GRID_ROWS;
}
if (mItemGridStartIdx + OffsetIdx <= mIOrder.mCurrentOrderItems.Count)
{
mItemGridStartIdx += OffsetIdx;
mItemGridEndIdx = mItemGridStartIdx + ITEM_GRID_ROWS;
setItemGridIndex(mItemGridStartIdx, mItemGridEndIdx);
mPresenterOrder.ProcessPanelDisplay(false);
mLastDisplayedRowIdx = mPresenterOrder.mLastDisplayedRowIdx;
mItemGridStartIdx = mPresenterOrder.mItemGridStartIdx;
mItemGridEndIdx = mPresenterOrder.mItemGridEndIdx;
//mPresenterOrder.DisplayOrderItems(mOrderItemRowList, panItems.Height);
}
}
private void setItemGridIndex(int pStartIndex, int pEndIndex)
{
if (pStartIndex < 0)
pStartIndex = 0;
mPresenterOrder.mItemGridStartIdx = pStartIndex;
mPresenterOrder.mItemGridEndIdx = pEndIndex;
mPresenterOrder.mLastDisplayedRowIdx = mLastDisplayedRowIdx;
// mLastDisplayedRowIdx = mPresenterOrder.mLastDisplayedRowIdx;
}
public void setSplitMode(bool pMode)
{
mSplitMode = pMode;
}
private void labCustNo_Click(object sender, EventArgs e)
{
OnCustDetailsClicked();
}
private void labCustNoDesc_Click(object sender, EventArgs e)
{
OnCustDetailsClicked();
}
private void labCustName_Click(object sender, EventArgs e)
{
OnCustDetailsClicked();
}
private void labCustNameTitle_Click(object sender, EventArgs e)
{
OnCustDetailsClicked();
}
private void labOrderNoDesc_Click(object sender, EventArgs e)
{
OnCustDetailsClicked();
}
private void labOrderNo_Click(object sender, EventArgs e)
{
OnCustDetailsClicked();
}
private void panCustInfo_Click(object sender, EventArgs e)
{
OnCustDetailsClicked();
}
public void TillMark2PrintClicked()
{
if (mIOrder.mCurrentOrderItems.Count > 0 && mCurrentItemRow != null)
{
mCurrentItemRow.SetMark2PrintOrderSelected(true);
foreach (TillOrderItem item in mIOrder.mCurrentOrderItems)
if (item.GetItemID() == mIOrder.mCurrentOrderItemID)
if (!item.GetMarked2Print())
item.SetMark2Print(true);
else
item.SetMark2Print(false);
}
}
public void TillMark2PrintReset()
{
foreach (TillOrderItem item in mIOrder.mCurrentOrderItems)
item.SetMark2Print(false);
}
[Category("Action")]
[Description("Order Item Price Clicked.")]
public event TillOrderPriceClickedHandler TillOrderPriceClicked;
protected virtual void OnTillOrderPriceClicked(Point pKeyPadLoc)
{
if (TillOrderPriceClicked != null)
{
TillOrderPriceClicked(pKeyPadLoc); // Notify Subscribers
}
}
private void TillOrderItemPriceClicked(OrderGridItemRow pOrderItemRow)
{
OnTillOrderPriceClicked(GetRowLocation(pOrderItemRow));
}
private Point GetRowLocation(OrderGridItemRow pOrderItemRow)
{
int mKeyPadX, mKeyPadY;
Point mFloutingKeypadLoc;
mCurrentItemRow = pOrderItemRow;
mKeyPadX = pOrderItemRow.Location.X + pOrderItemRow.Width + 2;
mKeyPadY = pOrderItemRow.Parent.Location.Y + pOrderItemRow.Location.Y + (pOrderItemRow.Height/2);
mPresenterOrder.ClearOrderItemGridSelections(false);
mIOrder.mCurrentOrderItemID = mCurrentItemRow.ItemID;
mFloutingKeypadLoc = new Point(mKeyPadX, mKeyPadY);
return mFloutingKeypadLoc;
}
private bool TillOrderItemPriceLeft(double pNewItemPrice, double pOldItemPrice)
{
if (pOldItemPrice >= 0)
{
if (pNewItemPrice >= 0)
{
if (SetTillItemPrice(pNewItemPrice))
return true;
}
}
else
{
if (pNewItemPrice < 0)
{
if (SetTillItemPrice(pNewItemPrice))
return true;
}
}
return false;
}
private bool SetTillItemPrice(double pNewItemPrice)
{
foreach (TillOrderItem Item in mIOrder.mCurrentOrderItems)
{
if (Item.GetItemID() == mIOrder.mCurrentOrderItemID)
{
Item.SetItemPrice(pNewItemPrice);
mPresenterOrder.UpdateTotals();
DisplayOrder(false);
return true;
}
}
return false;
}
[Category("Action")]
[Description("Order Item Quantity Clicked.")]
public event TillOrderQuantityClickedHandler TillOrderQuantityClicked;
protected virtual void OnTillOrderQuantityClicked(Point pKeyPadLoc)
{
if (TillOrderQuantityClicked != null)
{
TillOrderQuantityClicked(pKeyPadLoc); // Notify Subscribers
}
}
private void TillOrderItemQuantityClicked(OrderGridItemRow pOrderItemRow)
{
OnTillOrderQuantityClicked(GetRowLocation(pOrderItemRow));
}
public void SetItemQty()
{
mCurrentItemRow.RefreshItemRow();
if (mCurrentItemRow.ItemQty == 0)
mCurrentItemRow.ItemQty = 1;
mIOrder.mCurrentOrderItems[
mIOrder.mCurrentOrderItems.FindIndex(i => i.GetItemID() == mIOrder.mCurrentOrderItemID)].SetItemQty(
(int) mCurrentItemRow.ItemQty);
mPresenterOrder.UpdateTotals();
DisplayOrder(false);
}
private void TillOrderItemClicked(OrderGridItemRow pOrderItemRow)
{
mCurrentItemRow = pOrderItemRow;
mPresenterOrder.ClearOrderItemGridSelections(false);
mIOrder.mCurrentOrderItemID = pOrderItemRow.ItemID;
if (mSplitMode)
{
mPresenterOrder.SetAsSplitItem(mIOrder.mCurrentOrderItemID);
DisplayOrder(false);
mPresenterOrder.ProcessPanelDisplay(mSplitMode);
//mPresenterOrder.ProcessPanelDisplay(!mSplitMode);
}
else
{
mCurrentItemRow.SetOrderItemSelected(true);
ShowItemControls(true);
// viewfunc
}
}
public void UpdatePhone()
{
if ((string) picPhone1.Tag == "1")
{
picPhone1.BackgroundImage = Properties.Resources.phone_ringing;
panPhone.BackColor = Color.White;
picPhone1.Tag = "2";
}
else
{
picPhone1.BackgroundImage = Properties.Resources.phone1;
//picPhone1.BackColor = Color.Aqua;
panPhone.BackColor = Color.FromArgb(114, 205, 206);
picPhone1.Tag = "1";
}
}
[Category("Action")]
[Description("Order Item Phone Clicked.")]
public event TillOrderItemPhoneClickedHandler TillOrderItemPhoneClicked;
protected virtual void OnOrderItemPhoneClicked()
{
if (TillOrderItemPhoneClicked != null)
{
TillOrderItemPhoneClicked(); // Notify Subscribers
}
}
private void picPhone1_Click(object sender, EventArgs e)
{
OnOrderItemPhoneClicked();
}
public void ResetPhone()
{
picPhone1.BackgroundImage = Properties.Resources.phone1;
panPhone.BackColor = Color.Aqua;
picPhone1.BackColor = Color.Aqua;
picPhone1.Tag = "1";
}
public int getCurrentTableNo()
{
return Convert.ToInt32(labTableNo.Text);
}
[Category("Action")]
[Description("Order Item Clicked, Show Controls")]
public event TillOrderItemClickedHandler TillShowControls;
protected virtual void OnTillShowControls(bool pOption)
{
if (TillShowControls != null)
{
TillShowControls(true); // Notify Subscribers
}
}
private void OrderCheckboxClicked(OrderItemDetails pOrderItemRow)
{
OnOrderChecked(pOrderItemRow);
}
[Category("Action")]
[Description("Order Checkbox Clicked")]
public event TillOrderCheckBoxClickedHandler OrderChecked;
protected virtual void OnOrderChecked(OrderItemDetails pOrderItemRow)
{
if(OrderChecked != null)
{
OrderChecked(pOrderItemRow);
}
}
private void ShowItemControls(bool pOption)
{
OnTillShowControls(pOption);
}
[Category("Action")]
[Description("Assign Order to Table Clicked.")]
public event TillOrderTableSelectionClickedHandler TillOrderTableSelectionClicked;
protected virtual void OnTillOrderTableSelectionClicked()
{
if (TillOrderTableSelectionClicked != null)
{
TillOrderTableSelectionClicked(); // Notify Subscribers
}
}
private void panTableSel_Click(object sender, EventArgs e)
{
// Table Selections
Console.Write("Table Selection");
OnTillOrderTableSelectionClicked();
}
private void labTableNoDesc_Click(object sender, EventArgs e)
{
Console.Write("Table Selection");
OnTillOrderTableSelectionClicked();
}
private void labTableNo_Click(object sender, EventArgs e)
{
Console.Write("Table Selection");
OnTillOrderTableSelectionClicked();
}
[Category("Action")]
[Description("Assign Customers to Table Clicked.")]
public event TillOrderTableCoverClickedHandler TillOrderTableCoverClicked;
protected virtual void OnTillOrderTableCoverClicked()
{
if (TillOrderTableCoverClicked != null)
{
TillOrderTableCoverClicked(); // Notify Subscribers
}
}
private void panTableCov_Click(object sender, EventArgs e)
{
// No of People on Table, Selections
Console.Write("Table Covers");
OnTillOrderTableCoverClicked();
}
private void labTableCoversDesc_Click(object sender, EventArgs e)
{
Console.Write("Table Covers");
OnTillOrderTableCoverClicked();
}
private void labTableCovers_Click(object sender, EventArgs e)
{
Console.Write("Table Covers");
OnTillOrderTableCoverClicked();
}
}
}
Related
I have coded my behind code logic in xaml.cs file and now i want to move my code from code behind to ViewModel. How can this be done apart from code refactoring.
I am new to xamarin
Here is my Code behind
namespace _somename
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class CareingtonFeeSchedule : ContentPage
{
private OneDentalFeeScheduleService oneDentalFeeScheduleService;
private ObservableCollection<ProviderSearchViewModel> _allGroups;
private ObservableCollection<ProviderSearchViewModel> _expandedGroups;
protected ObservableCollection<Grouping<string, FeeScheduleItem>> feeScheduleGroups;
protected ObservableCollection<FeeScheduleItem> feeScheduleItems;
private readonly AppViewModel AppViewModelInstance;
private Plugin.Geolocator.Abstractions.Position currentPosition;
private FeeScheduleModel feeScheduleDataResult;
public CareingtonFeeSchedule(AppViewModel appViewModel)
{
InitializeComponent();
AppViewModelInstance = appViewModel;
BindingContext = AppViewModelInstance;
AppViewModelInstance.IsActivityLoading = true;
LoadFeeeSchedule();
}
private void HeaderTapped(object sender, EventArgs args)
{
int selectedIndex = _expandedGroups.IndexOf(
((ProviderSearchViewModel)((Button)sender).CommandParameter));
_allGroups[selectedIndex].Expanded = !_allGroups[selectedIndex].Expanded;
UpdateListContent();
}
async Task OnHomeFeeScheduleTapped_TappedAsync(object sender, EventArgs args)
{
await Navigation.PushAsync(new AccLandPage(AppViewModelInstance));
}
private void ProviderBar_TextChanged(object sender, TextChangedEventArgs e)
{
var keyword = ProviderSearchBar.Text;
GroupedView.ItemsSource =
_expandedGroups.Where(s =>
s.Title.ToLower().Contains(keyword.ToLower()));
}
private void UpdateListContent()
{
_expandedGroups = new ObservableCollection<ProviderSearchViewModel>();
foreach (ProviderSearchViewModel group in _allGroups)
{
ProviderSearchViewModel newGroup = new ProviderSearchViewModel(group.Title, group.ShortName, group.Expanded);
if (group.Expanded)
{
foreach (Plan plan in group)
{
newGroup.Add(plan);
}
}
_expandedGroups.Add(newGroup);
}
GroupedView.ItemsSource = _expandedGroups;
}
public FeeScheduleModel FeeScheduleDataResult
{
protected set
{
feeScheduleDataResult = value;
OnPropertyChanged(nameof(FeeScheduleDataResult));
}
get => feeScheduleDataResult;
}
protected int feeScheduleCount;
public int FeeScheduleCount => feeScheduleCount;
private async Task<bool> LoadFeeeSchedule()
{
try
{
if (oneDentalFeeScheduleService == null)
{
oneDentalFeeScheduleService = new OneDentalFeeScheduleService("1dental.com");
}
var feeSchedRes = await oneDentalFeeScheduleService.GetFeeScheduleAsync(AppViewModelInstance.ZipCode, string.Empty, CancellationToken.None);
if (feeSchedRes?.Schedule?.Count > 0)
{
ConvertFeeScheuleDict(feeSchedRes.Schedule);
}
else FeeScheduleDataResult = null;
return true;
}
catch (Exception eX)
{
with the fee schedule lookup: \n{eX.Message}", "OK");
return false;
}
finally
{
AppViewModelInstance.IsActivityLoading = false;
actInd.IsRunning = false;
}
}
private void ConvertFeeScheuleDict(Dictionary<string, List<FeeScheduleItem>> feesche)
{
ObservableCollection<ProviderSearchViewModel> list = new ObservableCollection<ProviderSearchViewModel>();
ProviderSearchViewModel psm = null;
foreach (var item in feesche)
{
psm = new ProviderSearchViewModel(item.Key, "");
foreach (var valitem in item.Value)
{
Plan p = new Plan();
p.Code = valitem.Code;
p.CostDisplay = valitem.CostDisplay;
p.Description = valitem.ProcedureSecondary;
p.Name = valitem.Procedure;
psm.Add(p);
}
list.Add(psm);
}
_allGroups = list;
UpdateListContent();
}
private async void GetZipCode()
{
try
{
if (AppViewModelInstance.UserPosition == null)
{
try
{
var hasPermission = await Utils.CheckPermissions(Permission.Location);
if (!hasPermission)
{
await Navigation.PushAsync(new MainScreen());
return;
}
}
catch (Exception ex)
{
Debug.WriteLine($"Exception occurred while looking permission during Appearing event: {ex}");
}
var locator = CrossGeolocator.Current;
currentPosition = await locator.GetPositionAsync(new TimeSpan(0, 0, 0, 10, 0));
var addressList = await locator.GetAddressesForPositionAsync(currentPosition, null);
AppViewModelInstance.UserPosition = currentPosition;
foreach (var item in addressList)
{
AppViewModelInstance.ZipCode = item.PostalCode;
ZipCodeEntry.Text = item.PostalCode;
break;
}
}
else
{
var locator = CrossGeolocator.Current;
currentPosition = AppViewModelInstance.UserPosition;
var addressList = await locator.GetAddressesForPositionAsync(currentPosition, null);
foreach (var item in addressList)
{
AppViewModelInstance.ZipCode = item.PostalCode;
ZipCodeEntry.Text = item.PostalCode;
break;
}
}
LoadFeeeSchedule();
}
catch (Exception ex)
{
Debug.WriteLine($"Exception occurred while looking up location during Appearing event: {ex}");
}
}
private void ZipCodeEntry_Complete(object sender, EventArgs e)
{
if (sender != null)
{
AppViewModelInstance.ZipCode = ((Entry)sender).Text;
}
}
private void ZipCodeEntry_Changed(object sender, EventArgs e)
{
if (sender != null)
{
string _text = ((Entry)sender).Text; //Get Current Text
if (_text.Length > 5) //If it is more than your character restriction
{
_text = _text.Remove(_text.Length - 1); // Remove Last character
ZipCodeEntry.Text = _text; //Set the Old value
}
if (_text.Length == 5)
{
AppViewModelInstance.ZipCode = _text;
LoadFeeeSchedule();
}
}
}
public bool CanRefreshExecute(string tempVal = null)
{
if (AppViewModelInstance.IsRefreshing) return false;
var valToCheck = tempVal ?? AppViewModelInstance.ZipCode;
if (string.IsNullOrEmpty(valToCheck) || string.IsNullOrWhiteSpace(valToCheck)) return false;
bool isDigitString = true;
foreach (var c in valToCheck)
{
if (char.IsDigit(c)) continue;
isDigitString = false;
}
if (isDigitString) AppViewModelInstance.ZipCode = valToCheck;
return isDigitString;
}
private void GroupedView_ItemTapped(object sender, ItemTappedEventArgs e)
{
}
}
}
just export your code to the view model and set the view model as binding context of the Page. For example in the constructor:
//In the code behind
PageViewModel viewModel;
public Page()
{
this.BindingContext = viewModel = new PageViewModel();
//...
}
The ViewModel should implement INotifyPropertyChanged.
(Functions which are triggered by events have to stay in the code behind and access the view model through the ViewModel Property)
I created Scintilla Popup for textbox to show autocomplete :
this.hWnd = CreateWindowEx(
0, "Scintilla", "",
WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_CLIPCHILDREN | 0x00002000,
x, y, textbox1.ClientSize.Width, textbox1.ClientSize.Height, textbox1.Handle, (IntPtr)0, (IntPtr)0, (IntPtr)0);
and in custom textbox, i overriden WndProc :
protected override void WndProc(ref Message m)
{
}
I build project in x86, and each time i call "SendMessage", the autocomplete showed on textbox and WndProc called. But when i build project in x64, only autocomplete showed and WndProc not called. Please, help me ??
Thanks.
EDIT: Added code below, previously posted by OP as an answer
#o_weisman, this is my custom textbox :
public partial class ScintillaControl : TextBox
{
ScintillaWrapper sw = null;
public ScintillaWrapper Scintilla
{
get { return this.sw; }
}
LanguageType languageType = LanguageType.CS;
public LanguageType LanguageType
{
get { return languageType; }
set { languageType = value; }
}
bool useBuiltInPopupMenu = true;
public bool UseBuiltInPopupMenu
{
get { return useBuiltInPopupMenu; }
set { useBuiltInPopupMenu = value; }
}
bool _notModified = false;
public bool NotModified
{
get { return _notModified; }
set { _notModified = value; }
}
public ScintillaControl()
{
this.Multiline = true;
this.AcceptsTab = true;
// this.ShortcutsEnabled = true;
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
const int WM_KEYDOWN = 0x100;
var keyCode = (Keys)(msg.WParam.ToInt32() &
Convert.ToInt32(Keys.KeyCode));
if ((msg.Msg == WM_KEYDOWN && keyCode == Keys.A)
&& (ModifierKeys == Keys.Control)
)
{
this.SelectAll();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
public new bool Enabled
{
get { return base.Enabled; }
set
{
base.Enabled = value;
Color bkColor = (value ? Color.White : System.Drawing.SystemColors.ControlLight);
if (this.sw != null)
this.sw.SetWindowBackground(bkColor);
}
}
//[DllImport("User32.dll")]
//private static extern int GetAsyncKeyState(int vKey);
private bool DetectCtrlPressed()
{
Keyboard kb = new Keyboard();
return kb.CtrlKeyDown;
//int detectCtrlPressed = GetAsyncKeyState(0x11);
//return (detectCtrlPressed == 32768 || detectCtrlPressed == -32767);
}
private bool DetectCtrlShiftPressed()
{
Keyboard kb = new Keyboard();
return kb.CtrlKeyDown && kb.ShiftKeyDown;
}
private bool DetectShiftPressed()
{
Keyboard kb = new Keyboard();
return kb.ShiftKeyDown;
}
protected override void OnCreateControl()
{
base.OnCreateControl();
CreateScintillaControl();
}
public void CreateScintillaControl()
{
if (this.sw != null)
return;
try
{
this.sw = new ScintillaWrapper();
this.sw.MapForm = this.mapForm;
this.sw.ParentControl = this;
this.sw._CreateWindow(0, 0, this.ClientSize.Width, this.ClientSize.Height, this, languageType);
this.sw._DisableBuiltInPopupMenu(this.useBuiltInPopupMenu);
//Trace.Listeners.Add(new TextWriterTraceListener("C:\\trace.txt"));
}
catch (Exception ex)
{
MessageBox.Show("error while creating scintilla wrapper, ex: " + ex.ToString());
}
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
if (this.sw != null)
this.sw._ChangeSize(new Point(0, 0), new Size(this.ClientSize.Width, this.ClientSize.Height));
}
public delegate void ScintillaDoubleClick(int lineNumber, string content);
public event ScintillaDoubleClick OnScintillaDoubleClick = null;
private void DoOnScintillaDoubleClick(int lineNumber, string content)
{
if (this.OnScintillaDoubleClick != null)
this.OnScintillaDoubleClick(lineNumber, content);
}
public delegate void TrackPopupMenu(Point p);
public event TrackPopupMenu OnTrackPopupMenu = null;
private void DoOnTrackPopupMenu(Point p)
{
if (this.OnTrackPopupMenu != null)
this.OnTrackPopupMenu(p);
}
public delegate void CodeChanged(ScintillaControl control);
public event CodeChanged OnCodeChanged = null;
private void DoOnCodeChanged(ScintillaControl control)
{
if (this.OnCodeChanged != null)
this.OnCodeChanged(control);
}
public delegate void SelectionChanged(bool isChanged);
public event SelectionChanged OnSelectionChanged = null;
private void DoOnSelectionChanged(bool isChanged)
{
if (this.OnSelectionChanged != null)
this.OnSelectionChanged(isChanged);
}
public delegate void ModifyCode();
public event ModifyCode OnModifyCode = null;
private void DoOnModifyCode()
{
this.sw.ReDrawLineNumberPanel();
if (this.OnModifyCode != null)
this.OnModifyCode();
}
public delegate void UIChangedDelegate();
public event UIChangedDelegate OnUIChanged = null;
protected override void OnGotFocus(EventArgs e)
{
base.OnGotFocus(e);
this.sw._SetFocus();
}
private const int WM_PASTE = 0x0302;
protected override void WndProc(ref Message m)
{
if (m.Msg == ScintillaWrapper.SCK_DELETE)
{
this.DoOnCodeChanged(this);
}
else if (m.Msg == 0x0111 /*WM_COMMAND*/ && this.sw != null)
{
if (m.LParam == this.sw._HWnd)
{
int value = m.WParam.ToInt32();
if ((value >> 16) == 512)
{
this.Select();
//this.sw._SetFocus();
}
}
}
else if (m.Msg == 0x007B /*WM_CONTEXTMENU*/ && this.useBuiltInPopupMenu == false)
{
int value = m.LParam.ToInt32();
// tach value lam low word va high word
int lowWord = value & 0x0000FFFF;
int highWord = value >> 16;
Point p = new Point(lowWord, highWord);
this.Select();
//this.sw._SetFocus();
this.DoOnTrackPopupMenu(p);
return;
}
else if (m.Msg == 0x004E /*WM_NOTIFY*/ && this.sw != null)
{
this.ProcessNotify(m);
}
base.WndProc(ref m);
}
CalltipInfo _currentCallTip = null;
bool _hasSelect = false;
bool _hasSelect2 = false;
SCNotification tmpNotify;
private void ProcessNotify(Message m)
{
bool is64bit = Util.Utility.OtherFunction.IsOS64bit;
SCNotification notify;
uint code = 0;
if (is64bit)
{
IntPtr pDevicePathName = new IntPtr(m.LParam.ToInt64() + IntPtr.Size);
notify = (SCNotification)Marshal.PtrToStructure(pDevicePathName, typeof(SCNotification));
code = notify.idFrom;
}
else
{
notify = (SCNotification)Marshal.PtrToStructure(m.LParam, typeof(SCNotification));
code = notify.code;
}
//if (notify.hwndFrom != this.sw._HWnd)
// return;
switch (code)//(notify.code)
{
case ScintillaWrapper.SCN_MARGINCLICK:
if (notify.margin == ScintillaWrapper.MARGIN_SCRIPT_FOLD_INDEX) this.Scintilla._Fold(notify.position);
else if (notify.margin == 2)
{
this.Scintilla._ToggleBreakPoint(notify.position);
}
break;
case ScintillaWrapper.SCN_CHARADDED:
if (this.sw.GetReadOnly()) break;
if (this.sw._CharAdd(notify.ch, this.DetectCtrlPressed(), this.DetectShiftPressed()))
break;
this.DoOnModifyCode();
this.OnTextChanged(new EventArgs());
break;
case ScintillaWrapper.SCN_AUTOCSELECTION:
_hasSelect = true;
// string s = Marshal.PtrToStringAnsi(notify.text);
// this.Scintilla._AutoCompleteSelected(notify.lParam.ToInt32(), s);
break;
case ScintillaWrapper.SCN_CALLTIPCLICK:
this.Scintilla._CalltipClicked(notify.position);
break;
case ScintillaWrapper.SCN_DOUBLECLICK:
int lineNumber = this.sw.GetCurrentLine();
string content = this.sw.GetLineContent(lineNumber);
this.DoOnScintillaDoubleClick(lineNumber, content);
break;
case ScintillaWrapper.SCN_SAVEPOINTLEFT:
this.DoOnCodeChanged(this);
break;
case ScintillaWrapper.SCN_DWELLSTART:
this.sw._MouseOver(notify.position);
break;
case ScintillaWrapper.SCN_DWELLEND:
this.sw._MouseOut();
break;
case ScintillaWrapper.SCN_UPDATEUI:
this.sw._CursorChanged();
if (this.sw.GetText() != "")
{
this.getCurrentColPos();
}
if (this.OnUIChanged != null)
OnUIChanged();
//this.DoOnModifyCode();
break;
case ScintillaWrapper.SCN_MODIFIED:
if (notify.modificationType == 2064 && notify.length == 1 && _notModified == false)
{
this.DoOnModifyCode();
this.OnTextChanged(new EventArgs());
}
else if ((notify.modificationType == 1040 || notify.modificationType == 2064) && !_notModified)
{
this.DoOnModifyCode();
}
//DVC 2/4/10
if (!ReferencesHolder.IsSearching)
{
if (this.Scintilla._GetBit(1, notify.modificationType))//Delete text event
{
this.Scintilla._CheckBreakPoint(notify.position);
}
}
//End
if (_hasSelect && ((notify.modificationType & ScintillaWrapper.SC_MOD_INSERTTEXT) != 0))
{
_hasSelect2 = true;
_hasSelect = false;
}
break;
case ScintillaWrapper.SCN_SELECT_AC_ITEM:
string s = Marshal.PtrToStringAnsi(notify.text);
_currentCallTip = this.sw.ShowToolTip(new Point(notify.x, notify.y), notify.position, notify.margin, notify.message, s);
tmpNotify = notify;
break;
case ScintillaWrapper.SCN_CLOSE_AC_LIST:
this.sw.HideToolTip();
break;
//case ScintillaWrapper.SCN_PAINTED:
// break;
case ScintillaWrapper.SCK_DELETE:
this.DoOnModifyCode();
break;
default:
if (_hasSelect2)
{
AddParenthesisIfNeeded();
_hasSelect2 = false;
sw.InsertText(" ");
sw.AutoCompleteProcess.InitAutoComplete(32, sw.GetCurrentPos(), sw.GetText(), false, true);
//string s1 = Marshal.PtrToStringAnsi(tmpNotify.text);
//this.sw.ShowToolTip(new Point(tmpNotify.x, tmpNotify.y), tmpNotify.position, tmpNotify.margin, tmpNotify.message, s1);
}
bool isChanged = this.sw.HasSelection();
this.DoOnSelectionChanged(isChanged);
//this.DoOnModifyCode();
break;
}
}
public void getCurrentColPos()
{
Control parent = this.Parent;
while (!(parent == null) && !(parent.Name == "Check Output"))
{
parent = parent.Parent;
}
if (parent != null)
{
var lengthOfAlllineBefore = 0;
var currentPos = 0;
if (this.sw.GetCurrentLine() > 0)
{
for (int i = 0; i < this.sw.GetCurrentLine(); i++)
{
lengthOfAlllineBefore += this.sw.GetLineContent(i).Length;
}
currentPos = this.sw.GetCurrentPos() - lengthOfAlllineBefore;
}
else
{
currentPos = this.sw.GetCurrentPos();
}
if (parent.Controls["panel2"] != null)
{
parent.Controls["panel2"].Controls["lblCurrentColumnPosition"].Text =
string.Format("Col:{0}", currentPos);
}
}
// this.sw.get
}
private void AddParenthesisIfNeeded()
{
try
{
string text = sw.GetText();
sw.AutoCompleteProcess.DocumentString = text;
_currentCallTip = sw.AutoCompleteProcess.FindCalltipVariable(sw.GetCurrentPos() - 1, text, 0);
if (_currentCallTip == null || _currentCallTip.IsProperty)
{
return;
}
sw.InsertText("()");
sw.SetCurrentPos(sw.GetCurrentPos() - 1);
sw.ClearSelection();
_currentCallTip = null;
}
catch { }
}
public void SetSavePoint()
{
if (this.sw != null)
this.sw._SetSavePoint();
}
public void SetReadOnly(bool readOnly)
{
this.Scintilla.SetReadOnly(readOnly);
}
public void ToggleBreakPoint()
{
this.Scintilla._ToggleBreakPoint();
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (this.sw != null)
this.sw.Dispose();
this.OnTrackPopupMenu = null;
this.OnCodeChanged = null;
this.OnSelectionChanged = null;
this.OnTrackPopupMenu = null;
}
private void InitializeComponent()
{
this.SuspendLayout();
//
// ScintillaControl
//
this.Multiline = true;
this.ResumeLayout(false);
}
}
I have a GUI that is linked to several Sensors through COM-Port. I have a Datahandler that makes sure that the received and sent packages have the correct size and content. And then i have a SensorContainer containing all Sensors, firing an event whenever a new sensor is added!
My problem is now:
I need a method, that can initialize all sensors with one click.
And i just cant do it. If I initialize them one by one, it works, but all in one method doesnt work.
My idea is that the packages get mixed and the handler doesnt accept the sensors anymore for initialization. So i tried to make the method wait for the first sensor to be initialized and the proceed, but i have no clue how!
I tried a few things with mulitthreading, but im not really experienced in that field and it didnt work out in the end anyway...
SensorContainerClass:
public static class SensorContainer
{
public static event EventHandler<ContainerEvent> ContainerChanged;
public static ObservableCollection<Sensor> SensorList
{
get { return _sensorList; }
}
public static void AddSensor(Sensor sensor)
{
Sensor sensorExists = GetSensor(sensor.Address);
if (sensorExists == null)
{
Application.Current.Dispatcher.Invoke(() => _sensorList.Add(sensor));
ContainerChanged(null,new ContainerEvent(sensor.Address, true));
}
else
{
Console.WriteLine("It's not possible to add multiple sensors with the same address.");
}
}
public static void RemoveSensor(Sensor sensor)
{
Sensor sensorExists = GetSensor(sensor.Address);
if (sensorExists != null)
{
Application.Current.Dispatcher.Invoke(() => _sensorList.Remove(sensor));
ContainerChanged(null, new ContainerEvent(sensor.Address, false));
}
else
{
Console.WriteLine("No sensor with address " + sensor.Address);
}
}
public static Sensor GetSensor(byte address)
{
foreach (Sensor sensor in _sensorList)
{
if (sensor.Address == address)
{
return sensor;
}
}
return null;
}
// members
private static readonly ObservableCollection<Sensor> _sensorList = new ObservableCollection<Sensor>();
}
DataHandler:
public class DataHandler:ModelBase
{
private const int MAX_TIMER_TIME = 500;
public long answertime_milli;
Timer aTimer;
Stopwatch watch;
Sensor tempSensor;
private byte[] tempFrame;
private bool framePartPendingFlag = false;
public bool framesEqual;
public bool initalisationFlag = false;
public InitType initialisationType;
public byte[] TxFrame
{
get { return txFrame; }
}
public byte TxAddress
{
get { return TxFrame[0]; }
}
public byte TxLength
{
get { return TxFrame[1]; }
}
public byte TxCommand
{
get { return TxFrame[2]; }
}
public byte[] TxData
{
get { return TxFrame.GetRange(3, TxLength - 2); }
}
public byte TxChecksum
{
get { return TxFrame[TxLength - 1]; }
}
private byte[] txFrame;
private bool successfull;
public bool Successfull
{
get
{
return successfull;
}
set
{
if(successfull != value)
{
successfull = value;
this.OnPropertyChanged();
}
}
}
public DataHandler()
{
txFrame = new byte[4] { 0, 0, 0, 0 };
aTimer = new Timer(MAX_TIMER_TIME);
watch = new Stopwatch();
CommandManager.Instance.Init();
InterfaceWrapper.Instance.SerialPort.DataReceived += OnSerialPortReceived;
}
public void InitializeSensor(InitType type, byte address, Int32 serialNumber = 0)
{
if (SensorContainer.GetSensor(address) != null )
{
MessageBox.Show("Sensoraddress already used");
return;
}
foreach(Sensor temp in SensorContainer.SensorList)
{
if(temp.Serialnr == serialNumber)
{
MessageBox.Show("Sensor with the same SerialNumber already initalized");
return;
}
}
byte[] frame;
if (type == InitType.INIT_TO_ONE_DEVICE)
{
Sensor.COM_ADDR_SET_ONE_TX initStruct = new Sensor.COM_ADDR_SET_ONE_TX();
initStruct.Address = address;
frame = createFrame(initStruct, 0xFF, 0x20);
}
else
{
Sensor.COM_ADDR_SET_TO_SN_TX initStruct = new Sensor.COM_ADDR_SET_TO_SN_TX();
initStruct.Address = address;
if (serialNumber == 0)
{
MessageBox.Show("Serialnumber is missing");
return;
}
initStruct.SerialNumber = serialNumber;
frame = createFrame(initStruct, 0x00, 0x22);
}
setTxFrame(frame);
InterfaceWrapper.Instance.SerialPort.SendData(frame);
initalisationFlag = true;
initialisationType = type;
}
public void StartDataTransfer(Sensor sensor, byte commandid)
{
if (sensor == null)
{
MessageBox.Show("No such sensor");
return;
}
Command command = sensor.getCommand(commandid);
if (command == null)
{
MessageBox.Show("Command does not exist");
return;
}
foreach (KeyValuePair<CommandAttribute, Command> pair in sensor.CommandList)
{
if (pair.Value == command)
{
timeout = pair.Key.Timeout;
transmission = pair.Key.Transmission;
break;
}
}
tempSensor = sensor;
if (SensorContainer.GetSensor(sensor.Address) != null)
{
byte[] endFrame = createFrame(command, sensor.Address, commandid);
setTxFrame(endFrame);
if (true)
{
InterfaceWrapper.Instance.SerialPort.SendData(txFrame);
}
}
else
{
MessageBox.Show("Sensor not yet initialized");
}
}
private byte[] createFrame(Command command, byte address, byte commandId)
{
byte[] data = MarshalHelper.Serialize(command);
byte[] frame = new byte[4 + data.Length];
frame[0] = address;
frame[1] = (byte)frame.Length;
frame[2] = commandId;
Buffer.BlockCopy(data, 0, frame, 3, data.Length);
frame[frame.Length - 1] = GenerateChecksum(frame);
return frame;
}
public void OnSerialPortReceived(object sender, ComDataRxEvent e)
{
byte[] data = e.Data;
setRxFrame(data);
}
public void setTxFrame(byte[] _txFrame)
{
Successfull = false;
txFrame = _txFrame;
aTimer.Elapsed += OnTimedEvent;
aTimer.AutoReset = false;
aTimer.Start();
watch.Start();
}
public void setRxFrame(byte[] _rxFrame)
{
if (framePartPendingFlag)
{
byte[] newTempFrame = new byte[tempFrame.Length + _rxFrame.Length];
tempFrame.CopyTo(newTempFrame, 0);
_rxFrame.CopyTo(newTempFrame, tempFrame.Length);
framePartPendingFlag = false;
setRxFrame(newTempFrame);
}
else if (!checkMinLength(_rxFrame))
{
tempFrame = _rxFrame;
framePartPendingFlag = true;
}
else if (!checkBit(_rxFrame))
{
tempFrame = _rxFrame;
framePartPendingFlag = true;
}
else
{
framePartPendingFlag = false;
aTimer.Stop();
watch.Stop();
answertime_milli = watch.ElapsedMilliseconds;
if (!initalisationFlag)
{
if (checkAll(_rxFrame))
{
writeCommandToSensor(_rxFrame);
}
}
else
{
createSensorAfterInitialization(_rxFrame);
}
}
}
private void writeCommandToSensor(byte[] frame)
{
Command expCommand = CommandManager.Instance.GetRxCommand(tempSensor.GetType(), TxCommand);
Command command = MarshalHelper.Deserialize(expCommand, frame.GetRange(3, frame[1] - 2));
tempSensor.setCommand(command);
}
private void createSensorAfterInitialization(byte[] frame)
{
if (initalisationFlag && initialisationType == InitType.INIT_TO_ONE_DEVICE)
{
Sensor.COM_ADDR_SET_ONE_RX expCommand = new Sensor.COM_ADDR_SET_ONE_RX();
Sensor.COM_ADDR_SET_ONE_RX command = (Sensor.COM_ADDR_SET_ONE_RX)MarshalHelper.Deserialize(expCommand, frame.GetRange(3, frame[1] - 2));
Sensor tempSensor = Sensor.GetSensorInstance(command.SerialNumber, command.Address, command.SensorName, command.SensorSubName, command.dataStructType, command.dataStructSubType,command.pcbVersion,command.firmware);
tempSensor.setCommand(command);
SensorContainer.AddSensor(tempSensor);
initalisationFlag = false;
}
else
{
Sensor.COM_ADDR_SET_TO_SN_RX expCommand = new Sensor.COM_ADDR_SET_TO_SN_RX();
Sensor.COM_ADDR_SET_TO_SN_RX command = (Sensor.COM_ADDR_SET_TO_SN_RX)MarshalHelper.Deserialize(expCommand, frame.GetRange(3, frame[1] - 2));
if (command == null)
{
MessageBox.Show("Sensor not answering");
}
else {
Sensor tempSensor = Sensor.GetSensorInstance(command.SerialNumber, command.Address, command.SensorName, command.SensorSubName, command.dataStructType, command.dataStructSubType, command.pcbVersion, command.firmware);
tempSensor.setCommand(command);
SensorContainer.AddSensor(tempSensor);
initalisationFlag = false;
}
}
}
public void OnTimedEvent(object source, ElapsedEventArgs e)
{
framePartPendingFlag = false;
}
}
I am trying to set a tooltip on an arbitrary range of text on a richtextbox. Is this possible? If so how would I do it e.g by passing in parameters "from" and "to" as (int) indexes.
Thanks
You could use the following as a starting point:
Add a reference to System.Windows.Interactivity.
Add the following classes to your project:
public class TextRangeToolTip
{
public int StartPosition { get; set; }
public int Length { get; set; }
public object ToolTip { get; set; }
internal bool IsInRange(int position)
{
return this.StartPosition <= position && position < this.StartPosition + this.Length;
}
}
public class TextRangeToolTipCollection : ObservableCollection<TextRangeToolTip> {}
[ContentProperty("Ranges")]
public class ToolTipBehavior : Behavior<RichTextBox>
{
private const int ToolTipHideMouseDelta = 9;
public static readonly DependencyProperty RangesProperty
= DependencyProperty.Register("Ranges", typeof(TextRangeToolTipCollection),
typeof (ToolTipBehavior),
new PropertyMetadata(OnRangesChanged));
private readonly DispatcherTimer timer;
private readonly ToolTip toolTip;
private Point lastMousePosition;
public TextRangeToolTipCollection Ranges
{
get
{
return (TextRangeToolTipCollection)this.GetValue(RangesProperty)
?? (this.Ranges = new TextRangeToolTipCollection());
}
set { this.SetValue(RangesProperty, value); }
}
public ToolTipBehavior()
{
this.Ranges = new TextRangeToolTipCollection();
this.timer = new DispatcherTimer();
this.timer.Tick += this.TimerOnTick;
this.timer.Interval = TimeSpan.FromSeconds(1);
this.toolTip = new ToolTip {Placement = PlacementMode.Relative};
}
protected override void OnAttached()
{
this.AssociatedObject.ToolTip = this.toolTip;
this.toolTip.PlacementTarget = this.AssociatedObject;
ToolTipService.SetIsEnabled(this.AssociatedObject, false);
this.AssociatedObject.MouseMove += this.AssociatedObjectOnMouseMove;
}
protected override void OnDetaching()
{
this.timer.Stop();
this.toolTip.PlacementTarget = null;
this.AssociatedObject.ToolTip = null;
this.AssociatedObject.ClearValue(ToolTipService.IsEnabledProperty);
this.AssociatedObject.MouseMove -= this.AssociatedObjectOnMouseMove;
}
private void AssociatedObjectOnMouseMove(object sender, MouseEventArgs mouseEventArgs)
{
Point currentMousePosition = mouseEventArgs.GetPosition(this.AssociatedObject);
if (this.AssociatedObject.IsMouseCaptured)
{
Vector delta = currentMousePosition
- this.lastMousePosition;
if (delta.X*delta.X + delta.Y*delta.Y <= ToolTipHideMouseDelta)
{
this.toolTip.HorizontalOffset = currentMousePosition.X + 10;
this.toolTip.VerticalOffset = currentMousePosition.Y + 10;
return;
}
this.AssociatedObject.ReleaseMouseCapture();
this.toolTip.IsOpen = false;
}
if (this.AssociatedObject.IsMouseOver)
{
this.lastMousePosition = currentMousePosition;
this.timer.Stop();
this.timer.Start();
}
}
private static void OnRangesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((ToolTipBehavior) d).OnRangesChanged((IEnumerable<TextRangeToolTip>) e.OldValue,
(IEnumerable<TextRangeToolTip>) e.NewValue);
}
private void OnRangesChanged(IEnumerable<TextRangeToolTip> oldRanges, IEnumerable<TextRangeToolTip> newRanges)
{
var oldObservable = oldRanges as INotifyCollectionChanged;
if (oldObservable != null)
{
CollectionChangedEventManager.RemoveHandler(oldObservable, this.OnRangesCollectionChanged);
}
var newObservable = newRanges as INotifyCollectionChanged;
if (newObservable != null)
{
CollectionChangedEventManager.AddHandler(newObservable, this.OnRangesCollectionChanged);
}
this.UpdateToolTip();
}
private void OnRangesCollectionChanged(
object sender,
NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
{
this.UpdateToolTip();
}
private bool SetToolTipData()
{
if (this.Ranges == null)
{
return false;
}
TextPointer pointer = this.AssociatedObject.GetPositionFromPoint(this.lastMousePosition, false);
if (pointer == null)
{
return false;
}
int position = this.AssociatedObject.Document.ContentStart.GetOffsetToPosition(pointer);
TextRangeToolTip matchingRange = this.Ranges.FirstOrDefault(r => r.IsInRange(position));
if (matchingRange == null)
{
return false;
}
this.toolTip.Content = matchingRange.ToolTip;
return true;
}
private void TimerOnTick(object sender, EventArgs eventArgs)
{
this.timer.Stop();
if (this.AssociatedObject.IsMouseOver && this.SetToolTipData())
{
this.toolTip.IsOpen = true;
this.AssociatedObject.CaptureMouse();
}
}
private void UpdateToolTip()
{
if (this.AssociatedObject != null && this.AssociatedObject.IsMouseCaptured && !this.SetToolTipData())
{
this.toolTip.IsOpen = false;
this.AssociatedObject.ReleaseMouseCapture();
}
}
}
Use it on your RichTextBox like this:
<RichTextBox>
<i:Interaction.Behaviors>
<myapp:ToolTipBehavior>
<myapp:TextRangeToolTip StartPosition="10" Length="4" ToolTip="some" />
<myapp:TextRangeToolTip StartPosition="15" Length="4" ToolTip="text" />
</myapp:ToolTipBehavior>
</i:Interaction.Behaviors>
<FlowDocument>
<Paragraph>This is some text. This is some other text.</Paragraph>
</FlowDocument>
</RichTextBox>
Alternatively, you can bind a TextRangeToolTipCollection to the Ranges property like this:
<RichTextBox Document="{Binding Document}">
<i:Interaction.Behaviors>
<myapp:ToolTipBehavior Ranges="{Binding RangeToolTips}" />
</i:Interaction.Behaviors>
</RichTextBox>
Getting the positions right is a bit tricky, because WPF counts symbols, not characters. You could extend the TextRangeToolTip class to have properties of type TextPointer or TextRange and construct it using your FlowDocument instance.
This is my code
gridView1.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn()
{
Caption = "Selected",
ColumnEdit = new RepositoryItemCheckEdit() { },
VisibleIndex = 1,
UnboundType = DevExpress.Data.UnboundColumnType.Boolean
});
But I cant check multiple checkEdit at the same time.
Why was that?
And please show me the way out.
Thanks.
Well, there are two answers to that question, one very simple, and one very complex, let's start with the simple:
If you want to have an column that has the "Selected" caption and act as a checkbox to indicate that a particular record was selected, you have two options:
1) If you can alter the class in your data source to add a property that is bool and could be used with DataBinding, then, all is done in a very simple way, jast add the property and bind the data and it will work:
class SimplePerson
{
public string Name { get; set; }
public bool IsSelected { get; set; }
}
BindingList<SimplePerson> source = new BindingList<SimplePerson>();
void InitGrid()
{
source.Add(new SimplePerson() { Name = "John", IsSelected = false });
source.Add(new SimplePerson() { Name = "Gabriel", IsSelected = true });
gridControl.DataSource = source;
}
2) You cannot alter you classes, so you need to this by signing the correct grid events and drawing the column yourself, and also adding the right handlers for all the actions.... is a very complex case, but for your luck i have this done, because i have had this problem in the past, so i will post you my full class!
public class GridCheckMarksSelection
{
public event EventHandler SelectionChanged;
protected GridView _view;
protected ArrayList _selection;
private GridColumn _column;
private RepositoryItemCheckEdit _edit;
public GridView View
{
get { return _view; }
set
{
if (_view == value)
return;
if (_view != null)
Detach();
_view = value;
Attach();
}
}
public GridColumn CheckMarkColumn { get { return _column; } }
public int SelectedCount { get { return _selection.Count; } }
public GridCheckMarksSelection()
{
_selection = new ArrayList();
}
public GridCheckMarksSelection(GridView view)
: this()
{
this.View = view;
}
protected virtual void Attach()
{
if (View == null)
return;
_selection.Clear();
_view = View;
_edit = View.GridControl.RepositoryItems.Add("CheckEdit")
as RepositoryItemCheckEdit;
_edit.EditValueChanged += edit_EditValueChanged;
_column = View.Columns.Insert(0);
_column.OptionsColumn.AllowSort = DefaultBoolean.False;
_column.VisibleIndex = int.MinValue;
_column.FieldName = "CheckMarkSelection";
_column.Caption = "Mark";
_column.OptionsColumn.ShowCaption = false;
_column.UnboundType = UnboundColumnType.Boolean;
_column.ColumnEdit = _edit;
View.CustomDrawColumnHeader += View_CustomDrawColumnHeader;
View.CustomDrawGroupRow += View_CustomDrawGroupRow;
View.CustomUnboundColumnData += view_CustomUnboundColumnData;
View.MouseUp += view_MouseUp;
}
protected virtual void Detach()
{
if (_view == null)
return;
if (_column != null)
_column.Dispose();
if (_edit != null)
{
_view.GridControl.RepositoryItems.Remove(_edit);
_edit.Dispose();
}
_view.CustomDrawColumnHeader -= View_CustomDrawColumnHeader;
_view.CustomDrawGroupRow -= View_CustomDrawGroupRow;
_view.CustomUnboundColumnData -= view_CustomUnboundColumnData;
_view.MouseDown -= view_MouseUp;
_view = null;
}
protected virtual void OnSelectionChanged(EventArgs e)
{
if (SelectionChanged != null)
SelectionChanged(this, e);
}
protected void DrawCheckBox(Graphics g, Rectangle r, bool Checked)
{
var info = _edit.CreateViewInfo() as CheckEditViewInfo;
var painter = _edit.CreatePainter() as CheckEditPainter;
ControlGraphicsInfoArgs args;
info.EditValue = Checked;
info.Bounds = r;
info.CalcViewInfo(g);
args = new ControlGraphicsInfoArgs(info, new GraphicsCache(g), r);
painter.Draw(args);
args.Cache.Dispose();
}
private void view_MouseUp(object sender, MouseEventArgs e)
{
if (e.Clicks == 1 && e.Button == MouseButtons.Left)
{
GridHitInfo info;
var pt = _view.GridControl.PointToClient(Control.MousePosition);
info = _view.CalcHitInfo(pt);
if (info.InRow && _view.IsDataRow(info.RowHandle))
UpdateSelection();
if (info.InColumn && info.Column == _column)
{
if (SelectedCount == _view.DataRowCount)
ClearSelection();
else
SelectAll();
}
if (info.InRow && _view.IsGroupRow(info.RowHandle)
&& info.HitTest != GridHitTest.RowGroupButton)
{
bool selected = IsGroupRowSelected(info.RowHandle);
SelectGroup(info.RowHandle, !selected);
}
}
}
private void View_CustomDrawColumnHeader
(object sender, ColumnHeaderCustomDrawEventArgs e)
{
if (e.Column != _column)
return;
e.Info.InnerElements.Clear();
e.Painter.DrawObject(e.Info);
DrawCheckBox(e.Graphics, e.Bounds, SelectedCount == _view.DataRowCount);
e.Handled = true;
}
private void View_CustomDrawGroupRow
(object sender, RowObjectCustomDrawEventArgs e)
{
var info = e.Info as GridGroupRowInfo;
info.GroupText = " " + info.GroupText.TrimStart();
e.Info.Paint.FillRectangle
(e.Graphics, e.Appearance.GetBackBrush(e.Cache), e.Bounds);
e.Painter.DrawObject(e.Info);
var r = info.ButtonBounds;
r.Offset(r.Width * 2, 0);
DrawCheckBox(e.Graphics, r, IsGroupRowSelected(e.RowHandle));
e.Handled = true;
}
private void view_CustomUnboundColumnData
(object sender, CustomColumnDataEventArgs e)
{
if (e.Column != CheckMarkColumn)
return;
if (e.IsGetData)
e.Value = IsRowSelected(View.GetRowHandle(e.ListSourceRowIndex));
else
SelectRow(View.GetRowHandle(e.ListSourceRowIndex), (bool)e.Value);
}
private void edit_EditValueChanged(object sender, EventArgs e)
{
_view.PostEditor();
}
private void SelectRow(int rowHandle, bool select, bool invalidate)
{
if (IsRowSelected(rowHandle) == select)
return;
object row = _view.GetRow(rowHandle);
if (select)
_selection.Add(row);
else
_selection.Remove(row);
if (invalidate)
Invalidate();
OnSelectionChanged(EventArgs.Empty);
}
public object GetSelectedRow(int index)
{
return _selection[index];
}
public int GetSelectedIndex(object row)
{
return _selection.IndexOf(row);
}
public void ClearSelection()
{
_selection.Clear();
View.ClearSelection();
Invalidate();
OnSelectionChanged(EventArgs.Empty);
}
private void Invalidate()
{
_view.CloseEditor();
_view.BeginUpdate();
_view.EndUpdate();
}
public void SelectAll()
{
_selection.Clear();
var dataSource = _view.DataSource as ICollection;
if (dataSource != null && dataSource.Count == _view.DataRowCount)
_selection.AddRange(dataSource); // fast
else
for (int i = 0; i < _view.DataRowCount; i++) // slow
_selection.Add(_view.GetRow(i));
Invalidate();
OnSelectionChanged(EventArgs.Empty);
}
public void SelectGroup(int rowHandle, bool select)
{
if (IsGroupRowSelected(rowHandle) && select) return;
for (int i = 0; i < _view.GetChildRowCount(rowHandle); i++)
{
int childRowHandle = _view.GetChildRowHandle(rowHandle, i);
if (_view.IsGroupRow(childRowHandle))
SelectGroup(childRowHandle, select);
else
SelectRow(childRowHandle, select, false);
}
Invalidate();
}
public void SelectRow(int rowHandle, bool select)
{
SelectRow(rowHandle, select, true);
}
public bool IsGroupRowSelected(int rowHandle)
{
for (int i = 0; i < _view.GetChildRowCount(rowHandle); i++)
{
int row = _view.GetChildRowHandle(rowHandle, i);
if (_view.IsGroupRow(row))
if (!IsGroupRowSelected(row))
return false;
else
if (!IsRowSelected(row))
return false;
}
return true;
}
public bool IsRowSelected(int rowHandle)
{
if (_view.IsGroupRow(rowHandle))
return IsGroupRowSelected(rowHandle);
object row = _view.GetRow(rowHandle);
return GetSelectedIndex(row) != -1;
}
public void UpdateSelection()
{
_selection.Clear();
Array.ForEach(View.GetSelectedRows(), item => SelectRow(item, true));
}
}
And now you need to know how to use this:
void InitGrid()
{
gridControl.DataSource = source;
// Do this after the database for the grid is set!
selectionHelper = new GridCheckMarksSelection(gridView1);
// Define where you want the column (0 = first)
selectionHelper.CheckMarkColumn.VisibleIndex = 0;
// You can even subscrive to the event that indicates that
// there was change in the selection.
selectionHelper.SelectionChanged += selectionHelper_SelectionChanged;
}
void selectionHelper_SelectionChanged(object sender, EventArgs e)
{
// Do something when the user selects or unselects something
}
But how do you retrieve all the selected items? There is a example assuming that the type bond is 'Person'
/// <summary>
/// Return all selected persons from the Grid
/// </summary>
public IList<Person> GetItems()
{
var ret = new List<Person>();
Array.ForEach
(
gridView1.GetSelectedRows(),
cell => ret.Add(gridView1.GetRow(cell) as Person)
);
return ret;
}