示例#1
0
        static void Main(string[] args)
        {
            var dec1 = new SqlDecimal(-0.00000450m);
            var dec2 = new SqlDecimal(0.193m);

            Console.WriteLine("=======================\n\nINITIAL:");
            DisplayStuffs(dec1, dec2);


            dec1 = SqlDecimal.ConvertToPrecScale(dec1, 38, 8);
            dec2 = SqlDecimal.ConvertToPrecScale(dec2, 18, 8);

            Console.WriteLine("=======================\n\nAFTER (38, 8) & (18, 8):");
            DisplayStuffs(dec1, dec2);


            dec1 = SqlDecimal.ConvertToPrecScale(dec1, 18, 8);

            Console.WriteLine("=======================\n\nAFTER (18, 8) & (18, 8):");
            DisplayStuffs(dec1, dec2);


            dec1 = SqlDecimal.ConvertToPrecScale(dec1, 38, 28);
            dec2 = SqlDecimal.ConvertToPrecScale(dec2, 38, 28);

            Console.WriteLine("=======================\n\nAFTER (38, 28) & (38, 28):");
            DisplayStuffs(dec1, dec2);

            Console.WriteLine("=======================");
            //Console.ReadLine();
        }
        private SqlDecimal ReducePrecision(SqlDecimal d, int newPrecision)
        {
            var newScale  = newPrecision - d.Precision + d.Scale;
            var truncated = SqlDecimal.Truncate(d, newScale);

            return(SqlDecimal.ConvertToPrecScale(truncated, newPrecision, newScale));
        }
        private IEnumerable <SqlDecimal> GetSortOrdersBetween(SqlDecimal before, SqlDecimal after, long eventsToInsert)
        {
            before = SqlDecimal.ConvertToPrecScale(before, 38, 19);//Unless we convert to the correct precision we will not be able to use the full resolution
            after  = SqlDecimal.ConvertToPrecScale(after, 38, 19);
            var diff      = after - before;
            var increment = diff / (eventsToInsert + 1);

            if (increment == 0)
            {
                throw new Exception("Resolution Failure 1");
            }
            var  previousSortOrder = before;
            long insertedEvents    = 0;

            for (var sortOrder = before + increment; sortOrder < after && insertedEvents < eventsToInsert; sortOrder += increment, insertedEvents++)
            {
                yield return(sortOrder);

                if (sortOrder == previousSortOrder)
                {
                    throw new Exception("Resolution failure 2");
                }
                previousSortOrder = sortOrder;
            }

            if (insertedEvents != eventsToInsert)
            {
                throw new Exception($"Should have generated {eventsToInsert} values but generated {insertedEvents} values.");
            }
        }
示例#4
0
        public void ConvertToPrecScale()
        {
            Assert.Equal(new SqlDecimal(6464.6m).Value, SqlDecimal.ConvertToPrecScale(_test1, 5, 1).Value);

            Assert.Throws <SqlTruncateException>(() => SqlDecimal.ConvertToPrecScale(_test1, 6, 4));

            Assert.Equal("10000.00", SqlDecimal.ConvertToPrecScale(_test2, 7, 2).ToSqlString());

            SqlDecimal tmp = new SqlDecimal(38, 4, true, 64646464, 0, 0, 0);

            Assert.Equal("6465", SqlDecimal.ConvertToPrecScale(tmp, 4, 0).ToString());
        }
 internal void SetSqlDecimal(SqlDecimal value)
 {
     if (SqlDbType.Variant == this._metaData.SqlDbType)
     {
         this._stateObj.Parser.WriteSqlVariantHeader(0x15, 0x6c, 2, this._stateObj);
         this._stateObj.Parser.WriteByte(value.Precision, this._stateObj);
         this._stateObj.Parser.WriteByte(value.Scale, this._stateObj);
         this._stateObj.Parser.WriteSqlDecimal(value, this._stateObj);
     }
     else
     {
         this._stateObj.Parser.WriteByte((byte)MetaType.MetaDecimal.FixedLength, this._stateObj);
         this._stateObj.Parser.WriteSqlDecimal(SqlDecimal.ConvertToPrecScale(value, this._metaData.Precision, this._metaData.Scale), this._stateObj);
     }
 }
