Exemple #1
0
 public RecurrencePattern(string value) : this()
 {
     if (value != null)
     {
         var serializer = new RecurrencePatternSerializer();
         CopyFrom(serializer.Deserialize(new StringReader(value)) as ICopyable);
     }
 }
Exemple #2
0
        public ActionResult Rule()
        {
            var rrule      = new RecurrencePattern(FrequencyType.Weekly, 2);
            var serializer = new RecurrencePatternSerializer();
            var s          = serializer.SerializeToString(rrule);

            return(Content(s));
        }
        public RecurrencePattern(string value) : this()
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                return;
            }
            var serializer = new RecurrencePatternSerializer();

            CopyFrom(serializer.Deserialize(new StringReader(value)) as ICopyable);
        }
        public RecurrencePattern(string value) :
            this()
        {
            if (value != null)
            {
                RecurrencePatternSerializer serializer = new RecurrencePatternSerializer();

                StringReader reader = new StringReader(value);
                CopyFrom(serializer.Deserialize(reader) as ICopyable);
                reader.Dispose();
            }
        }
Exemple #5
0
        /// <summary>
        /// Преобразует иерархию объектов SyncTranferData в Outlook Appointment
        /// </summary>
        /// <param name="transferData">The transfer data.</param>
        /// <param name="appItem">The app item.</param>
        /// <returns></returns>
        private OutlookAppointment TransferData2AppointmentItem(SyncTransferData transferData, OutlookAppointment appItem)
        {
            ITransferDataSerializable serializer = new AppointmentSerializer(appItem);

            serializer.Deserialize(transferData);
            foreach (SyncTransferData child in transferData.Childrens)
            {
                if (child.SyncDataName == RecurrencePatternTransferData.DataName)
                {
                    OutlookRecurrencePattern rPattern = appItem.GetRecurrencePattern();
                    serializer = new RecurrencePatternSerializer(rPattern);
                    if (serializer != null)
                    {
                        serializer.Deserialize(child);
                    }
                }
                else if (child.SyncDataName == RecipientTransferData.DataName)
                {
                    serializer = new RecipientSerializer();
                    string recipientName = (string)serializer.Deserialize(child);
                    if (string.IsNullOrEmpty(recipientName))
                    {
                        OutlookRecipient recipient = appItem.AddRecipient(recipientName);
                    }
                }
            }

            //Сохранем outlook appointment
            appItem.Save();
            //Переносим exception
            if (appItem.IsRecurring)
            {
                OutlookRecurrencePattern rPattern = appItem.GetRecurrencePattern();
                foreach (SyncTransferData child in transferData.Childrens)
                {
                    AppointmentTransferData exception = child as AppointmentTransferData;
                    if (exception != null)
                    {
                        OutlookAppointment appException = rPattern.GetOccurrence(exception.RecurrenceId);
                        TransferData2AppointmentItem(child, appException);
                        if (exception.DeletedException)
                        {
                            appException.Delete();
                        }
                    }
                }
            }
            return(appItem);
        }
        /// <summary>
        /// Returns a serializer that can be used to serialize and object
        /// of type <paramref name="objectType"/>.
        /// <note>
        ///     TODO: Add support for caching.
        /// </note>
        /// </summary>
        /// <param name="objectType">The type of object to be serialized.</param>
        /// <param name="ctx">The serialization context.</param>
        virtual public ISerializer Build(Type objectType, ISerializationContext ctx)
        {
            if (objectType != null)
            {
                ISerializer s = null;

                if (typeof(IAttachment).IsAssignableFrom(objectType))
                    s = new AttachmentSerializer();
                else if (typeof(IAttendee).IsAssignableFrom(objectType))
                    s = new AttendeeSerializer();
                else if (typeof(IDateTime).IsAssignableFrom(objectType))
                    s = new DateTimeSerializer();
                else if (typeof(IFreeBusyEntry).IsAssignableFrom(objectType))
                    s = new FreeBusyEntrySerializer();
                else if (typeof(IGeographicLocation).IsAssignableFrom(objectType))
                    s = new GeographicLocationSerializer();
                else if (typeof(IOrganizer).IsAssignableFrom(objectType))
                    s = new OrganizerSerializer();
                else if (typeof(IPeriod).IsAssignableFrom(objectType))
                    s = new PeriodSerializer();
                else if (typeof(IPeriodList).IsAssignableFrom(objectType))
                    s = new PeriodListSerializer();
                else if (typeof(IRecurrencePattern).IsAssignableFrom(objectType))
                    s = new RecurrencePatternSerializer();
                else if (typeof(IRequestStatus).IsAssignableFrom(objectType))
                    s = new RequestStatusSerializer();
                else if (typeof(IStatusCode).IsAssignableFrom(objectType))
                    s = new StatusCodeSerializer();
                else if (typeof(ITrigger).IsAssignableFrom(objectType))
                    s = new TriggerSerializer();
                else if (typeof(IUTCOffset).IsAssignableFrom(objectType))
                    s = new UTCOffsetSerializer();
                else if (typeof(IWeekDay).IsAssignableFrom(objectType))
                    s = new WeekDaySerializer();
                // Default to a string serializer, which simply calls
                // ToString() on the value to serialize it.
                else
                    s = new StringSerializer();
                
                // Set the serialization context
                if (s != null)
                    s.SerializationContext = ctx;

                return s;
            }
            return null;
        }
