Beispiel #1
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="id"></param>
 /// <param name="handler"></param>
 public void Enqueue(string id, QEventHandler handler)
 {
     if (Thread.CurrentThread.ManagedThreadId == _WorkingThread.ManagedThreadId)
     {
         if (!_Stop)
         {
             try
             {
                 handler();
             }
             catch (Exception ex)
             {
                 EventException?.Invoke(this, new Exception("ERROR running " + id + ": " + ex.Message));
                 //throw new Exception("ERROR running " + id + ": " + ex.Message);
             }
         }
     }
     else
     {
         lock (_Queue)
         {
             if (!_Stop)
             {
                 _Queue.Enqueue(new Event(id, handler));
                 _NewEvent.Set();
             }
         }
     }
 }
Beispiel #2
0
 protected void SafeRaiseEventException(Exception x)
 {
     EventException?.Invoke(this, new WebServerExceptionEventArgs()
     {
         X = x
     });
 }
Beispiel #3
0
        private void ProcessEvents()
        {
            WaitHandle[] waitHandles = new WaitHandle[] { _StopEvent, _NewEvent };

            while (!_Stop)
            {
                Event ev = null;

                lock (_Queue)
                {
                    if (_Queue.Count > 0)
                    {
                        ev = _Queue.Dequeue();
                    }
                    else
                    {
                        _NewEvent.Reset();
                    }
                }

                if (ev == null)
                {
                    if (WaitHandle.WaitAny(waitHandles) == 0)
                    {
                        break;
                    }
                    else
                    {
                        lock (_Queue)
                        {
                            ev = _Queue.Dequeue();
                        }
                    }
                }

                if (ev.Valid)
                {
                    try
                    {
                        ev.Handler();
                    }
                    catch (Exception ex)
                    {
                        EventException?.Invoke(this, new Exception("ERROR running " + ev.Id + ": " + ex.Message));
                        //throw new Exception("ERROR running " + ev.Id + ": " + ex.Message);
                    }
                }
            }
        }
        public static IResponse ResponseEventException(this EventException exception)
        {
            var errorsList = exception.Errors.Select(e =>
            {
                var result = new Dictionary <string, IEnumerable <string> >();

                if (e.Body is Exception exception)
                {
                    var eventName = e.Event?.GetType().Name ?? "";
                    result.Add(eventName, BuildErrorsList(exception));
                }

                return(result);
            }).ToArray();

            var body = new Dictionary <string, IEnumerable <Dictionary <string, IEnumerable <string> > > >
            {
                { exception.Message, errorsList }
            };

            return(new Response <object>(500, body, exception.Message));
        }
