Exemplo n.º 1
0
        public void BuildExpression_ProperStack_ReturnsCorrectUnaryFilterExpression()
        {
            _baseStrategy
            .Stub(x => x.BuildExpression(null))
            .IgnoreArguments()
            .Return(FilterExpression.Constant(true));

            var stack = new Stack <Token>();

            stack.Push(new Token
            {
                TokenType = TokenType.Boolean,
                Value     = "true"
            });

            stack.Push(new Token
            {
                TokenType = TokenType.UnaryOperator,
                Value     = "not"
            });

            var expression = _unaryStrategy.BuildExpression(stack);

            Assert.That(expression, Is.TypeOf <UnaryFilterExpression>());
            Assert.That(expression.ExpressionType, Is.EqualTo(FilterExpressionType.Unary));
            Assert.That(((UnaryFilterExpression)expression).Operator, Is.EqualTo(FilterExpressionOperator.Not));
            Assert.That(((UnaryFilterExpression)expression).Operand, Is.TypeOf <ConstantFilterExpression>());
        }
Exemplo n.º 2
0
        public string countCustomers(string serverName, string databaseName)
        {
            CompanyIdentifier companyIdentifier = session.LookupCompanyIdentifier(serverName, databaseName);

            connectionStatus = session.RequestAccess(companyIdentifier);
            Console.WriteLine("Result {0}", connectionStatus.ToString());

            if (connectionStatus == AuthorizationResult.Granted)
            {
                Company company = session.Open(companyIdentifier);
                Console.WriteLine("Company {0}", company.CompanyIdentifier.CompanyName);
                var customers           = company.Factories.CustomerFactory.List();
                FilterExpression filter = FilterExpression.Equal(
                    FilterExpression.Property("Customer.IsInactive"),
                    FilterExpression.Constant(false));
                LoadModifiers modifiers = LoadModifiers.Create();
                modifiers.Filters = filter;
                customers.Load(modifiers);

                int count = customers.Count;
                session.Close(company);

                return("{\"count\":\"" + count + "\"}");
            }

            return("{\"error\":\"Access: " + connectionStatus.ToString() + "\"}");
        }
Exemplo n.º 3
0
        public void QueryPartType_ReturnsFilterQueryPart()
        {
            var filterQueryPart = new FilterQueryPart(FilterExpression.Constant("string!"));

            Assert.That(filterQueryPart.QueryPartType, Is.EqualTo(ODataQueryPartType.Filter));
            Assert.That(filterQueryPart.ToString(), Is.EqualTo("$filter='string!'"));
        }
Exemplo n.º 4
0
        public void GetHashCode_FilterExpression_ReturnsFilterExpressionHashCode()
        {
            var filterExpression = FilterExpression.Binary(FilterExpression.Constant(4), FilterExpressionOperator.LessThanOrEqual, FilterExpression.MemberAccess("HelloWorld"));

            var queryPart = new FilterQueryPart(filterExpression);

            Assert.That(queryPart.GetHashCode(), Is.EqualTo(filterExpression.GetHashCode()));
        }
        public void Translate_EqualsFilterExpressionLeftConstant_ReturnsCorrectLinqExpression()
        {
            var filterExpression = FilterExpression.Binary(FilterExpression.Constant("hello"), FilterExpressionOperator.Equal, FilterExpression.MemberAccess("TestString"));

            var expression = _filterExpressionTranslator.Translate(filterExpression);

            var expected = GetLambdaBody(x => "hello" == x.TestString);

            Assert.That(expression.ToString(), Is.EqualTo(expected.ToString()));
        }
        public void Translate_ConstantStringFilterExpression_ReturnsCorrectLinqExpression()
        {
            var filterExpression = FilterExpression.Constant("hello");

            var expression = _filterExpressionTranslator.Translate(filterExpression);

            var expected = GetLambdaBody <string>(x => "hello");

            Assert.That(expression.ToString(), Is.EqualTo(expected.ToString()));
        }
