示例#1
0
        private void Save()
        {
            AppJournal.Write("Lot", "Save", true);

            try {
                if (Lot.filelistid == null)
                {
                    Lot.filelistid = DataBaseClient.CreateFileList(new FilesListEF()
                    {
                        description = "Файлы лота"
                    });
                }

                if (Lot.id != 0)
                {
                    DataBaseClient.UpdateLot(Lot);
                }
                else
                {
                    UpdateView(DataBaseClient.CreateLot(Lot));
                }

                auctionViewModel.UpdateLotList();
                MessagesService.Show("Сохранение лота", "Лот успешно сохранен");
                Workspace.This.Panels.Remove(Workspace.This.ActiveDocument);
            } catch (Exception ex) {
                MessagesService.Show("Сохранение лота", "Произошла ошибка во время сохранения");
                AppJournal.Write("Lot", "Saving error :" + ex.ToString(), true);
            }
        }
示例#2
0
        private void DefaultParametrs(LotEF lot = null, bool refresh = false)
        {
            if (!refresh)
            {
                UnitList = DataBaseClient.ReadUnits();
            }

            if (lot == null)
            {
                Lot               = new LotEF();
                Lot.auctionid     = _auctionId;
                Lot.number        = DataBaseClient.ReadAuction(_auctionId).siteid == 4 ? "0G" : "";
                Lot.deliveryplace = "Согласно договору";
                Lot.deliverytime  = "Согласно договору";
                Lot.paymentterm   = "Согласно договору";
                Lot.step          = 1;
                Lot.warranty      = 0.1;
                SelectedUnit      = UnitList[0];
            }
            else
            {
                try {
                    SelectedUnit = UnitList.FirstOrDefault(x => x.id == lot.unitid);
                } catch (Exception) {
                    SelectedUnit = UnitList[0];
                }

                Quantity = Lot.amount;
                Price    = Lot.price;
                Sum      = Lot.sum;
                Lot      = Lot;
            }
        }
示例#3
0
        public ActionResult AuctionOrder()
        {
            var auctionOrderModel = new AuctionOrderModel();

            // Default settings
            auctionOrderModel.Count         = "0";
            auctionOrderModel.Price         = "0";
            auctionOrderModel.Amount        = "0";
            auctionOrderModel.MinimalSum    = "0";
            auctionOrderModel.Step          = "1";
            auctionOrderModel.TradeWarranty = "1";
            auctionOrderModel.Percent       = "0";
            auctionOrderModel.DeliveryTerm  = "DDP";
            auctionOrderModel.DeliveryPlace = "г. Семей, ул. Би Боронбай, 93";
            auctionOrderModel.DeliveryTime  = "Согласно договору";
            auctionOrderModel.Payment       = "По факту";

            try {
                auctionOrderModel.units = DataBaseClient.GetUnits();
                LogService.LogInfo("AuctionOrder page opened");
            } catch (Exception ex) {
                LogService.LogInfo("AuctionOrder page opened with error: " + ex);
                return(null);
            }

            return(View(auctionOrderModel));
        }
        private static void FillTemplateFile()
        {
            word = new WordService(orderFileName, false);

            try {
                word.FindReplace("[orderNumber]", orderInfo.Title);
                word.FindReplace("[auctionDate]", orderInfo.Auction.Date.ToShortDateString());

                word.SetCell(1, 2, 1, "1");
                word.SetCell(1, 2, 2, lotInfo.description);
                word.SetCell(1, 2, 3, lotInfo.amount.ToString(CultureInfo.InvariantCulture));
                word.SetCell(1, 2, 4, DataBaseClient.ReadUnitInfo(lotInfo.unitid).name);
                word.SetCell(1, 2, 5, lotInfo.price.ToString(CultureInfo.InvariantCulture));
                word.SetCell(1, 2, 6, lotInfo.sum.ToString(CultureInfo.InvariantCulture));
                word.SetCell(1, 2, 7, lotInfo.step.ToString(CultureInfo.InvariantCulture));
                word.SetCell(1, 2, 8, lotInfo.deliveryplace);
                word.SetCell(1, 2, 9, lotInfo.paymentterm);
                word.SetCell(1, 2, 10, lotInfo.warranty.ToString(CultureInfo.InvariantCulture));
                word.SetCell(1, 2, 11, lotInfo.localcontent.ToString());
                word.SetCell(1, 3, 6, lotInfo.sum.ToString(CultureInfo.InvariantCulture));
            } catch (Exception) {
                // ignored
            }

            word.CloseDocument(true);
            word.CloseWord(true);
        }
