Esempio n. 1
0
        /// <summary>
        /// This demo shows how the customer ledger can be printed out, matched and unmatched.
        /// The same code can run for supplier ledger by changing api.Reporting.CustomerLedger to api.Reporting.SupplierLedger.
        /// </summary>
        public static async Task CustomerLedger()
        {
            var authorizationSettings = new AuthorizationSettings
            {
                ApplicationKey = "<You Application Key Here>",
                ClientKey      = "<PowerOffice Go Client Key Here>",
                TokenStore     = new BasicTokenStore(@"my.tokenstore"),
                EndPointHost   = Settings.EndPointMode.Production //For authorization against the demo environment - Change this to Settings.EndPointMode.Demo
            };

            // Initialize the PowerOffice Go API and request authorization
            var api = await Go.CreateAsync(authorizationSettings);

            Console.WriteLine("Customer ledger:");
            PrintStatement(api);
            //PrintOpenItems(api);

            //Create a match request with all IDs that you want matched or unmatched.
            var matchRequest = new MatchRequest(DateTime.Today, new long[] { 2612317, 2890048 });

            //Request to clear matches
            api.Reporting.CustomerLedger.UnmatchEntries(matchRequest);

            //Request to match entries together
            api.Reporting.CustomerLedger.MatchEntries(matchRequest);

            //NOTE: The same API methods also exists on api.Reporting.SupplierLedger
        }
Esempio n. 2
0
        /// <summary>
        ///     This is is very simple demo of how to create a customer invoices import.
        /// </summary>
        public static async Task CustomerInvoicesImportDemo()
        {
            // Set up authorization settings
            var authorizationSettings = new AuthorizationSettings
            {
                ApplicationKey = "<You Application Key Here>",
                ClientKey      = "<PowerOffice Go Client Key Here>",
                TokenStore     = new BasicTokenStore(@"my1.tokenstore"),
                EndPointHost   = Settings.EndPointMode.Production //For authorization against the demo environment - Change this to Settings.EndPointMode.Demo
            };

            // Initialize the PowerOffice Go API and request authorization
            var api = await Go.CreateAsync(authorizationSettings);

            // Create the import object and upload it to the server
            var import = CreateAndSaveImport(api);

            // List un-posted imports
            ListUnpostedImports(api);

            // The user can post the journal manually from the PowerOffice GO user interface,
            // or the journal can be posted by code.
            PostImport(api, import);

            Console.WriteLine("Demo finished! Press any key to exit...");
            Console.ReadKey();
        }
Esempio n. 3
0
        //// Main method for C# 7.0 and below. Be careful with Wait, you can get deadlocks. It is highly recommended to update to C# 7.1 for console applications.
        //// To change the C# version, open the project properties, go to Build, then click the Advanced button in the bottom right, and select your C# version.
        //// If you can't find an appropriate C# version you may need to update your Visual Studio.
        //public static void Main(string[] args)
        //{
        //    RunDemo().Wait();
        //}

        /// <summary>
        ///     The purpose of this demo is to test if the PowerOffice Go Authentication server will allow us
        ///     to be authorized to access the PowerOffice GO API.
        /// </summary>
        private static async Task RunDemo()
        {
            try
            {
                // Create authorization settings for the test client
                Console.WriteLine("Setting up authorization settings..");
                // Set up authorization settings
                var authorizationSettings = new AuthorizationSettings
                {
                    ApplicationKey = "<You Application Key Here>",
                    ClientKey      = "<PowerOffice Go Client Key Here>",
                    TokenStore     = new BasicTokenStore(@"my.tokenstore"),
                    EndPointHost   = Settings.EndPointMode.Production //For authorization against the demo environment - Change this to Settings.EndPointMode.Demo
                };

                // Request authorization from the PowerOffice GO authentication server
                Console.WriteLine("Requesting authorization..");
                var api = await Go.CreateAsync(authorizationSettings);

                // If no exceptions is thrown by now, we have sucessfully been authorized to access the PowerOffice GO API
                Console.WriteLine("Authorization granted!");
            }
            catch (ApiException e)
            {
                Console.WriteLine("Error: " + e.Message);
            }

            // Wait for user input
            Console.WriteLine("\n\nPress any key...");
            Console.ReadKey();
        }
 private async Task <Go> GetApiAsync()
 {
     return(_api ??= await Go.CreateAsync(new AuthorizationSettings
     {
         ApplicationKey = _options.Value.ApplicationKey,
         ClientKey = _options.Value.ClientKey,
         TokenStore = new BasicTokenStore(_options.Value.TokenStoreName),
         EndPointHost = new Settings.Host(_options.Value.Mode)
     }));
 }