Exemplo n.º 7
0
        /// <summary>
        /// Apply filter on EntityList by propertyName it value load single or default item from list
        /// </summary>
        public static EntityList <T> FilterBy <T>(this EntityList <T> list, string propertyName, object propertyValue) where T : Entity
        {
            FilterExpression expression = FilterExpression.Equal(
                FilterExpression.Property($"{typeof(T).Name}.{propertyName}"),
                FilterExpression.Constant(propertyValue.ToString()));

            var modifier = LoadModifiers.Create();

            modifier.Filters = expression;
            list.Load(modifier);

            return(list);
        }
Exemplo n.º 8
0
        public void Translate_TestIntEqualsThree_ReturnsOneResult()
        {
            var left  = FilterExpression.MemberAccess("TestInt");
            var right = FilterExpression.Constant(3);

            var filterExpression = FilterExpression.Binary(left, FilterExpressionOperator.Equal, right);

            var query = new ODataQuery
            {
                FilterPredicate = ODataQueryPart.Filter(filterExpression)
            };

            var expression = _translator.Translate <TestModel>(query);

            var fn = (Func <IQueryable <TestModel>, IQueryable <TestModel> >)expression.Compile();

            var result = fn(_source).ToList();

            Assert.That(result.Count, Is.EqualTo(1));
            Assert.That(result[0].TestInt, Is.EqualTo(3));
        }
Exemplo n.º 9
0
        public FilterExpression BuildExpression(Stack <Token> stack)
        {
            if (stack == null)
            {
                throw new ArgumentNullException("stack", "Cannot build expression from null expression stack.");
            }

            if (stack.Count < 1)
            {
                throw new ArgumentException("Cannot build expression from empty expression stack.", "stack");
            }

            var token = stack.Pop();

            if (token == null)
            {
                throw new ArgumentException("Cannot build expression from null token.");
            }

            ConstantFilterExpression result;

            var match = TypeSpecified.Match(token.Value);

            if (match.Success)
            {
                // TODO: need to support more than just the EDM type primitives defined in the OData ABNF
                var typeName = match.Groups.Cast <Group>().Skip(1).Single()
                               .Captures.Cast <Capture>().Single().Value;

                var type = EdmTypeNames.Lookup(typeName);

                result = FilterExpression.Constant(null, type);
            }
            else
            {
                result = FilterExpression.Constant <object>(null);
            }

            return(result);
        }
        public FilterExpression BuildExpression(Stack <Token> stack)
        {
            if (stack == null)
            {
                throw new ArgumentNullException("stack", "Cannot parse expression from null expression stack.");
            }

            if (stack.Any() == false)
            {
                throw new ArgumentException("Cannot parse expression from empty expression stack.", "stack");
            }

            var token = stack.Pop();

            if (token == null)
            {
                throw new ArgumentException("Cannot parse a null token.");
            }

            var value = Parse(token.Value);
            var type  = typeof(T);

            return(FilterExpression.Constant(value, type));
        }