示例#5
0
        public FileResult GetProtocolFile(string auctionDate, string auctionNumber)
        {
            var protocolFile = DataBaseClient.ReadDocument((int)DataBaseClient.ReadAuctions().FirstOrDefault(a => a.siteid == 5 && a.number == auctionNumber).fileslistid, (int)DocumentTypeEnum.Protocol);

            if (protocolFile != null)
            {
                var filePath = @"Y:\Auctions\KazETS\" + auctionDate + "\\" + auctionNumber.Replace("/", "_") + "\\";

                string[] files = Directory.GetFiles(filePath, protocolFile.name + "." + protocolFile.extension);
                if (files.Length > 0)
                {
                    filePath = files[0];

                    if (System.IO.File.Exists(filePath))
                    {
                        LogService.LogInfo("Report file for auction date " + auctionDate + " with № " + auctionNumber + " successfuly downloaded");
                        return(File(filePath, System.Net.Mime.MediaTypeNames.Application.Octet, "Протокол по аукциону №" + auctionNumber.Replace("/", "_") + "." + protocolFile.extension));
                    }
                    else
                    {
                        LogService.LogInfo("Report file loading error");
                        return(null);
                    }
                }
            }

            return(null);
        }
        private static void ChangeStatusesToSO(int auctionId, int supplierOrderId)
        {
            foreach (var item in DataBaseClient.ReadSupplierOrders(auctionId))
            {
                if (item.statusid != 16 && item.statusid != 23)
                {
                    item.statusid = 24;

                    try {
                        DataBaseClient.UpdateSupplierOrder(item);
                    } catch { }
                }
            }

            var soItem = DataBaseClient.ReadSupplierOrder(supplierOrderId);

            if (soItem != null)
            {
                soItem.statusid = 23;

                try {
                    DataBaseClient.UpdateSupplierOrder(soItem);
                } catch { }
            }
        }
        public static void CreateReport(string template, Report report, int type)
        {
            archiveManager = new ArchiveManager(dataManager);
            var service = new WordService(template, false);

            service = type == 2 ? InsertIntoSupplierReport(report, service) : InsertIntoClientReport(report, service);
            var fileListId = DataBaseClient.GetFileListAuctionByLot(report.Code);

            if (fileListId != null)
            {
                DocumentRequisite docReq = new DocumentRequisite()
                {
                    date     = fileListId.date,
                    fileName = template.Substring(template.LastIndexOf("\\") + 1),
                    market   = AltaBO.specifics.MarketPlaceEnum.ETS,
                    number   = fileListId.number,
                    section  = AltaBO.specifics.DocumentSectionEnum.Auction,
                    type     = type == 2 ? AltaBO.specifics.DocumentTypeEnum.SupplierReport : AltaBO.specifics.DocumentTypeEnum.CustomerReport
                };

                archiveManager.SaveFile(docReq, (int)fileListId.fileslistid);
                docReq.fileName = docReq.fileName.Replace(".docx", ".pdf");
                archiveManager.SaveFile(docReq, (int)fileListId.fileslistid);
            }

            service.SaveAsPDF(template);
            service.CloseDocument(true);
            service.CloseWord(true);
        }
        private void ExcludeDoc()
        {
            int selOthDoc = SelectedEnvelopContent.otherdocid;

            var listServStatus = DataBaseClient.ReadEnvelopContentList();

            if (listServStatus != null)
            {
                if (listServStatus.FirstOrDefault(l => l.otherdocid == selOthDoc).listserv.statusid != 14)
                {
                    if (!DataBaseClient.DeleteEnvelopContent(selOthDoc))
                    {
                        MessagesService.Show("Оповещение", "Произошла ошибка при исключении документа из реестра.");
                    }
                    else
                    {
                        try
                        {
                            UpdateEnvelopContent();
                        }
                        catch { }
                    }
                }
                else
                {
                    MessagesService.Show("Оповещение", "Конверт в статусе отправлен.");
                }
            }
        }
        private async void SetCode()
        {
            // Check for selected
            if (SelectedEnvelop != null)
            {
                // Get code from user
                string code = await MessagesService.GetInput("Установка ШПИ", "Введите код");

                if (!string.IsNullOrEmpty(code))
                {
                    // Update record in base & update view
                    if (DataBaseClient.UpdateEnvelop(SelectedEnvelop.id, code))
                    {
                        EnvelopsList = DataBaseClient.ReadEnvelopsList(SelectedListServ.id);
                    }
                    else
                    {
                        MessagesService.Show("Оповещение", "Произошла ошибка при присвоении ШПИ");
                    }
                }
            }
            else
            {
                MessagesService.Show("Оповещение", "Не выбран конверт");
            }
        }
