Пример #1
0
        public bool NewFrankingApplication(FormViewParameter Parameter, Remarks rem)
        {
            LicenseAppRow rowLic = (LicenseAppRow)Parameter.Values;

            try
            {
                Guid LicenseId = FileManager.OpenNewFile(rowLic.SubmissionOfficeId, "LIC");
                if ((rem.Body != "") || (rem.Subject != ""))
                {
                    FileManager.AddRemarkToFile(LicenseId, rem.Subject, rem.Body);
                }

                string UserName = Thread.CurrentPrincipal.Identity.Name;
                //IGRSS.DataAccessLayer.Complain.ComplainDatatableRow row = (IGRSS.DataAccessLayer.Complain.ComplainDatatableRow) parameter.Values;
                IGRSS.DataAccessLayer.LicenseApplication.LicenseApplicationRow row = (IGRSS.DataAccessLayer.LicenseApplication.LicenseApplicationRow)Parameter.Values;
                IgrssAdapters.LAppTableAdapter.AddFrankingMachineDetails(LicenseId, row.ApplnNumber, row.NameOfApplicant, row.PresentAddress, row.PermanentAddress, DateTime.Now, row.Qualification, row.Experience, row.BusinessAddress, row.TotalInvestmentAmount, row.NameAndAddressOfReferer, row.SubmissionOfficeId, row.HomePhone, row.HoldingAnyOtherLicense, row.PurposeOfLicense);

                Dictionary <string, object> WfParams = new Dictionary <string, object>();
                WfParams.Add("LicenseId", LicenseId);
                WfParams.Add("InitiatingOffice", row.SubmissionOfficeId);

                WorkflowResults WfResult = WorkflowMediator.RunWorkflow(typeof(LicenseIssueProcess), WfParams);
                return(true);
            }
            catch (Exception ex)
            {
                if (ExceptionPolicy.HandleException(ex, "DAL"))
                {
                    throw;
                }
                return(false);
            }
        }
        protected override void DoCommand(IOrderGroup order, CommandParameters cp)
        {
            Mediachase.Ibn.Web.UI.CHelper.RequireDataBind();
            PurchaseOrder   purchaseOrder   = order as PurchaseOrder;
            WorkflowResults workflowResults = OrderGroupWorkflowManager.RunWorkflow(purchaseOrder, "SaveChangesWorkflow",
                                                                                    false,
                                                                                    false,
                                                                                    new Dictionary <string, object>
            {
                {
                    "PreventProcessPayment",
                    !string.IsNullOrEmpty(order.Properties["QuoteStatus"] as string) &&
                    (order.Properties["QuoteStatus"].ToString() == Constants.Quote.RequestQuotation ||
                     order.Properties["QuoteStatus"].ToString() == Constants.Quote.RequestQuotationFinished)
                }
            });

            if (workflowResults.Status != WorkflowStatus.Completed)
            {
                string msg = "Unknow error";
                if (workflowResults.Exception != null)
                {
                    msg = workflowResults.Exception.Message;
                }
                ErrorManager.GenerateError(msg);
            }
            else
            {
                WritePurchaseOrderChangeNotes(purchaseOrder);
                SavePurchaseOrderChanges(purchaseOrder);
                PurchaseOrderManager.UpdatePromotionUsage(purchaseOrder, purchaseOrder);
                OrderHelper.ExitPurchaseOrderFromEditMode(purchaseOrder.OrderGroupId);
            }
        }