Exemplo n.º 11
0
        public string getCustomerInvoices(string serverName, string databaseName, string customerID, DateTime dateFrom, DateTime dateTo)
        {
            CompanyIdentifier companyIdentifier = session.LookupCompanyIdentifier(serverName, databaseName);

            connectionStatus = session.RequestAccess(companyIdentifier);

            if (connectionStatus == AuthorizationResult.Granted)
            {
                Company company = session.Open(companyIdentifier);

                var customers = company.Factories.CustomerFactory.List();

                FilterExpression filter2 = FilterExpression.Equal(
                    FilterExpression.Property("Customer.ID"),
                    FilterExpression.Constant(customerID));


                LoadModifiers modifiers2 = LoadModifiers.Create();
                modifiers2.Filters = filter2;
                customers.Load(modifiers2);
                var cs = customers.ToList();

                if (cs.Count == 0)
                {
                    session.Close(company);
                    return("{\"error\":\"Customer not found" + "\"}");
                }

                Customer customer = cs[0];

                EntityReference customer_key = customer.Key;

                var invoices            = company.Factories.SalesInvoiceFactory.List();
                FilterExpression filter = FilterExpression.Equal(
                    FilterExpression.Property("SalesInvoice.CustomerReference"),
                    FilterExpression.Constant(customer_key));

                LoadModifiers modifiers = LoadModifiers.Create();
                modifiers.Filters = filter;
                invoices.Load(modifiers);



                List <Sage.Peachtree.API.SalesInvoice> invoicesList = invoices.ToList();
                List <InvoiceDetails> invoiceDetailsList            = new List <InvoiceDetails>();

                for (int index = 0; index < invoicesList.Count; index++)
                {
                    SalesInvoice invoice = invoicesList[index];

                    InvoiceDetails invoiceDetails = new InvoiceDetails((decimal)invoice.Amount, (decimal)invoice.AmountDue)
                    {
                        DiscountAmount  = (decimal)invoice.DiscountAmount,
                        ReferenceNumber = invoice.ReferenceNumber,
                        Key             = invoice.Key.Guid.ToString()
                    };

                    if (invoice.Date != null)
                    {
                        invoiceDetails.Date = invoice.Date.ToString();
                    }

                    if (invoice.DateDue != null)
                    {
                        invoiceDetails.DateDue = invoice.DateDue.ToString();
                    }

                    if (invoice.DiscountDate != null)
                    {
                        invoiceDetails.DiscountDate = invoice.DiscountDate.ToString();
                    }


                    invoiceDetailsList.Add(invoiceDetails);
                }

                session.Close(company);

                var json = new JavaScriptSerializer().Serialize(invoiceDetailsList);
                return(json.ToString());
            }


            return("{\"error\":\"Access: " + connectionStatus.ToString() + "\"}");
        }
        public void Translate_GreaterThanOrEqualToFilterExpression_ReturnsCorrectLinqExpression()
        {
            var filterExpression = FilterExpression.Binary(FilterExpression.MemberAccess("TestInt"), FilterExpressionOperator.GreaterThanOrEqual, FilterExpression.Constant(42));

            var expression = _filterExpressionTranslator.Translate(filterExpression);

            var expected = GetLambdaBody(x => x.TestInt >= 42);

            Assert.That(expression.ToString(), Is.EqualTo(expected.ToString()));
        }
Exemplo n.º 13
0
        private Vendor FindSageVendor(Models.Data.Vendor vendor)
        {
            var vendorKey   = vendor.GlobalKey(actionSource);
            var sageVendors = VendorsList();

            // find mapping for vendor globalKey
            var sageVendorId = localDbApi.GetVendorIdByKey(vendorKey);

            if (sageVendorId != null)
            {
                return(sageVendors.SingleOrDefault(sageVendorId));
            }

            // find by GlobalKey in Sage50
            var sageCustomer = sageVendors.SingleOrDefault(vendorKey);

            if (sageCustomer != null)
            {
                localDbApi.StoreVendorId(vendorKey, sageCustomer.ID);
                return(sageCustomer);
            }

            // if no mapping found, find customer by name or email and store mapping to localDb

            if (string.IsNullOrEmpty(vendor.Name) && string.IsNullOrEmpty(vendor.Email))
            {
                throw new AbortException("Can not find Vendor because name and email is null");
            }

            FilterExpression expression;
            string           message = "";

            if (!string.IsNullOrEmpty(vendor.Name) && !string.IsNullOrEmpty(vendor.Email))
            {
                expression = FilterExpression.AndAlso(
                    FilterExpression.Equal(FilterExpression.Property("Vendor.Name"), FilterExpression.Constant(vendor.Name)),
                    FilterExpression.Equal(FilterExpression.Property("Vendor.Email"), FilterExpression.Constant(vendor.Email))
                    );
                LoadVendorsList(expression, sageVendors);
                message = $"name: '{vendor.Name}' and email: '{vendor.Email}'";
            }
            if (sageVendors.Count == 0 && !string.IsNullOrEmpty(vendor.Email))
            {
                expression = FilterExpression.Equal(FilterExpression.Property("Vendor.Email"),
                                                    FilterExpression.Constant(vendor.Email));
                LoadVendorsList(expression, sageVendors);
                message = $"email: '{vendor.Email}'";
            }
            if (sageVendors.Count == 0 && !string.IsNullOrEmpty(vendor.Name))
            {
                expression = FilterExpression.Equal(FilterExpression.Property("Vendor.Name"), FilterExpression.Constant(vendor.Name));
                LoadVendorsList(expression, sageVendors);
                message = $"name: '{vendor.Name}'";
            }

            if (sageVendors.Count == 0)
            {
                return(null);
            }

            if (sageVendors.Count > 1)
            {
                throw new AbortException($"Found more that one vendor with {message}");
            }

            sageCustomer = sageVendors.First();
            localDbApi.StoreVendorId(vendorKey, sageCustomer.ID);
            return(sageCustomer);
        }
        public void Translate_UnaryFilterExpression_ReturnsCorrectLinqExpression()
        {
            var filterExpression = FilterExpression.Unary(FilterExpressionOperator.Not, FilterExpression.Binary(FilterExpression.MemberAccess("TestString"), FilterExpressionOperator.Equal, FilterExpression.Constant("hi")));

            var expression = _filterExpressionTranslator.Translate(filterExpression);

            var expected = GetLambdaBody(x => !(x.TestString == "hi"));

            Assert.That(expression.ToString(), Is.EqualTo(expected.ToString()));
        }
        public void Translate_IndexOfFilterExpression_ReturnsCorrectLinqExpression()
        {
            var filterExpression = FilterExpression.MethodCall(Function.IndexOf, FilterExpression.MemberAccess("TestString"), FilterExpression.Constant("hi"));

            var expression = _filterExpressionTranslator.Translate(filterExpression);

            var expected = GetLambdaBody(x => x.TestString.IndexOf("hi"));

            Assert.That(expression.ToString(), Is.EqualTo(expected.ToString()));
        }
