I'm building a webapp in which are inputboxes with a date. How can I bind the data to my background code?
I tried just doing it directly but i guess an inputbox can only handle strings so a made a convert to string method and so on.
<div>
<label>start date: </label>
<input [(ngModel)]="item.stringStartDate" placeholder="start date" type="date">
</div>
void set startDate(DateTime startDate)
{
_startDate = startDate;
}
void set stringStartDate(String startDate)
{
this.startDate = parseDate(startDate);
}
static DateTime parseDate(String formattedString)
{
final RegExp r = new RegExp(
r'^(\d\d)-?(\d\d)-?([+-]?\d{4,6})');
Match match = r.firstMatch(formattedString);
if (match != null)
{
int years = int.parse(match[3]);
int month = int.parse(match[2]);
int day = int.parse(match[1]);
return new DateTime(years, month, day);
}
else
{
throw new FormatException("Invalid date format", formattedString);
}
}
static String dateToString(DateTime date){
if (date == null)
return null;
String ret = "${date.year}/";
if (date.month < 10)
ret+="0";
ret+="${date.month}/";
if (date.day < 10)
ret += "0";
ret+="${date.day}";
return ret;
}
it should be separated by - instead of /
you can use toIso8601String and substring
DateTime _date = new DateTime.now();
String get date => _date.toIso8601String().substring(0, 10);
void set date(value) {
if (value is DateTime) {
_date = value;
} else if (value is String) {
_date = DateTime.parse(value);
}
}
Related
Or Condition Query Example
SELECT ID, NAME, CREATE_DATE, UPDATE_DATE
FROM USER
WHERE ( CREATE_DATE > SYSDATE-1 OR UPDATE_DATE > SYSDATE -1)
How to assert OR Condition Query with junit?
// this test is fail : createDate is "2022-07-28" || updateDate is null
String oneDaysAgo = "2022-07-27";
List<UserInfo> list = jpaRepository.findAllByCreateDateGreaterThanOrUpdateDateGreaterThan(oneDaysAgo,oneDaysAgo);
for (UserInfo vo : list) {
assertThat(vo.getCreatedDate(), is(greaterThan(oneDaysAgo)));
assertThat(vo.getUpdateDate(), is(greaterThan(oneDaysAgo)));
log.info(vo.toString());
}
Expect assert
( createDate > oneDaysAgo ) or ( updateDate > oneDaysAgo )
OneDaysAgo = "2022-07-27";
Create Date
Update Date
Expect Result
Actual Result
null or lessThan or equal
null or lessThan or equal
False
False
"2022-07-28"
null or lessThan or equal
True
False
null or lessThan or equal
"2022-07-28"
True
False
"2022-07-28"
"2022-07-28"
True
True
thx for comment #pL4Gu33
Solve problem with Add Helper Method
#Test
void test_orCondition() {
String oneDaysAgo = "2022-07-27";
List<UserVo> list = getUserVoList(oneDaysAgo);
assertThat(list.size(), is(greaterThan(0)));
for (UserVo vo : list) {
assertThat(
getOrConditionBoolean(LocalDate.parse(oneDaysAgo)
, vo.getCreateDate(), vo.getUpdateDate()), is(true));
}
}
private Boolean getOrConditionBoolean(LocalDate baseDate, LocalDate arg1, LocalDate arg2) {
if (checkDate(arg1, baseDate)) {
return true;
}
if (checkDate(arg2, baseDate)) {
return true;
}
return false;
}
private boolean checkDate(LocalDate argDate, LocalDate baseDate) {
if (argDate == null) {
return false;
}
if (baseDate.isEqual(argDate) || baseDate.isBefore(argDate)) {
return true;
}
return false;
}
I write some code for getting current date and compare it with a future date for application limitation. I don't know why this function doesn't work.
getYYMMDD();
function getYYMMDD(): String {
var dateObj: Date = new Date();
var year: String = String(dateObj.getFullYear());
var month: String = String(dateObj.getMonth() + 1);
if (month.length == 1) {
month = "0" + month;
}
var date: String = String(dateObj.getDate());
if (date.length == 1) {
date = "0" + date;
}
return year.substring(0, 4) + month + date;
trace(year + ":" + month + ":" + date);
if (int(year) > 2017 && int(month) > 5 && int(date) > 31) {
trace("SYSTEM TIME IS OFF.");
} else {
trace("SYSTEM TIME IS ON.");
}
}
(1) Since your function returns data of String type...
function getYYMMDD(): String
Make sure that returned data is also being received by a String... ie: someString = getYYMMDD(); means someString now has returned value from function.
(2) You return (exit the function) too soon...
Put return as last command to allow all other code inside your function to run.
(3) You should consider returning a Boolean type (true/false)...
var can_Start : Boolean = false; //# assume false before checking
can_Start = getYYMMDD(); //# use function to update status to true/false
if (can_Start == true) { run_Program(); }
else { trace("Sorry time has expired"); }
function getYYMMDD(): Boolean
{
var dateObj: Date = new Date();
var year: String = String(dateObj.getFullYear());
var month: String = String(dateObj.getMonth() + 1);
if (month.length == 1) { month = "0" + month; }
var date: String = String(dateObj.getDate());
if (date.length == 1) { date = "0" + date; }
trace(year + ":" + month + ":" + date);
if(int(year) == 2017)
{
if(int(month) >= 05 && int(date) > 31)
{ trace("SYSTEM TIME IS OFF."); can_Start = false; } //# can_Start == false;
else { trace("SYSTEM TIME IS ON."); can_Start = true; } //# can_Start == true;
}
return can_Start;
}
We are using mySQL with WCF Restful service, we want to fetch our database content PACKAGEID wise...as mentioned below:
PackageId=2
{
StartRange = 1;
EndRange = 100;
IsDiscountAndChargeInPer = 1;
Discount =10;
ServiceCharge = 20;![enter image description here][1]
},
{
StartRange =101;
EndRange = 500;
IsDiscountAndChargeInPer = 1;
Discount =10;
ServiceCharge = 20;
}
PackageId=3
{
StartRange = 1;
EndRange = 100;
IsDiscountAndChargeInPer = 1;
Discount =10;
ServiceCharge = 20;
}
We have created a Result class to return result from out wcf service...for above service we have result class defined as below
[DataContract]
public class PackagePointRangeConfigurationResult : ResultBase
{
[DataMember]
public List<PackagePointRangeResult> Result;
}
public class PackagePointRangeResult
{
public int PackageId { get; set; }
public List<PointPlanInfo> Result { get; set; }
}
For fetching record we use following linq query:
var result = (from planinfo in db.mst_pointplan_info
join entityType in db.mst_entity_type
on planinfo.entityId equals entityType.id
where planinfo.entityId == entityId
&& planinfo.is_deleted != true
&& planinfo.system_id == systemId
&& entityType.enity_enum_id == entityId
group planinfo by planinfo.package_id into gplan
select new PackagePointRangeConfigurationResult
{
Result = (from planinfo in gplan
select new PackagePointRangeResult
{
PackageId = planinfo.package_id,
PointPlanInfo = (from pointPlanInfo in gplan
select new PointPlanInfo
{
StartRange = planinfo.start_range,
EndRange = planinfo.end_range,
IsDiscountAndChargeInPer = planinfo.is_discount_and_charge_in_per,
Discount = planinfo.discount,
ServiceCharge = planinfo.servicecharge,
AtonMerchantShare =planinfo.aton_merchant_share,
CommunityShare = planinfo.community_share
}).ToList()
}).ToList()
}).FirstOrDefault();
But it gives me below error:
LINQ to Entities does not recognize the method 'System.Collections.Generic.List1[PointPlanInfo] ToList[PointPlanInfo](System.Collections.Generic.IEnumerable1[PointPlanInfo])' method, and this method cannot be translated into a store expression.
Can this be refactored into one LINQ statement? I feel like it can be but can't wrap my head around it. The mishmash of extension methods and LINQ just looks ugly to me.
(db is a DataContext.)
void AddToSeries(Series series, DateTime date)
{
foreach (var date in db.Ad.Select(ad => ad.DateTime.Date).Distinct())
{
var phraseCount = (from pc in db.PhraseCount
where pc.DateTime.Date == date
select pc.Count).SingleOrDefault();
var adCount = db.Ad.Where(ad => ad.DateTime.Date == date).Count();
series.Add(new KeyValuePair<DateTime, double>(date, adCount));
}
}
First refactor to consistent style.
void AddToSeries(Series series, DateTime date)
{
var dates = db.Ad
.Select(ad => ad.DateTime.Date)
.Distinct();
foreach (DateTime date in dates)
{
var phraseCount = db.PhraseCount
.Where(pc => pc.DateTime.Date == date)
.Select(pc => pc.Count)
.SingleOrDefault();
var adCount = db.Ad
.Where(ad => ad.DateTime.Date == date)
.Count();
series.Add(new KeyValuePair<DateTime, double>(date, adCount));
}
}
Aha:
phraseCount is not used
key is a date, value is a count
multiple database trips is no fun
date parameter for this method is blocked by the foreach variable
Now we can refactor:
void AddToSeries(Series series, DateTime date)
{
var pairs = db.Ad
.GroupBy(ad => ad.DateTime.Date)
.Select(g => new {key = g.Key, theCount = g.Count()});
foreach (var x in pairs)
{
series.Add(new KeyValuePair<DateTime, double>(x.key, x.theCount));
}
}
I am able to do this query just fine with the test repository which is In Memory
when I move to the sqlRepository I get this error
Unsupported overload used for query operator 'Intersect'.
I assume it is because sending the query to sql is too complicated for Linq to Sql to do when it is not dealing with the Model.Model.Talent Type. Is there some way around doing a search like this with Intersect?
thanks
public class TalentService : ITalentService
{
ITalentRepository _repository = null;
private IQueryable<Talent> BasicSearch(string searchExpression)
{
IQueryable<Talent> t;
string[] sa = searchExpression.Trim().ToLower().Replace(" ", " ").Split(' ');
t = _repository.GetTalents();
foreach (string s in sa)
{
t = t.Intersect(AddBasicSearch(s), new TalentComparer());
}
return t;
}
private IQueryable<Talent> AddBasicSearch(string s)
{
IQueryable<Talent> t2 = _repository.GetTalents()
.Where(tal => tal.EyeColor.ToString().ToLower().Contains(s)
|| tal.FirstName.ToLower().Contains(s)
|| tal.LastName.ToLower().Contains(s)
|| tal.LanguagesString.ToLower().Contains(s)
);
return t2;
}
}
public class SqlTalentRepository:ITalentRepository
{
public IQueryable<Model.Model.Talent> GetTalents()
{
var tal = from t in _db.Talents
let tLanguage = GetTalentLanguages(t.TalentID)
where t.Active == true
select new Model.Model.Talent
{
Id = t.TalentID,
FirstName = t.FirstName,
LastName = t.LastName,
TalentLanguages = new LazyList<Model.Model.TalentLanguage>(tLanguage),
LanguagesString = t.TalentLanguages.ToLanguageNameString(_LanguageRepository.GetLanguages())
};
return tal ;
}
public IQueryable<Model.Model.TalentLanguage> GetTalentLanguages(int iTalentId)
{
var q = from y in this.talentLanguageList
let Languages = _LanguageRepository.GetLanguages()
where y.TalentId == iTalentId
select new Model.Model.TalentLanguage
{
TalentLanguageId = y.TalentLanguageId,
TalentId = y.TalentId,
LanguageId = y.LanguageId,
Language = Languages.Where(x => x.LanguageId == y.LanguageId).SingleOrDefault()
};
return q.AsQueryable<Model.Model.TalentLanguage>();
}
}
public static class TalentExtensions
{
public static string ToLanguageNameString(this IEnumerable<TalentLanguage> source
, IEnumerable<Model.Model.Language> allLanguages)
{
StringBuilder sb = new StringBuilder();
const string del = ", ";
foreach (TalentLanguage te in source)
{
sb.AppendFormat("{0}{1}", allLanguages
.Where(x => x.LanguageId == te.LanguageID).SingleOrDefault().LanguageName, del);
}
string sReturn = sb.ToString();
if (sReturn.EndsWith(del))
sReturn = sReturn.Substring(0, sReturn.Length - del.Length);
return sReturn;
}
}
public class TestTalentRepository : ITalentRepository
{
IList<Talent> talentList;
public TestTalentRepository(ILanguageRepository _LanguageRepo )
{
this._LanguageRepository = _LanguageRepo;
talentList = new List<Talent>();
talentLanguageList = new List<TalentLanguage>();
for (int i = 0; i < 55; i++)
{
var t = new Talent();
t.Id = i;
t.FirstName = (i % 3 == 0) ? "Ryan" : "Joe";
t.LastName = (i % 2 == 0) ? "Simpson" : "Zimmerman";
AddLanguagesToTestTalent(i, t);
talentList.Add(t);
}
}
private void AddLanguagesToTestTalent(int i, Talent t)
{
IList<Language> Languages = _LanguageRepository.GetLanguages().ToList<Language>();
Random rLanguages = new Random();
int numLanguages = rLanguages.Next(Languages.Count - 1) + 1;
t.TalentLanguages = new LazyList<TalentLanguage>();
for (int j = 0; j < numLanguages; j++)
{
var x = new TalentLanguage();
x.TalentLanguageId = j;
x.TalentId = i;
Random random2 = new Random();
int rand = random2.Next(Languages.Count);
var y = Languages.ElementAtOrDefault(rand);
Languages.RemoveAt(rand);
x.Language = y;
x.LanguageId = y.LanguageId;
t.TalentLanguages.Add(x);
}
}
public IQueryable<Talent> GetTalents()
{
var ts = from t in this.talentList
let tLanguage = GetTalentLanguages(t.Id)
where t.Active == true
select new Model.Model.Talent
{
Id = t.Id,
FirstName = t.FirstName,
LastName = t.LastName,
TalentLanguages = new LazyList<Model.Model.TalentLanguage>(tLanguage),
LanguagesString = t.TalentLanguages.ToLanguageNameString(_LanguageRepository.GetLanguages()),
City = t.City,
};
return ts.AsQueryable<Model.Model.Talent>();
}
public IQueryable<Model.Model.TalentLanguage> GetTalentLanguages(int iTalentId)
{
var q = from y in this.talentLanguageList
let Languages = _LanguageRepository.GetLanguages()
where y.TalentId == iTalentId
select new Model.Model.TalentLanguage
{
TalentLanguageId = y.TalentLanguageId,
TalentId = y.TalentId,
LanguageId = y.LanguageId,
Language = Languages.Where(x => x.LanguageId == y.LanguageId).SingleOrDefault()
};
return q.AsQueryable<Model.Model.TalentLanguage>();
}
}
If you're trying to find entries which match all of those criteria, you just need multiple where clauses:
private static readonly char[] SplitDelimiters = " ".ToCharArray();
private IQueryable<Talent> BasicSearch(string search)
{
// Just replacing " " with " " wouldn't help with "a b"
string[] terms = search.Trim()
.ToLower()
.Split(SplitDelimiters,
StringSplitOptions.RemoveEmptyEntries);
IQueryable<Talent> query = _repository.GetTalents();
foreach (string searchTerm in terms)
{
query = AddBasicSearch(query, searchTerm);
}
return query;
}
private IQueryable<Talent> AddBasicSearch(IQueryable<Talent> query, string s)
{
return query.Where(tal =>
tal.EyeColor.ToString().ToLower().Contains(s)
|| tal.FirstName.ToLower().Contains(s)
|| tal.LastName.ToLower().Contains(s)
|| tal.LanguagesString.ToLower().Contains(s)
);
}