Ejemplo n.º 1
0
        public IActionResult UpdatedCart(int userId, LineItems changedLineItem)
        {
            var  openCart      = _repository.FindOpenCarts(userId);
            bool cartDoesExist = openCart != null;

            if (cartDoesExist)
            {
                var shoppingCartItems = _repository.GetLineItem(changedLineItem.InvoiceId);
                var findCartItems     = shoppingCartItems.ToList().Find(x => x.LineItemId == changedLineItem.LineItemId);
                if (changedLineItem.Quantity == 0)
                {
                    // if line item quantity is zero then delete the line item
                    var multiplyQuantity = findCartItems.Price * findCartItems.Quantity;
                    _repository.DeleteLineItem(changedLineItem.LineItemId);
                    openCart = _repository.UpdateTotalCost(multiplyQuantity, changedLineItem.InvoiceId);
                }
                else
                {
                    // if the line item exists then modify it
                    var cartDif         = findCartItems.Quantity - changedLineItem.Quantity;
                    var multiDiff       = cartDif * findCartItems.Price;
                    var updatedLineItem = _repository.ChangeLineItemQty(changedLineItem.Quantity, changedLineItem.LineItemId);
                    openCart = _repository.UpdateTotalCost(multiDiff, changedLineItem.InvoiceId);
                }
            }
            return(Ok(openCart));
        }