Exemplo n.º 16
0
        public string getCustomers(string serverName, string databaseName, int page)
        {
            CompanyIdentifier companyIdentifier = session.LookupCompanyIdentifier(serverName, databaseName);

            connectionStatus = session.RequestAccess(companyIdentifier);
            Console.WriteLine("Result {0}", connectionStatus.ToString());

            if (connectionStatus == AuthorizationResult.Granted)
            {
                Company company = session.Open(companyIdentifier);
                Console.WriteLine("Company {0}", company.CompanyIdentifier.CompanyName);
                var customers           = company.Factories.CustomerFactory.List();
                FilterExpression filter = FilterExpression.Equal(
                    FilterExpression.Property("Customer.IsInactive"),
                    FilterExpression.Constant(false));

                LoadModifiers modifiers = LoadModifiers.Create();
                modifiers.Filters = filter;
                customers.Load(modifiers);
                var cs = customers.ToList();

                List <CustomerDetails> customerDetailsList = new List <CustomerDetails>();

                int start_index = page * config.recordsPerPage;

                for (int index = start_index; index < start_index + config.recordsPerPage; index++)
                {
                    if (index >= cs.Count)
                    {
                        break;
                    }

                    Customer customer = cs[index];

                    CustomerDetails customerDetails = new CustomerDetails(customer.ID)
                    {
                        AccountNumber     = customer.AccountNumber,
                        Balance           = customer.Balance,
                        Email             = customer.Email,
                        LastInvoiceAmount = customer.LastInvoiceAmount,

                        Name = customer.Name,

                        LastPaymentAmount = customer.LastPaymentAmount,

                        PaymentMethod = customer.PaymentMethod,


                        Category = customer.Category
                    };

                    if (customer.AverageDaysToPayInvoices != null)
                    {
                        customerDetails.AverageDaysToPayInvoices = (decimal)customer.AverageDaysToPayInvoices;
                    }

                    customerDetails.PhoneNumbers = customer.PhoneNumbers;

                    if (customer.CustomerSince != null)
                    {
                        customerDetails.CustomerSince = customer.CustomerSince.ToString();
                    }

                    if (customer.LastPaymentDate != null)
                    {
                        customerDetails.LastPaymentDate = customer.LastPaymentDate.ToString();
                    }

                    if (customer.LastStatementDate != null)
                    {
                        customerDetails.LastStatementDate = customer.LastStatementDate.ToString();
                    }

                    if (customer.LastInvoiceDate != null)
                    {
                        customerDetails.LastInvoiceDate = customer.LastInvoiceDate.ToString();
                    }

                    customerDetailsList.Add(customerDetails);
                }

                session.Close(company);

                var json = new JavaScriptSerializer().Serialize(customerDetailsList);
                return(json.ToString());
            }



            return("{\"error\":\"Access: " + connectionStatus.ToString() + "\"}");
        }
        public void Translate_CastMethodCallFilterExpression_ReturnsCorrectLinqExpression()
        {
            var filterExpression = FilterExpression.MethodCall(Function.Cast, FilterExpression.MemberAccess("TestObject"), FilterExpression.Constant(typeof(string)));

            var expression = _filterExpressionTranslator.Translate(filterExpression);

            var expected = GetLambdaBody(x => (string)x.TestObject);

            Assert.That(expression.ToString(), Is.EqualTo(expected.ToString()));
        }
