private async void ReadFromBilagscan(UnicontaBaseEntity selectedItem)
        {
#if !SILVERLIGHT
            if (!readingFromBilagscan)
            {
                readingFromBilagscan = true;

                bool processLines = false;
                var  accessToken  = await Bilagscan.Account.GetBilagscanAccessToken(api);

                var noOfVouchers    = 0;
                var companySettings = await api.Query <CompanySettingsClient>();

                var orgNo = companySettings.FirstOrDefault()._OrgNumber;

                var journal = dgGldailyJournal.SelectedItem as GLDailyJournalClient;

                //  UnicontaBaseEntity[] baseEntityArray = new UnicontaBaseEntity[1] { selectedItem };

                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    var response = await client.GetAsync($"https://api.bilagscan.dk/v1/organizations/" + orgNo.ToString() + "/vouchers?seen=false&count=100&offset=0&sorts=-upload_date&status=successful");

                    var content = await response.Content.ReadAsStringAsync();

                    var vouchers = Bilagscan.Voucher.GetVouchers(content);

                    var credCache = api.CompanyEntity.GetCache(typeof(Uniconta.DataModel.Creditor)) ?? await api.CompanyEntity.LoadCache(typeof(Uniconta.DataModel.Creditor), api);

                    var offsetCache = api.CompanyEntity.GetCache(typeof(Uniconta.DataModel.GLAccount)) ?? await api.CompanyEntity.LoadCache(typeof(Uniconta.DataModel.GLAccount), api);

                    var vouchersSeen = new CommaDelimitedStringCollection();

                    var master = new List <UnicontaBaseEntity>
                    {
                        journal
                    };

                    var newLines       = new List <UnicontaBaseEntity>();
                    var updateCreditor = new List <UnicontaBaseEntity>();

                    if (vouchers?.data != null)
                    {
                        var creditors = credCache.GetKeyStrRecords as Uniconta.DataModel.Creditor[];

                        foreach (var voucher in vouchers.data)
                        {
                            vouchersSeen.Add(NumberConvert.ToString(voucher.id));
                            var journalLine = new GLDailyJournalLineClient()
                            {
                                Approved        = false,
                                ForceSettlement = false
                            };

                            var postingType = BilagscanVoucherType.Invoice;

                            var hint = Bilagscan.Voucher.GetHint(voucher.note);

                            var bilagscanRefID = voucher.id;
                            journalLine.ReferenceNumber = bilagscanRefID != 0 ? NumberConvert.ToString(bilagscanRefID) : null;

                            var bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "voucher_number", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                journalLine.Invoice = bsItem.value;
                            }

                            bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "voucher_type", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                switch (bsItem.value)
                                {
                                case "invoice": postingType = BilagscanVoucherType.Invoice; break;

                                case "creditnote": postingType = BilagscanVoucherType.Creditnote; break;

                                case "receipt": postingType = BilagscanVoucherType.Receipt; break;
                                }
                            }

                            var creditorCVR = string.Empty;
                            bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "company_vat_reg_no", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                creditorCVR = bsItem.value;
                            }

                            bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "total_amount_incl_vat", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                journalLine.Amount = Math.Abs(NumberConvert.ToDoubleNoThousandSeperator(bsItem.value));

                                if (postingType != BilagscanVoucherType.Creditnote)
                                {
                                    journalLine.Amount = -journalLine.Amount;
                                }
                            }

                            CountryCode countryCode = CountryCode.Denmark;
                            bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "country", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                CountryISOCode countryISO;
                                countryCode = CountryCode.Denmark; //default
                                if (Enum.TryParse(bsItem.value, true, out countryISO))
                                {
                                    countryCode = (CountryCode)countryISO;
                                }
                            }

                            bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "invoice_date", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                var invoiceDate = bsItem.value == string.Empty ? GetSystemDefaultDate() : StringSplit.DateParse(bsItem.value, DateFormat.ymd);
                                journalLine.Date = invoiceDate;

                                if (journalLine.Date == DateTime.MinValue)
                                {
                                    journalLine.Date = GetSystemDefaultDate();
                                }
                            }

                            bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "payment_date", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                var paymentDate = bsItem.value == string.Empty ? DateTime.MinValue : StringSplit.DateParse(bsItem.value, DateFormat.ymd);
                                journalLine._DueDate = paymentDate;
                            }

                            bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "currency", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                Currencies currencyISO;
                                if (!Enum.TryParse(bsItem.value, true, out currencyISO))
                                {
                                    currencyISO = Currencies.DKK; //default
                                }
                                journalLine._Currency = (byte)currencyISO;
                            }

                            string bbanAcc = null;
                            bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "payment_account_number", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                bbanAcc = bsItem.value;
                            }

                            string bbanRegNum = null;
                            bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "payment_reg_number", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                bbanRegNum = bsItem.value;
                            }

                            string ibanNo = null;
                            bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "payment_iban", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                ibanNo = bsItem.value;
                            }

                            string swiftNo = null;
                            bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "payment_swift_bic", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                swiftNo = bsItem.value;
                            }

                            string paymentCodeId = null;
                            bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "payment_code_id", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                paymentCodeId = bsItem.value;
                            }

                            string paymentId = null;
                            bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "payment_id", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                paymentId = bsItem.value;
                            }

                            string jointPaymentId = null;
                            bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "joint_payment_id", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                jointPaymentId = bsItem.value;
                            }

                            var paymentMethod = PaymentTypes.VendorBankAccount;
                            switch (paymentCodeId)
                            {
                            case "71": paymentMethod = PaymentTypes.PaymentMethod3; break;

                            case "73": paymentMethod = PaymentTypes.PaymentMethod4; break;

                            case "75": paymentMethod = PaymentTypes.PaymentMethod5; break;

                            case "04":
                            case "4": paymentMethod = PaymentTypes.PaymentMethod6; break;
                            }

                            if (paymentMethod != PaymentTypes.VendorBankAccount && (paymentId != null || jointPaymentId != null))
                            {
                                journalLine._PaymentMethod = paymentMethod;
                                journalLine._PaymentId     = string.Format("{0} +{1}", paymentId, jointPaymentId);
                            }
                            else if (bbanRegNum != null && bbanAcc != null)
                            {
                                journalLine._PaymentMethod = PaymentTypes.VendorBankAccount;
                                journalLine._PaymentId     = string.Format("{0}-{1}", bbanRegNum, bbanAcc);
                            }
                            else if (swiftNo != null && ibanNo != null)
                            {
                                journalLine._PaymentMethod = PaymentTypes.IBAN;
                                journalLine._PaymentId     = ibanNo;
                            }

                            journalLine.SettleValue = "Voucher";

                            Uniconta.DataModel.Creditor creditor = null;

                            if (hint != null)
                            {
                                journalLine._DocumentRef = hint.RowId;
                                //if (hint.CreditorAccount != null)
                                //    creditor = (Uniconta.DataModel.Creditor)credCache.Get(hint.CreditorAccount);
                                //if (hint.Amount != 0)
                                //    journalLine.Amount = hint.Amount;
                                //if (hint.Currency != null && hint.Currency != "-")
                                //    journalLine.Currency = hint.Currency;
                                //if (hint.PaymentId != null)
                                //{
                                //    journalLine._PaymentId = hint.PaymentId;
                                //    journalLine.PaymentMethod = hint.PaymentMethod;
                                //}
                            }

                            journalLine._AccountType = 2;

                            var creditorCVRNum = Regex.Replace(creditorCVR, "[^0-9]", string.Empty);

                            if (creditorCVRNum != string.Empty)
                            {
                                creditor = creditors.Where(s => (Regex.Replace(s._LegalIdent ?? string.Empty, "[^0-9.]", "") == creditorCVRNum)).FirstOrDefault();
                            }

                            if (creditorCVRNum == string.Empty)
                            {
                                journalLine.Text = Uniconta.ClientTools.Localization.lookup("NotValidVatNo");
                            }
                            else if (creditor == null)
                            {
                                var newCreditor = new CreditorClient()
                                {
                                    _Account       = creditorCVR,
                                    _LegalIdent    = creditorCVR,
                                    _PaymentMethod = journalLine._PaymentMethod,
                                    _PaymentId     = journalLine._PaymentId,
                                    _SWIFT         = swiftNo
                                };

                                CompanyInfo companyInformation = null;
                                try
                                {
                                    companyInformation = await CVR.CheckCountry(creditorCVR, countryCode);
                                }
                                catch (Exception ex)
                                {
                                    UnicontaMessageBox.Show(ex);
                                    return;
                                }

                                if (companyInformation != null)
                                {
                                    if (companyInformation.life != null)
                                    {
                                        newCreditor._Name = companyInformation.life.name;
                                    }

                                    if (companyInformation.address != null)
                                    {
                                        newCreditor._Address1 = companyInformation.address.CompleteStreet;
                                        newCreditor._ZipCode  = companyInformation.address.zipcode;
                                        newCreditor._City     = companyInformation.address.cityname;
                                        newCreditor._Country  = companyInformation.address.Country;
                                    }

                                    if (companyInformation.contact != null)
                                    {
                                        newCreditor._Phone        = companyInformation.contact.phone;
                                        newCreditor._ContactEmail = companyInformation.contact.email;
                                    }

                                    journalLine.Text = newCreditor.Name;
                                }
                                else
                                {
                                    newCreditor.Name = Uniconta.ClientTools.Localization.lookup("NotValidVatNo");
                                }

                                await api.Insert(newCreditor);

                                journalLine.Account = creditorCVR;
                            }
                            else
                            {
                                if (!string.IsNullOrEmpty(creditor._PostingAccount))
                                {
                                    var account = (GLAccountClient)offsetCache.Get(creditor._PostingAccount);
                                    if (!string.IsNullOrEmpty(account.Vat))
                                    {
                                        var dailyJournal = (GLDailyJournalClient)master[0];
                                        if (dailyJournal.TwoVatCodes)
                                        {
                                            journalLine._OffsetVat = account.Vat;
                                        }
                                        else
                                        {
                                            journalLine._Vat = account.Vat;
                                        }
                                    }

                                    journalLine._OffsetAccount = creditor._PostingAccount;
                                }
                                else
                                {
                                    journalLine.Vat = creditor._Vat;
                                }


                                if (journalLine._DueDate == DateTime.MinValue && creditor._Payment != string.Empty)
                                {
                                    var paymentTermsCache = api.GetCache(typeof(PaymentTerm)) ?? await api.LoadCache(typeof(PaymentTerm));

                                    var paymentTerm = (PaymentTerm)paymentTermsCache.Get(creditor._Payment);

                                    if (paymentTerm != null)
                                    {
                                        journalLine._DueDate = paymentTerm.GetDueDate(journalLine.DueDate);
                                    }
                                }

                                journalLine.Account = creditor._Account;
                                journalLine.Text    = creditor._Name;

                                if (creditor._SWIFT == null && swiftNo != null)
                                {
                                    creditor._SWIFT = swiftNo;
                                    updateCreditor.Add(creditor);
                                }
                            }

                            journalLine.SetMaster(master[0]);
                            newLines.Add(journalLine);

                            noOfVouchers += 1;
                        }
                    }
                    var errorCode = await api.Insert(newLines);

                    api.UpdateNoResponse(updateCreditor);

                    if (vouchersSeen.Count != 0)
                    {
                        // Mark voucher as seen
                        string serializedRequest = "{ \"vouchers\": [ " + vouchersSeen.ToString() + " ] }";
                        var    vContent          = new StringContent(serializedRequest, Encoding.UTF8, "application/json");
                        response = await client.PostAsync($"https://api.bilagscan.dk/v1/organizations/" + NumberConvert.ToString(orgNo) + "/vouchers/seen", vContent);

                        var res = await response.Content.ReadAsStringAsync();
                    }
                }

                if (noOfVouchers == 0)
                {
                    UnicontaMessageBox.Show(string.Format(Uniconta.ClientTools.Localization.lookup("StillProcessingTryAgain"), Uniconta.ClientTools.Localization.lookup("Bilagscan")), Uniconta.ClientTools.Localization.lookup("Bilagscan"), MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    var messageText = string.Concat(string.Format("{0} {1}", Uniconta.ClientTools.Localization.lookup("NumberOfImportedVouchers"), noOfVouchers),
                                                    Environment.NewLine, Environment.NewLine,
                                                    string.Format(Uniconta.ClientTools.Localization.lookup("GoTo"), Uniconta.ClientTools.Localization.lookup("Journallines")), "?");
                    if (UnicontaMessageBox.Show(messageText, Uniconta.ClientTools.Localization.lookup("BilagscanRead"), MessageBoxButton.OKCancel, MessageBoxImage.Information) == MessageBoxResult.OK)
                    {
                        AddDockItem(TabControls.GL_DailyJournalLine, journal, null, null, true);
                    }
                }
                readingFromBilagscan = false;
            }