Beispiel #5
0
        //public virtual JsonResult Event_Read(DataSourceRequest request, string chkselected, DateTime start, DateTime end)
        //{
        //    return null;
        //}
        public virtual JsonResult Event_Read(DataSourceRequest request, string chkselected, DateTime start, DateTime end, string Search)
        {
            List<EventException> lstException = new List<EventException>();
            IList<CalEventViewModel> events = new List<CalEventViewModel>();

              //  string Search = "";
            if (Search.Length > 0)
            {
                {
                    var tasks = _scheduler.GetAllEventBySearch(Search);
                    var preExceptionList = _scheduler.GetEventExceptions();
                    var getAllEventException = _scheduler.GetAllEventException();
                    var colmaster = _scheduler.GetAllColor();
                    var usercalenderlst = _scheduler.GetAllCalendarUser();
                    if (tasks.ToList().Count > 0)
                    {
                        var reccEvents = tasks.Where(x => !string.IsNullOrEmpty(x.Recurrence)).ToList();

                        Dictionary<string, List<string>> test = new Dictionary<string, List<string>>();
                        foreach (var rec in reccEvents)
                        {
                            var exceptionList = tasks.Where(x => x.EventId.Contains(rec.EventId + "_")).Select(y => y.EventId.Replace(rec.EventId + "_", "")).ToList();
                            try
                            {
                                test.Add(rec.EventId, exceptionList);
                            }
                            catch { }
                        }

                        foreach (var item in tasks)
                        {
                            if (!string.IsNullOrEmpty(item.ColorId))
                            {
                                var coloritem = colmaster.Where(m => m.Row_Id == int.Parse(item.ColorId)).FirstOrDefault();
                                item.ColorId = coloritem.Row_Id.ToString();
                                ViewBag.Color = coloritem.Color;
                            }
                            else
                            {
                                item.ColorId = GetUsercalenderColor(item.CalendarId.Value, usercalenderlst, colmaster);
                                var coloritem = colmaster.Where(m => m.Row_Id == int.Parse(item.ColorId)).FirstOrDefault();
                                ViewBag.Color = coloritem.Color;
                            }
                            var eventObj = new CalEventViewModel();
                            if (item.StartDate.Value.Year.ToString() != "1900" && !item.Recurrence.StartsWith("~EXDATE"))
                            {
                                eventObj.EventId = item.EventId;
                                eventObj.Title = item.Title;
                                eventObj.Start = TimeZoneInfo.ConvertTimeToUtc((DateTime)item.StartDate);
                                eventObj.End = TimeZoneInfo.ConvertTimeToUtc((DateTime)item.EndDate);

                                DateTime endTime = DateTime.Now.AddSeconds(75);
                                TimeSpan span = eventObj.End.Subtract(eventObj.Start);

                                string timeSlot = string.Format("{0:D2} hours :{1:D2}minutes",
                                span.Hours,
                                span.Minutes

                                );

                                DateTime dtstart = (DateTime)item.StartDate;
                                DateTime dtEnd = (DateTime)item.EndDate;

                                string strdtStart = dtstart.ToString("dd/MM/yyyy");
                                string strdtEnd = dtEnd.ToString("dd/MM/yyyy");

                                eventObj.TooltipDescription = "Start Date: " + dtstart.ToString() + "\nEnd Date: " + dtEnd.ToString() + "\nDuration: " + timeSlot;
                                eventObj.Description = item.Description;

                                if (!string.IsNullOrEmpty(item.Recurrence))
                                {
                                    eventObj.RecurrenceRule = item.Recurrence.Replace("~RRULE:", string.Empty);
                                }

                                string exception = string.Empty;
                                if (preExceptionList.Keys.Contains(eventObj.EventId))
                                    exception = preExceptionList[eventObj.EventId];
                                if (test.Keys.Contains(eventObj.EventId))
                                {

                                    foreach (string exc in test[eventObj.EventId])
                                    {

                                        if (exception == string.Empty)
                                        {
                                            if (!exception.Contains(exc))
                                                exception = exc;
                                        }
                                        else
                                        {
                                            if (!exception.Contains(exc))
                                                exception = exception + ";" + exc;
                                        }
                                    }
                                    if (!preExceptionList.Keys.Contains(eventObj.EventId) && !string.IsNullOrEmpty(exception))
                                    {
                                        var EventException = new EventException { EventId = eventObj.EventId, Exception = exception };
                                        lstException.Add(EventException);

                                    }
                                    else if (preExceptionList.Keys.Contains(eventObj.EventId))
                                    {
                                        if (preExceptionList[eventObj.EventId] != exception)
                                        {
                                            var EventExceptionUpdate = getAllEventException.FirstOrDefault(x => x.EventId == eventObj.EventId);

                                            EventExceptionUpdate.Exception = exception;
                                            lstException.Add(EventExceptionUpdate);
                                            //  OrderMangtDB.EventExceptions.Add(EventExceptionUpdate);
                                        }
                                    }

                                    eventObj.RecurrenceException = exception;
                                }
                                eventObj.EventId = item.EventId;
                                eventObj.RecurrenceID = item.RecurrenceID;
                                eventObj.CalendarId = item.CalendarId;
                                eventObj.CalenderUser = item.CalendarId;
                                eventObj.Organizer = item.Organizer;
                                eventObj.Location = item.Location;
                                eventObj.Status = item.Status;
                                eventObj.Creator = item.Creator;
                                eventObj.ColorId = item.ColorId;
                                eventObj.EventColorid = int.Parse(item.ColorId);
                                eventObj.Color = ViewBag.Color;
                                eventObj.Description = item.Description;
                                eventObj.DeleteRecurrenceEvent = item.EventId;
                                if (item.IsAllDay != null)
                                    eventObj.IsAllDay = item.IsAllDay.Value;

                                events.Add(eventObj);
                            }
                        }
                    }

                    lock ("EventException")
                    {
                        _scheduler.AddOrUpdateException(lstException);
                    }

                    var temp = events as IEnumerable<CalEventViewModel>;
                    JsonResult jsonResult = Json(temp.ToDataSourceResult(request));
                    jsonResult.MaxJsonLength = Int32.MaxValue;
                    return jsonResult;
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(chkselected))
                {
                    if (chkselected.EndsWith(","))
                    {
                        chkselected = chkselected.Remove(chkselected.Length - 1);
                    }

                    List<int> userIds = new List<int>(Array.ConvertAll(chkselected.Split(','), int.Parse));

                    if (userIds != null && userIds.Count > 0)
                    {
                        end = end.AddDays(1);

                        var tasks = _scheduler.GetAllEventByUserIdAndDate(userIds, start, end);
                        var preExceptionList = _scheduler.GetEventExceptions();
                        var getAllEventException = _scheduler.GetAllEventException();
                        var colmaster = _scheduler.GetAllColor();
                        var usercalenderlst = _scheduler.GetAllCalendarUser();
                        if (tasks.ToList().Count > 0)
                        {
                            var reccEvents = tasks.Where(x => !string.IsNullOrEmpty(x.Recurrence)).ToList();

                            Dictionary<string, List<string>> test = new Dictionary<string, List<string>>();
                            foreach (var rec in reccEvents)
                            {
                                var exceptionList = tasks.Where(x => x.EventId.Contains(rec.EventId + "_")).Select(y => y.EventId.Replace(rec.EventId + "_", "")).ToList();
                                test.Add(rec.EventId, exceptionList);
                            }

                            foreach (var item in tasks)
                            {
                                if (!string.IsNullOrEmpty(item.ColorId))
                                {
                                    var coloritem = colmaster.Where(m => m.Row_Id == int.Parse(item.ColorId)).FirstOrDefault();
                                    item.ColorId = coloritem.Row_Id.ToString();
                                    ViewBag.Color = coloritem.Color;
                                }
                                else
                                {
                                    item.ColorId = GetUsercalenderColor(item.CalendarId.Value, usercalenderlst, colmaster);
                                    var coloritem = colmaster.Where(m => m.Row_Id == int.Parse(item.ColorId)).FirstOrDefault();
                                    ViewBag.Color = coloritem.Color;

                                }
                                var eventObj = new CalEventViewModel();
                                if (item.StartDate.Value.Year.ToString() != "1900" && !item.Recurrence.StartsWith("~EXDATE"))
                                {
                                    eventObj.EventId = item.EventId;
                                    eventObj.Title = item.Title;

                                    eventObj.Start = TimeZoneInfo.ConvertTimeToUtc((DateTime)item.StartDate);

                                    //.ToUniversalTime();// DateTime.SpecifyKind(DateTime.Parse(item.StartDate.ToString()), DateTimeKind.Utc);
                                    eventObj.End = TimeZoneInfo.ConvertTimeToUtc((DateTime)item.EndDate);

                                    DateTime endTime = DateTime.Now.AddSeconds(75);
                                    TimeSpan span = eventObj.End.Subtract(eventObj.Start);

                                    //string timeSlot = string.Format("{0:D2} hours :{1:D2}minutes :{2:D2}seconds",
                                    //span.Hours,
                                    //span.Minutes,
                                    //span.Seconds
                                    //);

                                    string timeSlot = string.Format("{0:D2} hours :{1:D2}minutes",
                                    span.Hours,
                                    span.Minutes

                                    );

                                    DateTime dtstart = (DateTime)item.StartDate;
                                    DateTime dtEnd = (DateTime)item.EndDate;

                                    string strdtStart = dtstart.ToString("dd/MM/yyyy");
                                    string strdtEnd = dtEnd.ToString("dd/MM/yyyy");

                                    eventObj.TooltipDescription = "Start Date: " + dtstart.ToString() + "\nEnd Date: " + dtEnd.ToString() + "\nDuration: " + timeSlot;

                                    //DateTime.Parse(item.StartDate.ToString()).ToUniversalTime();// DateTime.SpecifyKind(DateTime.Parse(item.EndDate.ToString()), DateTimeKind.Utc);
                                    eventObj.Description = item.Description;

                                    //if (item.StartDate.Value.ToString("HH:mm:ss") == "00:00:00"  && item.EndDate.Value.ToString("HH:mm:ss") == "00:00:00")
                                    //{
                                    //    eventObj.IsAllDay = true;
                                    //    eventObj.End = eventObj.End.AddDays(-1);
                                    //}
                                    //else
                                    //{
                                    //    eventObj.IsAllDay = false;
                                    //}

                                    if (!string.IsNullOrEmpty(item.Recurrence))
                                    {

                                        eventObj.RecurrenceRule = item.Recurrence.Replace("~RRULE:", string.Empty);
                                    }

                                    string exception = string.Empty;
                                    if (preExceptionList.Keys.Contains(eventObj.EventId))
                                        exception = preExceptionList[eventObj.EventId];
                                    if (test.Keys.Contains(eventObj.EventId))
                                    {

                                        foreach (string exc in test[eventObj.EventId])
                                        {

                                            if (exception == string.Empty)
                                            {
                                                if (!exception.Contains(exc))
                                                    exception = exc;
                                            }
                                            else
                                            {
                                                if (!exception.Contains(exc))
                                                    exception = exception + ";" + exc;
                                            }
                                        }
                                        if (!preExceptionList.Keys.Contains(eventObj.EventId) && !string.IsNullOrEmpty(exception))
                                        {
                                            var EventException = new EventException { EventId = eventObj.EventId, Exception = exception };
                                            lstException.Add(EventException);

                                        }
                                        else if (preExceptionList.Keys.Contains(eventObj.EventId))
                                        {
                                            if (preExceptionList[eventObj.EventId] != exception)
                                            {
                                                var EventExceptionUpdate = getAllEventException.FirstOrDefault(x => x.EventId == eventObj.EventId);

                                                EventExceptionUpdate.Exception = exception;
                                                lstException.Add(EventExceptionUpdate);
                                                //  OrderMangtDB.EventExceptions.Add(EventExceptionUpdate);
                                            }
                                        }

                                        eventObj.RecurrenceException = exception;
                                    }
                                    eventObj.EventId = item.EventId;
                                    eventObj.RecurrenceID = item.RecurrenceID;
                                    eventObj.CalendarId = item.CalendarId;
                                    eventObj.CalenderUser = item.CalendarId;
                                    eventObj.Organizer = item.Organizer;
                                    eventObj.Location = item.Location;
                                    eventObj.Status = item.Status;
                                    eventObj.Creator = item.Creator;
                                    eventObj.ColorId = item.ColorId;
                                    eventObj.EventColorid = int.Parse(item.ColorId);
                                    eventObj.Color = ViewBag.Color;
                                    eventObj.Description = item.Description;
                                    eventObj.DeleteRecurrenceEvent = item.EventId;
                                    if (item.IsAllDay != null)
                                        eventObj.IsAllDay = item.IsAllDay.Value;

                                    events.Add(eventObj);
                                }
                            }
                        }

                        lock ("EventException")
                        {
                            _scheduler.AddOrUpdateException(lstException);
                        }

                        var temp = events as IEnumerable<CalEventViewModel>;
                        JsonResult jsonResult = Json(temp.ToDataSourceResult(request));
                        jsonResult.MaxJsonLength = Int32.MaxValue;
                        return jsonResult;
                    }

                }
            }
            return null;
        }