示例#10
0
        private void DefaultParametrs()
        {
            DocDetailsVis = Visibility.Collapsed;
            IncludeVis    = Visibility.Collapsed;
            ExcludeVis    = Visibility.Collapsed;

            DateStart = DateTime.Now.AddDays(-60);
            DateEnd   = DateTime.Now;

            BrokersList = DataBaseClient.ReadBrokers().Where(b => b.id != 3).OrderByDescending(b => b.id).ToList();

            foreach (var item in BrokersList)
            {
                item.name = item.name.Replace("Товарищество с ограниченной ответственностью", "ТОО");
            }

            SelectedBroker    = BrokersList[0];
            SelectedDefBroker = BrokersList[0];
            DocTypesList      = DataBaseClient.ReadDocumentTypes(31, 42, 21);

            DocTypesList.Insert(9, DocTypesList.FirstOrDefault(d => d.id == 21));
            DocTypesList.RemoveAt(0);

            SelectedDocType = DocTypesList[0];
            DocQuantity     = 1;

            UpdateCompaniesList();
        }
        private void DeleteEnvelop()
        {
            // Check for selected and for listserv status
            if (SelectedEnvelop != null && SelectedListServ != null && SelectedListServ.statusid != 14)
            {
                // Delete all envelop content with change otherdocs status
                if (EnvelopContentList != null && EnvelopContentList.Count > 0)
                {
                    foreach (var item in EnvelopContentList)
                    {
                        // Change otherdocs status & delete envelop content
                        DataBaseClient.DeleteEnvelopContent(item.otherdocid);
                    }
                }

                // Delete envelop
                DataBaseClient.DeleteEnvelop(SelectedEnvelop.id);

                // Update views
                UpdateEnvelopList();
            }
            else
            {
                MessagesService.Show("Оповещение", "Не выполненно одно из условий:\n1. Не выбран конверт\n2. Реестр в статусе отправлен");
            }
        }
        private void UpdateAuctionsList(DateTime fromDate, DateTime toDate, int site, int statusId, int traderId, string searchText = null)
        {
            AppJournal.Write("Auctions List", "Update get auctions and check new orders from base", true);

            try {
                if (string.IsNullOrEmpty(searchText))
                {
                    AuctionsList = DataBaseClient.ReadAuctions(fromDate.AddDays(-1), toDate, site, statusId, traderId);
                }
                else
                {
                    AuctionsList = DataBaseClient.ReadAuctions(fromDate.AddDays(-1), toDate, site, statusId, traderId, searchText);
                }
            } catch (Exception ex) { AppJournal.Write("Auctions List", "Get auctions list from base error: " + ex.ToString(), true); }

            try {
                NewOrders = DataBaseClient.GetOrders(site, 1);
            } catch (Exception ex) { AppJournal.Write("Orders List", "Get new orders list from error: " + ex.ToString(), true); }

            if (NewOrders.Count > 0)
            {
                NewOrdersVis = System.Windows.Visibility.Visible;
            }
            else
            {
                NewOrdersVis = System.Windows.Visibility.Collapsed;
            }
        }
示例#13
0
        public virtual String execute()
        {
            try
            {
                //读取配置
                DataBaseConfig config   = Config.getConfig.dataBaseConfig[getDataBaseName()];
                Identity       identity = config[getDataBaseIdentity()];

                //获取数据库控制器
                DataBaseClient db = DataBaseManger.getDataClient(identity);

                //语句
                String sql = getSql();

                //数据表
                DataTable table = db.QueryForTable(sql);

                //装配
                return(getWebServiceDataXML(table));
            }
            catch (Exception e)
            {
                return(getErrorWebServiceDataXML(e.Message));
            }
        }
