Exemplo n.º 1
0
    protected void Page_Load(object sender, EventArgs e)
    {
        switch (_PortTypeID)
        {
            case "0":
            case "1":
            case "5":
                strTableName = "UserinfoPortfolioSetting";
                break;
            case "2":
            case "6":
                strTableName = "UserinfoILPSettings";
                break;
            case "3":
                strTableName = "UserinfoSSPSettings";
                break;
            case "4":
                strTableName = "UserinfoSDPortSettings";
                break;
        }

        decTotalSize = Convert.ToDecimal(CareerCruisingWeb.CCLib.Common.DataAccess.GetValue("select isnull(cast(UploadSize/1024.0 as decimal(9,1)),0) from " + strTableName + " where SchoolID = " + _SchoolID).ToString());
        strTotalSize = (Decimal.Round(decTotalSize / 1024)).ToString();

        decFileSize = Convert.ToDecimal(CareerCruisingWeb.CCLib.Common.DataAccess.GetValue("select isnull(cast(sum(FileSize)/1024.0 as decimal(9,1)),0) from Port_Files where PortfolioID = " + _PortfolioID).ToString());

        decPercent = decFileSize / decTotalSize * 100;

        imgProgress.Width = Convert.ToInt16(decPercent/100 * 161);
    }
Exemplo n.º 2
0
 public STD_CBEExamSubject(
     int cBEExamSubjectID, 
     int cBEExamID, 
     string subjectTitle, 
     string subjectCode, 
     string taxOrPaperVariant, 
     Decimal fees,
     DateTime examDate, 
     string addedBy, 
     DateTime addedDate, 
     string updatedBy, 
     DateTime updatedDate, 
     int rowStatusID
     )
 {
     this.CBEExamSubjectID = cBEExamSubjectID;
     this.CBEExamID = cBEExamID;
     this.SubjectTitle = subjectTitle;
     this.SubjectCode = subjectCode;
     this.TaxOrPaperVariant = taxOrPaperVariant;
     this.Fees = fees;
     this.ExamDate = examDate;
     this.AddedBy = addedBy;
     this.AddedDate = addedDate;
     this.UpdatedBy = updatedBy;
     this.UpdatedDate = updatedDate;
     this.RowStatusID = rowStatusID;
 }
Exemplo n.º 3
0
 private static int f(short a1, ushort a2, int a3, uint a4, long a5,
         ulong a6, byte a7, sbyte a8, Decimal a9, int[] a10,
         VT a11, CL a12, int a13, int a14, int a15,
         int a16, int a17, int a18, int a19, int a20,
         int a21, int a22, int a23, int a24, int a25)
 {
     Console.WriteLine(a1);
     Console.WriteLine(a2);
     Console.WriteLine(a3);
     Console.WriteLine(a4);
     Console.WriteLine(a5);
     Console.WriteLine(a6);
     Console.WriteLine(a7);
     Console.WriteLine(a8);
     Console.WriteLine(a9);
     Console.WriteLine(a10[0]);
     Console.WriteLine(a11.m);
     Console.WriteLine(a12.n);
     Console.WriteLine(a13);
     Console.WriteLine(a14);
     Console.WriteLine(a15);
     Console.WriteLine(a16);
     Console.WriteLine(a17);
     Console.WriteLine(a18);
     Console.WriteLine(a19);
     Console.WriteLine(a20);
     Console.WriteLine(a21);
     Console.WriteLine(a22);
     Console.WriteLine(a23);
     Console.WriteLine(a24);
     Console.WriteLine(a25);
     int sum = f1(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15,
             a16, a17, a18, a19, a20, a21, a22, a23, a24, a25);
     return sum;
 }
 public void grdEmpl_OnItemDataBound(object sender, DataGridItemEventArgs e)
 {
     if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
     {
         TotalEngHours += Convert.ToDecimal(Convert.ToDecimal(e.Item.Cells[1].Text));
         TotalFabHours += Convert.ToDecimal(Convert.ToDecimal(e.Item.Cells[2].Text));
         TotalfinHours += Convert.ToDecimal(Convert.ToDecimal(e.Item.Cells[3].Text));
         TotalMiscHours += Convert.ToDecimal(Convert.ToDecimal(e.Item.Cells[4].Text));
         TotalHours += Convert.ToDecimal(Convert.ToDecimal(e.Item.Cells[5].Text));
         TotalPrice += Convert.ToDecimal(Convert.ToDecimal(e.Item.Cells[6].Text));
     }
     else if (e.Item.ItemType == ListItemType.Footer)
     {
         e.Item.Cells[1].Text = TotalEngHours.ToString();
         e.Item.Cells[1].Font.Bold = true;
         e.Item.Cells[1].HorizontalAlign = HorizontalAlign.Left;
         e.Item.Cells[2].Text = TotalFabHours.ToString();
         e.Item.Cells[2].Font.Bold = true;
         e.Item.Cells[2].HorizontalAlign = HorizontalAlign.Left;
         e.Item.Cells[3].Text = TotalfinHours.ToString();
         e.Item.Cells[3].Font.Bold = true;
         e.Item.Cells[3].HorizontalAlign = HorizontalAlign.Left;
         e.Item.Cells[4].Text = TotalMiscHours.ToString();
         e.Item.Cells[4].Font.Bold = true;
         e.Item.Cells[4].HorizontalAlign = HorizontalAlign.Left;
         e.Item.Cells[5].Text = TotalHours.ToString();
         e.Item.Cells[5].Font.Bold = true;
         e.Item.Cells[5].HorizontalAlign = HorizontalAlign.Left;
         e.Item.Cells[6].Text = TotalPrice.ToString();
         e.Item.Cells[6].Font.Bold = true;
         e.Item.Cells[6].HorizontalAlign = HorizontalAlign.Left;
     }
 }
Exemplo n.º 5
0
    public bool PosTest2()
    {
        bool retVal = true;
        const string c_TEST_DESC = "PosTest2:Verify the param is UInt64.MinValue(0) ";
        const string c_TEST_ID = "P002";

        UInt64 dValue = UInt64.MinValue;
        Decimal resValue = 0m;

        TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);

        try
        {
            Decimal decimalValue = new Decimal(dValue);
            if (decimalValue != resValue)
            {
                string errorDesc = "Value is not " + resValue.ToString() + " as expected: param is " + decimalValue.ToString();
                TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
            retVal = false;
        }


        return retVal;
    }
Exemplo n.º 6
0
    public bool PosTest1()
    {
        bool retVal = true;
        const string c_TEST_DESC = "PosTest1:Verify the param is a random UInt64 ";
        const string c_TEST_ID = "P001";

        System.UInt64 uint64Value = Convert.ToUInt64(TestLibrary.Generator.GetInt64(-55));

        TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);

        try
        {
            Decimal decimalValue = new Decimal(uint64Value);
            if (decimalValue != Convert.ToDecimal(uint64Value))
            {
                string errorDesc = "Value is not " + Convert.ToDecimal(uint64Value).ToString() + " as expected: param is " + decimalValue.ToString();
                TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
            retVal = false;
        }


        return retVal;
    }
Exemplo n.º 7
0
 public static int Main(String[] args)
 {
     Decimal[] dcmlSecValues = new Decimal[2] { 2, 3 };
     Int32 aa = 1;
     Decimal dcml1 = --dcmlSecValues[aa];
     return 100;
 }
Exemplo n.º 8
0
 public Suplement(int id, int kolicina, Decimal cijena, String tipSuplementa)
     : base(kolicina)
 {
     IdSuplementa = id;
     TipSuplementaS = tipSuplementa;
     Cijena = cijena;
 }
 public static Money[] Distribute(this Money money,
     FractionReceivers fractionReceivers,
     RoundingPlaces roundingPlaces,
     Decimal distribution)
 {
     return new MoneyDistributor(money, fractionReceivers, roundingPlaces).Distribute(distribution);
 }
Exemplo n.º 10
0
 /*public Oprema(int id, int kolicina, Decimal cijena, string tipOpreme) : base(kolicina)
 {
     IdOpreme = id;
     if (tipOpreme == "Bandaze") TipOpreme = TipOpreme.Bandaze;
     if (tipOpreme == "Flasa") TipOpreme = TipOpreme.Flasa;
     if (tipOpreme == "Peskir") TipOpreme = TipOpreme.Peskir;
     if (tipOpreme == "Pojas") TipOpreme = TipOpreme.Pojas;
     if (tipOpreme == "Rukavice") TipOpreme = TipOpreme.Rukavice;
     if (tipOpreme == "Sorts") TipOpreme = TipOpreme.Sorts;
     if (tipOpreme == "Tene") TipOpreme = TipOpreme.Tene;
     CijenaNajama = cijena;
     tipopremes = tipOpreme;
 }*/
 public Oprema(int id, int kolicina, Decimal cijena, String tipOpreme)
     : base(kolicina)
 {
     IdOpreme = id;
     CijenaNajama = cijena;
     TipOpremeS = tipOpreme;
 }
Exemplo n.º 11
0
    public bool PosTest1()
    {
        bool retVal = true;
        const string c_TEST_DESC = "PosTest1:Verify the param is a random float ";
        const string c_TEST_ID = "P001";

        float dValue = TestLibrary.Generator.GetSingle(-55);
        while (dValue > Convert.ToSingle(Decimal.MaxValue) || dValue < Convert.ToSingle(Decimal.MinValue))
        {
            dValue = TestLibrary.Generator.GetSingle(-55);
        }

        TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);

        try
        {
            Decimal decimalValue = new Decimal(dValue);
            if (decimalValue != Convert.ToDecimal(dValue))
            {
                string errorDesc = "Value is not " + decimalValue.ToString() + " as expected: param is " + dValue.ToString();
                TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
            retVal = false;
        }


        return retVal;
    }
Exemplo n.º 12
0
 public static bool DoubleIsWithinEpsilon(double x, double y)
 {
     Decimal dx = new Decimal(x);
     Decimal dy = new Decimal(y);
     Decimal diff = Math.Abs(Decimal.Subtract(dx, dy));
     return diff.CompareTo(Epsilon) <= 0;
 }
Exemplo n.º 13
0
 public static bool FloatIsWithinEpsilon(float x, float y)
 {
     Decimal dx = new Decimal(x);
     Decimal dy = new Decimal(y);
     Decimal diff = Math.Abs(Decimal.Subtract(dx, dy));
     return diff.CompareTo(Epsilon) <= 0;
 }
 public static Decimal ToDecimal(string valueToParse, Decimal defaultValue)
 {
     Decimal returnValue;
     if (!Decimal.TryParse(valueToParse, out returnValue))
         returnValue = defaultValue;
     return returnValue;
 }
Exemplo n.º 15
0
    public string CurrencyName(string Code,
                               string DecPrecise
                               )
    {
        string Name = "";        

        if (Code != "")
        {
            //不需要加入小數位判斷(DecPrecise)  因為SLP已有屬性控制
            Decimal d = new Decimal();
            if (Decimal.TryParse(Code, out d))
            {
                string tempStr = "";
                string[] d2 = d.ToString().Split('.');
                string _NT = "NT$";
                for (int i = 0; i < d2.Length; i++)
                {
                    switch (i)
                    {
                        case 0:
                            _NT += d.ToString("n").Split('.')[0];
                            break;
                        case 1:
                            _NT += d.ToString("#." + tempStr.PadRight(int.Parse(DecPrecise), '0')).Split('.')[1];
                            break;
                        default:
                            break;
                    }
                    Name = _NT;                    
                }
            }
        }        

        return Name;
    }
Exemplo n.º 16
0
  public static Decimal Add(Decimal first, Decimal second)
  {
    Contract.Requires(first != 0);
    Contract.Requires(second != 0);
    Contract.Ensures(Contract.Result<Decimal>() == first + second);
 
    return first + second;
  }
Exemplo n.º 17
0
 public Notification(String name, String type, String condition, Decimal value, Boolean ringOnce)
 {
     this.Name = name;
     this.Type = type;
     this.Condition = condition; // >= and =<
     this.Value = value;
     this.RingOnce = ringOnce;
 }
Exemplo n.º 18
0
 public Pedido(bool pEstado, List<Producto> pColProductos, DateTime pFecha, String pDireccionEnvio, Decimal pMonto)
     : this()
 {
     this.Estado = pEstado;
     this.ColProductos = pColProductos;
     this.Fecha = pFecha;
     this.DireccionEnvio = pDireccionEnvio;
     this.Monto = pMonto;
 }
Exemplo n.º 19
0
 public ZaLedgerItem(DateTime date, String desc, ZaExpenseType expT, ZaSecondaryExpenseType secExpT, ZaAccount acc, Decimal price = 0)
 {
     PurchaseDate = date;
     Description = desc;
     ExpenseType = expT;
     SecondaryExpenseType = secExpT;
     Account = acc;
     PurchasePrice = price;
 }
Exemplo n.º 20
0
 public Uposlenik(int idUposlenika, String ime, String prezime, String spol, DateTime datumRodjenja,
         DateTime datumZaposlenja, Decimal plata, String kontakt, String zaposlenje, String sifra)
     : base(idUposlenika, ime, prezime, spol, datumRodjenja, kontakt)
 {
     Plata = plata;
         DatumZaposlenja = datumZaposlenja;
         ZaposlenjeS = zaposlenje;
         this.sifra = sifra;
 }
	// Constructors.
	public DecimalConstantAttribute(byte scale, byte sign,
									uint hi, uint mid, uint low)
			{
				unchecked
				{
					value = new Decimal((int)low, (int)mid, (int)hi,
										(sign != 0), scale);
				}
			}
Exemplo n.º 22
0
 public url(string locIn, DateTime lastmodIn, changefreq freqIn, Decimal priorityIn)
 {
     loc = locIn;
     lastmod = lastmodIn;
     changefreq = freqIn;
     changefreqSpecified = true;
     priority = priorityIn;
     prioritySpecified = true;
 }
Exemplo n.º 23
0
 public Klijent(int id, string ime, string prezime, string spol, DateTime datumRodjenja, 
     int visina, Decimal tezina, string kontakt, int idTrenera, int idNutricioniste)
     : base(id, ime, prezime, spol, datumRodjenja, kontakt)
 {
     Visina = visina;
     Tezina = tezina;
     IDtrenera = idTrenera;
     IDnutricioniste = idNutricioniste;
 }
 public ProductItem(Int32 companyId, Int32 productId, String productName, Int32 quantity, String description, Decimal productPrice, Boolean isApplied)
 {
     this.CompanyId = companyId;
     this.ProductId = productId;
     this.Description = description;
     this.ProductPrice = productPrice;
     this.IsApplied = IsApplied;
     this.ProductName = productName;
     this.Quantity = quantity;
 }
Exemplo n.º 25
0
    public bool PosTest1()
    {
        bool retVal = true;
        const string c_TEST_DESC = "PosTest1:Verify the top 3 param are  random Int32... ";
        const string c_TEST_ID = "P001";

        int low = TestLibrary.Generator.GetInt32(-55);
        int mid = TestLibrary.Generator.GetInt32(-55);
        int hi = TestLibrary.Generator.GetInt32(-55);
        int flags = 0x1C0000;
        int[] arrInt ={low, mid, hi, flags};


        TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);

        try
        {
            Decimal decimalValue = new Decimal(arrInt);
            int[] arrBits = Decimal.GetBits(decimalValue);

            if (arrBits[0] != low)
            {
                string errorDesc = "lo Value is not " + low.ToString() + " as expected: param is " + arrInt[0].ToString();
                TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
                retVal = false;
            }
            if (arrBits[1] != mid)
            {
                string errorDesc = "mid Value is not " + mid.ToString() + " as expected: param is " + arrInt[1].ToString();
                TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc);
                retVal = false;
            }
            if (arrBits[2] != hi)
            {
                string errorDesc = "hi Value is not " + hi.ToString() + " as expected: param is " + arrInt[2].ToString();
                TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
                retVal = false;
            }
            if (arrBits[3] != flags)
            {
                string errorDesc = "flags Value is not " + flags.ToString() + " as expected: param is " + arrInt[3].ToString();
                TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc);
                retVal = false;
            }
            
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
            retVal = false;
        }


        return retVal;
    }
        public ServiceItem(Int32 serviceId, Int32 companyId, String name, int timeInMinutes, Decimal servicePrice, Int32 employeeId, String employeeName)
        {
            this.ServiceId = serviceId;
            this.CompanyId = companyId;
            this.Name = name;
            this.TimeInMinutes = timeInMinutes;
            this.ServicePrice = servicePrice;
            this.EmployeeId = employeeId;
            this.EmployeeName = employeeName;

        }
Exemplo n.º 27
0
    Decimal ComputeMonthlyPay(Decimal P, Decimal r, int n)
    {
        //c = rP / (1 - (1+r)^-N)

        r = r / 100.0m;
        r = r / 12.0m;

        Decimal ret = (Decimal)(r * P) / (Decimal)(1 - Math.Pow((double)(1+r), (double)(-n)));

        return ret;
    }
Exemplo n.º 28
0
 public VT_0(int i)
 {
     a8_0 = 1;
     a20_0 = 1;
     a29_0 = 1;
     a32_0 = 1;
     a35_0 = 1;
     a36_0 = 1;
     a39_0 = 1;
     a48_0 = 1;
     a51_0 = 1;
     a59_0 = 1;
     a68_0 = 1;
     a95_0 = 1;
     a102_0 = 1;
     a113_0 = 1;
     a119_0 = 1;
     a122_0 = 1;
     a131_0 = 1;
     a157_0 = 1;
     a175_0 = 1;
     a191_0 = 1;
     a194_0 = 1;
     a199_0 = 1;
     a211_0 = 1;
     a221_0 = 1;
     a228_0 = 1;
     a231_0 = 1;
     a235_0 = 1;
     a255_0 = 1;
     a266_0 = 1;
     a267_0 = 1;
     a272_0 = 1;
     a275_0 = 1;
     a276_0 = 1;
     a284_0 = 1;
     a314_0 = 1;
     a327_0 = 1;
     a337_0 = 1;
     a356_0 = 1;
     a367_0 = 1;
     a372_0 = 1;
     a408_0 = 1;
     a409_0 = 1;
     a431_0 = 1;
     a434_0 = 1;
     a475_0 = 1;
     a492_0 = 1;
     a493_0 = 1;
     arr1d_0 = new int[1001];
     arr2d_0 = new int[3, 1001];
     arr3d_0 = new int[5, 1001, 4];
 }