Beispiel #6
0
        public ActionResult DeleteRecurrence(string eventid, int calendarId, string calenderUser, DateTime end, DateTime start)
        {
            string calenderName = string.Empty;
            string rtneventid = string.Empty;
            string exceptionfrmDB = string.Empty;
            string strNewDate = string.Empty;

            var objGoogleCal = new GoogleServiceMethodCalls();
            using (var OrderMangtDB = new OrderMgntEntities())
            {
                calenderName = OrderMangtDB.Calendars.FirstOrDefault(m => m.Row_Id == calendarId).Name;

                if (!string.IsNullOrEmpty(calenderName))
                {

                    rtneventid = objGoogleCal.DeleteEventInstance(eventid, calenderName, start);

                    if (!rtneventid.Equals("Instance not available"))
                    {
                        string Currexception = rtneventid.Split('_').Last();
                        //var datepart = Currexception.Split('T').First();
                        //var newDate = DateTime.ParseExact(datepart, "yyyyMMdd", CultureInfo.InvariantCulture).AddDays(1);
                        //strNewDate = newDate.Year.ToString() + newDate.Month.ToString() + newDate.Day.ToString();
                        //Currexception = Currexception.Replace(datepart, strNewDate);

                        string streventid = eventid;

                        var exceptionEntry = OrderMangtDB.EventExceptions.FirstOrDefault(c => c.EventId == streventid);

                        if (exceptionEntry != null)
                        {
                            exceptionfrmDB = exceptionEntry.Exception;
                        }

                        if (exceptionfrmDB == string.Empty)
                        {
                            if (!exceptionfrmDB.Contains(Currexception))
                                exceptionfrmDB = Currexception;
                        }
                        else
                        {
                            exceptionfrmDB = exceptionfrmDB + ";" + Currexception;
                        }

                        if (exceptionEntry == null)
                        {
                            var EventException = new EventException { EventId = eventid, Exception = exceptionfrmDB };
                            OrderMangtDB.EventExceptions.Add(EventException);
                        }
                        else
                        {
                            exceptionEntry.Exception = exceptionfrmDB;
                        }

                        OrderMangtDB.SaveChanges();
                    }
                    else
                    {
                        using (var OrderMangtDB2 = new OrderMgntEntities())
                        {
                            var Events =
                                     (from oEvents in OrderMangtDB2.Events
                                      where oEvents.EventId == eventid && oEvents.CalendarId == calendarId
                                      select oEvents).ToList();

                            foreach (var Event in Events)
                            {
                                Event.Status = "cancelled";

                            }
                            OrderMangtDB2.SaveChanges();
                        }
                    }
                }
            }
            return Content(rtneventid);
        }
        /// <summary>
        /// Periodically process SIF Events.
        /// </summary>
        /// <param name="cancellationToken">Notification that processing should be cancelled.</param>
        private void ProcessEvents(CancellationToken cancellationToken)
        {

            while (true)
            {

                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }

                bool getEvents = true;
                TimeSpan waitTime = TimeSpan.FromSeconds(SettingsManager.ConsumerSettings.EventProcessingWaitTime);
                string url = $"{EnvironmentUtils.ParseServiceUrl(Environment, ServiceType.UTILITY, InfrastructureServiceNames.queues)}/{Queue.id}/messages";
                string deleteMessageId = null;

                // Read from the message queue until no more messages are found.
                do
                {

                    try
                    {
                        WebHeaderCollection responseHeaders;
                        string deleteMessageIdMatrixParameter = (deleteMessageId == null ? "" : $";deleteMessageId={deleteMessageId.Trim()}");
                        if (log.IsDebugEnabled) log.Debug($"Making a request for an event message from {url}{deleteMessageIdMatrixParameter}.");
                        string xml = HttpUtils.GetRequestAndHeaders($"{url}{deleteMessageIdMatrixParameter}", RegistrationService.AuthorisationToken, out responseHeaders, deleteMessageId: deleteMessageId);
                        string contextId = responseHeaders?[HttpUtils.RequestHeader.contextId.ToDescription()];
                        deleteMessageId = responseHeaders?[HttpUtils.RequestHeader.messageId.ToDescription()];
                        string minWaitTimeValue = responseHeaders?[HttpUtils.RequestHeader.minWaitTime.ToDescription()];
                        string zoneId = responseHeaders?[HttpUtils.RequestHeader.zoneId.ToDescription()];

                        if (!string.IsNullOrWhiteSpace(minWaitTimeValue))
                        {
                            double minWaitTime;

                            if (double.TryParse(minWaitTimeValue, out minWaitTime) && (TimeSpan.FromSeconds(minWaitTime) > waitTime))
                            {
                                waitTime = TimeSpan.FromSeconds(minWaitTime);
                            }

                        }

                        // Call the appropriate event handler for messages read.
                        if (!string.IsNullOrWhiteSpace(xml))
                        {

                            try
                            {
                                TMultiple obj = DeserialiseMultiple(xml);
                                string eventAction = responseHeaders?[HttpUtils.RequestHeader.eventAction.ToDescription()];

                                if (EventAction.CREATE.ToDescription().Equals(eventAction))
                                {
                                    if (log.IsDebugEnabled) log.Debug($"Received create event message.");
                                    OnCreateEvent(obj, zoneId, contextId);
                                }
                                else if (EventAction.DELETE.ToDescription().Equals(eventAction))
                                {
                                    if (log.IsDebugEnabled) log.Debug($"Received delete event message.");
                                    OnDeleteEvent(obj, zoneId, contextId);
                                }
                                else if ("UPDATE".Equals(eventAction))
                                {
                                    string replacement = responseHeaders?[HttpUtils.RequestHeader.Replacement.ToDescription()];

                                    if ("FULL".Equals(replacement))
                                    {
                                        if (log.IsDebugEnabled) log.Debug($"Received update (full) event message.");
                                        OnUpdateEvent(obj, false, zoneId, contextId);
                                    }
                                    else if ("PARTIAL".Equals(replacement))
                                    {
                                        if (log.IsDebugEnabled) log.Debug($"Received update (partial) event message.");
                                        OnUpdateEvent(obj, true, zoneId, contextId);
                                    }
                                    else
                                    {
                                        if (log.IsDebugEnabled) log.Debug($"Received update (partial) event message.");
                                        OnUpdateEvent(obj, true, zoneId, contextId);
                                    }

                                }
                                else
                                {
                                    BaseException eventException = new EventException($"Event action {eventAction} not recognised for message received from {url}.");
                                    if (log.IsWarnEnabled) log.Warn(eventException.Message);
                                    ResponseError error = new ResponseError { Id = eventException.ExceptionReference, Code = 500, Message = eventException.Message, Description = xml, Scope = TypeName };
                                    OnErrorEvent(error);
                                }

                            }
                            catch (SerializationException e)
                            {
                                BaseException eventException = new EventException($"Event message received from {url} could not be processed due to the following error:\n{e.GetBaseException().Message}.", e);
                                if (log.IsWarnEnabled) log.Warn(e.Message);
                                ResponseError error = new ResponseError { Id = eventException.ExceptionReference, Code = 500, Message = e.Message, Description = xml, Scope = TypeName };
                                OnErrorEvent(error);
                            }

                        }
                        else
                        {
                            if (log.IsDebugEnabled) log.Debug($"No event messages.");
                            getEvents = false;
                        }

                    }
                    catch (Exception e)
                    {
                        string errorMessage = $"Error processing event messages due to the following error:\n{e.GetBaseException().Message}.";
                        if (log.IsErrorEnabled) log.Error($"{errorMessage}\n{e.StackTrace}");
                        getEvents = false;
                    }

                } while (getEvents);

                if (log.IsDebugEnabled) log.Debug($"Wait time is {waitTime.Seconds} seconds.");

                // Wait an appropriate amount of time before reading from the message queue again.
                Thread.Sleep(waitTime);
            }

        }