/// <summary>
        /// Add an order line to the order defined by <paramref name="order"/>
        /// </summary>
        /// <param name="order">The order to which the line should be added</param>
        /// <param name="gtin">The global trade identification number of the item in the line</param>
        /// <param name="lot">(Optional) The lot number to be used. Note if null is passed in <paramref name="lot"/> then the oldest lot is used first</param>
        /// <param name="qty">The quantity of the item to be added to the order</param>
        /// <param name="uom">(Optional) The base unit of measure. If <paramref name="uom"/> is null then the default UOM for the item described by <paramref name="gtin"/> is used</param>
        /// <returns>The constructed and saved <see cref="T:GIIS.DataLayer.TransferOrderDetail"/></returns>
        /// <remarks>
        /// The add order line function is responsible for adding a new order line to the order detail. This function operates in the following manner:
        /// <list type="ordered">
        /// <item>
        ///     <description>[Guard Condition] If the order passed into the function IS in the “Packed” or “Shipped” state then throw an invalid state exception (sanity check)</description>
        /// </item>
        /// <item>
        ///     <description>Lookup the item by the GTIN provided in the function call.</description>
        /// </item>
        /// <item>
        ///     <description>[Guard Condition] If the lot number is provided, and the lot number is not a valid lot number for the item provided then throw an error code</description>
        /// </item>
        /// <item>
        ///     <description>If the current status of the order to which the detail is to be attached is “Released” then
        ///         <list type="ordered">
        ///             <item>
        ///                 <description>Instantiate a StockManagementLogic BLL class</description>
        ///             </item>
        ///             <item>Allocate the stock using the Allocate method</item>
        ///         </list>
        ///     </description>
        /// </item>
        /// <item>
        ///     <description>Set the unit of measure, quantity, gtin, etc. fields of the TransferOrderDetail instance to the parameters and fields derived from loaded Item.</description>
        /// </item>
        /// <item>
        ///     <description>Save the order line.</description>
        /// </item>
        ///</list>
        /// </remarks>
        public TransferOrderDetail AddOrderLine(TransferOrderHeader order, String gtin, String lot, Int32 qty, Uom uom, Int32 modifiedBy)
        {
            if (order == null)
            {
                throw new ArgumentNullException("order");
            }
            if (String.IsNullOrEmpty(gtin))
            {
                throw new ArgumentNullException("gtin");
            }

            // Sanity check
            if (order.OrderStatus == (int)OrderStatusType.Shipped ||
                order.OrderStatus == (int)OrderStatusType.Cancelled)
            {
                throw new IllegalStateException((OrderStatusType)order.OrderStatus, "TransferOrderHeader", "AddOrderLine");
            }

            // Lookup item by GTIN and optionally lot
            ItemLot item = null;

            if (!String.IsNullOrEmpty(lot))
            {
                item = ItemLot.GetItemLotByGtinAndLotNo(gtin, lot);
            }
            if (item == null)
            {               // not found - We get the item by lot
                item = ItemLot.GetItemLotByGtin(gtin);
                lot  = "*"; // null;
            }

            // Item still null?
            if (item == null)
            {
                throw new InvalidOperationException(String.Format("Cannot locate item with GTIN {0}", gtin));
            }

            // Construct the order detail
            TransferOrderDetail retVal = new TransferOrderDetail()
            {
                ModifiedBy             = modifiedBy,
                ModifiedOn             = DateTime.Now,
                OrderCustomItem        = false,
                OrderDetailDescription = item.ItemObject.Name,
                OrderDetailStatus      = order.OrderStatus,
                OrderGtin         = gtin,
                OrderGtinLotnum   = lot,
                OrderNum          = order.OrderNum,
                OrderQty          = qty,
                OrderQtyInBaseUom = qty,
                OrderUom          = uom.Name
            };

            // HACK: Overcome lack of transaction processing we have to be careful about how we do this
            ItemTransaction allocateTransaction = null;

            // Current state of order is released? We need to allocate this line item
            if (order.OrderStatus == (int)OrderStatusType.Released)
            {
                StockManagementLogic stockLogic = new StockManagementLogic();
                // We need to release this order ... If the lot was null we'll use the oldest lot number
                if (String.IsNullOrEmpty(lot))
                {
                    item = this.GetOldestLot(order.OrderFacilityFromObject, gtin);
                }

                // Allocation of specified lot
                allocateTransaction = stockLogic.Allocate(order.OrderFacilityFromObject, gtin, item.LotNumber, qty, null, modifiedBy);

                // Update order
                retVal.OrderGtinLotnum = item.LotNumber;
            }

            // Save
            retVal.OrderDetailNum = TransferOrderDetail.Insert(retVal);

            // HACK: Update the allocate transaction. This would be cleaned up with a transaction to back out changes (basically do the order detail then allocate)
            if (allocateTransaction != null)
            {
                allocateTransaction.RefId    = retVal.OrderNum.ToString();
                allocateTransaction.RefIdNum = retVal.OrderDetailNum;
                ItemTransaction.Update(allocateTransaction);
            }

            return(retVal);
        }
    protected void btnEdit_Click(object sender, EventArgs e)
    {
        try
        {
            if (Page.IsValid)
            {
                int    id  = -1;
                string _id = Request.QueryString["id"].ToString();
                int.TryParse(_id, out id);
                int userId = CurrentEnvironment.LoggedUser.Id;

                ItemTransaction o = ItemTransaction.GetItemTransactionById(id);

                DateTime date = DateTime.ParseExact(txtStockCountDate.Text, ConfigurationDate.GetConfigurationDateById(int.Parse(Configuration.GetConfigurationByName("DateFormat").Value)).DateFormat.ToString(), CultureInfo.CurrentCulture);
                o.TransactionDate = date;
                o.Gtin            = ddlGtin.SelectedValue;
                if (ddlItemLot.SelectedIndex != 0)
                {
                    o.GtinLot = ddlItemLot.SelectedValue;
                }
                o.TransactionTypeId = 3; //Stock Count

                double qty  = double.Parse(txtQuantity.Text);
                int    diff = 0;
                if (o.TransactionQtyInBaseUom != qty)
                {
                    diff = (int)(qty - o.TransactionQtyInBaseUom);
                }

                o.TransactionQtyInBaseUom = double.Parse(txtQuantity.Text);
                o.Notes      = txtNotes.Text;
                o.ModifiedOn = DateTime.Now;
                o.ModifiedBy = userId;

                int i = ItemTransaction.Update(o);


                if (i > 0)
                {
                    UpdateBalance(o, diff);

                    lblSuccess.Visible = true;
                    lblWarning.Visible = false;
                    lblError.Visible   = false;
                    odsTransactionLines.SelectParameters.Clear();
                    odsTransactionLines.SelectParameters.Add("i", o.Id.ToString());
                    odsTransactionLines.DataBind();
                    ClearControls(this);
                    btnEdit.Visible = false;
                    btnAdd.Visible  = true;
                }
                else
                {
                    lblSuccess.Visible = false;
                    lblWarning.Visible = false;
                    lblError.Visible   = true;
                }
            }
        }
        catch (Exception ex)
        {
            lblSuccess.Visible = false;
            lblWarning.Visible = false;
            lblError.Visible   = true;
        }
    }