Пример #3
0
        /// <summary>
        /// Inserting the new RefundApplication
        /// </summary>
        /// <param name="Parameter"> formview parameter</param>
        /// <param name="StampDetails">stamps added by the user in the form of Datatable </param>
        /// <param name="ActsApplicable">Acts added by the user</param>
        /// <returns>true, a record is inserted</returns>

        public bool AddNewRefundApplication(FormViewParameter Parameter, DataTable StampDetails, DataTable ActsApplicable, Remarks rem)
        {
            // Initiate some of the fields required for the process
            RefundApplicationRow rowRef = (RefundApplicationRow)Parameter.Values;
            Guid RefundApplicationId    = FileManager.OpenNewFile(rowRef.OfficeId, "REF");

            FileManager.AddRemarkToFile(RefundApplicationId, rem.Subject, rem.Body);
            string curUser           = Thread.CurrentPrincipal.Identity.Name;
            RefundApplicationRow row = (IGRSS.DataAccessLayer.Refund.RefundApplicationRow)Parameter.Values;

            try
            {
                TimeSpan ts            = new TimeSpan(row.PurchasedDate.Ticks - row.ApplicationDate.Ticks);
                string   DayDifference = ts.TotalDays.ToString();

                // Insert the Refiund Application data to database
                decimal TotalValueOfStamps = Convert.ToDecimal(row.TotalValueOfStamps);
                decimal pActualStampValue  = 10 * TotalValueOfStamps / 100;
                decimal ActualStampValue   = TotalValueOfStamps - pActualStampValue;
                IgrssAdapters.RefundApplicationAdapter.NewRefundApplication(RefundApplicationId, row.OfficeId,
                                                                            row.RegistrationNo, row.TypeOfRefund, row.ApplicationDate,
                                                                            row.VendorLicenseId, row.PurchasedDate, row.TotalValueOfStamps, row.ReasonForNotUsing, row.ApplicantName,
                                                                            row.ApplicantAddress, row.City, row.District, row.PinCode, row.PhoneNo.ToString(), DateTime.Now, curUser, ActualStampValue);

                // For each Stamp Detail entered by user
                // Insert the Stamp Details for this Refund in to child table
                foreach (DataRow StampDetail in StampDetails.Rows)
                {
                    IgrssAdapters.RefundStampDetailsAdapter.InsertStampDetails(RefundApplicationId, (Guid)StampDetail["RevenueStampId"],
                                                                               (string)StampDetail["ReturnedQty"], (string)StampDetail["StampNumber"]);
                }
                // For each Act selected by the user
                // Insert the Applicable Acts to child table
                foreach (DataRow Act in ActsApplicable.Rows)
                {
                    IgrssAdapters.RefundActsApplicable.InsertRefundActsApplicable(RefundApplicationId, (Guid)Act["ActId"], (bool)Act["Checked"], "");
                }

                // All database Inserts have been completed sucessfully initiate the Workflow
                // Create a Dioctionary to store Workflow Paramaters for Refund
                Dictionary <string, object> WfParams = new Dictionary <string, object>();
                // Add Refund Application  Id into the Workflow Parameter
                WfParams.Add("RefundId", RefundApplicationId);
                // Add Office Id in to Workflow Parameter
                // (to identify the process flow for the Office)
                WfParams.Add("InitiatingOffice", row.OfficeId);

                // Initiate the Refund Workflow by passing the Wf Parameters Dictionary
                WorkflowResults WfResult = WorkflowMediator.RunWorkflow(typeof(RefundProcess), WfParams);
            }
            catch (Exception ex)
            {
                if (ExceptionPolicy.HandleException(ex, "DAL"))
                {
                    throw;
                }
            }
            return(true);
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     //run the validate workflow to update the totals
     if (CartHelper.LineItems.Count() > 0)
     {
         WorkflowResults results = CartHelper.Cart.RunWorkflow("CartPrepare");
         CartHelper.Cart.AcceptChanges();
     }
     LoadData();
 }
Пример #5
0
        /// <summary>
        /// Handles the WorkflowIdled event of the WorkflowRuntime control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Workflow.Runtime.WorkflowEventArgs"/> instance containing the event data.</param>
        void WorkflowRuntime_WorkflowIdled(object sender, WorkflowEventArgs e)
        {
            _WorkflowResults = WorkflowResults.CreateRunningWorkflowResults(e);

            // Either pass the event to the custom handler or generate the exception
            if (WorkflowIdled != null)
            {
                WorkflowIdled(sender, e);
            }
        }
Пример #6
0
        /// <summary>
        /// Handles the WorkflowTerminated event of the WorkflowRuntime control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Workflow.Runtime.WorkflowTerminatedEventArgs"/> instance containing the event data.</param>
        void WorkflowRuntime_WorkflowTerminated(object sender, WorkflowTerminatedEventArgs e)
        {
            //_WorkflowWaitHandle.Set();
            _WorkflowResults = WorkflowResults.CreateTerminatedWorkflowResults(e);

            // Either pass the event to the custom handler or generate the exception
            if (WorkflowTerminated != null)
            {
                WorkflowTerminated(sender, e);
            }
        }