示例#6
0
        public void TestDecimal()
        {
            TestSimpleValues(new SqlDataType(SqlDbType.Decimal, 28, 0), -53m, 42m, true);
            TestSimpleValues(new SqlDataType(SqlDbType.Decimal, 28, 0), 61m, -75m, false);
            TestSimpleValues(new SqlDataType(SqlDbType.Decimal, 4, 0), -5217m, 5829m, true);
            TestSimpleValues(new SqlDataType(SqlDbType.Decimal, 4, 0), 5217m, -5829m, false);
            TestSimpleValues(new SqlDataType(SqlDbType.Decimal, 4, 2), -52.17m, 58.29m, true);
            TestSimpleValues(new SqlDataType(SqlDbType.Decimal, 4, 2), 52.17m, -58.29m, false);
            SqlDecimal one = SqlDecimal.ConvertToPrecScale(new SqlDecimal(0.5217m), 38, 38);
            SqlDecimal two = SqlDecimal.ConvertToPrecScale(new SqlDecimal(-0.5829m), 38, 38);

            TestSimpleValues(new SqlDataType(SqlDbType.Decimal, 38, 38), one, two, true);
            TestSimpleValues(new SqlDataType(SqlDbType.Decimal, 38, 38), two, one, false);
            TestSimpleValues(new SqlDataType(SqlDbType.Decimal, 38, 37), null, one, true);
            TestSimpleValues(new SqlDataType(SqlDbType.Decimal, 38, 37), two, null, true);
        }
示例#7
0
 // valid for SqlDbType.Numeric (uses SqlDecimal since Decimal cannot hold full range)
 internal void SetSqlDecimal(SqlDecimal value)
 {
     Debug.Assert(
         SmiXetterAccessMap.IsSetterAccessValid(_metaData, SmiXetterTypeCode.XetSqlDecimal));
     if (SqlDbType.Variant == _metaData.SqlDbType)
     {
         _stateObj.Parser.WriteSqlVariantHeader(21, TdsEnums.SQLNUMERICN, 2, _stateObj);
         _stateObj.WriteByte(value.Precision); // propbytes: precision
         _stateObj.WriteByte(value.Scale);     // propbytes: scale
         _stateObj.Parser.WriteSqlDecimal(value, _stateObj);
     }
     else
     {
         _stateObj.WriteByte(checked ((byte)MetaType.MetaDecimal.FixedLength)); // SmiMetaData's length and actual wire format's length are different
         _stateObj.Parser.WriteSqlDecimal(SqlDecimal.ConvertToPrecScale(value, _metaData.Precision, _metaData.Scale), _stateObj);
     }
 }
示例#8
0
        public void ConvertToPrecScale()
        {
            Assert.AreEqual(new SqlDecimal(6464.6m).Value, SqlDecimal.ConvertToPrecScale(Test1, 5, 1).Value, "#F01");

            try {
                SqlDecimal test = SqlDecimal.ConvertToPrecScale(Test1, 6, 4);
                Assert.Fail("#F02");
            } catch (SqlTruncateException e) {
                Assert.AreEqual(typeof(SqlTruncateException), e.GetType(), "#F03");
            }

            Assert.AreEqual((SqlString)"10000.00", SqlDecimal.ConvertToPrecScale(Test2, 7, 2).ToSqlString(), "#F04");

            SqlDecimal tmp = new SqlDecimal(38, 4, true, 64646464, 0, 0, 0);

            Assert.AreEqual("6465", SqlDecimal.ConvertToPrecScale(tmp, 4, 0).ToString(), "#F05");
        }