示例#14
0
        private void UpdateRatesListView()
        {
            AppJournal.Write("Contract", "Update rates list view", true);

            try {
                RatesList = new ObservableCollection <RatesListEF>(DataBaseClient.ReadRatesList(Contract.id));
            } catch (Exception ex) { AppJournal.Write("Contract", "Get rates list from db error :" + ex.ToString(), true); }
        }
示例#15
0
        private void UpdateRateView()
        {
            AppJournal.Write("Contract", "Update rate list view", true);

            try {
                Rates = new ObservableCollection <RateEF>(DataBaseClient.ReadRates(SelectedRatesList.id).OrderBy(o => o.transaction));
            } catch (Exception ex) { AppJournal.Write("Contract", "Get rates from db error :" + ex.ToString(), true); }
        }
示例#16
0
        public ActionResult EconomySumGraph()
        {
            ordersList = DataBaseClient.GetKarazhiraAuctions(2);

            LogService.LogInfo("EconomySumGraph page opened");

            return(View(ordersList));
        }
        private void DefaultParametrs()
        {
            IsDropDown  = false;
            BrokersList = DataBaseClient.ReadBrokers();

            StartDate = DateTime.Now.AddYears(-1);
            EndDate   = DateTime.Now;
        }
        public void UpdateCompaniesList()
        {
            AppJournal.Write("Companies", "Update list", true);

            try {
                CompaniesList = DataBaseClient.ReadCompanies();
            } catch (Exception ex) { AppJournal.Write("Companies", "Get companies from db error :" + ex.ToString(), true); }
        }
示例#19
0
        private void DefaultParametrs(ContractEF contract = null, bool refresh = false)
        {
            if (!refresh)
            {
                archiveManager    = new ArchiveManager(dataManager);
                BanksList         = DataBaseClient.ReadBanks();
                ContractTypesList = DataBaseClient.ReadContractTypes();
                CurrenciesList    = DataBaseClient.ReadCurrencies();
                BrokersList       = DataBaseClient.ReadBrokers();
                AuthorsList       = DataBaseClient.ReadTraders();

                RangeList = new List <string>();
                RangeList.Add("От 1 ");
                RangeList.Add("От 20.000 тсч.");
                RangeList.Add("От 1.000.000 млн.");
                RangeList.Add("От 5.000.000 млн.");
                RangeList.Add("От 10.000.000 млн.");
                RangeList.Add("От 15.000.000 млн.");
                RangeList.Add("От 25.000.000 млн.");
                RangeList.Add("От 40.000.000 млн.");
                RangeList.Add("От 50.000.000 млн.");
                RangeList.Add("От 75.000.000 млн.");
                RangeList.Add("От 100.000.000 млн.");
                RangeList.Add("От 1.000.000.000 млрд.");
                SelectedRange = RangeList[0];

                ScanTypesList = new List <string>();
                ScanTypesList.Add("Копия");
                ScanTypesList.Add("Оригинал");
            }

            if (contract == null)
            {
                Contract               = new ContractEF();
                Contract.companyid     = companyId;
                Contract.agreementdate = DateTime.Now;
                SelectedContractType   = ContractTypesList[0];
                SelectedCurrency       = CurrenciesList[0];
                SelectedScanType       = ScanTypesList[0];
            }
            else
            {
                try {
                    if (contract.bankid != null)
                    {
                        SelectedBank = BanksList.Where(x => x.id == contract.bankid).FirstOrDefault();
                        SearchTxt    = SelectedBank.name;
                    }

                    SelectedContractType = ContractTypesList.Where(x => x.id == (contract.contracttypeid == null ? 1 : contract.contracttypeid)).FirstOrDefault();
                    SelectedCurrency     = CurrenciesList.Where(x => x.id == contract.currencyid).FirstOrDefault();
                    SelectedBroker       = BrokersList.Where(x => x.id == contract.brokerid).FirstOrDefault();
                    RatesList            = new ObservableCollection <RatesListEF>(DataBaseClient.ReadRatesList(Contract.id));
                    SelectedAuthor       = AuthorsList.FirstOrDefault(a => a.id == (contract.authorid == null ? 1 : contract.authorid));
                    SelectedScanType     = ScanTypesList[(contract.scantype == null ? 0 : (int)contract.scantype)];
                } catch (Exception) { }
            }
        }
