I have this scipt where I parse ical using iCal.Net.
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
string iCal = client.DownloadString("https://myurl");
DateTime today = DateTime.Today.ToUniversalTime();
var todayEvents = calendar.Events.Where(e => e.Start.AsUtc >= today && e.Start.AsUtc < today.AddDays).OrderByDescending(e => e.Start.AsUtc);
foreach (var evt in todayEvents)
{
console.log("Sum: " + evt.Summary + " Start: " + evt.Start + " End: " + evt.End);
}
My problem are, I only get events that starts and end the specific day (today in this example).
I do not get events like: Starts yesterday end ends tomorrow.
Any clue of how I solve that?
Related
The Problem
I have a Visual Studios 2015 Console Application with the Microsoft.Exchange.WebServices v2.2.0 NuGet package installed. I'm trying to create an appointment, update it, and cancel it while retaining the correct Timezone in the "When" string generated automatically in the calendar invite body. Currently, the initial creation has the correct timezone, but any subsequent updates cause the timezone to revert to UTC.
Note: We have an Exchange 2010 server and use Outlook 2013 clients.
Code Sample
using System;
using System.Globalization;
using Microsoft.Exchange.WebServices.Data;
namespace EWSTesting
{
class Program
{
private const string EmailServer = ""; //replace with your Exchange server
private const string EmailAddress = ""; //replace with your email
static void Main(string[] args)
{
Console.WriteLine("Current Timezone: " + TimeZoneInfo.Local.DisplayName);
var exchangeService = new ExchangeService(ExchangeVersion.Exchange2010, TimeZoneInfo.Local)
{
PreferredCulture = new CultureInfo("en-US"),
Url = new Uri(EmailServer),
UseDefaultCredentials = true
};
Console.WriteLine("exchangeService.TimeZone.DisplayName: " + exchangeService.TimeZone.DisplayName);
var startDate = DateTime.Today;
var endDate = startDate.AddHours(1);
//Create initial appointment
var appointment = new Appointment(exchangeService)
{
Subject = "Testing Appointments",
Body = "Testing Appointments Body",
Location = "Test Location",
LegacyFreeBusyStatus = LegacyFreeBusyStatus.Busy,
Sensitivity = Sensitivity.Private,
Start = startDate,
End = endDate
};
appointment.OptionalAttendees.Add(EmailAddress);
appointment.Save(SendInvitationsMode.SendOnlyToAll);
Console.WriteLine("exchangeService.TimeZone.DisplayName: " + exchangeService.TimeZone.DisplayName);
var appointmentId = appointment.Id;
Console.WriteLine("Pause to check inbox 'When' value on invite");
Console.ReadLine();
appointment = Appointment.Bind(exchangeService, appointmentId);
appointment.Load(new PropertySet(PropertySet.FirstClassProperties)
{
AppointmentSchema.StartTimeZone,
AppointmentSchema.EndTimeZone,
AppointmentSchema.TimeZone
});
appointment.Body = "Body Updated Successfully";
appointment.Update(ConflictResolutionMode.AlwaysOverwrite, SendInvitationsOrCancellationsMode.SendOnlyToAll);
Console.WriteLine("exchangeService.TimeZone.DisplayName: " + exchangeService.TimeZone.DisplayName);
Console.WriteLine("appointment.StartTimeZone.DisplayName: " + appointment.StartTimeZone.DisplayName);
Console.WriteLine("appointment.EndTimeZone.DisplayName: " + appointment.EndTimeZone.DisplayName);
Console.WriteLine("appointment.TimeZone: " + appointment.TimeZone);
Console.WriteLine();
Console.WriteLine("Pause to check updated inbox 'When' value on invite");
Console.ReadLine();
appointment = Appointment.Bind(exchangeService, appointmentId);
appointment.Load(new PropertySet(PropertySet.FirstClassProperties)
{
AppointmentSchema.StartTimeZone,
AppointmentSchema.EndTimeZone,
AppointmentSchema.TimeZone
});
Console.WriteLine("exchangeService.TimeZone.DisplayName: " + exchangeService.TimeZone.DisplayName);
Console.WriteLine("appointment.StartTimeZone.DisplayName: " + appointment.StartTimeZone.DisplayName);
Console.WriteLine("appointment.EndTimeZone.DisplayName: " + appointment.EndTimeZone.DisplayName);
Console.WriteLine("appointment.TimeZone: " + appointment.TimeZone);
appointment.CancelMeeting();
Console.WriteLine("Appointment Deleted");
Console.ReadLine();
}
}
}
The Results of the above code
Initial Invite (Correct Timezone)
Updated Appointment (Incorrect Timezone in body)
Appointment Cancellation (Incorrect Timezone in body)
Console Result of code provided
What I'm Looking For
I do not need this additional "When" (underlined in red in pictures above) to be appended to the body of the invite. Either I would like to completely remove it (preferred) or I would like to correct it in any updates.
It appears that the issue is a bug in the EWS 2.2.0 DLL, the timezone SOAP headers are not being added to the Update() and CancelMeeting() Exchange transactions. The code below resolves this issue by manually appending the correct header.
For Update():
exchangeService.OnSerializeCustomSoapHeaders += service_OnSerializeCustomSoapHeaders;
appointment.Update(ConflictResolutionMode.AlwaysOverwrite, SendInvitationsOrCancellationsMode.SendOnlyToAll);
exchangeService.OnSerializeCustomSoapHeaders -= service_OnSerializeCustomSoapHeaders;
For CancelMeeting():
exchangeService.OnSerializeCustomSoapHeaders += service_OnSerializeCustomSoapHeaders;
appointment.CancelMeeting();
exchangeService.OnSerializeCustomSoapHeaders -= service_OnSerializeCustomSoapHeaders;
Event Implementation:
static void service_OnSerializeCustomSoapHeaders(XmlWriter writer)
{
writer.WriteRaw(Environment.NewLine + " <t:TimeZoneContext><t:TimeZoneDefinition Id=\"" + TimeZoneInfo.Local.StandardName + "\"/></t:TimeZoneContext>" + Environment.NewLine);
}
In my jQuery code I am calling a controller action and I'm trying to pass in dates from the fullcalendar plugin:
url: ('Home/List/?dateValueStart=' + new Date($('#calendar').fullCalendar('getView').start))
+ '&dateValueEnd=' + new Date($('#calendar').fullCalendar('getView').end),
In my controller I have my method setup like this:
public ActionResult List(String dateValueStart, String dateValueEnd)
When I debug dateValueStart I see this:
Tue Oct 1 00:00:00 MDT 2013
DateTime dateVal = Convert.ToDateTime(dateValueStart);
But when I try to convert this to a date it tells me it is invalid.
String was not recognized as a valid DateTime.
How can I get a date close to 10/1/2013?
Javascript date support isn't the greatest. There are shorter ways to do the following but they don't work in all browsers:
var formatDate = function(d){
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
return curr_month + "/" + curr_date + "/" + curr_year;
}
var startDate = new Date($('#calendar').fullCalendar('getView').start);
var endDate = new Date($('#calendar').fullCalendar('getView').end);
var url = 'Home/List/?dateValueStart=' + formatDate(startDate) + '&dateValueEnd=' +
formatDate(endDate)
Also, check out this
I'm using JSON to send data to client. However, the date fields get transformed into a timespan format like /Date(1363807800000)/.
Is there anyway to get rid of it and let server send DateTime values like 2013/7/21 3:44 PM to client?
Think of this,
var data = "/Date(1363807800000)/";
var date = new Date(parseInt(data.replace("/Date(", "").replace(")/", ""), 10));
var result = date.getFullYear() + "-" + (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-" + (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " " + (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":" + (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes());
Then, use this RegEx to validate it,
/ ^ \ d {4} - \ d { 2} - \e{2} \e{2}:\e{2}:\e{2} $ /
Hope this helps...:)
Here is a solution using Json.NET (you can install it via NuGet):
object testObject = new { Name = "TestName", DateTime = DateTime.Now };
string output = JsonConvert.SerializeObject(testObject, new IsoDateTimeConverter());
Console.Write(output);
Output:
"{\"Name\":\"TestName\",\"DateTime\":\"2013-07-21T15:01:56.2872469+03:00\"}"
In case ISO DateTime format does not work well for you, you can write your own DateTimeConverter to use with SerializeObject function.
I wrote once this, maybe you could add the string to your json ?
var getDate = function() {
var date = new Date();
var prefix = "["
+ date.getDate() + "."
+ (date.getMonth() + 1) + "."
+ date.getFullYear() + " "
+ date.toString().split(" ")[4]
+ "]";
return prefix;
};
Does anybody know if its possible to save the windows event logs from a given time interval as a text file with C#? For example say I want to save the System event logs from between 10 - 11 am in a text file. If it is possible does anybody have a link to a good tutorial or maybe a code snippet that could get me going? I have searched online but cant get what I am looking for.
http://www.dreamincode.net/forums/topic/93268-working-with-the-system-event-log-with-c%23-intro/
Just adding info for others on how to filter event logs by time range as part of the WMI query.
Note that 'TimeGenerated' is when events happen and 'TimeWritten' when they are logged.
The 'RecordNumber' is a unique index, useful for preventing collision or duplicate logging.
There is System.Management.ManagementDateTimeConverter that converts between C# DateTime and the WMI CIM_DATETIME format.
But be aware it makes the UTC CIM into a LOCAL DateTime while leaving Kind Unspecified, so set Kind afterwards to avoid headaches!
This is an example for grabbing security failures ( to track lockouts ) in the last 30 minutes:
private void SearchEventViewer(string computerName, string userName, string userPass)
{
var scope = CreateManagementScope(computerName, userName, userPass);
var startTime = ManagementDateTimeConverter.ToDmtfDateTime(DateTime.UtcNow.AddMinutes(-30));
var query = new SelectQuery("SELECT * FROM Win32_NTLogEvent WHERE Logfile = 'Security' AND EventType = '5' AND TimeGenerated > '" + startTime + "'");
using (var searcher = new ManagementObjectSearcher(scope, query))
{
var result = searcher.Get();
foreach (var item in result)
{
var eventTimeLocal = DateTime.SpecifyKind(ManagementDateTimeConverter.ToDateTime(item["TimeGenerated"].ToString()), DateTimeKind.Local);
var eventTimeUtc = eventTimeLocal.ToUniversalTime();
var eventDetails = item["Message"].ToString().Replace("\r\n\r\n", "\r\n");
eventDetails += "\r\nEventCode: " + item["EventCode"];
eventDetails += "\r\nCatogory: " + item["Category"];
eventDetails += "\r\nRecord Number: " + item["RecordNumber"];
eventDetails += "\r\nLocal Time: " + eventTimeLocal.ToString("yyyy-MM-dd HH:mm:ss");
// Do something...
}
}
}
private ManagementScope CreateManagementScope(string computerName, string username = "", string password = "")
{
var managementPath = #"\\" + computerName + #"\root\cimv2";
var scope = new ManagementScope(managementPath);
if (username != "" && password != "")
{
scope.Options = new ConnectionOptions
{
Username = username,
Password = password,
Impersonation = ImpersonationLevel.Impersonate,
Authentication = AuthenticationLevel.PacketPrivacy
};
}
return scope;
}
I am learning jQuery. Here I have a requirement i.e I have to add Week number and Week ranges of a year to DropDown List in ASP.NET3.5. And I have to pass selected week range to database. I am using c#.net. This should be done automatically for every year.
How can I do this using JQUERY?
Regards,
JN
try this
function getDateRangeOfWeek(weekNo){
var d1 = new Date();
numOfdaysPastSinceLastMonday = eval(d1.getDay()- 1);
d1.setDate(d1.getDate() - numOfdaysPastSinceLastMonday);
var weekNoToday = d1.getWeek();
var weeksInTheFuture = eval( weekNo - weekNoToday );
d1.setDate(d1.getDate() + eval( 7 * weeksInTheFuture ));
var rangeIsFrom = eval(d1.getMonth()+1) +"/" + d1.getDate() + "/" + d1.getFullYear();
d1.setDate(d1.getDate() + 6);
var rangeIsTo = eval(d1.getMonth()+1) +"/" + d1.getDate() + "/" + d1.getFullYear() ;
return rangeIsFrom + " to "+rangeIsTo;
};
answer is originally from
http://snipplr.com/view/7540/get-date-range-from-week-number-in-year/