/// <summary>
        /// Makes the performance report - creates a new entry on the <see cref="CarrierPerformanceReport"/> for each shipping
        /// </summary>
        /// <param name="EDC">The EDC.</param>
        /// <param name="sp">The <see cref="Shipping"/>.</param>
        /// <param name="result">The result.</param>
        /// <exception cref="System.ApplicationException">
        /// <see cref="ApplicationException"/>: ShippingAssociatedPartner
        /// <see cref="ApplicationException"/>: MakePerformanceReportDataInconsistent
        /// </exception>
        private void MakePerformanceReport(EntitiesDataContext EDC, Shipping sp, ActionResult result)
        {
            try
            {
                DateTime _sDate = sp.StartTime.Value.Date;
                if (sp.PartnerTitle == null)
                {
                    throw new ApplicationException("ShippingAssociatedPartner".GetLocalizedString());
                }
                CarrierPerformanceReport _rprt = (from _rx in sp.PartnerTitle.CarrierPerformanceReport
                                                  where _rx.CPRDate.Value == _sDate
                                                  select _rx).FirstOrDefault();
                if (_rprt == null)
                {
                    _rprt = new CarrierPerformanceReport()
                    {
                        CPRDate                     = sp.StartTime.Value.Date,
                        CPR2PartnerTitle            = sp.PartnerTitle,
                        Title                       = sp.PartnerTitle.Title(),
                        CPRNumberDelayed            = 0,
                        CPRNumberDelayed1h          = 0,
                        CPRNumberNotShowingUp       = 0,
                        CPRNumberOnTime             = 0,
                        CPRNumberOrdered            = 0,
                        CPRNumberRejectedBadQuality = 0,
                        ReportPeriod                = sp.StartTime.Value.ToMonthString()
                    };
                    EDC.CarrierPerformanceReport.InsertOnSubmit(_rprt);
                }
                _rprt.CPRNumberOrdered++;
                List <TimeSlotTimeSlot> _dlyd = sp.DelayedTimeSlots(EDC);
                _rprt.CPRNumberNotShowingUp += _dlyd.Count();
                EDC.TimeSlot.DeleteAllOnSubmit(_dlyd);
                EDC.TimeSlot.DeleteAllOnSubmit(sp.OccupiedTimeSlots(EDC));
                if (sp.TrailerCondition.GetValueOrDefault(TrailerCondition.None) == TrailerCondition._1Unexceptable)
                {
                    _rprt.CPRNumberRejectedBadQuality++;
                }
                if (sp.ShippingState.Value == ShippingState.Completed)
                {
                    switch (CalculateDelay(sp.StartTime.Value - sp.TSStartTime.Value))
                    {
                    case Delay.JustInTime:
                        _rprt.CPRNumberOnTime++;
                        break;

                    case Delay.Delayed:
                        _rprt.CPRNumberDelayed++;
                        break;

                    case Delay.VeryLate:
                        _rprt.CPRNumberDelayed1h++;
                        break;
                    }
                }
                //TODO to be delated.
                try
                {
                    EDC.SubmitChanges();
                }
                catch (ChangeConflictException)
                {
                    EDC.ResolveChangeConflicts(result);
                    EDC.SubmitChanges();
                }
            }
            catch (Exception ex)
            {
                result.AddException("MakePerformanceReport", ex);
            }
        }
        private void m_CalculateTimeoutCode_ExecuteCode(object sender, EventArgs e)
        {
            try
            {
                this.SendingEmailsReplicator_InitialChildData = null;
                using (EntitiesDataContext EDC = new EntitiesDataContext(m_OnWorkflowActivated_WorkflowProperties.SiteUrl))
                {
                    Shipping _sp = Element.GetAtIndex <Shipping>(EDC.Shipping, m_OnWorkflowActivated_WorkflowProperties.ItemId.ToString());
                    TimeSpan _timeDistance;
                    switch (_sp.ShippingState.GetValueOrDefault(ShippingState.None))
                    {
                    case ShippingState.Confirmed:
                        switch (_sp.CalculateDistance(out _timeDistance))
                        {
                        case Shipping.Distance.UpTo72h:
                        case Shipping.Distance.UpTo24h:
                        case Shipping.Distance.UpTo2h:
                        case Shipping.Distance.VeryClose:
                            SetupTimeout(_timeDistance, _sp);
                            break;

                        case Shipping.Distance.Late:
                            MakeDelayed(_sp, EDC, m_TimeOutReached);
                            break;
                        }
                        break;

                    case ShippingState.WaitingForCarrierData:
                    case ShippingState.WaitingForConfirmation:
                    case ShippingState.Creation:
                        switch (_sp.CalculateDistance(out _timeDistance))
                        {
                        case Shipping.Distance.UpTo72h:
                            RequestData(_timeDistance, _sp, AlarmPriority.Normal, EDC, m_TimeOutReached);
                            break;

                        case Shipping.Distance.UpTo24h:
                            RequestData(_timeDistance, _sp, AlarmPriority.Warning, EDC, m_TimeOutReached);
                            break;

                        case Shipping.Distance.UpTo2h:
                            RequestData(_timeDistance, _sp, AlarmPriority.Warning, EDC, m_TimeOutReached);
                            break;

                        case Shipping.Distance.VeryClose:
                            RequestData(_timeDistance, _sp, AlarmPriority.High, EDC, m_TimeOutReached);
                            break;

                        case Shipping.Distance.Late:
                            MakeDelayed(_sp, EDC, m_TimeOutReached);
                            break;
                        }
                        break;

                    case ShippingState.Cancelation:
                        MakeCanceled(_sp, EDC);
                        break;

                    case ShippingState.Underway:
                    default:
                        SetupTimeout(TimeSpan.FromHours(5), _sp);
                        break;
                    }// switch (_sp.State.Value)
                    try
                    {
                        EDC.SubmitChanges(ConflictMode.ContinueOnConflict);
                    }
                    catch (ChangeConflictException)
                    {
                        ActionResult _ar = new ActionResult("ShippingStateMachine.m_CalculateTimeoutCode_ExecuteCode");
                        EDC.ResolveChangeConflicts(_ar);
                        EDC.SubmitChanges();
                        _ar.ReportActionResult(EDC);
                    }
                    finally { m_TimeOutReached = false; }
                } //using (EntitiesDataContext EDC
            }
            catch (Exception _ex)
            {
                ReportException("ShippingStateMachine.m_CalculateTimeoutCode_ExecuteCode", _ex);
            }
        }
        private void m_OnWorkflowItemChanged_Invoked(object sender, ExternalDataEventArgs e)
        {
            string _at = "Starting";

            try
            {
                ActionResult _ar = new ActionResult("ShippingStateMachine.m_OnWorkflowItemChanged_Invoked");
                _at = "using ( EntitiesDataContext ";
                using (EntitiesDataContext _EDC = new EntitiesDataContext(m_OnWorkflowActivated_WorkflowProperties.SiteUrl))
                {
                    _at = "Shipping _sp = ";
                    Shipping _sp = Element.GetAtIndex(_EDC.Shipping, m_OnWorkflowActivated_WorkflowProperties.Item.ID.ToString());
                    m_OnWorkflowItemChangedLogToHistoryList_HistoryDescription = string.Format("ShipmentModified".GetLocalizedString(), _sp.ShippingState.GetValueOrDefault(ShippingState.None), _sp.Editor.NotAvailable());
                    _at = "if ( _sp.IsOutbound";
                    bool _needSubmitChanges = false;
                    if (_sp.IsOutbound.GetValueOrDefault(false) && (_sp.ShippingState.GetValueOrDefault(ShippingState.None) == ShippingState.Completed))
                    {
                        _at = "MakeOutboundReport";
                        MakeOutboundReport(_sp, _EDC, _ar);
                        _needSubmitChanges = true;
                    }
                    if (_sp.ShippingState.GetValueOrDefault(ShippingState.None) == ShippingState.Completed ||
                        (_sp.ShippingState.GetValueOrDefault(ShippingState.None) == ShippingState.Cancelation && _sp.Shipping2PartnerTitle != null))
                    {
                        _at = "MakePerformanceReport";
                        MakePerformanceReport(_EDC, _sp, _ar);
                    }
                    if (_needSubmitChanges)
                    {
                        try
                        {
                            _at = "_EDC.SubmitChanges";
                            _EDC.SubmitChanges(ConflictMode.ContinueOnConflict);
                        }
                        catch (ChangeConflictException)
                        {
                            _at = "_EDC.ResolveChangeConflicts";
                            _EDC.ResolveChangeConflicts(_ar);
                            _at = "_EDC.SubmitChanges #2";
                            _EDC.SubmitChanges();
                        }
                    }
                    _at = "_ar.ReportActionResult";
                    _ar.ReportActionResult(_EDC);
                }
            }
            catch (Exception ex)
            {
                ReportException(_at, ex);
            }
            //if (m_OnWorkflowItemChanged_BeforeProperties1.Count == 0)
            //{
            //  string _msg = "Connot display changes because the BeforeProperties is empty.";
            //  m_SendWarningLogToHistoryListActivity_HistoryDescription = _msg;
            //}
            //else
            //{
            //  m_SendWarningLogToHistoryListActivity_HistoryDescription = "The following coluns have been changed: ";
            //  foreach (var item in m_OnWorkflowItemChanged_AfterProperties1.Keys)
            //  {
            //    try
            //    {
            //      if (m_OnWorkflowItemChanged_AfterProperties1[item] == null)
            //        throw new ApplicationException(String.Format("AfterProperties for key {0} is null.", item));
            //      if (m_OnWorkflowItemChanged_BeforeProperties1[item] == null)
            //        continue;
            //      if (m_OnWorkflowItemChanged_AfterProperties1[item].ToString() != m_OnWorkflowItemChanged_BeforeProperties1[item].ToString())
            //        m_SendWarningLogToHistoryListActivity_HistoryDescription += item.ToString() + ", ";
            //    }
            //    catch (Exception ex)
            //    {
            //      ReportException("m_OnWorkflowItemChanged_Invoked", ex);
            //    }
            //  }
            //}
        }