Method that does not proceed until event gets fired - c#

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;
}
}

Related

Firebird Duplicating items C# .NET

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();
}
}
}

PlayerPrefs won't save or load anything when I build the game

I'm trying to make a simple script that saves a text from an input field, like a "remember me" check box. It works fine on the editor. It saves, it logs correctly, it loads fine. But when I build the scene it doesn't work, it's like PlayerPrefs never saves anything. Anyone knows why?
public Toggle rememberMe;
public InputField fieldMail;
public InputField fieldPassword;
private string mail;
private string password;
private int rememberMeChecked = 0;
private bool justChecked = false;
public EventTrigger loginButton;
private void Awake()
{
if (!PlayerPrefs.HasKey("Checked")) { PlayerPrefs.SetInt("Checked", 0); }
if (!PlayerPrefs.HasKey("Mail")) { PlayerPrefs.SetString("Mail", string.Empty); }
if (!PlayerPrefs.HasKey("Password")) { PlayerPrefs.SetString("Password", string.Empty); }
}
private void Start()
{
rememberMeChecked = PlayerPrefs.GetInt("Checked");
mail = PlayerPrefs.GetString("Mail");
password = PlayerPrefs.GetString("Password");
if (!mail.Equals(string.Empty)) { fieldMail.text = mail; }
if (!password.Equals(string.Empty)) { fieldPassword.text = password; }
if (rememberMeChecked == 0) { rememberMe.isOn = false; }
if (rememberMeChecked == 1) { rememberMe.isOn = true; }
justChecked = rememberMe.isOn;
rememberMe.onValueChanged.AddListener(delegate {
justChecked = !justChecked;
if (justChecked) { Save(1); }
else { Save(0); }
LogInfo();
});
}
private void OnEnable()
{
fieldMail.text = mail;
fieldPassword.text = password;
if (rememberMeChecked == 0) { rememberMe.isOn = false; }
if (rememberMeChecked == 1) { rememberMe.isOn = true; }
}
public void OnButtonClicked()
{
PlayerPrefs.Save();
Debug.Log("PlayerPrefs saved.");
LogInfo();
}
public void Save(int rememberMeChecked)
{
switch (rememberMeChecked)
{
case 1:
{
PlayerPrefs.SetString("Mail", fieldMail.text);
PlayerPrefs.SetString("Password", fieldPassword.text);
PlayerPrefs.SetInt("Checked", rememberMeChecked);
}
break;
case 0:
default:
{
PlayerPrefs.SetString("Mail", string.Empty);
PlayerPrefs.SetString("Password", string.Empty);
PlayerPrefs.SetInt("Checked", rememberMeChecked);
}
break;
}
PlayerPrefs.Save();
}

Moving code behind xaml.cs to ViewModel in xamarin

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)

Cannot receive window message from child popup - Winforms

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);
}
}

xamarin.ios mp3 streaming from url stops before its end

