private void ImportProductButtonClick(object sender, EventArgs e)
        {
            var all = checkBoxAllProducts.Checked;
            var sb = new StringBuilder();
            tradeOutputText.Lines = null;
            var trades = new List<Trade>();
            //var excludeTradeIds = new List<long>();
            var folderName = textBoxTradeFolder.Text;
            var ccys = Utilities.ToList(checkedComboBoxEditCurrency.Text);
            //var tranIds = Utilities.ToList(textBoxTransIds.Text);               // ??
            var stgys = Utilities.ToList(checkedComboBoxEditStrategy.Text);     // disabled
            var les = Utilities.ToList(checkedComboBoxEditLegalEntity.Text);    // disabled
            var sources = Utilities.ToList(checkedComboBoxEditSources.Text.ToLower());
            var liveDate = GetLiveDate();
            importProductButton.Enabled = false;
            buttonCancel.Enabled = true;
            bool onlyNewTrade = checkBoxnlyNewTrade.Checked;

            var progress = new ImportProgress { ProgressBar = saveProgressBar, IsCanceled = false };
            importProductButton.Tag = progress;

            var filterData = new FilterData
            {
                Currencies = ccys,
                //TransIds = tranIds,
                OnlyNewTrades = onlyNewTrade,
                LiveDate = liveDate,
                Strategies = stgys,
                Progress = progress,
                FolderName = folderName
            };

            var existIds = Env.Current.Trade.GetTradePropertyValues(TradeImportHelper.SymmetryTranId, false);
            filterData.ExistingTransIds = new List<string>();
            filterData.ExistingIds = new List<string>();
            foreach (var id in existIds.Keys) filterData.ExistingTransIds.Add(id);

            tradeOutputText.Text = "";
            var feed = checkBoxUseFeed.Checked ? GetFeed() : null;
            // if (TradeImportHelper.NewMethod) filterData.Data = TradeImportHelper.LoadFile(fileName, filterData);
            var market = GetMarket();
            var importers = BuildImporters();
            var thread = new Thread(() =>
            {
                try
                {
                    var lst = new List<string>();
                    lst.AddRange(all ? AllProducTypes : Utilities.ToList(checkedComboBoxEditProduct.Text).ToArray());
                    string[] files = Directory.GetFiles(filterData.FolderName, "*.csv");
                    var filesSorted = SortFiles(files, sources);        // remove not used and sort files in the folder
                    foreach (var f in filesSorted)
                    {
                        filterData.FolderName = f;        // replace with file name
                        filterData.Data = null;

                        sb.Append("-------- Importing from " + Path.GetFileName(f) +
                                      " --------\n");
                        foreach (var ci in lst)
                        {
                            if (progress.IsCanceled) return;


                            Invoke(new MethodInvoker(() =>
                            {
                                tradeOutputText.AppendText(" Importing " + ci + "\n");
                            }));
                            ITradeImportHelper importer;
                            if (importers.TryGetValue(ci, out importer))
                            {
                                trades.AddRange(importer.Import(market, feed, sb, filterData));
                            }
                            else
                            {
                                Logger.Error("Cannot Find Importer for " + ci);
                            }
                        }

                    }

                    //Filter Trades
                    //var newtrades = trades.Where(t => t.Id <= 0 || t.Status != "Matured").ToList();
                    //trades = newtrades;
                    /*
                    var ssb = new StringBuilder();
                    foreach (var s in filterData.MissingEntities)
                    {
                        ssb.Append("Missing Entity " + s + "\n");
                        sb.Append("Missing Entity " + s + "\n");
                    }
                    foreach (var s in filterData.MissingStrategies)
                    {
                        ssb.Append("Missing Strategy " + s + "\n");
                        sb.Append("Missing Strategy " + s + "\n");
                    }
                    if (ssb.Length > 0)
                        Invoke(new MethodInvoker(() => MessageBox.Show(ssb.ToString())));
                     */
                    //Filter using IsValidInput
                    {
                        var validTrades = new List<Trade>();
                        var errors = new List<string>();
                        var warnings = new List<string>();
                        sb.Append("-------------------- Validation Check --------------------\n");
                        foreach (var t in trades)
                        {
                            try
                            {
                                errors.Clear();
                                warnings.Clear();
                                bool isValid = t.IsValid(warnings, errors);
                                var id = t.GetProperty(TradeImportHelper.SymmetryTranId) ?? "N/A";
                                var sid = t.GetProperty(TradeImportHelper.MurexTradeId) ?? "N/A";
                                if (!isValid)
                                {
                                    foreach (var err in errors)
                                        sb.Append("[IsValid Error]   Trade= ").Append(t.Id).Append(" HoldingID= ").Append(id).Append(" TradeId= ").Append(sid).
                                            Append(" type= ").Append(t.Product.GetType().Name).Append(" ").Append(err).Append("\n");
                                }
                                else
                                {
                                    foreach (var err in warnings)
                                        sb.Append("[IsValid Warning] Trade= ").Append(t.Id).Append(" HoldingID= ").Append(id).Append(" TradeId= ").Append(sid).
                                            Append(" type= ").Append(t.Product.GetType().Name).Append(" ").Append(err).Append("\n");
                                    validTrades.Add(t);
                                }
                            }
                            catch (Exception xx)
                            {
                                Logger.Error("IsValid Input " + t.Id + " ", xx);
                            }
                        }
                        trades = validTrades;
                    }
                    sb.Append("\nImported Trades Count in all: " + trades.Count + "\n");
                    saveProductButton.Tag = trades;
                    /*
                    if (excludeTradeIds.Count != 0)
                    {
                        foreach (long id in excludeTradeIds)
                        {
                            var trade = Env.Current.Trade.GetTrade(id);
                            if (trade == null) continue;
                            if (trade.Status == "Canceled") continue;
                            trade.Action = "Cancel";
                            trade.SetProperty("InitialId", Convert.ToString(trade.Id));
                            trades.Add(trade);
                        }
                    }*/
                    if (progress.IsCanceled) return;
                    Invoke(new MethodInvoker(() =>
                    {
                        MessageBox.Show(trades.Count +
                                        " trades Imported");
                        tradeOutputText.Lines =
                            sb.ToString().Split('\n');
                        if (trades.Count > 0)
                            ShowTrades(trades, null);
                    }));
                }
                catch (Exception x)
                {
                    Logger.Error(x);
                    Invoke(new MethodInvoker(() => MessageBox.Show(x.ToString())));
                }
                finally
                {
                    Invoke(new MethodInvoker(() =>
                    {
                        importProductButton.Enabled = true;
                        importProductButton.Tag = null;
                        buttonCancel.Enabled = false;
                    }
                                    ));
                }
            });
            thread.Start();
        }
        private void ImportPartyButtonClick(object sender, EventArgs e)
        {
            importPartyButton.Enabled = false;
            var sb = new StringBuilder();
            var progress = new ImportProgress { ProgressBar = saveProgressBar, IsCanceled = false };
            importPartyButton.Tag = progress;
            var filename = textBoxPartyFile.Text;
            var filterData = new FilterData
            {
                FileName = filename
            };
            var thread = new Thread(() =>
            {
                try
                {
                    sb.Append("-------- Importing from " + Path.GetFileName(filename) +
                                      " --------\n");
                    Invoke(new MethodInvoker(() =>
                    {
                        tradeOutputText.AppendText(" Importing parties \n");
                    }));
                    var infos = TradeImportHelper.ReadPartyData(filterData, sb);
                    var infos2 = new List<PartyInfo>();
                    var parties = new List<Party>();
                    var partyCodes = new HashSet<string>();
                    string duplicates = string.Empty;
                    int newCount = 0, updateCount = 0;
                    foreach (var info in infos)
                    {
                        if (partyCodes.Contains(info.Code))
                        {
                            var msg = "[Load Party Error] Duplicated code (" + info.Code + ") found, will be ignored\n";
                            duplicates += msg;
                            sb.Append(msg);
                        }
                        else
                        {
                            partyCodes.Add(info.Code);
                            infos2.Add(info);
                        }
                    }
                    if (duplicates.Length > 0)
                    {
                        if (MessageBox.Show("Duplicates:\n" + duplicates + "Do you want to continue without them?", 
                            "Load Parties", MessageBoxButtons.YesNo) == DialogResult.No)
                            return;
                    }

                    foreach (var info in infos2)
                    {
                        var party = TradeImportHelper.LoadParty(info, sb);
                        if (party != null)
                        {
                            parties.Add(party);
                            if (party.Action.Equals(TradeImportHelper.UpdateAction))
                                updateCount++;
                            else
                                newCount++;

                        }
                    }
                    var count = parties.Count;
                    if (count == 0)
                    {
                        sb.Append("No new parties loaded\n");
                    }
                    else
                    {
                        var msg = newCount + " new and " + updateCount + " updated parties loaded.\n";                        
                        sb.Append(msg);
                        if (MessageBox.Show(msg + " Do you want to Save?", "Save Parties", MessageBoxButtons.YesNo) == DialogResult.No)
                            return;
                        saveProgressBar.Properties.Minimum = 0;
                        saveProgressBar.Properties.Maximum = count;
                        saveProgressBar.EditValue = 0;
                        var thread2 = new Thread(() => SaveParties(parties, importPartyButton));
                        thread2.Start();
                    }

                    tradeOutputText.Lines = sb.ToString().Split('\n');

                }
                catch (Exception x)
                {
                    Logger.Error(x);
                    Invoke(new MethodInvoker(() => MessageBox.Show(x.ToString())));
                }
                finally
                {
                    Invoke(new MethodInvoker(() =>
                        {
                            importPartyButton.Enabled = true;
                        }
                    ));
                }

            });
            thread.Start();
        }