Exemple #7
0
        public async Task <ActionResult> Save(string data)
        {
            return(await RunActionAsync(async() =>
            {
                var model = data?.JsonToEntity <CalendarEventEntity>(throwIfException: false);
                if (model == null)
                {
                    return GetJsonRes("参数错误");
                }
                if (model.ByDay != null && model.ByDay.Value > 0)
                {
                    var rrule = new RecurrencePattern(FrequencyType.Daily, model.ByDay.Value);
                    var serializer = new RecurrencePatternSerializer();
                    var s = serializer.SerializeToString(rrule);
                    model.RRule = s;
                }
                model.HasRule = ValidateHelper.IsPlumpString(model.RRule).ToBoolInt();

                var org_uid = this.GetSelectedOrgUID();
                var loginuser = await this.X.context.GetAuthUserAsync();

                model.OrgUID = org_uid;
                model.UserUID = loginuser?.UserID;


                if (ValidateHelper.IsPlumpString(model.UID))
                {
                    var res = await this._calService.UpdateEvent(model);
                    if (res.error)
                    {
                        return GetJsonRes(res.msg);
                    }
                }
                else
                {
                    var res = await this._calService.AddEvent(model);
                    if (res.error)
                    {
                        return GetJsonRes(res.msg);
                    }
                }


                return GetJsonRes(string.Empty);
            }));
        }
Exemple #8
0
        /// <summary>
        /// Преобразует Outlook appointment  в иерархию объектов transferData
        /// </summary>
        /// <param name="appItem">The app item.</param>
        /// <returns></returns>
        private SyncTransferData Appointment2TransferData(OutlookAppointment appItem)
        {
            SyncTransferData          retVal     = null;
            ITransferDataSerializable serializer = new AppointmentSerializer(appItem);

            retVal = serializer.Serialize();
            if (appItem.IsRecurring)
            {
                OutlookRecurrencePattern rPattern = appItem.GetRecurrencePattern();
                serializer = new RecurrencePatternSerializer(rPattern);
                retVal.Childrens.Add(serializer.Serialize());
                serializer = null;
                foreach (OutlookException exception in rPattern.Exceptions)
                {
                    AppointmentTransferData transferException = new AppointmentTransferData();
                    if (!exception.Deleted)
                    {
                        OutlookAppointment appointmentException = exception.AppointmentItem;
                        serializer        = new AppointmentSerializer(appointmentException);
                        transferException = (AppointmentTransferData)serializer.Serialize();
                        //exception recipient
                        foreach (OutlookRecipient exceptionRecipient in appointmentException.Recipients)
                        {
                            serializer = new RecipientSerializer(exceptionRecipient);
                            transferException.Childrens.Add(serializer.Serialize());
                        }
                    }
                    transferException.DeletedException = exception.Deleted;
                    transferException.RecurrenceId     = exception.OriginalDate;

                    retVal.Childrens.Add(transferException);
                }
            }
            //appointment recipient
            foreach (OutlookRecipient recipient in appItem.Recipients)
            {
                serializer = new RecipientSerializer(recipient);
                retVal.Childrens.Add(serializer.Serialize());
            }

            //Инициализируем дополнительные поля (LastModified и Uri)
            retVal.LastModified = (ulong)appItem.LastModificationTime.ToUniversalTime().Ticks;
            retVal.Uri          = appItem.EntryID;

            return(retVal);
        }
        public void Test2()
        {
            IICalendar iCal = new iCalendar();
            IEvent evt = iCal.Create<Event>();
            evt.Summary = "Event summary";
            evt.Start = new iCalDateTime(DateTime.SpecifyKind(DateTime.Today, DateTimeKind.Utc));

            IRecurrencePattern recur = new RecurrencePattern();
            recur.Frequency = FrequencyType.Daily;
            recur.Count = 3;
            recur.ByDay.Add(new WeekDay(DayOfWeek.Monday));
            recur.ByDay.Add(new WeekDay(DayOfWeek.Wednesday));
            recur.ByDay.Add(new WeekDay(DayOfWeek.Friday));
            evt.RecurrenceRules.Add(recur);

            RecurrencePatternSerializer serializer = new RecurrencePatternSerializer();
            Assert.IsTrue(string.Compare(serializer.SerializeToString(recur), "FREQ=DAILY;COUNT=3;BYDAY=MO,WE,FR") == 0,
                "Serialized recurrence string is incorrect");
        }