Exemplo n.º 18
0
        private Customer FindSageCustomer(Models.Data.Customer customer)
        {
            var customerKey   = customer.GlobalKey(actionSource);
            var sageCustomers = CustomersList();

            // find mapping for customer globalKey
            var sageCustomerId = localDbApi.GetCustomerIdByKey(customerKey);

            if (sageCustomerId != null)
            {
                return(sageCustomers.SingleOrDefault(sageCustomerId));
            }

            // find by GlobalKey in Sage50
            var sageCustomer = sageCustomers.SingleOrDefault(customerKey);

            if (sageCustomer != null)
            {
                localDbApi.StoreCustomerId(customerKey, sageCustomer.ID);
                return(sageCustomer);
            }

            // if no mapping found and by extrnalId, find customer by email, phone or name and store mapping to localDb
            if (string.IsNullOrEmpty(customer.Email) && !customer.PhoneNumbers.IsPhonesAbsent())
            {
                // if email empty and phone present, load whole customers list and find first by phone
                sageCustomers.Load();
                sageCustomer = sageCustomers.FirstOrDefault(c => c.PhoneNumbers.ContainsOneOf(customer.PhoneNumbers));
            }
            if (sageCustomer == null)
            {
                FilterExpression expression;
                if (!string.IsNullOrEmpty(customer.Email))
                {
                    expression = FilterExpression.Equal(FilterExpression.Property("Customer.Email"),
                                                        FilterExpression.Constant(customer.Email));
                }
                else if (!string.IsNullOrEmpty(customer.Name))
                {
                    expression = FilterExpression.Equal(FilterExpression.Property("Customer.Name"),
                                                        FilterExpression.Constant(customer.Name));
                }
                else
                {
                    throw new AbortException("Can not search customer because name and email is null");
                }

                var modifier = LoadModifiers.Create();
                modifier.Filters = expression;
                sageCustomers.Load(modifier);

                if (sageCustomers.Count == 0)
                {
                    return(null);
                }

                if (sageCustomers.Count > 1)
                {
                    throw new AbortException(
                              $"Found more that one customer with name: '{customer.Name}' or phones or email: '{customer.Email}'");
                }

                sageCustomer = sageCustomers.First();
            }

            if (sageCustomer == null)
            {
                return(null);
            }

            sageCustomer = sageCustomers.First();
            localDbApi.StoreCustomerId(customerKey, sageCustomer.ID);
            return(sageCustomer);
        }
Exemplo n.º 19
0
        public void Equals_ObjectOfDifferentType_ReturnsFalse()
        {
            var    queryPart = new FilterQueryPart(FilterExpression.Binary(FilterExpression.MemberAccess("Hello"), FilterExpressionOperator.LessThan, FilterExpression.Constant(4)));
            object other     = String.Empty;

            var actual = queryPart.Equals(other);

            Assert.That(actual, Is.False);
        }
Exemplo n.º 20
0
        public void FilterQueryPart_InheritsFromIEquatable()
        {
            var actual = new FilterQueryPart(FilterExpression.Binary(FilterExpression.MemberAccess("Hello"), FilterExpressionOperator.LessThan, FilterExpression.Constant(4)));

            Assert.That(actual, Is.InstanceOf <IEquatable <FilterQueryPart> >());
        }