Esempio n. 5
0
        //// Main method for C# 7.0 and below. Be careful with Wait, you can get deadlocks. It is highly recommended to update to C# 7.1 for console applications.
        //// To change the C# version, open the project properties, go to Build, then click the Advanced button in the bottom right, and select your C# version.
        //// If you can't find an appropriate C# version you may need to update your Visual Studio.
        //public static void Main(string[] args)
        //{
        //    RunDemo().Wait();
        //}

        /// <summary>
        ///     The purpose of this demo is to show how salary lines that should be paid out over a payroll can be created.
        /// </summary>
        private static async Task RunDemo()
        {
            var authorizationSettings = new AuthorizationSettings
            {
                ApplicationKey = "<You Application Key Here>",
                ClientKey      = "<PowerOffice Go Client Key Here>",
                TokenStore     = new BasicTokenStore(@"my.tokenstore"),
                EndPointHost   = Settings.EndPointMode.Production //For authorization against the demo environment - Change this to Settings.EndPointMode.Demo
            };

            // Initialize the PowerOffice Go API and request authorization
            var api = await Go.CreateAsync(authorizationSettings);

            //Query all pay items existing in Go
            var payItems = api.Payroll.PayItem.Get().ToArray();

            Console.WriteLine("Number of pay items: " + payItems.Length);

            //Gets the pay item with code 120
            var hourlyWagePayItem = api.Payroll.PayItem.Get().First(p => p.Code == "120");

            Console.WriteLine(hourlyWagePayItem.Name + " - " + hourlyWagePayItem.Benefit + " - " +
                              hourlyWagePayItem.Description);

            //Creates a salary line for hourly wage
            var salaryLine = new SalaryLine
            {
                EmployeeCode   = 64,
                PayItemCode    = "120",
                Quantity       = 100,
                ProjectCode    = "1",
                DepartmentCode = "1",
                Comment        = "This is a text that will appear on the payslip"
            };

            //Saves the created line to Go and prints the Id it's assigned
            salaryLine = api.Payroll.SalaryLine.Save(salaryLine);
            Console.WriteLine("ImportedSalaryLine id: " + salaryLine.Id);

            //Gets all the imported salary lines and prints them out
            var importedSalaryLines = api.Payroll.SalaryLine.Get();

            Console.WriteLine();
            Console.WriteLine("Imported salary lines:");
            foreach (var importedSalaryLine in importedSalaryLines)
            {
                Console.WriteLine("Employee: " + importedSalaryLine.EmployeeCode + " - PayItem: " +
                                  importedSalaryLine.PayItemCode + " - Quantity: " + importedSalaryLine.Quantity);
            }

            //Deletes the imported SalaryLine
            api.Payroll.SalaryLine.Delete(salaryLine);

            Console.ReadKey();
        }
Esempio n. 6
0
        /// <summary>
        /// This demo code shows how to print out account transactions between two dates.
        /// </summary>
        /// <returns></returns>
        public static async Task AccountTransactionsDemo()
        {
            // Set up authorization settings
            var authorizationSettings = new AuthorizationSettings
            {
                ApplicationKey = "<You Application Key Here>",
                ClientKey      = "<PowerOffice Go Client Key Here>",
                TokenStore     = new BasicTokenStore(@"my.tokenstore"),
                EndPointHost   = Settings.EndPointMode.Production //For authorization against the demo environment - Change this to Settings.EndPointMode.Demo
            };

            // Initialize the PowerOffice Go API and request authorization
            var api = await Go.CreateAsync(authorizationSettings);

            // List all transactions on account 3000 between 2014-01-01 and today
            const int accountNo = 3000;
            var       fromDate  = new DateTime(2014, 1, 1);
            var       toDate    = DateTime.Now;

            Console.WriteLine("Account Transactions:");
            var accountTransactions = api.Reporting.AccountTransactions.Get(accountNo, fromDate, toDate).ToList();

            //This commented out query will get all account transactions without account filter.
            //var accountTransactions = api.Reporting.AccountTransactions.Get(fromDate, toDate).ToList();

            foreach (var transaction in accountTransactions)
            {
                Console.WriteLine(transaction.Date + " " + transaction.Text + " " + transaction.VoucherType + " " + transaction.Amount + " Number of voucher images: " + transaction.VoucherImagesCount);
            }

            // Load image for the first transaction with an attached voucher image
            var transactionWithImages = accountTransactions.FirstOrDefault(t => t.VoucherImagesCount > 0);

            if (transactionWithImages != null)
            {
                Console.WriteLine("Load first image for voucher {0}", transactionWithImages.VoucherNo);

                var imageStream = api.Blob.GetVoucherImage(transactionWithImages.VoucherNo, 1);
                // At this point imageStream contains a jpeg image of the first page of the voucher
            }
        }
