public BuyAndHoldRawTransactionViewModel MapDtoToViewModel(BuyAndHoldRawTransactionDto dto)
        {
            var viewModel = new BuyAndHoldRawTransactionViewModel
            {
                Id = dto.Id,
                Xref = dto.Xref.ToString(),
                OriginalRawTransactionId = dto.OriginalRawTransactionId.ToString(),
                TransactionDate = dto.TransactionDate.ToShortDateString(),
                SecurityId = dto.SecurityId.ToString(),
                TickerSymbol = dto.TickerSymbol,
                //OriginalSymbol = dto.OriginalTickerSymbol,
                //OriginalSecurityId = dto.OriginalSecurityId.ToString(),
                Company = dto.Company,
                Description = dto.Description,
                Quantity = dto.Quantity,
                Price = dto.Price,
                Amount = dto.Amount,
                Fee = dto.Fees,
                Credit = dto.DebitCredit,
                SuspectedType = dto.SuspectedType,
                Period = dto.Period,
                //TransactionType = dto.TransactionType,
                TransactionTypeId = dto.TransactionTypeId,
                TransactionApplied = dto.TransactionApplied.ToString(),
                DividendAmount = dto.DividendAmount.ToString(),
                AmountInvested = dto.AmountInvested.ToString(),
                NumberShares = dto.NumberShares.ToString(),
                BuyPrice = dto.BuyPrice.ToString(),
                Split = dto.Split,
                ValidFrom = dto.ValidFrom.ToShortDateString(),
                ValidTo = dto.ValidTo.ToShortDateString(),
                SellDate = dto.SellDate.ToShortDateString(),
                SellId = dto.SellId.ToString(),
                Notes = dto.Notes,
                XXX = dto.XXX
            };

            var qq = new List<string>();

            if (dto.BuyAndHoldTransactionTransactionsDto != null)
            {

                foreach (var ww in dto.BuyAndHoldTransactionTransactionsDto)
                {
                    qq.Add(ww.AmountInvested.ToString());
                }
                viewModel.qq = qq;
            }
            return viewModel;
        }
        //          [Id]
        //          [Xref]
        //          [OriginalId]
        //          [TransactionDate]
        //          [Symbol]
        //          [SecurityId]
        //          [OriginalSymbol]
        //          [OriginalSecurityId]
        //          [Company]
        //          [Description]
        //          [Quantity]
        //          [Price]
        //          [Amount]
        //          [Fees]
        //          [DebitCredit]
        //          [Transaction]
        //          [Period]
        //          [TransactionTypeId]
        //          [TransactionType]
        //          [TransactionApplied]
        //          [DividendAmount]
        //          [AmountInvested]
        //          [NumberShares]
        //          [BuyPrice]
        //          [Split]
        //          [ValidFrom]
        //          [ValidTo]
        //          [SellDate]
        //          [SellId]
        //          [Notes]
        //          [XXX]
        public BuyAndHoldRawTransactionDto MapViewModelToDto(BuyAndHoldRawTransactionViewModel viewModel)
        {
            return new BuyAndHoldRawTransactionDto
            {
                Id = viewModel.Id,
                Xref = viewModel.Xref.ToNullableInt(),

                OriginalRawTransactionId = viewModel.OriginalRawTransactionId.ToNullableInt(),
                TransactionDate = viewModel.TransactionDate.ToNullableDateTime(),
                SecurityId = viewModel.SecurityId.ToNullableInt(),
                TickerSymbol = viewModel.TickerSymbol,
                //OriginalSecurityId = viewModel.OriginalSecurityId.ToNullableInt(),
                Company = viewModel.Company,
                Description = viewModel.Description,
                Quantity = viewModel.Quantity,
                Price = viewModel.Price,
                Amount = viewModel.Amount,
                Fees = viewModel.Fee,
                DebitCredit = viewModel.Credit,
                SuspectedType = viewModel.SuspectedType,
                Period = viewModel.Period,
                TransactionTypeId = viewModel.TransactionTypeId,
                TransactionApplied = viewModel.TransactionApplied.ToNullableBool(),
                DividendAmount = viewModel.DividendAmount.ToNullableDecimal(),
                AmountInvested = viewModel.AmountInvested.ToNullableDecimal(),
                NumberShares = viewModel.NumberShares.ToNullableDouble(),
                BuyPrice = viewModel.BuyPrice.ToNullableDecimal(),
                Split = viewModel.Split,
                ValidFrom = viewModel.ValidFrom.ToNullableDateTime(),
                ValidTo = viewModel.ValidTo.ToNullableDateTime(),
                SellDate = viewModel.SellDate.ToNullableDateTime(),
                SellId = viewModel.SellId.ToNullableInt(),
                Notes = viewModel.Notes,
                XXX = viewModel.XXX,
            };
            //var qq = new List<string>();

            //if (viewModel.BuyAndHoldTransactionTransactionsDto != null)
            //{

            //    foreach (var ww in viewModel.BuyAndHoldTransactionTransactionsDto)
            //    {
            //        qq.Add(ww.AmountInvested.ToString());
            //    }
            //    dto.qq = qq;
            //}
        }
        public BuyAndHoldRawTransactionsViewModel BuildRawTransactionObjects(List<BuyAndHoldRawTransactionDto> transactions, NavDto nav, bool seperateReinvest)
        {
            var currentShareValue = nav.Nav; //GetLatestTickersNav("TWCUX");

            var viewModel = new BuyAndHoldRawTransactionsViewModel
            {
                Nav = currentShareValue.ToString("C"),
                SecurityTicker = "TWCUX",
                SecurityName = "American Century Ultra",
                Transactions = new List<BuyAndHoldRawTransactionViewModel>()
            };
            decimal totalInvested = 0;
            decimal totalReinvested = 0;
            decimal totalShares = 0;
            decimal currentValue = 0;
            decimal totalValue = 0;
            decimal gain = 0;
            foreach (var transaction in transactions)
            {
                var buyAndHoldTransaction = new BuyAndHoldRawTransactionViewModel();

                var shares = transaction.NumberShares;
                var amountInvested = transaction.AmountInvested.HasValue ? transaction.AmountInvested.Value : 0;

                if (transaction.TransactionType == "Buy" || !seperateReinvest)
                {
                    totalInvested += amountInvested;
                }
                else
                {
                    totalReinvested += amountInvested;
                }

                var _shares = shares.HasValue ? decimal.Parse(shares.Value.ToString()) : 0;

                if (_shares != 0)
                {
                    totalShares += _shares;
                    currentValue = _shares * currentShareValue;
                    totalValue += currentValue;
                    gain = currentValue - amountInvested;
                    //profit = currentValue - amountInvested;
                }

                buyAndHoldTransaction.Id = transaction.Id;
                //var sellTransaction = transaction.BuyAndHoldSellTransaction;
                //var originalTransaction = transaction.BuyAndHoldOriginalTransaction;

                //if (originalTransaction != null)
                //{
                //    var originalTransactionAmountInvested = originalTransaction.AmountInvested.HasValue ? originalTransaction.AmountInvested.Value : 0;

                //    buyAndHoldTransaction.OriginalTransaction = new BuyAndHoldTransactionViewModel();
                //    buyAndHoldTransaction.OriginalTransaction.Type = originalTransaction.Type + " [" + originalTransaction.OriginalSymbol.ToUpper() + "]";
                //    buyAndHoldTransaction.OriginalTransaction.Id = originalTransaction.id;
                //    buyAndHoldTransaction.OriginalTransaction.AmountInvested = originalTransactionAmountInvested.ToString("C");
                //}

                //if (sellTransaction != null)
                //{
                //    buyAndHoldTransaction.SellDate = sellTransaction.TransactionDate.Value.ToShortDateString();
                //    buyAndHoldTransaction.SellPrice = sellTransaction.BuyPrice.HasValue ? sellTransaction.BuyPrice.Value.ToString("C") : "";
                //    buyAndHoldTransaction.Proceeds = sellTransaction.AmountInvested.HasValue ? sellTransaction.AmountInvested.Value.ToString("C") : "";
                //    buyAndHoldTransaction.Profit = ((sellTransaction.AmountInvested.HasValue ? sellTransaction.AmountInvested.Value : 0) - amountInvested).ToString("C");
                //}
                buyAndHoldTransaction.BuyDate = transaction.TransactionDate.Value.ToShortDateString();
                if (transaction.TransactionType == "Buy" || !seperateReinvest)
                {
                    buyAndHoldTransaction.AmountInvested = amountInvested.ToString("C");
                }
                else if (amountInvested != 0)
                {
                    buyAndHoldTransaction.AmountReinvested = amountInvested.ToString("C");
                }
                buyAndHoldTransaction.DividendAmount = transaction.DividendAmount.HasValue ? transaction.DividendAmount.Value.ToString("C") : "";
                buyAndHoldTransaction.BuyPrice = transaction.BuyPrice.HasValue ? transaction.BuyPrice.Value.ToString("C") : "";
                buyAndHoldTransaction.NumberShares = transaction.NumberShares.HasValue ? transaction.NumberShares.Value.ToString("F3") : "";
                if (transaction.NumberShares.HasValue)
                {
                    buyAndHoldTransaction.CurrentValue = currentValue.ToString("C");
                }
                buyAndHoldTransaction.IsGainNegative = gain < 0;
                buyAndHoldTransaction.Gain = gain.ToString("C");
                buyAndHoldTransaction.TransactionType = transaction.TransactionType;
                buyAndHoldTransaction.TotalShares = double.Parse(totalShares.ToString("F3"));
                buyAndHoldTransaction.TotalValue = totalValue.ToString("C");

                //if (transaction.AmericanCenturySell != null)
                //{
                //    var sellPrice = transaction.AmericanCenturySell.SellPrice;
                //    var proceeds = shares * sellPrice;

                //    AmericanCenturyTransaction.SellDate = transaction.AmericanCenturySell.SellDate.Date.ToShortDateString();
                //    AmericanCenturyTransaction.SellPrice = transaction.AmericanCenturySell.SellPrice.ToString("C");
                //    AmericanCenturyTransaction.Proceeds = proceeds.ToString("C");
                //    AmericanCenturyTransaction.Profit = (proceeds - amountInvested).ToString("C");
                //    AmericanCenturyTransaction.CurrentValue = null;
                //    AmericanCenturyTransaction.Gain = null;
                //}

                viewModel.Transactions.Add(buyAndHoldTransaction);
            }
            viewModel.TotalInvested = totalInvested.ToString("C");
            viewModel.TotalReinvested = totalReinvested.ToString("C");
            viewModel.TotalShares = totalShares.ToString("F3");
            viewModel.TotalValue = totalValue.ToString("C");
            return viewModel;
        }
        private List<BuyAndHoldRawTransactionViewModel> GetTransactions(string ticker = "")
        {
            try
            {
                var totalShares = 0.0;
                var buyAndHoldTransactions = new List<BuyAndHoldRawTransactionViewModel>();

                var buyAndHoldTransactionDtos = _buyAndHoldService.GetBuyAndHoldRawTransactionsByTickerSymbol(ticker);

                foreach (var buyAndHoldTransactionDto in buyAndHoldTransactionDtos)
                {
                    var buyAndHoldTransactionViewModel = new BuyAndHoldRawTransactionViewModel();

                    buyAndHoldTransactionViewModel = _buyAndHoldRawTransactionMapper.MapDtoToViewModel(buyAndHoldTransactionDto);

                    double numShares = 0;
                    if (buyAndHoldTransactionDto.ValidTo.HasValue &&
                        double.TryParse(buyAndHoldTransactionDto.NumberShares.ToString(), out numShares))
                    {
                        if (!buyAndHoldTransactionDto.TransactionApplied.ToBool())
                        {
                            if (buyAndHoldTransactionDto.TransactionType == "Sell")
                            {
                                totalShares -= Math.Round(Math.Abs(numShares), 4);
                            }
                            else
                            {
                                totalShares += Math.Round(numShares, 4);
                            }
                        }
                        buyAndHoldTransactionViewModel.TotalShares = totalShares;
                    }
                    buyAndHoldTransactions.Add(buyAndHoldTransactionViewModel);
                }
                return buyAndHoldTransactions.OrderByDescending(p => p.TransactionDate).ThenBy(p => p.TransactionType).ToList();

                //List<BuyAndHoldTransactionViewModel> buyAndHoldTransactions = new List<BuyAndHoldTransactionViewModel>();
                //connectionString = "Data Source=192.168.1.101;Initial Catalog=Invest;Persist Security Info=True;User ID=;Password=;";

                //if (ticker == "zzz")
                //{
                //    sql = "SELECT TOP 500 * FROM BuyAndHoldTransaction";
                //    sql += " WHERE ISNULL(XXX, '') != 'xxx'";
                //    sql += " ORDER BY TransactionDate DESC";
                //}

                //else if (!string.IsNullOrWhiteSpace(ticker))
                //{
                //    sql = "SELECT * FROM BuyAndHoldTransaction";
                //    sql += " WHERE Symbol = '" + ticker + "'";
                //    sql += " ORDER BY TransactionDate ";
                //}
                //else
                //{
                //    sql = "SELECT TOP 500 * FROM BuyAndHoldTransaction";
                //    sql += " WHERE ISNULL(XXX, '') != 'xxx'";
                //    sql += " ORDER BY TransactionDate DESC";
                //}
                //try
                //{
                //    using (SqlConnection cn = new SqlConnection(connectionString))
                //    {
                //        using (SqlCommand cmd = new SqlCommand(sql, cn))
                //        {
                //            var totalShares = 0.0;
                //            cn.Open();
                //            SqlDataReader dr = cmd.ExecuteReader();
                //            while (dr.Read())
                //            {
                //                var transaction = new BuyAndHoldTransactionViewModel();
                //                transaction.Id = Int32.Parse(dr["Id"].ToString());
                //                transaction.BhId = dr["BhId"].ToString();
                //                transaction.TxId = dr["TxId"].ToString();
                //                transaction.Date = (DateTime)dr["TransactionDate"];
                //                transaction.Symbol = dr["Symbol"].ToString();
                //                transaction.Company = dr["Company"].ToString();
                //                transaction.Quantity = dr["Quantity"].ToString();
                //                transaction.Price = dr["Price"].ToString();
                //                transaction.Amount = dr["Amount"].ToString();
                //                transaction.Fee = dr["Fees"].ToString();
                //                transaction.Credit = dr["DebitCredit"].ToString();
                //                transaction.SuspectedType = dr["Transaction"].ToString();
                //                transaction.Type = dr["Type"].ToString();
                //                transaction.Period = dr["Period"].ToString();
                //                transaction.DividendAmount = dr["DividendAmount"].ToString();
                //                transaction.AmtInv = dr["AmountInvested"].ToString();
                //                transaction.NumShares = dr["NumberShares"].ToString();
                //                double numShares = 0;
                //                if (Double.TryParse(dr["NumberShares"].ToString(), out numShares))
                //                {
                //                    totalShares += Math.Round(numShares, 4);
                //                    transaction.TotalShares = totalShares;
                //                }
                //                transaction.BuyPrice = dr["BuyPrice"].ToString();
                //                transaction.XXX = dr["XXX"].ToString();
                //                transaction.Xref = dr["Xref"].ToString();
                //                transaction.Xref2 = dr["Notes"].ToString();
                //                buyAndHoldTransactions.Add(transaction);
                //            }
                //        }
                //    }
                //    return buyAndHoldTransactions.OrderByDescending(p => p.Date).ToList();
            }

            // var model = db.ArtistNews.Take(20);

            catch (Exception ex)
            {
                var w = ex;
                return null;
            }
        }
        public ActionResult EditRawTransaction(BuyAndHoldRawTransactionViewModel model)
        {
            var dto = _buyAndHoldRawTransactionMapper.MapViewModelToDto(model);

            dto = _buyAndHoldService.UpdateBuyAndHoldRawTransaction(dto);

            var viewModel = BuildBuyAndHoldRawTransactionViewModel(dto);
            return View(viewModel);
        }
 public ActionResult Delete(BuyAndHoldRawTransactionViewModel model)
 {
     try
     {
         var id = model.Id;
         // TODO: Add delete logic here
         DeleteTransaction(id);
         //return RedirectToAction("SearchByTicker", new { id = model.Symbol });
         return RedirectToAction("Search", new { id = model.SecurityId });
     }
     catch
     {
         return View();
     }
 }