Exemplo n.º 21
0
        public void Equals_FilterQueryPartNull_ReturnsFalse()
        {
            var             queryPart = new FilterQueryPart(FilterExpression.Binary(FilterExpression.MemberAccess("Hello"), FilterExpressionOperator.LessThan, FilterExpression.Constant(4)));
            FilterQueryPart other     = null;

            var actual = queryPart.Equals(other);

            Assert.That(actual, Is.False);
        }
Exemplo n.º 22
0
        public string getCustomerReceipts(string serverName, string databaseName, string customerID, DateTime dateFrom, DateTime dateTo)
        {
            CompanyIdentifier companyIdentifier = session.LookupCompanyIdentifier(serverName, databaseName);

            connectionStatus = session.RequestAccess(companyIdentifier);

            if (connectionStatus == AuthorizationResult.Granted)
            {
                Company company = session.Open(companyIdentifier);

                var customers = company.Factories.CustomerFactory.List();

                FilterExpression filter3 = FilterExpression.Equal(
                    FilterExpression.Property("Customer.ID"),
                    FilterExpression.Constant(customerID));


                LoadModifiers modifiers3 = LoadModifiers.Create();
                modifiers3.Filters = filter3;
                customers.Load(modifiers3);
                var cs = customers.ToList();

                if (cs.Count == 0)
                {
                    session.Close(company);
                    return("{\"error\":\"Customer not found" + "\"}");
                }

                Customer customer = cs[0];

                EntityReference customer_key = customer.Key;

                var receipts = company.Factories.ReceiptFactory.List();

                //var cpf = company.Factories.ReceiptInvoiceLineFactory.List();


                FilterExpression filter_receipt = FilterExpression.Equal(
                    FilterExpression.Property("Receipt.CustomerReference"),
                    FilterExpression.Constant(customer_key));

                LoadModifiers modifiers = LoadModifiers.Create();
                modifiers.Filters = filter_receipt;
                receipts.Load(modifiers);

                //LoadModifiers modifiers2 = LoadModifiers.Create();
                //modifiers.Filters = filter_receipt;


                //cpf.Load();

                //List<Sage.Peachtree.API.ReceiptInvoiceLine> cpfList = cpf.ToList();

                List <Sage.Peachtree.API.Receipt> receiptList        = receipts.ToList();
                List <ReceiptDetails>             receiptDetailsList = new List <ReceiptDetails>();

                for (int index = 0; index < receiptList.Count; index++)
                {
                    Receipt receipt = receiptList[index];

                    ReceiptDetails ReceiptDetails = new ReceiptDetails((decimal)receipt.Amount)
                    {
                        PaymentMethod   = receipt.PaymentMethod,
                        ReferenceNumber = receipt.ReferenceNumber,
                        Key             = receipt.Key.Guid.ToString()
                    };

                    if (receipt.Date != null)
                    {
                        ReceiptDetails.Date = receipt.Date.ToString();
                    }

                    for (int x = 0; x < receipt.ApplyToInvoiceLines.Count; x++)
                    {
                        InvoiceLine Invoice = new InvoiceLine(receipt.ApplyToInvoiceLines[x].Amount, receipt.ApplyToInvoiceLines[x].AmountPaid)
                        {
                            Description    = receipt.ApplyToInvoiceLines[x].Description,
                            DiscountAmount = receipt.ApplyToInvoiceLines[x].DiscountAmount,
                            InvoiceKey     = receipt.ApplyToInvoiceLines[x].InvoiceReference.Guid.ToString()
                        };

                        ReceiptDetails.ApplyToInvoices.Add(Invoice);
                    }

                    receiptDetailsList.Add(ReceiptDetails);
                }

                session.Close(company);

                var json = new JavaScriptSerializer().Serialize(receiptDetailsList);
                return(json.ToString());
            }

            return("{\"error\":\"Access: " + connectionStatus.ToString() + "\"}");
        }
Exemplo n.º 23
0
        public void Equals_Self_ReturnsTrue()
        {
            var queryPart = new FilterQueryPart(FilterExpression.Binary(FilterExpression.MemberAccess("Hello"), FilterExpressionOperator.LessThan, FilterExpression.Constant(4)));
            var other     = queryPart;

            var actual = queryPart.Equals(other);

            Assert.That(actual, Is.True);
        }