示例#9
0
        public void ConvertToPrecScale()
        {
            Assert.Equal(new SqlDecimal(6464.6m).Value, SqlDecimal.ConvertToPrecScale(_test1, 5, 1).Value);

            try
            {
                SqlDecimal test = SqlDecimal.ConvertToPrecScale(_test1, 6, 4);
                Assert.False(true);
            }
            catch (SqlTruncateException e)
            {
                Assert.Equal(typeof(SqlTruncateException), e.GetType());
            }

            Assert.Equal("10000.00", SqlDecimal.ConvertToPrecScale(_test2, 7, 2).ToSqlString());

            SqlDecimal tmp = new SqlDecimal(38, 4, true, 64646464, 0, 0, 0);

            Assert.Equal("6465", SqlDecimal.ConvertToPrecScale(tmp, 4, 0).ToString());
        }
        /// <summary>
        /// .NET Decimal has a max precision of 28-29, so we need to set it here to prevent overflow errors (#708477, #1105735)
        /// </summary>
        internal static decimal FixDecimalPrecision(SqlDecimal value)
        {
            int nrDigitsIntegerPart = SqlDecimal.Floor(value).ToString().Length;
            int newScale            = 29 - nrDigitsIntegerPart;

            //#1214665 Original scale must be preserved if possible because SQL driver Value method will append trailing zeros
            if (newScale > value.Scale)
            {
                newScale = value.Scale;
            }
            try {
                // Try to convert to a decimal with 29 digits
                return(SqlDecimal.ConvertToPrecScale(value, 29, newScale).Value);
            } catch (OverflowException) {
                // Value didn't fit a decimal with 29 digits, try with 28 digits
                newScale = 28 - nrDigitsIntegerPart;
                if (newScale > value.Scale)
                {
                    newScale = value.Scale;
                }
                return(SqlDecimal.ConvertToPrecScale(value, 28, newScale).Value);
            }
        }
        private static SqlDecimal BulkCopySqlDecimalToTable(SqlDecimal decimalValue, int sourcePrecision, int sourceScale, int targetPrecision, int targetScale)
        {
            string tableName        = DataTestUtility.GenerateTableName();
            string connectionString = DataTestUtility.TcpConnStr;

            SqlDecimal resultValue;

            try
            {
                DataTestUtility.RunNonQuery(connectionString, $"create table {tableName} (target_column decimal({targetPrecision}, {targetScale}))");

                SqlDecimal inputValue = SqlDecimal.ConvertToPrecScale(decimalValue, sourcePrecision, sourceScale);

                DataTable dt = new DataTable();
                dt.Clear();
                dt.Columns.Add("source_column", typeof(SqlDecimal));
                DataRow row = dt.NewRow();
                row["source_column"] = inputValue;
                dt.Rows.Add(row);

                using (SqlBulkCopy sbc = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.KeepIdentity))
                {
                    sbc.DestinationTableName = tableName;
                    sbc.ColumnMappings.Add("source_column", "target_column");
                    sbc.WriteToServer(dt);
                }

                DataTable resultTable = DataTestUtility.RunQuery(connectionString, $"select * from {tableName}");
                resultValue = new SqlDecimal((Decimal)resultTable.Rows[0][0]);
            }
            finally
            {
                DataTestUtility.RunNonQuery(connectionString, $"drop table {tableName}");
            }

            return(resultValue);
        }
示例#12
0
 private object GetData(int columnIndex)
 {
     try
     {
         if (this._reader.GetDataTypeName(columnIndex) == "decimal")
         {
             try
             {
                 return(this._reader.GetDecimal(columnIndex));
             }
             catch
             {
                 try
                 {
                     var sql = this._reader.GetSqlDecimal(columnIndex);
                     if (sql.IsNull)
                     {
                         return(DBNull.Value);
                     }
                     var newPrecision = 28;
                     var newScale     = newPrecision - Math.Min(newPrecision, (sql.Precision - sql.Scale));
                     return(SqlDecimal.ConvertToPrecScale(sql, newPrecision, newScale).Value);
                 }
                 catch (SqlTruncateException tex)
                 {
                     return(DBNull.Value);
                 }
             }
         }
         return(this._reader[columnIndex]);
     }
     catch
     {
         return(DBNull.Value);
     }
 }
示例#13
0
        public override object Parse(ColumnTypeInfo colTypeInfo, object sourceValue)
        {
            SqlDecimal decimalData = SqlDecimal.Parse(sourceValue.ToString());

            return(SqlDecimal.ConvertToPrecScale(decimalData, colTypeInfo.Precision, colTypeInfo.Scale));
        }
 private static SqlDecimal ToCorrectPrecisionAndScale(SqlDecimal value)
 {
     return(SqlDecimal.ConvertToPrecScale(value, 38, 19));
 }