Exemplo n.º 29
0
 private static int f1(short a1, ushort a2, int a3, uint a4, long a5,
         ulong a6, byte a7, sbyte a8, Decimal a9, int[] a10,
         VT a11, CL a12, int a13, int a14, int a15,
         int a16, int a17, int a18, int a19, int a20,
         int a21, int a22, int a23, int a24, int a25)
 {
     int sum = (int)(a1 + a2 + a3 + a4 + (int)a5 + (int)a6 + a7 + a8 + (int)a9 + a10[0]
         + a11.m + a12.n + a13 + a14 + a15 + a16 + a17 + a18 + a19
         + a20 + a21 + a22 + a23 + a24 + a25);
     Console.WriteLine("The sum is {0}", sum);
     return sum;
 }
	public CurrencyWrapper(Object obj)
			{
				if(obj is Decimal)
				{
					value = (Decimal)obj;
				}
				else
				{
					throw new ArgumentException
						(_("Arg_MustBeDecimal"), "obj");
				}
			}
 public void Write(Decimal value)
 {
     bitConverter.CopyBytes(value, buffer, 0);
     WriteInternal(buffer, 16);
 }
Exemplo n.º 32
0
 private void cmdGetProducts_Click(object sender, RoutedEventArgs e)
 {
     products = App.StoreDb.GetProductsFilteredWithLinq(Decimal.Parse(txtMinimumCost.Text));
     lstProducts.ItemsSource = products;
 }
Exemplo n.º 33
0
        /// <summary>
        /// 判断字符串是否是Decimal
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool IsDecimal(this string input)
        {
            Decimal output = 0;

            return(decimal.TryParse(input, out output));
        }
Exemplo n.º 34
0
        public void CalculateGameStatistics(int gameId)
        {
            Check.Argument.IsNotZeroOrNegative(gameId, "gameId");

            var game      = _gameRepository.GetById(gameId);
            var gameShots = _shotRepository.GetByGame(gameId);

            // Watch out for games that were created but never started
            if (gameShots.Any())
            {
                var players = _playerRepository.GetByGame(gameId);

                int maxPlayerPoints = 0;
                int maxHole         = gameShots.Max(s => s.Hole.Id);

                // The first thing that we want to calculate is the max number of points scored (the winner's points). This way
                // we can easily determine who the winner is later when actually adding the stats to the repository.
                foreach (var player in players)
                {
                    int playerPoints = gameShots.Where(s => s.Player.Id == player.Id).Sum(s => s.Points);

                    if (playerPoints > maxPlayerPoints)
                    {
                        maxPlayerPoints = playerPoints;
                    }
                }

                // Calculate all of the game statistics for each player individually
                foreach (var player in players)
                {
                    var playerShots          = gameShots.Where(s => s.Player.Id == player.Id);
                    var playerGameStatistics = new PlayerGameStatistics();

                    playerGameStatistics.Game               = game;
                    playerGameStatistics.Player             = player;
                    playerGameStatistics.Points             = playerShots.Where(s => s.ShotType.Id != ShotTypePush).Sum(s => s.Points);
                    playerGameStatistics.ShotsMade          = playerShots.Count(s => s.ShotMade);
                    playerGameStatistics.Attempts           = playerShots.Sum(s => s.Attempts);
                    playerGameStatistics.ShootingPercentage = Decimal.Round((decimal)playerGameStatistics.ShotsMade / (decimal)playerGameStatistics.Attempts, 3, MidpointRounding.AwayFromZero);
                    playerGameStatistics.Pushes             = playerShots.Count(s => s.ShotType.Id == ShotTypePush);
                    playerGameStatistics.Steals             = playerShots.Count(s => s.ShotType.Id == ShotTypeSteal);
                    playerGameStatistics.SugarFreeSteals    = playerShots.Count(s => s.ShotType.Id == ShotTypeSugarFreeSteal);
                    playerGameStatistics.Winner             = (playerGameStatistics.Points == maxPlayerPoints);
                    playerGameStatistics.OvertimeWin        = playerShots.Max(s => s.Hole.Id > 10 && playerGameStatistics.Winner);
                    playerGameStatistics.GameWinningSteal   = playerShots.Any(s => s.Hole.Id == maxHole && (s.ShotType.Id == ShotTypeSteal || s.ShotType.Id == ShotTypeSugarFreeSteal));

                    int totalGamePoints = gameShots.Sum(s => s.Points);

                    playerGameStatistics.Shutout     = playerGameStatistics.Points == totalGamePoints;
                    playerGameStatistics.PerfectGame = playerGameStatistics.Shutout && (playerGameStatistics.ShotsMade == playerGameStatistics.Attempts);

                    _playerGameStatisticsRepository.Add(playerGameStatistics);
                }

                // Calculate the total stats for the game
                var gameStatistics = new GameStatistics();

                gameStatistics.Game      = game;
                gameStatistics.HoleCount = maxHole;

                // if HoleCount mod NumberOfHoles = 0 --> OvertimeCount = HoleCount / NumberOfHoles
                // else OvertimeCount = (HoleCount - (HoleCount mod NumberOfHoles)) / NumberOfHoles

                gameStatistics.OvertimeCount      = (maxHole > 10) ? 1 : 0;
                gameStatistics.PlayerCount        = gameShots.Select(s => s.Player.Id).Distinct().Count();
                gameStatistics.Points             = gameShots.Where(s => s.ShotType.Id != ShotTypePush).Sum(s => s.Points);
                gameStatistics.ShotsMade          = gameShots.Count(s => s.ShotMade);
                gameStatistics.Attempts           = gameShots.Sum(s => s.Attempts);
                gameStatistics.ShotsMissed        = gameStatistics.Attempts - gameStatistics.ShotsMade;
                gameStatistics.ShootingPercentage = Decimal.Round((decimal)gameStatistics.ShotsMade / (decimal)gameStatistics.Attempts, 3, MidpointRounding.AwayFromZero);
                gameStatistics.Pushes             = gameShots.Count(s => s.ShotType.Id == ShotTypePush);
                gameStatistics.Steals             = gameShots.Count(s => s.ShotType.Id == ShotTypeSteal);
                gameStatistics.SugarFreeSteals    = gameShots.Count(s => s.ShotType.Id == ShotTypeSugarFreeSteal);
                gameStatistics.StainlessSteals    = gameShots.Count(s => (s.ShotType.Id == ShotTypeSteal || s.ShotType.Id == ShotTypeSugarFreeSteal) && s.ShotMade && s.Attempts == 1);

                _gameStatisticsRepository.Add(gameStatistics);
            }
        }
Exemplo n.º 35
0
 public void FromParent(Form inForm, int inFundID, int inPortfolioID, String inFundDescription, String inBBG_Ticker, Decimal inLast_Sale)
 {
     ParentForm1     = inForm;
     FundID          = inFundID;
     PortfolioID     = inPortfolioID;
     FundDescription = inFundDescription;
     BBG_Ticker      = inBBG_Ticker;
     Last_Sale       = inLast_Sale;
 } // FromParent()
Exemplo n.º 36
0
 public BsonValue(Decimal value)
 {
     this.Type     = BsonType.Decimal;
     this.RawValue = value;
 }
Exemplo n.º 37
0
        public JsonResult MuaSach(string ID, string Gia)
        {
            taikhoan tk = (taikhoan)Session[CommonConstants.SESSION_ACCOUNT];

            if (tk == null)
            {
                return(Json(false, JsonRequestBehavior.AllowGet));
            }

            DonHangValue DonHang = new GioHangController().KiemTraTkTrongDonHang(tk.id);

            if (DonHang != null)
            {
                GioHangValue GioHang = new GioHangValue()
                {
                    IdDonHang = DonHang.IdDonHang,
                    IdGioHang = Guid.NewGuid(),
                    IdSach    = Guid.Parse(ID),
                    Soluong   = 1,
                    Tamtinh   = decimal.Parse(Gia)
                };

                bool    ThemGh   = new GioHangController().ThemGioHang(GioHang);
                decimal?tongiten = new GioHangController().TongTien(DonHang.IdDonHang);
                DonHang.TongTien = tongiten;

                new GioHangController().CapNhatDonHang(DonHang);


                if (ThemGh == true)
                {
                    return(Json(true, JsonRequestBehavior.AllowGet));
                }
            }
            else
            {
                DonHangValue DHMoi = new DonHangValue()
                {
                    IdDonHang   = Guid.NewGuid(),
                    IdNguoiMua  = tk.id,
                    NgayDatHang = DateTime.Now.Date,
                    TongTien    = 0
                };

                bool ThemDonHang = new GioHangController().ThemDonHang(DHMoi);
                if (ThemDonHang == true)
                {
                    GioHangValue Ghmoi = new GioHangValue()
                    {
                        IdDonHang = DHMoi.IdDonHang,
                        IdGioHang = Guid.NewGuid(),
                        IdSach    = Guid.Parse(ID),
                        Soluong   = 1,
                        Tamtinh   = Decimal.Parse(Gia)
                    };

                    bool ThemGioHangM = new GioHangController().ThemGioHang(Ghmoi);

                    decimal?tongtien = new GioHangController().TongTien(DHMoi.IdDonHang);
                    DHMoi.TongTien = tongtien;



                    bool CapNhatDonH = new GioHangController().CapNhatDonHang(DHMoi);
                    if (ThemDonHang == true)
                    {
                        return(Json(true, JsonRequestBehavior.DenyGet));
                    }
                }
            }


            return(Json(true, JsonRequestBehavior.DenyGet));
        }