Esempio n. 7
0
        //// Main method for C# 7.0 and below. Be careful with Wait, you can get deadlocks. It is highly recommended to update to C# 7.1 for console applications.
        //// To change the C# version, open the project properties, go to Build, then click the Advanced button in the bottom right, and select your C# version.
        //// If you can't find an appropriate C# version you may need to update your Visual Studio.
        //public static void Main(string[] args)
        //{
        //    RunDemo().Wait();
        //}


        /// <summary>
        /// The purpose of this demo is to create a new General Ledger Account and print out the chart of accounts for a client.
        /// </summary>
        private static async Task RunDemo()
        {
            var authorizationSettings = new AuthorizationSettings
            {
                ApplicationKey = "<You Application Key Here>",
                ClientKey      = "<PowerOffice Go Client Key Here>",
                TokenStore     = new BasicTokenStore(@"my.tokenstore"),
                EndPointHost   = Settings.EndPointMode.Production //For authorization against the demo environment - Change this to Settings.EndPointMode.Demo
            };

            // Initialize the PowerOffice Go API and request authorization
            var api = await Go.CreateAsync(authorizationSettings);

            //Add a new General Ledger Account
            var account3016 = new GeneralLedgerAccount()
            {
                Code         = 3016,
                Name         = "Salgskonto 3016",
                CurrencyCode = "NOK",
                IsActive     = true,
                VatCode      = "3"
            };

            account3016 = api.GeneralLedgerAccount.Save(account3016);

            //Query all General Ledger Accounts (Chart of Accounts)
            var generalLedgerAccounts = api.GeneralLedgerAccount.Get().OrderBy(a => a.Code).ToArray();

            foreach (var generalLedgerAccount in generalLedgerAccounts)
            {
                Console.WriteLine($"{generalLedgerAccount.Code} - {generalLedgerAccount.Name} - IsActive: {generalLedgerAccount.IsActive}");
            }

            //Delete General Ledger Account
            api.GeneralLedgerAccount.Delete(account3016);

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
Esempio n. 8
0
        private async Task <Go> GetApiAsync()
        {
            // read per-org power office settings,
            // fallback to system-wide settings if not set.

            var appKey = await _organizationSettingsAccessorService
                         .GetOrganizationSettingByNameAsync(PowerOfficeConstants.ApplicationKey)
                         ?? _options.Value.ApplicationKey;

            var clientKey = await _organizationSettingsAccessorService
                            .GetOrganizationSettingByNameAsync(PowerOfficeConstants.ClientKey)
                            ?? _options.Value.ClientKey;

            _logger.LogInformation("Using PowerOffice Client with applicationKey: {AppKey}", appKey);

            return(_api ??= await Go.CreateAsync(new AuthorizationSettings
            {
                ApplicationKey = appKey,
                ClientKey = clientKey,
                TokenStore = new BasicInMemoryTokenStore(),
                EndPointHost = new Settings.Host(_options.Value.Mode)
            }));
        }
Esempio n. 9
0
        /// <summary>
        /// Lists the unposted imports.
        /// </summary>
        public static async Task ListUnpostedImports()
        {
            // Initialize the PowerOffice Go API and request authorization
            // Set up authorization settings
            var authorizationSettings = new AuthorizationSettings
            {
                ApplicationKey = "<You Application Key Here>",
                ClientKey      = "<PowerOffice Go Client Key Here>",
                TokenStore     = new BasicTokenStore(@"my.tokenstore"),
                EndPointHost   = Settings.EndPointMode.Production //For authorization against the demo environment - Change this to Settings.EndPointMode.Demo
            };

            var api = await Go.CreateAsync(authorizationSettings);

            // Get list of imports
            Console.WriteLine("List of unposted imports:");
            var imports = api.Import.Get().Where(i => i.IsPosted == false);

            foreach (var import in imports)
            {
                Console.WriteLine("{0}: {1} {2} {3}", import.Id, import.Type, import.Description, import.IsPosted ? "[POSTED]" : "");
            }
            Console.WriteLine();
        }
Esempio n. 10
0
        /// <summary>
        ///     This is is very simple demo of how to create a sales order import.
        /// </summary>
        public static async Task SalesOrderImportDemo()
        {
            // Set up authorization settings
            var authorizationSettings = new AuthorizationSettings
            {
                ApplicationKey = "<You Application Key Here>",
                ClientKey      = "<PowerOffice Go Client Key Here>",
                TokenStore     = new BasicTokenStore(@"my.tokenstore"),
                EndPointHost   = Settings.EndPointMode.Production //For authorization against the demo environment - Change this to Settings.EndPointMode.Demo
            };

            // Initialize the PowerOffice Go API and request authorization
            var api = await Go.CreateAsync(authorizationSettings);

            //First we need to make sure that all customers that we're using are created in PowerOffice Go
            //For more a more detailed example on how to do changes to customers, check out the CustomerDemo on https://github.com/PowerOffice/go-api/tree/master/Examples
            UpsertCustomers(api);

            //Then we need to make sure that all products that we're using are created in PowerOffice Go
            //For more a more detailed example on how to do changes to products, check out the ProductDemo on https://github.com/PowerOffice/go-api/tree/master/Examples
            UpsertProducts(api);

            //Now it's time to import the sales orders
            // Create the import object and upload it to the server
            var import = CreateAndSaveImport(api);

            // List un-posted imports
            ListUnpostedImports(api);

            // The user can post the journal manually from the PowerOffice GO user interface,
            // or the journal can be posted by code.
            PostImport(api, import);

            Console.WriteLine("Demo finished! Press any key to exit...");
            Console.ReadKey();
        }
Esempio n. 11
0
        /// <summary>
        ///     List the trial balance as at today
        /// </summary>
        public static async Task TrialBalanceDemo()
        {
            // Set up authorization settings
            var authorizationSettings = new AuthorizationSettings
            {
                ApplicationKey = "<You Application Key Here>",
                ClientKey      = "<PowerOffice Go Client Key Here>",
                TokenStore     = new BasicTokenStore(@"my.tokenstore"),
                EndPointHost   = Settings.EndPointMode.Production //For authorization against the demo environment - Change this to Settings.EndPointMode.Demo
            };

            // Initialize the PowerOffice Go API and request authorization
            var api = await Go.CreateAsync(authorizationSettings);

            // List all accounts in the trial balance as at today
            Console.WriteLine("Trial Balance:");

            var trialBalanceLines = api.Reporting.TrialBalance.Get(DateTime.Now);

            foreach (var trialBalanceLine in trialBalanceLines)
            {
                Console.WriteLine(trialBalanceLine.AccountCode + " " + trialBalanceLine.AccountName + " " + trialBalanceLine.Balance + " " + trialBalanceLine.Budget);
            }
        }
Esempio n. 12
0
        //// Main method for C# 7.0 and below. Be careful with Wait, you can get deadlocks. It is highly recommended to update to C# 7.1 for console applications.
        //// To change the C# version, open the project properties, go to Build, then click the Advanced button in the bottom right, and select your C# version.
        //// If you can't find an appropriate C# version you may need to update your Visual Studio.
        //public static void Main(string[] args)
        //{
        //    RunDemo().Wait();
        //}

        /// <summary>
        ///     The purpose of this demo is to show how projects can be created and queried.
        /// </summary>
        private static async Task RunDemo()
        {
            try
            {
                // Set up authorization settings
                var authorizationSettings = new AuthorizationSettings
                {
                    ApplicationKey = "<You Application Key Here>",
                    ClientKey      = "<PowerOffice Go Client Key Here>",
                    TokenStore     = new BasicTokenStore(@"my.tokenstore"),
                    EndPointHost   = Settings.EndPointMode.Production //For authorization against the demo environment - Change this to Settings.EndPointMode.Demo
                };

                // Initialize the PowerOffice Go API and request authorization
                var api = await Go.CreateAsync(authorizationSettings);

                // Create new Project
                Console.WriteLine("Create new project...");
                var myNewProject = new Project
                {
                    Code = "P105",
                    Name = "My new project"
                };
                api.Project.Save(myNewProject);

                Console.WriteLine("Name: " + myNewProject.Name);

                // Get a list of projects starting with My (restricted to 50 rows)
                Console.WriteLine("Getting projects with name starting with \"My\". Max 50...");
                var customers = api.Project.Get().Where(c => c.Name.ToUpper().StartsWith("MY")).Skip(0).Take(50);
                foreach (var customer1 in customers)
                {
                    Console.WriteLine("Name: " + customer1.Name);
                }

                // Look up a project with a given project code
                Console.WriteLine("Get Project with Code Number: " + myNewProject.Code);

                var project = api.Project.Get().FirstOrDefault(c => c.Code == myNewProject.Code);
                if (project != null)
                {
                    Console.WriteLine("Name: " + project.Name);
                }

                // Change project name name
                project.Name = "My Project";

                // Save the project
                Console.WriteLine("Saving...");
                project = api.Project.Save(project);
                if (project != null)
                {
                    Console.WriteLine("Name: " + project.Name);
                }

                // Delete the project
                Console.WriteLine("Deleting...");
                api.Project.Delete(project);

                Console.WriteLine("Done");
            }
            catch (ApiException e)
            {
                Console.WriteLine("Error: " + e.Message);
            }

            // Wait for user input
            Console.WriteLine("\n\nPress any key...");
            Console.ReadKey();
        }
Esempio n. 13
0
        //// Main method for C# 7.0 and below. Be careful with Wait, you can get deadlocks. It is highly recommended to update to C# 7.1 for console applications.
        //// To change the C# version, open the project properties, go to Build, then click the Advanced button in the bottom right, and select your C# version.
        //// If you can't find an appropriate C# version you may need to update your Visual Studio.
        //public static void Main(string[] args)
        //{
        //    RunDemo().Wait();
        //}

        /// <summary>
        ///     The purpose of this demo is to test some of the Customer functionallity available to PowerOffice Go users.
        /// </summary>
        private static async Task RunDemo()
        {
            try
            {
                // Set up authorization settings
                var authorizationSettings = new AuthorizationSettings
                {
                    ApplicationKey = "<You Application Key Here>",
                    ClientKey      = "<PowerOffice Go Client Key Here>",
                    TokenStore     = new BasicTokenStore(@"my.tokenstore"),
                    EndPointHost   = Settings.EndPointMode.Production //For authorization against the demo environment - Change this to Settings.EndPointMode.Demo
                };

                // Initialize the PowerOffice Go API and request authorization
                var api = await Go.CreateAsync(authorizationSettings);

                // Create new customer
                Console.WriteLine("Create new customer...");
                var myNewCustomer = new Customer
                {
                    Name      = "My new customer",
                    VatNumber = "999999997"
                };
                api.Customer.Save(myNewCustomer);

                Console.WriteLine("Name: " + myNewCustomer.Name);

                // Get a list of customers starting with Power (restricted to 50 rows)
                Console.WriteLine("Getting customers with name starting with \"My\". Max 50...");
                var customers = api.Customer.Get().Where(c => c.Name.ToUpper().StartsWith("MY")).Skip(0).Take(50);
                foreach (var customer1 in customers)
                {
                    Console.WriteLine("Name: " + customer1.Name);
                }

                // Look up a customer with a given Vat number
                Console.WriteLine("Get Customer with Vat Number: " + myNewCustomer.VatNumber);

                var customer = api.Customer.Get().FirstOrDefault(c => c.VatNumber == myNewCustomer.VatNumber);
                if (customer != null)
                {
                    Console.WriteLine("Name: " + customer.Name);
                }

                // Change customer name
                customer.Name = "My Customer AS";

                // Save the customer
                Console.WriteLine("Saving...");
                customer = api.Customer.Save(customer);
                if (customer != null)
                {
                    Console.WriteLine("Name: " + customer.Name);
                }

                // Delete the customer
                Console.WriteLine("Deleting...");
                api.Customer.Delete(customer);

                Console.WriteLine("Done");
            }
            catch (ApiException e)
            {
                Console.WriteLine("Error: " + e.Message);
            }

            // Wait for user input
            Console.WriteLine("\n\nPress any key...");
            Console.ReadKey();
        }
Esempio n. 14
0
        //// Main method for C# 7.0 and below. Be careful with Wait, you can get deadlocks. It is highly recommended to update to C# 7.1 for console applications.
        //// To change the C# version, open the project properties, go to Build, then click the Advanced button in the bottom right, and select your C# version.
        //// If you can't find an appropriate C# version you may need to update your Visual Studio.
        //public static void Main(string[] args)
        //{
        //    RunDemo().Wait();
        //}

        /// <summary>
        ///     The purpose of this demo is to show how time tracking can be used through the API.
        /// </summary>
        private static async Task RunDemo()
        {
            var authorizationSettings = new AuthorizationSettings
            {
                ApplicationKey = "<You Application Key Here>",
                ClientKey      = "<PowerOffice Go Client Key Here>",
                TokenStore     = new BasicTokenStore(@"my.tokenstore"),
                EndPointHost   = Settings.EndPointMode.Production //For authorization against the demo environment - Change this to Settings.EndPointMode.Demo
            };

            // Initialize the PowerOffice Go API and request authorization
            var api = await Go.CreateAsync(authorizationSettings);

            //Get and print out all hour types available on the Client
            Console.WriteLine("Hour types:");
            var hourTypes = api.TimeTracking.HourType.Get().ToArray();

            foreach (var hourType in hourTypes)
            {
                Console.WriteLine($"{hourType.Description} | PayItemCode: {hourType.PayItemCode} | IsActive: {hourType.IsActive}");
            }

            Console.WriteLine();

            //Get and print all Activities available on the Client.
            Console.WriteLine("Activities:");
            var activities = api.TimeTracking.Activity.Get().ToArray();

            foreach (var activity in activities)
            {
                Console.WriteLine($"{activity.Name} ({activity.Code}) | Type: {activity.ActivityType} | IsActive: {activity.IsActive}");
            }

            Console.WriteLine();

            //Query time tracking entries this month
            Console.WriteLine("Time tracking entries:");
            var currentDate         = DateTime.Today;
            var monthStart          = new DateTime(currentDate.Year, currentDate.Month, 1);
            var timeTrackingEntries = api.TimeTracking.TimeTrackingEntry.Get().Where(t => t.Date >= monthStart).OrderBy(t => t.Date).ToArray();

            foreach (var timeTrackingEntry in timeTrackingEntries)
            {
                Console.WriteLine($"{timeTrackingEntry.EmployeeCode} - {timeTrackingEntry.ActivityCode} - {timeTrackingEntry.Date} - {timeTrackingEntry.Hours}");
            }

            Console.WriteLine();

            //Get entry for a given employee, project, activity and hour type, or create new with the same dimensions
            var date          = new DateTime(2017, 7, 3);
            var employeeCode  = 1;
            var activityCode  = "802";
            var projectCode   = "2";
            var hourTypeToUse = "Overtid 100 %";
            var numberOfHours = 12;


            var timeTrackingEntryToEdit =
                timeTrackingEntries.FirstOrDefault(t => t.Date == date && t.EmployeeCode == employeeCode && t.ActivityCode == activityCode && t.ProjectCode == projectCode && t.HourType == hourTypeToUse);

            if (timeTrackingEntryToEdit != null)
            {
                timeTrackingEntryToEdit.Hours  += numberOfHours;
                timeTrackingEntryToEdit.Comment = "A comment from edit";
            }
            else
            {
                timeTrackingEntryToEdit = new TimeTrackingEntry()
                {
                    ActivityCode = activityCode,
                    Date         = date,
                    Comment      = "A comment",
                    Hours        = numberOfHours,
                    EmployeeCode = employeeCode,
                    ProjectCode  = projectCode,
                    HourType     = hourTypeToUse
                };
            }

            //Save the time tracking entry
            api.TimeTracking.TimeTrackingEntry.Save(timeTrackingEntryToEdit);

            //Query again and print
            Console.WriteLine("Time tracking entries:");
            timeTrackingEntries = api.TimeTracking.TimeTrackingEntry.Get().Where(t => t.Date >= monthStart).OrderBy(t => t.Date).ToArray();
            foreach (var timeTrackingEntry in timeTrackingEntries)
            {
                Console.WriteLine($"{timeTrackingEntry.EmployeeCode} - {timeTrackingEntry.ActivityCode} - {timeTrackingEntry.Date} - {timeTrackingEntry.Hours}");
            }

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
Esempio n. 15
0
        //// Main method for C# 7.0 and below. Be careful with Wait, you can get deadlocks. It is highly recommended to update to C# 7.1 for console applications.
        //// To change the C# version, open the project properties, go to Build, then click the Advanced button in the bottom right, and select your C# version.
        //// If you can't find an appropriate C# version you may need to update your Visual Studio.
        //public static void Main(string[] args)
        //{
        //    RunDemo().Wait();
        //}

        /// <summary>
        ///     The purpose of this demo is to show how the API can update and query products and product groups.
        /// </summary>
        private static async Task RunDemo()
        {
            try
            {
                // Set up authorization settings
                var authorizationSettings = new AuthorizationSettings
                {
                    ApplicationKey = "<You Application Key Here>",
                    ClientKey      = "<PowerOffice Go Client Key Here>",
                    TokenStore     = new BasicTokenStore(@"my.tokenstore"),
                    EndPointHost   = Settings.EndPointMode.Production //For authorization against the demo environment - Change this to Settings.EndPointMode.Demo
                };

                // Initialize the PowerOffice Go API and request authorization
                var api = await Go.CreateAsync(authorizationSettings);

                //Create new product group
                Console.WriteLine("Creating product group");
                var productGroup = new ProductGroup
                {
                    Code                  = "1",
                    Name                  = "Sandwiches",
                    Description           = "Product group for all the sandwiches",
                    Type                  = ProductType.Product,
                    SalesAccount          = 3000,
                    VatExemptSalesAccount = 3100,
                    Unit                  = "each"
                };

                //Saves the product group
                Console.WriteLine("Saving product group \"" + productGroup.Name + "\".");
                api.ProductGroup.Save(productGroup);

                //Get product group by it's code
                var savedProductGroup = api.ProductGroup.Get().First(pg => pg.Code == "1");

                //Edit the description for a saved product group
                Console.WriteLine("Editing product group: \"" + savedProductGroup.Name + "\".");
                savedProductGroup.Description = "Product group for most sandwiches";
                savedProductGroup.Name        = "Footlong sandwiches";
                var editedProductGroup = api.ProductGroup.Save(savedProductGroup);
                Console.WriteLine("Edited description. It is now \"" + editedProductGroup.Description + "\"");
                Console.WriteLine("Edited name. It is now \"" + editedProductGroup.Name + "\"");

                //Create new product
                var product = new Product
                {
                    Code                  = "1",
                    Description           = "One footlong sandwich",
                    Name                  = "Footlong edited",
                    CostPrice             = new decimal(10.5),
                    SalesPrice            = new decimal(50),
                    ProductGroupId        = savedProductGroup.Id,
                    SalesAccount          = 3000,
                    VatExemptSalesAccount = 3100,
                    Type                  = ProductType.Product,
                    Gtin                  = "",
                    Unit                  = "each"
                };

                //Saves the product
                Console.WriteLine("Saving product \"" + product.Name + "\".");
                api.Product.Save(product);

                //Get all the products
                var allProducts = api.Product.Get();

                //Deletes the with product code 1
                Console.WriteLine("Deleting product with product code \"1\".");
                api.Product.Delete(allProducts.First(p => p.Code == "1"));

                //Deletes the saved product group
                Console.WriteLine("Deleting product group \"" + editedProductGroup.Name + "\".");
                api.ProductGroup.Delete(editedProductGroup);

                Console.WriteLine("Demo finished! Press any key to exit...");
                Console.ReadKey();
            }
            catch (ApiException e)
            {
                Console.WriteLine("Error: " + e.Message);
                Console.ReadKey();
            }
        }
Esempio n. 16
0
        //// Main method for C# 7.0 and below. Be careful with Wait, you can get deadlocks. It is highly recommended to update to C# 7.1 for console applications.
        //// To change the C# version, open the project properties, go to Build, then click the Advanced button in the bottom right, and select your C# version.
        //// If you can't find an appropriate C# version you may need to update your Visual Studio.
        //public static void Main(string[] args)
        //{
        //    RunDemo().Wait();
        //}

        /// <summary>
        /// The purpose of this demo is to show how Journal Entry Vouchers can be created with suggested voucher lines.
        /// Journal Entry Vouchers are vouchers that is unposted and will appear in Journal Entry.
        /// Users in PowerOffice Go will then verify the suggested voucherlines, perhaps edit it some and then the voucher.
        /// </summary>
        static async Task RunDemo()
        {
            try
            {
                var authorizationSettings = new AuthorizationSettings
                {
                    ApplicationKey = "<You Application Key Here>",
                    ClientKey      = "<PowerOffice Go Client Key Here>",
                    TokenStore     = new BasicTokenStore(@"my.tokenstore"),
                    EndPointHost   = Settings.EndPointMode.Production //For authorization against the demo environment - Change this to Settings.EndPointMode.Demo
                };


                // Initialize the PowerOffice Go API and request authorization
                var api = await Go.CreateAsync(authorizationSettings);


                //Queries and prints out all previously created Journal Entry Vouchers
                var vouchers = api.JournalEntryVoucher.Get().ToList();
                foreach (var voucher in vouchers)
                {
                    Console.WriteLine($"{voucher.VoucherDate} {voucher.SupplierCode} {voucher.TotalAmount}");

                    foreach (var journalEntryVoucherLine in voucher.VoucherLines)
                    {
                        Console.WriteLine($"{journalEntryVoucherLine.Date} {journalEntryVoucherLine.Description} {journalEntryVoucherLine.DebitAccountCode} {journalEntryVoucherLine.CreditAccountCode} {journalEntryVoucherLine.Amount}");
                    }

                    Console.WriteLine();
                }

                //Reads a file from disk and converts it to a Base64 string.
                byte[] bytes = File.ReadAllBytes("C:\\temp\\Test.pdf");
                string file  = Convert.ToBase64String(bytes);

                //Creates a journal entry voucher and saves it Go.
                var journalEntryVoucher = new JournalEntryVoucher
                {
                    VoucherType  = JournalEntryVoucherType.ManualJournal,
                    Description  = "Test manuelt kassesalg ellerno",
                    VoucherDate  = DateTime.Today,
                    CurrencyCode = "NOK",
                    VoucherLines = new[]
                    {
                        new JournalEntryVoucherLine()
                        {
                            Date              = DateTime.Today,
                            DebitAccountCode  = 1920,
                            DebitVatCode      = null,
                            CreditAccountCode = 3000,
                            CreditVatCode     = "3",
                            CurrencyCode      = "NOK",
                            Amount            = 150000,
                            DepartmentCode    = null,
                            ProjectCode       = null,
                            Description       = "Solgte noe for noe til noen..."
                        }
                    },
                    File = new JournalEntryFile()
                    {
                        FileName          = "Test.pdf",
                        FileType          = JournalEntryFileType.Pdf,
                        Base64EncodedData = file
                    }
                };

                //Saves the Journal Entry Voucher
                var result = api.JournalEntryVoucher.Save(journalEntryVoucher);

                Console.WriteLine($"Journal entry voucher created with id: {result.Id}.");
            }
            catch (ApiException e)
            {
                Console.WriteLine("Error: " + e.Message);
            }

            Console.WriteLine("Done...");
            Console.ReadKey();
        }
Esempio n. 17
0
        //// Main method for C# 7.0 and below. Be careful with Wait, you can get deadlocks. It is highly recommended to update to C# 7.1 for console applications.
        //// To change the C# version, open the project properties, go to Build, then click the Advanced button in the bottom right, and select your C# version.
        //// If you can't find an appropriate C# version you may need to update your Visual Studio.
        //public static void Main(string[] args)
        //{
        //    RunDemo().Wait();
        //}

        /// <summary>
        ///     The purpose of this demo is to show how different vouchers can be created through the API.
        ///     There is one method for each of the Voucher Types supported by this service.
        ///     All methods will create a voucher, then create a reversal voucher for the previous voucher.
        ///     Reversal Vouchers can be used to reverse the accounting entries that the voucher that is reversed created.
        ///     This is a new feature from version 2.6.0 and is the prefered way to import vouchers to PowerOffice Go.
        /// </summary>
        private static async Task RunDemo()
        {
            try
            {
                // Set up authorization settings
                var authorizationSettings = new AuthorizationSettings
                {
                    ApplicationKey = "<You Application Key Here>",
                    ClientKey      = "<PowerOffice Go Client Key Here>",
                    TokenStore     = new BasicTokenStore(@"my.tokenstore"),
                    EndPointHost   = Settings.EndPointMode.Production //For authorization against the demo environment - Change this to Settings.EndPointMode.Demo
                };

                // Initialize the PowerOffice Go API and request authorization
                var api = await Go.CreateAsync(authorizationSettings);

                //Prints out the client we're working on
                var currentClient = api.Client.Get();
                Console.WriteLine("Client:");
                Console.WriteLine($"{currentClient.Name}, LockDate: {currentClient.LockDate}");
                Console.WriteLine();

                Console.WriteLine("Creating outgoing invoice:");
                CreateOutgoingInvoiceAndReverse(api);
                Console.WriteLine();

                Console.WriteLine("Creating incoming invoice:");
                CreateIncomingInvoiceAndReverse(api);
                Console.WriteLine();

                Console.WriteLine("Creating expense:");
                CreateExpenseAndReverse(api);
                Console.WriteLine();

                Console.WriteLine("Creating manual voucher:");
                CreateManualVoucherAndReverse(api);
                Console.WriteLine();

                Console.WriteLine("Creating year end voucher:");
                CreateYearEndVoucherAndReverse(api);
                Console.WriteLine();

                Console.WriteLine("Creating payroll journal:");
                CreatePayrollJournalAndReverse(api);
                Console.WriteLine();

                Console.WriteLine("Creating cash journal:");
                CreateCashJournalAndReverse(api);
                Console.WriteLine();

                Console.WriteLine("Creating bank journal:");
                CreateBankJournalAndReverse(api);
                Console.WriteLine();

                Console.WriteLine("Done");
            }
            catch (ApiException e)
            {
                Console.WriteLine("Error: " + e.Message);
            }

            // Wait for user input
            Console.WriteLine("\n\nPress any key...");
            Console.ReadKey();
        }
Esempio n. 18
0
        //// Main method for C# 7.0 and below. Be careful with Wait, you can get deadlocks. It is highly recommended to update to C# 7.1 for console applications.
        //// To change the C# version, open the project properties, go to Build, then click the Advanced button in the bottom right, and select your C# version.
        //// If you can't find an appropriate C# version you may need to update your Visual Studio.
        //public static void Main(string[] args)
        //{
        //    RunDemo().Wait();
        //}

        /// <summary>
        ///     The purpose of this demo is to show how to list out invoices and creating invoices ready to be sent from PowerOffice Go
        /// </summary>
        private static async Task RunDemo()
        {
            var authorizationSettings = new AuthorizationSettings
            {
                ApplicationKey = "<You Application Key Here>",
                ClientKey      = "<PowerOffice Go Client Key Here>",
                TokenStore     = new BasicTokenStore(@"my.tokenstore"),
                EndPointHost   = Settings.EndPointMode.Production //For authorization against the demo environment - Change this to Settings.EndPointMode.Demo
            };

            // Initialize the PowerOffice Go API and request authorization
            var api = await Go.CreateAsync(authorizationSettings);

            //Query all invoices with order dat in the last 10 days
            var dateTime10DaysAgo = DateTime.Now.AddDays(-10).Date;
            var invoices          = api.OutgoingInvoice.List().Where(i => i.OrderDate > dateTime10DaysAgo).ToArray();

            foreach (var outgoingInvoiceListItem in invoices)
            {
                Console.WriteLine(outgoingInvoiceListItem.CustomerCode + " - " + outgoingInvoiceListItem.TotalAmount);
            }

            //Create a new invoice
            var newInvoice = new GoApi.Invoices.OutgoingInvoice
            {
                CustomerCode      = 10000,
                ContractNo        = "12345",
                CurrencyCode      = "NOK",
                CustomerReference = "Reference",
                DepartmentCode    = "1",
                ProjectCode       = "1",
                OrderDate         = DateTime.Now,
                PurchaseOrderNo   = "123",
                ImportedOrderNo   = 5555,
                DeliveryDate      = DateTime.Now.AddDays(-10)
            };

            newInvoice.OutgoingInvoiceLines.Add(new OutgoingInvoiceLine
            {
                LineType        = VoucherLineType.Normal,
                ProductCode     = "1",
                Description     = "Test",
                Quantity        = 5,
                UnitOfMeasure   = "ea",
                UnitPrice       = new decimal(5000.0),
                ExemptVat       = false,
                DiscountPercent = new decimal(0.1),
                SortOrder       = 0
            });

            newInvoice.OutgoingInvoiceLines.Add(new OutgoingInvoiceLine
            {
                LineType    = VoucherLineType.Text,
                Description = "Description line",
                SortOrder   = 1
            });

            //Save the invoices, store it's ID that can be used later to edit the invoice
            var newInvoiceId = api.OutgoingInvoice.Save(newInvoice).Id.Value;

            //Get the saved invoice
            newInvoice = api.OutgoingInvoice.Get(newInvoiceId);

            //Add another line to the invoice
            newInvoice.OutgoingInvoiceLines.Add(new OutgoingInvoiceLine
            {
                Description     = "Test",
                DiscountPercent = new decimal(0.5),
                ExemptVat       = false,
                LineType        = VoucherLineType.Normal,
                Quantity        = 5,
                ProductCode     = "1",
                SortOrder       = 2
            });

            //Set the delivery address on the invoice (this id can be queried from Customer service)
            newInvoice.DeliveryAddressId = 17506;

            //Save the invoice
            api.OutgoingInvoice.Save(newInvoice);

            //Delete the invoice
            api.OutgoingInvoice.Delete(newInvoice);

            Console.ReadKey();
        }
Esempio n. 19
0
        //// Main method for C# 7.0 and below. Be careful with Wait, you can get deadlocks. It is highly recommended to update to C# 7.1 for console applications.
        //// To change the C# version, open the project properties, go to Build, then click the Advanced button in the bottom right, and select your C# version.
        //// If you can't find an appropriate C# version you may need to update your Visual Studio.
        //public static void Main(string[] args)
        //{
        //    RunDemo().Wait();
        //}

        /// <summary>
        ///     The purpose of this demo is to show how recurring (repeated) invoices can be created through the API.
        /// </summary>
        private static async Task RunDemo()
        {
            try
            {
                var authorizationSettings = new AuthorizationSettings
                {
                    ApplicationKey = "<You Application Key Here>",
                    ClientKey      = "<PowerOffice Go Client Key Here>",
                    TokenStore     = new BasicTokenStore(@"my.tokenstore"),
                    EndPointHost   = Settings.EndPointMode.Production //For authorization against the demo environment - Change this to Settings.EndPointMode.Demo
                };

                // Initialize the PowerOffice Go API and request authorization
                var api = await Go.CreateAsync(authorizationSettings);

                //Get all recurring invoices as a list
                Console.WriteLine("Recurring Invoices:");
                var allRecurringInvoices = api.RecurringInvoice.List().ToArray();
                foreach (var recurringInvoiceListItem in allRecurringInvoices)
                {
                    Console.WriteLine($"Active:{recurringInvoiceListItem.IsActive} Cust:{recurringInvoiceListItem.CustomerCode} Net:{recurringInvoiceListItem.NetAmount}, Tot:{recurringInvoiceListItem.TotalAmount}.");
                    Console.WriteLine($"NextDate:{recurringInvoiceListItem.NextInvoiceDate} DaysInAdvance:{recurringInvoiceListItem.DaysInAdvance} Repeat:{recurringInvoiceListItem.SendFrequencyUnit} SendMethod:{recurringInvoiceListItem.SendMethod}");
                }

                Console.WriteLine();

                //Create recurring invoice
                var newRecurringInvoice = new GoApi.Invoices.RecurringInvoice
                {
                    IsActive                 = false,
                    NextInvoiceDate          = new DateTime(2017, 10, 01),
                    DaysInAdvance            = 1,
                    RepeatTimes              = 12,
                    SendFrequency            = 1,
                    SendFrequencyUnit        = RecurringSendFrequencyUnit.Monthly,
                    SendMethod               = RecurringSendMethod.Confirm,
                    CustomerCode             = 100000,
                    ProjectCode              = "1",
                    DepartmentCode           = "1",
                    OurReferenceEmployeeCode = 1,
                    ContractNo               = "Test",
                    PurchaseOrderNo          = "Test",
                    CurrencyCode             = "NOK"
                };

                newRecurringInvoice.OutgoingInvoiceLines.Add(new OutgoingInvoiceLine
                {
                    ProductCode   = "1",
                    Description   = "Overridden product description",
                    Quantity      = 15,
                    UnitOfMeasure = "EA",
                    UnitPrice     = 1250,
                    LineType      = VoucherLineType.Normal,
                    SortOrder     = 0
                });


                //Save recurring invoice
                newRecurringInvoice = api.RecurringInvoice.Save(newRecurringInvoice);

                //Get recurring invoice by id
                var recurringInvoiceSaved = api.RecurringInvoice.Get(newRecurringInvoice.Id.Value);
                Console.WriteLine("First recurring invoice:");
                Console.WriteLine($"{recurringInvoiceSaved.CustomerCode} Net:{recurringInvoiceSaved.NetAmount}, Tot:{recurringInvoiceSaved.TotalAmount}.");

                //Edit recurring invoice by adding another line, changing the send method and setting it to active
                recurringInvoiceSaved.SendMethod = RecurringSendMethod.Send;
                recurringInvoiceSaved.IsActive   = true;
                recurringInvoiceSaved.OutgoingInvoiceLines.Add(new OutgoingInvoiceLine
                {
                    LineType    = VoucherLineType.Text,
                    Description = "Additional description",
                    SortOrder   = int.MaxValue //want this line to be the last line, therefore setting sort order to int max
                });

                //Post changes
                api.RecurringInvoice.Save(recurringInvoiceSaved);

                //Delete recurring invoice
                api.RecurringInvoice.Delete(recurringInvoiceSaved);
            }
            catch (ApiException e)
            {
                Console.WriteLine("Error: " + e.Message);
            }

            Console.WriteLine("Done. Press any key to exit...");
            Console.ReadKey();
        }