I am running a windows service which runs every 6 hours and generates files. For some files I want to generate them only once a month.
var todaysDate = DateTime.Now.Date;
var firstOfMonth = new DateTime(todaysDate.Year, todaysDate.Month, 1);
var monthEnd = firstOfMonth.AddMonths(1).AddDays(-1);
var fileGenerated = false;
if (Convert.ToBoolean(firstOfMonth))
{
var fileToUploadOne = GenerateFileOne("sproc_name");
var fileToUploadTwo = GenerateFileTwo("sproc_name");
fileGenerated = true;
}
How can I make sure the file is generate only once a month.
Updates: Once is month means, generate file one time each month, so that when the services runs every X hours, it does not generate the file over and over again.
The idea is based on saving somewhere on a disk date of last file generation and checking if new month has begun.
You could try this (necessary comments are in code):
class Program
{
// some safe location
private static var path = "";
static void Main(string[] args)
{
//get the saved tade
var saveDate = GetLastSavingDate();
var today = DateTime.Now;
//var todaysDate = DateTime.Now.Date;
//var firstOfMonth = new DateTime(todaysDate.Year, todaysDate.Month, 1);
//var monthEnd = firstOfMonth.AddMonths(1).AddDays(-1);
var fileGenerated = false;
// check if the difference in months exceeded 1 - this will be true on every 1st of new month, for example 8 - 7 or even 1 - 12
if(Math.Abs(today.Month - saveDate.Month) >= 1)
{
var filetouploadone = generatefileone("sproc_name");
var filetouploadtwo = generatefiletwo("sproc_name");
filegenerated = true;
// save date
File.WriteAllText(path, JsonConvert.SerializeObject(today));
}
}
//method to get saved date
private static DateTime GetLastSavingDate()
{
var dt = new DateTime();
return JsonConvert.DeserializeAnonymousType(File.ReadAllText(path), dt);
}
}
I have taken Console App just for the sake of example, this can be easily applied in WinForms as well.
Related
I want to get client machine date format, my application is hosted on US machine.
Hosting Server date format : MM/dd/yyyy
Local(Client) machine date format: dd/MM/yyyy
I want to get dd/MM/yyyy format which is the format of the client machine.
I have used the following code but it returns server date format(MM/dd/yyyy) but I want client machine date format(Local).
DateTimeFormatInfo info = new DateTimeFormatInfo
{
ShortDatePattern = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern
};
Can anyone please tell how to get client machine date format(dd/MM/yyyy)?
In MVC asp.net :
Frist put Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(Request.UserLanguages.FirstOrDefault());into Application_BeginRequest
if you don't have Application_BeginRequest. Please click Global.asaxin your project.
add new function in MvcApplication class
protected void Application_BeginRequest() {
Thread.CurrentThread.CurrentCulture = new
System.Globalization.CultureInfo(Request.UserLanguages.FirstOrDefault());
}
now , you could use format of DateTime.Now with client machine
For Retrieving Client date format. I think java-script would be the best option
Try below code. I hope it will help.
getDateFormat(){
// initialize date value "31st January 2019"
var my_date = new Date(2019,0,31);
console.log(my_date.toLocaleDateString());
// Initialize variables
var separator="";
var first="";
var second="";
var third="";
var date_parts = [];
// get separator : "-", "/" or " ", format based on toLocaleDateString function
if (my_date.toLocaleDateString().split("-").length==3){
separator = " - ";
date_parts = my_date.toLocaleDateString().split("-");
}
if (my_date.toLocaleDateString().split("/").length == 3) {
separator = " / ";
date_parts = my_date.toLocaleDateString().split("/");
}
if (my_date.toLocaleDateString().split(" ").length == 3) {
separator = " ";
date_parts = my_date.toLocaleDateString().split(" ");
}
// get first part
if (date_parts[0]==2019){
first ="yyyy";
} else if (date_parts[0] == 31){
first = "dd";
} else{
if (date_parts[0].length<=2){
first ="mm";
}
else{
first="mmm";
}
}
// get second part
if (date_parts[1] == 2019) {
second = "yyyy";
} else if (date_parts[1] == 31) {
second = "dd";
} else {
if (date_parts[1].length <= 2) {
second = "mm";
}
else {
second = "mmm";
}
}
// get third part
if (date_parts[2] == 2019) {
third = "yyyy";
} else if (date_parts[2] == 31) {
third = "dd";
} else {
if (date_parts[2].length <= 2) {
third = "mm";
}
else {
third = "mmm";
}
}
// assembly
var format = first + separator + second + separator + third;
console.log(format);
return format;
}
I need to play a audio file which is 3 minutes length. But default notification sound does not play more than 30 seconds. So my idea is Calling a Avplayer
which will play my desired audio. But i do not know how to call this. Can any one please help me. I will be very grateful.
I am attaching my notification method here.
public void AVPlayer()
{
NSUrl songURL;
if (!MusicOn) return;
//Song url from your local Resource
songURL = new NSUrl("azan.wav");
NSError err;
player = new AVAudioPlayer(songURL, "Song", out err);
player.Volume = MusicVolume;
player.FinishedPlaying += delegate {
// backgroundMusic.Dispose();
player = null;
};
//Background Music play
player.Play();
}
public void CreateRequest(JamatTime jamat)
{
// Create action
var actionID = "pause";
var title = "PAUSE";
var action = UNNotificationAction.FromIdentifier(actionID, title, UNNotificationActionOptions.None);
// Create category
var categoryID = "message";
var actions = new UNNotificationAction[] { action };
var intentIDs = new string[] { };
var categoryOptions = new UNNotificationCategoryOptions[] { };
var category = UNNotificationCategory.FromIdentifier(categoryID, actions, intentIDs, UNNotificationCategoryOptions.None);
// Register category
var categories = new UNNotificationCategory[] { category };
UNUserNotificationCenter.Current.SetNotificationCategories(new NSSet<UNNotificationCategory>(categories));
// Rebuild notification
var content = new UNMutableNotificationContent();
content.Title = " Jamat Time alert";
content.Badge = 1;
content.CategoryIdentifier = "message";`enter code here`
content.Sound = UNNotificationSound.GetSound("sample.wav");
var times = new string[] { jamat.Asr, jamat.Dhuhr, jamat.Faijr, jamat.Ishaa, jamat.Jumah, jamat.Maghib };
int id = 0;
foreach (var time in times)
{
var ndate = DateTime.ParseExact(time, "h:mm tt", null);
var date = new NSDateComponents()
{
Calendar = NSCalendar.CurrentCalendar,
Hour = ndate.Hour,
Minute = ndate.Minute,
Second = 0
};
content.UserInfo = new NSDictionary<NSString, NSString>(
new NSString[] {
(NSString)"time1",
(NSString)"time2"
},
new NSString[] {
(NSString)DateTime.Now.ToString("h:mm tt"),
(NSString)time
});
var trigger = UNCalendarNotificationTrigger.CreateTrigger(date, true);
// ID of Notification to be updated
var request = UNNotificationRequest.FromIdentifier(id++.ToString(), content, trigger);
// Add to system to modify existing Notification
UNUserNotificationCenter.Current.AddNotificationRequest(request, (err1) =>
{
if (err1 != null)
{
Console.WriteLine("Error: {0}", err1);
}
Console.WriteLine($"Success: {request}");
});
}
}
You can't play an audio file instead of the UNNotificationSound.
There's no way to trigger the player's play method when the local notification comes. You could only configure the sound property using the code you post above. And the file should be embedded in the bundle resource.
It seems you are aware of UNNotificationSound: https://developer.apple.com/documentation/usernotifications/unnotificationsound?language=objc. But I still want to remind you of the file's format and length limitations.
Finally I have solved my problem.
When a notification fires then WillPresentNotification() method hits and I simply call the AVplayer there and perfectly working. If u want to play sound via UNNotificationSound then not possible because that is limited by 30 second duration..but problem this works only in foreground.
Im trying to make PatternedRecurrence's so that a user can choose from 3 options, weekly, biweekly and monthly. However the code i've tried dosen't appear to be working, it posts to the API without error but does not appear anywhere on the test calendar, where as a non patterned one does appear on the calendar. THis is the code i've tried to set a weekly pattern.
NewEvent.Recurrence = new PatternedRecurrence();
NewEvent.Recurrence.Range = new RecurrenceRange();
NewEvent.Recurrence.Pattern = new RecurrencePattern();
NewEvent.Recurrence.Pattern.DaysOfWeek = new List<Microsoft.Office365.OutlookServices.DayOfWeek>();
NewEvent.Recurrence.Range.Type = RecurrenceRangeType.EndDate;
NewEvent.Recurrence.Range.EndDate = start.AddYears(2).ToString();
NewEvent.Recurrence.Range.StartDate = start.ToString();
NewEvent.Recurrence.Pattern.Interval = 1;
NewEvent.Recurrence.Pattern.Type = RecurrencePatternType.Weekly;
NewEvent.Recurrence.Pattern.FirstDayOfWeek = Microsoft.Office365.OutlookServices.DayOfWeek.Monday;
if (StartDay.ToString() == "Monday")
{NewEvent.Recurrence.Pattern.DaysOfWeek.Add(Microsoft.Office365.OutlookServices.DayOfWeek.DayOfWeek.Monday); }
else if (StartDay.ToString() == "Tuesday")
{ NewEvent.Recurrence.Pattern.DaysOfWeek.Add(Microsoft.Office365.OutlookServices.DayOfWeek.DayOfWeek.Tuesday); }
... for the rest of the days of the week
I've looked up the referances for this but they aren't very helpful, although i'd think what i've written makes enough sense to work, apart from all them if statements, I couldn't figure a better way to convert from System.DayOfWeek to Microsoft.Office365.OutlookServices.DayOfWeek
Did you have code to catch the execption? What's the response of the Request? We can use the Fiddler to track the response, if the recurrent appointment was created successfully, the response would contains the detail information about recurrence.
For example, here is a successful response:
{"#odata.context":"https://outlook.office.com/api/v2.0/$metadata#Me/Events/$entity","#odata.id":"https://outlook.office.com/api/v2.0/Users('7f4f5db6-539f-45d2-b133-26a25318269a#60c1366c-1b8f-4fcd-a190-058bfd47bcb4')/Events('AQMkADVkMTY3YmNiLTJiMDctNGU5Yi05MmM4LTFjODZkNDgxMzhkMQBGAAAE19y4nS_cT5eu67AiEA77BwB6jcCHf_RcRZqcWLJUEog7AAACAQ0AAAB6jcCHf_RcRZqcWLJUEog7AAAAA_dGpgAAAA==')","#odata.etag":"W/\"eo3Ah3/kXEWanFiyVBKIOwAAA+SaVA==\"","Id":"AQMkADVkMTY3YmNiLTJiMDctNGU5Yi05MmM4LTFjODZkNDgxMzhkMQBGAAAE19y4nS_cT5eu67AiEA77BwB6jcCHf_RcRZqcWLJUEog7AAACAQ0AAAB6jcCHf_RcRZqcWLJUEog7AAAAA_dGpgAAAA==","CreatedDateTime":"2016-01-21T23:45:06.8317353-08:00","LastModifiedDateTime":"2016-01-21T23:45:07.0973601-08:00","ChangeKey":"eo3Ah3/kXEWanFiyVBKIOwAAA+SaVA==","Categories":[],"OriginalStartTimeZone":"Pacific Standard Time","OriginalEndTimeZone":"Pacific Standard Time","ResponseStatus":{"Response":"Organizer","Time":"0001-01-01T00:00:00Z"},"iCalUId":"040000008200E00074C5B7101A82E00800000000A996F1CFE854D101000000000000000010000000D968C3A111A417438178343B150C0974","ReminderMinutesBeforeStart":15,"IsReminderOn":true,"HasAttachments":false,"Subject":"Sync up","Body":{"ContentType":"Text","Content":"Status updates, blocking issues, and next steps"},"BodyPreview":"Status updates, blocking issues, and next steps","Importance":"Normal","Sensitivity":"Normal","Start":{"DateTime":"2016-01-22T02:30:00.0000000","TimeZone":"Pacific Standard Time"},"End":{"DateTime":"2016-01-22T03:30:00.0000000","TimeZone":"Pacific Standard Time"},"Location":{"DisplayName":"Water cooler"},"IsAllDay":false,"IsCancelled":false,"IsOrganizer":true,"Recurrence":{"Pattern":{"Type":"Weekly","Interval":1,"Month":0,"DayOfMonth":0,"DaysOfWeek":["Friday"],"FirstDayOfWeek":"Sunday","Index":"First"},"Range":{"Type":"EndDate","StartDate":"2016-01-22","EndDate":"2017-01-22","RecurrenceTimeZone":"Pacific Standard Time","NumberOfOccurrences":0}},"ResponseRequested":true,"SeriesMasterId":null,"ShowAs":"Busy","Type":"SeriesMaster","Attendees":[],"Organizer":{"EmailAddress":{"Name":"Fei Xue","Address":"fx#msdnofficedev.onmicrosoft.com"}},"WebLink":"https://outlook.office365.com/owa/?ItemID=AQMkADVkMTY3YmNiLTJiMDctNGU5Yi05MmM4LTFjODZkNDgxMzhkMQBGAAAE19y4nS%2BcT5eu67AiEA77BwB6jcCHf%2BRcRZqcWLJUEog7AAACAQ0AAAB6jcCHf%2BRcRZqcWLJUEog7AAAAA%2BdGpgAAAA%3D%3D&exvsurl=1&viewmodel=ICalendarItemDetailsViewModelFactory"}
And Here is the code that created the recurrent appointment by weekly:
OutlookServicesClient client = new OutlookServicesClient(new Uri("https://outlook.office.com/api/v2.0"),
async () =>
{
// Since we have it locally from the Session, just return it here.
return token;
});
Location location = new Location
{
DisplayName = "Water cooler"
};
// Create a description for the event
ItemBody body = new ItemBody
{
Content = "Status updates, blocking issues, and next steps",
ContentType = BodyType.Text
};
// Create the event object
DateTimeTimeZone start=new DateTimeTimeZone() ;
string dateTimeFormat = "yyyy-MM-ddThh:mm:ss";
string timeZone = "Pacific Standard Time";//"Eastern Standard Time";
start.DateTime = new DateTime(2016, 1, 22, 14, 30, 0).ToString(dateTimeFormat);
start.TimeZone = timeZone;
DateTimeTimeZone end = new DateTimeTimeZone();
end.DateTime = new DateTime(2016, 1, 22, 15, 30, 0).ToString(dateTimeFormat);
end.TimeZone = timeZone;
Event newEvent = new Event
{
Subject = "Sync up",
Location = location,
Start = start,
End = end,
Body = body
};
newEvent.Recurrence = new PatternedRecurrence();
newEvent.Recurrence.Range = new RecurrenceRange();
string dateFormat = "yyyy-MM-dd";
newEvent.Recurrence.Range.EndDate = DateTime.Now.AddYears(1).ToString(dateFormat);
newEvent.Recurrence.Range.StartDate = DateTime.Now.ToString(dateFormat);
newEvent.Recurrence.Range.NumberOfOccurrences = 11;
newEvent.Recurrence.Pattern = new RecurrencePattern();
newEvent.Recurrence.Pattern.Type = RecurrencePatternType.Weekly;
newEvent.Recurrence.Pattern.Interval = 1;
newEvent.Recurrence.Pattern.DaysOfWeek= new List<Microsoft.Office365.OutlookServices.DayOfWeek>() { Microsoft.Office365.OutlookServices.DayOfWeek.Friday };
// Add the event to the default calendar
await client.Me.Events.AddEventAsync(newEvent);
GetUserAvailabilityResults shows result which are outside working hours in Exchange web service although I have set MaximumNonWorkHoursSuggestionsPerDay = 0
Also, I want to know how to get and set the working hours. Moreover, results.AttendeesAvailability returns null
private static void GetSuggestedMeetingTimes(ExchangeService service)
{
// Create a list of attendees.
List<AttendeeInfo> attendees = new List<AttendeeInfo>();
attendees.Add(new AttendeeInfo()
{
SmtpAddress = "vrr#e.edu.sa",
AttendeeType = MeetingAttendeeType.Organizer
});
attendees.Add(new AttendeeInfo()
{
SmtpAddress = "abc#e.edu.sa",
AttendeeType = MeetingAttendeeType.Required
});
AvailabilityOptions meetingOptions = new AvailabilityOptions();
meetingOptions.MeetingDuration = 30;
meetingOptions.MaximumNonWorkHoursSuggestionsPerDay = 0;
meetingOptions.GoodSuggestionThreshold = 49;
meetingOptions.MinimumSuggestionQuality = SuggestionQuality.Good;
meetingOptions.DetailedSuggestionsWindow = new TimeWindow(DateTime.Now, DateTime.Now.AddDays(2));
meetingOptions.MaximumSuggestionsPerDay = 48;
// Return a set of of suggested meeting times.
GetUserAvailabilityResults results = service.GetUserAvailability(attendees,
new TimeWindow(DateTime.Now, DateTime.Now.AddDays(2)),
AvailabilityData.Suggestions,
meetingOptions);
// Console.WriteLine(results.AttendeesAvailability[0].WorkingHours.EndTime);
// Display available meeting times.
Console.WriteLine("Availability for {0} and {1}", attendees[0].SmtpAddress, attendees[0].SmtpAddress);
Console.WriteLine();
//foreach (AttendeeAvailability aa in results.AttendeesAvailability)
//{
// //Console.WriteLine(aa.Result.Date);
// Console.WriteLine(aa.CalendarEvents.Count);
//}
foreach (Suggestion suggestion in results.Suggestions)
{
Console.WriteLine(suggestion.Date);
Console.WriteLine();
foreach (TimeSuggestion timeSuggestion in suggestion.TimeSuggestions)
{
Console.WriteLine("Suggested meeting time:" + timeSuggestion.MeetingTime);
Console.WriteLine();
}
}
}
In Exchange the working hours is maintained separately for each user. Every User can have its own working hours.(Although it does not seems to be reasonable for employees in 1 organization)
GetUserAvailabilityResults was giving suggestions outside the working hours because one of the attendee's working hour was different from the other
You cannot set the working hour for a user (as far as I know) however every user can change the working hours using outlook
Outlook Change working hour
You can see the working hours of each attendee using results.AttendeesAvailability
the results.AttendeesAvailability will not give null if AvailabilityData.FreeBusyAndSuggestions instead of AvailabilityData.Suggestions
is used
the following is the modified code
private static void GetSuggestedMeetingTimes(ExchangeService service)
{
// Create a list of attendees.
List<AttendeeInfo> attendees = new List<AttendeeInfo>();
attendees.Add(new AttendeeInfo()
{
SmtpAddress = "shomaail#kfupm.edu.sa",
AttendeeType = MeetingAttendeeType.Required,
ExcludeConflicts = false
});
attendees.Add(new AttendeeInfo()
{
SmtpAddress = "vrr#kfupm.edu.sa",
AttendeeType = MeetingAttendeeType.Required
});
AvailabilityOptions meetingOptions = new AvailabilityOptions();
meetingOptions.MeetingDuration = 30;
meetingOptions.MaximumNonWorkHoursSuggestionsPerDay = 0;
meetingOptions.GoodSuggestionThreshold = 49;
meetingOptions.MinimumSuggestionQuality = SuggestionQuality.Excellent;
meetingOptions.DetailedSuggestionsWindow = new TimeWindow(DateTime.Now, DateTime.Now.AddDays(2));
meetingOptions.MaximumSuggestionsPerDay = 48;
// Return a set of of suggested meeting times.
GetUserAvailabilityResults results = service.GetUserAvailability(attendees,
new TimeWindow(DateTime.Now, DateTime.Now.AddDays(2)),
AvailabilityData.FreeBusyAndSuggestions,
meetingOptions);
// Console.WriteLine(results.AttendeesAvailability[0].WorkingHours.EndTime);
// Display available meeting times.
Console.WriteLine("Availability for {0} and {1}", attendees[0].SmtpAddress, attendees[1].SmtpAddress);
Console.WriteLine();
foreach (AttendeeAvailability aa in results.AttendeesAvailability)
{
Console.WriteLine("=============================================");
Console.WriteLine(aa.Result.ToString());
Console.WriteLine(aa.ViewType.ToString());
Console.WriteLine(aa.CalendarEvents.Count);
Console.WriteLine(aa.WorkingHours.StartTime);
Console.WriteLine(aa.WorkingHours.EndTime);
Console.WriteLine(aa.WorkingHours.DaysOfTheWeek.Count);
Console.WriteLine(aa.WorkingHours.DaysOfTheWeek[0]);
Console.WriteLine(aa.WorkingHours.DaysOfTheWeek[aa.WorkingHours.DaysOfTheWeek.Count-1]);
foreach (DayOfTheWeek dow in aa.WorkingHours.DaysOfTheWeek)
{
Console.WriteLine(dow);
}
}
foreach (Suggestion suggestion in results.Suggestions)
{
Console.WriteLine(suggestion.Date);
Console.WriteLine();
foreach (TimeSuggestion timeSuggestion in suggestion.TimeSuggestions)
{
Console.WriteLine("Suggested meeting time:" + timeSuggestion.MeetingTime);
Console.WriteLine();
}
}
}
I want to get the most current questions from Stack Overflow using the Stacky C# library for the Stack Exchange API.
I took the example code and tried to run it but it hangs when it comes to returning data from the Stack Exchange website.
StackyClient client = new StackyClient("0.9", "", Sites.StackOverflow,
new UrlClient(), new JsonProtocol());
var o = new QuestionOptions();
o.FromDate = DateTime.Now.AddMinutes(-10.0);
o.ToDate = DateTime.Now;
o.IncludeAnswers = false;
o.IncludeBody = false;
o.IncludeComments = false;
o.SortBy = QuestionSort.Creation;
o.SortDirection = SortDirection.Descending;
IPagedList<Question> l = client.GetQuestions(o); <--- program hangs here 4ever
What am I doing wrong?
I also saw that I can register my application to get an API Key. But that is not necessary to make it run in the first place, is it?
Edit
If I remove the lines
o.FromDate = DateTime.Now.AddMinutes(-10.0);
o.ToDate = DateTime.Now;
it works and returns all questions. Also if I add the line
o.Max = 50;
instead, then it does not work either.
Edit 2
Now it works - rebooted my computer.
BTW I used that code in the end
var o = new QuestionOptions();
o.FromDate = DateTime.UtcNow.AddMinutes(-20);
o.IncludeAnswers = false;
o.IncludeBody = false;
o.IncludeComments = false;
o.SortBy = QuestionSort.Creation;
o.SortDirection = SortDirection.Descending;
IPagedList<Question> l = client.GetQuestions(o);
And
o.Max
expects an Unix Epoch time, not a number of maximum posts.
Try changing the version specified in the StackyClient constructor from "0.9" to "1.1". I get a JSON parse error on the client.GetQuestions(o) line when the version is "0.9", but it runs fine with "1.1".
Using the latest Stacky code from bitbucket there is no longer a QuestionOptions parameter to GetQuestions. Also using version 0.9 of the API causes Stacky to crash, but according to this version 1.x is deprecated, so maybe 0.9 is removed?
StackyClient client = new StackyClient("2.1", Sites.StackOverflow,
new UrlClient(), new JsonProtocol());
//var o = new QuestionOptions();
//o.FromDate = DateTime.Now.AddMinutes(-10.0);
//o.ToDate = DateTime.Now;
//o.IncludeAnswers = false;
//o.IncludeBody = false;
//o.IncludeComments = false;
//o.SortBy = QuestionSort.Creation;
//o.SortDirection = SortDirection.Descending;
QuestionSort sort = QuestionSort.Creation;
SortDirection sortDir = SortDirection.Descending;
int page = 1;
int pageSize = 100;
DateTime fromDate = DateTime.Now.AddMinutes(-10.0);
DateTime toDate = DateTime.Now;
IPagedList<Question> l = client.GetQuestions(sort, sortDir, page, pageSize, fromDate, toDate);
foreach (var question in l)
{
Console.WriteLine(question.Title);
}
Or, just remove the date and see if you get any results.
IPagedList<Question> l = client.GetQuestions(sort, sortDir, page, pageSize);//, fromDate, toDate);
foreach (var question in l)
{
Console.WriteLine(question.Title);
}