示例#15
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (state == "Add")
            {
                MemoryStream ms = new MemoryStream();
                pbox.Image.Save(ms, pbox.Image.RawFormat);
                byte[] byteimage = ms.ToArray();
                //check amount
                //convert from  date time to date only
                //change from MemID in add donation to Donator ID
                //image button not added...
                if (categoriescombo.SelectedValue.ToString() == "1" || categoriescombo.SelectedValue.ToString() == "6")
                {
                    try
                    {
                        //decimal.Parse(Amount.Text, NumberStyles.Currency);

                        Dona.Add_Donation(Convert.ToInt32(categoriescombo.SelectedValue),
                                          Convert.ToInt32(DonatorID.Text), DonaTitle.Text,
                                          // float.Parse(Amount.Text, CultureInfo.InvariantCulture.NumberFormat)
                                          decimal.Parse(Amount.Text),
                                          1, Description.Text, DateOfDona.Value, byteimage, OtherNote.Text);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error in Adding Donation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    finally
                    {
                        MessageBox.Show("Added Donation Success...", "Donation", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        dona.dataGridViewDonations.DataSource = Dona.GET_ALL_Donations();
                    }
                }
                else
                {
                    try
                    {
                        Dona.Add_Donation(Convert.ToInt32(categoriescombo.SelectedValue),
                                          Convert.ToInt32(DonatorID.Text), DonaTitle.Text,
                                          // float.Parse(Amount.Text, CultureInfo.InvariantCulture.NumberFormat)
                                          decimal.Parse(Amount.Text),
                                          Convert.ToInt32(qty.Text), Description.Text, DateOfDona.Value, byteimage, OtherNote.Text);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error in Adding Donation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    //float.Parse(price2.Text, CultureInfo.InvariantCulture.NumberFormat); convertion to float, add using system.globaltio...
                    finally
                    {
                        MessageBox.Show("Added Donation Success...", "Donation", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        dona.dataGridViewDonations.DataSource = Dona.GET_ALL_Donations();
                    }
                }
                //finally added without testing, test it another time..
            }
            else
            {
                MemoryStream ms = new MemoryStream();
                pbox.Image.Save(ms, pbox.Image.RawFormat);
                byte[] byteimage = ms.ToArray();
                //check amount
                //convert from  date time to date only
                //change from MemID in add donation to Donator ID
                //MessageBox.Show(dona.dataGridViewDonations.CurrentRow.Cells[0].Value.ToString());

                // MessageBox.Show(Convert.ToInt32(dona.dataGridViewDonations.CurrentRow.Cells[0].Value.ToString()));
                //MessageBox.Show(dona.dataGridViewDonations.CurrentRow.Selected.ToString());


                //if (dona.dataGridViewDonations.CurrentRow.Cells[0].Value.ToString() == null) {
                //    MessageBox.Show("error null value 1");
                //}
                //if (dona.dataGridViewDonations.CurrentRow.Cells[0].Value != null)
                //{
                //    MessageBox.Show("error null value 2");
                //}
                //txtDonatorName
                //MessageBox.Show(Convert.ToString(Convert.ToInt32(dona.dataGridViewDonations.CurrentRow.Cells[0].Value)));
                //MessageBox.Show(dona.dataGridViewDonations.CurrentRow.Cells[0].Value.ToString());


                //int DonationIDafterExit = Convert.ToInt32(txtDonatorName.Text);
                // int DonationIDafterExit = Convert.ToInt32(txtDonatorName.Text);// change DonatorName from Add Donation

                MessageBox.Show(DonationID.ToString());
                if (categoriescombo.SelectedValue.ToString() == "1" || categoriescombo.SelectedValue.ToString() == "6")
                {
                    try
                    {
                        Dona.Update_Donation(DonationID, Convert.ToInt32(categoriescombo.SelectedValue),
                                             Convert.ToInt32(DonatorID.Text), DonaTitle.Text,
                                             SqlDecimal.ConvertToPrecScale(SqlDecimal.Parse(Amount.Text), 10, 4),
                                             1, Description.Text, DateOfDona.Value, byteimage, OtherNote.Text);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "1 Error in Editing/Modifying Donation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    finally
                    {
                    }
                    MessageBox.Show("1 Editing/Modifying Donation Successed...", "Donation", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    dona.dataGridViewDonations.DataSource = Dona.GET_ALL_Donations();
                }
                else
                {
                    try
                    {
                        Dona.Update_Donation(DonationID, Convert.ToInt32(categoriescombo.SelectedValue),
                                             Convert.ToInt32(DonatorID.Text), DonaTitle.Text,
                                             // float.Parse(Amount.Text, CultureInfo.InvariantCulture.NumberFormat)
                                             //decimal.Parse(Amount.Text)
                                             SqlDecimal.ConvertToPrecScale(SqlDecimal.Parse(Amount.Text), 10, 4)
                                             ,
                                             Convert.ToInt32(qty.Text), Description.Text, DateOfDona.Value, byteimage,
                                             OtherNote.Text);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, " 2Error in Editing/Modifying Donation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    //float.Parse(price2.Text, CultureInfo.InvariantCulture.NumberFormat); convertion to float, add using system.globaltio...
                    finally
                    {
                        MessageBox.Show(" 2 Editing/Modifying Donation Successed...", "Donation", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        dona.dataGridViewDonations.DataSource = Dona.GET_ALL_Donations();
                    }
                }
            }
            PL.FrmManageDona.getMainForm.dataGridViewDonations.DataSource = Dona.GET_ALL_Donations();
        }
示例#16
0
        //Data

        //Constructor

        //Accessors
        public override NodeValue CreateRandomValueForFacets(NodeFacets propertyFacets)
        {
            if (propertyFacets.Precision != null && propertyFacets.Scale != null)
            {
                //ISSUE: Small money has a range - 214,748.3648 through +214,748.3647
                // In order to always make this work, reducing the Pre by 1 does this

                decimal?max = null;
                decimal?min = null;
                decimal temp;
                if (propertyFacets.TryGetMaxValue(out temp))
                {
                    max = temp;
                }
                if (propertyFacets.TryGetMinValue(out temp))
                {
                    min = temp;
                }

                int scale     = propertyFacets.Scale.Value;
                int precision = propertyFacets.Precision.Value;
                if (precision > 28)
                {
                    precision = 28; //can't exceed CLR limit
                }
                Decimal[] specialValues = new Decimal[] { Decimal.MinValue, Decimal.MinusOne, Decimal.Zero, Decimal.One, Decimal.MaxValue };
                Decimal?  value         = null;
                int       random        = AstoriaTestProperties.Random.Next(50 + specialValues.Length);
                if (random < specialValues.Length)
                {
                    value = specialValues[random];
                    string asString = Math.Abs(value.Value).ToString();

                    // is there enough precision?
                    if (asString.Length >= precision)
                    {
                        value = null;
                    }

                    // is there enough scale?
                    if (asString.Length - asString.IndexOf('.') >= scale)
                    {
                        value = null;
                    }

                    // is it too big?
                    if (max.HasValue && value > max)
                    {
                        value = null;
                    }

                    // is it too small?
                    if (min.HasValue && value < min)
                    {
                        value = null;
                    }
                }

                if (value == null)
                {
                    bool negative = (random % 2 == 0);
                    if (min.HasValue && min >= decimal.Zero)
                    {
                        negative = false;
                    }

                    int fractionLength = AstoriaTestProperties.Random.Next(scale);
                    int integerLength  = AstoriaTestProperties.Random.Next(precision - scale); //assume that it will be padded to the maximum scale

                    if (max.HasValue && max <= decimal.One && !negative)
                    {
                        integerLength = 0;
                    }

                    StringBuilder builder = new StringBuilder();
                    if (negative)
                    {
                        builder.Append('-');
                    }

                    if (integerLength == 0)
                    {
                        builder.Append('0');
                    }
                    else
                    {
                        for (int i = 0; i < integerLength; i++)
                        {
                            builder.Append(AstoriaTestProperties.Random.Next(10));
                        }
                    }

                    if (fractionLength > 0)
                    {
                        builder.Append('.');
                        for (int i = 0; i < fractionLength; i++)
                        {
                            builder.Append(AstoriaTestProperties.Random.Next(10));
                        }
                    }

                    string asString = builder.ToString();

                    SqlDecimal sqlValue = SqlDecimal.Parse(builder.ToString());
                    value = sqlValue.Value;

                    try
                    {
                        SqlDecimal.ConvertToPrecScale(sqlValue, precision, scale); //in case the DB wants it to use the whole scale
                    }
                    catch (Exception e)
                    {
                        throw new TestFailedException(String.Format("Generated decimal value '{0}' exceeds precision/scale specified", asString), null, null, e);
                    }
                }

                return(new NodeValue(value.Value, this));
            }
            else
            {
                return(this.CreateRandomValue());
            }
        }