public override void SetResult(string answer) { if (!answer.Equals(string.Empty)) Answer = Decimal.Parse(answer); else Answer = null; }
private void Button_Click(object sender, RoutedEventArgs e) { try { if (dpDate.SelectedDate == null) throw new Exception(); date = dpDate.SelectedDate.Value; nalog = Int32.Parse(txtProcent.Text); if (nalog <= 0 || nalog > 100) throw new Exception(); docNumber = txtNumDoc.Text.Length > 2? txtNumDoc.Text : null; try { docMoney = Decimal.Parse(txtMoney.Text); } catch { docMoney = null; } docDate = dpDateDoc.SelectedDate; } catch { MessageBox.Show("Некорректные значения!"); return; } DialogResult = true; }
/// <summary> /// Constructeur de lieu /// </summary> /// <param name="adresse">adresse</param> /// <param name="codePostal">codePostal</param> /// <param name="nom">nom</param> /// <param name="nbPlacesTotal">nbPlacesTotal</param> /// <param name="pays">pays</param> /// <param name="prctCom">pourcentage de commission</param> /// <param name="tel">numéro de téléphone</param> /// <param name="ville">Ville</param> public LieuWS(System.Guid guid, string adresse, string nom, int nbPlacesTotal, Decimal? prctCom) { _guid = guid; _adresse = adresse; _nom = nom; _nombrePlacesTotal = nbPlacesTotal; _pourcentageCommission = prctCom; }
public static void Default() { a04id = 0; a02id = 0; a04type = 0; a04code = String.Empty; a04isvalid = false; a08id = null; }
private void Button_Click(object sender, RoutedEventArgs e) { try { if (dpDate.SelectedDate == null) throw new Exception(); date = dpDate.SelectedDate.Value; Days = Int32.Parse(txtDays.Text); if (Days <= 0 || Days > 30) throw new Exception(); docNumber = txtNumDoc.Text.Length > 2 ? txtNumDoc.Text : null; try { docMoney = Decimal.Parse(txtMoney.Text); } catch { docMoney = null; } docDate = dpDateDoc.SelectedDate; try { Others = Decimal.Parse(txtOthers.Text); } catch { Others = null; } Month = cbMonth.SelectedIndex; try { Fond = Decimal.Parse(txtFond.Text); } catch { Fond = null; } try { Dolg = Decimal.Parse(txtDolg.Text); } catch { Dolg = null; } } catch { MessageBox.Show("Некорректные значения!"); return; } DialogResult = true; }
/// <summary> /// /// </summary> public Quote(decimal? ask, decimal? bid, decimal? volume, DateTime? time) { _ask = ask; _bid = bid; _volume = volume; _time = time; _low = null; _high = null; _open = null; }
/// <summary> /// Special constructor allows to build a quote from data bar. /// </summary> /// <param name="bar"></param> public Quote(DataBar bar, decimal spread) { _ask = bar.Close; _bid = bar.Close - spread; _volume = bar.Volume; _time = bar.DateTime; _low = null; _high = null; _open = null; }
public static decimal? NullableDecimal(bool includeNullValues = true) { var returnValue = new Decimal?(); var getNullValue = Random.Next(5) == 1; if (!includeNullValues || !getNullValue) { var scale = (byte) Random.Next(29); var sign = Random.Next(2) == 1; returnValue = new decimal(Random.Next(), Random.Next(), Random.Next(), sign, scale); } return returnValue; }
/// <summary> /// Creates a new range of decimal values. /// </summary> /// <param name="Min">The minimum value or lower bound.</param> /// <param name="Max">The maximum value or upper bound.</param> public DecimalMinMax(Decimal? Min, Decimal? Max) { #region Initial checks if (Min.HasValue && Max.HasValue && Min > Max) throw new ArgumentException("The minimum must not be larger than the maximum!"); #endregion _Min = Min; _Max = Max; }
private void assignFilters() { name=textBoxName.Text; lastname=textBoxLastname.Text; docType=comboBoxDocType.Text; if (!String.IsNullOrEmpty(textBoxDocNumber.Text)) { docNumber = Decimal.Parse(textBoxDocNumber.Text); } else { docNumber = -1; } mail=textBoxEmail.Text; }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { Decimal? d = default(Decimal?); if (value != null) { d = value as Decimal?; if (d.HasValue) // If value was a decimal?, then this is possible { d = new Decimal?(new Decimal(Decimal.ToDouble(d.Value))); // The ToDouble-conversion removes all unnessecary precision } } JToken.FromObject((int)(d * 100)).WriteTo(writer); }
public void Convert_Boundary_NullOrEmptyReturnsEmptyString() { FileSizeConverter converter = new FileSizeConverter(); object input = null; string expected = string.Empty; object output = converter.Convert(input, typeof(string), null, Thread.CurrentThread.CurrentCulture); Assert.AreEqual(expected, output, string.Format("Expected result is '{0}'", expected)); input = new Decimal?(); expected = string.Empty; output = converter.Convert(input, typeof(string), null, Thread.CurrentThread.CurrentCulture); Assert.AreEqual(expected, output, string.Format("Expected result is '{0}'", expected)); }
private void bottomListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); bottomTextBox.TextChanged -= bottomTextBox_TextChanged; rate = cur.getRate(topListBox.SelectedIndex, bottomListBox.SelectedIndex); if (rate != null) { middleTextBlock.Text = String.Format("{0:0.00##}", rate); if (!topTextBox.Text.Equals("")) { numBot = rate * numTop; bottomTextBox.Text = String.Format("{0:0.####}", numBot); } } else { middleTextBlock.Text = "Unknown"; bottomTextBox.Text = ""; } bottomTextBox.TextChanged += bottomTextBox_TextChanged; }
private static void TestDialect(Dialect dialect) { Console.Clear(); Console.WriteLine("Testing expressions for Dialect {0}", dialect.Name); OrmLiteConfig.ClearCache(); OrmLiteConfig.DialectProvider = dialect.DialectProvider; SqlExpression <Author> ev = OrmLiteConfig.DialectProvider.SqlExpression <Author>(); using (IDbConnection db = dialect.ConnectionString.OpenDbConnection()) { try { db.DropTable <Author>(); var tableExists = OrmLiteConfig.DialectProvider.DoesTableExist(db, typeof(Author).Name); Console.WriteLine("Expected:{0} Selected:{1} {2}", bool.FalseString, tableExists.ToString(), !tableExists ? "OK" : "************** FAILED ***************"); db.CreateTable <Author>(); tableExists = OrmLiteConfig.DialectProvider.DoesTableExist(db, typeof(Author).Name); Console.WriteLine("Expected:{0} Selected:{1} {2}", bool.TrueString, tableExists.ToString(), tableExists ? "OK" : "************** FAILED ***************"); db.DeleteAll <Author>(); Console.WriteLine("Inserting..."); DateTime t1 = DateTime.Now; db.InsertAll(authors); DateTime t2 = DateTime.Now; Console.WriteLine("Inserted {0} rows in {1}", authors.Count, t2 - t1); Console.WriteLine("Selecting....."); int year = DateTime.Today.AddYears(-20).Year; var lastDay = new DateTime(year, 12, 31); int expected = 5; ev.Where().Where(rn => rn.Birthday >= new DateTime(year, 1, 1) && rn.Birthday <= lastDay); Console.WriteLine(ev.ToSelectStatement()); List <Author> result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); result = db.Select <Author>(qry => qry.Where(rn => rn.Birthday >= new DateTime(year, 1, 1) && rn.Birthday <= lastDay)); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); result = db.Select <Author>(rn => rn.Birthday >= new DateTime(year, 1, 1) && rn.Birthday <= lastDay); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); Author a = new Author() { Birthday = lastDay }; result = db.Select <Author>(rn => rn.Birthday >= new DateTime(year, 1, 1) && rn.Birthday <= a.Birthday); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); // select authors from London, Berlin and Madrid : 6 expected = 6; //Sql.In can take params object[] var city = "Berlin"; ev.Where().Where(rn => Sql.In(rn.City, "London", "Madrid", city)); //clean prev result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); result = db.Select <Author>(rn => Sql.In(rn.City, new[] { "London", "Madrid", "Berlin" })); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); // select authors from Bogota and Cartagena : 7 expected = 7; //... or Sql.In can take List<Object> city = "Bogota"; List <Object> cities = new List <Object>(); cities.Add(city); cities.Add("Cartagena"); ev.Where().Where(rn => Sql.In(rn.City, cities)); result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); result = db.Select <Author>(rn => Sql.In(rn.City, "Bogota", "Cartagena")); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); // select authors which name starts with A expected = 3; ev.Where().Where(rn => rn.Name.StartsWith("A")); result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); result = db.Select <Author>(rn => rn.Name.StartsWith("A")); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); // select authors which name ends with Garzon o GARZON o garzon ( no case sensitive ) expected = 3; var name = "GARZON"; ev.Where().Where(rn => rn.Name.ToUpper().EndsWith(name)); result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); result = db.Select <Author>(rn => rn.Name.ToUpper().EndsWith(name)); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); // select authors which name ends with garzon //A percent symbol ("%") in the LIKE pattern matches any sequence of zero or more characters //in the string. //An underscore ("_") in the LIKE pattern matches any single character in the string. //Any other character matches itself or its lower/upper case equivalent (i.e. case-insensitive matching). expected = 3; ev.Where().Where(rn => rn.Name.EndsWith("garzon")); result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); result = db.Select <Author>(rn => rn.Name.EndsWith("garzon")); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); // select authors which name contains Benedict expected = 2; name = "Benedict"; ev.Where().Where(rn => rn.Name.Contains(name)); result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); result = db.Select <Author>(rn => rn.Name.Contains("Benedict")); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); a.Name = name; result = db.Select <Author>(rn => rn.Name.Contains(a.Name)); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); // select authors with Earnings <= 50 expected = 3; var earnings = 50; ev.Where().Where(rn => rn.Earnings <= earnings); result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); result = db.Select <Author>(rn => rn.Earnings <= 50); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); // select authors with Rate = 10 and city=Mexio expected = 1; city = "Mexico"; ev.Where().Where(rn => rn.Rate == 10 && rn.City == city); result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); result = db.Select <Author>(rn => rn.Rate == 10 && rn.City == "Mexico"); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); a.City = city; result = db.Select <Author>(rn => rn.Rate == 10 && rn.City == a.City); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); // enough selecting, lets update; // set Active=false where rate =0 expected = 2; var rate = 0; ev.Where().Where(rn => rn.Rate == rate).Update(rn => rn.Active); var rows = db.UpdateOnly(new Author() { Active = false }, ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, rows, expected == rows ? "OK" : "************** FAILED ***************"); // insert values only in Id, Name, Birthday, Rate and Active fields expected = 4; ev.Insert(rn => new { rn.Id, rn.Name, rn.Birthday, rn.Active, rn.Rate }); db.InsertOnly(new Author() { Active = false, Rate = 0, Name = "Victor Grozny", Birthday = DateTime.Today.AddYears(-18) }, ev); db.InsertOnly(new Author() { Active = false, Rate = 0, Name = "Ivan Chorny", Birthday = DateTime.Today.AddYears(-19) }, ev); ev.Where().Where(rn => !rn.Active); result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); //update comment for City == null expected = 2; ev.Where().Where(rn => rn.City == null).Update(rn => rn.Comments); rows = db.UpdateOnly(new Author() { Comments = "No comments" }, ev); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, rows, expected == rows ? "OK" : "************** FAILED ***************"); // delete where City is null expected = 2; rows = db.Delete(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, rows, expected == rows ? "OK" : "************** FAILED ***************"); // lets select all records ordered by Rate Descending and Name Ascending expected = 14; ev.Where().OrderBy(rn => new { at = Sql.Desc(rn.Rate), rn.Name }); // clear where condition result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); Console.WriteLine(ev.OrderByExpression); var author = result.FirstOrDefault(); Console.WriteLine("Expected:{0} Selected:{1} {2}", "Claudia Espinel", author.Name, "Claudia Espinel" == author.Name ? "OK" : "************** FAILED ***************"); // select only first 5 rows .... expected = 5; ev.Limit(5); // note: order is the same as in the last sentence result = db.Select(ev); Console.WriteLine(ev.WhereExpression); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); // and finally lets select only Name and City (name will be "UPPERCASED" ) ev.Select(rn => new { at = Sql.As(rn.Name.ToUpper(), "Name"), rn.City }); Console.WriteLine(ev.SelectExpression); result = db.Select(ev); author = result.FirstOrDefault(); Console.WriteLine("Expected:{0} Selected:{1} {2}", "Claudia Espinel".ToUpper(), author.Name, "Claudia Espinel".ToUpper() == author.Name ? "OK" : "************** FAILED ***************"); ev.Select(rn => new { at = Sql.As(rn.Name.ToUpper(), rn.Name), rn.City }); Console.WriteLine(ev.SelectExpression); result = db.Select(ev); author = result.FirstOrDefault(); Console.WriteLine("Expected:{0} Selected:{1} {2}", "Claudia Espinel".ToUpper(), author.Name, "Claudia Espinel".ToUpper() == author.Name ? "OK" : "************** FAILED ***************"); //paging : ev.Limit(0, 4); // first page, page size=4; result = db.Select(ev); author = result.FirstOrDefault(); Console.WriteLine("Expected:{0} Selected:{1} {2}", "Claudia Espinel".ToUpper(), author.Name, "Claudia Espinel".ToUpper() == author.Name ? "OK" : "************** FAILED ***************"); ev.Limit(4, 4); // second page result = db.Select(ev); author = result.FirstOrDefault(); Console.WriteLine("Expected:{0} Selected:{1} {2}", "Jorge Garzon".ToUpper(), author.Name, "Jorge Garzon".ToUpper() == author.Name ? "OK" : "************** FAILED ***************"); ev.Limit(8, 4); // third page result = db.Select(ev); author = result.FirstOrDefault(); Console.WriteLine("Expected:{0} Selected:{1} {2}", "Rodger Contreras".ToUpper(), author.Name, "Rodger Contreras".ToUpper() == author.Name ? "OK" : "************** FAILED ***************"); // select distinct.. ev.Limit().OrderBy(); // clear limit, clear order for postres ev.SelectDistinct(r => r.City); expected = 6; result = db.Select(ev); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, result.Count, expected == result.Count ? "OK" : "************** FAILED ***************"); ev.Select(r => Sql.As(Sql.Max(r.Birthday), "Birthday")); result = db.Select(ev); var expectedResult = authors.Max(r => r.Birthday); Console.WriteLine("Expected:{0} Selected {1} {2}", expectedResult, result[0].Birthday, expectedResult == result[0].Birthday ? "OK" : "************** FAILED ***************"); ev.Select(r => Sql.As(Sql.Max(r.Birthday), r.Birthday)); result = db.Select(ev); expectedResult = authors.Max(r => r.Birthday); Console.WriteLine("Expected:{0} Selected {1} {2}", expectedResult, result[0].Birthday, expectedResult == result[0].Birthday ? "OK" : "************** FAILED ***************"); var r1 = db.Single(ev); Console.WriteLine("FOD: Expected:{0} Selected {1} {2}", expectedResult, r1.Birthday, expectedResult == r1.Birthday ? "OK" : "************** FAILED ***************"); var r2 = db.Scalar <Author, DateTime>(e => Sql.Max(e.Birthday)); Console.WriteLine("GetScalar DateTime: Expected:{0} Selected {1} {2}", expectedResult, r2, expectedResult == r2 ? "OK" : "************** FAILED ***************"); ev.Select(r => Sql.As(Sql.Min(r.Birthday), "Birthday")); result = db.Select(ev); expectedResult = authors.Min(r => r.Birthday); Console.WriteLine("Expected:{0} Selected {1} {2}", expectedResult, result[0].Birthday, expectedResult == result[0].Birthday? "OK" : "************** FAILED ***************"); ev.Select(r => Sql.As(Sql.Min(r.Birthday), r.Birthday)); result = db.Select(ev); expectedResult = authors.Min(r => r.Birthday); Console.WriteLine("Expected:{0} Selected {1} {2}", expectedResult, result[0].Birthday, expectedResult == result[0].Birthday? "OK" : "************** FAILED ***************"); ev.Select(r => new{ r.City, MaxResult = Sql.As(Sql.Min(r.Birthday), "Birthday") }) .GroupBy(r => r.City) .OrderBy(r => r.City); result = db.Select(ev); var expectedStringResult = "Berlin"; Console.WriteLine("Expected:{0} Selected {1} {2}", expectedResult, result[0].City, expectedStringResult == result[0].City ? "OK" : "************** FAILED ***************"); ev.Select(r => new{ r.City, MaxResult = Sql.As(Sql.Min(r.Birthday), r.Birthday) }) .GroupBy(r => r.City) .OrderBy(r => r.City); result = db.Select(ev); expectedStringResult = "Berlin"; Console.WriteLine("Expected:{0} Selected {1} {2}", expectedResult, result[0].City, expectedStringResult == result[0].City ? "OK" : "************** FAILED ***************"); r1 = db.Single(ev); Console.WriteLine("FOD: Expected:{0} Selected {1} {2}", expectedResult, r1.City, expectedStringResult == result[0].City ? "OK" : "************** FAILED ***************"); var expectedDecimal = authors.Max(e => e.Earnings); Decimal?r3 = db.Scalar <Author, Decimal?>(e => Sql.Max(e.Earnings)); Console.WriteLine("GetScalar decimal?: Expected:{0} Selected {1} {2}", expectedDecimal, r3.Value, expectedDecimal == r3.Value ? "OK" : "************** FAILED ***************"); var expectedString = authors.Max(e => e.Name); string r4 = db.Scalar <Author, String>(e => Sql.Max(e.Name)); Console.WriteLine("GetScalar string?: Expected:{0} Selected {1} {2}", expectedString, r4, expectedString == r4 ? "OK" : "************** FAILED ***************"); var expectedDate = authors.Max(e => e.LastActivity); DateTime?r5 = db.Scalar <Author, DateTime?>(e => Sql.Max(e.LastActivity)); Console.WriteLine("GetScalar datetime?: Expected:{0} Selected {1} {2}", expectedDate, r5, expectedDate == r5 ? "OK" : "************** FAILED ***************"); var expectedDate51 = authors.Where(e => e.City == "Bogota").Max(e => e.LastActivity); DateTime?r51 = db.Scalar <Author, DateTime?>( e => Sql.Max(e.LastActivity), e => e.City == "Bogota"); Console.WriteLine("GetScalar datetime?: Expected:{0} Selected {1} {2}", expectedDate51, r51, expectedDate51 == r51 ? "OK" : "************** FAILED ***************"); try{ var expectedBool = authors.Max(e => e.Active); bool r6 = db.Scalar <Author, bool>(e => Sql.Max(e.Active)); Console.WriteLine("GetScalar bool: Expected:{0} Selected {1} {2}", expectedBool, r6, expectedBool == r6 ? "OK" : "************** FAILED ***************"); } catch (Exception e) { if (dialect.Name == "PostgreSQL") { Console.WriteLine("OK PostgreSQL: " + e.Message); } else { Console.WriteLine("************** FAILED *************** " + e.Message); } } // Tests for predicate overloads that make use of the expression visitor Console.WriteLine("First author by name (exists)"); author = db.Single <Author>(q => q.Name == "Jorge Garzon"); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Jorge Garzon", author.Name, "Jorge Garzon" == author.Name); try { Console.WriteLine("First author by name (does not exist)"); author = db.Single <Author>(q => q.Name == "Does not exist"); Console.WriteLine("Expected exception thrown, OK? False"); } catch { Console.WriteLine("Expected exception thrown, OK? True"); } Console.WriteLine("First author or default (does not exist)"); author = db.Single <Author>(q => q.Name == "Does not exist"); Console.WriteLine("Expected:null ; OK? {0}", author == null); Console.WriteLine("First author or default by city (multiple matches)"); author = db.Single <Author>(q => q.City == "Bogota"); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Angel Colmenares", author.Name, "Angel Colmenares" == author.Name); a.City = "Bogota"; author = db.Single <Author>(q => q.City == a.City); Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Angel Colmenares", author.Name, "Angel Colmenares" == author.Name); // count test var expectedCount = authors.Count(); long r7 = db.Scalar <Author, long>(e => Sql.Count(e.Id)); Console.WriteLine("GetScalar long: Expected:{0} Selected {1} {2}", expectedCount, r7, expectedCount == r7 ? "OK" : "************** FAILED ***************"); expectedCount = authors.Count(e => e.City == "Bogota"); r7 = db.Scalar <Author, long>( e => Sql.Count(e.Id), e => e.City == "Bogota"); Console.WriteLine("GetScalar long: Expected:{0} Selected {1} {2}", expectedCount, r7, expectedCount == r7 ? "OK" : "************** FAILED ***************"); // more updates..... Console.WriteLine("more updates....................."); ev.Update(); // all fields will be updated // select and update expected = 1; var rr = db.Single <Author>(rn => rn.Name == "Luis garzon"); rr.City = "Madrid"; rr.Comments = "Updated"; ev.Where().Where(r => r.Id == rr.Id); // if omit, then all records will be updated rows = db.UpdateOnly(rr, ev); // == dbCmd.Update(rr) but it returns void Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, rows, expected == rows ? "OK" : "************** FAILED ***************"); expected = 0; ev.Where().Where(r => r.City == "Ciudad Gotica"); rows = db.UpdateOnly(rr, ev); Console.WriteLine("Expected:{0} Selected:{1} {2}", expected, rows, expected == rows ? "OK" : "************** FAILED ***************"); expected = db.Select <Author>(x => x.City == "Madrid").Count; author = new Author() { Active = false }; rows = db.UpdateOnly(author, x => x.Active, x => x.City == "Madrid"); Console.WriteLine("Expected:{0} Updated:{1} {2}", expected, rows, expected == rows ? "OK" : "************** FAILED ***************"); expected = db.Select <Author>(x => x.Active == false).Count; rows = db.Delete <Author>(x => x.Active == false); Console.WriteLine("Expected:{0} Deleted:{1} {2}", expected, rows, expected == rows ? "OK" : "************** FAILED ***************"); DateTime t3 = DateTime.Now; Console.WriteLine("Expressions test in: {0}", t3 - t2); Console.WriteLine("All test in : {0}", t3 - t1); } catch (Exception e) { Console.WriteLine(e.Message); } } Console.WriteLine("Press enter to return to main menu"); Console.ReadLine(); PaintMenu(); }
/// <summary> /// Sets the TotalFeedback property /// </summary> /// <param name="totalFeedback">TotalFeedback property</param> /// <returns>this instance</returns> public Merchant WithTotalFeedback(Decimal totalFeedback) { this.totalFeedbackField = totalFeedback; return this; }
/** Set Process Number. * @param P_Number Process Parameter */ public void SetP_Number(Decimal?P_Number) { Set_Value("P_Number", (Decimal?)P_Number); }
/// <summary> /// Convert Qty/Amt from entered UOM TO product UoM and round. /// </summary> /// <param name="ctx"></param> /// <param name="M_Product_ID">product</param> /// <param name="C_UOM_To_ID">entered UOM</param> /// <param name="qtyPrice">entered quantity or price</param> /// <returns>Product: Qty/Amt in product UoM (precision rounded)</returns> public static Decimal?ConvertProductTo(Ctx ctx, int M_Product_ID, int C_UOM_To_ID, Decimal?qtyPrice) { if (qtyPrice == null || qtyPrice == 0 || M_Product_ID == 0 || C_UOM_To_ID == 0) { return(qtyPrice); } Decimal?retValue = (Decimal?)(GetProductRateTo(ctx, M_Product_ID, C_UOM_To_ID)); if (retValue != null) { if (Env.ONE.CompareTo(retValue) == 0) { return(qtyPrice); } MUOM uom = MUOM.Get(ctx, C_UOM_To_ID); if (uom != null) { return(uom.Round(Decimal.Multiply(Utility.Util.GetValueOfDecimal(retValue), Utility.Util.GetValueOfDecimal(qtyPrice)), true)); } return(Decimal.Multiply(Utility.Util.GetValueOfDecimal(retValue), Utility.Util.GetValueOfDecimal(qtyPrice))); } return(null); }
/// <summary> /// Sets the InstanceCount property /// </summary> /// <param name="instanceCount">The number of Reserved Instances purchased.</param> /// <returns>this instance</returns> public ReservedInstances WithInstanceCount(Decimal instanceCount) { this.instanceCountField = instanceCount; return this; }
/** Set Account Debit. * @param AccountDebit Account Debit */ public void SetAccountDebit(Decimal?AccountDebit) { Set_Value("AccountDebit", (Decimal?)AccountDebit); }
/// <summary> /// Sets the Count property /// </summary> /// <param name="count">Count property</param> /// <returns>this instance</returns> public UpdateReportAcknowledgementsResult WithCount(Decimal count) { this.countField = count; return(this); }
/// <summary> /// Sets the BytesConverted property /// </summary> /// <param name="bytesConverted">Number of bytes converted so far.</param> /// <returns>this instance</returns> public ImportInstanceVolumeDetailItemType WithBytesConverted(Decimal bytesConverted) { this.bytesConvertedField = bytesConverted; return this; }
/// <summary> /// Sets the Rank property /// </summary> /// <param name="rank">Rank property</param> /// <returns>this instance</returns> public SalesRankType WithRank(Decimal rank) { this.rankField = rank; return(this); }
public ImportInstanceVolumeDetailItemType WithBytesConverted(Decimal bytesConverted) { this.bytesConvertedField = bytesConverted; return(this); }
public List <SPE_OBTIENE_C_EMPLEADO_IDIOMA_Result> Obtener_C_EMPLEADO_IDIOMA(int?ID_EMPLEADO_IDIOMA = null, int?ID_EMPLEADO = null, int?ID_CANDIDATO = null, int?ID_IDIOMA = null, Decimal?PR_LECTURA = null, Decimal?PR_ESCRITURA = null, Decimal?PR_CONVERSACIONAL = null, int?CL_INSTITUCION = null, Decimal?NO_PUNTAJE = null, DateTime?FE_CREACION = null, DateTime?FE_MODIFICACION = null, String CL_USUARIO_APP_CREA = null, String CL_USUARIO_APP_MODIFICA = null, String NB_PROGRAMA_CREA = null, String NB_PROGRAMA_MODIFICA = null) { using (context = new SistemaSigeinEntities()) { var q = from V_C_EMPLEADO_IDIOMA in context.SPE_OBTIENE_C_EMPLEADO_IDIOMA(ID_EMPLEADO_IDIOMA, ID_EMPLEADO, ID_CANDIDATO, ID_IDIOMA, PR_LECTURA, PR_ESCRITURA, PR_CONVERSACIONAL, CL_INSTITUCION, NO_PUNTAJE) select V_C_EMPLEADO_IDIOMA; return(q.ToList()); } }
/*public DataTable filters(String name, String lastname, String docType, Decimal? docNumber, String mail) { * SqlResults results = new SqlQuery() * }*/ public DataTable filteredSearch(String name, String lastname, String docType, Decimal?docNumber, String mail) { if (docNumber == -1) { SqlResults results = new SqlFunction("[BOBBY_TABLES].SP_FILTER_PERSONS_NULLDOC") .WithParam("@Name").As(SqlDbType.VarChar).Value(name) .WithParam("@Lastname").As(SqlDbType.VarChar).Value(lastname) .WithParam("@DocType").As(SqlDbType.VarChar).Value(docType) .WithParam("@Mail").As(SqlDbType.VarChar).Value(mail) .Execute(); return((DataTable)results["ReturnedValues"]); } else { SqlResults results = new SqlFunction("[BOBBY_TABLES].SP_FILTER_PERSONS") .WithParam("@Name").As(SqlDbType.VarChar).Value(name) .WithParam("@Lastname").As(SqlDbType.VarChar).Value(lastname) .WithParam("@DocType").As(SqlDbType.VarChar).Value(docType) .WithParam("@DocNumber").As(SqlDbType.Decimal).Value(docNumber) .WithParam("@Mail").As(SqlDbType.VarChar).Value(mail) .Execute(); return((DataTable)results["ReturnedValues"]); } }
/** Set Source Debit. * @param SourceDebit Source Debit */ public void SetSourceDebit(Decimal?SourceDebit) { Set_Value("SourceDebit", (Decimal?)SourceDebit); }
/// <summary> /// Sets the MaxRecords property /// </summary> /// <param name="maxRecords">The maximum number of records to include in the response. If more than the MaxRecords value is available, a /// marker is included in the response so that the following results can be retrieved. /// Default: 100. Constraints: Minimum 20, maximum 100</param> /// <returns>this instance</returns> public DescribeEventsRequest WithMaxRecords(Decimal maxRecords) { this.maxRecordsField = maxRecords; return(this); }
/// <summary> /// Sets the InstanceCount property /// </summary> /// <param name="instanceCount">Number of EC2 instances in the cluster. If the value is 1, one instance serves as the master and slave node. /// If the value is greater than one, one instance is the master node and the remainder are slave nodes.</param> /// <returns>this instance</returns> public JobFlowInstancesConfig WithInstanceCount(Decimal instanceCount) { this.instanceCountField = instanceCount; return(this); }
/// <summary> /// Sets the ListPage property /// </summary> /// <param name="listPage">ListPage property</param> /// <returns>this instance</returns> public ListSearchRequest WithListPage(Decimal listPage) { this.listPageField = listPage; return this; }
private void TableForm_Load(object sender, EventArgs e) { // TODO: This line of code loads data into the 'dataSetQuery.QCondenserTypes' table. You can move, or remove it, as needed. if (Program.m_bExpertMode) { panelExpertMode.Visible = true; } else { panelExpertMode.Visible = false; } string strSeparator = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator; if (strSeparator == ".") { strSeparator = "\\."; } teKoefA.Properties.Mask.EditMask = "(-?\\d{1,6}|-?\\d{1,6}" + strSeparator + "\\d{1,4})"; teKoefB.Properties.Mask.EditMask = "(-?\\d{1,6}|-?\\d{1,6}" + strSeparator + "\\d{1,4})"; teR2.Properties.Mask.EditMask = "(-?\\d{1,6}|-?\\d{1,6}" + strSeparator + "\\d{1,4})"; teKI1.Properties.Mask.EditMask = "(\\d{1,6}|-?\\d{1,6}" + strSeparator + "\\d{1,4})"; listFunctionType.Add(new DataSourceString(0, "степенная")); listFunctionType.Add(new DataSourceString(1, "экспоненциальная")); listFunctionType.Add(new DataSourceString(2, "логарифмическая")); cbFunctionType.Properties.DataSource = listFunctionType; cbFunctionType.Properties.DisplayMember = "VAL"; cbFunctionType.Properties.ValueMember = "KEY"; cbFunctionType.Properties.DropDownRows = listFunctionType.Count; cbFunctionType.EditValue = (long)0; // TODO: This line of code loads data into the 'dataSetQuery.QCondenserTypesForTable' table. You can move, or remove it, as needed. this.qCondenserTypesTableAdapter.Fill(this.dataSetQuery.QCondenserTypes); // TODO: This line of code loads data into the 'dataSetQuery.QCondenserTypes' table. You can move, or remove it, as needed. if (this.dataSetQuery.QCondenserTypes.Count < 7) { cbCondenserType.Properties.DropDownRows = this.dataSetQuery.QCondenserTypes.Count; } else { cbCondenserType.Properties.DropDownRows = 7; } Graphics formGraphics = this.CreateGraphics(); DpiXRel = formGraphics.DpiX / 96.0f; DpiYRel = formGraphics.DpiY / 96.0f; GridDC.DataSource = listData; //BandedGridViewInfo viewInfo = GridView.GetViewInfo() as BandedGridViewInfo; Size captionSize = GridView.Appearance.BandPanel.CalcTextSize(formGraphics, "www", 1000).ToSize(); m_singleLineHeight = captionSize.Height;// viewInfo.BandRowHeight; //DevExpress.Utils.AppearanceObject[] styles = {GridView.Appearance.BandPanel}; //m_singleLineHeight = viewInfo.CalcMaxHeight(styles); //int ii = viewInfo.ColumnRowHeight; cbCondenserType.EditValue = m_iCondenserTypeID; for (int i = 1; i <= 4; i++) { for (int j = 1; j <= 4; j++) { dictRecords[i * 10 + j] = new RecommendationInfo(); } } if (m_iKoefID != DBNull.Value) { try { SQLiteConnection connection = new SQLiteConnection(global::Condenser.Properties.Settings.Default.condenserConnectionString); connection.Open(); SQLiteCommand com = new SQLiteCommand(connection); com.CommandText = "SELECT KI1, KoefA, KoefB, KoefR2, FunctionType FROM CondenserTypeParameters WHERE KoefID = @koefID"; com.CommandType = CommandType.Text; SQLiteParameter param1 = new SQLiteParameter("@koefID", DbType.Int64); param1.Value = (long)m_iKoefID; com.Parameters.Add(param1); SQLiteDataReader dr = com.ExecuteReader(); while (dr.Read()) { if (dr["KI1"] != DBNull.Value) { teKI1.EditValue = dr["KI1"]; } if (dr["KoefA"] != DBNull.Value) { teKoefA.EditValue = dr["KoefA"]; } if (dr["KoefB"] != DBNull.Value) { teKoefB.EditValue = dr["KoefB"]; } if (dr["KoefR2"] != DBNull.Value) { teR2.EditValue = dr["KoefR2"]; } if (dr["FunctionType"] != DBNull.Value) { cbFunctionType.EditValue = dr["FunctionType"]; } break; } dr.Close(); com.CommandText = "select ID, Position, Value, Conclusion, Recommendation FROM ParameterRecommendations WHERE KoefID = @KoefID"; com.CommandType = CommandType.Text; SQLiteDataReader drRecomm = com.ExecuteReader(); while (drRecomm.Read()) { long ID = Convert.ToInt64(drRecomm["ID"]); long iPosition = Convert.ToInt64(drRecomm["Position"]); Decimal?fValue = null; if (drRecomm["Value"] != DBNull.Value) { fValue = Convert.ToDecimal(drRecomm["Value"]); } string strConclusion = Convert.ToString(drRecomm["Conclusion"]); string strRecommendation = Convert.ToString(drRecomm["Recommendation"]); dictRecords[iPosition] = new RecommendationInfo(ID, strRecommendation, strConclusion, fValue); /*if (fValue != null) * strRecommendation = strRecommendation.Replace("$", "<b>" + fValue.ToString() + "%</b>"); * else * strRecommendation = strRecommendation.Replace("$", ""); * * if (strConclusion != "") * dictRecords[iPosition] = "<b>Заключение:</b> " + strConclusion; * if (strRecommendation != "") * { * if (strConclusion != "") dictRecords[iPosition] += "<br>"; * dictRecords[iPosition] += "<b>Рекомендация:</b> " + strRecommendation; * }*/ } drRecomm.Close(); connection.Close(); } catch (SQLiteException ex) { MyLocalizer.XtraMessageBoxShow("Ошибка при работе с базой данных. Описание: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { teKI1.EditValue = null; // 20; teKoefA.EditValue = null; //11; teKoefB.EditValue = null; //-1.1; teR2.EditValue = null; /*dictRecords[11] = new RecommendationInfo(null, "следующий отбор пробы провести после $ от РЕС циклов", "конденсатор работоспособен.", 20); * dictRecords[12] = new RecommendationInfo(null, "следующий отбор пробы провести после $ от РЕС циклов", "конденсатор работоспособен.", 10); * dictRecords[13] = new RecommendationInfo(null, "следующий отбор пробы провести после $ от РЕС циклов", "конденсатор работоспособен.", 5); * dictRecords[14] = new RecommendationInfo(null, "следующий отбор пробы провести после $ от РЕС циклов", "конденсатор работоспособен.", 5); * * dictRecords[21] = new RecommendationInfo(null, "следующий отбор пробы провести после $ от РЕС циклов", "конденсатор работоспособен.", 10); * dictRecords[22] = new RecommendationInfo(null, "следующий отбор пробы провести после $ от РЕС циклов", "конденсатор работоспособен.", 10); * dictRecords[23] = new RecommendationInfo(null, "следующий отбор пробы провести после $ от РЕС циклов", "конденсатор работоспособен.", 5); * dictRecords[24] = new RecommendationInfo(null, "следующий отбор пробы провести после $ от РЕС циклов", "конденсатор работоспособен.", 5); * * dictRecords[31] = new RecommendationInfo(null, "следующий отбор пробы провести после $ от РЕС циклов", "по показаниям газосодержания масла выработано более 90% ресурса конденсатора.", 5); * dictRecords[32] = new RecommendationInfo(null, "следующий отбор пробы провести после $ от РЕС циклов", "по показаниям газосодержания масла выработано более 90% ресурса конденсатора.", 5); * dictRecords[33] = new RecommendationInfo(null, "следующий отбор пробы провести после $ от РЕС циклов", "по показаниям газосодержания масла выработано более 90% ресурса конденсатора.", 5); * dictRecords[34] = new RecommendationInfo(null, "целесообразно вывести конденсатор из эксплуатации", "по показаниям газосодержания масла выработано более 90% ресурса конденсатора.", null); * * dictRecords[41] = new RecommendationInfo(null, "вывести конденсатор из эксплуатации", "по показаниям газосодержания масла ресурс конденсатора исчерпан.", null); * dictRecords[42] = new RecommendationInfo(null, "вывести конденсатор из эксплуатации", "по показаниям газосодержания масла ресурс конденсатора исчерпан.", null); * dictRecords[43] = new RecommendationInfo(null, "вывести конденсатор из эксплуатации", "по показаниям газосодержания масла ресурс конденсатора исчерпан.", null); * dictRecords[44] = new RecommendationInfo(null, "вывести конденсатор из эксплуатации", "по показаниям газосодержания масла ресурс конденсатора исчерпан.", null);*/ } FillData(); GridView.FocusedColumn = GridView.Columns[1]; GridView.FocusedRowHandle = 0; this.WindowState = FormWindowState.Maximized; m_bLoadEnd = true; timer1.Enabled = true; //SetBandsHeight(); }
/// <summary> /// Sets the Code property /// </summary> /// <param name="code">The ICMP code. A value of -1 is a wildcard meaning all codes.</param> /// <returns>this instance</returns> public Icmp WithCode(Decimal code) { this.codeField = code; return this; }
public RecommendationInfo(long?ID, string strRecommendation, string strConclusion, Decimal?fValue) { m_ID = ID; m_strRecommendation = strRecommendation; m_strConclusion = strConclusion; m_fValue = fValue; m_strResult = ""; if (strConclusion != "") { m_strResult = "<b>Заключение:</b> " + strConclusion; } if (strRecommendation != "") { if (strConclusion != "") { m_strResult += "<br>"; } if (fValue != null) { m_strResult += "<b>Рекомендация:</b> " + strRecommendation.Replace("$", "<b>" + fValue.ToString() + "%</b>"); } else { m_strResult += "<b>Рекомендация:</b> " + strRecommendation.Replace("$", ""); } } }
/// <summary> /// Sets the ToPort property /// </summary> /// <param name="toPort">ToPort property</param> /// <returns>this instance</returns> public AuthorizeSecurityGroupIngressRequest WithToPort(Decimal toPort) { this.toPortField = toPort; return this; }
} /** Set Quantity. * @param Qty Quantity */ public void SetQty(Decimal?Qty) { Set_Value("Qty", (Decimal?)Qty); } /** Get Quantity.
/** Set Process Number To. * @param P_Number_To Process Parameter */ public void SetP_Number_To(Decimal?P_Number_To) { Set_Value("P_Number_To", (Decimal?)P_Number_To); }
/** Set Quantity Invoiced. * @param QtyInvoiced Invoiced Quantity */ public void SetQtyInvoiced(Decimal?QtyInvoiced) { Set_Value("QtyInvoiced", (Decimal?)QtyInvoiced); }
/// <summary> /// Convert Qty/Amt FROM product UOM to entered UOM and round. /// </summary> /// <param name="ctx"></param> /// <param name="M_Product_ID">product</param> /// <param name="C_UOM_To_ID">quantity or price</param> /// <param name="qtyPrice">quantity or price</param> /// <returns>Entered: Qty in entered UoM (precision rounded)</returns> //public static Decimal? ConvertProductFrom(Ctx ctx, int M_Product_ID, int C_UOM_To_ID, Decimal? qtyPrice,bool _ProductToConversion=false) public static Decimal?ConvertProductFrom(Ctx ctx, int M_Product_ID, int C_UOM_To_ID, Decimal?qtyPrice) { // No conversion // Arpit to Pass a Parametrized Constructor so that we can have the reverse conversion rate for the defined product // bool ProductToConversion = _ProductToConversion; // Arpit if (qtyPrice == null || qtyPrice.Equals(Env.ZERO) || C_UOM_To_ID == 0 || M_Product_ID == 0) { _log.Fine("No Conversion - QtyPrice=" + qtyPrice); return(qtyPrice); } //Decimal? retValue = (Decimal?)GetProductRateFrom(ctx, M_Product_ID, C_UOM_To_ID, ProductToConversion); Decimal?retValue = (Decimal?)GetProductRateFrom(ctx, M_Product_ID, C_UOM_To_ID); if (retValue != null) { if (Env.ONE.CompareTo(retValue.Value) == 0) { return(qtyPrice); } MUOM uom = MUOM.Get(ctx, C_UOM_To_ID); if (uom != null) { return(uom.Round(Decimal.Multiply(retValue.Value, qtyPrice.Value), true)); } //return retValue.multiply(qtyPrice); return(Decimal.Multiply(retValue.Value, (Decimal)qtyPrice)); } _log.Fine("No Rate M_Product_ID=" + M_Product_ID); return(null); }
/** Set Quantity Plan. * @param QtyPlan Planned Quantity */ public void SetQtyPlan(Decimal?QtyPlan) { Set_Value("QtyPlan", (Decimal?)QtyPlan); }
/// <summary> /// Get Converted Qty from Server (no cache) /// </summary> /// <param name="C_UOM_From_ID">The C_UOM_ID of the qty</param> /// <param name="C_UOM_To_ID">The targeted UOM</param> /// <param name="qty">The quantity to be converted</param> /// <param name="StdPrecision">if true, standard precision, if false costing precision</param> /// <returns>should not be used</returns> public static Decimal?Convert(int C_UOM_From_ID, int C_UOM_To_ID, Decimal qty, bool StdPrecision) { // Nothing to do if (qty == null || qty.Equals(Env.ZERO) || C_UOM_From_ID == C_UOM_To_ID) { return(qty); } // Decimal?retValue = null; int precision = 2; String sql = "SELECT c.MultiplyRate, uomTo.StdPrecision, uomTo.CostingPrecision " + "FROM C_UOM_Conversion c" + " INNER JOIN C_UOM uomTo ON (c.C_UOM_To_ID=uomTo.C_UOM_ID) " + "WHERE c.IsActive='Y' AND c.C_UOM_ID=" + C_UOM_From_ID + " AND c.C_UOM_To_ID=" + C_UOM_To_ID // #1/2 + " AND c.M_Product_ID IS NULL" + " ORDER BY c.AD_Client_ID DESC, c.AD_Org_ID DESC"; DataTable dt = null; IDataReader idr = null; try { idr = DataBase.DB.ExecuteReader(sql, null, null); dt = new DataTable(); dt.Load(idr); idr.Close(); foreach (DataRow dr in dt.Rows) { retValue = Utility.Util.GetValueOfDecimal(dr[0]); precision = Utility.Util.GetValueOfInt(dr[StdPrecision ? 2 : 3]); } } catch (Exception e) { if (idr != null) { idr.Close(); idr = null; } _log.Log(Level.SEVERE, sql, e); } finally { if (idr != null) { idr.Close(); idr = null; } dt = null; } if (retValue == null) { _log.Info("NOT found - FromUOM=" + C_UOM_From_ID + ", ToUOM=" + C_UOM_To_ID); return(null); } // Just get Rate if (GETRATE.Equals(qty)) { return((Decimal)retValue); } // Calculate & Scale retValue = Decimal.Multiply((Decimal)retValue, qty); if (Env.Scale((Decimal)retValue) > precision) { retValue = Decimal.Round((Decimal)retValue, precision);//, MidpointRounding.AwayFromZero); } return((Decimal)retValue); }
/** Set Quantity Used. * @param QtySpent Quantity used for this event */ public void SetQtySpent(Decimal?QtySpent) { Set_Value("QtySpent", (Decimal?)QtySpent); }
/// <summary> /// Sets the AverageFeedbackRating property /// </summary> /// <param name="averageFeedbackRating">AverageFeedbackRating property</param> /// <returns>this instance</returns> public Merchant WithAverageFeedbackRating(Decimal averageFeedbackRating) { this.averageFeedbackRatingField = averageFeedbackRating; return this; }
/// <summary> /// Sets the MaxNumberOfMessages property /// </summary> /// <param name="maxNumberOfMessages">Maximum number of messages to return. SQS never returns more messages than this value but might return fewer. /// Not necessarily all the messages in the queue are returned (for more information, see the preceding note about /// machine sampling). Values can be from 1 to 10. Default is 1.</param> /// <returns>this instance</returns> public ReceiveMessageRequest WithMaxNumberOfMessages(Decimal maxNumberOfMessages) { this.maxNumberOfMessagesField = maxNumberOfMessages; return this; }
/// <summary> /// Sets the TotalFeedbackPages property /// </summary> /// <param name="totalFeedbackPages">TotalFeedbackPages property</param> /// <returns>this instance</returns> public Merchant WithTotalFeedbackPages(Decimal totalFeedbackPages) { this.totalFeedbackPagesField = totalFeedbackPages; return this; }
/// <summary> /// Sets the MaxNumberOfDomains property /// </summary> /// <param name="maxNumberOfDomains">The maximum number of domain names you want returned. The range is 1 to 100. The default setting is 100.</param> /// <returns>this instance</returns> public ListDomainsRequest WithMaxNumberOfDomains(Decimal maxNumberOfDomains) { this.maxNumberOfDomainsField = maxNumberOfDomains; return this; }
protected virtual void OnIsOpenChanged( bool oldValue, bool newValue ) { if( newValue ) _initialValue = Value; }
/// <summary> /// Sets the Duration property /// </summary> /// <param name="duration">The number of minutes to retrieve events for. Default: 60.</param> /// <returns>this instance</returns> public DescribeEventsRequest WithDuration(Decimal duration) { this.durationField = duration; return(this); }
/// <summary> /// Sets the RuleNumber property /// </summary> /// <param name="ruleNumber">Rule number of the entry to replace.</param> /// <returns>this instance</returns> public ReplaceNetworkAclEntryRequest WithRuleNumber(Decimal ruleNumber) { this.ruleNumberField = ruleNumber; return this; }
public ActionResult SellStock(Int32 numShares, Int32 selectedStock) { DateTime dateEntered = System.DateTime.Now; //Get the ID for the user who is currently logged in UserManager <AppUser> userManager = new UserManager <AppUser>(new UserStore <AppUser>(db)); var user = userManager.FindById(User.Identity.GetUserId()); //Find the portfolio belonging to this user StockPortfolio portfolio = user.StockPortfolio; ///SUMMARY OF THIS METHOD //Get a list of all the transactions for buying that stock and then determine the purchase //price based upon that information. Subtract however many shares you need going to the first //purchase transaction first and then workign your way forward. //Then make a transaction object to reflect all of this information ///SUMMARY OF THIS METHOD //First, make sure they have adequate shares to begin with //If they don't, boot them back to the sale page //also boot them if they try to sell a negative number of shares StockDetail detailInQuestion = new StockDetail(); foreach (StockDetail sd in portfolio.StockDetails) { if (selectedStock == sd.Stock.StockID) { detailInQuestion = sd; } } if (numShares > detailInQuestion.Quantity || numShares < 0) { return(View()); } //Get a list of all the transactions we care about List <Transaction> relevantTransactions = GetRelevantTransactions(detailInQuestion); List <TransactionViewModel> transViewModels = new List <TransactionViewModel>(); //Make a list of transactionviewmodel objects to reflect each of these transactions foreach (Transaction t in relevantTransactions) { TransactionViewModel trvmobj = new TransactionViewModel(); trvmobj.NumPurchased = t.NumShares; trvmobj.PurchasePrice = (t.Amount / t.NumShares); transViewModels.Add(trvmobj); } //Running number of shares still to be subtracted Int32 runningShares = numShares; //Total ORIGINAL market value of the stocks sold from the account //We assume FIFO for stock sales Decimal?stockMarketValueReduction = new Decimal?(); stockMarketValueReduction = 0; //Make an actual Transaction object to record the sale of stock //And determine its value before you stubtract the number of shares down to one, //you f*****g idiot Transaction transToAdd = new Transaction(); transToAdd.StockPortfolios = new List <StockPortfolio>(); transToAdd.StockPortfolios.Add(db.StockPortfolios.Find(portfolio.StockPortfolioID)); transToAdd.Amount = numShares * bevo.Utilities.GetQuote.GetStock(detailInQuestion.Stock.StockTicker).LastTradePrice; transToAdd.FromAccount = portfolio.AccountNum; transToAdd.Stock = detailInQuestion.Stock; transToAdd.Description = "Sold " + numShares.ToString() + " shares of " + detailInQuestion.Stock.StockName + " (" + detailInQuestion.Stock.StockTicker + ") stock for $" + transToAdd.Amount.ToString(); transToAdd.Date = dateEntered; transToAdd.TransType = TransType.Sell_Stock; //Take away the appropriate number of stocks from the relevant stockdetail object attached to this //portfolio detailInQuestion.Quantity -= numShares; db.Entry(detailInQuestion).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); //Add the amount of money made from selling the stock back into the portfolio's balance portfolio.Balance += transToAdd.Amount; db.Entry(portfolio).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); //Logic to get how much the original stock market value should decrease by //Based on incrementally determining how many transactions need to be negated to //sell as many stocks as the user wants to sell Int32 listIndex = 0; while (numShares > 0) { //Take one away from the stocks in that purchase transViewModels[listIndex].NumPurchased -= 1; //Add that stock's original market value to the amount to be subtracted from the //StockMarketValue of the portfolio stockMarketValueReduction += transViewModels[listIndex].PurchasePrice; //If that is all the stocks from that transaction, move on to the next one if (transViewModels[listIndex].NumPurchased == 0) { listIndex += 1; } //Reduce the number of shares still to be sold by one numShares -= 1; } //Assign all the remaining values to the transaction to be created //Assign the SMVRedux property on the transaction record transToAdd.SMVRedux = stockMarketValueReduction; if (detailInQuestion.Stock.feeAmount != null) { //FEE TRANSACTION //create a transaction to reflect the fee Int32 sellStockFee = (Int32)detailInQuestion.Stock.feeAmount; Transaction feeTransaction = new Transaction(); feeTransaction.FromAccount = portfolio.AccountNum; feeTransaction.Date = dateEntered; feeTransaction.TransType = TransType.Fee; feeTransaction.Amount = sellStockFee; feeTransaction.Description = "Fee incurred from selling " + numShares.ToString() + " shares of " + detailInQuestion.Stock.StockName + " (" + detailInQuestion.Stock.StockTicker + ") stock on " + dateEntered.ToString(); feeTransaction.StockPortfolios = new List <StockPortfolio>(); feeTransaction.StockPortfolios.Add(portfolio); //Subtract the ten dollars from the stock portfolio cash section as a result of the fee for selling stock //Assume here that they have at least ten bucks in their account db.Entry(portfolio).State = System.Data.Entity.EntityState.Modified; db.Transactions.Add(feeTransaction); db.SaveChanges(); } //Save this to the DB db.Transactions.Add(transToAdd); db.SaveChanges(); //Redirect to the details page return(Content("<script language'javascript' type = 'text/javascript'> alert('Confirmation: Successfully sold a stock!'); window.location='../../StockPortfolio/Details';</script>")); }
/// <summary> /// Sets the Type property /// </summary> /// <param name="type">The ICMP type. A value of -1 is a wildcard meaning all types.</param> /// <returns>this instance</returns> public Icmp WithType(Decimal type) { this.typeField = type; return this; }
public static double ToDouble(this Decimal?obj) { return(Convert.ToDouble(obj)); }
/// <summary> /// Sets the Duration property /// </summary> /// <param name="duration">The duration of the Reserved Instance, in /// seconds.</param> /// <returns>this instance</returns> public ReservedInstances WithDuration(Decimal duration) { this.durationField = duration; return this; }
/// <summary> /// Generate PaySelection /// </summary> public string GeneratePaySelect(Ctx ctx, List <GridRecords> selectedRecords, Decimal?paymentAmt, String paymentRule, int C_BankAccount_ID, DateTime?payDate) { Trx trx = null; Trx p_trx = null; List <int> Invoice_ID = new List <int>(); List <Decimal?> openAmt = new List <Decimal?>(); List <Decimal?> payAmt = new List <Decimal?>(); int rowsSelected = 0; Decimal?totalAmt = 0; // BindingSource rowSource = vdgvPayment.ItemsSource as BindingSource; for (int i = 0; i < selectedRecords.Count; i++) { if ((Convert.ToBoolean(selectedRecords[i].SELECT))) { Decimal?amt = Util.GetValueOfDecimal(selectedRecords[i].PAYMENTAMOUNT); Invoice_ID.Add(Util.GetValueOfInt(selectedRecords[i].C_INVOICE_ID)); openAmt.Add(Util.GetValueOfDecimal(selectedRecords[i].AMOUNTDUE)); payAmt.Add(Util.GetValueOfDecimal(selectedRecords[i].PAYMENTAMOUNT)); rowsSelected++; } } if (rowsSelected == 0) { return(""); } //String paymentRule = Util.GetValueOfString(cmbPaymentRule.SelectedValue); //int C_BankAccount_ID = Util.GetValueOfInt(cmbBankAccount.SelectedValue); //// Create Header //DateTime? payDate = Util.GetValueOfDateTime(vdtpPayDate.SelectedDate); MPaySelection m_ps = new MPaySelection(ctx, 0, null); m_ps.SetName(Msg.GetMsg(ctx, "VPaySelect") + " - " + paymentRule + " - " + payDate.Value.Date); m_ps.SetPayDate(payDate); m_ps.SetC_BankAccount_ID(C_BankAccount_ID); m_ps.SetIsApproved(true); if (!m_ps.Save()) { //log.SaveError("SaveError", Msg.Translate(Envs.GetCtx(), "C_PaySelection_ID")); m_ps = null; return(""); } _C_PaySelection_ID = m_ps.GetC_PaySelection_ID(); string name = m_ps.GetName(); //string sqlTableID = "select ad_table_id from ad_table where tablename = 'C_PaySelection'"; //int AD_Table_ID = Util.GetValueOfInt(DB.ExecuteScalar(sqlTableID, null, null)); // log.Config(m_ps.ToString()); bool isSOTrx = false; if (X_C_Order.PAYMENTRULE_DirectDebit.Equals(paymentRule)) { isSOTrx = true; } int line = 0; Decimal?pAmt = Decimal.Zero; Decimal?oldpAmt = Decimal.Zero; for (int j = 0; j < Invoice_ID.Count; j++) { line = line + 10; if (Decimal.Add(pAmt.Value, Util.GetValueOfDecimal(payAmt[j])) > paymentAmt) { oldpAmt = Decimal.Subtract(paymentAmt.Value, pAmt.Value); } pAmt = Decimal.Add(pAmt.Value, Util.GetValueOfDecimal(payAmt[j])); // pAmt = Util.GetValueOfDecimal(payAmt[j]); MPaySelectionLine psl = new MPaySelectionLine(m_ps, line, paymentRule); //psl.SetInvoice(Util.GetValueOfInt(Invoice_ID[j]), isSOTrx, Util.GetValueOfDecimal(openAmt[j]), Util.GetValueOfDecimal(payAmt[j]), Decimal.Subtract(Util.GetValueOfDecimal(openAmt[j]), Util.GetValueOfDecimal(payAmt[j]))); if (paymentAmt >= pAmt) { psl.SetInvoice(Util.GetValueOfInt(Invoice_ID[j]), isSOTrx, Util.GetValueOfDecimal(openAmt[j]), Util.GetValueOfDecimal(payAmt[j]), Decimal.Zero); if (!psl.Save()) { // log.SaveError("PaymentSelectionLineNotSaved", "PaymentSelectionLineNotSaved"); return(""); } // log.Fine("C_Invoice_ID=" + Util.GetValueOfInt(Invoice_ID[j]) + ", PayAmt=" + Util.GetValueOfDecimal(payAmt[j])); } else { psl.SetInvoice(Util.GetValueOfInt(Invoice_ID[j]), isSOTrx, Util.GetValueOfDecimal(openAmt[j]), oldpAmt.Value, Decimal.Zero); if (!psl.Save()) { // log.SaveError("PaymentSelectionLineNotSaved", "PaymentSelectionLineNotSaved"); return(""); } // log.Fine("C_Invoice_ID=" + Util.GetValueOfInt(Invoice_ID[j]) + ", PayAmt=" + Util.GetValueOfDecimal(payAmt[j])); } } //if (false.Equals(((Message)sc).DialogResult)) //{ // Dispose(); // return; //} MPaySelection psel = new MPaySelection(ctx, _C_PaySelection_ID, null); if (psel.Get_ID() == 0) { throw new ArgumentException("Not found C_PaySelection_ID=" + _C_PaySelection_ID); } if (psel.IsProcessed()) { throw new ArgumentException("@Processed@"); } // MPaySelectionLine[] lines = psel.GetLines(false); List <MPaySelectionCheck> _list = new List <MPaySelectionCheck>(); for (int i = 0; i < lines.Length; i++) { MPaySelectionLine payLine = lines[i]; if (!payLine.IsActive() || payLine.IsProcessed()) { continue; } CreateCheck(ctx, payLine, _list); } // psel.SetProcessed(true); psel.Save(); string sql = "select ad_form_id from ad_form where classname = 'VAdvantage.Apps.AForms.VPayPrint'"; int AD_Form_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, null)); //return "@C_PaySelectionCheck_ID@ - #" + _list.Count; //SetBusy(false); //Dispose(); //FormFrame ff = new FormFrame(); //ff.OpenForm(AD_Form_ID); return(""); } // generatePaySelect
/// <summary> /// Sets the FromPort property /// </summary> /// <param name="fromPort">FromPort property</param> /// <returns>this instance</returns> public AuthorizeSecurityGroupIngressRequest WithFromPort(Decimal fromPort) { this.fromPortField = fromPort; return this; }
public dynamic AsJsDecimal(Decimal?d) { return(d != null?d.ToString() : null); }
/// <summary> /// Sets the capacity property /// </summary> /// <param name="capacity">capacity property</param> /// <returns>this instance</returns> public ActivateLicense Withcapacity(Decimal capacity) { this.capacityField = capacity; return(this); }
public Listado_NutrientesPorAlimentosEntityInfo(int oEncuestaNro, string oHistoriaClinica, DateTime?oFecha, string oSexo, short?oEdad, Decimal?oPeso, Decimal?oTalla, Decimal?oIMC, string oTipoDeDieta, string oAlimento, Decimal?oCantidadAlimento, string oNutriente, Decimal?oCantidadNutriente, Guid oUserId) { this.EncuestaNro = oEncuestaNro; this.HistoriaClinica = oHistoriaClinica; this.Fecha = oFecha; this.Sexo = oSexo; this.Edad = oEdad; this.Peso = oPeso; this.Talla = oTalla; this.IMC = oIMC; this.TipoDeDieta = oTipoDeDieta; this.Alimento = oAlimento; this.CantidadAlimento = oCantidadAlimento; this.Nutriente = oNutriente; this.CantidadNutriente = oCantidadNutriente; this.UserId = oUserId; }
/// <summary> /// Sets the VisibilityTimeout property /// </summary> /// <param name="visibilityTimeout">The duration (in seconds) that the received messages are hidden from subsequent retrieve requests after being retrieved /// by a ReceiveMessage request.</param> /// <returns>this instance</returns> public ReceiveMessageRequest WithVisibilityTimeout(Decimal visibilityTimeout) { this.visibilityTimeoutField = visibilityTimeout; return this; }
/// <summary> /// Sets the Count property /// </summary> /// <param name="count">Count property</param> /// <returns>this instance</returns> public ManageReportScheduleResult WithCount(Decimal count) { this.countField = count; return(this); }
public DescribeReservedInstancesOfferingsRequest WithMinDuration(Decimal minDuration) { this.minDurationField = minDuration; return this; }
/// <summary> /// Sets the Size property /// </summary> /// <param name="size">Size of the disk image.</param> /// <returns>this instance</returns> public DiskImageDescriptionType WithSize(Decimal size) { this.sizeField = size; return(this); }