示例#20
0
        public void UpdateContractList()
        {
            AppJournal.Write("Company", "Update contracts list", true);

            try
            {
                ContractsList = DataBaseClient.ReadContracts(Company.id);
            }
            catch (Exception ex) { AppJournal.Write("Company", "Get contracts list from db error :" + ex.ToString(), true); }
        }
示例#21
0
        private void UpdateC01List()
        {
            AppJournal.Write("Company", "Update c01 list", true);

            try
            {
                C01List = DataBaseClient.ReadSuppliersJournals(DataBaseClient.GetSupplierId(Company.id));
            }
            catch (Exception ex) { AppJournal.Write("Company", "Get c01 from db error :" + ex.ToString(), true); }
        }
示例#22
0
        private void DefaultParametrs(CompanyEF company = null, bool refresh = false)
        {
            IikColor = System.Windows.Media.Brushes.Black;

            if (!refresh)
            {
                archiveManager = new ArchiveManager(dataManager);
                CountriesList  = DataBaseClient.ReadCountries();
            }

            if (company == null)
            {
                Company            = new CompanyEF();
                Company.createdate = DateTime.Now;
                IsSupplier         = true;
            }
            else
            {
                try
                {
                    if (DataBaseClient.ReadSupplier(Company.id) != null)
                    {
                        IsSupplier = true;
                    }
                    if (DataBaseClient.ReadCustomer(Company.id) != null)
                    {
                        IsCustomer = true;
                    }

                    SelectedCountry = CountriesList.Where(x => x.id == company.countryid).FirstOrDefault();
                    ContractsList   = DataBaseClient.ReadContracts(Company.id);
                    C01List         = DataBaseClient.ReadSuppliersJournals(DataBaseClient.GetSupplierId(Company.id));
                    SearchSupplier  = Company.name;

                    if (Company.iik == null)
                    {
                        return;
                    }

                    if (Company.iik.Length < 20)
                    {
                        IikColor = System.Windows.Media.Brushes.Red;
                    }
                    else
                    {
                        IikColor = System.Windows.Media.Brushes.Black;
                    }
                }
                catch (Exception ex)
                {
                    MessagesService.Show("ОШИБКА", "Ошибка загрузки данных для страницы");
                    AppJournal.Write("Company", "Get company info from db error :" + ex.ToString(), true);
                }
            }
        }
        private void DeleteAuction()
        {
            if (SelectedAuction != null)
            {
                try {
                    DataBaseClient.DeleteAuction(SelectedAuction.id);
                } catch (Exception) { MessagesService.Show("ОШИБКА", "Произошла ошибка во время удаления"); }

                UpdateAuctionsList(FromDate, ToDate, SelectedSite.id, SelectedStatus.id, SelectedTrader.id);
            }
        }
示例#24
0
 private void Apply(int mode)
 {
     if (mode == 0)
     {
         ClearingCountingsList = DataBaseClient.ReadClearingCountings(FromDate, ToDate, SelectedStatus.id, SelectedBroker.id);
     }
     else
     {
         ClearingCountingsList = DataBaseClient.ReadClearingCountings(FromDate, ToDate, SelectedStatus.id, SelectedBroker.id, SelectedSupplier.companyId);
     }
 }
 private void UpdateListServ()
 {
     if (string.IsNullOrEmpty(ListServNumber))
     {
         ListServ = DataBaseClient.ReadListServ(StartDate, EndDate);
     }
     else
     {
         ListServ = DataBaseClient.ReadListServ(StartDate, EndDate, Convert.ToInt32(ListServNumber));
     }
 }