Пример #7
0
        public bool AddAppealAplication(FormViewParameter parameter, DataTable dtAct, Remarks rem)
        {
            //Initiate some of the fields required for the process
            AppealApplicationRow rowApl = (AppealApplicationRow)parameter.Values;
            Guid AppealId = FileManager.OpenNewFile(rowApl.OfficeId, "APL");

            FileManager.AddRemarkToFile(AppealId, rem.Subject, rem.Body);
            string curUser = Thread.CurrentPrincipal.Identity.Name;
            int    i       = 0;

            try
            {
                IGRSS.DataAccessLayer.Appeal.AppealApplicationRow row = (AppealApplicationRow)parameter.Values;
                i = IgrssAdapters.AppealAdapter.AddAppealApplication(AppealId, row.OfficeId, row.RegistrationNo, row.ApplicantName, row.Address, row.TypeOfAppeal, row.CalculatedAmount, row.DepositAmount, row.FeeReceiptNo, row.Amount, row.InwardDate, row.IsPaidAppealFee, row.AppealInTime, row.PaperFromTo, row.CourtFeeTicket, curUser, DateTime.Now, row.DocumentNo, row.OriginalSRO, row.DocumentDate, row.DaTeOffOrderFromCollector, row.DficitAmount, row.ReceiptNo, row.ReceiptDate);
                if (i > 0)
                {
                    foreach (DataRow dr in dtAct.Rows)
                    {
                        IgrssAdapters.AppealActAdapter.AddAppealAct(AppealId, (Guid)dr["ActId"], (bool)dr["Checked"]);
                    }

                    // All database Inserts have been completed sucessfully initiate the Workflow
                    // Create a Dioctionary to store Workflow Paramaters for Appeal
                    Dictionary <string, object> WfParams = new Dictionary <string, object>();
                    // Add Refund Application  Id into the Workflow Parameter
                    WfParams.Add("AppealId", AppealId);
                    // Add Office Id in to Workflow Parameter
                    // (to identify the process flow for the Office)
                    WfParams.Add("InitiatingOffice", row.OfficeId);

                    // Initiate the Refund Workflow by passing the Wf Parameters Dictionary
                    WorkflowResults WfResult = WorkflowMediator.RunWorkflow(typeof(AppealProcess), WfParams);
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                if (ExceptionPolicy.HandleException(ex, "DAL"))
                {
                    throw;
                }
                return(false);
            }
        }
Пример #8
0
        /// <summary>
        /// This function will add the new Complain.
        /// </summary>
        /// <returns>void</returns>
        public bool AddNewComplain(FormViewParameter Parameter, Remarks rem) //string ComplaintNo, Guid ComplaintType, Guid AgainstEmpID, Guid ComplainingEmpID, string ComplainantName, string ComplainantAddress, DateTime ComplaintDate, Guid ReceivingOfficeId, string Subject, string Detail)
        {
            string             curUser = Thread.CurrentPrincipal.Identity.Name;
            int                i       = 0;
            ComplainDetailsRow row     = (ComplainDetailsRow)Parameter.Values;

            try
            {
                Guid ComplainId = FileManager.OpenNewFile(row.ReceivingOfficeId, "COM");
                // Commented By Akhilesh.
                //if (rem.Subject != "" && rem.Body != "")
                //{
                //    FileManager.AddRemarkToFile(ComplainId, rem.Subject, rem.Body);
                //}
                int rowsAffected = 0;
                if (row.ComplaintType == new Guid("85aefd8d-6b7e-4ab8-b124-21b52073f7b3"))
                {
                    i = IgrssAdapters.ComplainAdapter.AddNewComplainDetails(ComplainId, row.ComplaintNo, row.ComplaintType, row.AgainstEmpID, row.ComplainingEmpID, row.ComplainantName, row.ComplainantAddress, row.ComplaintDate, row.ReceivingOfficeId, row.Subject, row.Detail, curUser, DateTime.Now, row.Designation, row.CurrentOffice);
                }
                if (row.ComplaintType == new Guid("96369687-0450-42fc-ba41-ad35ade13b53"))
                {
                    i = IgrssAdapters.ComplainAdapter.AddNewComplainDetails(ComplainId, row.ComplaintNo, row.ComplaintType, row.AgainstEmpID, row.ComplainingEmpID, row.ComplainantName, row.ComplainantAddress, row.ComplaintDate, null, row.Subject, row.Detail, curUser, DateTime.Now, row.Designation, null);
                }
                if (i > 0)
                {
                    Dictionary <string, object> WfParams = new Dictionary <string, object>();
                    WfParams.Add("ComplainId", ComplainId);
                    WfParams.Add("ComplainOffice", row.ReceivingOfficeId);

                    WorkflowResults WfResult = WorkflowMediator.RunWorkflow(typeof(ComplainProcess), WfParams);

                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                if (ExceptionPolicy.HandleException(ex, "DAL"))
                {
                    throw;
                }
                return(false);
            }
        }
Пример #9
0
        /// <summary>
        /// Runs the workflow and generates the error message for all the warnings.
        /// </summary>
        /// <param name="name">The name.</param>
        public virtual void RunWorkflow(string name)
        {
            WorkflowResults results  = this.Cart.RunWorkflow(name);
            object          warnings = results.OutputParameters["Warnings"];

            if (warnings != null)
            {
                StringDictionary warningsList = warnings as StringDictionary;
                if (warningsList != null)
                {
                    foreach (string warning in warningsList.Values)
                    {
                        ErrorManager.GenerateError(warning);
                    }
                }
            }
        }
Пример #10
0
        public static string RunWorkflowAndReturnFormattedMessage(Cart cart, string workflowName)
        {
            WorkflowResults      results         = cart.RunWorkflow(workflowName);
            IEnumerable <string> resultsMessages = OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(results);
            string returnString = string.Empty;

            if (resultsMessages.Count() > 0)
            {
                returnString = "Workflow Messages: ";
                foreach (string result in resultsMessages)
                {
                    returnString += result + "<BR />";
                }
            }

            return(returnString);
        }
Пример #11
0
        public static string RunWorkflowAndReturnFormattedMessage(Cart cart, string workflowName)
        {
            string returnString = string.Empty;

            // TODO: Be aware of this magic string that the workflow requires
            cart.ProviderId = "FrontEnd";
            WorkflowResults results         = cart.RunWorkflow(workflowName);
            var             resultsMessages = OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(results);

            if (resultsMessages.Count() > 0)
            {
                returnString = "";
                foreach (string result in resultsMessages)
                {
                    returnString += result + "<br />";
                }
            }
            return(returnString);
        }
Пример #12
0
        /// <summary>
        /// This function will Renew the vendor License.
        /// </summary>
        /// <param name="LicenseApplicationID"></param>
        /// <param name="RenewApplicationDate"></param>
        /// <returns>boolean</returns>

        public bool RenewAppDate(Guid LicenseApplicationID, DateTime RenewApplicationDate)
        {
            try
            {
                IgrssAdapters.LAppTableAdapter.UpdateRenewAppDate(Guid.NewGuid(), RenewApplicationDate, LicenseApplicationID);
                Dictionary <string, object> WfParams = new Dictionary <string, object>();
                WfParams.Add("LicenseId", LicenseApplicationID);
                //WfParams.Add("InitiatingOffice", row.SubmissionOfficeId);
                WorkflowResults WfResult = WorkflowMediator.RunWorkflow(typeof(LicenseIssueProcess), WfParams);
                return(true);
            }
            catch (Exception ex)
            {
                if (ExceptionPolicy.HandleException(ex, "DAL"))
                {
                    throw;
                }
                return(false);
            }
        }
Пример #13
0
        public bool AddAdjudicationRequest(FormViewParameter ValFormParameter, AdjudicationRequestRow AdjReqRow, DataTable FeeDetails, DataTable DocDetails)
        {
            string           curUser         = Thread.CurrentPrincipal.Identity.Name;
            Guid             AdjudicationId  = FileManager.OpenNewFile(AdjReqRow.OfficeId, "ADJ");;
            Guid             ValuationFormId = Guid.NewGuid();
            ValuationFormRow ValFormrow      = (IGRSS.DataAccessLayer.Adjudication.ValuationFormRow)ValFormParameter.Values;

            IgrssAdapters.ValuationAdapter.AddValuationDetail(ValuationFormId, ValFormrow.OfficeId, ValFormrow.DistrictCode, ValFormrow.TalukaCode, ValFormrow.VillageCode,
                                                              null, ValFormrow.Village_CityName, ValFormrow.TPSchemeNo, ValFormrow.TPSchemeName, ValFormrow.FinalPlotNo, ValFormrow.CitySurveyNo, ValFormrow.RevenueSurveyNo,
                                                              ValFormrow.Ward_SubWardNo, ValFormrow.NameOfOwner, ValFormrow.AddressOfOwner, ValFormrow.NameOfClaimingParty, ValFormrow.AddressOfClaimingParty,
                                                              ValFormrow.AreaOfPlot, ValFormrow.AreaOfConstruction, ValFormrow.YearOfConstruction, ValFormrow.NoOfFloors, ValFormrow.TypeOfProperty,
                                                              ValFormrow.DescOfProperty, ValFormrow.ShopsOnGroundFloor, ValFormrow.IsPropertyInCommercial, ValFormrow.TypeOfElectricfication,
                                                              ValFormrow.CompoundWallType, ValFormrow.IsLightsOnCompoundWall, ValFormrow.WaterStorageFacility, ValFormrow.DrainageSystem, ValFormrow.NoOfLifts,
                                                              ValFormrow.AreaOfEachLift, ValFormrow.InternalRoad, ValFormrow.ValuatedBefore, ValFormrow.HeightOfCeiling, ValFormrow.TypeOfTiles,
                                                              ValFormrow.WallFurnishing, ValFormrow.NoOfBathrooms, ValFormrow.BathroomTilesHeight, ValFormrow.NoOfToilets, ValFormrow.ToiletTilesHeight, ValFormrow.Parking, curUser, DateTime.Now);

            IgrssAdapters.AdjudicationAdapter.AddAdjudicationRequest(AdjudicationId, ValuationFormId, null, AdjReqRow.OfficeId, AdjReqRow.ApplicationDate, AdjReqRow.ReceiptNumber, AdjReqRow.AdjudicationTotalFees);

            foreach (DataRow FeeDetail in FeeDetails.Rows)
            {
                IgrssAdapters.AdjudicationFeeAdapter.AddAdjudicationFees(AdjudicationId, (Guid)FeeDetail["FeeId"], Convert.ToDecimal(FeeDetail["Amount"]));
            }
            foreach (DataRow DocDetail in DocDetails.Rows)
            {
                IgrssAdapters.AdjudicationDocumentAdapter.AddAdjudicationDocument(ValuationFormId, (Guid)DocDetail["DocumentTypeId"], Convert.ToBoolean(DocDetail["Submitted"]), Convert.ToString(DocDetail["DocumentNumber"]), Convert.ToString(DocDetail["Remarks"]));
            }
            // All database Inserts have been completed sucessfully initiate the Workflow
            // Create a Dioctionary to store Workflow Paramaters for Adjudication
            Dictionary <string, object> WfParams = new Dictionary <string, object>();

            // Add Adjudication Application  Id into the Workflow Parameter
            WfParams.Add("AdjudicationId", AdjudicationId);
            WfParams.Add("ValuationFormId", ValuationFormId);
            // Add Office Id in to Workflow Parameter
            // (to identify the process flow for the Office)
            WfParams.Add("InitiatingOffice", ValFormrow.OfficeId);
            // Initiate the Refund Workflow by passing the Wf Parameters Dictionary
            WorkflowResults WfResult = WorkflowMediator.RunWorkflow(typeof(AdjudicationProcess), WfParams);

            return(true);
        }
        public ActionResult Index(CartPage currentPage)
        {
            // (added for D2)
            if (ch.LineItems.Count() == 0) // cart could exist but not containing LineItems? ... gets the "Index Out Of Range" then
            {
                wfMessages.Add("No LineItems");

                var model = new CartViewModel // using a bit of it
                {
                    //lineItems = new List<LineItem>(),
                    //cartTotal = "0",
                    messages = wfMessages
                };

                //return View(model);
                return(View("NoCart", model));
            }
            else
            {
                // ToDo: (lab D2)
                //WorkflowResults result = ch.Cart.RunWorkflow(OrderGroupWorkflowManager.CartValidateWorkflowName);
                WorkflowResults result = OrderGroupWorkflowManager.RunWorkflow
                                             (ch.Cart, OrderGroupWorkflowManager.CartValidateWorkflowName);

                //List<string> wfMessages = new List<string>(OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(result));
                wfMessages = OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(result).ToList();

                ch.Cart.AcceptChanges();

                var model = new CartViewModel
                {
                    lineItems = ch.LineItems,
                    cartTotal = ch.Cart.Total.ToString("C"),
                    messages  = wfMessages
                };

                return(View(model));
            }
        }
        //Exercise (E2) Do CheckOut
        public ActionResult CheckOut(CheckOutViewModel model)
        {
            // ToDo: declare a variable for CartHelper
            CartHelper ch = new CartHelper(Cart.DefaultName);

            int orderAddressId = 0;

            // ToDo: Addresses (an If-Else)
            if (CustomerContext.Current.CurrentContact == null)
            {
                // Anonymous... one way of "doing it"... for example, if no other address exist
                orderAddressId = ch.Cart.OrderAddresses.Add(
                    new OrderAddress
                {
                    CountryCode        = "SWE",
                    CountryName        = "Sweden",
                    Name               = "SomeCustomerAddress",
                    DaytimePhoneNumber = "123456",
                    FirstName          = "John",
                    LastName           = "Smith",
                    Email              = "*****@*****.**",
                });
            }
            else
            {
                // Logged in
                if (CustomerContext.Current.CurrentContact.PreferredShippingAddress == null)
                {
                    // no pref. address set... so we set one for the contact
                    CustomerAddress newCustAddress =
                        CustomerAddress.CreateForApplication(AppContext.Current.ApplicationId);
                    newCustAddress.AddressType        = CustomerAddressTypeEnum.Shipping; // mandatory
                    newCustAddress.ContactId          = CustomerContext.Current.CurrentContact.PrimaryKeyId;
                    newCustAddress.CountryCode        = "SWE";
                    newCustAddress.CountryName        = "Sweden";
                    newCustAddress.Name               = "new customer address"; // mandatory
                    newCustAddress.DaytimePhoneNumber = "123456";
                    newCustAddress.FirstName          = CustomerContext.Current.CurrentContact.FirstName;
                    newCustAddress.LastName           = CustomerContext.Current.CurrentContact.LastName;
                    newCustAddress.Email              = "*****@*****.**";

                    // note: Line1 & City is what is shown in CM at a few places... not the Name
                    CustomerContext.Current.CurrentContact.AddContactAddress(newCustAddress);
                    CustomerContext.Current.CurrentContact.SaveChanges();

                    // ... needs to be in this order
                    CustomerContext.Current.CurrentContact.PreferredShippingAddress = newCustAddress;
                    CustomerContext.Current.CurrentContact.SaveChanges(); // need this ...again

                    // then, for the cart
                    orderAddressId = ch.Cart.OrderAddresses.Add(new OrderAddress(newCustAddress));
                }
                else
                {
                    // there is a preferred address set (and, a fourth alternative exists... do later )
                    OrderAddress orderAddress =
                        new OrderAddress(CustomerContext.Current.CurrentContact.PreferredShippingAddress);

                    // then, for the cart
                    orderAddressId = ch.Cart.OrderAddresses.Add(orderAddress);
                }
            }

            // Depending how it was created...
            OrderAddress address = ch.FindAddressById(orderAddressId.ToString());

            // ToDo: Define Shipping
            ShippingMethodDto.ShippingMethodRow theShip =
                ShippingManager.GetShippingMethod(model.SelectedShipId).ShippingMethod.First();

            int shippingId = ch.Cart.OrderForms[0].Shipments.Add(
                new Shipment
            {                                          // ...removing anything?
                ShippingAddressId      = address.Name, // note: use no custom prefixes
                ShippingMethodId       = theShip.ShippingMethodId,
                ShippingMethodName     = theShip.Name,
                ShipmentTotal          = theShip.BasePrice,
                ShipmentTrackingNumber = "My tracking number",
            });

            // get the Shipping ... check to see if the Shipping knows about the LineItem
            Shipment firstOrderShipment = ch.Cart.OrderForms[0].Shipments.FirstOrDefault();

            // First (and only) OrderForm
            LineItemCollection lineItems = ch.Cart.OrderForms[0].LineItems;

            // ...basic now... one OrderForm - one Shipping
            foreach (LineItem lineItem in lineItems)
            {
                int index = lineItems.IndexOf(lineItem);
                if ((firstOrderShipment != null) && (index != -1))
                {
                    firstOrderShipment.AddLineItemIndex(index, lineItem.Quantity);
                }
            }


            // Execute the "Shipping & Taxes - WF" (CartPrepare) ... and take care of the return object
            WorkflowResults resultPrepare     = ch.Cart.RunWorkflow(OrderGroupWorkflowManager.CartPrepareWorkflowName);
            List <string>   wfMessagesPrepare = new List <string>(OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(resultPrepare));


            // ToDo: Define Shipping
            PaymentMethodDto.PaymentMethodRow thePay = PaymentManager.GetPaymentMethod(model.SelectedPayId).PaymentMethod.First();
            Payment firstOrderPayment = ch.Cart.OrderForms[0].Payments.AddNew(typeof(OtherPayment));

            // ... need both below
            firstOrderPayment.Amount            = firstOrderShipment.SubTotal + firstOrderShipment.ShipmentTotal; // will change...
            firstOrderPayment.BillingAddressId  = address.Name;
            firstOrderPayment.PaymentMethodId   = thePay.PaymentMethodId;
            firstOrderPayment.PaymentMethodName = thePay.Name;
            // ch.Cart.CustomerName = "John Smith"; // ... this line overwrites what´s in there, if logged in


            // Execute the "Payment activation - WF" (CartCheckout) ... and take care of the return object
            // ...activates the gateway (same for shipping)
            WorkflowResults resultCheckout     = ch.Cart.RunWorkflow(OrderGroupWorkflowManager.CartCheckOutWorkflowName, false);
            List <string>   wfMessagesCheckout = new List <string>(OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(resultCheckout));
            //ch.RunWorkflow("CartValidate") ... can see this (or variations)

            string        trackingNumber = String.Empty;
            PurchaseOrder purchaseOrder  = null;

            // Add a transaction scope and convert the cart to PO
            using (var scope = new Mediachase.Data.Provider.TransactionScope())
            {
                purchaseOrder = ch.Cart.SaveAsPurchaseOrder();
                ch.Cart.Delete();
                ch.Cart.AcceptChanges();
                trackingNumber = purchaseOrder.TrackingNumber;
                scope.Complete();
            }

            // Housekeeping below (Shipping release, OrderNotes and save the order)
            OrderStatusManager.ReleaseOrderShipment(purchaseOrder.OrderForms[0].Shipments[0]);

            OrderNotesManager.AddNoteToPurchaseOrder(purchaseOrder, DateTime.UtcNow.ToShortDateString() + " released for shipping", OrderNoteTypes.System, CustomerContext.Current.CurrentContactId);

            purchaseOrder.ExpirationDate = DateTime.UtcNow.AddDays(30);
            purchaseOrder.Status         = OrderStatus.InProgress.ToString();

            purchaseOrder.AcceptChanges(); // need this here, else no "order-note" persisted


            // Final steps, navigate to the order confirmation page
            StartPage        home = _contentLoader.Service.Get <StartPage>(ContentReference.StartPage);
            ContentReference orderPageReference = home.Settings.orderPage;

            string passingValue = trackingNumber;

            return(RedirectToAction("Index", new { node = orderPageReference, passedAlong = passingValue }));
        }
        public void CheckOnCalc() // (Cart theCart, Guid id)
        {
            Cart theCart = LoadOrCreateCart();

            //CartHelper ch = new CartHelper(theCart); // lazy now
            if (theCart.OrderForms[0].LineItems.Count() > 0) // before WF-exec
            {
                // Do calc
            }
            else // just looking
            {
                // add a LineItem
                //ILineItem lineItem = new // nope
                //_oRep.Service. // nope nothing about LineItems
                // seems to need "OldSchool" ... doing it lazy for now
                //ch.AddEntry(CatalogContext.Current.GetCatalogEntry("Some-Sox_1")); // have a look at "LoadOrCreateCart"

                ContentReference theRef     = _refConv.GetContentLink("Long-Sleeve-Shirt-White-Small_1");
                VariationContent theContent = _contentLoader.Get <VariationContent>(theRef);
                LineItem         li         = CreateLineItem(theContent, 2, 22);

                var orderForm = theCart.OrderForms.First();
                orderForm.LineItems.Add(li);
                var index = orderForm.LineItems.IndexOf(li);
                theCart.OrderForms.First().Shipments.First().AddLineItemIndex(index, li.Quantity);
            }

            // just checking
            WorkflowResults wfResult = OrderGroupWorkflowManager.RunWorkflow
                                           (theCart, OrderGroupWorkflowManager.CartValidateWorkflowName);

            IMarket  market = _currentMarket.GetCurrentMarket();
            Currency curr   = theCart.BillingCurrency; // og.Currency;

            Guid        id   = new Guid("097361ec-a4ac-4671-9f2a-a56e3b6f7e97");
            IOrderGroup og   = _oRep.Service.Load(id, theCart.Name).FirstOrDefault();
            IOrderForm  form = og.Forms.FirstOrDefault();
            IShipment   ship = form.Shipments.FirstOrDefault(); // there is a shipment there (...is a "bigger change")

            //CartHelper ch = new CartHelper((Cart)og);
            int liId = form.Shipments.FirstOrDefault().LineItems.FirstOrDefault().LineItemId; // okay

            Shipment otherShip = theCart.OrderForms[0].Shipments.FirstOrDefault();            // no ship here...?
            // it's not added yet the old-school way
            int shipments = theCart.OrderForms[0].Shipments.Count;                            // zero...?

            //otherShip = (Shipment)ship;
            //int ShipId = theCart.OrderForms[0].Shipments.Add(otherShip); // Gets ordinal index it seems ... not ShipmentId
            // okay, but...



            ILineItem Ili = form.Shipments.FirstOrDefault().LineItems.FirstOrDefault();

            var dtoShip = ShippingManager.GetShippingMethodsByMarket
                              (_currMarket.Service.GetCurrentMarket().MarketId.Value, false).ShippingMethod.FirstOrDefault();
            Shipment s = new Shipment();

            s.ShippingMethodId   = dtoShip.ShippingMethodId;
            s.ShippingMethodName = dtoShip.Name;
            int ShipId = theCart.OrderForms[0].Shipments.Add(s);

            // ..seems to work,
            //PurchaseOrderManager.AddLineItemToShipment(
            //  theCart, Ili.LineItemId, s, 2);
            // probably need to persist (old way) & reload "the new way"
            //ILineItem li2 = form.Shipments.FirstOrDefault().LineItems.FirstOrDefault(); // new way (null)

            // OrderForm
            Money formTot = _ofCalc.Service.GetTotal(form, market, curr);

            // OrderGroup
            Money handlingFee = _ogCalc.Service.GetHandlingTotal(theCart);
            Money subTotal    = _ogCalc.Service.GetSubTotal(theCart);
            Money total       = _ogCalc.Service.GetTotal(theCart);

            // Shipping
            //var shipCost = _shipCalc.Service.GetShipmentCost(form, market, curr);
            var shipTot = _shipCalc.Service.GetShippingItemsTotal(ship, curr);

            //LineItems
            var x = _lItemCalc.Service.GetExtendedPrice(theCart.OrderForms.FirstOrDefault().LineItems.FirstOrDefault(), curr); // Ext.Price verkar vara på väg ut

            //Taxes
            var t = _taxCalc.Service.GetTaxTotal(form, market, curr);
        }