Exemplo n.º 38
0
        public ActionResult BalanceSheetPerBranch(String DateAsOf, Int32 CompanyId, Int32 BranchId)
        {
            // ============
            // PDF settings
            // ============
            MemoryStream workStream = new MemoryStream();
            Rectangle    rectangle  = new Rectangle(PageSize.A3);
            Document     document   = new Document(rectangle, 72, 72, 72, 72);

            document.SetMargins(30f, 30f, 30f, 30f);
            PdfWriter.GetInstance(document, workStream).CloseStream = false;

            document.Open();

            // ===================
            // Fonts Customization
            // ===================
            Font fontArial17Bold = FontFactory.GetFont("Arial", 17, Font.BOLD);
            Font fontArial11     = FontFactory.GetFont("Arial", 11);
            Font fontArial10Bold = FontFactory.GetFont("Arial", 10, Font.BOLD);
            Font fontArial10     = FontFactory.GetFont("Arial", 10);
            Font fontArial11Bold = FontFactory.GetFont("Arial", 11, Font.BOLD);
            Font fontArial12Bold = FontFactory.GetFont("Arial", 12, Font.BOLD);

            Paragraph line = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 4.5F)));

            // ==============
            // Company Detail
            // ==============
            var companyName = (from d in db.MstCompanies where d.Id == CompanyId select d.Company).SingleOrDefault();
            var branch      = (from d in db.MstBranches where d.Id == BranchId select d.Branch).SingleOrDefault();
            var address     = (from d in db.MstCompanies where d.Id == CompanyId select d.Address).SingleOrDefault();
            var contactNo   = (from d in db.MstCompanies where d.Id == CompanyId select d.ContactNumber).SingleOrDefault();

            // ======
            // Header
            // ======
            PdfPTable header = new PdfPTable(2);

            float[] widthsCellsHeader = new float[] { 100f, 75f };
            header.SetWidths(widthsCellsHeader);
            header.WidthPercentage = 100;
            header.AddCell(new PdfPCell(new Phrase(companyName, fontArial17Bold))
            {
                Border = 0
            });
            header.AddCell(new PdfPCell(new Phrase("Balance Sheet Per Branch", fontArial17Bold))
            {
                Border = 0, HorizontalAlignment = 2
            });
            header.AddCell(new PdfPCell(new Phrase(address, fontArial11))
            {
                Border = 0, PaddingTop = 5f
            });
            header.AddCell(new PdfPCell(new Phrase("Date as of " + Convert.ToDateTime(DateAsOf).ToString("MM-dd-yyyy", CultureInfo.InvariantCulture), fontArial11))
            {
                Border = 0, PaddingTop = 5f, HorizontalAlignment = 2,
            });
            header.AddCell(new PdfPCell(new Phrase(contactNo, fontArial11))
            {
                Border = 0, PaddingTop = 5f
            });
            header.AddCell(new PdfPCell(new Phrase("Printed " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToString("hh:mm:ss tt"), fontArial11))
            {
                Border = 0, PaddingTop = 5f, HorizontalAlignment = 2
            });
            document.Add(header);
            document.Add(line);

            // ============
            // Branch Title
            // ============
            PdfPTable branchTitle = new PdfPTable(1);

            float[] widthCellsBranchTitle = new float[] { 100f };
            branchTitle.SetWidths(widthCellsBranchTitle);
            branchTitle.WidthPercentage = 100;
            PdfPCell branchHeaderColspan = (new PdfPCell(new Phrase(branch, fontArial12Bold))
            {
                HorizontalAlignment = 0, PaddingTop = 10f, Border = 0
            });

            branchTitle.AddCell(branchHeaderColspan);
            document.Add(branchTitle);

            // =====
            // Space
            // =====
            PdfPTable spaceTable = new PdfPTable(1);

            float[] widthCellsSpaceTable = new float[] { 100f };
            spaceTable.SetWidths(widthCellsSpaceTable);
            spaceTable.WidthPercentage = 100;
            spaceTable.AddCell(new PdfPCell(new Phrase(" ", fontArial10Bold))
            {
                Border = 0, PaddingTop = 5f
            });
            document.Add(spaceTable);

            Decimal totalOverallAssets      = 0;
            Decimal totalOverallLiabilities = 0;
            Decimal totalOverallEquities    = 0;

            // ==========
            // Get Assets
            // ==========
            var assets = from d in db.TrnJournals
                         where d.JournalDate <= Convert.ToDateTime(DateAsOf) &&
                         d.MstAccount.MstAccountType.MstAccountCategory.Id == 1 &&
                         d.MstBranch.CompanyId == CompanyId &&
                         d.BranchId == BranchId
                         group d by d.MstAccount into g
                         select new
            {
                DocumentReference      = "1 - Asset",
                AccountCategoryCode    = g.Key.MstAccountType.MstAccountCategory.AccountCategoryCode,
                AccountCategory        = g.Key.MstAccountType.MstAccountCategory.AccountCategory,
                SubCategoryDescription = g.Key.MstAccountType.SubCategoryDescription,
                AccountTypeCode        = g.Key.MstAccountType.AccountTypeCode,
                AccountType            = g.Key.MstAccountType.AccountType,
                AccountCode            = g.Key.AccountCode,
                Account      = g.Key.Account,
                DebitAmount  = g.Sum(d => d.DebitAmount),
                CreditAmount = g.Sum(d => d.CreditAmount),
                Balance      = g.Sum(d => d.DebitAmount - d.CreditAmount)
            };

            if (assets.Any())
            {
                // ==============================
                // Asset Sub Category Description
                // ==============================
                var assetSubCategoryDescriptions = from d in assets
                                                   group d by new
                {
                    SubCategoryDescription = d.SubCategoryDescription
                } into g
                    select new
                {
                    SubCategoryDescription = g.Key.SubCategoryDescription,
                    Balance = g.Sum(d => d.DebitAmount - d.CreditAmount)
                };

                if (assetSubCategoryDescriptions.Any())
                {
                    Decimal totalAllAssets = 0;
                    foreach (var assetSubCategoryDescription in assetSubCategoryDescriptions)
                    {
                        PdfPTable assetSubCategoryDescriptionTable           = new PdfPTable(1);
                        float[]   widthCellsAssetSubCategoryDescriptionTable = new float[] { 100f };
                        assetSubCategoryDescriptionTable.SetWidths(widthCellsAssetSubCategoryDescriptionTable);
                        assetSubCategoryDescriptionTable.WidthPercentage = 100;
                        assetSubCategoryDescriptionTable.AddCell(new PdfPCell(new Phrase(assetSubCategoryDescription.SubCategoryDescription, fontArial10Bold))
                        {
                            Border = 0, HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 6f, BackgroundColor = BaseColor.LIGHT_GRAY
                        });
                        document.Add(assetSubCategoryDescriptionTable);

                        // ===================
                        // Asset Account Types
                        // ===================
                        var assetAccountTypes = from d in assets
                                                where d.SubCategoryDescription.Equals(assetSubCategoryDescription.SubCategoryDescription)
                                                group d by new
                        {
                            AccountType = d.AccountType
                        } into g
                            select new
                        {
                            AccountType = g.Key.AccountType,
                            Balance     = g.Sum(d => d.DebitAmount - d.CreditAmount)
                        };

                        if (assetAccountTypes.Any())
                        {
                            Decimal totalCurrentAssets = 0;
                            foreach (var assetAccountType in assetAccountTypes)
                            {
                                totalCurrentAssets += assetAccountType.Balance;

                                PdfPTable assetAccountTypeTable           = new PdfPTable(3);
                                float[]   widthCellsAssetAccountTypeTable = new float[] { 50f, 100f, 50f };
                                assetAccountTypeTable.SetWidths(widthCellsAssetAccountTypeTable);
                                assetAccountTypeTable.WidthPercentage = 100;
                                assetAccountTypeTable.AddCell(new PdfPCell(new Phrase(assetAccountType.AccountType, fontArial10Bold))
                                {
                                    Border = 0, HorizontalAlignment = 0, PaddingTop = 10f, PaddingBottom = 5f, PaddingLeft = 25f
                                });
                                assetAccountTypeTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                                {
                                    Border = 0, HorizontalAlignment = 0, PaddingTop = 10f, PaddingBottom = 5f
                                });
                                assetAccountTypeTable.AddCell(new PdfPCell(new Phrase(assetAccountType.Balance.ToString("#,##0.00"), fontArial10Bold))
                                {
                                    Border = 0, HorizontalAlignment = 2, PaddingTop = 10f, PaddingBottom = 5f
                                });
                                document.Add(assetAccountTypeTable);

                                // ==============
                                // Asset Accounts
                                // ==============
                                var assetAccounts = from d in assets
                                                    where d.AccountType.Equals(assetAccountType.AccountType)
                                                    group d by new
                                {
                                    AccountCode = d.AccountCode,
                                    Account     = d.Account
                                } into g
                                    select new
                                {
                                    AccountCode  = g.Key.AccountCode,
                                    Account      = g.Key.Account,
                                    DebitAmount  = g.Sum(d => d.DebitAmount),
                                    CreditAmount = g.Sum(d => d.CreditAmount),
                                    Balance      = g.Sum(d => d.DebitAmount - d.CreditAmount)
                                };

                                if (assetAccounts.Any())
                                {
                                    foreach (var assetAccount in assetAccounts)
                                    {
                                        totalAllAssets += assetAccount.Balance;

                                        PdfPTable assetAccountTable           = new PdfPTable(3);
                                        float[]   widthCellsAssetAccountTable = new float[] { 50f, 100f, 50f };
                                        assetAccountTable.SetWidths(widthCellsAssetAccountTable);
                                        assetAccountTable.WidthPercentage = 100;
                                        assetAccountTable.AddCell(new PdfPCell(new Phrase(assetAccount.AccountCode, fontArial10))
                                        {
                                            Border = 0, HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingLeft = 50f
                                        });
                                        assetAccountTable.AddCell(new PdfPCell(new Phrase(assetAccount.Account, fontArial10))
                                        {
                                            Border = 0, HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingLeft = 20f
                                        });
                                        assetAccountTable.AddCell(new PdfPCell(new Phrase(assetAccount.Balance.ToString("#,##0.00"), fontArial10))
                                        {
                                            Border = 0, HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 5f
                                        });
                                        document.Add(assetAccountTable);
                                    }
                                }
                            }

                            // ====================
                            // Total Current Assets
                            // ====================
                            document.Add(line);
                            PdfPTable totalCurrentAssetsTable           = new PdfPTable(5);
                            float[]   widthCellsTotalCurrentAssetsTable = new float[] { 50f, 70f, 100f, 100f, 60f };
                            totalCurrentAssetsTable.SetWidths(widthCellsTotalCurrentAssetsTable);
                            totalCurrentAssetsTable.WidthPercentage = 100;
                            totalCurrentAssetsTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            totalCurrentAssetsTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            totalCurrentAssetsTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            totalCurrentAssetsTable.AddCell(new PdfPCell(new Phrase("Total " + assetSubCategoryDescription.SubCategoryDescription, fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            totalCurrentAssetsTable.AddCell(new PdfPCell(new Phrase(totalCurrentAssets.ToString("#,##0.00"), fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            document.Add(totalCurrentAssetsTable);
                        }
                    }

                    // ================
                    // Total All Assets
                    // ================
                    document.Add(line);
                    PdfPTable totalAllAssetsTable           = new PdfPTable(5);
                    float[]   widthCellsTotalAllAssetsTable = new float[] { 50f, 70f, 100f, 100f, 60f };
                    totalAllAssetsTable.SetWidths(widthCellsTotalAllAssetsTable);
                    totalAllAssetsTable.WidthPercentage = 100;
                    totalAllAssetsTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    totalAllAssetsTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    totalAllAssetsTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    totalAllAssetsTable.AddCell(new PdfPCell(new Phrase("Total Asset", fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    totalAllAssetsTable.AddCell(new PdfPCell(new Phrase(totalAllAssets.ToString("#,##0.00"), fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    document.Add(totalAllAssetsTable);

                    totalOverallAssets += totalAllAssets;
                    document.Add(Chunk.NEWLINE);
                }
            }

            // ===============
            // Get Liabilities
            // ===============
            var liabilities = from d in db.TrnJournals
                              where d.JournalDate <= Convert.ToDateTime(DateAsOf) &&
                              d.MstAccount.MstAccountType.MstAccountCategory.Id == 2 &&
                              d.MstBranch.CompanyId == CompanyId &&
                              d.BranchId == BranchId
                              group d by d.MstAccount into g
                              select new
            {
                DocumentReference      = "2 - Liability",
                AccountCategoryCode    = g.Key.MstAccountType.MstAccountCategory.AccountCategoryCode,
                AccountCategory        = g.Key.MstAccountType.MstAccountCategory.AccountCategory,
                SubCategoryDescription = g.Key.MstAccountType.SubCategoryDescription,
                AccountTypeCode        = g.Key.MstAccountType.AccountTypeCode,
                AccountType            = g.Key.MstAccountType.AccountType,
                AccountCode            = g.Key.AccountCode,
                Account      = g.Key.Account,
                DebitAmount  = g.Sum(d => d.DebitAmount),
                CreditAmount = g.Sum(d => d.CreditAmount),
                Balance      = g.Sum(d => d.CreditAmount - d.DebitAmount)
            };

            if (liabilities.Any())
            {
                // ==================================
                // Liability Sub Category Description
                // ==================================
                var liabilitySubCategoryDescriptions = from d in liabilities
                                                       group d by new
                {
                    SubCategoryDescription = d.SubCategoryDescription
                } into g
                    select new
                {
                    SubCategoryDescription = g.Key.SubCategoryDescription,
                    Balance = g.Sum(d => d.CreditAmount - d.DebitAmount)
                };

                if (liabilitySubCategoryDescriptions.Any())
                {
                    Decimal totalAllLiabilities = 0;
                    foreach (var liabilitySubCategoryDescription in liabilitySubCategoryDescriptions)
                    {
                        PdfPTable liabilitySubCategoryDescriptionTable           = new PdfPTable(1);
                        float[]   widthCellsLiabilitySubCategoryDescriptionTable = new float[] { 100f };
                        liabilitySubCategoryDescriptionTable.SetWidths(widthCellsLiabilitySubCategoryDescriptionTable);
                        liabilitySubCategoryDescriptionTable.WidthPercentage = 100;
                        liabilitySubCategoryDescriptionTable.AddCell(new PdfPCell(new Phrase(liabilitySubCategoryDescription.SubCategoryDescription, fontArial10Bold))
                        {
                            Border = 0, HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 6f, BackgroundColor = BaseColor.LIGHT_GRAY
                        });
                        document.Add(liabilitySubCategoryDescriptionTable);

                        // =======================
                        // Liability Account Types
                        // =======================
                        var liabilityAccountTypes = from d in liabilities
                                                    where d.SubCategoryDescription.Equals(liabilitySubCategoryDescription.SubCategoryDescription)
                                                    group d by new
                        {
                            AccountType = d.AccountType
                        } into g
                            select new
                        {
                            AccountType = g.Key.AccountType,
                            Balance     = g.Sum(d => d.CreditAmount - d.DebitAmount)
                        };

                        if (liabilityAccountTypes.Any())
                        {
                            Decimal totalCurrentLiabilities = 0;
                            foreach (var liabilityAccountType in liabilityAccountTypes)
                            {
                                totalCurrentLiabilities += liabilityAccountType.Balance;

                                PdfPTable liabilityAccountTypeTable           = new PdfPTable(3);
                                float[]   widthCellsLiabilityAccountTypeTable = new float[] { 50f, 100f, 50f };
                                liabilityAccountTypeTable.SetWidths(widthCellsLiabilityAccountTypeTable);
                                liabilityAccountTypeTable.WidthPercentage = 100;
                                liabilityAccountTypeTable.AddCell(new PdfPCell(new Phrase(liabilityAccountType.AccountType, fontArial10Bold))
                                {
                                    Border = 0, HorizontalAlignment = 0, PaddingTop = 10f, PaddingBottom = 5f, PaddingLeft = 25f
                                });
                                liabilityAccountTypeTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                                {
                                    Border = 0, HorizontalAlignment = 0, PaddingTop = 10f, PaddingBottom = 5f
                                });
                                liabilityAccountTypeTable.AddCell(new PdfPCell(new Phrase(liabilityAccountType.Balance.ToString("#,##0.00"), fontArial10Bold))
                                {
                                    Border = 0, HorizontalAlignment = 2, PaddingTop = 10f, PaddingBottom = 5f
                                });
                                document.Add(liabilityAccountTypeTable);

                                // ==================
                                // Liability Accounts
                                // ==================
                                var liabilityAccounts = from d in liabilities
                                                        where d.AccountType.Equals(liabilityAccountType.AccountType)
                                                        group d by new
                                {
                                    AccountCode = d.AccountCode,
                                    Account     = d.Account
                                } into g
                                    select new
                                {
                                    AccountCode  = g.Key.AccountCode,
                                    Account      = g.Key.Account,
                                    DebitAmount  = g.Sum(d => d.DebitAmount),
                                    CreditAmount = g.Sum(d => d.CreditAmount),
                                    Balance      = g.Sum(d => d.CreditAmount - d.DebitAmount)
                                };

                                if (liabilityAccounts.Any())
                                {
                                    foreach (var liabilityAccount in liabilityAccounts)
                                    {
                                        totalAllLiabilities += liabilityAccount.Balance;

                                        PdfPTable liabilityAccountTable           = new PdfPTable(3);
                                        float[]   widthCellsLiabilityAccountTable = new float[] { 50f, 100f, 50f };
                                        liabilityAccountTable.SetWidths(widthCellsLiabilityAccountTable);
                                        liabilityAccountTable.WidthPercentage = 100;
                                        liabilityAccountTable.AddCell(new PdfPCell(new Phrase(liabilityAccount.AccountCode, fontArial10))
                                        {
                                            Border = 0, HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingLeft = 50f
                                        });
                                        liabilityAccountTable.AddCell(new PdfPCell(new Phrase(liabilityAccount.Account, fontArial10))
                                        {
                                            Border = 0, HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingLeft = 20f
                                        });
                                        liabilityAccountTable.AddCell(new PdfPCell(new Phrase(liabilityAccount.Balance.ToString("#,##0.00"), fontArial10))
                                        {
                                            Border = 0, HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 5f
                                        });
                                        document.Add(liabilityAccountTable);
                                    }
                                }
                            }

                            // =========================
                            // Total Current Liabilities
                            // =========================
                            document.Add(line);
                            PdfPTable totalCurrentLiabilitiesTable           = new PdfPTable(5);
                            float[]   widthCellsTotalCurrentLiabilitiesTable = new float[] { 50f, 70f, 100f, 100f, 60f };
                            totalCurrentLiabilitiesTable.SetWidths(widthCellsTotalCurrentLiabilitiesTable);
                            totalCurrentLiabilitiesTable.WidthPercentage = 100;
                            totalCurrentLiabilitiesTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            totalCurrentLiabilitiesTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            totalCurrentLiabilitiesTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            totalCurrentLiabilitiesTable.AddCell(new PdfPCell(new Phrase("Total " + liabilitySubCategoryDescription.SubCategoryDescription, fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            totalCurrentLiabilitiesTable.AddCell(new PdfPCell(new Phrase(totalCurrentLiabilities.ToString("#,##0.00"), fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            document.Add(totalCurrentLiabilitiesTable);
                        }
                    }

                    // =====================
                    // Total All Liabilities
                    // =====================
                    document.Add(line);
                    PdfPTable totalAllLiabilitiesTable           = new PdfPTable(5);
                    float[]   widthCellsTotalAllLiabilitiesTable = new float[] { 50f, 70f, 100f, 100f, 60f };
                    totalAllLiabilitiesTable.SetWidths(widthCellsTotalAllLiabilitiesTable);
                    totalAllLiabilitiesTable.WidthPercentage = 100;
                    totalAllLiabilitiesTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    totalAllLiabilitiesTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    totalAllLiabilitiesTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    totalAllLiabilitiesTable.AddCell(new PdfPCell(new Phrase("Total Liability", fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    totalAllLiabilitiesTable.AddCell(new PdfPCell(new Phrase(totalAllLiabilities.ToString("#,##0.00"), fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    document.Add(totalAllLiabilitiesTable);

                    totalOverallLiabilities += totalAllLiabilities;
                    document.Add(Chunk.NEWLINE);
                }
            }

            // ===================
            // Get Profit and Loss
            // ===================
            var profitAndLoss = from d in db.TrnJournals
                                where d.JournalDate <= Convert.ToDateTime(DateAsOf) &&
                                (d.MstAccount.MstAccountType.MstAccountCategory.Id == 5 || d.MstAccount.MstAccountType.MstAccountCategory.Id == 6) &&
                                d.MstBranch.CompanyId == CompanyId &&
                                d.BranchId == BranchId
                                group d by d.MstAccount into g
                                select new
            {
                DocumentReference      = "ProfitAndLoss",
                AccountCategoryCode    = g.Key.MstAccountType.MstAccountCategory.AccountCategoryCode,
                AccountCategory        = g.Key.MstAccountType.MstAccountCategory.AccountCategory,
                SubCategoryDescription = g.Key.MstAccountType.SubCategoryDescription,
                AccountTypeCode        = g.Key.MstAccountType.AccountTypeCode,
                AccountType            = g.Key.MstAccountType.AccountType,
                AccountCode            = g.Key.AccountCode,
                Account      = g.Key.Account,
                DebitAmount  = g.Sum(d => d.DebitAmount),
                CreditAmount = g.Sum(d => d.CreditAmount),
                Balance      = g.Sum(d => d.CreditAmount - d.DebitAmount)
            };

            // ============
            // Get Equities
            // ============
            var equities = from d in db.TrnJournals
                           where d.JournalDate <= Convert.ToDateTime(DateAsOf) &&
                           d.MstAccount.MstAccountType.MstAccountCategory.Id == 4 &&
                           d.MstBranch.CompanyId == CompanyId &&
                           d.BranchId == BranchId
                           group d by d.MstAccount into g
                           select new
            {
                DocumentReference      = "3 - Equity",
                AccountCategoryCode    = g.Key.MstAccountType.MstAccountCategory.AccountCategoryCode,
                AccountCategory        = g.Key.MstAccountType.MstAccountCategory.AccountCategory,
                SubCategoryDescription = g.Key.MstAccountType.SubCategoryDescription,
                AccountTypeCode        = g.Key.MstAccountType.AccountTypeCode,
                AccountType            = g.Key.MstAccountType.AccountType,
                AccountCode            = g.Key.AccountCode,
                Account      = g.Key.Account,
                DebitAmount  = g.Sum(d => d.DebitAmount),
                CreditAmount = g.Sum(d => d.CreditAmount),
                Balance      = g.Sum(d => d.CreditAmount - d.DebitAmount)
            };

            var currentUser   = from d in db.MstUsers where d.UserId == User.Identity.GetUserId() select d;
            var incomeAccount = from d in db.MstAccounts where d.Id == currentUser.FirstOrDefault().IncomeAccountId select d;

            var retainedEarnings = from d in profitAndLoss
                                   group d by d.DocumentReference into g
                                   select new
            {
                DocumentReference      = "3 - Equity",
                AccountCategoryCode    = incomeAccount.FirstOrDefault().MstAccountType.MstAccountCategory.AccountCategoryCode,
                AccountCategory        = incomeAccount.FirstOrDefault().MstAccountType.MstAccountCategory.AccountCategory,
                SubCategoryDescription = incomeAccount.FirstOrDefault().MstAccountType.SubCategoryDescription,
                AccountTypeCode        = incomeAccount.FirstOrDefault().MstAccountType.AccountTypeCode,
                AccountType            = incomeAccount.FirstOrDefault().MstAccountType.AccountType,
                AccountCode            = incomeAccount.FirstOrDefault().AccountCode,
                Account      = incomeAccount.FirstOrDefault().Account,
                DebitAmount  = g.Sum(d => d.DebitAmount),
                CreditAmount = g.Sum(d => d.CreditAmount),
                Balance      = g.Sum(d => d.Balance),
            };

            var unionEquitiesWithRetainEarnings = equities.Union(retainedEarnings);

            if (unionEquitiesWithRetainEarnings.Any())
            {
                // ================================
                // Equity Sub Category Descriptions
                // ================================
                var equitySubCategoryDescriptions = from d in unionEquitiesWithRetainEarnings
                                                    group d by new
                {
                    SubCategoryDescription = d.SubCategoryDescription
                } into g
                    select new
                {
                    SubCategoryDescription = g.Key.SubCategoryDescription,
                    Balance = g.Sum(d => d.CreditAmount - d.DebitAmount)
                };

                if (equitySubCategoryDescriptions.Any())
                {
                    Decimal totalAllEquities = 0;
                    foreach (var equitySubCategoryDescription in equitySubCategoryDescriptions)
                    {
                        PdfPTable equitySubCategoryDescriptionTable           = new PdfPTable(1);
                        float[]   widthCellsEquitySubCategoryDescriptionTable = new float[] { 100f };
                        equitySubCategoryDescriptionTable.SetWidths(widthCellsEquitySubCategoryDescriptionTable);
                        equitySubCategoryDescriptionTable.WidthPercentage = 100;
                        equitySubCategoryDescriptionTable.AddCell(new PdfPCell(new Phrase(equitySubCategoryDescription.SubCategoryDescription, fontArial10Bold))
                        {
                            Border = 0, HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 6f, BackgroundColor = BaseColor.LIGHT_GRAY
                        });
                        document.Add(equitySubCategoryDescriptionTable);

                        // ====================
                        // Equity Account Types
                        // ====================
                        var equityAccountTypes = from d in unionEquitiesWithRetainEarnings
                                                 where d.SubCategoryDescription.Equals(equitySubCategoryDescription.SubCategoryDescription)
                                                 group d by new
                        {
                            AccountType = d.AccountType
                        } into g
                            select new
                        {
                            AccountType = g.Key.AccountType,
                            Balance     = g.Sum(d => d.CreditAmount - d.DebitAmount)
                        };

                        if (equityAccountTypes.Any())
                        {
                            Decimal totalCurrentEquities = 0;
                            foreach (var equityAccountType in equityAccountTypes)
                            {
                                totalCurrentEquities += equityAccountType.Balance;

                                PdfPTable equityAccountTypeTable           = new PdfPTable(3);
                                float[]   widthCellsEquityAccountTypeTable = new float[] { 50f, 100f, 50f };
                                equityAccountTypeTable.SetWidths(widthCellsEquityAccountTypeTable);
                                equityAccountTypeTable.WidthPercentage = 100;
                                equityAccountTypeTable.AddCell(new PdfPCell(new Phrase(equityAccountType.AccountType, fontArial10Bold))
                                {
                                    Border = 0, HorizontalAlignment = 0, PaddingTop = 10f, PaddingBottom = 5f, PaddingLeft = 25f
                                });
                                equityAccountTypeTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                                {
                                    Border = 0, HorizontalAlignment = 0, PaddingTop = 10f, PaddingBottom = 5f
                                });
                                equityAccountTypeTable.AddCell(new PdfPCell(new Phrase(equityAccountType.Balance.ToString("#,##0.00"), fontArial10Bold))
                                {
                                    Border = 0, HorizontalAlignment = 2, PaddingTop = 10f, PaddingBottom = 5f
                                });
                                document.Add(equityAccountTypeTable);

                                // ===============
                                // Equity Accounts
                                // ===============
                                var equityAccounts = from d in unionEquitiesWithRetainEarnings
                                                     where d.AccountType.Equals(equityAccountType.AccountType)
                                                     group d by new
                                {
                                    AccountCode = d.AccountCode,
                                    Account     = d.Account
                                } into g
                                    select new
                                {
                                    AccountCode  = g.Key.AccountCode,
                                    Account      = g.Key.Account,
                                    DebitAmount  = g.Sum(d => d.DebitAmount),
                                    CreditAmount = g.Sum(d => d.CreditAmount),
                                    Balance      = g.Sum(d => d.CreditAmount - d.DebitAmount)
                                };

                                if (equityAccounts.Any())
                                {
                                    foreach (var equityAccount in equityAccounts)
                                    {
                                        totalAllEquities += equityAccount.Balance;

                                        PdfPTable equityAccountTable           = new PdfPTable(3);
                                        float[]   widthCellsEquityAccountTable = new float[] { 50f, 100f, 50f };
                                        equityAccountTable.SetWidths(widthCellsEquityAccountTable);
                                        equityAccountTable.WidthPercentage = 100;
                                        equityAccountTable.AddCell(new PdfPCell(new Phrase(equityAccount.AccountCode, fontArial10))
                                        {
                                            Border = 0, HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingLeft = 50f
                                        });
                                        equityAccountTable.AddCell(new PdfPCell(new Phrase(equityAccount.Account, fontArial10))
                                        {
                                            Border = 0, HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingLeft = 20f
                                        });
                                        equityAccountTable.AddCell(new PdfPCell(new Phrase(equityAccount.Balance.ToString("#,##0.00"), fontArial10))
                                        {
                                            Border = 0, HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 5f
                                        });
                                        document.Add(equityAccountTable);
                                    }
                                }
                            }

                            // ======================
                            // Total Current Equities
                            // ======================
                            document.Add(line);
                            PdfPTable totalCurrentEquitiesTable           = new PdfPTable(5);
                            float[]   widthCellsTotalCurrentEquitiesTable = new float[] { 50f, 70f, 100f, 100f, 60f };
                            totalCurrentEquitiesTable.SetWidths(widthCellsTotalCurrentEquitiesTable);
                            totalCurrentEquitiesTable.WidthPercentage = 100;
                            totalCurrentEquitiesTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            totalCurrentEquitiesTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            totalCurrentEquitiesTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            totalCurrentEquitiesTable.AddCell(new PdfPCell(new Phrase("Total " + equitySubCategoryDescription.SubCategoryDescription, fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            totalCurrentEquitiesTable.AddCell(new PdfPCell(new Phrase(totalCurrentEquities.ToString("#,##0.00"), fontArial10Bold))
                            {
                                Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                            });
                            document.Add(totalCurrentEquitiesTable);
                        }
                    }

                    // ==================
                    // Total All Equities
                    // ==================
                    document.Add(line);
                    PdfPTable totalAllEquitiesTable           = new PdfPTable(5);
                    float[]   widthCellsTotalAllEquitiesTable = new float[] { 50f, 70f, 100f, 100f, 60f };
                    totalAllEquitiesTable.SetWidths(widthCellsTotalAllEquitiesTable);
                    totalAllEquitiesTable.WidthPercentage = 100;
                    totalAllEquitiesTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    totalAllEquitiesTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    totalAllEquitiesTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    totalAllEquitiesTable.AddCell(new PdfPCell(new Phrase("Total Equity", fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    totalAllEquitiesTable.AddCell(new PdfPCell(new Phrase(totalAllEquities.ToString("#,##0.00"), fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                    });
                    document.Add(totalAllEquitiesTable);

                    totalOverallEquities += totalAllEquities;
                    document.Add(Chunk.NEWLINE);
                }
            }

            document.Add(Chunk.NEWLINE);

            // ==============================
            // Total Liabilities and Equities
            // ==============================
            Decimal totalLiabilityAndEquity = totalOverallLiabilities + totalOverallEquities;

            document.Add(line);
            PdfPTable tableTotalLiabilityAndEquityTable = new PdfPTable(5);

            float[] widthCellsTableTotalLiabilityAndEquityTable = new float[] { 50f, 70f, 100f, 100f, 60f };
            tableTotalLiabilityAndEquityTable.SetWidths(widthCellsTableTotalLiabilityAndEquityTable);
            tableTotalLiabilityAndEquityTable.WidthPercentage = 100;
            tableTotalLiabilityAndEquityTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
            {
                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
            });
            tableTotalLiabilityAndEquityTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
            {
                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
            });
            tableTotalLiabilityAndEquityTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
            {
                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
            });
            tableTotalLiabilityAndEquityTable.AddCell(new PdfPCell(new Phrase("Total Liability and Equity", fontArial10Bold))
            {
                Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
            });
            tableTotalLiabilityAndEquityTable.AddCell(new PdfPCell(new Phrase(totalLiabilityAndEquity.ToString("#,##0.00"), fontArial10Bold))
            {
                Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
            });
            document.Add(tableTotalLiabilityAndEquityTable);

            // =======
            // Balance
            // =======
            Decimal Balance = totalOverallAssets - totalLiabilityAndEquity;

            document.Add(line);
            PdfPTable balanceTable = new PdfPTable(5);

            float[] widthCellsBalanceTable = new float[] { 50f, 70f, 100f, 100f, 60f };
            balanceTable.SetWidths(widthCellsBalanceTable);
            balanceTable.WidthPercentage = 100;
            balanceTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
            {
                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
            });
            balanceTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
            {
                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
            });
            balanceTable.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
            {
                Border = 0, HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
            });
            balanceTable.AddCell(new PdfPCell(new Phrase("Balance", fontArial10Bold))
            {
                Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
            });
            balanceTable.AddCell(new PdfPCell(new Phrase(Balance.ToString("#,##0.00"), fontArial10Bold))
            {
                Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
            });
            document.Add(balanceTable);

            document.Close();

            byte[] byteInfo = workStream.ToArray();
            workStream.Write(byteInfo, 0, byteInfo.Length);
            workStream.Position = 0;

            return(new FileStreamResult(workStream, "application/pdf"));
        }
Exemplo n.º 39
0
 public Decimal GetCurrentValue(Decimal defaultOriginValue, Decimal defaultDestinationValue, AnimationClock animationClock)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 40
0
 protected abstract Decimal GetCurrentValueCore(Decimal defaultOriginValue, Decimal defaultDestinationValue, AnimationClock animationClock);
Exemplo n.º 41
0
        protected virtual void OnRecordFieldTypeAssessment(IDictionary <string, Type> fieldTypes, IDictionary <string, object> fieldValues, bool isLastScanRow = false)
        {
            CultureInfo ci = Thread.CurrentThread.CurrentCulture;

            foreach (var key in fieldTypes.Keys.ToArray())
            {
                if (!fieldValues.ContainsKey(key))
                {
                    continue;
                }

                object value     = fieldValues[key];
                Type   fieldType = null;
                if (fieldTypes[key] == typeof(string))
                {
                    continue;
                }

                if (value == null ||
                    (value is string && ((string)value).IsNullOrWhiteSpace()))
                {
                    //if (isLastScanRow)
                    //    fieldTypes[key] = typeof(string);
                    //else
                    continue;
                }

                bool        boolValue;
                long        lresult   = 0;
                double      dresult   = 0;
                decimal     decResult = 0;
                DateTime    dtResult;
                ChoCurrency currResult = 0;
                Guid        guidResult;
                bool        treatCurrencyAsDecimal = RecordConfiguration.TypeConverterFormatSpec.TreatCurrencyAsDecimal;

                if (ChoBoolean.TryParse(value.ToNString(), out boolValue))
                {
                    fieldType = typeof(bool);
                }
                else if (Guid.TryParse(value.ToNString(), out guidResult))
                {
                    fieldType = typeof(Guid);
                }
                else if (!value.ToNString().Contains(ci.NumberFormat.NumberDecimalSeparator) && long.TryParse(value.ToNString(), out lresult))
                {
                    fieldType = typeof(long);
                }
                else if (double.TryParse(value.ToNString(), out dresult))
                {
                    fieldType = typeof(double);
                }
                else if (decimal.TryParse(value.ToNString(), out decResult))
                {
                    fieldType = typeof(decimal);
                }
                else if (!treatCurrencyAsDecimal && ChoCurrency.TryParse(value.ToNString(), out currResult))
                {
                    fieldType = typeof(ChoCurrency);
                }
                else if (treatCurrencyAsDecimal && Decimal.TryParse(value.ToNString(), NumberStyles.Currency, CultureInfo.CurrentCulture, out decResult))
                {
                    fieldType = typeof(Decimal);
                }
                else if (!RecordConfiguration.TypeConverterFormatSpec.DateTimeFormat.IsNullOrWhiteSpace() &&
                         ChoDateTime.TryParseExact(value.ToNString(), RecordConfiguration.TypeConverterFormatSpec.DateTimeFormat, CultureInfo.CurrentCulture, out dtResult))
                {
                    fieldType = typeof(DateTime);
                }
                else if (DateTime.TryParse(value.ToNString(), out dtResult))
                {
                    fieldType = typeof(DateTime);
                }
                else
                {
                    if (value.ToNString().Length == 1)
                    {
                        fieldType = typeof(char);
                    }
                    else
                    {
                        fieldType = typeof(string);
                    }
                }

                if (fieldType == typeof(string))
                {
                    fieldTypes[key] = fieldType;
                }
                else if (fieldType == typeof(ChoCurrency))
                {
                    if (fieldTypes[key] == null)
                    {
                        fieldTypes[key] = fieldType;
                    }
                    else if (fieldTypes[key] != typeof(ChoCurrency))
                    {
                        fieldTypes[key] = typeof(string);
                    }
                }
                else if (fieldType == typeof(Guid))
                {
                    if (fieldTypes[key] == null)
                    {
                        fieldTypes[key] = fieldType;
                    }
                    else if (fieldTypes[key] != typeof(Guid))
                    {
                        fieldTypes[key] = typeof(string);
                    }
                }
                else if (fieldType == typeof(DateTime))
                {
                    if (fieldTypes[key] == null)
                    {
                        fieldTypes[key] = fieldType;
                    }
                    else if (fieldTypes[key] != typeof(DateTime))
                    {
                        fieldTypes[key] = typeof(string);
                    }
                }
                else if (fieldType == typeof(decimal))
                {
                    if (fieldTypes[key] == null)
                    {
                        fieldTypes[key] = fieldType;
                    }
                    else if (fieldTypes[key] == typeof(DateTime))
                    {
                        fieldTypes[key] = typeof(string);
                    }
                    else if (fieldTypes[key] == typeof(double) ||
                             fieldTypes[key] == typeof(long) ||
                             fieldTypes[key] == typeof(bool))
                    {
                        fieldTypes[key] = fieldType;
                    }
                }
                else if (fieldType == typeof(double))
                {
                    if (fieldTypes[key] == null)
                    {
                        fieldTypes[key] = fieldType;
                    }
                    else if (fieldTypes[key] == typeof(DateTime))
                    {
                        fieldTypes[key] = typeof(string);
                    }
                    else if (fieldTypes[key] == typeof(long) ||
                             fieldTypes[key] == typeof(bool))
                    {
                        fieldTypes[key] = fieldType;
                    }
                }
                else if (fieldType == typeof(long))
                {
                    if (fieldTypes[key] == null)
                    {
                        fieldTypes[key] = fieldType;
                    }
                    else if (fieldTypes[key] == typeof(DateTime))
                    {
                        fieldTypes[key] = typeof(string);
                    }
                    else if (fieldTypes[key] == typeof(bool))
                    {
                        fieldTypes[key] = fieldType;
                    }
                }
                else if (fieldType == typeof(bool))
                {
                    if (fieldTypes[key] == null)
                    {
                        fieldTypes[key] = fieldType;
                    }
                }
                else if (fieldType == typeof(char))
                {
                    if (fieldTypes[key] == null)
                    {
                        fieldTypes[key] = fieldType;
                    }
                }
                else
                {
                    fieldType = typeof(string);
                }
            }
            if (isLastScanRow)
            {
                foreach (var key in fieldTypes.Keys.ToArray())
                {
                    if (fieldTypes[key] == null)
                    {
                        fieldTypes[key] = typeof(string);
                    }
                }
            }
        }
Exemplo n.º 42
0
        } //dgv_ShowFills_CellMouseClick()

        public static void dgv_ShowFillsSystemMenuItem_Click(object sender, MouseEventArgs e)
        {
            //
            // Purpose: A generic menu click event for the Order Right-Click
            //

            // Local Variables
            ToolStripMenuItem ts_From      = (ToolStripMenuItem)sender;
            OrderMenuStruct   myOrderStr   = (OrderMenuStruct)ts_From.Tag;
            String            myQuestion   = "";
            String            myMessage    = "";
            String            OrderRefID   = myOrderStr.OrderRefID;
            Decimal           Quantity     = myOrderStr.Quantity;
            Decimal           FillAmount   = myOrderStr.FillAmount;
            Decimal           RoutedAmount = myOrderStr.RoutedAmount;
            ShowFillStatus    myForm       = myOrderStr.myParentForm;


            if (OrderRefID.Length > 0)
            {
                switch (myOrderStr.Instruction)
                {
                case "Delete":
                    if (myOrderStr.FillAmount != 0)
                    {
                        myQuestion = "WARNING: This order has already been filled " + myOrderStr.FillAmount.ToString("#,###") + " @" + myOrderStr.FillPrice.ToString("#,###.####") + ", so you should 'Resize to Fill' rather than Delete\r\n\r\n";
                    }
                    else if (myOrderStr.RoutedAmount != 0)
                    {
                        myQuestion = "WARNING: Part of this order has already been routed " + myOrderStr.RoutedAmount.ToString("#,###") + " and should be cancelled first.\r\n\r\n";
                    }
                    myQuestion = myQuestion +
                                 "You are about to Delete the Order for\r\n\r\n" +
                                 myOrderStr.Side + " " + myOrderStr.Quantity + "  " + myOrderStr.BBG_Ticker + "\r\n";
                    if (myOrderStr.EMSX_Sequence.Length > 0)
                    {
                        myQuestion = myQuestion + "\r\nBloomberg Order# " + myOrderStr.EMSX_Sequence;
                    }
                    myQuestion = myQuestion + "\r\n\r\n" + "Is this Ok?";

                    if (MessageBox.Show(myQuestion, "Delete Order", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        if (myOrderStr.EMSX_Sequence.Length > 0)
                        {
                            myMessage = SendToBloomberg.EMSXAPI_Delete(OrderRefID);
                        }

                        if (myMessage.Length > 0)
                        {
                            if (MessageBox.Show("We received the UNEXPECTED message below from Bloomberg while trying to delete the order.\r\n\r\n" +
                                                "Do you wish to continue with the Delete?\r\n\r\n" +
                                                "=============================================\r\n\r\n\r\n" +
                                                myMessage, "Delete Order", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                            {
                                return;
                            }
                        }

                        // Delete the Order
                        SystemLibrary.SQLExecute("Exec sp_ReverseOrder '" + OrderRefID + "'");
                        myForm.bt_Refresh_Click(null, null);

                        // Update The Positions Table
                        myForm.NeedUpdate     = true;
                        myForm.NeedFullUpdate = true;
                        // Refresh the Portfolio Tab
                        //myForm.ParentForm1.LoadPortfolioIncr();

                        // Report what Bloomberg says
                        if (myMessage.Length > 0)
                        {
                            SystemLibrary.SQLExecute("Exec sp_Fills_From_EMSX_API");
                            MessageBox.Show("Changed in the Portfolio Management System, but received this messagae from Bloomberg.\r\n\r\n" + myMessage, myOrderStr.Instruction);
                        }
                    }
                    break;

                case "ResizeToFill":
                    myQuestion = "You are about to Resize the Order for\r\n\r\n" +
                                 myOrderStr.Side + " " + myOrderStr.FormattedQuantity + "  " + myOrderStr.BBG_Ticker + "\r\n\n" +
                                 "To the FillAmount of " + myOrderStr.FormattedFillAmount + "\r\n\r\n" +
                                 "Is this Ok?";

                    if (Math.Abs(RoutedAmount) > Math.Abs(FillAmount))
                    {
                        myQuestion = "WARNING: The Routed part of this order (" + myOrderStr.RoutedAmount.ToString("#,###") + ") is greater than the Filled Amount (" + myOrderStr.FillAmount.ToString("#,###") + ") and should be cancelled first.\r\n\r\n" +
                                     myQuestion;
                    }

                    if (FillAmount == 0)
                    {
                        MessageBox.Show("The Order has not been Filled (Fill Amount = 0).\r\n\r\nPlease use the [Delete Order] menu if that is your intention", "Resize order to Fill Amount");
                    }
                    else if (MessageBox.Show(myQuestion, "Resize Order", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        myMessage = SendToBloomberg.EMSXAPI_Modify(OrderRefID, myOrderStr.BBG_Ticker, Convert.ToInt32(myOrderStr.FillAmount));

                        // Resize the Order
                        SystemLibrary.SQLExecute("Exec sp_ResizeOrder '" + OrderRefID + "', " + myOrderStr.FillAmount.ToString());
                        myForm.bt_Refresh_Click(null, null);

                        // Update The Positions Table
                        myForm.NeedUpdate = true;
                        // Refresh the Portfolio Tab
                        //myForm.ParentForm1.LoadPortfolioIncr();

                        // Report what Bloomberg says
                        if (myMessage.Length > 0)
                        {
                            MessageBox.Show("Changed in the Portfolio Management System, but received this messagae from Bloomberg.\r\n\r\n" + myMessage, myOrderStr.Instruction);
                        }
                    }
                    break;

                case "ResizeToRouted":
                    if (RoutedAmount == 0)
                    {
                        MessageBox.Show("The Order has not been Routed (Routed Amount = 0).\r\n\r\nPlease use the [Delete Order] menu if that is your intention", "Resize order to Routed Amount");
                    }
                    else if (MessageBox.Show("You are about to Resize the Order for\r\n\r\n" +
                                             myOrderStr.Side + " " + myOrderStr.FormattedQuantity + "  " + myOrderStr.BBG_Ticker + "\r\n\n" +
                                             "To the RoutedAmount of " + myOrderStr.FormattedRoutedAmount + "\r\n\r\n" +
                                             "Is this Ok?", "Resize Order", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        myMessage = SendToBloomberg.EMSXAPI_Modify(OrderRefID, myOrderStr.BBG_Ticker, Convert.ToInt32(myOrderStr.RoutedAmount));

                        // Resize the Order
                        SystemLibrary.SQLExecute("Exec sp_ResizeOrder '" + OrderRefID + "', " + myOrderStr.RoutedAmount.ToString());
                        myForm.bt_Refresh_Click(null, null);

                        // Update The Positions Table
                        myForm.NeedUpdate = true;
                        // Refresh the Portfolio Tab
                        //myForm.ParentForm1.LoadPortfolioIncr();

                        // Report what Bloomberg says
                        if (myMessage.Length > 0)
                        {
                            MessageBox.Show("Changed in the Portfolio Management System, but received this messagae from Bloomberg.\r\n\r\n" + myMessage, myOrderStr.Instruction);
                        }
                    }
                    break;

                case "ResizeToDouble":
                    Decimal DoubleQuantity = myOrderStr.Quantity * 2;
                    if (MessageBox.Show("You are about to Double the Order for\r\n\r\n" +
                                        myOrderStr.Side + " " + myOrderStr.FormattedQuantity + "  " + myOrderStr.BBG_Ticker + "\r\n\n" +
                                        "Is this Ok?", "Resize Order", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        myMessage = SendToBloomberg.EMSXAPI_Modify(OrderRefID, myOrderStr.BBG_Ticker, Convert.ToInt32(DoubleQuantity));

                        // Resize the Order
                        SystemLibrary.SQLExecute("Exec sp_ResizeOrder '" + OrderRefID + "', " + DoubleQuantity.ToString());
                        myForm.bt_Refresh_Click(null, null);

                        // Update The Positions Table
                        myForm.NeedUpdate = true;
                        // Refresh the Portfolio Tab
                        //myForm.ParentForm1.LoadPortfolioIncr();

                        // Report what Bloomberg says
                        if (myMessage.Length > 0)
                        {
                            MessageBox.Show("Changed in the Portfolio Management System, but received this messagae from Bloomberg.\r\n\r\n" + myMessage, myOrderStr.Instruction);
                        }
                    }
                    break;

                case "ResizeOrder":
                    String myValue = myOrderStr.FormattedQuantity;
                    long   myQty;
                    String mySql;

                    if (SystemLibrary.InputBox("Resize Order for " + myOrderStr.BBG_Ticker + " from " + myOrderStr.FormattedQuantity, "Change the Size of the Order OR Cancel", ref myValue, myForm.validate_ResizOrder, MessageBoxIcon.Question) == DialogResult.OK)
                    {
                        myQty = SystemLibrary.ToInt32(myValue);
                        if (Math.Sign(myQty) != Math.Sign(myOrderStr.Quantity))
                        {
                            MessageBox.Show(@"Cannot swap between Buy & Sell.", "Resize aborted");
                            return;
                        }
                        if (Math.Abs(myQty) < Math.Abs(myOrderStr.FillAmount))
                        {
                            MessageBox.Show(@"Cannot resize below the Fill Amount of " + myOrderStr.FillAmount.ToString("#,###") + ".", "Resize aborted");
                            return;
                        }
                        if (Math.Abs(myQty) < Math.Abs(myOrderStr.RoutedAmount))
                        {
                            MessageBox.Show(@"Cannot resize below the Routed Amount of " + myOrderStr.RoutedAmount.ToString("#,###") + ".", "Resize aborted");
                            return;
                        }

                        myMessage = SendToBloomberg.EMSXAPI_Modify(OrderRefID, myOrderStr.BBG_Ticker, (Int32)myQty);

                        mySql = "Exec sp_ResizeOrder '" + OrderRefID + "', " + myQty.ToString();
                        SystemLibrary.SQLExecute(mySql);

                        myForm.bt_Refresh_Click(null, null);

                        // Update The Positions Table
                        myForm.NeedUpdate = true;
                        // Refresh the Portfolio Tab
                        //myForm.ParentForm1.LoadPortfolioIncr();

                        // Report what Bloomberg says
                        if (myMessage.Length > 0)
                        {
                            MessageBox.Show("Changed in the Portfolio Management System, but received this messagae from Bloomberg.\r\n\r\n" + myMessage, myOrderStr.Instruction);
                        }
                    }
                    break;
                }
            }
        } //dgv_ShowFillsSystemMenuItem_Click()
        public bool MeesageParsing(string msg_body, int msg_idnum)
        {
            bool result = false;

            try
            {
                #region Initialize values
                string[] msgBody;
                string[] rowLine;
                string   header;

                EDI315                  dbEDI315               = new EDI315();
                EDI315_Detail           dbEDI315_Detail        = new EDI315_Detail();
                List <EDI315_Detail_N9> dbEDI315_Detail_N9List = new List <EDI315_Detail_N9>();
                List <EDI315_Detail_R4> dbEDI315_Detail_R4List = new List <EDI315_Detail_R4>();

                int     convertToInt     = 0;
                decimal convertToDecimal = 0;
                #endregion

                msg_body = Regex.Replace(msg_body, @"^\s+$[\r\n]*", "", RegexOptions.Multiline);
                msgBody  = msg_body.Split(new[] { Environment.NewLine }, StringSplitOptions.None);

                foreach (string row in msgBody)
                {
                    if (row != null && row.Count() > 0)
                    {
                        rowLine = row.Split('*');

                        header = "";
                        if (EDI315_HEADERS.Any(x => x.ToUpper() == rowLine[0]))
                        {
                            header = rowLine[0];
                        }

                        switch (header)
                        {
                        case "ISA":
                            #region ISA
                            dbEDI315 = new EDI315()
                            {
                                msg_idnum = msg_idnum,
                                ISA_auth_info_qualifier                = rowLine[1] ?? "",
                                ISA_auth_info                          = rowLine[2] ?? "",
                                ISA_security_info_qualifier            = rowLine[3] ?? "",
                                ISA_security_info                      = rowLine[4] ?? "",
                                ISA_interchange_id_qualifier_1         = rowLine[5] ?? "",
                                ISA_interchange_sender_id              = rowLine[6] ?? "",
                                ISA_interchange_id_qualifier_2         = rowLine[7] ?? "",
                                ISA_interchange_receiver_id            = rowLine[8] ?? "",
                                ISA_interchage_date                    = rowLine[9] ?? "",
                                ISA_interchange_time                   = rowLine[10] ?? "",
                                ISA_interchange_control_standards_id   = rowLine[11] ?? "",
                                ISA_interchange_control_version_number = rowLine[12] ?? "",
                                ISA_interchange_control_number         = rowLine[13] ?? "",
                                ISA_ack_requested                      = rowLine[14] ?? "",
                                ISA_usage_indicator                    = rowLine[15] ?? "",
                                ISA_component_element_separator        = rowLine[16] ?? "",
                            };
                            #endregion
                            break;

                        case "GS":
                            // Table EDI315 insert here.
                            #region GS
                            dbEDI315.GS_functional_id_code = rowLine[1] ?? "";
                            dbEDI315.GS_app_sender_code    = rowLine[2] ?? "";
                            dbEDI315.GS_app_receiver_code  = rowLine[3] ?? "";
                            dbEDI315.GS_date = rowLine[4] ?? "";
                            dbEDI315.GS_time = rowLine[5] ?? "";
                            dbEDI315.GS_group_control_number   = rowLine[6] ?? "";
                            dbEDI315.GS_reponsible_agency_code = rowLine[7] ?? "";
                            dbEDI315.GS_industry_id_code       = rowLine[8] ?? "";

                            /* Insert table EDI315 after done with ISA & GS */
                            if (dbEDI315.msg_idnum != 0)
                            {
                                using (DBContext context = new DBContext())
                                {
                                    /* check DB is open */

                                    dbEDI315.created_date = DateTime.Now;
                                    context.EDI315.Add(dbEDI315);
                                    context.SaveChanges();
                                }
                            }
                            #endregion
                            break;

                        case "ST":
                            dbEDI315_Detail = new EDI315_Detail();

                            break;

                        case "SE":
                            // insert Table EDI315_Detail, EDI315_Detail_N9, EDI315_Detail_R4 & EDI315_Detail_R4_DTM
                            break;

                        case "B4":
                            #region B4
                            if (dbEDI315 == null || dbEDI315.EDI315_idnum == 0)
                            {
                                continue;
                            }

                            dbEDI315_Detail.B4_SHC = rowLine[1];

                            convertToInt = 0;
                            if (rowLine[2] != null && rowLine[2].Trim() != string.Empty && Int32.TryParse(rowLine[2], out convertToInt))
                            {
                                dbEDI315_Detail.B4_request_number = convertToInt;
                            }

                            dbEDI315_Detail.B4_status_code     = rowLine[3];
                            dbEDI315_Detail.B4_date            = rowLine[4] ?? "";
                            dbEDI315_Detail.B4_status_time     = rowLine[5] ?? "";
                            dbEDI315_Detail.B4_status_location = rowLine[6] ?? "";

                            dbEDI315_Detail.B4_equip_initial     = rowLine[7];
                            dbEDI315_Detail.B4_equip_number      = rowLine[8];
                            dbEDI315_Detail.B4_equip_status_code = rowLine[9];
                            dbEDI315_Detail.B4_equip_type        = rowLine[10];
                            dbEDI315_Detail.B4_location_code     = rowLine[11];
                            dbEDI315_Detail.B4_location_id       = rowLine[12];

                            if (rowLine.Count() > 13)
                            {
                                convertToInt = 0;
                                if (rowLine[13] != null && rowLine[13].Trim() != string.Empty && Int32.TryParse(rowLine[13], out convertToInt))
                                {
                                    dbEDI315_Detail.B4_equip_check_digit = convertToInt;
                                }
                            }
                            #endregion
                            break;

                        case "Q2":
                            #region Q2
                            if (dbEDI315 == null || dbEDI315.EDI315_idnum == 0)
                            {
                                continue;
                            }

                            dbEDI315_Detail.Q2_vessel_code  = rowLine[1];
                            dbEDI315_Detail.Q2_country_code = rowLine[2];
                            dbEDI315_Detail.Q2_date_1       = rowLine[3];
                            dbEDI315_Detail.Q2_date_2       = rowLine[4];
                            dbEDI315_Detail.Q2_date_3       = rowLine[5];

                            convertToInt = 0;
                            if (rowLine[6] != null && rowLine[6].Trim() != string.Empty && Int32.TryParse(rowLine[6], out convertToInt))
                            {
                                dbEDI315_Detail.Q2_lading_quantity = convertToInt;
                            }

                            convertToDecimal = 0;
                            if (rowLine[7] != null && rowLine[7].Trim() != string.Empty && Decimal.TryParse(rowLine[7], out convertToDecimal))
                            {
                                dbEDI315_Detail.Q2_weight = convertToDecimal;
                            }

                            dbEDI315_Detail.Q2_weight_qualifier       = rowLine[8];
                            dbEDI315_Detail.Q2_voyage_number          = rowLine[9];
                            dbEDI315_Detail.Q2_reference_id_qualifier = rowLine[10];
                            dbEDI315_Detail.Q2_reference_id           = rowLine[11];
                            dbEDI315_Detail.Q2_vessel_code_qualifier  = rowLine[12];
                            dbEDI315_Detail.Q2_vessel_name            = rowLine[13];

                            convertToDecimal = 0;
                            if (rowLine[14] != null && rowLine[14].Trim() != string.Empty && Decimal.TryParse(rowLine[14], out convertToDecimal))
                            {
                                dbEDI315_Detail.Q2_volume = convertToDecimal;
                            }

                            dbEDI315_Detail.Q2_volume_unit_qualifier = rowLine[15];
                            dbEDI315_Detail.Q2_weight_unit_code      = rowLine[16];
                            #endregion
                            break;

                        case "N9":
                            #region N9
                            if (dbEDI315 == null || dbEDI315.EDI315_idnum == 0)
                            {
                                continue;
                            }

                            EDI315_Detail_N9 dbTemp = new EDI315_Detail_N9();

                            dbTemp.reference_id_qualifier = rowLine[1];

                            if (rowLine.Count() > 2)
                            {
                                dbTemp.reference_id = rowLine[2];
                            }

                            if (rowLine.Count() > 3)
                            {
                                dbTemp.free_form_description = rowLine[3];
                            }

                            if (rowLine.Count() > 4)
                            {
                                dbTemp.free_form_description = rowLine[4];
                            }

                            if (rowLine.Count() > 5)
                            {
                                dbTemp.date = rowLine[5];
                            }

                            if (rowLine.Count() > 6)
                            {
                                dbTemp.time = rowLine[6];
                            }

                            if (rowLine.Count() > 7)
                            {
                                dbTemp.time_code = rowLine[7];
                            }

                            dbEDI315_Detail_N9List.Add(dbTemp);
                            #endregion
                            break;

                        case "R4":
                            break;

                        case "DTM":
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result = false;
            }

            return(result);
        }
Exemplo n.º 44
0
        public ActionResult Deposit(CardsViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View(viewModel));
            }

            var info = new RequestInfo
            {
                //Merchant site id
                Merchant_id = _merchantId,
                //Email tài khoản nhận tiền khi nạp
                Merchant_acount = _merchantEmail,
                //Mật khẩu giao tiếp khi đăng ký merchant site
                Merchant_password = _merchantPassword,

                //Nhà mạng
                CardType = viewModel.CardType,
                Pincard  = viewModel.PinCard,

                //Mã đơn hàng
                Refcode    = (new Random().Next(0, 10000)).ToString(),
                SerialCard = viewModel.SerialCard
            };

            var    result      = NLCardLib.CardChage(info);
            string html        = "";
            var    applyResult = new CardsViewModel();

            if (result.Errorcode.Equals("00"))
            {
                html += "<div>" + result.Message + "</div>";
                html += "<div>Số tiền nạp : <b>" + result.Card_amount + "</b> đ</div>";
                html += "<div>Mã giao dịch : <b>" + result.TransactionID + "</b></div>";
                html += "<div>Mã đơn hàng : <b>" + result.Refcode + "</b></div>";

                applyResult.Result.Message = html;
                applyResult.Result.Result  = true;

                var coin = int.Parse(result.Card_amount);
                coin = (coin / 1000 * 8) / 10;
                _applicationUserService.UpdateCoin(User.Identity.GetUserId(), coin);
                _applicationUserService.SaveChanges();

                var transactionHistory = new TransactionHistory
                {
                    CardOwner   = User.Identity.GetUserId(),
                    Description = $"Mã thẻ: {info.Pincard} | Seri thẻ: { info.SerialCard }",
                    Money       = Decimal.Parse(result.Card_amount),
                    MoneyInSite = coin
                };

                this.transactionHistoryService.AddTransactionHistory(transactionHistory);
                _applicationUserService.SaveChanges();

                return(View("Deposit", applyResult));
            }

            html += "<div>Nạp thẻ không thành công</div>";
            html += "<div>" + result.Message + "</div>";
            applyResult.Result.Message = html;
            applyResult.Result.Result  = false;
            return(View("Deposit", applyResult));
        }
        public HttpResponseMessage Get()
        {
            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);

            DataTable dt = new DataTable();

            dt.Columns.AddRange(new DataColumn[29] {
                new DataColumn("PRODUTO"),
                new DataColumn("NUMERO_CONTRATO"),
                new DataColumn("CIDADE_DOC"),
                new DataColumn("DATA"),
                new DataColumn("COMPRADOR"),
                new DataColumn("ENDERECO_COMPRADOR"),
                new DataColumn("CNPJ_COMPRADOR"),
                new DataColumn("INSCRICAO_COMPRADOR"),
                new DataColumn("VENDEDOR"),
                new DataColumn("ENDERECO_VENDEDOR"),
                new DataColumn("CNPJ_VENDEDOR"),
                new DataColumn("INSCRICAO_VENDEDOR"),
                new DataColumn("SAFRA"),
                new DataColumn("QUANTIDADE"),
                new DataColumn("QUANTIDADE_EXTENSO"),
                new DataColumn("PRAZO_ENTREGA"),
                new DataColumn("LOCAL_ENTREGA"),
                new DataColumn("TAMANHO_SACA"),
                new DataColumn("VLR_SACA"),
                new DataColumn("VLR_EXTENSO"),
                new DataColumn("VLR_BRUTO"),
                new DataColumn("BRUTO_EXTENSO"),
                new DataColumn("DT_CONTRATO"),
                new DataColumn("BANCO"),
                new DataColumn("AGENCIA"),
                new DataColumn("CONTA"),
                new DataColumn("TITULARIDADE"),
                new DataColumn("CPF"),
                new DataColumn("DT_EXTENSO"),
            });
            dt.Rows.Add("SOJA",
                        "304AG",
                        "UBERLANDIA/MG",
                        DateTime.Now.ToShortDateString(),
                        "AMAGGI EXPORTAÇÃO E IMPORTAÇÃO LTDA",
                        "AVENIDA PRESIDENTE VARGAS, QUADRA R, SALA 604. 6º ANDAR, COND. EMP. LE MONDE, BAIRRO MARCONAL, RIO VERDE – GO, CEP 75.901-551",
                        "77.294.254/0074-40",
                        "10.593.088-1",
                        "ISIS IPOLITO DE PAULA RIBEIRO",
                        "ROD. GO 118 KM 153 A DIREITA 20 KM – FAZENDA SÃO JORGE, SÃO JOÃO D ALIANÇA - GO, CEP 73.760-000",
                        "001.966.561-09",
                        "11.402.866-4",
                        "2019/2019",
                        "1.200.000",
                        NumeroExtenso.NumeroPorExtenso(Decimal.Parse("1.200.000")).ToUpper(),
                        "01/09/2019 a 15/10/2019",
                        "FAZENDA SÃO JORGE, no município de SÃO JOÃO D´ALIANÇA – GO",
                        "60KG",
                        "22,80",
                        ValorExtenso.NumeroPorExtenso(Decimal.Parse("22,80")).ToUpper(),
                        "456.000,00",
                        ValorExtenso.NumeroPorExtenso(Decimal.Parse("456.000,00")).ToUpper(),
                        "04/11/2019",
                        "BANCO DO BRASIL (001)",
                        "0377-8",
                        "47.233-6",
                        "ISIS IPOLIO DE PAULA RIBEIRO",
                        "001.966.561-09",
                        DataExtenso.RetornaDataExtenso(DateTime.Now)
                        );
            if (dt.Rows.Count > 0)
            {
                object           fileName = System.Web.Hosting.HostingEnvironment.MapPath("~/Files/CONFIRMACAO_FIXACAO_PRECO.docx");
                Word.Application word     = new Word.Application();
                Word.Document    doc      = new Word.Document();
                object           missing  = System.Type.Missing;

                try
                {
                    doc = word.Documents.Add(fileName, missing, missing, missing);
                    doc.Activate();

                    string path        = System.Web.Hosting.HostingEnvironment.MapPath("~/Files");
                    Object oSaveAsFile = (Object)(path + @"\CONFIRMACAO_FIXACAO_PRECO - " + dt.Rows[0]["NUMERO_CONTRATO"].ToString() + " - " + dt.Rows[0]["COMPRADOR"].ToString() + ".docx");
                    Object oMissing    = System.Reflection.Missing.Value;

                    FindAndReplace(word, "#PRODUTO", dt.Rows[0]["PRODUTO"].ToString());
                    FindAndReplace(word, "#NUMERO_CONTRATO", dt.Rows[0]["NUMERO_CONTRATO"].ToString());
                    FindAndReplace(word, "#CIDADE_DOC", dt.Rows[0]["CIDADE_DOC"].ToString());
                    FindAndReplace(word, "#DATA", dt.Rows[0]["DATA"].ToString());
                    FindAndReplace(word, "#COMPRADOR", dt.Rows[0]["COMPRADOR"].ToString());
                    FindAndReplace(word, "#ENDERECO_COMPRADOR", dt.Rows[0]["ENDERECO_COMPRADOR"].ToString());
                    FindAndReplace(word, "#CNPJ_COMPRADOR", dt.Rows[0]["CNPJ_COMPRADOR"].ToString());
                    FindAndReplace(word, "#INSCRICAO_COMPRADOR", dt.Rows[0]["INSCRICAO_COMPRADOR"].ToString());
                    FindAndReplace(word, "#VENDEDOR", dt.Rows[0]["VENDEDOR"].ToString());
                    FindAndReplace(word, "#ENDERECO_VENDEDOR", dt.Rows[0]["ENDERECO_VENDEDOR"].ToString());
                    FindAndReplace(word, "#CNPJ_VENDEDOR", dt.Rows[0]["CNPJ_VENDEDOR"].ToString());
                    FindAndReplace(word, "#INSCRICAO_VENDEDOR", dt.Rows[0]["INSCRICAO_VENDEDOR"].ToString());
                    FindAndReplace(word, "#SAFRA", dt.Rows[0]["SAFRA"].ToString());
                    FindAndReplace(word, "#QUANTIDADE", dt.Rows[0]["QUANTIDADE"].ToString());
                    FindAndReplace(word, "#QTD_EXTENSO", dt.Rows[0]["QUANTIDADE_EXTENSO"].ToString());

                    if (dt.Rows[0]["PRODUTO"].ToString() == "MILHO")
                    {
                        FindAndReplace(word, "#PADRAO_ANEC", "com até 14% de umidade, 5% de impurezas totais, sendo 1% de ardido (PADRÃO EXPORTAÇÃO ANEC 44)");
                    }
                    else
                    {
                        FindAndReplace(word, "#PADRAO_ANEC", "com até 14% de umidade, 1% de impurezas, 8% de avariados, estes últimos com até 6% de mofados, 4% de ardidos e 1% queimados, 8% de grãos esverdeados, 30% de grãos quebrados. A Classificação será efetuada a cada caminhão e/ou vagão recebido");
                    }

                    FindAndReplace(word, "#PRAZO_ENTREGA", dt.Rows[0]["PRAZO_ENTREGA"].ToString());
                    FindAndReplace(word, "#LOCAL_ENTREGA", dt.Rows[0]["LOCAL_ENTREGA"].ToString());
                    FindAndReplace(word, "#TAMANHO_SACA", dt.Rows[0]["TAMANHO_SACA"].ToString());
                    FindAndReplace(word, "#VLR_SACA", dt.Rows[0]["VLR_SACA"].ToString());
                    FindAndReplace(word, "#VLR_EXTENSO", dt.Rows[0]["VLR_EXTENSO"].ToString());
                    FindAndReplace(word, "#VLR_BRUTO", dt.Rows[0]["VLR_BRUTO"].ToString());
                    FindAndReplace(word, "#BRUTO_EXTENSO", dt.Rows[0]["BRUTO_EXTENSO"].ToString());
                    FindAndReplace(word, "#DT_CONTRATO", dt.Rows[0]["DT_CONTRATO"].ToString());
                    FindAndReplace(word, "#BANCO", dt.Rows[0]["BANCO"].ToString());
                    FindAndReplace(word, "#AGENCIA", dt.Rows[0]["AGENCIA"].ToString());
                    FindAndReplace(word, "#CONTA", dt.Rows[0]["CONTA"].ToString());
                    FindAndReplace(word, "#TITULARIDADE", dt.Rows[0]["TITULARIDADE"].ToString());
                    FindAndReplace(word, "#CPF", dt.Rows[0]["CPF"].ToString());
                    FindAndReplace(word, "#DT_EXTENSO", dt.Rows[0]["DT_EXTENSO"].ToString().ToLower());

                    doc.SaveAs2(
                        ref oSaveAsFile, ref oMissing, ref oMissing, ref oMissing,
                        ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                        ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                        ref oMissing, ref oMissing);
                    doc.Close(ref missing, ref missing, ref missing);
                    ((Word._Application)word).Quit();

                    GerarArquivoPdf(path + @"\CONFIRMACAO_FIXACAO_PRECO - " + dt.Rows[0]["NUMERO_CONTRATO"].ToString() + " - " + dt.Rows[0]["COMPRADOR"].ToString() + ".docx", path + @"\CONFIRMACAO_FIXACAO_PRECO - " + dt.Rows[0]["NUMERO_CONTRATO"].ToString() + " - " + dt.Rows[0]["COMPRADOR"].ToString() + ".pdf");
                }
                catch (Exception ex)
                {
                    result.StatusCode = HttpStatusCode.InternalServerError;
                }
            }

            return(result);
        }
Exemplo n.º 46
0
        /// <summary>
        /// Instantiate a 'Primitive' Type.获取一个值,通过该值指示 Type 是否为基元类型之一
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns>An object.</returns>
        public static object InstantiatePrimitiveType(Type type)
        {
            object resultObject = null;

            if (type.IsPrimitive || type == typeof(string))
            {
                TypeCode typeCode = Type.GetTypeCode(type);
                switch (typeCode)
                {
                case TypeCode.Boolean:
                    resultObject = new Boolean();
                    break;

                case TypeCode.Byte:
                    resultObject = new Byte();
                    break;

                case TypeCode.Char:
                    resultObject = new Char();
                    break;

                case TypeCode.DateTime:
                    resultObject = new DateTime();
                    break;

                case TypeCode.Decimal:
                    resultObject = new Decimal();
                    break;

                case TypeCode.Double:
                    resultObject = new Double();
                    break;

                case TypeCode.Int16:
                    resultObject = new Int16();
                    break;

                case TypeCode.Int32:
                    resultObject = new Int32();
                    break;

                case TypeCode.Int64:
                    resultObject = new Int64();
                    break;

                case TypeCode.SByte:
                    resultObject = new SByte();
                    break;

                case TypeCode.Single:
                    resultObject = new Single();
                    break;

                case TypeCode.String:
                    resultObject = string.Empty;
                    break;

                case TypeCode.UInt16:
                    resultObject = new UInt16();
                    break;

                case TypeCode.UInt32:
                    resultObject = new UInt32();
                    break;

                case TypeCode.UInt64:
                    resultObject = new UInt64();
                    break;
                }
            }
            else
            {
                if (type.IsValueType)//获取一个值,通过该值指示 Type 是否为值类型
                {
                    if (type == typeof(DateTime))
                    {
                        return(new DateTime());
                    }
                    if (type == typeof(Decimal))
                    {
                        return(new Decimal());
                    }
                    if (type == typeof(Guid))
                    {
                        return(Guid.Empty);
                    }
                    if (type == typeof(TimeSpan))
                    {
                        return(new TimeSpan(0));
                    }
                    if (type.IsGenericType &&
                        typeof(Nullable <>).IsAssignableFrom(type.GetGenericTypeDefinition()))
                    {
                        return(InstantiateNullableType(type));
                    }
                    throw new NotImplementedException("Unable to instanciate value type");
                }
            }

            return(resultObject);
        }
Exemplo n.º 47
0
        public ActionResult BIRCASPurchaseJournal(String StartDate, String EndDate, String CompanyId, String BranchId)
        {
            // ==============================
            // PDF Settings and Customization
            // ==============================
            MemoryStream workStream = new MemoryStream();
            Rectangle    rectangle  = new Rectangle(PageSize.A3);
            Document     document   = new Document(rectangle, 72, 72, 72, 72);

            document.SetMargins(30f, 30f, 30f, 30f);
            PdfWriter.GetInstance(document, workStream).CloseStream = false;

            // =============
            // Document Open
            // =============
            document.Open();

            // ============
            // Fonts Styles
            // ============
            Font fontArial17Bold = FontFactory.GetFont("Arial", 17, Font.BOLD);
            Font fontArial11Bold = FontFactory.GetFont("Arial", 11, Font.BOLD);
            Font fontArial11     = FontFactory.GetFont("Arial", 11);

            // ====
            // Line
            // ====
            Paragraph line = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 4.5F)));

            // ==============
            // Company Detail
            // ==============
            var company = from d in db.MstCompanies where d.Id == Convert.ToInt32(CompanyId) select d;

            var branchName = "All Branches";

            if (Convert.ToInt32(BranchId) != 0)
            {
                var branch = from d in db.MstBranches where d.Id == Convert.ToInt32(BranchId) select d;
                branchName = branch.FirstOrDefault().Branch;
            }

            // ===========
            // Header Page
            // ===========
            PdfPTable header = new PdfPTable(2);

            header.SetWidths(new float[] { 100f, 75f });
            header.WidthPercentage = 100;
            header.AddCell(new PdfPCell(new Phrase(company.FirstOrDefault().Company, fontArial17Bold))
            {
                Border = 0
            });
            header.AddCell(new PdfPCell(new Phrase("Purchase Journal", fontArial17Bold))
            {
                Border = 0, HorizontalAlignment = 2
            });
            header.AddCell(new PdfPCell(new Phrase(company.FirstOrDefault().Address, fontArial11))
            {
                Border = 0, PaddingTop = 5f
            });
            header.AddCell(new PdfPCell(new Phrase(branchName, fontArial11))
            {
                Border = 0, PaddingTop = 5f, HorizontalAlignment = 2
            });
            header.AddCell(new PdfPCell(new Phrase(company.FirstOrDefault().ContactNumber, fontArial11))
            {
                Border = 0, PaddingTop = 5f
            });
            header.AddCell(new PdfPCell(new Phrase("Date Printed: " + DateTime.Now.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture) + " " + DateTime.Now.ToString("hh:mm:ss tt"), fontArial11))
            {
                Border = 0, PaddingTop = 5f, HorizontalAlignment = 2
            });
            header.AddCell(new PdfPCell(new Phrase("TIN: " + company.FirstOrDefault().TaxNumber, fontArial11))
            {
                Border = 0, PaddingTop = 5f
            });
            header.AddCell(new PdfPCell(new Phrase("", fontArial11))
            {
                Border = 0
            });
            document.Add(header);
            document.Add(line);

            // ==================
            // Date Range Filters
            // ==================
            PdfPTable dateRangeFilters = new PdfPTable(1);

            dateRangeFilters.SetWidths(new float[] { 100f });
            dateRangeFilters.WidthPercentage = 100;
            dateRangeFilters.AddCell(new PdfPCell(new Phrase("Date Start:  " + Convert.ToDateTime(StartDate).ToString("MM/dd/yyyy", CultureInfo.InvariantCulture), fontArial11))
            {
                Border = 0, HorizontalAlignment = 0, PaddingTop = 8f
            });
            dateRangeFilters.AddCell(new PdfPCell(new Phrase("Date End:   " + Convert.ToDateTime(EndDate).ToString("MM/dd/yyyy", CultureInfo.InvariantCulture), fontArial11))
            {
                Border = 0, HorizontalAlignment = 0, PaddingTop = 5f
            });
            document.Add(dateRangeFilters);

            // =====
            // Space
            // =====
            PdfPTable space = new PdfPTable(1);

            space.SetWidths(new float[] { 100f });
            space.WidthPercentage = 100;
            space.AddCell(new PdfPCell(new Phrase(" ", fontArial11))
            {
                Border = 0, PaddingTop = 7f
            });
            document.Add(space);

            // ====
            // Data
            // ====
            IQueryable <Data.TrnReceivingReceiptItem> receivingReceiptItems;

            if (Convert.ToInt32(BranchId) != 0)
            {
                receivingReceiptItems = from d in db.TrnReceivingReceiptItems
                                        where d.TrnReceivingReceipt.MstBranch.CompanyId == Convert.ToInt32(CompanyId) &&
                                        d.TrnReceivingReceipt.BranchId == Convert.ToInt32(BranchId) &&
                                        d.TrnReceivingReceipt.RRDate >= Convert.ToDateTime(StartDate) &&
                                        d.TrnReceivingReceipt.RRDate <= Convert.ToDateTime(EndDate)
                                        select d;
            }
            else
            {
                receivingReceiptItems = from d in db.TrnReceivingReceiptItems
                                        where d.TrnReceivingReceipt.MstBranch.CompanyId == Convert.ToInt32(CompanyId) &&
                                        d.TrnReceivingReceipt.RRDate >= Convert.ToDateTime(StartDate) &&
                                        d.TrnReceivingReceipt.RRDate <= Convert.ToDateTime(EndDate)
                                        select d;
            }

            if (receivingReceiptItems.Any())
            {
                PdfPTable data = new PdfPTable(10);
                data.SetWidths(new float[] { 50f, 65f, 60f, 50f, 50f, 55f, 50f, 50f, 50f, 50f });
                data.WidthPercentage = 100;
                data.AddCell(new PdfPCell(new Phrase("Date", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 4f, PaddingBottom = 8f, PaddingLeft = 5f, PaddingRight = 5f
                });
                data.AddCell(new PdfPCell(new Phrase("Tx No.", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 4f, PaddingBottom = 8f, PaddingLeft = 5f, PaddingRight = 5f
                });
                data.AddCell(new PdfPCell(new Phrase("Supplier", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 4f, PaddingBottom = 8f, PaddingLeft = 5f, PaddingRight = 5f
                });
                data.AddCell(new PdfPCell(new Phrase("Supplier TIN", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 4f, PaddingBottom = 8f, PaddingLeft = 5f, PaddingRight = 5f
                });
                data.AddCell(new PdfPCell(new Phrase("Address", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 4f, PaddingBottom = 8f, PaddingLeft = 5f, PaddingRight = 5f
                });
                data.AddCell(new PdfPCell(new Phrase("Doc. Ref. No.", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 4f, PaddingBottom = 8f, PaddingLeft = 5f, PaddingRight = 5f
                });
                data.AddCell(new PdfPCell(new Phrase("Total Amount", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 4f, PaddingBottom = 8f, PaddingLeft = 5f, PaddingRight = 5f
                });
                data.AddCell(new PdfPCell(new Phrase("Discount", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 4f, PaddingBottom = 8f, PaddingLeft = 5f, PaddingRight = 5f
                });
                data.AddCell(new PdfPCell(new Phrase("VAT", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 4f, PaddingBottom = 8f, PaddingLeft = 5f, PaddingRight = 5f
                });
                data.AddCell(new PdfPCell(new Phrase("Net Purchase", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 4f, PaddingBottom = 8f, PaddingLeft = 5f, PaddingRight = 5f
                });

                Decimal totalAmount      = 0;
                Decimal totalDiscount    = 0;
                Decimal totalVAT         = 0;
                Decimal totalNetPurchase = 0;

                foreach (var receivingReceiptItem in receivingReceiptItems)
                {
                    totalAmount      += receivingReceiptItem.Amount;
                    totalDiscount    += 0;
                    totalVAT         += receivingReceiptItem.VATAmount;
                    totalNetPurchase += receivingReceiptItem.Amount;

                    data.AddCell(new PdfPCell(new Phrase(receivingReceiptItem.TrnReceivingReceipt.RRDate.ToShortDateString(), fontArial11))
                    {
                        HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 6f, PaddingLeft = 5f, PaddingRight = 5f
                    });
                    data.AddCell(new PdfPCell(new Phrase("RR-" + receivingReceiptItem.TrnReceivingReceipt.MstBranch.BranchCode + "-" + receivingReceiptItem.TrnReceivingReceipt.RRNumber, fontArial11))
                    {
                        HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 6f, PaddingLeft = 5f, PaddingRight = 5f
                    });
                    data.AddCell(new PdfPCell(new Phrase(receivingReceiptItem.TrnReceivingReceipt.MstArticle.Article, fontArial11))
                    {
                        HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 6f, PaddingLeft = 5f, PaddingRight = 5f
                    });
                    data.AddCell(new PdfPCell(new Phrase(receivingReceiptItem.TrnReceivingReceipt.MstArticle.TaxNumber, fontArial11))
                    {
                        HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 6f, PaddingLeft = 5f, PaddingRight = 5f
                    });
                    data.AddCell(new PdfPCell(new Phrase(receivingReceiptItem.TrnReceivingReceipt.MstArticle.Address, fontArial11))
                    {
                        HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 6f, PaddingLeft = 5f, PaddingRight = 5f
                    });
                    data.AddCell(new PdfPCell(new Phrase(receivingReceiptItem.TrnReceivingReceipt.ManualRRNumber, fontArial11))
                    {
                        HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 6f, PaddingLeft = 5f, PaddingRight = 5f
                    });
                    data.AddCell(new PdfPCell(new Phrase(receivingReceiptItem.Amount.ToString("#,##0.00"), fontArial11))
                    {
                        HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 6f, PaddingLeft = 5f, PaddingRight = 5f
                    });
                    data.AddCell(new PdfPCell(new Phrase("0.00", fontArial11))
                    {
                        HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 6f, PaddingLeft = 5f, PaddingRight = 5f
                    });
                    data.AddCell(new PdfPCell(new Phrase(receivingReceiptItem.VATAmount.ToString("#,##0.00"), fontArial11))
                    {
                        HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 6f, PaddingLeft = 5f, PaddingRight = 5f
                    });
                    data.AddCell(new PdfPCell(new Phrase(receivingReceiptItem.Amount.ToString("#,##0.00"), fontArial11))
                    {
                        HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 6f, PaddingLeft = 5f, PaddingRight = 5f
                    });
                }

                data.AddCell(new PdfPCell(new Phrase("TOTAL", fontArial11Bold))
                {
                    Colspan = 6, HorizontalAlignment = 2, PaddingTop = 4f, PaddingBottom = 8f, PaddingRight = 5f, PaddingLeft = 5f
                });
                data.AddCell(new PdfPCell(new Phrase(totalAmount.ToString("#,##0.00"), fontArial11Bold))
                {
                    HorizontalAlignment = 2, PaddingTop = 4f, PaddingBottom = 8f, PaddingRight = 5f, PaddingLeft = 5f
                });
                data.AddCell(new PdfPCell(new Phrase(totalDiscount.ToString("#,##0.00"), fontArial11Bold))
                {
                    HorizontalAlignment = 2, PaddingTop = 4f, PaddingBottom = 8f, PaddingRight = 5f, PaddingLeft = 5f
                });
                data.AddCell(new PdfPCell(new Phrase(totalVAT.ToString("#,##0.00"), fontArial11Bold))
                {
                    HorizontalAlignment = 2, PaddingTop = 4f, PaddingBottom = 8f, PaddingRight = 5f, PaddingLeft = 5f
                });
                data.AddCell(new PdfPCell(new Phrase(totalNetPurchase.ToString("#,##0.00"), fontArial11Bold))
                {
                    HorizontalAlignment = 2, PaddingTop = 4f, PaddingBottom = 8f, PaddingRight = 5f, PaddingLeft = 5f
                });

                document.Add(data);
            }

            // ==============
            // Document Close
            // ==============
            document.Close();

            // ================
            // Byte File Stream
            // ================
            byte[] byteInfo = workStream.ToArray();
            workStream.Write(byteInfo, 0, byteInfo.Length);
            workStream.Position = 0;

            return(new FileStreamResult(workStream, "application/pdf"));
        }
        /// <summary>
        /// Function returns option contract parameters (underlying name, expiration date, strike, right) from IQFeed option ticker
        /// Symbology details: http://www.iqfeed.net/symbolguide/index.cfm?symbolguide=guide&amp;displayaction=support%C2%A7ion=guide&amp;web=iqfeed&amp;guide=options&amp;web=IQFeed&amp;type=stock
        /// </summary>
        /// <param name="ticker">IQFeed option ticker</param>
        /// <returns>Results containing 1) underlying name, 2) option right, 3) option strike 4) expiration date</returns>
        public static OptionTickerProperties ParseOptionTickerIQFeed(string ticker)
        {
            // This table describes IQFeed option symbology
            var symbology = new Dictionary <string, Tuple <int, OptionRight> >
            {
                { "A", Tuple.Create(1, OptionRight.Call) }, { "M", Tuple.Create(1, OptionRight.Put) },
                { "B", Tuple.Create(2, OptionRight.Call) }, { "N", Tuple.Create(2, OptionRight.Put) },
                { "C", Tuple.Create(3, OptionRight.Call) }, { "O", Tuple.Create(3, OptionRight.Put) },
                { "D", Tuple.Create(4, OptionRight.Call) }, { "P", Tuple.Create(4, OptionRight.Put) },
                { "E", Tuple.Create(5, OptionRight.Call) }, { "Q", Tuple.Create(5, OptionRight.Put) },
                { "F", Tuple.Create(6, OptionRight.Call) }, { "R", Tuple.Create(6, OptionRight.Put) },
                { "G", Tuple.Create(7, OptionRight.Call) }, { "S", Tuple.Create(7, OptionRight.Put) },
                { "H", Tuple.Create(8, OptionRight.Call) }, { "T", Tuple.Create(8, OptionRight.Put) },
                { "I", Tuple.Create(9, OptionRight.Call) }, { "U", Tuple.Create(9, OptionRight.Put) },
                { "J", Tuple.Create(10, OptionRight.Call) }, { "V", Tuple.Create(10, OptionRight.Put) },
                { "K", Tuple.Create(11, OptionRight.Call) }, { "W", Tuple.Create(11, OptionRight.Put) },
                { "L", Tuple.Create(12, OptionRight.Call) }, { "X", Tuple.Create(12, OptionRight.Put) },
            };

            var letterRange = symbology.Keys
                              .Select(x => x[0])
                              .ToArray();
            var optionTypeDelimiter = ticker.LastIndexOfAny(letterRange);
            var strikePriceString   = ticker.Substring(optionTypeDelimiter + 1, ticker.Length - optionTypeDelimiter - 1);

            var lookupResult = symbology[ticker[optionTypeDelimiter].ToStringInvariant()];
            var month        = lookupResult.Item1;
            var optionRight  = lookupResult.Item2;

            var dayString  = ticker.Substring(optionTypeDelimiter - 2, 2);
            var yearString = ticker.Substring(optionTypeDelimiter - 4, 2);
            var underlying = ticker.Substring(0, optionTypeDelimiter - 4);

            // if we cannot parse strike price, we ignore this contract, but log the information.
            decimal strikePrice;

            if (!Decimal.TryParse(strikePriceString, out strikePrice))
            {
                return(null);
            }

            int day;

            if (!int.TryParse(dayString, out day))
            {
                return(null);
            }

            int year;

            if (!int.TryParse(yearString, out year))
            {
                return(null);
            }

            var expirationDate = new DateTime(2000 + year, month, day);

            return(new OptionTickerProperties
            {
                Underlying = underlying,
                OptionRight = optionRight,
                OptionStrike = strikePrice,
                ExpirationDate = expirationDate
            });
        }
        }       //	getPriceReimbursed

        /// <summary>
        /// Get Approval Amt
        /// </summary>
        /// <returns>qty * converted amt</returns>
        public Decimal GetApprovalAmt()
        {
            //return getQty().multiply(getConvertedAmt());
            return(Decimal.Multiply(GetQty(), GetConvertedAmt()));
        }       //	getApprovalAmt
Exemplo n.º 50
0
        } //SetUpSummary()

        private void SetSummary()
        {
            // Local Variables
            Decimal TotalProfit     = 0;
            Decimal Pos_Mult_Factor = SystemLibrary.ToDecimal(dt_ShowFills.Compute("Min(Pos_Mult_Factor)", ""));
            Decimal Fill_Quantity; // Moved to this as IFF is unreliable.
            Decimal FillValue;

            // SOD
            dgv_Summary.Rows[0].Cells["Order_Quantity"].Value = dt_ShowFills.Compute("Sum(Qty_Order)", "Side Like 'SOD%'");
            dgv_Summary.Rows[0].Cells["Fill_Quantity"].Value  = dgv_Summary.Rows[0].Cells["Order_Quantity"].Value;
            //dgv_Summary.Rows[0].Cells["Fill_Price"].Value = dt_ShowFills.Compute("IIF(Sum(Fill_Quantity)=0,0,Sum(FillValue)/Sum(Fill_Quantity))", "Side Like 'SOD%'");
            Fill_Quantity = SystemLibrary.ToDecimal(dt_ShowFills.Compute("Sum(Fill_Quantity)", "Side Like 'SOD%'"));
            FillValue     = SystemLibrary.ToDecimal(dt_ShowFills.Compute("Sum(FillValue)", "Side Like 'SOD%'"));
            if (Fill_Quantity == 0)
            {
                dgv_Summary.Rows[0].Cells["Fill_Price"].Value = DBNull.Value;
            }
            else
            {
                dgv_Summary.Rows[0].Cells["Fill_Price"].Value = FillValue / Fill_Quantity;
            }

            // Buy
            dgv_Summary.Rows[1].Cells["Order_Quantity"].Value = dt_ShowFills.Compute("Sum(Qty_Order)", "Side Like '%Buy%'");
            dgv_Summary.Rows[1].Cells["Qty_Routed"].Value     = dt_ShowFills.Compute("Sum(Qty_Routed)", "Side Like '%Buy%'");
            dgv_Summary.Rows[1].Cells["Qty_Working"].Value    = dt_ShowFills.Compute("Sum(Qty_Working)", "Side Like '%Buy%'");
            dgv_Summary.Rows[1].Cells["Fill_Quantity"].Value  = dt_ShowFills.Compute("Sum(Fill_Quantity)", "Side Like '%Buy%'");
            //dgv_Summary.Rows[1].Cells["Fill_Price"].Value = dt_ShowFills.Compute("IIF(Sum(Fill_Quantity)=0,0,Sum(FillValue)/Sum(Fill_Quantity))", "Side Like '%Buy%'");
            Fill_Quantity = SystemLibrary.ToDecimal(dt_ShowFills.Compute("Sum(Fill_Quantity)", "Side Like '%Buy%'"));
            FillValue     = SystemLibrary.ToDecimal(dt_ShowFills.Compute("Sum(FillValue)", "Side Like '%Buy%'"));
            if (Fill_Quantity == 0)
            {
                dgv_Summary.Rows[1].Cells["Fill_Price"].Value = DBNull.Value;
            }
            else
            {
                dgv_Summary.Rows[1].Cells["Fill_Price"].Value = FillValue / Fill_Quantity;
            }

            // Sell
            dgv_Summary.Rows[2].Cells["Order_Quantity"].Value = dt_ShowFills.Compute("Sum(Qty_Order)", "Side='Sell' Or Side='Short'");
            dgv_Summary.Rows[2].Cells["Qty_Routed"].Value     = dt_ShowFills.Compute("Sum(Qty_Routed)", "Side='Sell' Or Side='Short'");
            dgv_Summary.Rows[2].Cells["Qty_Working"].Value    = dt_ShowFills.Compute("Sum(Qty_Working)", "Side='Sell' Or Side='Short'");
            dgv_Summary.Rows[2].Cells["Fill_Quantity"].Value  = dt_ShowFills.Compute("Sum(Fill_Quantity)", "Side='Sell' Or Side='Short'");
            //dgv_Summary.Rows[2].Cells["Fill_Price"].Value = dt_ShowFills.Compute("IIF(Sum(Fill_Quantity)=0,0,Sum(FillValue)/Sum(Fill_Quantity))", "Side='Sell' Or Side='Short'");
            Fill_Quantity = SystemLibrary.ToDecimal(dt_ShowFills.Compute("Sum(Fill_Quantity)", "Side='Sell' Or Side='Short'"));
            FillValue     = SystemLibrary.ToDecimal(dt_ShowFills.Compute("Sum(FillValue)", "Side='Sell' Or Side='Short'"));
            if (Fill_Quantity == 0)
            {
                dgv_Summary.Rows[2].Cells["Fill_Price"].Value = DBNull.Value;
            }
            else
            {
                dgv_Summary.Rows[2].Cells["Fill_Price"].Value = FillValue / Fill_Quantity;
            }

            // EOD
            dgv_Summary.Rows[3].Cells["Order_Quantity"].Value = dt_ShowFills.Compute("Sum(Qty_Order)", "");
            dgv_Summary.Rows[3].Cells["Qty_Routed"].Value     = dt_ShowFills.Compute("Sum(Qty_Routed)", "");
            dgv_Summary.Rows[3].Cells["Qty_Working"].Value    = dt_ShowFills.Compute("Sum(Qty_Working)", "");
            dgv_Summary.Rows[3].Cells["Fill_Quantity"].Value  = dt_ShowFills.Compute("Sum(Fill_Quantity)", "");
            Fill_Quantity = SystemLibrary.ToDecimal(dt_ShowFills.Compute("Sum(Fill_Quantity)", ""));
            FillValue     = SystemLibrary.ToDecimal(dt_ShowFills.Compute("Sum(FillValue)", ""));
            if (Fill_Quantity == 0)
            {
                dgv_Summary.Rows[3].Cells["Fill_Price"].Value = DBNull.Value;
            }
            else
            {
                dgv_Summary.Rows[3].Cells["Fill_Price"].Value = FillValue / Fill_Quantity;
            }

            // Calulate Profit
            for (int i = 0; i < dgv_Summary.Rows.Count; i++)
            {
                dgv_Summary.Rows[i].Cells["Profit"].Value = SystemLibrary.ToDecimal(dgv_Summary.Rows[i].Cells["Fill_Quantity"].Value) *
                                                            Pos_Mult_Factor *
                                                            (Last_Sale - SystemLibrary.ToDecimal(dgv_Summary.Rows[i].Cells["Fill_Price"].Value));
                // Total Line is Sum of parts as Buy Qty may equal Sell Qty
                if (i < 3)
                {
                    TotalProfit = TotalProfit + SystemLibrary.ToDecimal(dgv_Summary.Rows[i].Cells["Profit"].Value);
                }
                else
                {
                    dgv_Summary.Rows[i].Cells["Profit"].Value = TotalProfit;
                }
            }

            // Formats
            SystemLibrary.SetColumn(dgv_Summary, "Order_Quantity");
            SystemLibrary.SetColumn(dgv_Summary, "Qty_Routed");
            SystemLibrary.SetColumn(dgv_Summary, "Qty_Working");
            SystemLibrary.SetColumn(dgv_Summary, "Fill_Quantity");
            SystemLibrary.SetColumn(dgv_Summary, "Profit");

            // See if just for one EMSX_Sequence.Length
            if (EMSX_Sequence.Length > 0)
            {
                dgv_Summary.Rows[0].Visible = false; // Hide SOD
                dgv_Summary.Rows[3].Visible = false; // Hide EOD

                // Hide one of the Sides
                if (SystemLibrary.ToDecimal(dgv_Summary.Rows[1].Cells["Order_Quantity"].Value) != 0)
                {
                    dgv_Summary.Rows[2].Visible = false;
                }
                else
                {
                    dgv_Summary.Rows[1].Visible = false;
                }
            }
        } //SetSummary()
Exemplo n.º 51
0
        public ActionResult Test(FormCollection form)
        {
            decimal tempScore  = 0;
            string  tempId     = string.Empty;
            decimal totalScore = 0;

            TestResult testResult   = null;
            long       testResultId = 0;
            string     friendlyUrl  = string.Empty;

            if (!String.IsNullOrEmpty(form["QuestionCount"]))
            {
                int questionCount = Convert.ToInt32(form["QuestionCount"]);

                for (int i = 1; i <= questionCount; i++)
                {
                    tempId = "o-rb-s-" + i;
                    if (!String.IsNullOrEmpty(form[tempId]))
                    {
                        tempScore = 0;
                        Decimal.TryParse(form[tempId], out tempScore);

                        totalScore += tempScore;
                    }
                }

                if (!String.IsNullOrEmpty(form["TestId"]))
                {
                    long testId = Convert.ToInt64(form["TestId"]);

                    var test = db.Tests.Find(testId);

                    if (test != null)
                    {
                        if (test.UsageCount != null)
                        {
                            test.UsageCount = test.UsageCount + 1;
                        }
                        else
                        {
                            test.UsageCount = 1;
                        }

                        db.SaveChanges();

                        testResult = test.TestResults.FirstOrDefault(x => x.RangeStart <= totalScore && x.RangeEnd >= totalScore);
                    }
                }

                if (testResult != null)
                {
                    testResultId = testResult.Id;

                    if (String.IsNullOrEmpty(testResult.TextForSharing))
                    {
                        friendlyUrl = testResult.TitleText + "  " + testResult.ResultText;
                    }
                    else
                    {
                        friendlyUrl = testResult.TextForSharing;
                    }

                    if (!String.IsNullOrEmpty(friendlyUrl))
                    {
                        friendlyUrl = friendlyUrl.Replace(' ', '-');
                        friendlyUrl = friendlyUrl.Trim().ToLower();
                    }
                }
                else
                {
                    return(RedirectToAction("Alert", "Home", new { id = 1 }));
                }
            }

            return(RedirectToAction("TestResult", "Home", new { id = testResultId, ignoreThis = friendlyUrl }));
        }
Exemplo n.º 52
0
        public IActionResult SoilTestDetails(SoilTestDetailsViewModel tvm)
        {
            decimal nmbr;

            if (ModelState.IsValid)
            {
                if (!Decimal.TryParse(tvm.dispNO3H, out nmbr))
                {
                    ModelState.AddModelError("dispNO3H", "Numbers only.");
                }
                else
                {
                    if (nmbr < 0)
                    {
                        ModelState.AddModelError("dispNO3H", "Invalid.");
                    }
                }
                if (!Decimal.TryParse(tvm.dispP, out nmbr))
                {
                    ModelState.AddModelError("dispP", "Numbers only.");
                }
                else
                {
                    if (nmbr < 0)
                    {
                        ModelState.AddModelError("dispP", "Invalid.");
                    }
                }
                if (!Decimal.TryParse(tvm.dispK, out nmbr))
                {
                    ModelState.AddModelError("dispK", "Numbers only.");
                }
                else
                {
                    if (nmbr < 0)
                    {
                        ModelState.AddModelError("dispK", "Invalid.");
                    }
                }
                if (!Decimal.TryParse(tvm.dispPH, out nmbr))
                {
                    ModelState.AddModelError("dispPH", "Numbers only.");
                }
                else
                {
                    if (nmbr < 0 ||
                        nmbr > 14)
                    {
                        ModelState.AddModelError("dispPH", "Invalid.");
                    }
                }
                if (!ModelState.IsValid)
                {
                    return(View(tvm));
                }

                Utility.SoilTestConversions soilTestConversions = new Utility.SoilTestConversions(_ud, _sd);
                Field fld = _ud.GetFieldDetails(tvm.fieldName);
                if (fld.soilTest == null)
                {
                    fld.soilTest = new Models.SoilTest();
                }
                fld.soilTest.sampleDate        = Convert.ToDateTime(tvm.sampleDate);
                fld.soilTest.ValP              = Convert.ToDecimal(tvm.dispP);
                fld.soilTest.valK              = Convert.ToDecimal(tvm.dispK);
                fld.soilTest.valNO3H           = Convert.ToDecimal(tvm.dispNO3H);
                fld.soilTest.valPH             = Convert.ToDecimal(tvm.dispPH);
                fld.soilTest.ConvertedKelownaK = soilTestConversions.GetConvertedSTK(fld.soilTest);
                fld.soilTest.ConvertedKelownaP = soilTestConversions.GetConvertedSTP(fld.soilTest);

                _ud.UpdateFieldSoilTest(fld);

                //update the Nutrient calculations with the new/changed soil test data
                Utility.ChemicalBalanceMessage cbm = new Utility.ChemicalBalanceMessage(_ud, _sd);
                cbm.RecalcCropsSoilTestMessagesByField(tvm.fieldName);

                string target = "#test";
                string url    = Url.Action("RefreshTestList", "Soil");
                return(Json(new { success = true, url = url, target = target }));
            }
            return(View(tvm));
        }
Exemplo n.º 53
0
        /// <summary>
        /// Compares the given pattern members, throwing a "Type Error" whenever the comparison operator detects sematically incompatible members;
        /// </summary>
        internal static Int32 CompareRDFPatternMembers(RDFPatternMember left, RDFPatternMember right) {

            #region NULLS
            if (left      == null) {
                if (right == null) {
                    return  0;
                }
                return -1;
            }
            if (right     == null) {
                return 1;
            }
            #endregion

            #region RESOURCE/CONTEXT
            if (left      is RDFResource || left is RDFContext) {

                //RESOURCE/CONTEXT VS RESOURCE/CONTEXT/PLAINLITERAL
                if (right is RDFResource || right is RDFContext || right is RDFPlainLiteral) {
                    return String.Compare(left.ToString(), right.ToString(), StringComparison.Ordinal);
                }

                //RESOURCE/CONTEXT VS TYPEDLITERAL
                else {
                    if (((RDFTypedLiteral)right).HasStringDatatype()) {
                        return String.Compare(left.ToString(), ((RDFTypedLiteral)right).Value, StringComparison.Ordinal);
                    }
                    return -99; //Type Error
                }

            }
            #endregion

            #region PLAINLITERAL
            else if (left is RDFPlainLiteral) {

                //PLAINLITERAL VS RESOURCE/CONTEXT/PLAINLITERAL
                if (right is RDFResource || right is RDFContext || right is RDFPlainLiteral) {
                    return String.Compare(left.ToString(), right.ToString(), StringComparison.Ordinal);
                }

                //PLAINLITERAL VS TYPEDLITERAL
                else {
                    if (((RDFTypedLiteral)right).HasStringDatatype()) {
                        return String.Compare(left.ToString(), ((RDFTypedLiteral)right).Value, StringComparison.Ordinal);
                    }
                    return -99; //Type Error
                }

            }
            #endregion

            #region TYPEDLITERAL
           else {

                //TYPEDLITERAL VS RESOURCE/CONTEXT/PLAINLITERAL
                if (right is RDFResource || right is RDFContext || right is RDFPlainLiteral) {
                    if (((RDFTypedLiteral)left).HasStringDatatype()) {
                        return String.Compare(((RDFTypedLiteral)left).Value, right.ToString(), StringComparison.Ordinal);
                    }
                    return -99; //Type Error
                }

                //TYPEDLITERAL VS TYPEDLITERAL
                else {
                    if (((RDFTypedLiteral)left).HasBooleanDatatype()       && ((RDFTypedLiteral)right).HasBooleanDatatype()) {
                        Boolean leftValueBoolean    = Boolean.Parse(((RDFTypedLiteral)left).Value);
                        Boolean rightValueBoolean   = Boolean.Parse(((RDFTypedLiteral)right).Value);
                        return leftValueBoolean.CompareTo(rightValueBoolean);
                    }
                    else if (((RDFTypedLiteral)left).HasDatetimeDatatype() && ((RDFTypedLiteral)right).HasDatetimeDatatype()) {
                        DateTime leftValueDateTime  = DateTime.Parse(((RDFTypedLiteral)left).Value,  CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
                        DateTime rightValueDateTime = DateTime.Parse(((RDFTypedLiteral)right).Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
                        return leftValueDateTime.CompareTo(rightValueDateTime);
                    }
                    else if (((RDFTypedLiteral)left).HasDecimalDatatype()  && ((RDFTypedLiteral)right).HasDecimalDatatype()) {
                        Decimal leftValueDecimal    = Decimal.Parse(((RDFTypedLiteral)left).Value,  CultureInfo.InvariantCulture);
                        Decimal rightValueDecimal   = Decimal.Parse(((RDFTypedLiteral)right).Value, CultureInfo.InvariantCulture);
                        return leftValueDecimal.CompareTo(rightValueDecimal);
                    }
                    else if (((RDFTypedLiteral)left).HasStringDatatype()   && ((RDFTypedLiteral)right).HasStringDatatype()) {
                        String leftValueString      = ((RDFTypedLiteral)left).Value;
                        String rightValueString     = ((RDFTypedLiteral)right).Value;
                        return leftValueString.CompareTo(rightValueString);
                    }
                    else if (((RDFTypedLiteral)left).HasTimespanDatatype() && ((RDFTypedLiteral)right).HasTimespanDatatype()) {
                        TimeSpan leftValueDuration  = XmlConvert.ToTimeSpan(((RDFTypedLiteral)left).Value);
                        TimeSpan rightValueDuration = XmlConvert.ToTimeSpan(((RDFTypedLiteral)right).Value);
                        return leftValueDuration.CompareTo(rightValueDuration);
                    }
                    else {
                        return -99; //Type Error
                    }
                }

            }
            #endregion

        }
Exemplo n.º 54
0
        public static List <NormalDistributionTestCase> TestCases()
        {
            List <NormalDistributionTestCase> testCases = new List <NormalDistributionTestCase>();

            string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\" + "TestCases.txt";

            var file = File.ReadAllLines(path).TakeWhile(line => !string.IsNullOrWhiteSpace(line)).ToList();

            //Looping on each line in file and build test case parameter.
            foreach (var line in file)
            {
                //Temp parameter used to store data after perform it.
                int           totalQty;
                string        testCaseName;
                List <InCap>  inCaps   = new List <InCap>();
                List <OutCap> expected = new List <OutCap>();

                // Remove all white space and square brackets.
                string trim = line.Replace(" ", "").Replace("[", "").Replace("]", "");

                // Get case name and total quantity.
                var nameAndTotalQty = trim.Split('@')[0].Split(':');
                testCaseName = nameAndTotalQty[0];
                totalQty     = int.Parse(nameAndTotalQty[1]);

                // Get all inCaps and outCaps as strings.
                var inCapsAndOutCaps = trim.Split('@')[1].Split('=');
                var inCapsArray      = inCapsAndOutCaps[0].Replace(">,<", ";").Replace("<", "").Replace(">", "").Split(';');
                var outCapsArray     = inCapsAndOutCaps[1].Replace(">,<", ";").Replace("<", "").Replace(">", "").Split(';');

                //Start Build Test Case
                foreach (var inCapitem in inCapsArray)
                {
                    // Perform each inCap and add it to inCaps list
                    inCaps.Add(new InCap()
                    {
                        ID            = inCapitem.Split(',')[0],
                        Participation = Decimal.Divide(decimal.Parse(inCapitem.Split(',')[1].Split('/')[0]), decimal.Parse(inCapitem.Split(',')[1].Split('/')[1]))
                    });
                }

                foreach (var outCapitem in outCapsArray)
                {
                    // Perform each outCap and add it to outCaps list
                    expected.Add(new OutCap()
                    {
                        ID       = outCapitem.Split(',')[0],
                        Quantity = int.Parse(outCapitem.Split(',')[1])
                    });
                }
                //End Build Test Case.

                //Add test Case to test cases list.
                testCases.Add(
                    new NormalDistributionTestCase()
                {
                    TotalQty = totalQty,
                    InCaps   = inCaps,
                    Expected = expected,
                    TestName = testCaseName
                }
                    );
            }
            return(testCases);
        }
Exemplo n.º 55
0
 public void GrossPay_50_10()
 {
     Assert.AreEqual(550m,
                     Decimal.Round(Ex3bCalculations.GrossPay(50m, 10m), 2));
 }
Exemplo n.º 56
0
        private void button1_Click(object sender, EventArgs e)
        {
            double outValue   = 1;
            bool   resultTxt1 = Double.TryParse(textBox1.Text, out outValue);

            //(textBox1.Text != String.Empty) || (textBox2.Text != String.Empty )
            if (resultTxt1 == true)
            {
                a             = decimal.Parse(textBox2.Text);
                b             = decimal.Parse(textBox1.Text);
                textBox1.Text = String.Empty;
                textBox2.Text = String.Empty;

                if (radioButton1.Checked)
                {
                    listBox1.Items.Clear();
                    c = a + b;

                    z = Decimal.Round(c, y);
                    listBox1.Items.Clear();
                    listBox1.Items.Add(z);
                }
                else if (radioButton2.Checked)
                {
                    listBox1.Items.Clear();
                    c = a - b;
                    z = Decimal.Round(c, y);
                    listBox1.Items.Clear();
                    listBox1.Items.Add(z);
                }
                else if (radioButton3.Checked)
                {
                    listBox1.Items.Clear();
                    if (b == 0)
                    {
                        string x = "Nie można dzielić przez 0.";
                        string y = "Operacja niedozwolona!";
                        MessageBox.Show(x, y, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        c = a / b;
                        z = Decimal.Round(c, y);
                        listBox1.Items.Clear();
                        listBox1.Items.Add(z);
                    }
                }
                else if (radioButton4.Checked)
                {
                    listBox1.Items.Clear();
                    c = a * b;
                    z = Decimal.Round(c, y);
                    listBox1.Items.Clear();
                    listBox1.Items.Add(z);
                }
            }
            else
            {
                string alert = "Nie wprowadziłeś nic lub wprowadziłeś litere/ciąg liter";
                string main  = "Ostrzeżenie!";
                MessageBox.Show(alert, main, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 57
0
 public void TotalHours()
 {
     Assert.AreEqual(10m,
                     Decimal.Round(Ex3bCalculations.TotalHours("1.1 2.2 3.3 3.4 "), 2));
 }
Exemplo n.º 58
0
 public void GrossPay_String_10()
 {
     Assert.AreEqual(100m,
                     Decimal.Round(Ex3bCalculations.GrossPay("1.1 2.2 3.3 3.4 ", 10m), 2));
 }
Exemplo n.º 59
0
        private void dgv_ShowFills_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            // Show the popup menu
            try
            {
                if (e.Button == MouseButtons.Right && e.RowIndex > -1 && e.ColumnIndex > -1)
                {
                    Point myLocation = new Point(this.Location.X + CXLocation, this.Location.Y + CYLocation);
                    // Select the Order as needed in code later on.
                    String EMSX_Sequence = SystemLibrary.ToString(dgv_ShowFills.Rows[e.RowIndex].Cells["Order#"].Value);
                    String mySql         = "select OrderRefID, BBG_Ticker, Amount as Quantity, Sum(RoutedAmount) as RoutedAmount, Sum(FillAmount) as FillAmount, Side " +
                                           "From Fills " +
                                           "Where OrderRefID = (Select OrderRefID From Orders where Emsx_Sequence = " + EMSX_Sequence + ") " +
                                           "Group By OrderRefID, BBG_Ticker, Amount, Side " +
                                           "Union " +
                                           "Select OrderRefID, BBG_Ticker, Quantity, 0 as RoutedAmount, 0 as FillAmount, Side " +
                                           "From Orders " +
                                           "Where Emsx_Sequence = " + EMSX_Sequence + " " +
                                           "And Not Exists (Select 'x' from Fills Where Fills.OrderRefID = Orders.OrderRefID) ";
                    DataTable dt_Order = SystemLibrary.SQLSelectToDataTable(mySql);
                    if (dt_Order.Rows.Count > 0)
                    {
                        String  OrderRefID            = SystemLibrary.ToString(dt_Order.Rows[0]["OrderRefID"]);
                        String  BBG_Ticker            = SystemLibrary.ToString(dt_Order.Rows[0]["BBG_Ticker"]);
                        String  Side                  = SystemLibrary.ToString(dt_Order.Rows[0]["Side"]);
                        Decimal Quantity              = SystemLibrary.ToDecimal(dt_Order.Rows[0]["Quantity"]);
                        Decimal RoutedAmount          = SystemLibrary.ToDecimal(dt_Order.Rows[0]["RoutedAmount"]);
                        Decimal FillAmount            = SystemLibrary.ToDecimal(dt_Order.Rows[0]["FillAmount"]);
                        String  FormattedQuantity     = Quantity.ToString("#,##0");
                        String  FormattedFillAmount   = FillAmount.ToString("#,##0");
                        String  FormattedRoutedAmount = RoutedAmount.ToString("#,##0");
                        Qty_Order = Quantity;

                        ContextMenuStrip  myMenu    = new ContextMenuStrip();
                        ToolStripMenuItem mySubMenu = new ToolStripMenuItem();

                        OrderMenuStruct myOrderStr = new OrderMenuStruct();
                        myOrderStr.OrderRefID            = OrderRefID;
                        myOrderStr.EMSX_Sequence         = EMSX_Sequence;
                        myOrderStr.BBG_Ticker            = BBG_Ticker;
                        myOrderStr.FormattedQuantity     = FormattedQuantity;
                        myOrderStr.FormattedFillAmount   = FormattedFillAmount;
                        myOrderStr.FormattedRoutedAmount = FormattedRoutedAmount;
                        myOrderStr.Quantity   = Quantity;
                        myOrderStr.FillAmount = FillAmount;
                        //myOrderStr.FillPrice = FillPrice;
                        myOrderStr.RoutedAmount = RoutedAmount;
                        myOrderStr.Side         = Side;
                        myOrderStr.myParentForm = this;

                        // Resize to Fill Menu
                        if (Quantity != FillAmount)
                        {
                            mySubMenu = new ToolStripMenuItem("Resize Order (" + FormattedQuantity + ") to the Fill Amount (" + FormattedFillAmount + ")");
                            myOrderStr.Instruction = "ResizeToFill";
                            mySubMenu.Tag          = myOrderStr;
                            mySubMenu.MouseUp     += new MouseEventHandler(dgv_ShowFillsSystemMenuItem_Click);
                            myMenu.Items.Add(mySubMenu);
                        }

                        // Resize to Fill Menu
                        if (Quantity != RoutedAmount)
                        {
                            mySubMenu = new ToolStripMenuItem("Resize Order (" + FormattedQuantity + ") to the Routed Amount (" + FormattedRoutedAmount + ")");
                            myOrderStr.Instruction = "ResizeToRouted";
                            mySubMenu.Tag          = myOrderStr;
                            mySubMenu.MouseUp     += new MouseEventHandler(dgv_ShowFillsSystemMenuItem_Click);
                            myMenu.Items.Add(mySubMenu);
                        }
                        // Double Order Menu
                        mySubMenu = new ToolStripMenuItem("Double Order Size");
                        myOrderStr.Instruction = "ResizeToDouble";
                        mySubMenu.Tag          = myOrderStr;
                        mySubMenu.MouseUp     += new MouseEventHandler(dgv_ShowFillsSystemMenuItem_Click);
                        myMenu.Items.Add(mySubMenu);

                        // Resize Order Menu
                        myMenu.Items.Add("-");
                        mySubMenu = new ToolStripMenuItem("Resize Order");
                        myOrderStr.Instruction = "ResizeOrder";
                        mySubMenu.Tag          = myOrderStr;
                        mySubMenu.MouseUp     += new MouseEventHandler(dgv_ShowFillsSystemMenuItem_Click);
                        myMenu.Items.Add(mySubMenu);

                        // Delete Order Menu
                        myMenu.Items.Add("-");
                        mySubMenu = new ToolStripMenuItem("Delete Order");
                        myOrderStr.Instruction = "Delete";
                        mySubMenu.Tag          = myOrderStr;
                        mySubMenu.MouseUp     += new MouseEventHandler(dgv_ShowFillsSystemMenuItem_Click);
                        myMenu.Items.Add(mySubMenu);

                        // Show the Menu
                        myMenu.Show(myLocation);
                    }
                }
            }
            catch { }
        } //dgv_ShowFills_CellMouseClick()
Exemplo n.º 60
0
 public ListDomainsRequest WithMaxNumberOfDomains(Decimal maxNumberOfDomains)
 {
     this.maxNumberOfDomainsField = maxNumberOfDomains;
     return(this);
 }