#endif
        }
        private async void TxtCVR_EditValueChanged(object sender, DevExpress.Xpf.Editors.EditValueChangedEventArgs e)
        {
            var s = sender as TextEditor;

            if (s != null && s.IsLoaded)
            {
                var cvr = s.Text?.Trim();
                if (cvr == null || cvr.Length < 5)
                {
                    return;
                }

                var allIsLetter = cvr.All(x => char.IsLetter(x));
                if (allIsLetter)
                {
                    return;
                }
                CompanyInfo ci = null;
                try
                {
#if !SILVERLIGHT
                    ci = await CVR.CheckCountry(cvr, editrow._Country);
#else
                    var lookupApi = new Uniconta.API.System.UtilityAPI(api);
                    ci = await lookupApi.LookupCVR(cvr, editrow._Country);
#endif
                }
                catch (Exception ex)
                {
                    UnicontaMessageBox.Show(ex);
                    return;
                }
                if (!onlyRunOnce)
                {
                    if (ci == null)
                    {
                        return;
                    }

                    if (!string.IsNullOrWhiteSpace(ci?.life?.name))
                    {
                        var address = ci.address;
                        if (address != null)
                        {
                            var streetAddress = address.CompleteStreet;
                            if (ci.life.name == editrow._Name && streetAddress == editrow._Address1 &&
                                address.zipcode == editrow._ZipCode)
                            {
                                return; // we wil not override since address has not changed
                            }
                            onlyRunOnce = true;
                            if (editrow._Address1 == null)
                            {
                                editrow.Address1 = address.CompleteStreet;
                                editrow.ZipCode  = address.zipcode;
                                editrow.City     = address.cityname;
                                editrow.Country  = address.Country;
                            }
                            else
                            {
                                var result = UnicontaMessageBox.Show(Uniconta.ClientTools.Localization.lookup("UpdateAddress"), Uniconta.ClientTools.Localization.lookup("Information"), UnicontaMessageBox.YesNo);
                                if (result != UnicontaMessageBox.Yes)
                                {
                                    return;
                                }
                                {
                                    editrow.Address1 = address.CompleteStreet;
                                    editrow.ZipCode  = address.zipcode;
                                    editrow.City     = address.cityname;
                                    editrow.Country  = address.Country;
                                }
                            }
                        }

                        if (string.IsNullOrWhiteSpace(editrow._Name))
                        {
                            editrow.Name = ci.life.name;
                        }

                        var contact = ci.contact;
                        if (contact != null)
                        {
                            editrow.Phone        = contact.phone;
                            editrow.ContactEmail = contact.email;
                            editrow.Www          = contact.www;
                        }
                    }
                }
                else
                {
                    onlyRunOnce = false;
                }
            }
        }
        private async void txtCVR_OnEditValueChanged(object sender, EditValueChangedEventArgs e)
        {
            var s = sender as TextEditor;

            if (s != null && s.IsLoaded)
            {
                var cvr = s.Text?.Trim();
                if (cvr == null || cvr.Length < 5)
                {
                    return;
                }

                var allIsLetter = cvr.All(x => char.IsLetter(x));
                if (allIsLetter)
                {
                    return;
                }

                CompanyInfo ci = null;
                try
                {
#if !SILVERLIGHT
                    ci = await CVR.CheckCountry(cvr, editrow.Country);
#else
                    var lookupApi = new Uniconta.API.System.UtilityAPI(api);
                    ci = await lookupApi.LookupCVR(cvr, editrow.Country);
#endif
                }
                catch (Exception ex)
                {
                    UnicontaMessageBox.Show(ex);
                    return;
                }

                if (!onlyRunOnce)
                {
                    if (ci == null)
                    {
                        return;
                    }

                    if (!string.IsNullOrWhiteSpace(ci?.life?.name))
                    {
                        var address = ci.address;
                        if (address != null)
                        {
                            onlyRunOnce = true;
                            var streetAddress = address.CompleteStreet;
                            if (string.IsNullOrWhiteSpace(editrow.Address1))
                            {
                                editrow.Address1 = streetAddress;
                                editrow.Address2 = address.ZipCity;
                                editrow.Country  = address.Country;
                            }
                            else
                            {
                                var result = UnicontaMessageBox.Show(Uniconta.ClientTools.Localization.lookup("UpdateAddress"), Uniconta.ClientTools.Localization.lookup("Information"), UnicontaMessageBox.YesNo);
                                if (result != UnicontaMessageBox.Yes)
                                {
                                    return;
                                }
                                {
                                    editrow.Address1 = streetAddress;
                                    editrow.Address2 = address.ZipCity;
                                    editrow.Country  = address.Country;
                                }
                            }
                        }
                        if (string.IsNullOrWhiteSpace(editrow._Name))
                        {
                            editrow._Name = ci.life.name;
                        }

                        if (!string.IsNullOrEmpty(ci.contact?.phone))
                        {
                            editrow.Phone = ci.contact.phone;
                        }
                    }
                }
                else
                {
                    onlyRunOnce = false;
                }
            }
        }