asp.net date time is not result same - asp.net

this is the property I have :
[DataType(DataType.Time)]
public TimeSpan StartingTime { get; set; }
now in controller I will check if the starting time is less then now
var now = DateTime.Now.TimeOfDay;
return View(db.SchoolTime.ToList().Where(a => a.StartingTime < now );
here even the starting-time is less then now in database but not returning list to vew
I think it's because Starting-time is lik(09:00:00) but the now is like 09:10:00:12312312
please help thanks in advance

It is not because of the '<' condition.
Try changing the code to:
return View(db.SchoolTime.Where(a => a.StartingTime < now).ToList());
Where condition doesn't get applied unless you enumerate over the collection.
ToList() will help you do that.
Else it will execute once the collection is enumerated in the View.

Use the following code
DateTime parsedDate;
string pattern = ;
DateTime.TryParseExact(StartingTime, "MM-dd-yy", null, DateTimeStyles.None, out parsedDate);
parsedDate.TimeOfDay;// out put in your format MM:HH:SS
Inorder to make the above code to work you need to add using System.Globalization; namespace.
Update 1 :
As per your code
var now = DateTime.Now.TimeOfDay;
returns 00:00:00 every time because it should be assigned when you are creating the DateTime object itself.
So use this
var now = DateTime.Now.ToString("hh:mm:ss")
return View(db.SchoolTime.ToList().Where(a => a.StartingTime < now );

Related

$date not picking up current date - Sitecore

I am having an issue while setting default value for datetime field in sitecore standard values.
I know that $date takes the current date. If I specify $date in standard values for a date time field , it always takes the date as "1/1/0001".
How do I fix this ?
It is possible to enter tokens in the fields on the standard values, and then these will be replaced with other values, but only when a new item which use that template is created. It will not set date for the existing items which use this template.
$date is one of the token and it's replates with the system date (yyyyMMdd).
There is a blog post written by John West which explains how to Expand Standard Values Tokens in Existing Items with the Sitecore ASP.NET CMS.
EDIT:
Here is the code which is a part of MasterVariablesReplacer class which is used to replace $date token:
text = this.ReplaceWithDefault(text, "$date", (Func<string>) (() => DateUtil.IsoNowDate), context);
It is called from the ReplaceVariables processor, which is a part of expandInitialFieldValue pipeline (see /sitecore/admin/showconfig.aspx for all the expandInitialFieldValue processors).
You can try to add your own processor to this pipeline and see why the $date is not replaced properly:
public class ReplaceVariables : ExpandInitialFieldValueProcessor
{
public override void Process(ExpandInitialFieldValueArgs args)
{
Assert.ArgumentNotNull((object) args, "args");
MasterVariablesReplacer variablesReplacer = Factory.GetMasterVariablesReplacer();
string text = args.SourceField.Value;
if (variablesReplacer == null)
args.Result = text;
else
args.Result = variablesReplacer.Replace(text, args.TargetItem);
}
}

Invalid date format causing ModelState to be invalid in controller

I am getting an invalid ModelState when data is returned from a View using an ajax call but only for edits. I am passing a datetime value from a SQL record to the view. The date shows up just fine in a Kendo UI DateTime picker. If I make a new selection from the datetime picker, I don't get the exception, it's only if I don't make any changes do I get the invalid error. Here is what the MVC controller is showing:
The value '/Date(1387443600000)/' is not valid for RequiredByDate."
What am I missing here? First time I have ever had an issue with a datetime field like this.
EDIT: Found out the date was being formatted in the view once the controller passed it in. Here is what I had to do before using it on the page and eventually sending it back to the controller (code is verbose for debugging purposes):
var myModel = model;
var jsonDate = myModel.Header.RequiredByDate; // "/Date(1387443600000)/"
var value = new Date(parseInt(jsonDate.substr(6)));
var ret = value.getMonth() + 1 + "/" + value.getDate() + "/" + value.getFullYear();
//ret is now in normal date format "12-13-2013"
After posting an edit above I found what I think is an even better solution to the problem. Here is a function that converts the string to an actual date object:
function dateFromStringWithTime(str) {
var match;
if (!(match = str.match(/\d+/))) {
return false;
}
var date = new Date();
date.setTime(match[0] - 0);
return date;
}

Int does not contain a constructor that takes one argument

In my .NET application, I recently had to make some changes in the database structure and upon changing code I have run into this error message.
The line used to say _categoryID = new Guid(Request.QueryString["CategoryID"].ToString()); which worked fine to retrieve a list of products based on the categoryid, but now I had to add a top level category called Market, and I used int instead of Guid in the database, because to me using Guid is a pain.
But now when I change the line I mentioned to _marketID = new Int32(Request.QueryString["MarketID"].ToString()); I get the error.
Here is the chunk of code :
#region Variables
Int32 _marketID;
#endregion
if ( Request.QueryString [ "MarketID" ] != null )
{
_marketID = new Int32(Request.QueryString["MarketID"].ToString());
ViewState["MarketID"] = _marketID;
BindDataToUI ( );
CreateFilterInSession ( );
}
Try this instead :
_marketID = Convert.ToInt32(Request.QueryString["MarketID"]);
note : no need to use ToString() for querystring values, they're all natively strings anyway.

Cannot implicitly convert type 'System.Linq.IQueryable to System.Data.Entity.DbSet<>

I receive the following error when I try to run my code. I haven't managed to solve it yet, please Help:
edit: Marked with * where it fails.
>
public IQueryable<Video> GetVideos([QueryString("id")] int? categorieId)
{
var _db = new TeleviziuneAcademicaAspSilverlight.Models.VideoContext();
IQueryable<Video> query = *_db.Videos;*
if (categorieId.HasValue && categorieId > 0)
{
query = query.Where(v => v.CategorieID == categorieId);
}
return query;
Change
IQueryable<Video> query =
to
IQueryable<Appname.Models.Video> query =
The reason for your error is that you have the type Video defined twice and because of using a short type name you accidentally reference not the one Video you should.
Also change it in the method's return value
public IQueryable<Appname.Models.Video> GetVideos( ... )
You seem to have two classes called Video. If you need both, you'll need to project from one to the other before your return statement:
return query.Select(dbVideo => new Appname.Video()
{
Prop1 = dbVideo.Prop1,
Prop2 = dbVideo.Prop2,
// etc.
});
Though you'll probably need to change the return type to an IEnumerable<> if you do that.
If you can just work with Appname.Models.Video, change IQueryable<Video> to IQueryable<Appname.Models.Video> in the method signature and the method body.

how to use multiple order by in LINQ?

I want to use multiple order by in my query, and i am using LINQ.i am new to LINQ, i have tried the examples given on stackoverflow. but i dont know why these are not working for me , i am sure i am wrong some where. below is my situation.
I got a project in which created using LINQ. I have little task to set order of column. Actually what is my task there is a column created date by which its ordering now. Now i want to use Createddate as well a sortOrder column for ordering.Below is code used for it:
Code in page load method
ViewState["SortDirection"] = "desc";
ViewState["SortColumn"] = "createddate";
BindAllTopics(ViewState["SortDirection"].ToString(), ViewState["SortColumn"].ToString());
And my BindAllTopic Method is as bellow:
protected void BindAllTopics(string SortType, string SortColumn)
{
var LstTopics = (from topic in Dbobj.T_topic select topic).ToList();
if (LstTopics.Count() > 0)
{
if (SortType == "ASC")
{
LstTopics = LstTopics.OrderBy(q => q.Name).ToList();
}
else
{
LstTopics = LstTopics.OrderByDescending(q => q.Name).ThenBy(q => q.SortOrder).ToList();
}
GrdTopics.DataSource = LstTopics.ToList();
GrdTopics.PageSize = 25;
GrdTopics.DataBind();
}
else
{
GrdTopics.DataSource = null;
GrdTopics.DataBind();
lblMsg.DisplayMessage(StatusMessages.InfoMessage, "No Topics Found.");
}
}
I want to sort it firstly by sortorder which is of int type and then by Createddate.
Please help me..
you can add one more ThenBy() in trail
LstTopics.OrderByDescending(q => q.Name).ThenBy(q => q.SortOrder).ThenBy(m=>m.date)
If you do not want to use Dynamic Linq the following see Marc Gravell's answer below
stackoverflow:Dynamic Linq OrderBy
After correction you can achieve this by Dynamic Linq
LstTopics = LstTopics.OrderBy(SortColumn + " " + SortType);)

Resources