I have class called LaborRate as below. It has Id, start date, end date column.
user can see existing records from database table in a grid and he can edit them and/or he can add new records to the grid.
while saving existing modified records or new records I need to do below validation.
If the Start Date or End Date falls within Start Date & End Date on other record for then I need to through some error. I cannot depend on Id column because for newly added record the id value is -1. What is the best method to do this comparison.
public class LaborRate
{
private int _id;
private decimal _laborRate;
private DateTime _StartDate;
private DateTime _EndDate;
public int Id
{ get { return _id; } set { _id = value; } }
public Decimal Rate
{ get { return _laborRate; } set { _laborRate = value; } }
public DateTime StartDate
{ get { return _StartDate; } set { _StartDate = value; } }
public DateTime EndDate
{ get { return _EndDate; } set { _EndDate = value; } }
}
Related
Hi all I am trying to set max date below
But Modified always returns a null value instant of return max value between ModifiedDate and OfferProductsModified.
public DateTime? Modified { get { return _FinalDate; } set { _FinalDate = value; } }
/// <summary>
/// this are not in offer view model
/// </summary>
[JsonIgnore] public DateTime? _FinalDate;
[JsonIgnore]
public DateTime? FinalDate
{
get
{
if (ModifiedDate < OfferProductsModified)
{
return OfferProductsModified;
}
else
{
return ModifiedDate;
}
}
set
{
if (ModifiedDate < OfferProductsModified)
{
_FinalDate = OfferProductsModified;
}
else
{
//DEFAULT Value.
_FinalDate = value;
}
}
}
How can I return the max value between ModifiedDate and OfferProductsModified ?
Note :- Both ModifiedDate and OfferProductsModified having values (confirm by debugging )
Hello i am doing a school assignment. Everything in my program works fine but the teacher wants me to add a parameter of type DateTime in one of my constructors. I am a bit confused since i think that i already have a parameter of this type:
using System;
using System.Windows.Forms;
namespace Assignment4
{
class Task
{
private string time = string.Empty;
private string date = string.Empty;
private DateTime dateTime = new DateTime();
private string description = string.Empty;
private object priorityType;
private string priority;
public string Description
{
get
{
return description;
}
set
{
description = value;
}
}
public DateTime DateTime
{
set
{
dateTime = value;
time = dateTime.TimeOfDay.ToString();
date = dateTime.Date.ToString("d");
}
}
public string Time
{
get
{
return time;
}
}
public string Date
{
get
{
return date;
}
}
public object PriorityType
{
set
{
priorityType = value;
priority = priorityType.ToString();
}
}
public string Priority
{
get
{
return priority;
}
}
}
}
Is dateTime = value not a parameter of type DateTime?
The constructor of a C# class is a method without a return type and with the same name of the class. The constructor is called everytime you create an instance of the class (new YourClass).
You can have many constructors with different kind of parameters passed to these methods, even one without parameters (it is the default constructor).
The correct constructor is identified by the parameters that you pass when you create the class....
public class Person
{
private string _name;
private DateTime _dob;
public Person(string name, DateTime dateOfBirth)
{
_name = name;
_dob = dateOfBirth;
}
}
..... somewhere in your code .....
Person myself = new Person("Steve", new DateTime(1970,1,1));
Since DateTime is an immutable struct, you can only set its values from the constructor. That means you need to do something like this:
dateTime = new DateTime(2016, 05, 03);
In your case, you can just use this, since you set it somewhere else:
private DateTime dateTime;
(Also, your property needs a get too, you just have a set now)
I have a (Devexpress) Datagrid-Control, which contains 3 columns of information. The names of the columns are generated automatically, each line describes one object of those:
private string fName;
private bool fCheck;
private DateTime fDate;
public bool checked
{
get { return this.fCheck; }
set { this.fCheck = value; }
}
public string fileName
{
get { return this.fName; }
set { this.fName = value; }
}
public DateTime createDate
{
get { return this.fDate; }
set { this.fDate = value; }
}
These Objects are saved in a List<> (dataSource):
gridFiles.DataSource = dataSource;
gridFiles.MainView.PopulateColumns();
Now, the names of the Columns are "checked","fileName" & "createDate". How can I change those?
Veeramani's answer does the job perfectly but just thought I should share an alternative solution with take less coding. You can also achieve this by adding a DisplayName attribute on each property. i.e:
My Class:
public class GridColumns
{
private string fName;
private bool fCheck;
private DateTime fDate;
[DisplayName("Checked Option")]
public bool Checked
{
get { return fCheck; }
set { this.fCheck = value; }
}
[DisplayName("File Name")]
public string fileName
{
get { return this.fName; }
set { this.fName = value; }
}
[DisplayName("Date Created")]
public DateTime createDate
{
get { return this.fDate; }
set { this.fDate = value; }
}
}
Then use it:
List<GridColumns> dataSourc = new List<GridColumns>();
dataGridView1.DataSource = dataSourc;
Using Gridview, we can rename the column name at Form_load() event...
gridView1.Columns["fileName"].Caption = "Your custom name";
The code is as follows:
public class MyEvent
{
public string EventTitle { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public bool IsInsideSameMonth
{
get
{
// No code is bug-free, so we assume this situation may occur somehow.
if (StartDate > EndDate)
{
// And when this occurs, we want to halt the application by throwing exception to prevent further potential damage.
throw new MyEventException("Start date is not supposed to be greater than end date.");
}
return (StartDate.Year == EndDate.Year && StartDate.Month == EndDate.Month);
}
}
public void Validate()
{
if (StartDate > EndDate)
{
throw new MyEventException("Start date is not supposed to be greater than end date.");
}
if (String.IsNullOrWhiteSpace(EventTitle))
{
throw new MyEventException("Title cannot be empty.");
}
}
}
public class MyEventException : Exception
{
public MyEventException(string message)
: base(message)
{
}
}
It might seem redundant that I perform StartDate > EndDate validation inside the IsInsideSameMonth property. I just prefer being on the safe side. But it feels as if I am doing something wrong but I cannot describe it.
Is this a good practice? Please share your valuable experience and thoughts.
You shouldn't use Auto-implemented property. You should instead use a backing private field and then check while setting the property like:
private DateTime _StartDate;
public DateTime StartDate
{
get { return _StartDate; }
set
{
if (value > _EndDate)
{
throw new MyEventException("Start date is not supposed to be greater than end date.");
}
else
{
_StartDate = value;
}
}
}
private DateTime _EndDate;
public DateTime EndDate
{
get { return _EndDate; }
set { _EndDate = value; }
}
Your current code would allow the user to set StartDate to any value and you will only realize if you check your property IsInsideSameMonth.
For the EventTitle you could declare a backing field and make the validation inside the setter of the property. Something like this:
string eventTitle;
public string EventTitle
{
get
{
return eventTitle;
}
set
{
if(!IsNullOrWhiteSpace(value))
eventTitle = value;
else
throw new MyEventException("Title cannot be empty.");
}
}
As for the DateTime objects you could follow the same path:
private DateTime startDate;
public DateTime StartDate
{
get
{
return startDate;
}
set
{
if (value > EndDate)
{
throw new MyEventException("Start date is not supposed to be greater than end date.");
}
else
{
startDate = value;
}
}
}
private DateTime endDate;
public DateTime EndDate
{
get
{
return endDate;
}
set
{
endDate = value;
}
}
It's better to control values when the properties are set, so you need to convert your automatic properties to old style (properties with private field) and put your checking there.
Here is the Microsoft property design guide.
Here is an example checking the values when setting, throwing if invalid. I've also defined functions for validation to reduce redundant code (in case you want to change your validation or error messaging- it will be in one location).
public class MyEvent
{
public bool IsInsideSameMonth
{
get
{
return (StartDate.Year == EndDate.Year && StartDate.Month == EndDate.Month);
}
}
private string _EventTile;
public string EventTitle
{
get { return _EventTile; }
set
{
ValidateTitle(value); // this will throw if invalid and leave the value of _EventTitle unchanged
_EventTile = value;
}
}
private DateTime _StartDate = DateTime.MinValue;;
public DateTime StartDate
{
get { return _StartDate; }
set
{
ValidateDates(value, EndDate); // this will throw if invalid and leave the value of _StartDate unchanged
_StartDate = value;
}
}
private DateTime _EndDate = DateTime.MaxValue;;
public DateTime EndDate
{
get { return _EndDate; }
set
{
ValidateDates(StartDate, value); // this will throw if invalid and leave the value of _EndDate unchanged
_EndDate = value;
}
}
private void ValidateDates(DateTime start, DateTime end)
{
if (start > end)
{
throw new MyEventException("Start date is not supposed to be greater than end date.");
}
}
private void ValidateTitle(string title)
{
if (String.IsNullOrWhiteSpace(title))
{
throw new MyEventException("Title cannot be empty.");
}
}
public void Validate()
{
ValidateDates(StartDate, EndDate);
ValidateTitle(EventTitle);
}
}
public class MyEventException : Exception
{
public MyEventException(string message)
: base(message)
{
}
}
I'm very new to C#/LINQ/WP7 development and am struggling to format data being returned from my LINQ query.
I have the following LINQ c# structure:
var boughtItemsInDB = from DBControl.MoneySpent bought in BoughtItemDB.BoughtItems
select bought;
BoughtItems = new ObservableCollection<DBControl.MoneySpent>(boughtItemsInDB);
The definition for MoneySpent is below;
[Table(Name = "MoneySpent")]
public class MoneySpent : INotifyPropertyChanged, INotifyPropertyChanging
{
// Define ID: private field, public property and database column.
private int _itemId;
[Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
public int ItemId
{
get
{
return _itemId;
}
set
{
if (_itemId != value)
{
NotifyPropertyChanging("ItemId");
_itemId = value;
NotifyPropertyChanged("ItemId");
}
}
}
// Define item budget: private field, public property and database column.
private int _itemBudget;
[Column]
public int ItemBudget
{
get
{
return _itemBudget;
}
set
{
if (_itemBudget != value)
{
NotifyPropertyChanging("ItemBudget");
_itemBudget = value;
NotifyPropertyChanged("ItemBudget");
}
}
}
// Define item category: private field, public property and database column.
private string _itemCategory;
[Column]
public string ItemCategory
{
get
{
return _itemCategory;
}
set
{
if (_itemCategory != value)
{
NotifyPropertyChanging("ItemCategory");
_itemCategory = value;
NotifyPropertyChanged("ItemCategory");
}
}
}
// Define item description: private field, public property and database column.
private string _itemDescription;
[Column]
public string ItemDescription
{
get
{
return _itemDescription;
}
set
{
if (_itemDescription != value)
{
NotifyPropertyChanging("ItemDescription");
_itemDescription = value;
NotifyPropertyChanged("ItemDescription");
}
}
}
// Define item amount: private field, public property and database column.
private decimal _itemAmount;
[Column]
public decimal ItemAmount
{
get
{
return _itemAmount;
}
set
{
if (_itemAmount != value)
{
NotifyPropertyChanging("ItemAmount");
_itemAmount = value;
NotifyPropertyChanged("ItemAmount");
}
}
}
// Define item date: private field, public property and database column.
private DateTime _itemDateTime;
[Column]
public DateTime ItemDateTime
{
get
{
return _itemDateTime;
}
set
{
if (_itemDateTime != value)
{
NotifyPropertyChanging("ItemDateTime");
_itemDateTime = value;
NotifyPropertyChanged("ItemDateTime");
}
}
}
I need to format the data returned from the database, the following is stored in my DB:
ItemDateTime - DateTime, ItemDescription - String, ItemAmount - Decimal
I need to be able to to format the Date based on the current locale of the user, and format the decimal to 2 dp.
I am also not sure if I need to use IQueryable when I get the data results .
Any help would be much appreciated.
Thanks,
Mark
Since you don't provide enough detail - just a general idea
var boughtItemsInDB = from bought in BoughtItemDB.BoughtItems
select new { ItemDateTime = bought.ItemDateTime.ToString(), ItemDescription = bought.ItemDescription, ItemAmount = bought.ItemAmount.ToString("0,0.00") };
BUT formatting is better done in the control you use to display the data, not in the Linq query...
EDIT - after the addition frm OP:
From what I see the MoneySpent class is already prepared for "data binding"...
So formatting should be done in the displaying control... for some information see:
What is the WPF XAML Data Binding equivalent of String.Format?
http://www.codeproject.com/KB/WPF/binding_in_linq-sql.aspx
http://odetocode.com/code/740.aspx
http://www.codeguru.com/csharp/.net/wp7/article.php/c18933