I would like add an event to my calendar with graph API.
I use this endpoint https://graph.microsoft.com/v1.0/me/events
I create my class event to registrer my event
public class Event
{
public string subject { get; set; }
public Body body { get; set; }
public Start start { get; set; }
public End end { get; set; }
public Location location { get; set; }
public List<Attendee> attendees { get; set; }
}
I have issue to set correctly a starting date. My start object is like that
public class Start
{
public DateTime dateTime { get; set; }
public string timeZone { get; set; }
}
I try different method to set the value
lunch.start = new Start()
{
dateTime = DateTime.Today,
timeZone = "UTC" // Resource.DefaultTimeZone
};
lunch.start = new Start()
{
dateTime = DateTime.Today,
timeZone = "UTC+4" // Resource.DefaultTimeZone
};
lunch.start = new Start()
{
dateTime = DateTime.Today,
timeZone = "Pacific Standard Time" // Resource.DefaultTimeZone
};
But my meeting is still to the same time. How I could select the time zone to my meeting ?
Set it to UTC.
lunch.start = new Start()
{
dateTime = DateTime.ToUniversalTime().ToString()
// timeZone = "UTC" // This is supposed to be the friendly name like Pacific Standard Time. I think this is optional.
};
Related
I'm working on a mvc application where people can search for train routes. I made my database code-first with the entity framework but i cant seem to figure out how to ask some more complex queries.
I have a collection of routes which i use in my viewmodel. So the first step is asking which routes have a certain start and end station. Then i want to include the schedule where a certain day is set on true (and where the start and end date of that schedule match). This is linked to a collection of trips (i am using this table cause routes run multiple times on a day). From here i can find all the matching stations with the arrive and depart hours from the table routeHasStations.
So i was thinking something like:
public IEnumerable<Route> Search(DateTime date, int? departure, int? arrival)
{
var day = date.DayOfWeek.ToString();
return db.Routes.Where(r => r.DepartureStationID == departure && r.ArrivalStationID == arrival)
.Include(s => s.Train)
//using linq.dynamic here
.Include(r => r.Schedule.where(day + "==" + true)
.Include(sch => sch.trip.where(date > sch.DepartureTime)
.Include(route => route.RouteHaseStations)
.Include(st => st.Stations)
}
But this is offcourse not working. Here are my models:
public class Route
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int RouteID { get; set; }
public String RouteName { get; set; }
[ForeignKey("Train")]
public int TrainID { get; set; }
[ForeignKey("Station")]
public int DepartureStationID { get; set; }
[ForeignKey("Station")]
public int ArrivalStationID { get; set; }
public virtual ICollection<Schedule> Schedule { get; set; }
public virtual Train Train { get; set; }
public virtual Station DepartureStation { get; set; }
public virtual Station ArrivalStation { get; set; }
}
public class Station
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int StationID { get; set; }
[Display(Name = "Station")]
public String Name { get; set; }
public int Platforms { get; set; }
public float Latitude { get; set; }
public float Longitude { get; set; }
public virtual ICollection<RouteHasStation> RouteHasStation { get; set; }
}
public class Train
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int TrainID { get; set; }
public String Name { get; set; }
public virtual ICollection<Route> Route { get; set; }
}
public class Schedule
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ScheduleID { get; set; }
[ForeignKey("Route")]
public int RouteID { get; set; }
public Boolean Monday { get; set; }
public Boolean Tuesday { get; set; }
public Boolean Wednesday { get; set; }
public Boolean Thursday { get; set; }
public Boolean Friday { get; set; }
public Boolean Saturday { get; set; }
public Boolean Sunday { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public virtual ICollection<Trip> Trip { get; set; }
public virtual Route Route { get; set; }
}
public class Trip
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int TripID { get; set; }
[ForeignKey("Schedule")]
public int ScheduleID { get; set; }
public DateTime DepartureTime { get; set; }
public virtual ICollection<RouteHasStation> RouteHasStation { get; set; }
}
public class RouteHasStation
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int RouteHasStationID { get; set; }
[ForeignKey("Station")]
public int StationID { get; set; }
public virtual Station Station { get; set; }
[ForeignKey("Trip")]
public int TripID { get; set; }
public virtual Trip Trip { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:HH:mm}")]
public DateTime? Arrival { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:HH:mm}")]
public DateTime? Departure { get; set; }
public int Platform { get; set; }
public float Distance { get; set; }
}
Apart from your typing errors, your program has several problems.
The statement
.Include(r => r.Schedule.where(day + "==" + true)
does not have a correct predicate. Even if you'd be able to change it into a predicate LINQ to SQL doesn't know how to handle this as a query, because you need to call a different procedure from your Schedule class depending on variable day.
Because of the combination with the include, I'm not sure what you want. From your description I'd say you want all routes (with a certain departure station and arrival station) that are scheduled to run on the given search date.
I'm not sure if you are using an existing database, or are still developing it. In the latter case, consider changing the Schedule class such that Schedule is a flagged enum like this
[Flags]
public enum MyDayOfWeek
{
Sunday = 1 << System.DayOfWeek.Sunday, // 0x01
Monday = 1 << System.DayOfWeek.Monday, // 0x02
Tuesday = 1 << System.DayOfWeek.Tuesday, // 0x04
Wednesday 1 << System.DayOfWeek.Wednesday, // 0x08
Thursday 1<< System.DayOfWeek.Thursday, // 0x10
Friday = 1 << System.DayOfWeek.Friday, // 0x20
Saturday = 1 << System.DayOfWeek.Saturday, // 0x40
}
public class Schedule
{
public int ScheduleID { get; set; }
public int RouteID { get; set; }
public MyDayOfWeek RunDays { get; set; }
public virtual ICollection<Trip> Trips {get; set;}
...
RunDays is an or-flagged variable of all days the route is scheduled to be run, for instance, if scheduled to run in weekends only:
RunDays = DayOfWeek.Saturday | DayOfWeek.Sunday;
The query to get all routes that are scheduled to run on a given DateTime will be like:
System.DayOfWeek dayOfWeek = day.DayOfWeek;
MyDayOfWeek myDayOfWeek = (MyDayOfWeek)( 1 << (int)dayOfWeek);
var routesRunningOnDate = db
.Where(route => route.DepartureStation etc
&& (route.RunDays & myDayOfWeek) == myDayOfWeek)
Linq to SQL will know how to handle it.
If you can't change the model of your database and you are stuck with this definition of Schedule, you can't perform it AsQueryable, however it will be possible to perform it AsEnumerable, in your local memory.
If you want to check if your route is scheduled on a certain day of week using the functions Schedule.Monday, Schedule.Tuesday, etc, I'd advise you define and extension for your Schedule class:
public static class ScheduleExtensions
{
// returns whether schedule scheduled on date:
public static bool IsScheduled(this Schedule schedule, DateTime date)
{
switch (date.DayOfWeek)
{
case DayOfWeek.Sunday:
return schedule.Sunday;
case DayOfWeek.Monday:
return chedule.Monday;
...
}
}
}
Usage:
db.Routes.AsEnumerable().Where (route => route.Schedule.IsScheduled(date));
Furthermore, it seems you haven't bracketed all your includes correctly. all your paramertes r, s, sch, route, st are all expected to be routes, while in fact you mean your sch to be Schedules, etc.
Be aware, that as long as you don't really enumerate over your sequence (and you don't dispose your DbContext), you don't need the Include statements. Include statements are needed when you don't specifically ask for a value, but you want them in local memory.
If you have an IQueryable, that does not use a certain field of your table and late you use this field, before you enumerate it, the field is automatically added to the query and thus to your SQL query:
var query1 = routes.Where(r.DepartureStationID == departure && r.ArrivalStationID == arrival);
var query2 = query1.Where(route => route.Schedule.Trips...)
Without the extra include LINQ to SQL knows that a join with the Schedule table is needed.
I guess you want the following routes:
(1) All routes that start on DepartureStation and arrive on ArrivalStation
(2) AND that are scheduled to run on day
(3) AND that are scheduled after (not on?) Schedule.DepartureTime
(4) Make sure you have all stations from route.RouteHasStations
Not really sure if Schedule.DepartureTime means the first day that this schedule is valid (so wouldn't ActivationDate be a better name?) or whether DepartureTime is the time that the train departs on the Scheduled dates.
In the latter case the statement
.Include(sch => sch.trip.where(date > sch.DepartureTime)
doesn't do what you want: it returns all schedules that were schedule on dates after your date, even if the departuretime is later than the time in your date
db.Routes.Where(route => route.DepartureStaionId == departure
&& route.ArrivalStationId == arrival
&& route.Schedule.IsScheduled(date)
&& date > route.Trips.DepartureTime)
// you don't need to include Schedule and Trips explicitly
// unless you need their fields outside this query
.Include(route => route.Train)
.Include(route => route.HasTrips)
// only include these if you need their fields outside this query
// if the only thing from train you want is Train.Name,
// use route.Train.Name in a select after the Where
I have a little problem, here is my code:
public partial class Tourist
{
public Tourist()
{
Reserve = new HashSet<Reserve>();
}
public int touristID { get; set; }
[Required]
[StringLength(50)]
public string touristNAME { get; set; }
public DateTime touristBIRTHDAY { get; set; }
[Required]
[StringLength(50)]
public string touristEMAIL { get; set; }
public int touristPHONE { get; set; }
public virtual ICollection<Reserve> Reserve { get; set; }
}
}
How can I restrict touristBIRTHDAY to be +18 years old? I think that I have to use this function, but I don't know where to put it:
Note: this function it's an example.
DateTime bday = DateTime.Parse(dob_main.Text);
DateTime today = DateTime.Today;
int age = today.Year - bday.Year;
if(age < 18)
{
MessageBox.Show("Invalid Birth Day");
}
Thanks ;)
UPDATE:
I follow the solution of Berkay Yaylaci, but I'm getting a NullReferenceException. It's seems that my value parameter is default, and then my method is not posting, why? What is the solution to that?
You can write your own Validation. First, create a class.
I called MinAge.cs
public class MinAge : ValidationAttribute
{
private int _Limit;
public MinAge(int Limit) { // The constructor which we use in modal.
this._Limit = Limit;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
DateTime bday = DateTime.Parse(value.ToString());
DateTime today = DateTime.Today;
int age = today.Year - bday.Year;
if (bday > today.AddYears(-age))
{
age--;
}
if (age < _Limit)
{
var result = new ValidationResult("Sorry you are not old enough");
return result;
}
return null;
}
}
SampleModal.cs
[MinAge(18)] // 18 is the parameter of constructor.
public DateTime UserBirthDate { get; set; }
IsValid runs after post and check the Limit. If age is not greater than the Limit (which we gave in modal!) than return ValidationResult
Implement IValidatableObject on your tourist class.
Put your logic in the Validate() method.
You are using MVC so there is no MessageBox.Show(). The MVC model binder will automatically call you validation routine.
Here's another SO question with the details How do I use IValidatableObject?
Also your age logic is wrong. it needs to be
DateTime now = DateTime.Today;
int age = now.Year - bday.Year;
if (now < bday.AddYears(age)) age--;
I am using a ViewModel to Create a new item in my DB
the ViewModel has only the properties that I want the user to be able to set, and when it is posted back I make a new 'real' object and save it away to the DB.
I am doing this as detailed below
[HttpGet]
public ActionResult Create(int id = 0)
{
var opt = unitOfWork.OptionRepository.GetByID(id);
CreateAvailabilityViewModel model = new CreateAvailabilityViewModel();
model.OptionDescription = opt.Description;
model.CentreCode = opt.CentreCode;
model.OptionID = id;
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CreateAvailabilityViewModel cavm)
{
if (ModelState.IsValid)
{
OptionAvailability newOA = new OptionAvailability();
DateTime now = DateTime.Now;
newOA.ChangedDate = newOA.CreatedDate = now;
newOA.ChangedBy = newOA.CreatedBy = User.Identity.Name;
newOA.DateFrom = cavm.DateFrom;
newOA.DateTo = cavm.DateTo;
newOA.MinNumbers = cavm.MinNumbers;
newOA.MaxNumbers = cavm.MaxNumbers;
newOA.OptionID = cavm.OptionID;
unitOfWork.OptionAvailabilityRepository.Insert(newOA);
unitOfWork.Save();
return RedirectToAction("Detail", "Option", new { id = newOA.OptionID });
}
return View(cavm);
}
and this is the ViewModel
public class CreateAvailabilityViewModel
{
[HiddenInput(DisplayValue = false)]
public int OptionAvailabilityID { get; set; }
[HiddenInput(DisplayValue = false)]
public int OptionID { get; set; }
[Required]
public DateTime DateFrom { get; set; }
[Required]
public DateTime DateTo { get; set; }
[Required]
public int MinNumbers { get; set; }
[Required]
public int MaxNumbers { get; set; }
public string CentreCode { get; set; }
public string OptionDescription { get; set; }
}
the problem I am facing is that when the form is rendered the form fields for the dates and ints are defaulting to 01/01/0001 and 0 instead of being blank. I am using the Html.EditorFor helpers to render the inputs I assume it is because in the HttpGet Create method, when I instantiate the ViewModel it uses the type defaults and then passes them through in the object to the form, but this is not wha tI want to be happening.. do I need to set these properties to DateTime? and/or int? ?
I am pretty sure this is good practice to use but am a bit stumped as to why
can anyone explain what I am doing wrong please
thanks muchly
You can instantiate the dates with whatever values you want.
You could use backing fields in your viewmodel (instead of auto properties) and initialize them:
public class MyViewModel
{
private DateTime _firstDate = new DateTime(12/12/2012);
private DateTime _secondDate = DateTime.Now();
public DateTime FirstDate { get { return _firstDate; } set { _firstDate = value; } }
...
}
Or you could initialize them in the viewmodel's constructor:
public class MyViewModel
{
public MyViewModel(DateTime firstDate)
{
FirstDate = firstDate;
SecondDate = DateTime.Now();
}
public DateTime FirstDate { get; set; }
....
}
Or you could initialize them in your controller; you probably get the idea.
Also consider decorating these members with metadata:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime FirstDate { get; set; }
I have a viewModel that contains the following:
public class CreateCardViewModel
{
[HiddenInput(DisplayValue = false)]
public int SetId { get; set; }
[Required]
public IList<Side> Sides { get; set; }
[Required]
public int Stage { get; set; }
[Required]
[DataType(DataType.Date)]
[HiddenInput(DisplayValue = false)]
public DateTime DateCreated { get; set; }
[Required]
public bool IsReady { get; set; }
}
The model is as follows:
public class Card
{
public virtual int CardId { get; set; }
// belongs to a Set
public virtual int SetId { get; set; }
public virtual Set Set { get; set; }
// has Sides
public virtual IList<Side> Sides { get; set; }
// is in a certain Stage
public virtual int Stage { get; set; }
// is ready to study
public virtual bool IsReady { get; set; }
public virtual DateTime DateCreated { get; set; }
}
How can I set a default value for DateCreated?
Would the method change if I want to insert a blank Side into Sides upon Card creation?
You could set defaults in the constructor:
public CreateCardViewModel()
{
DateCreated = DateTime.Now;
Sides = new List<Side> { new Side() };
}
Caveat: There is an issue with using DateTime.Now from a unit testing perspective. If you're unit testing your ViewModel creation and need to be able to verify that the created date is set to a known value, you can look at creating a separate concept for time, as detailed in Ayende's blog. You basically create a static func, SystemTime, that you can set to a known value in your tests. If you don't set it, it defaults to DateTime.Now:
public static class SystemTime
{
public static Func<DateTime> Now = () => DateTime.Now;
}
Your constructor code then becomes:
public CreateCardViewModel()
{
DateCreated = SystemTime.Now();
Sides = new List<Side> { new Side() };
}
If you need to actually set the time to a known value, you do this:
SystemTime.Now = () => new DateTime(2013, 2, 11, 17, 41, 12);
I agree on The SystemTime approach.
Although, I personally don't like setting the CreatedDate on the constructor, since there can be a short time lapse since you instantiate the object and when you persist it to the database. (And here I am assuming you definitely are)
You could make all your domain objects inherit from an interface like this one:
public interface ITimeStamped
{
DateTime DateCreated { get; set; }
}
And then on the Commit method int the Context class I would do something like this to set the date for all entities that implement the interface:
foreach (var entry in ChangeTracker.Entries<ITimeStamped>()
.Where(entry => entry.State == EntityState.Added))
{
entry.Entity.DateCreated = SystemTime.Now();
}
This way you're totally certain that the entity is stored with the correct DateTime when it was persisted on the database.
I am fairly new to MVC 3 and I was tasked with creating a to-do list, that has got timestamps for every independent variable, so when one variable changes, the timestamp of when it was changed would appear on the text field of that variable and not change the other timestamps of the other variables i.e each variable would have an individual timestamp. I believe I can only or most likely achieve this by creating an array. Any ideas on how I can carry this out?
I dummy code would be really appreciated
Here's a sample of my model, I followed this tutorial http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/cs/intro-to-aspnet-mvc-3
public class Checklist
{
public int ID { get; set; }
public string Title { get; set; }
public string Status { get; set; }
[Display(Name = "Start Date")]
public string Start_Date { get; set; }
[Display(Name = "Complesion Date")]
public string Complesion_Date { get; set; }
public DateTime[] Timestamp
{
get { return timestamp; }
set { timestamp = value; }
[Display(Name = "Internal Review System Reference")]
public string Internal_Review_System_Reference { get; set; }
[Display(Name = "Assignment from Original Owner")]
public bool Assignment_from_Original_Owner { get; set; }
public class listDBContext : DbContext
{
public DbSet<Checklist> List { get; set; }
}
And here's a sample of my controller code
public class SybreController : Controller
{
private listDBContext db = new listDBContext();
private Checklist check = new Checklist();
private string oldTitle { get; set; }
private string oldStatus { get; set; }
public ActionResult Edit(int id)// Called when edit button is clicked
{
Checklist checklist = db.List.Find(id);
this.oldTitle = checklist.Title;
this.oldStatus = checklist.Status;
//initAllArrays(checklist);//initialize our arrays with previous values
return View(checklist);
}
[HttpPost]
public ActionResult Edit(Checklist checklist)
{
if (ModelState.IsValid)
{
checklist.Timestamp = DateTime.Now;
if (checklist.Title != this.oldTitle)
{
checklist.stamps[0] = DateTime.Now;
}
if (checklist.Status != this.oldStatus)
{
checklist.stamps[1] = DateTime.Now;
}
else
{ checklist.stamps[1] = checklist.stamps[1]; }
db.Entry(checklist).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
Basically I need an timestamp for every individual variable in my model, so that when edited, the timestamp corresponded to when it was edited, the problem I've been facing is the timestamp variable changes across all the variables instead of only the one which was changed. I just need the program to print the former timestamp from when it was last edited, and if edited, display the current time along side the text field.
Hope you understand -__-
You can't solve your problem in this way. Asp.net MVC is stateless, it means that the instance of the controller is created per every request. It means that the checks that you have performed to set time stamps have always true value, as oldTitle and oldStatus are nulls.