Exemplo n.º 24
0
        static void Main(string[] args)
        {
            string devToken = ConfigurationManager.AppSettings["applicationIdentifier"];
            var    resolver = Assembly.LoadWithPartialName("Sage.Peachtree.API.Resolver");
            var    api      = Assembly.LoadWithPartialName("Sage.Peachtree.API");

            Console.WriteLine("Sage 50 ShipGear write-back performance test");

            Console.WriteLine("Enter server name:");
            string serverName = Console.ReadLine();

            AssemblyInitializer.Initialize();

            var session = new PeachtreeSession();

            try
            {
                try
                {
                    session.Begin(devToken);
                }
                catch (InvalidApplicationIdentifierException e)
                {
                    Message("Put a valid application identifier into the app configuration file.");
                }

                var companyList = session.CompanyList();
                foreach (var item in companyList)
                {
                    Console.WriteLine(string.Format("{0} {1}", item.CompanyName, item.Path));
                }

                Console.WriteLine("Enter company name. The first will be selected if more than one with the same name.");
                string companyName = Console.ReadLine();

                CompanyIdentifier company = null;
                foreach (var item in companyList)
                {
                    if (item.CompanyName == companyName)
                    {
                        company = item;
                        break;
                    }
                }

                if (company == null)
                {
                    Message("No company was selected - quit.");
                }

                var authResult = session.RequestAccess(company);
                if (authResult == AuthorizationResult.Granted)
                {
                    Company comp = null;
                    try
                    {
                        comp = session.Open(company);
                    }
                    catch (Sage.Peachtree.API.Exceptions.AuthorizationException e)
                    {
                        Message("Reopen the company in Sage 50 to enable access to this application.");
                    }

                    try
                    {
                        SalesInvoiceList list = comp.Factories.SalesInvoiceFactory.List();

                        Console.WriteLine("Enter invoice number:");
                        string           documentKey = Console.ReadLine();
                        FilterExpression filter      = FilterExpression.Equal(FilterExpression.Property("SalesInvoice.ReferenceNumber"), FilterExpression.Constant(documentKey));
                        var modifiers = LoadModifiers.Create();
                        modifiers.Filters = filter;

                        list.Load(modifiers);
                        Console.WriteLine("Invoices selected: {0}", list.Count());

                        var enumerator = list.GetEnumerator();
                        if (enumerator == null)
                        {
                            Message("GetEnumerator returned NULL");
                        }

                        Console.WriteLine("Moving to the next record");
                        enumerator.MoveNext();

                        enumerator.Current.CustomerNote = "Test Customer Note";
                        enumerator.Current.InternalNote = "Test Internal Note";

                        Console.WriteLine("Editing the freight (Y[y]/N[n], Y if empty)?");
                        string strFreightEdit = Console.ReadLine();
                        if (string.IsNullOrWhiteSpace(strFreightEdit))
                        {
                            strFreightEdit = "Y";
                        }
                        bool freightEdit = string.Equals(strFreightEdit, "Y", StringComparison.CurrentCultureIgnoreCase);

                        Console.WriteLine("Editing freight: {0}", freightEdit.ToString());
                        if (freightEdit)
                        {
                            enumerator.Current.FreightAmount = 199.99M;
                        }

                        Stopwatch w = Stopwatch.StartNew();
                        Console.WriteLine("Starting performance counter");
                        enumerator.Current.Save();
                        w.Stop();
                        Message(string.Format("Elapsed msec: {0}", w.Elapsed.TotalMilliseconds), ConsoleColor.Green, false);
                        Message("Completed", ConsoleColor.Green, true);
                    }
                    finally
                    {
                        comp.Close();
                    }
                }
                else if (authResult == AuthorizationResult.Pending)
                {
                    Message("Authorization result: Pending - cannot continue. Reopen the company in Sage 50 to enable access to this application.");
                }
                else
                {
                    Message(string.Format("Authorization result: {0} - cannot continue", authResult.ToString()));
                }
            }
            finally
            {
                session.End();
            }
        }