protected virtual void ProcessInternal(string xml) { PrepForProcessing(); ValidateXml(xml); MaybeThrowValidationException(); // deserialize as object model XmlSerializer xs = new XmlSerializer(typeof(QuartzXmlConfiguration20)); QuartzXmlConfiguration20 data = (QuartzXmlConfiguration20)xs.Deserialize(new StringReader(xml)); if (data == null) { throw new SchedulerConfigException("Job definition data from XML was null after deserialization"); } // // Extract pre-processing commands // if (data.preprocessingcommands != null) { foreach (preprocessingcommandsType command in data.preprocessingcommands) { if (command.deletejobsingroup != null) { foreach (string s in command.deletejobsingroup) { string deleteJobGroup = s.NullSafeTrim(); if (!String.IsNullOrEmpty(deleteJobGroup)) { jobGroupsToDelete.Add(deleteJobGroup); } } } if (command.deletetriggersingroup != null) { foreach (string s in command.deletetriggersingroup) { string deleteTriggerGroup = s.NullSafeTrim(); if (!String.IsNullOrEmpty(deleteTriggerGroup)) { triggerGroupsToDelete.Add(deleteTriggerGroup); } } } if (command.deletejob != null) { foreach (preprocessingcommandsTypeDeletejob s in command.deletejob) { string name = s.name.TrimEmptyToNull(); string group = s.group.TrimEmptyToNull(); if (name == null) { throw new SchedulerConfigException("Encountered a 'delete-job' command without a name specified."); } jobsToDelete.Add(new JobKey(name, group)); } } if (command.deletetrigger != null) { foreach (preprocessingcommandsTypeDeletetrigger s in command.deletetrigger) { string name = s.name.TrimEmptyToNull(); string group = s.group.TrimEmptyToNull(); if (name == null) { throw new SchedulerConfigException("Encountered a 'delete-trigger' command without a name specified."); } triggersToDelete.Add(new TriggerKey(name, group)); } } } } log.Debug("Found " + jobGroupsToDelete.Count + " delete job group commands."); log.Debug("Found " + triggerGroupsToDelete.Count + " delete trigger group commands."); log.Debug("Found " + jobsToDelete.Count + " delete job commands."); log.Debug("Found " + triggersToDelete.Count + " delete trigger commands."); // // Extract directives // if (data.processingdirectives != null && data.processingdirectives.Length > 0) { bool overWrite = data.processingdirectives[0].overwriteexistingdata; log.Debug("Directive 'overwrite-existing-data' specified as: " + overWrite); OverWriteExistingData = overWrite; } else { log.Debug("Directive 'ignore-duplicates' not specified, defaulting to " + OverWriteExistingData); } if (data.processingdirectives != null && data.processingdirectives.Length > 0) { bool ignoreduplicates = data.processingdirectives[0].ignoreduplicates; log.Debug("Directive 'ignore-duplicates' specified as: " + ignoreduplicates); IgnoreDuplicates = ignoreduplicates; } else { log.Debug("Directive 'overwrite-existing-data' not specified, defaulting to " + IgnoreDuplicates); } // // Extract Job definitions... // List <jobdetailType> jobNodes = new List <jobdetailType>(); if (data.schedule != null && data.schedule.Length > 0 && data.schedule[0].job != null) { jobNodes.AddRange(data.schedule[0].job); } log.Debug("Found " + jobNodes.Count + " job definitions."); foreach (jobdetailType jobDetailType in jobNodes) { string jobName = jobDetailType.name.TrimEmptyToNull(); string jobGroup = jobDetailType.group.TrimEmptyToNull(); string jobDescription = jobDetailType.description.TrimEmptyToNull(); string jobTypeName = jobDetailType.jobtype.TrimEmptyToNull(); bool jobDurability = jobDetailType.durable; bool jobRecoveryRequested = jobDetailType.recover; Type jobType = typeLoadHelper.LoadType(jobTypeName); IJobDetail jobDetail = JobBuilder.Create(jobType) .WithIdentity(jobName, jobGroup) .WithDescription(jobDescription) .StoreDurably(jobDurability) .RequestRecovery(jobRecoveryRequested) .Build(); if (jobDetailType.jobdatamap != null && jobDetailType.jobdatamap.entry != null) { foreach (entryType entry in jobDetailType.jobdatamap.entry) { string key = entry.key.TrimEmptyToNull(); string value = entry.value.TrimEmptyToNull(); jobDetail.JobDataMap.Add(key, value); } } if (log.IsDebugEnabled) { log.Debug("Parsed job definition: " + jobDetail); } AddJobToSchedule(jobDetail); } // // Extract Trigger definitions... // List <triggerType> triggerEntries = new List <triggerType>(); if (data.schedule != null && data.schedule.Length > 0 && data.schedule[0].trigger != null) { triggerEntries.AddRange(data.schedule[0].trigger); } log.Debug("Found " + triggerEntries.Count + " trigger definitions."); foreach (triggerType triggerNode in triggerEntries) { string triggerName = triggerNode.Item.name.TrimEmptyToNull(); string triggerGroup = triggerNode.Item.group.TrimEmptyToNull(); string triggerDescription = triggerNode.Item.description.TrimEmptyToNull(); string triggerCalendarRef = triggerNode.Item.calendarname.TrimEmptyToNull(); string triggerJobName = triggerNode.Item.jobname.TrimEmptyToNull(); string triggerJobGroup = triggerNode.Item.jobgroup.TrimEmptyToNull(); int triggerPriority = TriggerConstants.DefaultPriority; if (!triggerNode.Item.priority.IsNullOrWhiteSpace()) { triggerPriority = Convert.ToInt32(triggerNode.Item.priority); } DateTimeOffset triggerStartTime = SystemTime.UtcNow(); if (triggerNode.Item.Item != null) { if (triggerNode.Item.Item is DateTime) { triggerStartTime = new DateTimeOffset((DateTime)triggerNode.Item.Item); } else { triggerStartTime = triggerStartTime.AddSeconds(Convert.ToInt32(triggerNode.Item.Item)); } } DateTime?triggerEndTime = triggerNode.Item.endtimeSpecified ? triggerNode.Item.endtime : (DateTime?)null; IScheduleBuilder sched; if (triggerNode.Item is simpleTriggerType) { simpleTriggerType simpleTrigger = (simpleTriggerType)triggerNode.Item; string repeatCountString = simpleTrigger.repeatcount.TrimEmptyToNull(); string repeatIntervalString = simpleTrigger.repeatinterval.TrimEmptyToNull(); int repeatCount = ParseSimpleTriggerRepeatCount(repeatCountString); TimeSpan repeatInterval = repeatIntervalString == null ? TimeSpan.Zero : TimeSpan.FromMilliseconds(Convert.ToInt64(repeatIntervalString)); sched = SimpleScheduleBuilder.Create() .WithInterval(repeatInterval) .WithRepeatCount(repeatCount); if (!simpleTrigger.misfireinstruction.IsNullOrWhiteSpace()) { ((SimpleScheduleBuilder)sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(simpleTrigger.misfireinstruction)); } } else if (triggerNode.Item is cronTriggerType) { cronTriggerType cronTrigger = (cronTriggerType)triggerNode.Item; string cronExpression = cronTrigger.cronexpression.TrimEmptyToNull(); string timezoneString = cronTrigger.timezone.TrimEmptyToNull(); TimeZoneInfo tz = timezoneString != null?TimeZoneInfo.FindSystemTimeZoneById(timezoneString) : null; sched = CronScheduleBuilder.CronSchedule(cronExpression) .InTimeZone(tz); if (!cronTrigger.misfireinstruction.IsNullOrWhiteSpace()) { ((CronScheduleBuilder)sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(cronTrigger.misfireinstruction)); } } else if (triggerNode.Item is calendarIntervalTriggerType) { calendarIntervalTriggerType calendarIntervalTrigger = (calendarIntervalTriggerType)triggerNode.Item; string repeatIntervalString = calendarIntervalTrigger.repeatinterval.TrimEmptyToNull(); IntervalUnit intervalUnit = ParseDateIntervalTriggerIntervalUnit(calendarIntervalTrigger.repeatintervalunit.TrimEmptyToNull()); int repeatInterval = repeatIntervalString == null ? 0 : Convert.ToInt32(repeatIntervalString); sched = CalendarIntervalScheduleBuilder.Create() .WithInterval(repeatInterval, intervalUnit); if (!calendarIntervalTrigger.misfireinstruction.IsNullOrWhiteSpace()) { ((CalendarIntervalScheduleBuilder)sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(calendarIntervalTrigger.misfireinstruction)); } } else { throw new SchedulerConfigException("Unknown trigger type in XML configuration"); } IMutableTrigger trigger = (IMutableTrigger)TriggerBuilder.Create() .WithIdentity(triggerName, triggerGroup) .WithDescription(triggerDescription) .ForJob(triggerJobName, triggerJobGroup) .StartAt(triggerStartTime) .EndAt(triggerEndTime) .WithPriority(triggerPriority) .ModifiedByCalendar(triggerCalendarRef) .WithSchedule(sched) .Build(); if (triggerNode.Item.jobdatamap != null && triggerNode.Item.jobdatamap.entry != null) { foreach (entryType entry in triggerNode.Item.jobdatamap.entry) { string key = entry.key.TrimEmptyToNull(); string value = entry.value.TrimEmptyToNull(); trigger.JobDataMap.Add(key, value); } } if (log.IsDebugEnabled) { log.Debug("Parsed trigger definition: " + trigger); } AddTriggerToSchedule(trigger); } }
public void Publish(IntegrationEvent @event, string brokerName, string routingKey, string typeOfExchange) { try { if (!_persistentConnection.IsConnected) { _persistentConnection.TryConnect(); _logger.Info("\nDate:" + DateTime.UtcNow + "\nMethodName:" + "TryConnect" + ", Controllername: " + "Publish" + "\nAccessToken: " + "\nRequest: " + "RabbitMq Sucessfully Connected...." + "\n==================================================================================================================="); } else { using (var channel = _persistentConnection.CreateModel()) { var eventName = @event.GetType().Name; channel.ExchangeDeclare(exchange: brokerName, type: typeOfExchange, true); var message = JsonConvert.SerializeObject(@event); var body = Encoding.UTF8.GetBytes(message); var properties = channel.CreateBasicProperties(); properties.DeliveryMode = 2; // persistent channel.BasicPublish(exchange: brokerName, routingKey: routingKey, mandatory: true, basicProperties: properties, body: body); _logger.Info("\nDate:" + DateTime.UtcNow + "\nMethodName:" + "BasicPublish" + ", Controllername: " + "Publish" + "\nAccessToken: " + "\nRequest: " + eventName + " Published..." + "\n==================================================================================================================="); } } } catch (Exception ex) { _logger.Error("\nDate:" + TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time")) + "\nMethodName:" + "Publish" + ",Controllername: " + "RabitMQEventBus" + "\nError: " + ex.Message + "\nOtherInfo:" + "==================================================================================================================="); } }
public ActionResult Meeting(string identifier) { var token = JObject.Parse(ConfigurationManager.AppSettings["TokenFilePath"]); RestClient restClient = new RestClient(); RestRequest restRequest = new RestRequest(); restRequest.AddHeader("Authorization", "Bearer " + token["access_token"]); restClient.BaseUrl = new Uri($"https://api.zoom.us/v2/meetings/{identifier}"); var response = restClient.Get(restRequest); if (response.StatusCode == System.Net.HttpStatusCode.OK) { var zoomMeeting = JObject.Parse(response.Content).ToObject <ZoomMeeting>(); zoomMeeting.Start_Time = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(zoomMeeting.Start_Time.Ticks, DateTimeKind.Unspecified), TimeZoneInfo.FindSystemTimeZoneById("India Standard Time")); return(View(zoomMeeting)); } return(View("Error")); }
static void InitializeAnnual(AnnualCalendar annualCalendar, IAnnualCalendar calendar) { annualCalendar.TimeZone = TimeZoneInfo.FindSystemTimeZoneById(Persistent.Base.General.RegistryTimeZoneProvider.GetRegistryKeyNameByTimeZoneId(calendar.TimeZone)); calendar.DatesExcluded.ForEach(time => annualCalendar.SetDayExcluded(time, true)); calendar.DatesIncluded.ForEach(time => annualCalendar.SetDayExcluded(time, false)); }
public void AddEventToDatabase(SmsRequest incomingMessage) { bool badDate = false; bool unknownGroup = false; bool badFormat = false; bool unknownUser = false; try { UserInfo userInfo = _context.UserInfo.Where(x => x.PhoneNumber == incomingMessage.From).First(); if (userInfo == null) { unknownUser = true; throw new Exception(); } AspNetUsers user = _context.AspNetUsers.Where(x => x.Id == userInfo.UserId).First(); StringReader reader = new StringReader(incomingMessage.Body); string line = reader.ReadLine(); List <string> textParts = new List <string>(); while (line != null) { textParts.Add(line); line = reader.ReadLine(); } string eventName = textParts[0]; //Date Time Format: ("MM/dd/yyyy h:mm tt") (05/29/2015 5:50 AM) DateTime eventDateTime = DateTime.Parse(textParts[1]); string eventVenue = textParts[2]; string eventLoc = textParts[3]; string groupName = textParts[4]; //list of user's groups List <Groups> userGroups = _context.Groups.Where(x => x.UserId == user.Id).ToList(); //list of group names List <string> groupNames = new List <string>(); foreach (var u in userGroups) { groupNames.Add(u.GroupName); } TimeZoneInfo myTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); DateTime currentDateTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, myTimeZone); //exception handling! if (eventDateTime.CompareTo(currentDateTime) < 1) { badDate = true; throw new Exception(); } else if (!groupNames.Contains(groupName)) { unknownGroup = true; throw new Exception(); } else if (textParts.Count != 5) { badFormat = true; throw new Exception(); } Groups group = _context.Groups.Where(x => x.GroupName == groupName).First(); EventTable newEvent = new EventTable(eventName, "Description", group.GroupId, eventDateTime, eventVenue, eventLoc, user.Id, group.GroupName, eventDateTime); _context.EventTable.Add(newEvent); _context.SaveChanges(); //Code for sending group text List <GroupMembers> groupMembers = _context.GroupMembers.Where(x => x.Groups == group.GroupId).ToList(); EventTable tempEvent = _context.EventTable.Where(x => x.EventName == eventName).Where(x => x.GroupId == group.GroupId).First(); foreach (var g in groupMembers) { SendText($"Hi, {g.MemberName}! {userInfo.FirstName} just invited you to {eventName} on {eventDateTime.ToShortDateString()} at {eventVenue}, {eventLoc}. Respond with 'yes {tempEvent.EventId}' if you accept, and 'no {tempEvent.EventId}' if you decline.", g.PhoneNumber); } SendSuccessText(incomingMessage, $"You just created the event {eventName}! Reminders to everyone in {group.GroupName} are on the way."); } catch (Exception) { if (badDate) { SendErrorText(incomingMessage, "The date you entered is too early."); } else if (badFormat) { SendErrorText(incomingMessage, "The format you entered is incorrect."); } else if (unknownGroup) { SendErrorText(incomingMessage, "That group doesn't exist."); } else if (unknownUser) { SendRegisterText(incomingMessage); } else { SendErrorText(incomingMessage, null); } } }
static void InitializeDaily(DailyCalendar dailyCalendar, IDailyCalendar calendar) { dailyCalendar.TimeZone = TimeZoneInfo.FindSystemTimeZoneById(Persistent.Base.General.RegistryTimeZoneProvider.GetRegistryKeyNameByTimeZoneId(calendar.TimeZone)); calendar.DateRanges.ToList().ForEach(range => dailyCalendar.SetTimeRange(range.StartPoint, range.EndPoint)); }
static void InitializeWeekly(WeeklyCalendar weeklyCalendar, IWeeklyCalendar calendar) { weeklyCalendar.TimeZone = TimeZoneInfo.FindSystemTimeZoneById(Persistent.Base.General.RegistryTimeZoneProvider.GetRegistryKeyNameByTimeZoneId(calendar.TimeZone)); calendar.DaysOfWeekExcluded.ForEach(week => weeklyCalendar.SetDayExcluded(week, true)); calendar.DaysOfWeekIncluded.ForEach(week => weeklyCalendar.SetDayExcluded(week, false)); }
public IEnumerable <EventDetails> GetEventSchedules(int year, int month, int date, int crewid) { try { //int crewid = 3; DateTime selectedDate = new DateTime(year, month, date); DateTime from = GetFirstDayOfWeek(selectedDate, null); List <EventDetails> eventDetails = new List <EventDetails>(); var service = new EventService(); var eventSchedules = service.GetEventsForCrewForDay(from, crewid); foreach (var eventVal in eventSchedules) { EventTaskList propTask = db.EventTaskLists.Include("Crew").Include("Property").Include("EventTaskTimes").Single(pt => pt.Id == eventVal.EventTaskListId); if (propTask.Crew == null) { continue; } Crew crewVal = propTask.Crew; if (crewVal == null) { continue; } if (!string.IsNullOrEmpty(eventVal.RecurrenceRule)) { var pattern = new RecurrencePattern(eventVal.RecurrenceRule); var evaluator = new RecurrencePatternEvaluator(pattern); var items = evaluator.Evaluate(new CalDateTime(eventVal.StartTime), eventVal.StartTime, eventVal.StartTime.AddYears(5), false); if (!items.Any(i => i.StartTime.Date == selectedDate)) { continue; } } else { if (eventVal.StartTime.AddDays(-1) > selectedDate || eventVal.EndTime < selectedDate) { continue; } } EventDetails eventDetail = new EventDetails(); TimeZoneInfo estZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); eventDetail.EventId = eventVal.Id; eventDetail.StartTime = TimeZoneInfo.ConvertTimeFromUtc(eventVal.StartTime, estZone); eventDetail.EndTime = TimeZoneInfo.ConvertTimeFromUtc(eventVal.EndTime, estZone); eventDetail.ActualEndTime = eventVal.ActualEndTime; eventDetail.ActualStartTime = eventVal.ActualStartTime; eventDetail.IsAllDay = eventVal.IsAllDay; eventDetail.RecurrenceRule = eventVal.RecurrenceRule; eventDetail.RecurrenceID = eventVal.RecurrenceID; eventDetail.RecurrenceException = eventVal.RecurrenceException; eventDetail.StartTimezone = eventVal.StartTimezone; eventDetail.EndTimezone = eventVal.EndTimezone; eventDetail.Status = (StatusEnum)eventVal.Status; eventDetail.Title = eventVal.Title; eventVal.EventTaskList = propTask; eventDetail.TaskId = propTask.Id; eventDetail.EventTaskListId = eventVal.EventTaskListId; eventDetail.PropertyId = propTask.Property.Id; eventDetail.PropertyAddress = propTask.Property.Address1 + " " + propTask.Property.Address2 + " " + propTask.Property.City.Name + " " + propTask.Property.State + " " + propTask.Property.Zip; eventDetail.PropertyName = eventVal.EventTaskList.Property.Name; eventDetail.PropertyRefNumber = eventVal.EventTaskList.Property.PropertyRefNumber; var eventTaskTime = propTask.EventTaskTimes.FirstOrDefault(e => e.EventDate.Subtract(selectedDate) == TimeSpan.Zero); if (eventTaskTime != null) { eventDetail.TaskStartTime = eventTaskTime.StartTime; eventDetail.TaskEndTime = eventTaskTime.EndTime; } eventDetails.Add(eventDetail); } return(eventDetails.OrderBy(e => e.StartTime)); } catch (Exception ex) { throw ex; } }
public ActionResult Disapprove(Requerimiento requerimiento) { var errors = ModelState.Values.SelectMany(v => v.Errors); Requerimiento Requerimiento = db.Requerimientos.Find(requerimiento.requerimientoId); DateTime timeUtc = DateTime.UtcNow; TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"); DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, cstZone); var estado = db.EstadoRequerimiento.Where(p => p.nombre == "Aprobación Rechazada").SingleOrDefault();; var estadoDetalle = db.EstadoRequerimientoDetalle.Where(p => p.nombre == "Aprobación Rechazada").SingleOrDefault(); var estadoList = new string[] { "Sin Aprobación", "Aprobación Rechazada" }; if (Requerimiento.Detalles.Where(p => estadoList.Contains(p.EstadoRequerimientoDetalle.nombre)).Count() != requerimiento.Detalles.Count()) { //if (Requerimiento.EstadoRequerimiento.nombre != "Aprobado Parcial") //{ estado = db.EstadoRequerimiento.Where(p => p.nombre == "Rechazado Parcial").SingleOrDefault(); //} } Requerimiento.estadoRequerimientoId = estadoDetalle.estadoRequerimientoDetalleId; var requerimientoEstado = new RequerimientoEstadoRequerimiento(); var requerimientoDetalleEstado = new RequerimientoDetalleEstadoRequerimientoDetalle(); requerimientoEstado.Requerimiento = Requerimiento; requerimientoEstado.requerimientoId = requerimiento.requerimientoId; requerimientoEstado.estadoRequerimientoId = estado.estadoRequerimientoId; requerimientoEstado.usuarioCreacion = User.Identity.Name; requerimientoEstado.fechaCreacion = cstTime; Requerimiento.estadoRequerimientoId = estado.estadoRequerimientoId; //Actualiza datos en Requerimiento requerimientoEstado.Requerimiento.estadoRequerimientoId = estado.estadoRequerimientoId; requerimientoEstado.Requerimiento.usuarioModificacion = User.Identity.Name; requerimientoEstado.Requerimiento.fechaModificacion = cstTime; db.RequerimientoEstadoRequerimiento.Add(requerimientoEstado); foreach (var item in requerimiento.Detalles) { var requerimientoDetalleEstadoRequerimientoDetalle = new RequerimientoDetalleEstadoRequerimientoDetalle(); requerimientoDetalleEstadoRequerimientoDetalle.requerimientoDetalleId = item.requerimientoDetalleId; requerimientoDetalleEstadoRequerimientoDetalle.estadoRequerimientoDetalleId = estadoDetalle.estadoRequerimientoDetalleId; requerimientoDetalleEstadoRequerimientoDetalle.usuarioCreacion = User.Identity.Name; requerimientoDetalleEstadoRequerimientoDetalle.fechaCreacion = cstTime; RequerimientoDetalle RequerimientoDetalle = db.RequerimientoDetalles.Find(item.requerimientoDetalleId); RequerimientoDetalle.estadoRequerimientoDetalleId = estadoDetalle.estadoRequerimientoDetalleId; requerimientoDetalleEstadoRequerimientoDetalle.RequerimientoDetalle = RequerimientoDetalle; db.RequerimientoDetalleEstadoRequerimientoDetalle.Add(requerimientoDetalleEstadoRequerimientoDetalle); } try { db.SaveChanges(); } catch (DbEntityValidationException ex) { StringBuilder sb = new StringBuilder(); foreach (var failure in ex.EntityValidationErrors) { sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType()); foreach (var error in failure.ValidationErrors) { sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage); sb.AppendLine(); } } throw new DbEntityValidationException( "Entity Validation Failed - errors follow:\n" + sb.ToString(), ex ); } return(RedirectToAction("IndexApprove")); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IBackgroundJobClient backgroundJobClient, IRecurringJobManager recurringJobManager, IServiceProvider serviceProvider) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // To Enable CORS app.UseCors(builder => builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); app.UseHttpsRedirection(); app.UseHsts(h => h.MaxAge(days: 365).IncludeSubdomains().Preload()); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "UAEGLP"); }); app.UseHangfireDashboard(); //app.UseFileServer(new FileServerOptions() //{ // FileProvider = new PhysicalFileProvider( // Path.Combine(Directory.GetCurrentDirectory(), @".well-known")), // RequestPath = new PathString("/.well-known"), // EnableDirectoryBrowsing = true, //}); //app.UseRewriter(new RewriteOptions() // .AddRewrite("(.*)/apple-app-site-association", "$1/apple-app-site-association.json", true)); app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), @".well-known")), RequestPath = new PathString("/.well-known"), ServeUnknownFileTypes = true, DefaultContentType = "text/plain" }); app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), @"Redirection")), RequestPath = new PathString("/Redirection"), ServeUnknownFileTypes = true, DefaultContentType = "text/plain" }); // app.UseStaticFiles(new StaticFileOptions // { // FileProvider = new PhysicalFileProvider( //Path.Combine(env.WebRootPath, "images")), // RequestPath = "/MyImages" // }); app.UseDirectoryBrowser(new DirectoryBrowserOptions { FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), @"Redirection")), RequestPath = new PathString("/Redirection") }); app.UseDirectoryBrowser(new DirectoryBrowserOptions { FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), @".well-known")), RequestPath = new PathString("/.well-known") }); recurringJobManager.AddOrUpdate( "Running job every day once", () => serviceProvider.GetService <IReminderService>().SendReminder(), Cron.Daily(9, 0), TimeZoneInfo.FindSystemTimeZoneById("India Standard Time") ); recurringJobManager.AddOrUpdate( "Custom Notification Like", () => serviceProvider.GetService <IWebPortalNotificationService>().PostLikeNotification(), "*/10 * * * * *", TimeZoneInfo.FindSystemTimeZoneById("India Standard Time") ); recurringJobManager.AddOrUpdate( "Custom Notification Comment", () => serviceProvider.GetService <IWebPortalNotificationService>().PostCommentNotification(), "*/10 * * * * *", TimeZoneInfo.FindSystemTimeZoneById("India Standard Time") ); recurringJobManager.AddOrUpdate( "Custom Notification Share", () => serviceProvider.GetService <IWebPortalNotificationService>().PostShareNotification(), "*/10 * * * * *", TimeZoneInfo.FindSystemTimeZoneById("India Standard Time") ); recurringJobManager.AddOrUpdate( "Custom Notification Activity", () => serviceProvider.GetService <IWebPortalNotificationService>().ActivityAndChallengeNotification(), "*/10 * * * * *", TimeZoneInfo.FindSystemTimeZoneById("India Standard Time") ); recurringJobManager.AddOrUpdate( "Custom Notification Program", () => serviceProvider.GetService <IWebPortalNotificationService>().ProgrammeNotification(), "*/10 * * * * *", TimeZoneInfo.FindSystemTimeZoneById("India Standard Time") ); recurringJobManager.AddOrUpdate( "Custom Notification Batch", () => serviceProvider.GetService <IWebPortalNotificationService>().BatchNotification(), "*/10 * * * * *", TimeZoneInfo.FindSystemTimeZoneById("India Standard Time") ); recurringJobManager.AddOrUpdate( "Custom Notification Following", () => serviceProvider.GetService <IWebPortalNotificationService>().UserFollowingNotification(), "*/10 * * * * *", TimeZoneInfo.FindSystemTimeZoneById("India Standard Time") ); recurringJobManager.AddOrUpdate( "Custom Notification Network", () => serviceProvider.GetService <IWebPortalNotificationService>().NetworkGroupNotification(), "*/10 * * * * *", TimeZoneInfo.FindSystemTimeZoneById("India Standard Time") ); recurringJobManager.AddOrUpdate( "Custom Notification AssignedAssessment", () => serviceProvider.GetService <IWebPortalNotificationService>().AssessmentAssignedNotification(), "*/10 * * * * *", TimeZoneInfo.FindSystemTimeZoneById("India Standard Time") ); recurringJobManager.AddOrUpdate( "Custom Notification AssessmentMember", () => serviceProvider.GetService <IWebPortalNotificationService>().AssessmentMemberNotification(), "*/10 * * * * *", TimeZoneInfo.FindSystemTimeZoneById("India Standard Time") ); recurringJobManager.AddOrUpdate( "Custom Notification Meetup", () => serviceProvider.GetService <IWebPortalNotificationService>().MeetupNotification(), "*/10 * * * * *", TimeZoneInfo.FindSystemTimeZoneById("India Standard Time") ); recurringJobManager.AddOrUpdate( "Custom Notification Messaging", () => serviceProvider.GetService <IWebPortalNotificationService>().MessagingNotification(), "*/10 * * * * *", TimeZoneInfo.FindSystemTimeZoneById("India Standard Time") ); recurringJobManager.AddOrUpdate( "Custom Notification Events", () => serviceProvider.GetService <IWebPortalNotificationService>().EventNotification(), "*/10 * * * * *", TimeZoneInfo.FindSystemTimeZoneById("India Standard Time") ); recurringJobManager.AddOrUpdate( "Custom Notification EngagementActiity", () => serviceProvider.GetService <IWebPortalNotificationService>().EngagementActiity(), "*/10 * * * * *", TimeZoneInfo.FindSystemTimeZoneById("India Standard Time") ); RotativaConfiguration.Setup((Microsoft.AspNetCore.Hosting.IHostingEnvironment)env); }
public ActionResult UploadPart1(UploadSessionVM model) { // Check we have a valid user var user = _authRepository.GetUserAccount(User.Identity.GetUserId()); if (user == null) { HttpContext.GetOwinContext().Authentication.SignOut(); return(RedirectToAction("Index", "Home")); } if (ModelState.IsValid) { // Generate an upload token and make sure it's not in use while (true) { model.UploadToken = AuthEncryption.RandomFilename(); _logger.Debug(string.Format("Checking to see if session token {0} has been used before", model.UploadToken)); if (!_sessionLogRepository.SessionLogTokenExists(model.UploadToken)) { _logger.Debug("Token wasn't found, so inserting a new session with it now."); break; } _logger.Debug(string.Format("Found an existing log with the token {0} - generating a new one.", model.UploadToken)); } TimeSpan utcOffset = TimeZoneInfo.FindSystemTimeZoneById(user.TimeZone).GetUtcOffset(DateTime.UtcNow); var result = _sessionRepository.CreateSession(User.Identity.GetUserId(), new Session() { AuthUserCharacterId = model.UploadCharacterId, Date = model.SessionDate.Subtract(utcOffset), Name = model.Name, EncountersPublic = model.Public }); if (result.Success) { int sessionId = int.Parse(result.Message); model.UploadedSessionId = sessionId; // Add this session to the SessionLog table in case other guild members or this user choose to upload additional logs to the session var guildId = _authUserCharacterRepository.GetGuildIdForCharacter(model.UploadCharacterId); if (guildId > 0) { var newSessionLog = new SessionLog() { AuthUserCharacterId = model.UploadCharacterId, Filename = model.UploadToken + ".zip", Token = model.UploadToken, GuildId = guildId, LogSize = 0, SessionId = sessionId, TotalPlayedTime = 0 }; var returnValue = _sessionLogRepository.Create(newSessionLog); } return(UploadPart2(model)); } ModelState.AddModelError("", result.Message); } //var user = _authRepository.GetUserAccount(User.Identity.GetUserId()); var userCharacters = _authUserCharacterRepository.GetUploaders(user.Email); model.Characters = userCharacters; return(View(model)); }
public ActionResult UploadFileTruckDriverDoc(FileDetail fileUpload) { DateTime dateTime = DateTime.UtcNow; var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("SE Asia Standard Time"); var convertedTime = TimeZoneInfo.ConvertTime(dateTime, timeZoneInfo); if (ModelState.IsValid) { List <FileDetail> fileDetails = new List <FileDetail>(); for (var i = 0; i < Request.Files.Count; i++) { var file = Request.Files[i]; if (file != null && file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); FileDetail fileDetail = new FileDetail() { FileName = fileName, Extension = Path.GetExtension(fileName), FileId = Guid.NewGuid(), FileCategory = fileUpload.FileCategory, LastModified = convertedTime }; if (fileDetail.Extension == ".pdf") { fileDetails.Add(fileDetail); var path = Path.Combine(Server.MapPath("~/App_Data/Upload/"), fileDetail.FileId + fileDetail.Extension); file.SaveAs(path); var findTruckDriverDocAndTruckDriverById = _truckDriverDocRepository.GetTruckDriverDocAndTruckDriverById(fileUpload.TruckDriverDocId); if (findTruckDriverDocAndTruckDriverById != null) { findTruckDriverDocAndTruckDriverById.FileDetails = fileDetails; bool addFileDetail = _truckDriverDocRepository.AddFileDetails(fileDetail); if (addFileDetail.Equals(true)) { _truckDriverDocRepository.SaveChanges(); var listFilesByTruckDriverDocId = _truckDriverDocRepository.ListFilesByTruckDriverDocId(fileUpload.TruckDriverDocId); ListFileTruckDriverDocViewModel listFileTruckDriverDoc = new ListFileTruckDriverDocViewModel { TruckDriverDocument = findTruckDriverDocAndTruckDriverById, FileDetails = listFilesByTruckDriverDocId }; return(View("ListFilesTruckDriverDoc", listFileTruckDriverDoc)); } } } ViewBag.Message = "Please, upload PDF File Only"; return(View("UploadFileTruckDriverDocView", fileUpload)); } } return(View("UploadFileTruckDriverDocView", fileUpload)); } return(View("UploadFileTruckDriverDocView", fileUpload)); }
public override object Deserialize(TextReader tr) { string value = tr.ReadToEnd(); // Instantiate the data type IRecurrencePattern r = CreateAndAssociate() as IRecurrencePattern; ISerializerFactory factory = GetService <ISerializerFactory>(); if (r != null && factory != null) { // Decode the value, if necessary value = Decode(r, value); Match match = Regex.Match(value, @"FREQ=(SECONDLY|MINUTELY|HOURLY|DAILY|WEEKLY|MONTHLY|YEARLY);?(.*)", RegexOptions.IgnoreCase); if (match.Success) { // Parse the frequency type r.Frequency = (FrequencyType)Enum.Parse(typeof(FrequencyType), match.Groups[1].Value, true); // NOTE: fixed a bug where the group 2 match // resulted in an empty string, which caused // an error. if (match.Groups[2].Success && match.Groups[2].Length > 0) { string[] keywordPairs = match.Groups[2].Value.Split(';'); foreach (string keywordPair in keywordPairs) { string[] keyValues = keywordPair.Split('='); string keyword = keyValues[0]; string keyValue = keyValues[1]; switch (keyword.ToUpper()) { case "UNTIL": { IStringSerializer serializer = factory.Build(typeof(IDateTime), SerializationContext) as IStringSerializer; if (serializer != null) { IDateTime dt = serializer.Deserialize(new StringReader(keyValue)) as IDateTime; if (dt != null) { TimeZoneInfo timeZoneInfo = null; if (r.Calendar != null && r.Calendar.TimeZones.Any()) { var tzId = r.Calendar.TimeZones.First().TZID; if (TimeZoneMap.DefaultValuesTZMapper.GetAvailableTZIDs().Contains(tzId)) { timeZoneInfo = TimeZoneMap.DefaultValuesTZMapper.MapTZID(tzId); } else if (TimeZoneInfo.GetSystemTimeZones().Any(x => x.StandardName == tzId)) { timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(tzId); } } r.Until = timeZoneInfo == null ? dt.Value : TimeZoneInfo.ConvertTimeFromUtc(dt.Value, timeZoneInfo); } } } break; case "COUNT": r.Count = Convert.ToInt32(keyValue); break; case "INTERVAL": r.Interval = Convert.ToInt32(keyValue); break; case "BYSECOND": AddInt32Values(r.BySecond, keyValue); break; case "BYMINUTE": AddInt32Values(r.ByMinute, keyValue); break; case "BYHOUR": AddInt32Values(r.ByHour, keyValue); break; case "BYDAY": { string[] days = keyValue.Split(','); foreach (string day in days) { r.ByDay.Add(new WeekDay(day)); } } break; case "BYMONTHDAY": AddInt32Values(r.ByMonthDay, keyValue); break; case "BYYEARDAY": AddInt32Values(r.ByYearDay, keyValue); break; case "BYWEEKNO": AddInt32Values(r.ByWeekNo, keyValue); break; case "BYMONTH": AddInt32Values(r.ByMonth, keyValue); break; case "BYSETPOS": AddInt32Values(r.BySetPosition, keyValue); break; case "WKST": r.FirstDayOfWeek = GetDayOfWeek(keyValue); break; } } } } // // This matches strings such as: // // "Every 6 minutes" // "Every 3 days" // else if ((match = Regex.Match(value, @"every\s+(?<Interval>other|\d+)?\w{0,2}\s*(?<Freq>second|minute|hour|day|week|month|year)s?,?\s*(?<More>.+)", RegexOptions.IgnoreCase)).Success) { if (match.Groups["Interval"].Success) { int interval; if (!int.TryParse(match.Groups["Interval"].Value, out interval)) { r.Interval = 2; // "other" } else { r.Interval = interval; } } else { r.Interval = 1; } switch (match.Groups["Freq"].Value.ToLower()) { case "second": r.Frequency = FrequencyType.Secondly; break; case "minute": r.Frequency = FrequencyType.Minutely; break; case "hour": r.Frequency = FrequencyType.Hourly; break; case "day": r.Frequency = FrequencyType.Daily; break; case "week": r.Frequency = FrequencyType.Weekly; break; case "month": r.Frequency = FrequencyType.Monthly; break; case "year": r.Frequency = FrequencyType.Yearly; break; } string[] values = match.Groups["More"].Value.Split(','); foreach (string item in values) { if ((match = Regex.Match(item, @"(?<Num>\d+)\w\w\s+(?<Type>second|minute|hour|day|week|month)", RegexOptions.IgnoreCase)).Success || (match = Regex.Match(item, @"(?<Type>second|minute|hour|day|week|month)\s+(?<Num>\d+)", RegexOptions.IgnoreCase)).Success) { int num; if (int.TryParse(match.Groups["Num"].Value, out num)) { switch (match.Groups["Type"].Value.ToLower()) { case "second": r.BySecond.Add(num); break; case "minute": r.ByMinute.Add(num); break; case "hour": r.ByHour.Add(num); break; case "day": switch (r.Frequency) { case FrequencyType.Yearly: r.ByYearDay.Add(num); break; case FrequencyType.Monthly: r.ByMonthDay.Add(num); break; } break; case "week": r.ByWeekNo.Add(num); break; case "month": r.ByMonth.Add(num); break; } } } else if ((match = Regex.Match(item, @"(?<Num>\d+\w{0,2})?(\w|\s)+?(?<First>first)?(?<Last>last)?\s*((?<Day>sunday|monday|tuesday|wednesday|thursday|friday|saturday)\s*(and|or)?\s*)+", RegexOptions.IgnoreCase)).Success) { int num = int.MinValue; if (match.Groups["Num"].Success) { if (int.TryParse(match.Groups["Num"].Value, out num)) { if (match.Groups["Last"].Success) { // Make number negative num *= -1; } } } else if (match.Groups["Last"].Success) { num = -1; } else if (match.Groups["First"].Success) { num = 1; } foreach (Capture capture in match.Groups["Day"].Captures) { WeekDay ds = new WeekDay((DayOfWeek)Enum.Parse(typeof(DayOfWeek), capture.Value, true)); ds.Offset = num; r.ByDay.Add(ds); } } else if ((match = Regex.Match(item, @"at\s+(?<Hour>\d{1,2})(:(?<Minute>\d{2})((:|\.)(?<Second>\d{2}))?)?\s*(?<Meridian>(a|p)m?)?", RegexOptions.IgnoreCase)).Success) { int hour, minute, second; if (int.TryParse(match.Groups["Hour"].Value, out hour)) { // Adjust for PM if (match.Groups["Meridian"].Success && match.Groups["Meridian"].Value.ToUpper().StartsWith("P")) { hour += 12; } r.ByHour.Add(hour); if (match.Groups["Minute"].Success && int.TryParse(match.Groups["Minute"].Value, out minute)) { r.ByMinute.Add(minute); if (match.Groups["Second"].Success && int.TryParse(match.Groups["Second"].Value, out second)) { r.BySecond.Add(second); } } } } else if ((match = Regex.Match(item, @"^\s*until\s+(?<DateTime>.+)$", RegexOptions.IgnoreCase)).Success) { DateTime dt = DateTime.Parse(match.Groups["DateTime"].Value); DateTime.SpecifyKind(dt, DateTimeKind.Utc); r.Until = dt; } else if ((match = Regex.Match(item, @"^\s*for\s+(?<Count>\d+)\s+occurrences\s*$", RegexOptions.IgnoreCase)).Success) { int count; if (!int.TryParse(match.Groups["Count"].Value, out count)) { return(false); } else { r.Count = count; } } } } else { // Couldn't parse the object, return null! r = null; } if (r != null) { CheckMutuallyExclusive("COUNT", "UNTIL", r.Count, r.Until); CheckRange("INTERVAL", r.Interval, 0, int.MaxValue); CheckRange("COUNT", r.Count, 0, int.MaxValue); CheckRange("BYSECOND", r.BySecond, 0, 59); CheckRange("BYMINUTE", r.ByMinute, 0, 59); CheckRange("BYHOUR", r.ByHour, 0, 23); CheckRange("BYMONTHDAY", r.ByMonthDay, -31, 31); CheckRange("BYYEARDAY", r.ByYearDay, -366, 366); CheckRange("BYWEEKNO", r.ByWeekNo, -53, 53); CheckRange("BYMONTH", r.ByMonth, 1, 12); CheckRange("BYSETPOS", r.BySetPosition, -366, 366); } } return(r); }
public static DateTime ToUtcTime(this DateTime dt) { var tzi = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); return(TimeZoneInfo.ConvertTimeToUtc(dt, tzi)); }
public async Task <bool> RemindAsync(string tenant, ReminderMessage message) { await Task.Delay(0).ConfigureAwait(false); string sendTo = message.Contact.EmailAddresses; string timezone = message.Contact.TimeZone.Or(message.Event.TimeZone); if (string.IsNullOrWhiteSpace(sendTo)) { return(false); } int alarm = message.Event.Alarm ?? 0; if (alarm == 0) { return(false); } string template = Configs.GetNotificationEmailTemplate(tenant); string eventDate = TimeZoneInfo.ConvertTime(DateTime.UtcNow.AddMinutes(alarm), TimeZoneInfo.FindSystemTimeZoneById(timezone)).Date.ToString("D"); string startTime = TimeZoneInfo.ConvertTime(message.Event.StartsAt, TimeZoneInfo.FindSystemTimeZoneById(timezone)).ToString("t"); string endTime = TimeZoneInfo.ConvertTime(message.Event.EndsOn, TimeZoneInfo.FindSystemTimeZoneById(timezone)).ToString("t"); template = template.Replace("{Name}", message.Event.Name); template = template.Replace("{StartTime}", startTime); template = template.Replace("{EndTime}", endTime); template = template.Replace("{Date}", eventDate); template = template.Replace("{Location}", message.Event.Location); template = template.Replace("{Note}", message.Event.Note); var processor = EmailProcessor.GetDefault(tenant); if (processor == null) { return(false); } var email = new EmailQueue { AddedOn = DateTimeOffset.UtcNow, SendOn = DateTimeOffset.UtcNow, SendTo = sendTo, FromName = processor.Config.FromName, ReplyTo = processor.Config.FromEmail, ReplyToName = processor.Config.FromName, Subject = string.Format(I18N.CalendarNotificationEmailSubject, message.Event.Name, startTime), Message = template }; var manager = new MailQueueManager(tenant, email); await manager.AddAsync().ConfigureAwait(false); await manager.ProcessQueueAsync(processor).ConfigureAwait(false); return(true); }
public async Task <IActionResult> Post([FromBody] OrderViewModel value) { try { if (value.TimeSlots == null || value.TimeSlots.Count < 1) { throw new AppException("You have not chosen any timesheets to book. " + "Please go back and select timeslots for this engineer"); } var customer = _mapper.Map <CustomerAccount>(value.Customer); var job = _mapper.Map <Job>(value.Job); var tz = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); //adjust from UTC to EST value.TimeSlots.ForEach( x => { x.BeginDatetime = TimeZoneInfo.ConvertTimeFromUtc(x.BeginDatetime, tz); x.EndDatetime = TimeZoneInfo.ConvertTimeFromUtc(x.EndDatetime, tz); } ); var timeslots = _mapper.Map <List <TimeSlot> >(value.TimeSlots); //create or return existing customer customer = _customers.Add(customer); //create or return job job.CustomerId = customer.CustomerId; job = _jobs.Add(job); //create the order entity var order = new Order(); order.JobID = job.JobId; order.HasPaid = false; order.Signature = value.Signature; order.TimeSlots = timeslots; //add to persistance store //convert return model into viewmodel for further processing var added = RefreshViewModel( _orders.Add(order) ); //TODO: Port the emails to a queue based solution //create and send invoice string body = await _razor.RenderViewToStringAsync("/Email/Templates/Invoice.cshtml", added); _email.SendMail(new List <string>() { customer.Email }, new List <string>(), new List <string>() { _BccEmail }, _invoiceSubject, body); return(StatusCode((int)HttpStatusCode.Created, added)); } catch (AppException ex) { return(StatusCode((int)HttpStatusCode.UnprocessableEntity, new AppException(ex.Message))); } catch (Exception ex) { return(StatusCode((int)HttpStatusCode.BadRequest, new AppException(ex.Message))); } }
static void InitializeCron(CronCalendar cronCalendar, ICronCalendar calendar) { cronCalendar.TimeZone = TimeZoneInfo.FindSystemTimeZoneById(Persistent.Base.General.RegistryTimeZoneProvider.GetRegistryKeyNameByTimeZoneId(calendar.TimeZone)); cronCalendar.CronExpression = new CronExpression(calendar.CronExpression); }
private void radButton5_Click(object sender, EventArgs e) { if (this.txtRemarks.Text.Length < 40) { int num1 = (int)RadMessageBox.Show("Your request must be at least 40 characters long."); } else { this.txtTitle.Text = this.txtTitle.Text.Trim(); this.txtRemarks.Text = this.txtRemarks.Text.Trim(); this.txtEmail.Text = this.txtEmail.Text.Trim(); string str1 = this.chkSyslog.Checked ? GClass6.smethod_18() : "No data provided"; if (this.txtTitle.Text == "") { int num2 = (int)RadMessageBox.Show("Please provide a short description of the issue."); } else if (this.txtRemarks.Text.Length < 40) { int num3 = (int)RadMessageBox.Show("Your request must be at least 40 characters long."); } else if (!this.method_1(this.txtEmail.Text)) { int num4 = (int)RadMessageBox.Show("You must specify a valid email address, otherwise we can't reply to you!"); } else { string str2 = this.txtRemarks.Text.Trim() + Environment.NewLine; foreach (ListViewDataItem checkedItem in (ReadOnlyCollection <ListViewDataItem>) this.lstTitles.CheckedItems) { str2 = str2 + checkedItem.Tag + Environment.NewLine; } if (this.chkTeamViewer.Checked) { str2 = str2 + Environment.NewLine + string.Format("The user has requested a TeamViewer Session at {0}.", (object)TimeZoneInfo.ConvertTimeFromUtc(this.timeViewer.Value.ToUniversalTime(), TimeZoneInfo.FindSystemTimeZoneById("Romance Standard Time"))); } if (this.string_0 != null) { str2 = str2 + Environment.NewLine + Environment.NewLine + this.string_0; } string s = GClass6.smethod_20(string.Format("{0}/issue/open_issue.php", (object)Class67.String_4), new NameValueCollection() { { "email", this.txtEmail.Text }, { "app_id", Settings.Default.AppId }, { "title", this.txtTitle.Text }, { "syslog", str1 } }); try { int num5 = (int)uint.Parse(s); } catch { int num5 = (int)RadMessageBox.Show("Sorry but we are unable to process your request at the moment"); return; } string str3 = GClass6.smethod_20(string.Format("{0}/issue/answer_issue.php", (object)Class67.String_4), new NameValueCollection() { { "issue_id", s }, { "message", str2 } }); try { int num5 = (int)uint.Parse(str3); } catch { int num5 = (int)RadMessageBox.Show("Sorry but we are unable to process your request at the moment"); return; } foreach (string sourceFileName in this.list_0) { try { string str4 = Path.Combine(GClass88.CachePath, str3); System.IO.File.Copy(sourceFileName, str4, true); Encoding.UTF8.GetString(new WebClient().UploadFile(string.Format("{0}/issue/upload.php", (object)Class67.String_4), str4)); } catch { } } int num6 = (int)RadMessageBox.Show(string.Format("<html>Thank you for contacting us!\nYou will be notified by email (make sure to check your spam box) when a reply is available.\nYour issue id is : {0}\nYou can follow its status <a href=\"{1}/issue/view/view.php?issue_id={2}\">here</a>.\nPlease keep it for future reference.<html>", (object)s, (object)Class67.String_4, (object)s)); this.Close(); } } }
static void InitializeMonthly(MonthlyCalendar monthlyCalendar, IMonthlyCalendar calendar) { monthlyCalendar.TimeZone = TimeZoneInfo.FindSystemTimeZoneById(Persistent.Base.General.RegistryTimeZoneProvider.GetRegistryKeyNameByTimeZoneId(calendar.TimeZone)); calendar.DaysExcluded.ForEach(i => monthlyCalendar.SetDayExcluded(i, true)); calendar.DaysIncluded.ForEach(i => monthlyCalendar.SetDayExcluded(i, false)); }
protected override void ProcessRecord() { // make sure we've got fresh data, in case the requested time zone was added // to the system (registry) after our process was started TimeZoneInfo.ClearCachedData(); // acquire a TimeZoneInfo if one wasn't supplied. if (this.ParameterSetName.Equals("Id", StringComparison.OrdinalIgnoreCase)) { try { InputObject = TimeZoneInfo.FindSystemTimeZoneById(Id); } catch (TimeZoneNotFoundException e) { ThrowTerminatingError(new ErrorRecord( e, TimeZoneHelper.TimeZoneNotFoundError, ErrorCategory.InvalidArgument, "Id")); } } else if (this.ParameterSetName.Equals("Name", StringComparison.OrdinalIgnoreCase)) { // lookup the time zone name and make sure we have one (and only one) match TimeZoneInfo[] timeZones = TimeZoneHelper.LookupSystemTimeZoneInfoByName(Name); if (timeZones.Length == 0) { string message = string.Format(CultureInfo.InvariantCulture, TimeZoneResources.TimeZoneNameNotFound, Name); Exception e = new TimeZoneNotFoundException(message); ThrowTerminatingError(new ErrorRecord(e, TimeZoneHelper.TimeZoneNotFoundError, ErrorCategory.InvalidArgument, "Name")); } else if (timeZones.Length > 1) { string message = string.Format(CultureInfo.InvariantCulture, TimeZoneResources.MultipleMatchingTimeZones, Name); ThrowTerminatingError(new ErrorRecord( new PSArgumentException(message, "Name"), TimeZoneHelper.MultipleMatchingTimeZonesError, ErrorCategory.InvalidArgument, "Name")); } else { InputObject = timeZones[0]; } } else // ParameterSetName == "InputObject" { try { // a TimeZoneInfo object was supplied, so use it to make sure we can find // a backing system time zone, otherwise it's an error condition InputObject = TimeZoneInfo.FindSystemTimeZoneById(InputObject.Id); } catch (TimeZoneNotFoundException e) { ThrowTerminatingError(new ErrorRecord( e, TimeZoneHelper.TimeZoneNotFoundError, ErrorCategory.InvalidArgument, "InputObject")); } } if (ShouldProcess(TimeZoneTarget)) { bool acquireAccess = false; try { // check to see if permission to set the time zone is already enabled for this process if (!HasAccess) { // acquire permissions to set the timezone SetAccessToken(true); acquireAccess = true; } } catch (Win32Exception e) { ThrowTerminatingError(new ErrorRecord(e, TimeZoneHelper.InsufficientPermissionsError, ErrorCategory.PermissionDenied, null)); } try { // construct and populate a new DYNAMIC_TIME_ZONE_INFORMATION structure NativeMethods.DYNAMIC_TIME_ZONE_INFORMATION dtzi = new(); dtzi.Bias -= (int)InputObject.BaseUtcOffset.TotalMinutes; dtzi.StandardName = InputObject.StandardName; dtzi.DaylightName = InputObject.DaylightName; dtzi.TimeZoneKeyName = InputObject.Id; // Request time zone transition information for the current year NativeMethods.TIME_ZONE_INFORMATION tzi = new(); if (!NativeMethods.GetTimeZoneInformationForYear((ushort)DateTime.Now.Year, ref dtzi, ref tzi)) { ThrowWin32Error(); } // copy over the transition times dtzi.StandardBias = tzi.StandardBias; dtzi.StandardDate = tzi.StandardDate; dtzi.DaylightBias = tzi.DaylightBias; dtzi.DaylightDate = tzi.DaylightDate; // set the new local time zone for the system if (!NativeMethods.SetDynamicTimeZoneInformation(ref dtzi)) { ThrowWin32Error(); } // broadcast a WM_SETTINGCHANGE notification message to all top-level windows so that they // know to update their notion of the current system time (and time zone) if applicable int result = 0; NativeMethods.SendMessageTimeout((IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WM_SETTINGCHANGE, (IntPtr)0, "intl", NativeMethods.SMTO_ABORTIFHUNG, 5000, ref result); // clear the time zone data or this PowerShell session // will not recognize the new time zone settings TimeZoneInfo.ClearCachedData(); if (PassThru.IsPresent) { // return the TimeZoneInfo object for the (new) current local time zone WriteObject(TimeZoneInfo.Local); } } catch (Win32Exception e) { ThrowTerminatingError(new ErrorRecord(e, TimeZoneHelper.SetTimeZoneFailedError, ErrorCategory.FromStdErr, null)); } finally { if (acquireAccess) { // reset the permissions SetAccessToken(false); } } } else { if (PassThru.IsPresent) { // show the user the time zone settings that would have been used. WriteObject(InputObject); } } }
static void InitializeHoliday(HolidayCalendar holidayCalendar, IHolidayCalendar calendar) { holidayCalendar.TimeZone = TimeZoneInfo.FindSystemTimeZoneById(Persistent.Base.General.RegistryTimeZoneProvider.GetRegistryKeyNameByTimeZoneId(calendar.TimeZone)); calendar.DatesExcluded.ForEach(holidayCalendar.AddExcludedDate); }
/// <summary> /// Implementation of the ProcessRecord method for Get-TimeZone. /// </summary> protected override void ProcessRecord() { // make sure we've got the latest time zone settings TimeZoneInfo.ClearCachedData(); if (this.ParameterSetName.Equals("ListAvailable", StringComparison.OrdinalIgnoreCase)) { // output the list of all available time zones WriteObject(TimeZoneInfo.GetSystemTimeZones(), true); } else if (this.ParameterSetName.Equals("Id", StringComparison.OrdinalIgnoreCase)) { // lookup each time zone id foreach (string tzid in Id) { try { WriteObject(TimeZoneInfo.FindSystemTimeZoneById(tzid)); } catch (TimeZoneNotFoundException e) { WriteError(new ErrorRecord(e, TimeZoneHelper.TimeZoneNotFoundError, ErrorCategory.InvalidArgument, "Id")); } } } else // ParameterSetName == "Name" { if (Name != null) { // lookup each time zone name (or wildcard pattern) foreach (string tzname in Name) { TimeZoneInfo[] timeZones = TimeZoneHelper.LookupSystemTimeZoneInfoByName(tzname); if (timeZones.Length > 0) { // manually process each object in the array, so if there is only a single // entry then the returned type is TimeZoneInfo and not TimeZoneInfo[], and // it can be pipelined to Set-TimeZone more easily foreach (TimeZoneInfo timeZone in timeZones) { WriteObject(timeZone); } } else { string message = string.Format(CultureInfo.InvariantCulture, TimeZoneResources.TimeZoneNameNotFound, tzname); Exception e = new TimeZoneNotFoundException(message); WriteError(new ErrorRecord(e, TimeZoneHelper.TimeZoneNotFoundError, ErrorCategory.InvalidArgument, "Name")); } } } else { // return the current system local time zone WriteObject(TimeZoneInfo.Local); } } }
/// <summary> /// Retrieves a System.TimeZoneInfo object from the registry based on its identifier. /// </summary> /// <param name="id">The time zone identifier, which corresponds to the System.TimeZoneInfo.Id property.</param> /// <returns>A System.TimeZoneInfo object whose identifier is the value of the id parameter.</returns> public virtual TimeZoneInfo FindTimeZoneById(string id) { return(TimeZoneInfo.FindSystemTimeZoneById(id)); }
public static DateTime GetChinaStandardDateTime() { var newTime = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("China Standard Time")); return(newTime.DateTime); }
public void SendReminder(SmsRequest incomingMessage, string userNumberString) { bool badNumber = false; bool outOfRange = false; bool unknownUser = false; try { //check if number entered is in fact a number. if (!int.TryParse(userNumberString, out int userNumber)) { Exception badParse = new Exception(); badNumber = true; throw badParse; } UserInfo userInfo = _context.UserInfo.Where(x => x.PhoneNumber == incomingMessage.From).First(); if (userInfo == null) { unknownUser = true; throw new Exception(); } AspNetUsers user = _context.AspNetUsers.Where(x => x.Id == userInfo.UserId).First(); List <EventTable> userEvents = _context.EventTable.Where(x => x.UserId == user.Id).ToList(); //check if the number sent is too high or too low, since it might be out of range. if (userNumber > userEvents.Count || userNumber < 1) { outOfRange = true; Exception badRange = new Exception(); throw badRange; } int foundIndex = 0; for (int i = 0; i < userEvents.Count; i++) { if (i + 1 == userNumber) { foundIndex = i; } } EventTable userEvent = userEvents[foundIndex]; TimeZoneInfo myTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); DateTime currentDateTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, myTimeZone); TimeSpan timeRemainingForEvent = userEvent.DateAndTime.Subtract(currentDateTime); string timeLeft; if (timeRemainingForEvent.TotalDays < 1) { if (timeRemainingForEvent.Hours > 1) { timeLeft = timeRemainingForEvent.Hours.ToString(); timeLeft = timeLeft + " hours"; } else { timeLeft = timeRemainingForEvent.Hours.ToString(); timeLeft = timeLeft + " hour"; } } else { if (timeRemainingForEvent.Days > 1) { timeLeft = timeRemainingForEvent.Days.ToString(); timeLeft = timeLeft + " days"; } else { timeLeft = timeRemainingForEvent.Days.ToString(); timeLeft = timeLeft + " day"; } } List <GroupMembers> eventMembers = _context.GroupMembers.Where(x => x.Groups == userEvent.GroupId).ToList(); Groups group = _context.Groups.Where(x => x.GroupId == userEvent.GroupId).First(); foreach (var e in eventMembers) { SendText($"Hey, {e.MemberName}! Just a reminder from {userInfo.FirstName} You have {timeLeft} until {userEvent.EventName}. Are you still coming? You can still RSVP by texting back with 'yes {userEvent.EventId}' or 'no {userEvent.EventId}'", e.PhoneNumber); } SendSuccessText(incomingMessage, $"You just sent out reminders to everyone in {group.GroupName}"); } catch (Exception) { if (badNumber) { SendErrorText(incomingMessage, $"{userNumberString} isn't a number ಠ_ಠ."); SendListOfEvents(incomingMessage); } else if (outOfRange) { SendErrorText(incomingMessage, "That event doesn't exist."); SendListOfEvents(incomingMessage); } else if (unknownUser) { SendRegisterText(incomingMessage); } } }
public static DateTime GetCentralStandardTime() { var timezone = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time")); return(timezone.DateTime); }
public ActionResult UpdateMeeting(string identifier) { var token = JObject.Parse(System.IO.File.ReadAllText("C:/Users/Purshotam/Desktop/Zoom Meeting/Zoom Meeting/Credentials/OauthToken.json")); var access_token = token["access_token"]; RestClient restClient = new RestClient(); RestRequest restRequest = new RestRequest(); restRequest.AddHeader("Authorization", "Bearer " + access_token); restClient.BaseUrl = new Uri($"https://api.zoom.us/v2/meetings/{identifier}"); var response = restClient.Get(restRequest); if (response.StatusCode == System.Net.HttpStatusCode.OK) { var zoomMeeting = JObject.Parse(response.Content).ToObject <ZoomMeeting>(); DateTime utcTime = new DateTime(zoomMeeting.Start_Time.Ticks, DateTimeKind.Unspecified); var datetime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time")); var meeting = new Meeting() { Id = zoomMeeting.Id, Topic = zoomMeeting.Topic, Agenda = zoomMeeting.Agenda, Date = zoomMeeting.Start_Time.Date, Time = double.Parse(TimeZoneInfo.ConvertTimeFromUtc(new DateTime(zoomMeeting.Start_Time.Ticks, DateTimeKind.Unspecified), TimeZoneInfo.FindSystemTimeZoneById("India Standard Time")).ToString("H.m")), Duration = zoomMeeting.Duration, }; return(View(meeting)); } return(View("Error")); }
public static DateTime GetLocalDateTime(string timeZone, DateTime utc) { TimeZoneInfo zone = TimeZoneInfo.FindSystemTimeZoneById(timeZone); return(TimeZoneInfo.ConvertTimeFromUtc(utc, zone)); }
public ActionResult AllMeetings() { var token = JObject.Parse(System.IO.File.ReadAllText(ConfigurationManager.AppSettings["TokenFilePath"])); var userDetails = JObject.Parse(System.IO.File.ReadAllText(ConfigurationManager.AppSettings["UserDetailsPath"])); var access_token = token["access_token"]; var userId = userDetails["id"]; RestClient restClient = new RestClient(); RestRequest restRequest = new RestRequest(); restRequest.AddHeader("Authorization", "Bearer " + access_token); restClient.BaseUrl = new Uri($"https://api.zoom.us/v2/users/{userId}/meetings"); var response = restClient.Get(restRequest); if (response.StatusCode == System.Net.HttpStatusCode.OK) { var zoomMeetings = JObject.Parse(response.Content)["meetings"].ToObject <IEnumerable <ZoomMeeting> >(); foreach (ZoomMeeting meeting in zoomMeetings) { meeting.Start_Time = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(meeting.Start_Time.Ticks, DateTimeKind.Unspecified), TimeZoneInfo.FindSystemTimeZoneById("India Standard Time")); } return(View(zoomMeetings)); } return(View("Error")); }
private void ProcessJobs(quartz data) { if (data.job == null) { // no jobs to process, file is empty return; } foreach (var jt in data.job) { var jsb = new JobSchedulingBundle(); var j = jt.jobdetail; var jobType = Type.GetType(j.jobtype); if (jobType == null) { throw new SchedulerConfigException("Unknown job type " + j.jobtype); } var jd = new JobDetail(j.name, j.group, jobType, j.@volatile, j.durable, j.recover); jd.Description = j.description; if (j.joblistenerref != null && j.joblistenerref.Trim().Length > 0) { jd.AddJobListener(j.joblistenerref); } jsb.JobDetail = jd; // read job data map if (j.jobdatamap != null && j.jobdatamap.entry != null) { foreach (var entry in j.jobdatamap.entry) { jd.JobDataMap.Put(entry.key, entry.value); } } var tArr = jt.trigger; foreach (var t in tArr) { Trigger trigger; if (t.Item is cronType) { var c = (cronType)t.Item; var startTime = (c.starttime == DateTime.MinValue ? DateTime.UtcNow : c.starttime); var endTime = (c.endtime == DateTime.MinValue ? null : (NullableDateTime)c.endtime); var jobName = c.jobname != null ? c.jobname : j.name; var jobGroup = c.jobgroup != null ? c.jobgroup : j.group; var ct = new CronTrigger( c.name, c.group, jobName, jobGroup, startTime, endTime, c.cronexpression); if (c.timezone != null && c.timezone.Trim().Length > 0) { #if NET_35 ct.TimeZone = TimeZoneInfo.FindSystemTimeZoneById(c.timezone); #else throw new ArgumentException( "Specifying time zone for cron trigger is only supported in .NET 3.5 builds"); #endif } trigger = ct; } else if (t.Item is simpleType) { var s = (simpleType)t.Item; var startTime = (s.starttime == DateTime.MinValue ? DateTime.UtcNow : s.starttime); var endTime = (s.endtime == DateTime.MinValue ? null : (NullableDateTime)s.endtime); var jobName = s.jobname != null ? s.jobname : j.name; var jobGroup = s.jobgroup != null ? s.jobgroup : j.group; var st = new SimpleTrigger( s.name, s.group, jobName, jobGroup, startTime, endTime, ParseSimpleTriggerRepeatCount(s.repeatcount), TimeSpan.FromMilliseconds(Convert.ToInt64(s.repeatinterval, CultureInfo.InvariantCulture))); trigger = st; } else { throw new ArgumentException("Unknown trigger type in XML"); } trigger.CalendarName = t.Item.calendarname; if (t.Item.misfireinstruction != null) { trigger.MisfireInstruction = ReadMisfireInstructionFromString(t.Item.misfireinstruction); } if (t.Item.jobdatamap != null && t.Item.jobdatamap.entry != null) { foreach (var entry in t.Item.jobdatamap.entry) { if (trigger.JobDataMap.Contains(entry.key)) { Log.Warn("Overriding key '" + entry.key + "' with another value in same trigger job data map"); } trigger.JobDataMap[entry.key] = entry.value; } } jsb.Triggers.Add(trigger); } AddJobToSchedule(jsb); } }