Exemple #10
0
        /// <summary>
        ///     Returns a <see cref="System.String" /> that represents this instance.
        /// </summary>
        /// <returns>
        ///     A <see cref="System.String" /> that represents this instance.
        /// </returns>
        public override string ToString( )
        {
            var serializer = new RecurrencePatternSerializer( );

            return(serializer.SerializeToString(this));
        }
        /// <summary>
        /// Returns a serializer that can be used to serialize and object
        /// of type <paramref name="objectType"/>.
        /// <note>
        ///     TODO: Add support for caching.
        /// </note>
        /// </summary>
        /// <param name="objectType">The type of object to be serialized.</param>
        /// <param name="ctx">The serialization context.</param>
        public virtual ISerializer Build(Type objectType, SerializationContext ctx)
        {
            if (objectType != null)
            {
                ISerializer s;

                if (typeof(Attachment).IsAssignableFrom(objectType))
                {
                    s = new AttachmentSerializer();
                }
                else if (typeof(Attendee).IsAssignableFrom(objectType))
                {
                    s = new AttendeeSerializer();
                }
                else if (typeof(IDateTime).IsAssignableFrom(objectType))
                {
                    s = new DateTimeSerializer();
                }
                else if (typeof(FreeBusyEntry).IsAssignableFrom(objectType))
                {
                    s = new FreeBusyEntrySerializer();
                }
                else if (typeof(GeographicLocation).IsAssignableFrom(objectType))
                {
                    s = new GeographicLocationSerializer();
                }
                else if (typeof(Organizer).IsAssignableFrom(objectType))
                {
                    s = new OrganizerSerializer();
                }
                else if (typeof(Period).IsAssignableFrom(objectType))
                {
                    s = new PeriodSerializer();
                }
                else if (typeof(PeriodList).IsAssignableFrom(objectType))
                {
                    s = new PeriodListSerializer();
                }
                else if (typeof(RecurrencePattern).IsAssignableFrom(objectType))
                {
                    s = new RecurrencePatternSerializer();
                }
                else if (typeof(RequestStatus).IsAssignableFrom(objectType))
                {
                    s = new RequestStatusSerializer();
                }
                else if (typeof(StatusCode).IsAssignableFrom(objectType))
                {
                    s = new StatusCodeSerializer();
                }
                else if (typeof(Trigger).IsAssignableFrom(objectType))
                {
                    s = new TriggerSerializer();
                }
                else if (typeof(UtcOffset).IsAssignableFrom(objectType))
                {
                    s = new UtcOffsetSerializer();
                }
                else if (typeof(WeekDay).IsAssignableFrom(objectType))
                {
                    s = new WeekDaySerializer();
                }
                // Default to a string serializer, which simply calls
                // ToString() on the value to serialize it.
                else
                {
                    s = new StringSerializer();
                }

                // Set the serialization context
                s.SerializationContext = ctx;

                return(s);
            }
            return(null);
        }
        public void Bug3292737()
        {
            using (StringReader sr = new StringReader("FREQ=WEEKLY;UNTIL=20251126"))
            {
                RecurrencePatternSerializer serializer = new RecurrencePatternSerializer();
                var rp = (RecurrencePattern)serializer.Deserialize(sr);

                Assert.IsNotNull(rp);
                Assert.AreEqual(new DateTime(2025, 11, 26), rp.Until);
            }
        }
        public void Bug3119920()
        {
            using (StringReader sr = new StringReader("FREQ=WEEKLY;UNTIL=20251126T120000;INTERVAL=1;BYDAY=MO"))
            {
                DateTime start = DateTime.Parse("2010-11-27 9:00:00");
                RecurrencePatternSerializer serializer = new RecurrencePatternSerializer();
                RecurrencePattern rp = (RecurrencePattern)serializer.Deserialize(sr);
                RecurrencePatternEvaluator rpe = new RecurrencePatternEvaluator(rp);
                IList<IPeriod> recurringPeriods = rpe.Evaluate(new iCalDateTime(start), start, rp.Until, false);
                
                IPeriod period = recurringPeriods.ElementAt(recurringPeriods.Count() - 1);

                Assert.AreEqual(new iCalDateTime(2025, 11, 24, 9, 0, 0), period.StartTime);
            }
        }
        public async Task <List <ViewModel.CalendarItem> > GetCalendar(Configuration.CalendarAndColor config)
        {
            List <ViewModel.CalendarItem> items = new List <ViewModel.CalendarItem>();

            try
            {
                string icsStr = await WebHelper.DownloadString(config.URL);

                string[] cal_array = icsStr.Split(new string[] { "\r\n", "\n", }, StringSplitOptions.RemoveEmptyEntries);
                var      in_event  = false;
                var      in_alarm  = false;
                //Use as a holder for the current event being proccessed.
                ViewModel.CalendarItem cur_event = null;
                for (var i = 0; i < cal_array.Length; i++)
                {
                    try
                    {
                        string ln = cal_array[i].Trim();
                        //If we encounted a new Event, create a blank event object + set in event options.
                        if (!in_event && ln == "BEGIN:VEVENT")
                        {
                            in_event            = true;
                            cur_event           = new ViewModel.CalendarItem();
                            cur_event.TextBrush = config.Foreground;
                        }
                        //If we encounter end event, complete the object and add it to our events array then clear it for reuse.
                        if (in_event && ln == "END:VEVENT")
                        {
                            in_event = false;


                            items.Add(cur_event);
                            cur_event = null;
                        }
                        //If we are in an event
                        else if (in_event)
                        {
                            if (ln == "BEGIN:VALARM")
                            {
                                in_alarm = true;
                            }
                            else if (ln == "END:VALARM")
                            {
                                in_alarm = false;
                            }
                            else
                            {
                                //Split the item based on the first ":"
                                var idx = ln.IndexOf(':');

                                if (idx != -1)
                                {
                                    //Apply trimming to values to reduce risks of badly formatted ical files.
                                    var type = ln.Substring(0, idx).Trim();//Trim
                                    if (in_alarm)
                                    {
                                        type = "valarm_" + type;
                                    }
                                    var    val    = ln.Substring(idx + 1).Trim();
                                    string subkey = "";
                                    if (type.Contains(";"))
                                    {
                                        string t2        = type;
                                        int    subkeysep = t2.IndexOf(";");
                                        type   = t2.Substring(0, subkeysep);
                                        subkey = t2.Substring(subkeysep + 1);
                                    }


                                    //If the type is a start date, proccess it and store details
                                    if (type == "DTSTART")
                                    {
                                        cur_event.Start = GetDateTime(val);
                                        if (cur_event.Start == DateTime.MinValue)
                                        {
                                            cur_event.Start = GetDateTime2(val);
                                        }
                                    }
                                    //If the type is an end date, do the same as above
                                    else if (type == "DTEND")
                                    {
                                        cur_event.End = GetDateTime(val);
                                        if (cur_event.End == DateTime.MinValue)
                                        {
                                            cur_event.End = GetDateTime2(val);
                                        }
                                    }
                                    //Convert timestamp
                                    else if (type == "DTSTAMP")
                                    {
                                        cur_event.Stamp = GetDateTime(val);
                                    }
                                    else if (type == "SUMMARY")
                                    {
                                        cur_event.Text = val
                                                         .Replace("\\r\\n", "")
                                                         .Replace("\\n", "")
                                                         .Replace("\\,", ",")
                                                         .Trim();
                                    }
                                    else if (type == "DESCRIPTION")
                                    {
                                        int j = i;
                                        while (j++ < cal_array.Length && cal_array[j].StartsWith(" "))
                                        {
                                            i++;
                                            val += cal_array[j].TrimStart();
                                        }
                                    }
                                    else if (type == "RRULE")
                                    {
                                        cur_event.RRULE = val;
                                    }
                                    else
                                    {
                                        val = val
                                              .Replace("\\r\\n", "")
                                              .Replace("\\n", "")
                                              .Replace("\\,", ",")
                                              .Trim();
                                    }

                                    //Add the value to our event object.
                                    cur_event.Values[type] = val;
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.e(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.e(ex);
            }


            if (items.Count == 0)
            {
                return(null);
            }

            List <ViewModel.CalendarItem> ritems = new List <ViewModel.CalendarItem>();

            foreach (var item in items)
            {
                if (string.IsNullOrEmpty(item.RRULE))
                {
                    ritems.Add(item);
                }
                else
                {
                    try
                    {
                        RecurrencePattern r = new RecurrencePattern(item.RRULE);

                        var      duration = item.End - item.Start;
                        DateTime begin    = DateTimeFactory.Instance.Now;
                        DateTime end      = begin.AddYears(10);
                        foreach (var date in RecurrencePatternSerializer.GetDates(begin, begin, end, 2, r, false))
                        {
                            var nitem = item.Copy();
                            nitem.Start = date;
                            nitem.End   = date + duration;
                            nitem.RRULE = null;
                            ritems.Add(nitem);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.e(ex);
                    }
                }
            }



            return(ritems);
        }