Ejemplo n.º 2
0
        protected virtual async Task <CartAggregate> InnerAddLineItemAsync(LineItem lineItem, CartProduct product = null, IList <DynamicPropertyValue> dynamicProperties = null)
        {
            var existingLineItem = LineItems.FirstOrDefault(li => li.ProductId == lineItem.ProductId);

            if (existingLineItem != null)
            {
                await InnerChangeItemQuantityAsync(existingLineItem, existingLineItem.Quantity + Math.Max(1, lineItem.Quantity), product);

                existingLineItem.FulfillmentCenterId   = lineItem.FulfillmentCenterId;
                existingLineItem.FulfillmentCenterName = lineItem.FulfillmentCenterName;

                lineItem = existingLineItem;
            }
            else
            {
                lineItem.Id = null;
                Cart.Items.Add(lineItem);
            }

            if (dynamicProperties != null)
            {
                await UpdateCartItemDynamicProperties(lineItem, dynamicProperties);
            }

            return(this);
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Gets the hash code
 /// </summary>
 /// <returns>Hash code</returns>
 public override int GetHashCode()
 {
     unchecked // Overflow is fine, just wrap
     {
         var hashCode = 41;
         // Suitable nullity checks etc, of course :)
         if (OrderSummary != null)
         {
             hashCode = hashCode * 59 + OrderSummary.GetHashCode();
         }
         if (Membership != null)
         {
             hashCode = hashCode * 59 + Membership.GetHashCode();
         }
         if (LineItems != null)
         {
             hashCode = hashCode * 59 + LineItems.GetHashCode();
         }
         if (Addresses != null)
         {
             hashCode = hashCode * 59 + Addresses.GetHashCode();
         }
         return(hashCode);
     }
 }
Ejemplo n.º 4
0
        public ILineItem LineItemByCode(string code)
        {
            var lineItem = LineItems.FirstOrDefault(x =>
                                                    x.Code.Equals(code, StringComparison.OrdinalIgnoreCase));

            return(lineItem);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Add InvoiceLine By InvoiceLine
        /// </summary>
        /// <param name="invoiceLine"></param>
        /// <returns></returns>
        public bool AddInvoiceLine(InvoiceLine invoiceLine)
        {
            if (invoiceLine == null)
            {
                //empty item
                new LogManager().Log($"Fail to add invoice line (NULL) to invoice(Id: {InvoiceNumber})");
                return(false);
            }
            if (LineItems == null)
            {
                LineItems = new List <InvoiceLine>();
            }

            if (!LineItems.Any(i => i.InvoiceLineId == invoiceLine.InvoiceLineId))
            {
                //add
                LineItems.Add(invoiceLine);
                new LogManager().Log($"Add invoice line (Id: {invoiceLine.InvoiceLineId}) to invoice (Id: {InvoiceNumber})");
                return(true);
            }
            else
            {
                //update
                var existingItem = LineItems.Where(i => i.InvoiceLineId == invoiceLine.InvoiceLineId).First();
                LineItems.Remove(existingItem);
                LineItems.Add(invoiceLine);
                new LogManager().Log($"Update invoice line (Id: {invoiceLine.InvoiceLineId}) to invoice (Id: {InvoiceNumber})");
                return(false);
            }
        }
Ejemplo n.º 6
0
        internal void UpdateItems(Order order, LineItems lineItems)
        {
            var delList = GetDeletedList <LineItem>(lineItems);

            foreach (var item in delList)
            {
                MockDb.LineItems.Remove(MockDb.LineItems.Where(r => r.Id == item.Id).First());
            }
            delList.Clear();

            foreach (var item in lineItems)
            {
                if (item.IsNew)
                {
                    var data = new LineItemData {
                        OrderId = order.Id, Id = item.Id, Name = item.Name
                    };
                    MockDb.LineItems.Add(data);
                }
                else
                {
                    var data = MockDb.LineItems.Where(r => r.Id == item.Id).First();
                    data.Name = item.Name;
                }
                MarkOld(item);
            }
        }
        private void PlaceOrder()
        {
            Order order = new Order()
            {
                ID          = Guid.NewGuid().ToString(),
                UserID      = CustomerId,
                BreweryID   = BreweryId,
                Date        = DateTime.Now,
                TableNumber = CustomerCartMenu.TableNumber,
                LineItems   = new List <LineItems>(),
                TotalPrice  = (Beers.Count * 4).ToString()
            };

            foreach (var beer in CustomerCartMenu.Beers)
            {
                //Dictionary<string,object> orderItems = new Dictionary<string, object>();
                LineItems lineItem = new LineItems()
                {
                    ID      = Guid.NewGuid().ToString(),
                    OrderID = order.ID,
                    BeerID  = beer.ID,
                };
                // orderItems["customerId"] = CustomerId;
                // orderItems["tableNumber"] = CustomerCartMenu.TableNumber;
                // orderItems["breweryId"] = BreweryId;
                // orderItems["orderId"] = order.ID;
                // orderItems["beerId"] = beer.ID;
                order.LineItems.Add(lineItem);

                //DecrementKeg(beer);
            }
            customerService.PlaceOrder(order);
            CustomerCartMenu.Beers.Clear();
        }
Ejemplo n.º 8
0
 public OrderDto(Order order)
 {
     OrderId         = order.OrderId;
     UserId          = order.UserId;
     StreetAddress   = order.StreetAddress;
     UnitDesignation = order.UnitDesignation;
     City            = order.City;
     Province        = order.Province;
     PostalCode      = order.PostalCode;
     Country         = order.Country;
     TaxEstimate     = order.TaxEstimate;
     ServiceFee      = order.ServiceFee;
     DriverTip       = order.DriverTip;
     TotalEstimate   = order.TotalEstimate;
     TotalExact      = order.TotalExact;
     CreatedDate     = order.CreatedDate;
     AcceptedById    = order.AcceptedById;
     AcceptedDate    = order.AcceptedDate;
     ApprovedDate    = order.ApprovedDate;
     CompletedDate   = order.CompletedDate;
     foreach (LineItem item in order.LineItems)
     {
         LineItems.Add(new LineItemDto(item));
     }
     foreach (OrderNote note in order.OrderNotes)
     {
         OrderNotes.Add(new OrderNoteDto(note));
     }
 }
Ejemplo n.º 9
0
 public void RemoveLineItem(LineItem li)
 {
     if (LineItems != null)
     {
         LineItems.Remove(li);
     }
 }
Ejemplo n.º 10
0
 /// <summary>
 /// Validates that the order does not have a duplicate product ID in the line items. Throws
 /// an exception if it does.
 /// </summary>
 /// <param name="productId"></param>
 private void ValidateNotDuplicateProductId(int productId)
 {
     if (LineItems.Any(l => l.Key.Id == productId))
     {
         throw new BusinessOrderException($"[!] Duplicate product Id {productId}");
     }
 }
        /// <summary>
        /// Returns the string presentation of the object
        /// </summary>
        /// <returns>String presentation of the object</returns>
        public override string ToString()
        {
            var sb = new StringBuilder();

            sb.Append("class CreatePaymentLinkRequest {\n");
            sb.Append("  AllowedPaymentMethods: ").Append(AllowedPaymentMethods.ToListString()).Append("\n");
            sb.Append("  Amount: ").Append(Amount).Append("\n");
            sb.Append("  ApplicationInfo: ").Append(ApplicationInfo).Append("\n");
            sb.Append("  BillingAddress: ").Append(BillingAddress).Append("\n");
            sb.Append("  BlockedPaymentMethods: ").Append(BlockedPaymentMethods).Append("\n");
            sb.Append("  CountryCode: ").Append(CountryCode).Append("\n");
            sb.Append("  DeliverAt: ").Append(DeliverAt).Append("\n");
            sb.Append("  DeliveryAddress: ").Append(DeliveryAddress).Append("\n");
            sb.Append("  Description: ").Append(Description).Append("\n");
            sb.Append("  ExpiresAt: ").Append(ExpiresAt).Append("\n");
            sb.Append("  InstallmentOptions: ").Append(InstallmentOptions.ToCollectionsString()).Append("\n");
            sb.Append("  LineItems: ").Append(LineItems.ObjectListToString()).Append("\n");
            sb.Append("  MerchantAccount: ").Append(MerchantAccount).Append("\n");
            sb.Append("  MerchantOrderReference: ").Append(MerchantOrderReference).Append("\n");
            sb.Append("  Metadata: ").Append(Metadata.ToCollectionsString()).Append("\n");
            sb.Append("  RecurringProcessingModel: ").Append(RecurringProcessingModel).Append("\n");
            sb.Append("  Reference: ").Append(Reference).Append("\n");
            sb.Append("  ReturnUrl: ").Append(ReturnUrl).Append("\n");
            sb.Append("  Reusable: ").Append(Reusable).Append("\n");
            sb.Append("  RiskData: ").Append(RiskData).Append("\n");
            sb.Append("  ShopperEmail: ").Append(ShopperEmail).Append("\n");
            sb.Append("  ShopperLocale: ").Append(ShopperLocale).Append("\n");
            sb.Append("  ShopperName: ").Append(ShopperName).Append("\n");
            sb.Append("  ShopperReference: ").Append(ShopperReference).Append("\n");
            sb.Append("  Splits: ").Append(Splits.ObjectListToString()).Append("\n");
            sb.Append("  Store: ").Append(Store).Append("\n");
            sb.Append("  StorePaymentMethod: ").Append(StorePaymentMethod).Append("\n");
            sb.Append("}\n");
            return(sb.ToString());
        }
 public bool IsItemInCategory(string categoryId, string[] excludingCategoryIds, string[] excludingProductIds)
 {
     return(LineItems.InCategories(new[] { categoryId })
            .ExcludeCategories(excludingCategoryIds)
            .ExcludeProducts(excludingProductIds)
            .Any());
 }
Ejemplo n.º 13
0
        public IActionResult CreateNewOrder(int UserId, LineItems lineItemToAdd)
        {
            var findUser = _userRepository.GetUserById(UserId);

            if (findUser == null)
            {
                return(NotFound("This user could not be found."));
            }
            var       hasCart   = _repository.FindOpenCarts(UserId);
            var       totalCost = lineItemToAdd.Price * lineItemToAdd.Quantity;
            OrderCart cart;

            if (hasCart != null)
            {
                cart = _repository.AddToExistingCart(hasCart.InvoiceId, totalCost);
            }
            else
            {
                cart = _repository.StartNewOrder(UserId, totalCost);
            }
            lineItemToAdd.InvoiceId = cart.InvoiceId;
            var newLineItem = _repository.AddLineItem(lineItemToAdd);

            if (newLineItem == null)
            {
                return(NotFound("There was an error adding this item to your cart. Please try again."));
            }
            return(Created("", cart));
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Returns true if PartnerOrder instances are equal
        /// </summary>
        /// <param name="other">Instance of PartnerOrder to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(PartnerOrder other)
        {
            if (ReferenceEquals(null, other))
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return
                ((
                     OrderSummary == other.OrderSummary ||
                     OrderSummary != null &&
                     OrderSummary.Equals(other.OrderSummary)
                     ) &&
                 (
                     Membership == other.Membership ||
                     Membership != null &&
                     Membership.Equals(other.Membership)
                 ) &&
                 (
                     LineItems == other.LineItems ||
                     LineItems != null &&
                     LineItems.SequenceEqual(other.LineItems)
                 ) &&
                 (
                     Addresses == other.Addresses ||
                     Addresses != null &&
                     Addresses.SequenceEqual(other.Addresses)
                 ));
        }
Ejemplo n.º 15
0
        public async Task <LineItems> AddLineItem(LineItems lineItem)
        {
            var result = await halloweenDBContext.LineItems.AddAsync(lineItem);

            await halloweenDBContext.SaveChangesAsync();

            return(result.Entity);
        }
Ejemplo n.º 16
0
        public double GetTotalAmountAfterDiscounts()
        {
            var cartTotal = LineItems.Sum(a => a.Product.UnitPrice * a.Quantity);

            var discountTotal = GetCampaignDiscount() + GetCouponDiscount();

            return(cartTotal - discountTotal);
        }
        public decimal GetItemsOfProductQuantity(string productId, string[] excludingSkuIds)
        {
            var retVal = LineItems.InProducts(new[] { productId })
                         .ExcludeSkus(excludingSkuIds)
                         .Sum(x => x.Quantity);

            return(retVal);
        }
Ejemplo n.º 18
0
 /// <summary>
 /// Marks current instance as new which will cause new record to be created in the database for the specified object.
 /// This is useful for creating duplicates of existing objects.
 /// </summary>
 internal override void MarkNew()
 {
     base.MarkNew();
     Shipments.MarkNew();
     Payments.MarkNew();
     LineItems.MarkNew();
     Discounts.MarkNew();
 }
Ejemplo n.º 19
0
 public void AddLineItem(LineItem li)
 {
     if (LineItems == null)
     {
         LineItems = new ObservableCollection <LineItem>();
     }
     LineItems.Add(li);
 }
Ejemplo n.º 20
0
        public void Remove(string lineItemId)
        {
            var lineItem = LineItems.FirstOrDefault(li => li.Id == lineItemId);

            if (lineItem != null)
            {
                LineItems.Remove(lineItem);
            }
        }
Ejemplo n.º 21
0
 public bool IsValidForSubmit() =>
 AccountId > 0 &&
 Currency.HasValue(3) &&
 Tax > 0 && Tax < 1 &&
 LineItems.HasAny() &&
 Price > 0 &&
 ShippingInfo.IsValid() &&
 PaymentInfo.IsValid() &&
 LineItems.Count > 0;
Ejemplo n.º 22
0
        public void RemoveProduct(int productId)
        {
            var item = LineItems.FirstOrDefault(x => x.ProductId == productId);

            if (item != null)
            {
                LineItems.Remove(item);
            }
        }
Ejemplo n.º 23
0
        public void AddLineItem(PurchaseOrderLineItem item)
        {
            if (!IsInBudget(item))
            {
                throw new InvalidOperationException("Item exceeds budget");
            }

            LineItems.Add(item);
        }
        public decimal GetItemsQuantity(string[] excludingCategoryIds, string[] excludingProductIds, string[] excludingSkuIds)
        {
            var retVal = LineItems.ExcludeCategories(excludingCategoryIds)
                         .ExcludeProducts(excludingProductIds)
                         .ExcludeSkus(excludingSkuIds)
                         .Sum(x => x.Quantity);

            return(retVal);
        }
Ejemplo n.º 25
0
        public void AddLineItem(LineItem lineItem)
        {
            if (LineItems.Contains(lineItem))
            {
                throw new ArgumentException("Line item already added");
            }

            LineItems.Add(lineItem);
        }
        public decimal GetTotalWithExcludings(string[] excludingCategoryIds, string[] excludingProductIds, string[] excludingSkuIds)
        {
            var retVal = LineItems.ExcludeCategories(excludingCategoryIds)
                         .ExcludeProducts(excludingProductIds)
                         .ExcludeSkus(excludingSkuIds)
                         .Sum(x => x.CostPerEntry * x.Quantity);

            return(retVal);
        }
Ejemplo n.º 27
0
        public void Validate(Validations validationType = Validations.Weak)
        {
            InputValidators.ValidateValuedString(FulfillmentId, "Fulfillment Id");
            InputValidators.ValidateDateNotDefault(CreatedAt.GetValueOrDefault(), "Created At");
            InputValidators.ValidateObjectNotNull(Status, "Status");


            LineItems?.ToList().ForEach(item => item.Validate(validationType));
        }
Ejemplo n.º 28
0
 public override string ToString()
 {
     return
         (string.Format(
              "{0}[{11}]{0} {0} BusinessProcessName: {1}{0} BusinessPartnerCode: {2}{0} CustomerBankDescription: {11}{0} RequestDate: {3}{0} CustomerPO: {4}{0} Customer: {5}{0} "
              + "ShipToAddress: {14}{0} LineItems: {6}{0} ControlNumber: {7}{0} DocumentID: {8}{0} Location: {12}{0} Warehouse: {9}{0} PhoneNumber: {10}{0} CustomerBankDescription {13}{0}",
              Environment.NewLine, BusinessProcessName, BusinessPartnerCode, RequestDate, CustomerPO, Customer,
              LineItems.PrintAll(), ControlNumber, DocumentId, SpecificLocationNumber, PhoneNumber, GetType().Name, GeographicLocation,
              CustomerBankDescription, ShipToAddress));
 }
Ejemplo n.º 29
0
        public bool Equals(FinancialResultCategory other)
        {
            if (other == null)
            {
                return(false);
            }

            return(LineItems.SequenceEqual(other.LineItems) &&
                   Title.Equals(other.Title, StringComparison.InvariantCultureIgnoreCase));
        }
Ejemplo n.º 30
0
        public void AddingOneLineItemGetsCountofone()
        {
            LineItems li = new LineItems();

            SingleLineItem sli = new SingleLineItem();

            li.Add(sli);

            Assert.Equal(1, li.Count);
        }
Ejemplo n.º 31
0
    internal void UpdateItems(Order order, LineItems lineItems)
    {
      var delList = GetDeletedList<LineItem>(lineItems);
      foreach (var item in delList)
        MockDb.LineItems.Remove(MockDb.LineItems.Where(r => r.Id == item.Id).First());
      delList.Clear();

      foreach (var item in lineItems)
      {
        if (item.IsNew)
        {
          var data = new LineItemData { OrderId = order.Id, Id = item.Id, Name = item.Name };
          MockDb.LineItems.Add(data);
        }
        else
        {
          var data = MockDb.LineItems.Where(r => r.Id == item.Id).First();
          data.Name = item.Name;
        }
        MarkOld(item);
      }
    }
Ejemplo n.º 32
0
        private bool CreateXeroInvoice()
        {
            bool invoiceCreated = false;

            Invoice invoice = new Invoice();
            invoice.Type = "ACCREC";
            //invoice.Contact = new Contact { Name = ds.Tables[0].Rows[0]["XeroName"].ToString() };
            invoice.Date = DateTime.Today;
            invoice.DueDate = DateTime.Today.AddDays(30);
            invoice.Status = "DRAFT";
            invoice.TotalTax = 0;
            invoice.HasAttachments = true;
            invoice.LineAmountTypes = XeroApi.Model.LineAmountType.Inclusive;
            //invoice.Reference = ds.Tables[0].Rows[0]["Property"].ToString();
            LineItems lineitems = new LineItems();
            invoice.LineItems = new XeroApi.Model.LineItems();
            //for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
            //{
            //    if (ds.Tables[0].Rows[j]["CreateInvoice"].ToString() == "True")
            //    {
            //        ds.Tables[1].DefaultView.RowFilter = "OrderId='" + ds.Tables[0].Rows[j]["OrderId"].ToString() + "'";
            //        for (int i = 0; i < ds.Tables[1].DefaultView.Count; i++)
            //        {

            //            LineItem lineItem = new LineItem();
            //            lineItem.ItemCode = ds.Tables[1].DefaultView[i]["XeroCode"].ToString();
            //            lineItem.Description = ds.Tables[1].DefaultView[i]["XeroItemDescription"].ToString();
            //            lineItem.Quantity = 1;
            //            lineItem.UnitAmount = Convert.ToDecimal(ds.Tables[1].DefaultView[i]["Cost1"]);
            //            lineItem.TaxType = ds.Tables[1].DefaultView[i]["SalesTaxType"].ToString().Replace("GST on Income", "OUTPUT");
            //            lineItem.AccountCode = ds.Tables[1].DefaultView[i]["SalesAccountCode"].ToString();
            //            invoice.LineItems.Add(lineItem);
            //        }

            //    }

            //}

            //var inv = repository.Create<XeroApi.Model.Invoice>(invoice);

            return invoiceCreated;
        }
Ejemplo n.º 33
0
        public string ProcessData()
        {
            string strLog = "";
            XmlDocument xmlDoc = new XmlDocument();
            IOAuthSession session;
            DateTime DueDate = DateTime.Now;
            string strd;
            string Subject;
            string jpgfilename;
            Email.Email eml = new Email.Email();

            try
            {
                session = XeroAPI();
                Repository repository = new Repository(session);
                //OpreateData opftp = new OpreateData();
                //string strLogs = opftp.GetDataFromServer(ref connectionSuccess);//, ref index);
                HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
                DataSet dsProductNotification = new DataSet();
                String[] OrderId = null;
                foreach (string file in Directory.EnumerateFiles(FullPath, "*.htm"))
                {
                    filename = Path.GetFileName(file);
                    // filename = "201404161759591372889.htm";
                    htmlDoc.Load(file);
                    StartBrowser(htmlDoc.DocumentNode.OuterHtml);

                }

                // }
                foreach (string file in Directory.EnumerateFiles(FullPath, "*.htm"))
                {
                    int propertyId = 0;
                    string location=string.Empty;

                    filename = Path.GetFileName(file);
                    jpgfilename = filename.Replace("htm", "jpg");
                    // filename = "201404161759591372889.htm";
                    XmlNode rootElement = xmlDoc.CreateElement("Root");
                    xmlDoc.AppendChild(rootElement);
                    htmlDoc.Load(file);
                    htmlDoc.OptionWriteEmptyNodes = true;
                    htmlDoc.OptionOutputAsXml = true;
                    string value = "";
                    HtmlNodeCollection nodesitemheading = htmlDoc.DocumentNode.SelectNodes(".//b");
                    /*This is an order notification from Robin Parker at Marshall White Brighton<br />
                    <i>Relating to
                     campaign: 11 Lagnicourt Street, Hampton</i> */

                    String[] SplitValues = new String[1000];

                    XmlElement Element = xmlDoc.CreateElement("PrimaryContact");
                    try
                    {
                        SplitValues = Splits(sep(nodesitemheading[0].InnerText, "from "), new char[] { ' ' });
                    }
                    catch
                    {
                        File.Move(file, System.Configuration.ConfigurationSettings.AppSettings["Error"] + "\\" + filename);
                        File.Move(file.Replace("htm", "txt"), System.Configuration.ConfigurationSettings.AppSettings["Error"] + "\\" + filename.Replace("htm", "txt"));
                        xmlDoc.RemoveAll();
                        continue;
                    };

                    string cncl1 = "", cncl2 = "", cncl3 = "";

                    if (nodesitemheading[0].InnerText.Contains("The order listed below was cancelled by"))
                    {

                        IList<string> arrayAsList = (IList<string>)SplitValues;
                        int index;
                        index = arrayAsList.IndexOf("campaign:");
                        if (index == -1)
                            index = arrayAsList.IndexOf("\r\ncampaign:");
                        for (int i = index + 1; i < SplitValues.Length; i++)
                        {
                            if (SplitValues[i].Contains("of")) { break; };
                            cncl1 = cncl1 + " " + SplitValues[i];//email body subject
                            cncl1 = cncl1.Replace("Description", "").Replace("\r\n", "");
                        }

                        IList<string> arrayAsList1 = (IList<string>)SplitValues;
                        int index1 = arrayAsList.IndexOf("being");
                        for (int i = index1 + 2; i < SplitValues.Length; i++)
                        {
                            if (SplitValues[i].Contains("on")) { break; };
                            cncl2 = cncl2 + " " + SplitValues[i];//email body subject
                            cncl2 = cncl2.Replace("Required", "").Replace("\r\n", "");
                        }
                        IList<string> arrayAsList2 = (IList<string>)SplitValues;
                        int index2 = arrayAsList.IndexOf("on");
                        cncl3 = SplitValues[index2 + 1].Replace("Product", "");

                        InsertCancelledOrders(cncl1, cncl2, cncl3, filename);
                        File.Move(file, System.Configuration.ConfigurationSettings.AppSettings["Cancelled"] + "\\" + filename);
                        File.Move(file.Replace("htm", "txt"), System.Configuration.ConfigurationSettings.AppSettings["Cancelled"] + "\\" + filename.Replace("htm", "txt"));
                        xmlDoc.RemoveAll();
                        continue;
                    }

                    string str11 = "", str22 = "", str33 = "";
                    try
                    {
                        #region Fixed on 9 Oct 2014

                        if (SplitValues[3] == "at")
                        {
                            var midleName = SplitValues[1];
                            SplitValues = SplitValues.Where(x => x != midleName).ToArray();
                            var lastName = SplitValues[1];
                            SplitValues[1] = midleName + " " + lastName;
                        }

                        #endregion

                        str11 = SplitValues[0] + " " + SplitValues[1];//primary contact
                        str22 = SplitValues[3] + " " + SplitValues[4] + " " + SplitValues[5];//company name
                        str22 = str22.Replace("Relating", "");

                        //if (SplitValues[7].Contains("to"))
                        //{
                        //    str33 = "";
                        //    for (int i = 8; i < SplitValues.Length; i++)
                        //    {
                        //        str33 = str33 + " " + SplitValues[i];//email body subject
                        //    }
                        //}
                        //else
                        //    str33 = SplitValues[7] + " " + SplitValues[8] + " " + SplitValues[9] + " " + SplitValues[10] + SplitValues[11];//email body subject

                        IList<string> arrayAsList = (IList<string>)SplitValues;
                        int index;
                        index = arrayAsList.IndexOf("Relating".Replace("\r\n", ""));
                        if (index == -1)
                            index = arrayAsList.IndexOf("\r\ncampaign:");//campaign:
                        if (index == -1)
                            index = arrayAsList.IndexOf("campaign:");//campaign:

                        for (int i = index + 1; i < SplitValues.Length; i++)
                        {
                            if (SplitValues[i].Contains("of")) { break; };
                            str33 = str33 + " " + SplitValues[i];//email body subject
                            str33 = str33.Replace("Description", "").Replace("\r\n", "");
                        }

                        //if (SplitValues[7].Contains("Relating"))
                        //{
                        //    str33 = "";
                        //    for (int i = 10; i < SplitValues.Length; i++)
                        //    {
                        //        str33 = str33 + " " + SplitValues[i];//email body subject
                        //    }
                        //}
                    }
                    catch
                    {
                        File.Move(file, System.Configuration.ConfigurationSettings.AppSettings["Error"] + "\\" + filename);
                        File.Move(file.Replace("htm", "txt"), System.Configuration.ConfigurationSettings.AppSettings["Error"] + "\\" + filename.Replace("htm", "txt"));
                        xmlDoc.RemoveAll();
                        continue;
                    };
                    XmlElement PrimaryContactElement = xmlDoc.CreateElement("PrimaryContact");
                    PrimaryContactElement.InnerText = str11;
                    rootElement.AppendChild(PrimaryContactElement);

                    XmlElement CompanyNameElement = xmlDoc.CreateElement("CompanyName");
                    CompanyNameElement.InnerText = str22;
                    rootElement.AppendChild(CompanyNameElement);

                    XmlElement EmailBodySubjectElement = xmlDoc.CreateElement("EmailBodySubject");
                    EmailBodySubjectElement.InnerText = nodesitemheading[0].InnerText;
                    rootElement.AppendChild(EmailBodySubjectElement);

                    XmlElement PropertyNameElement = xmlDoc.CreateElement("PropertyName");
                    str33 = str33.Replace("campaign:", "");
                    PropertyNameElement.InnerText = str33;
                    rootElement.AppendChild(PropertyNameElement);
                    location = str33;

                    XmlElement FileNameElement = xmlDoc.CreateElement("FileName");
                    FileNameElement.InnerText = Path.GetFileName(file);
                    rootElement.AppendChild(FileNameElement);
                    string strfile = file.Replace("htm", "txt");
                    string[] lines = File.ReadAllLines(strfile);

                    string From = lines[0].ToString().Replace("From:", "");
                    XmlElement FromElement = xmlDoc.CreateElement("From");
                    FromElement.InnerText = From;
                    rootElement.AppendChild(FromElement);

                    string SentDate = lines[1].ToString().Replace("SentDate:", "");
                    XmlElement SentDateElement = xmlDoc.CreateElement("SentDate");
                    //DateTime objSentDate = Convert.ToDateTime(SentDate,CultureInfo.CreateSpecificCulture("en-US"));
                    DateTime objSentDate = DateTime.Parse(SentDate, CultureInfo.GetCultureInfo("en-gb"));
                    SentDateElement.InnerText = objSentDate.Month.ToString().PadLeft(2, '0') + "/" + objSentDate.Day.ToString().PadLeft(2, '0') + "/" + objSentDate.Year + " " + objSentDate.ToLongTimeString();
                    rootElement.AppendChild(SentDateElement);

                    Subject = lines[2].ToString().Replace("Subject:", "");
                    XmlElement SubjectElement = xmlDoc.CreateElement("Subject");
                    SubjectElement.InnerText = Subject;
                    rootElement.AppendChild(SubjectElement);

                    HtmlNodeCollection nodesitemcontacts = htmlDoc.DocumentNode.SelectNodes(".//td[@class='content']");
                    //htmlDoc.DocumentNode.SelectNodes(".//td[@class='content']")[0].ChildNodes
                    foreach (HtmlNode childNode in nodesitemcontacts)
                    {
                        if (childNode.ChildNodes.Count > 0)
                        {
                            foreach (HtmlNode childOfChildNode in childNode.ChildNodes)
                            {
                                if (childOfChildNode.Name == "#text")
                                {
                                    if (childOfChildNode.ChildNodes.Count == 0)
                                    {

                                        if (childOfChildNode.InnerText.Trim().Contains("Property ID") || childOfChildNode.InnerText.Trim().Contains("Property"))
                                        {
                                            //MessageBox.Show(childOfChildofChildNode.InnerText.Trim().Replace("Property ID:", ""));//Property Id
                                            XmlElement PropertyIdElement = xmlDoc.CreateElement("PropertyId");

                                            PropertyIdElement.InnerText = childOfChildNode.InnerText.Trim().Replace("Property ID:", "").Replace("\r\n", "").Replace("Property ID:", "");
                                            rootElement.AppendChild(PropertyIdElement);
                                            try
                                            {
                                                propertyId = int.Parse(PropertyIdElement.InnerText);
                                            }
                                            catch
                                            { }

                                        }

                                        if (childOfChildNode.InnerText.Trim().Contains("OrderItem"))
                                        {
                                            // MessageBox.Show(childOfChildofChildNode.InnerText.Trim().Replace("OrderItem:", ""));
                                            String[] SplitValue = Splits(childOfChildNode.InnerText.Trim().Replace("OrderItem:", ""), new char[] { ',' });//Order Item Id
                                            OrderId = SplitValue;
                                            SplitValueOrderItemId = Splits(childOfChildNode.InnerText.Trim().Replace("OrderItem:", ""), new char[] { ',' });
                                            XmlElement OrderItemIdElement = xmlDoc.CreateElement("OrderItemId");
                                            for (int i = 0; i < SplitValue.Length; i++)
                                            {
                                                string str = SplitValue[i];
                                                XmlElement IdElement = xmlDoc.CreateElement("Id");
                                                IdElement.InnerText = str.Trim();
                                                OrderItemIdElement.AppendChild(IdElement);
                                            }
                                            rootElement.AppendChild(OrderItemIdElement);
                                        }

                                        if (childOfChildNode.InnerText.Trim().Contains("Sales contacts"))
                                        {
                                            // MessageBox.Show(childOfChildofChildNode.InnerText.Trim().Replace("Sales contacts:", ""), "8");
                                            String[] SplitValue = Splits(childOfChildNode.InnerText.Trim().Replace("Sales contacts:", ""), new char[] { ',' });
                                            for (int i = 0; i < SplitValue.Length; i++)
                                            {
                                                string str = (SplitValue[i].Replace(" on ", ",").Replace("\r\non", ","));
                                                String[] strValue = Splits(str, new char[] { ',' });

                                                string str1 = strValue[0];//Sales contact name
                                                string str2 = strValue[1].Replace("or", "");//Sales contact phone number

                                                XmlElement SalesContactElement = xmlDoc.CreateElement("SalesContact");
                                                SalesContactElement.InnerText = str1.Trim(); ;
                                                rootElement.AppendChild(SalesContactElement);

                                                XmlElement SalesContactNumberElement = xmlDoc.CreateElement("SalesContactNumber");
                                                SalesContactNumberElement.InnerText = str2.Trim();
                                                rootElement.AppendChild(SalesContactNumberElement);

                                            }

                                            HtmlNodeCollection adminemail = htmlDoc.DocumentNode.SelectNodes(".//a[@href]");
                                            string stradmin = adminemail[1].InnerText;//Admin email address

                                        }

                                        if (childOfChildNode.InnerText.Trim().Contains("Admin contact"))
                                        {
                                            // MessageBox.Show(childOfChildofChildNode.InnerText.Trim(), "9");
                                            // String[] SplitValue = Splits(childOfChildNode.InnerText.Trim().Replace("Admin contact:", "").Replace(" on", ","), new char[] { ',' });
                                            String[] SplitValue = Splits(childOfChildNode.InnerText.Trim().Replace("Admin contact:", "").Replace(" on", ","), "or".ToCharArray());

                                            string admindetails = childOfChildNode.InnerText.Trim().Replace("Admin contact:", "");//Admin contact name
                                            string str1;
                                            try
                                            {
                                                // bool string1Matched = Regex.IsMatch(string1, @"\bthe\b", RegexOptions.IgnoreCase);
                                                str1 = admindetails.Substring(0, admindetails.IndexOf(" or "));
                                                str1 = str1.Substring(0, str1.IndexOf(" on "));//Admin name
                                                string str2;
                                                str2 = admindetails.Substring(0, admindetails.IndexOf(" or "));
                                                str2 = str2.Substring(str2.LastIndexOf(" on ") + 3);//Admin Phone

                                                string str3 = "";
                                                str3 = admindetails.Substring(admindetails.IndexOf(" or ") + 4);
                                                XmlElement AdminContactElement = xmlDoc.CreateElement("AdminContact");
                                                AdminContactElement.InnerText = str1.Trim();
                                                rootElement.AppendChild(AdminContactElement);

                                                XmlElement AdminContactNumberElement = xmlDoc.CreateElement("AdminContactNumber");
                                                AdminContactNumberElement.InnerText = str2.Trim();
                                                rootElement.AppendChild(AdminContactNumberElement);

                                                XmlElement AdminContactEmailElement = xmlDoc.CreateElement("AdminContactEmail");
                                                AdminContactEmailElement.InnerText = str3.Trim();
                                                rootElement.AppendChild(AdminContactEmailElement);
                                            }
                                            catch (Exception ex)
                                            {
                                                strLog = ex.StackTrace.ToString();
                                                WriteLog(strLog + " " + filename);
                                            }

                                        }

                                        if (childOfChildNode.InnerText.Trim().Contains("Supplier:"))
                                        {
                                            //MessageBox.Show(childOfChildofChildNode.InnerText.Trim(), "10");
                                            string str1 = childOfChildNode.InnerText.Replace("Supplier:", "");//Product

                                            XmlElement SupplierElement = xmlDoc.CreateElement("Supplier");
                                            SupplierElement.InnerText = str1.Trim();
                                            rootElement.AppendChild(SupplierElement);
                                        }

                                        if (childOfChildNode.InnerText.Trim().Contains("Description of product/service being ordered:"))
                                        {
                                            value = "Description of product";
                                            continue;
                                        }

                                        if (value == "Description of product")
                                        {
                                            //MessageBox.Show(childOfChildofChildNode.InnerText.Trim(), "11");
                                            string str = childOfChildNode.InnerText.Replace("Description of product/service being ordered: ", "");//Product Description
                                            value = "";

                                            XmlElement DescriptionElement = xmlDoc.CreateElement("Description");
                                            DescriptionElement.InnerText = str.Trim();
                                            rootElement.AppendChild(DescriptionElement);
                                        }

                                        if (childOfChildNode.InnerText.Trim().Contains("Required"))
                                        {
                                            // MessageBox.Show(childOfChildofChildNode.InnerText.Trim(), "12");

                                            string RequiredDate = childOfChildNode.InnerText.Replace("Required on", "").Replace("Required \r\non", "").Replace("\r\n", "");//Required Date
                                            DateTime objRequiredDate = DateTime.Parse(RequiredDate, CultureInfo.GetCultureInfo("en-gb"));
                                            XmlElement RequiredDateElement = xmlDoc.CreateElement("RequiredDate");
                                            // RequiredDateElement.InnerText = objRequiredDate.Month.ToString().PadLeft(2, '0') + "-" + objRequiredDate.Day.ToString().PadLeft(2, '0') + "-" + objRequiredDate.Year;
                                            RequiredDateElement.InnerText = objRequiredDate.ToShortDateString();
                                            rootElement.AppendChild(RequiredDateElement);
                                            DueDate = Convert.ToDateTime(objRequiredDate.ToShortDateString());
                                            //DueDate = DateTime.Parse(RequiredDate, "dd/MM/yyyy").ToString("MM/dd/yyyy");
                                        }

                                        if (value == "PROPERTY")
                                        {
                                            //    MessageBox.Show(childOfChildofChildNode.InnerText, "2");//Property Comments

                                            XmlElement PropertyDetailsElement = xmlDoc.CreateElement("PropertyDetails");
                                            PropertyDetailsElement.InnerText = childOfChildNode.InnerText;
                                            rootElement.AppendChild(PropertyDetailsElement);

                                            HtmlNodeCollection propertycomments = htmlDoc.DocumentNode.SelectNodes(".//i");
                                            string str = propertycomments[1].InnerText;//Property Comments
                                            value = "";

                                            XmlElement PropertyCommentsElement = xmlDoc.CreateElement("PropertyComments");
                                            PropertyCommentsElement.InnerText = str.Trim();
                                            rootElement.AppendChild(PropertyCommentsElement);

                                        }
                                        if (childOfChildNode.InnerText.Trim() == "PROPERTY")
                                        {
                                            value = "PROPERTY";
                                            continue;
                                        }

                                        //}
                                        // }

                                    }
                                }
                            }
                        }
                    }

                    HtmlNodeCollection Nds = htmlDoc.DocumentNode.SelectNodes(".//table[@cellpadding='3']");
                    int cnt = 1;

                    if (Nds == null)
                    {
                        if (Subject.Contains("cancellation"))
                        {
                            File.Move(file, System.Configuration.ConfigurationSettings.AppSettings["Cancelled"] + "\\" + filename);
                            File.Move(file.Replace("htm", "txt"), System.Configuration.ConfigurationSettings.AppSettings["Cancelled"] + "\\" + filename.Replace("htm", "txt"));

                        }
                    };

                    if (Nds != null)
                    {
                        foreach (HtmlNode childNds in Nds)
                        {

                            if (childNds.ChildNodes.Count > 0)
                            {
                                if (childNds.InnerText.Contains("This is an order"))
                                {
                                    continue;

                                }
                                else
                                {
                                    if (childNds.ChildNodes.Count > 0)
                                    {

                                        foreach (HtmlNode childofChildNds in childNds.ChildNodes)
                                        {
                                            XmlElement OrderItemDetailsElement = xmlDoc.CreateElement("OrderItemDetails");
                                            if (childofChildNds.InnerText.Trim() != "" && childofChildNds.InnerText.Contains("Client PriceCost") == false && childofChildNds.InnerText.Contains("Client \r\nPriceCost") == false && childofChildNds.InnerText.Trim() != "campaigntrack.com.auhelpdesk")
                                            {
                                                string str = childofChildNds.InnerText;
                                                str = str.Replace("$", "|");

                                                String[] SplitValue = Splits(str, new char[] { '|' });
                                                string str1 = SplitValue[0].ToString().Trim();
                                                string str2 = SplitValue[1].ToString().Trim();
                                                string str3 = SplitValue[2].ToString().Trim();
                                                //MessageBox.Show(str1 + ' ' + str2 + ' ' + str3);

                                                //for (int i = 1; i < SplitValue.Length; i++)
                                                //{
                                                //    if (i != 4 && i != 10 && i != 16) { continue; }
                                                //    if (str1 == "   " || str2 == "   " || str3 == "   ") { continue; }
                                                //    string str = SplitValue[i];
                                                //    XmlElement IdElement = xmlDoc.CreateElement("n");
                                                //    //cnt = cnt + 1;
                                                //    IdElement.InnerText = cnt.ToString() + "_" + str1 + "|" + str2 + "|" + str3;
                                                //    OrderItemDetailsElement.AppendChild(IdElement);
                                                //}
                                                if (str1 != "" || str2 != "" || str3 != "")
                                                {
                                                    XmlElement IdElement = xmlDoc.CreateElement("n");
                                                    IdElement.InnerText = cnt.ToString() + "_" + str1 + "|" + str2 + "|" + str3;
                                                    OrderItemDetailsElement.AppendChild(IdElement);
                                                    rootElement.AppendChild(OrderItemDetailsElement);
                                                }

                                                //dsProductNotification = ProductEmailNotification(str1);
                                                //if (dsProductNotification.Tables[0].Rows.Count > 0)
                                                //{

                                                //    //(String subject,String Message,string To,string CC, bool hasattachment)
                                                //    //   eml.SendMail("", "", dsProductNotification.Tables[0].Rows[0]["EmailTo"].ToString(), dsProductNotification.Tables[0].Rows[0]["EmailCC"].ToString(), false);

                                                //}
                                            }

                                        }
                                        { cnt = cnt + 1; }
                                    }

                                }

                            }
                        }
                    }
                    strd = xmlDoc.InnerXml.ToString();
                    strd = strd.Replace("&amp;", "and").Replace("andamp;", " and ");
                    strd = strd.Replace("'", "''");
                    DataSet ds = new DataSet();
                    strd = strd.Replace("\r\n",string.Empty);
                    strd = strd.Replace(";", string.Empty);
                    ds = ExecuteProcess(strd);
                    xmlDoc.RemoveAll();
                    if (propertyId != 0 && !string.IsNullOrEmpty(location))
                    {
                        ProprtyCoordinates(propertyId, location);
                    }
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        for (int j = 0; j < ds.Tables[1].Rows.Count; j++)
                        {
                            dsProductNotification = ProductSchedule((int)ds.Tables[1].Rows[j]["Xero_Id"]);

                            if (dsProductNotification.Tables[0].Rows.Count > 0)
                            {
                                string productGroupName = string.Empty;
                                string productGroupId = string.Empty;
                                try
                                {
                                    if (dsProductNotification.Tables[0].Rows[dsProductNotification.Tables[0].Rows.Count - 1]["ProductGroupId"] != null)
                                    {
                                        productGroupId = dsProductNotification.Tables[0].Rows[dsProductNotification.Tables[0].Rows.Count - 1]["ProductGroupId"].ToString();
                                    }
                                    if (dsProductNotification.Tables[0].Rows[dsProductNotification.Tables[0].Rows.Count - 1]["ProductGroupName"] != null)
                                    {
                                        productGroupName = dsProductNotification.Tables[0].Rows[dsProductNotification.Tables[0].Rows.Count - 1]["ProductGroupName"].ToString();
                                    }
                                }
                                catch
                                {
                                    productGroupId = string.Empty;
                                    productGroupName = string.Empty;
                                }

                                //(String subject,String Message,string To,string CC, bool hasattachment)
                                //   eml.SendMail("", "", dsProductNotification.Tables[0].Rows[0]["EmailTo"].ToString(), dsProductNotification.Tables[0].Rows[0]["EmailCC"].ToString(), false);

                                if (dsProductNotification.Tables[0].Rows[dsProductNotification.Tables[0].Rows.Count - 1]["Value"].ToString().Contains("@"))
                                {
                                    // eml.SendMail(Subject, htmlDoc.DocumentNode.OuterHtml, dsProductNotification.Tables[0].Rows[0]["EmailTo"].ToString(), "", false);
                                    eml.SendMail(Subject, htmlDoc.DocumentNode.OuterHtml, "*****@*****.**", "", false);

                                }
                                else
                                {
                                    DataSet dsRecordtoProcess = new DataSet();
                                    DataTable dtRecordtoProcess = new DataTable();
                                    dsRecordtoProcess = ReturnDataforCalenderEntry(ds.Tables[1].Rows[j]["OrderId"].ToString());
                                    dtRecordtoProcess = dsRecordtoProcess.Tables[0];
                                    CampaignTrack_MailScarapper.GoogleService.IGoogleNotificationService client = (CampaignTrack_MailScarapper.GoogleService.IGoogleNotificationService)new CampaignTrack_MailScarapper.GoogleService.GoogleNotificationServiceClient();

                                    //GoogleCalSvc s = new GoogleCalSvc();
                                    if (dtRecordtoProcess.Rows.Count > 0)
                                    {
                                        for (int i = 0; i < dtRecordtoProcess.Rows.Count; i++)
                                        {
                                            //s.CreateEvent(dtRecordtoProcess.Rows[i]["Title"].ToString(), dtRecordtoProcess.Rows[i]["Location"].ToString(), dtRecordtoProcess.Rows[i]["SalesContact"].ToString(), dtRecordtoProcess.Rows[i]["Startdate"].ToString(), dtRecordtoProcess.Rows[i]["Enddate"].ToString(), dtRecordtoProcess.Rows[i]["Comments"].ToString(), dtRecordtoProcess.Rows[i]["ProductDescription"].ToString(), dtRecordtoProcess.Rows[i]["OrderId"].ToString(), dtRecordtoProcess.Rows[i]["RequiredDate"].ToString(), dtRecordtoProcess.Rows[i]["ColorId"].ToString());
                                            string orderItemDetails = string.Empty;
                                            if (!string.IsNullOrEmpty(productGroupId))
                                            {
                                                orderItemDetails = "Order Item (Please do not delete or update Order Item Id) :" + dtRecordtoProcess.Rows[i]["OrderId"].ToString() + ", " + productGroupId + "-" + productGroupName;
                                            }
                                            else
                                            {
                                                orderItemDetails = "Order Item (Please do not delete or update Order Item Id) :" + dtRecordtoProcess.Rows[i]["OrderId"].ToString();
                                            }
                                            //string description = "SalesContact : " + dtRecordtoProcess.Rows[i]["SalesContact"].ToString() + Environment.NewLine + Environment.NewLine + "Required On :" + Convert.ToDateTime(dtRecordtoProcess.Rows[i]["RequiredDate"].ToString()).ToShortDateString() + Environment.NewLine + Environment.NewLine + "Product Description :" + dtRecordtoProcess.Rows[i]["ProductDescription"].ToString() + Environment.NewLine + Environment.NewLine + "Supplier Instructions :" + dtRecordtoProcess.Rows[i]["Comments"].ToString().Replace("Supplier Instructions", "") + Environment.NewLine + Environment.NewLine + "Order Item (Please do not delete or update Order Item Id) :" + dtRecordtoProcess.Rows[i]["OrderId"].ToString() + ", " + productGroupId + "-" + productGroupName;
                                            string description = "SalesContact : " + dtRecordtoProcess.Rows[i]["SalesContact"].ToString() + Environment.NewLine + Environment.NewLine + "Required On :" + Convert.ToDateTime(dtRecordtoProcess.Rows[i]["RequiredDate"].ToString()).ToShortDateString() + Environment.NewLine + Environment.NewLine + "Product Description :" + dtRecordtoProcess.Rows[i]["ProductDescription"].ToString() + Environment.NewLine + Environment.NewLine + "Supplier Instructions :" + dtRecordtoProcess.Rows[i]["Comments"].ToString().Replace("Supplier Instructions", "") + Environment.NewLine + Environment.NewLine + orderItemDetails;
                                            //client.CreateEvent(dtRecordtoProcess.Rows[i]["Title"].ToString(), dtRecordtoProcess.Rows[i]["Location"].ToString(), dtRecordtoProcess.Rows[i]["SalesContact"].ToString(), Convert.ToDateTime(dtRecordtoProcess.Rows[i]["Startdate"].ToString()), Convert.ToDateTime(dtRecordtoProcess.Rows[i]["Enddate"].ToString()), dtRecordtoProcess.Rows[i]["Comments"].ToString(), dtRecordtoProcess.Rows[i]["ProductDescription"].ToString(), dtRecordtoProcess.Rows[i]["OrderId"].ToString(), dtRecordtoProcess.Rows[i]["RequiredDate"].ToString(), dtRecordtoProcess.Rows[i]["ColorId"].ToString(), "*****@*****.**", description, string.Empty, false);
                                            //  if (s.CheckedCalendarEvent == 0) { s.CheckedCalendarEvent = 1; }
                                            //UpdateOrderEvent((int)ds.Tables[1].Rows[j]["row_id1"]);//OrderId
                                            //  s.A1CreateEvent("*****@*****.**", "abc", "05-12-2013", "06-12-2013", "Test", "def", "ghi");
                                        }
                                    }
                                }
                            }
                            UpdateOrderEvent((int)ds.Tables[1].Rows[j]["row_id1"]);//OrderId
                        }

                        Invoice invoice = new Invoice();
                        invoice.Type = "ACCREC";
                        invoice.Contact = new Contact { Name = ds.Tables[0].Rows[0]["XeroName"].ToString() };
                        invoice.Date = DateTime.Today;
                        invoice.DueDate = DateTime.Today.AddDays(30);
                        invoice.Status = "DRAFT";
                        invoice.TotalTax = 0;
                        invoice.HasAttachments = true;
                        invoice.LineAmountTypes = XeroApi.Model.LineAmountType.Inclusive;
                        invoice.Reference = ds.Tables[0].Rows[0]["Property"].ToString();
                        LineItems lineitems = new LineItems();
                        invoice.LineItems = new XeroApi.Model.LineItems();
                        for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
                        {
                            if (ds.Tables[0].Rows[j]["CreateInvoice"].ToString() == "True")
                            {
                                ds.Tables[1].DefaultView.RowFilter = "OrderId='" + ds.Tables[0].Rows[j]["OrderId"].ToString() + "'";
                                for (int i = 0; i < ds.Tables[1].DefaultView.Count; i++)
                                {

                                    LineItem lineItem = new LineItem();
                                    lineItem.ItemCode = ds.Tables[1].DefaultView[i]["XeroCode"].ToString();
                                    lineItem.Description = ds.Tables[1].DefaultView[i]["XeroItemDescription"].ToString();
                                    lineItem.Quantity = 1;
                                    lineItem.UnitAmount = Convert.ToDecimal(ds.Tables[1].DefaultView[i]["Cost1"]);
                                    lineItem.TaxType = ds.Tables[1].DefaultView[i]["SalesTaxType"].ToString().Replace("GST on Income", "OUTPUT");
                                    lineItem.AccountCode = ds.Tables[1].DefaultView[i]["SalesAccountCode"].ToString();
                                    invoice.LineItems.Add(lineItem);
                                }

                            }

                        }

                        var inv = repository.Create<XeroApi.Model.Invoice>(invoice);
                        if (invoice.ValidationStatus == ValidationStatus.ERROR)
                        {
                            foreach (var message in invoice.ValidationErrors)
                            {
                            }
                        }
                        try
                        {
                            Guid invoiceId = inv.InvoiceID;
                            string invoiceNo = inv.InvoiceNumber;
                            // System.Threading.Thread.Sleep(5000);
                            string AnyAttachmentFilename = FullPath + "\\" + jpgfilename;
                            var SalesInvoice = repository.Invoices.FirstOrDefault(it => it.InvoiceID == invoiceId);
                            var newAttachment = repository.Attachments.Create(SalesInvoice, new FileInfo(AnyAttachmentFilename));
                            InsertPropertyInvoice((int)ds.Tables[1].Rows[0]["Property_Id"], invoiceNo);
                            ds.Tables[1].DefaultView.RowFilter = string.Empty;
                            System.Threading.Thread.Sleep(5000);
                        }
                        catch (Exception ex)
                        {
                            strLog = ex.StackTrace.ToString() + "~~~~~~~~~~~~Error~~~~~~~~~~~:" + ex.Message.ToString();
                            WriteLog(strLog + "For Filename :" + filename);
                            File.Move(System.Configuration.ConfigurationSettings.AppSettings["MailPath"] + filename, System.Configuration.ConfigurationSettings.AppSettings["Error"] + filename);
                            filename = filename.Replace("htm", "txt");
                            File.Move(System.Configuration.ConfigurationSettings.AppSettings["MailPath"] + filename, System.Configuration.ConfigurationSettings.AppSettings["Error"] + filename);
                        }
                        System.Threading.Thread.Sleep(5000);
                        System.IO.File.Move(System.Configuration.ConfigurationSettings.AppSettings["MailPath"] + filename, System.Configuration.ConfigurationSettings.AppSettings["Archive"] + filename);
                        //System.IO.File.Delete(System.Configuration.ConfigurationSettings.AppSettings["MailPath"] + "\\" + filename);
                        filename = filename.Replace("htm", "txt");
                        //if (System.IO.File.Exists(System.Configuration.ConfigurationSettings.AppSettings["MailPath"] + "\\" + filename))
                        //{ System.IO.File.Delete(System.Configuration.ConfigurationSettings.AppSettings["MailPath"] + "\\" + filename); }
                        //filename = filename.Replace("txt", "jpg");
                        //System.IO.File.Move(System.Configuration.ConfigurationSettings.AppSettings["MailPath"] + "\\" + filename, System.Configuration.ConfigurationSettings.AppSettings["MailPath"] + "\\Archive\\" + filename);

                    }
                    else
                    {
                        eml.SendMail("No Product Match..", "The file name is " + filename, "*****@*****.**", "", false);
                        File.Move(System.Configuration.ConfigurationSettings.AppSettings["MailPath"] + filename, System.Configuration.ConfigurationSettings.AppSettings["NoMatch"] + filename);
                        filename = filename.Replace("htm", "txt");
                        File.Move(System.Configuration.ConfigurationSettings.AppSettings["MailPath"] + filename, System.Configuration.ConfigurationSettings.AppSettings["NoMatch"] + filename);

                    };

                }
            }
            catch (Exception ex)
            {
                strLog = ex.StackTrace.ToString() + "~~~~~~~~~~~~Error~~~~~~~~~~~:" + ex.Message.ToString();
                //if (strLog.Contains("at Google.Apis.Requests.ClientServiceRequest") == false)
                //{
                    eml.SendMail("Error in parsing file..", "The file name is " + filename + ". Error :- " + strLog, "*****@*****.**", "", false);
                    WriteLog(strLog + "For Filename :" + filename);
                    File.Move(System.Configuration.ConfigurationSettings.AppSettings["MailPath"] + filename, System.Configuration.ConfigurationSettings.AppSettings["Error"] + filename);
                    filename = filename.Replace("htm", "txt");
                    File.Move(System.Configuration.ConfigurationSettings.AppSettings["MailPath"] + filename, System.Configuration.ConfigurationSettings.AppSettings["Error"] + filename);
                //}
            }

            return strLog;
        }
Ejemplo n.º 34
0
        private void AddItemsToXeroInvoice(string propertyAddress, List<int> xeroCodes, string companyName, Dictionary<int, XeroProductInfo> xeroProductCostDictionary)
        {
            //bool invoiceCreated = false;

            if (invoice == null)
            {
                invoice = new Invoice(); invoice.Type = "ACCREC";
                invoice.Contact = new Contact { Name = companyName.Trim() };
                invoice.Date = DateTime.Today;
                invoice.DueDate = DateTime.Today.AddDays(30);
                invoice.Status = "DRAFT";
                invoice.TotalTax = 0;
                invoice.HasAttachments = true;
                invoice.LineAmountTypes = XeroApi.Model.LineAmountType.Inclusive;
                invoice.Reference = propertyAddress.Trim();
                LineItems lineitems = new LineItems();
                invoice.LineItems = new XeroApi.Model.LineItems();
            }
            if (createInvoice)
            {
                for (int i = 0; i < xeroCodes.Count; i++)
                {
                    LineItem lineItem = new LineItem();
                    lineItem.ItemCode = xeroProductCostDictionary[xeroCodes[i]].Code;
                    lineItem.Description = xeroProductCostDictionary[xeroCodes[i]].Name;
                    lineItem.Quantity = xeroProductCostDictionary[xeroCodes[i]].Count;
                    lineItem.UnitAmount = Convert.ToDecimal(xeroProductCostDictionary[xeroCodes[i]].Cost);
                    lineItem.TaxType = xeroProductCostDictionary[xeroCodes[i]].SalesTaxType.Replace("GST on Income", "OUTPUT");
                    lineItem.AccountCode = xeroProductCostDictionary[xeroCodes[i]].SalesAccountCode;
                    invoice.LineItems.Add(lineItem);
                }
            }
        }
Ejemplo n.º 35
0
 public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(global::System.Xml.Schema.XmlSchemaSet xs) {
     LineItems ds = new LineItems();
     global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType();
     global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence();
     global::System.Xml.Schema.XmlSchemaAny any = new global::System.Xml.Schema.XmlSchemaAny();
     any.Namespace = ds.Namespace;
     sequence.Items.Add(any);
     type.Particle = sequence;
     global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable();
     if (xs.Contains(dsSchema.TargetNamespace)) {
         global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream();
         global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream();
         try {
             global::System.Xml.Schema.XmlSchema schema = null;
             dsSchema.Write(s1);
             for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) {
                 schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current));
                 s2.SetLength(0);
                 schema.Write(s2);
                 if ((s1.Length == s2.Length)) {
                     s1.Position = 0;
                     s2.Position = 0;
                     for (; ((s1.Position != s1.Length) 
                                 && (s1.ReadByte() == s2.ReadByte())); ) {
                         ;
                     }
                     if ((s1.Position == s1.Length)) {
                         return type;
                     }
                 }
             }
         }
         finally {
             if ((s1 != null)) {
                 s1.Close();
             }
             if ((s2 != null)) {
                 s2.Close();
             }
         }
     }
     xs.Add(dsSchema);
     return type;
 }