示例#26
0
 private bool CheckForSame()
 {
     if (!DataBaseClient.CheckDuplicateContract(Contract))
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
示例#27
0
        public ActionResult AuctionOrder(AuctionOrderModel auctionOrderModel)
        {
            if (ModelState.IsValid)
            {
                Order order = new Order();

                order.Date = DateTime.Now;
                order.Auction.Lots.Add(new Lot {
                    Name          = auctionOrderModel.LotName,
                    Quantity      = Convert.ToDecimal(auctionOrderModel.Count.Replace(".", ",")),
                    UnitId        = auctionOrderModel.UnitId,
                    Price         = Convert.ToDecimal(auctionOrderModel.Price.Replace(".", ",")),
                    Sum           = Convert.ToDecimal(auctionOrderModel.Amount.Replace(".", ",")),
                    Step          = Convert.ToDecimal(auctionOrderModel.Step.Replace(".", ",")),
                    Warranty      = Convert.ToDecimal(auctionOrderModel.TradeWarranty.Replace(".", ",")),
                    LocalContent  = Convert.ToInt32(auctionOrderModel.Percent),
                    DeliveryPlace = auctionOrderModel.DeliveryPlace + "|" + auctionOrderModel.DeliveryTerm,
                    DeliveryTime  = auctionOrderModel.DeliveryTime,
                    PaymentTerm   = auctionOrderModel.Payment
                });

                try {
                    order.Auction.OwnerId = DataBaseClient.GetUserByLogin(HttpContext.User.Identity.Name).Id;
                } catch (Exception) { order.Auction.OwnerId = 1; }

                order.Auction.Comments = auctionOrderModel.MinimalSum + "|" + auctionOrderModel.Comments;

                var statusModel = new StatusModel();

                try {
                    DataBaseClient.SetNewKarazhiraOrder(order);
                    statusModel.Status = 1;
                    EmailSender.Send("*****@*****.**", "ablrzaieneayisqa", "*****@*****.**", "Новая заявка Каражыры от " + DateTime.Now.ToShortDateString() + " по лоту " + order.Auction.Lots[0].Name, "Не забудьте обработать!");
                    LogService.LogInfo("Order created successfuly");
                } catch (Exception ex) {
                    statusModel.Status = 0;
                    LogService.LogInfo("Order created with error: " + ex);
                }

                return(View("CreateStatus", statusModel));
            }
            else
            {
                try {
                    auctionOrderModel.units = DataBaseClient.GetUnits();
                    LogService.LogInfo("AuctionOrder page re-opened because validation summary error");
                } catch (Exception ex) {
                    LogService.LogInfo("AuctionOrder page re-opened with error: " + ex);
                    return(null);
                }

                return(View(auctionOrderModel));
            }
        }
 private void Init()
 {
     FromDate       = DateTime.Now.AddDays(-14);
     ToDate         = DateTime.Now.AddDays(14);
     StatusesList   = DataBaseClient.ReadStatuses().Where(s => s.id < 5).ToList();
     SelectedStatus = StatusesList[3];
     TradersList    = DataBaseClient.ReadTraders();//.Where(t => t.id < 10).ToList();
     SelectedTrader = TradersList[0];
     SitesList      = DataBaseClient.ReadSites().Where(s => s.id == 1 || s.id > 3).ToList();
     SelectedSite   = SitesList.FirstOrDefault(s => s.id == 4);
 }
示例#29
0
        private void UpdateView(int id)
        {
            AppJournal.Write("Lot", "Update view", true);

            try {
                Lot = DataBaseClient.ReadLot(id);
            } catch (Exception ex) { AppJournal.Write("Lot", "Get lot from db error :" + ex.ToString(), true); }

            FormTitle = "Просмотр/редактирование лота";
            DefaultParametrs(Lot, true);
        }
        public static void CreateOrder(Order order, int auctionId, int traderId)
        {
            orderInfo = order;

            orderFileName = ArchiveTransport.PutUTBOrder(order);

            lotInfo = DataBaseClient.UpdateUTBNewOrder(order, auctionId, traderId);

            FillTemplateFile();

            Process.Start("explorer", @"\\192.168.11.5\Archive\Auctions\UTB\" + order.Auction.Date.ToShortDateString() + "\\" + order.Title.Replace("/", "_"));
        }
        //getClusters button will create clusters in excel 
        private void getClusters(object sender, RoutedEventArgs e)
        {

            //start our database connection proxy
            DataBaseClient client = new DataBaseClient();

            DateTime d1 = (DateTime)date1.SelectedDate;
            DateTime d2 = (DateTime)date2.SelectedDate;
            string x_ticker = xcoor.Text;
            string y_ticker = ycoor.Text;
            decimal[] x_vector = client.getPriceArray(x_ticker, d1, d2);
            decimal[] y_vector = client.getPriceArray(y_ticker, d1, d2);
            int k = int.Parse(k_param.Text);

            //generate numerical points from ticker symbols. Encode points to tickers so we can translate back.
            Dictionary<Tuple<decimal, decimal>, string> tuple_ticker = new Dictionary<Tuple<decimal, decimal>, string>(tickers.Length);
            Tuple<decimal, decimal>[] ticker_coords = new Tuple<decimal, decimal>[tickers.Length];

            int count = 0;
            foreach (string symbol in tickers)
            {
                decimal[] price_vector = client.getPriceArray(symbol, d1, d2);
                decimal x = Statistics.correlation(x_vector, price_vector);
                decimal y = Statistics.correlation(y_vector, price_vector);
                Tuple<decimal, decimal> point = new Tuple<decimal, decimal>(x, y);
                ticker_coords[count] = point;
                tuple_ticker[point] = symbol;
                count += 1;
            }
            // cluster the data
            Dictionary<Tuple<decimal, decimal>, Tuple<decimal, decimal>[]> result = Statistics.k_means(ticker_coords, k);

            //re_translate the numerical data back to ticker symbols. 
            //format our data object to be ready for excel
            //each cluster will fill a column. first two rows of each 
            // column will be x and y coordinate of cluster centroid
            var data = new object[tickers.Length + 2, k];

            int i = 2;
            int j = 0;
            foreach (KeyValuePair<Tuple<decimal, decimal>, Tuple<decimal, decimal>[]> entry in result)
            {
                data[0, j] = entry.Key.Item1;
                data[1, j] = entry.Key.Item2;

                foreach (Tuple<decimal, decimal> p in entry.Value)
                {
                    data[i, j] = tuple_ticker[p];
                    i += 1;
                }
                j += 1;
                i = 2;
            }

            // Handles creation of excel workbook and loads the data all at once
            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            Workbook wb = app.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
            Worksheet ws = wb.Worksheets[1];
            var startCell = ws.Cells[1, 1];
            var endCell = ws.Cells[tickers.Length + 2, k];
            var writeRange = ws.Range[startCell, endCell];

            writeRange.Value2 = data;
            app.Visible = true;
            app.WindowState = XlWindowState.xlMaximized;


        }
        //Generates stock correlation matrix from user input params: tickers and daterange
        private void GenerateExcelFile(object sender, RoutedEventArgs e)
        {
            //harvesting user input data for further processing
            string ticker = Tickers.Text;
            char[] delimit = { ',' };

            string[] tickerArray = ticker.Split(delimit);
            DateTime start = (DateTime)Date1.SelectedDate;
            DateTime end = (DateTime)Date2.SelectedDate;



            //creating the correlation matrix and storing it in var data
            int rows = tickerArray.Length + 1;
            int columns = rows;
            var data = new object[rows, columns];
            //preparing the database connection proxy
            DataBaseClient client = new DataBaseClient();
            //matrix is filled in row by row
            for (var row = 1; row <= rows; row++)
            {
                //first row is all ticker headers
                if (row == 1)
                {
                    for (var column = 1; column <= columns; column++)
                    {
                        if (column > 1)
                        {
                            data[row - 1, column - 1] = tickerArray[column - 2];
                        }
                    }
                }
                else
                //all other rows contain correlation coefficents
                {
                    decimal[] stock1 = client.getPriceArray(tickerArray[row - 2], start, end); ;
                    decimal[] stock2;
                    decimal coefficient;
                    for (var column = 1; column <= columns; column++)
                    {
                        if (column == 1)
                        {
                            data[row - 1, column - 1] = tickerArray[row - 2];
                        }
                        //gets price data through database proxy
                        //Then uses statsAPI to get coefficent
                        else if (column >= row)
                        {
                            if (column == row)
                            {
                                data[row - 1, column - 1] = 1;
                            }

                            else
                            {
                                stock2 = client.getPriceArray(tickerArray[column - 2], start, end);
                                coefficient = Statistics.correlation(stock1, stock2);

                                data[row - 1, column - 1] = coefficient;
                            }
                        }
                    }
                    
                }
                
            }
            client.Close();

            // Handles creation of excel workbook and loads the data all at once
            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            Workbook wb = app.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
            Worksheet ws = wb.Worksheets[1];
            var startCell = ws.Cells[1, 1];
            var endCell = ws.Cells[rows, columns];
            var writeRange = ws.Range[startCell, endCell];

            writeRange.Value2 = data;
            app.Visible = true;
            app.WindowState = XlWindowState.xlMaximized;
        }