I'm developing an ios app with xamarin, that contains some mp3 files to stream in the app.
i used thissample, and it seems to work fine...
but the mp3 stops before its end, always at around 2' 30"
this is the code i used:
public partial class PlayerViewController : UIViewController
{
NSTimer updatingTimer;
StreamingPlayback player;
public event EventHandler<ErrorArg> ErrorOccurred;
public string SourceUrl { get; private set; }
public string Title { get; private set; }
public PlayerOption PlayerOption { get; private set; }
public bool IsPlaying { get; private set; }
public PlayerViewController (PlayerOption playerOption, string sourceUrl, string title) : base ("PlayerViewController", null)
{
PlayerOption = playerOption;
SourceUrl = sourceUrl;
Title = title;
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
this.View = View;
volumeSlider.TouchUpInside += SetVolume;
playPauseButton.TouchUpInside += PlayPauseButtonClickHandler;
headerMusic.Text = this.Title;
}
void SetVolume (object sender, EventArgs e)
{
if (player == null)
return;
player.Volume = volumeSlider.Value;
}
public override void ViewWillAppear (bool animated)
{
base.ViewWillAppear (animated);
Title = PlayerOption == PlayerOption.Stream ? "Stream " : "Stream & Save";
playPauseButton.TitleLabel.Text = "Pause";
timeLabel.Text = string.Empty;
// Create a shared intance session & check
var session = AVAudioSession.SharedInstance ();
if (session == null) {
var alert = new UIAlertView ("Playback error", "Unable to playback stream", null, "Cancel");
alert.Show ();
alert.Clicked += (object sender, UIButtonEventArgs e) => alert.DismissWithClickedButtonIndex (0, true);
} else {
StartPlayback ();
IsPlaying = true;
// Set up the session for playback category
NSError error;
session.SetCategory (AVAudioSessionCategory.Playback, AVAudioSessionCategoryOptions.DefaultToSpeaker);
session.OverrideOutputAudioPort (AVAudioSessionPortOverride.Speaker, out error);
}
}
public override void ViewDidDisappear (bool animated)
{
base.ViewDidDisappear (animated);
if (updatingTimer != null)
updatingTimer.Invalidate ();
if (player != null) {
player.FlushAndClose ();
player = null;
}
}
void PlayPauseButtonClickHandler (object sender, EventArgs e)
{
if (player == null)
return;
if (IsPlaying)
player.Pause ();
else
player.Play ();
var title = IsPlaying ? "Play" : "Pause";
playPauseButton.SetTitle (title, UIControlState.Normal);
playPauseButton.SetTitle (title, UIControlState.Selected);
IsPlaying = !IsPlaying;
}
void StartPlayback ()
{
try {
var request = (HttpWebRequest)WebRequest.Create (SourceUrl);
request.BeginGetResponse (StreamDownloadedHandler, request);
} catch (Exception e) {
string.Format ("Error: {0}", e.ToString ());
}
}
void RaiseErrorOccurredEvent (string message)
{
var handler = ErrorOccurred;
if (handler != null)
handler (this, new ErrorArg { Description = message });
}
void StreamDownloadedHandler (IAsyncResult result)
{
var buffer = new byte [8192];
int l = 0;
int inputStreamLength;
double sampleRate = 0;
Stream inputStream;
AudioQueueTimeline timeline = null;
var request = result.AsyncState as HttpWebRequest;
try {
var response = request.EndGetResponse (result);
var responseStream = response.GetResponseStream ();
if (PlayerOption == PlayerOption.StreamAndSave)
inputStream = GetQueueStream (responseStream);
else
inputStream = responseStream;
using (player = new StreamingPlayback ()) {
player.OutputReady += delegate {
timeline = player.OutputQueue.CreateTimeline ();
sampleRate = player.OutputQueue.SampleRate;
};
InvokeOnMainThread (delegate {
if (updatingTimer != null)
updatingTimer.Invalidate ();
updatingTimer = NSTimer.CreateRepeatingScheduledTimer (0.5, (timer) => RepeatingAction (timeline, sampleRate));
});
while ((inputStreamLength = inputStream.Read (buffer, 0, buffer.Length)) != 0 && player != null) {
l += inputStreamLength;
player.ParseBytes (buffer, inputStreamLength, false, l == (int)response.ContentLength);
InvokeOnMainThread (delegate {
progressBar.Progress = l / (float)response.ContentLength;
});
}
}
} catch (Exception e) {
RaiseErrorOccurredEvent ("Error fetching response stream\n" + e);
Debug.WriteLine (e);
InvokeOnMainThread (delegate {
if (NavigationController != null)
NavigationController.PopToRootViewController (true);
});
}
}
void RepeatingAction (AudioQueueTimeline timeline, double sampleRate)
{
var queue = player.OutputQueue;
if (queue == null || timeline == null)
return;
bool disc = false;
var time = new AudioTimeStamp ();
queue.GetCurrentTime (timeline, ref time, ref disc);
playbackTime.Text = FormatTime (time.SampleTime / sampleRate);
}
string FormatTime (double time)
{
double minutes = time / 60;
double seconds = time % 60;
return String.Format ("{0}:{1:D2}", (int)minutes, (int)seconds);
}
Stream GetQueueStream (Stream responseStream)
{
var queueStream = new QueueStream (Environment.GetFolderPath (Environment.SpecialFolder.Personal) + "/copy.mp3");
var t = new Thread ((x) => {
var tbuf = new byte [8192];
int count;
while ((count = responseStream.Read (tbuf, 0, tbuf.Length)) != 0)
queueStream.Push (tbuf, 0, count);
});
t.Start ();
return queueStream;
}
}
how can i solve this problem?
thanks in advance
Had the same issue.
Open the StreamingPlayback.cs file
Change the variable
int bufferSize = 128 * 1024
Into
int bufferSize = 128 * 128
Or try other sizes..
It worked for me

Categories

Resources