Ejemplo n.º 1
0
        private DomainEventWrapper GetDomainEventWrapperFromEvent(TEventSet @event)
        {
            var domainEvent = _serializer.Deserialize <IDomainEvent>(@event.Payload);

            return(new DomainEventWrapper(@event.EventId, @event.AggregateId, @event.Sequence, @event.AggregateVersion,
                                          domainEvent));
        }
        /// <summary>
        /// Deserializes from bytes.
        /// </summary>
        /// <param name="serializer">The serializer.</param>
        /// <param name="data">The data.</param>
        /// <param name="type">The type.</param>
        /// <param name="encoding">The encoding.</param>
        /// <returns>System.Object.</returns>
        public static object DeserializeFromBytes(this IStringSerializer serializer, byte[] data, Type type, Encoding encoding = null)
        {
            var encoder = encoding ?? Encoding.UTF8;
            var str     = encoder.GetString(data, 0, data.Length);

            return(serializer.Deserialize(str, type));
        }
        public static T DeserializeFromBytes <T>(this IStringSerializer serializer, byte[] data, Encoding encoding = null)
        {
            var encoder = encoding ?? Encoding.UTF8;
            var str     = encoder.GetString(data, 0, data.Length);

            return(serializer.Deserialize <T>(str));
        }
Ejemplo n.º 4
0
        public static KnownPublicKeys Load(IDataStore store, IStringSerializer serializer)
        {
            if (store == null)
            {
                throw new ArgumentNullException("store");
            }
            if (serializer == null)
            {
                throw new ArgumentNullException("serializer");
            }

            string json = String.Empty;

            using (FileLock fileLock = New <FileLocker>().Acquire(store))
            {
                if (store.IsAvailable)
                {
                    using (StreamReader reader = new StreamReader(store.OpenRead(), Encoding.UTF8))
                    {
                        json = reader.ReadToEnd();
                    }
                }
            }
            KnownPublicKeys knownPublicKeys = serializer.Deserialize <KnownPublicKeys>(json);

            if (knownPublicKeys == null)
            {
                knownPublicKeys = new KnownPublicKeys();
            }
            knownPublicKeys._store      = store;
            knownPublicKeys._serializer = serializer;
            return(knownPublicKeys);
        }
Ejemplo n.º 5
0
        public static bool CanSerializeString <T>(this IStringSerializer serializer, T item)
        {
            var text = serializer.Serialize(item);

            var obj = serializer.Deserialize <T>(text);

            return(obj.Equals(item));
        }
Ejemplo n.º 6
0
        public override object Deserialize(TextReader tr)
        {
            string value = tr.ReadToEnd();

            IPeriod            p       = CreateAndAssociate() as IPeriod;
            ISerializerFactory factory = GetService <ISerializerFactory>();

            if (p != null && factory != null)
            {
                IStringSerializer dtSerializer       = factory.Build(typeof(IDateTime), SerializationContext) as IStringSerializer;
                IStringSerializer durationSerializer = factory.Build(typeof(TimeSpan), SerializationContext) as IStringSerializer;
                if (dtSerializer != null && durationSerializer != null)
                {
                    // Decode the value as necessary
                    value = Decode(p, value);

                    string[] values = value.Split('/');
                    if (values.Length != 2)
                    {
                        return(false);
                    }

                    StringReader reader = new StringReader(values[0]);
                    p.StartTime = dtSerializer.Deserialize(reader) as IDateTime;
                    reader.Dispose();
                    reader    = new StringReader(values[1]);
                    p.EndTime = dtSerializer.Deserialize(reader) as IDateTime;
                    reader.Dispose();

                    if (p.EndTime == null)
                    {
                        reader     = new StringReader(values[1]);
                        p.Duration = (TimeSpan)durationSerializer.Deserialize(reader);
                        reader.Dispose();
                    }

                    // Only return an object if it has been deserialized correctly.
                    if (p.StartTime != null && p.Duration != null)
                    {
                        return(p);
                    }
                }
            }

            return(null);
        }
Ejemplo n.º 7
0
 private static IICalendar DeserializeCalendar(string iCalData, IStringSerializer calendarSerializer)
 {
     using (var reader = new StringReader(iCalData))
     {
         var calendarCollection = (iCalendarCollection)calendarSerializer.Deserialize(reader);
         return(calendarCollection[0]);
     }
 }
Ejemplo n.º 8
0
        public override object Deserialize(TextReader tr)
        {
            string value = tr.ReadToEnd();

            ITrigger t = CreateAndAssociate() as ITrigger;

            if (t != null)
            {
                // Push the trigger onto the serialization stack
                SerializationContext.Push(t);
                try
                {
                    // Decode the value as needed
                    value = Decode(t, value);

                    // Set the trigger relation
                    if (t.Parameters.ContainsKey("RELATED") &&
                        t.Parameters.Get("RELATED").Equals("END"))
                    {
                        t.Related = TriggerRelation.End;
                    }

                    ISerializerFactory factory = GetService <ISerializerFactory>();
                    if (factory != null)
                    {
                        Type valueType = t.GetValueType() ?? typeof(TimeSpan);
                        IStringSerializer serializer = factory.Build(valueType, SerializationContext) as IStringSerializer;
                        if (serializer != null)
                        {
                            StringReader reader = new StringReader(value);
                            object       obj    = serializer.Deserialize(reader);
                            reader.Dispose();

                            if (obj != null)
                            {
                                if (obj is IDateTime)
                                {
                                    t.DateTime = (IDateTime)obj;
                                }
                                else
                                {
                                    t.Duration = (TimeSpan)obj;
                                }

                                return(t);
                            }
                        }
                    }
                }
                finally
                {
                    // Pop the trigger off the serialization stack
                    SerializationContext.Pop();
                }
            }
            return(null);
        }
Ejemplo n.º 9
0
 protected T LoadObject(string pathToFile, string key)
 {
     using (StreamReader reader = File.OpenText(pathToFile))
     {
         var payload = reader.ReadToEnd();
         var result  = serializer.Deserialize(payload, key);
         return(result);
     }
 }
Ejemplo n.º 10
0
        public void TestDeserializeWithEnglishUsCulture()
        {
            IStringSerializer serializer = New <IStringSerializer>();
            string            json       = "{\r\n  \"messageCulture\": \"en-US\",\r\n  \"customMessage\": \"A message\"\r\n}".Replace("\r\n", Environment.NewLine);

            CustomMessageParameters parameters = serializer.Deserialize <CustomMessageParameters>(json);

            Assert.That(parameters.MessageCulture.ToString(), Is.EqualTo("en-US"));
            Assert.That(parameters.CustomMessage, Is.EqualTo("A message"));
        }
        public ApplicationSettings GetApplicationSettings()
        {
            if (!File.Exists(_filePath))
            {
                return(null);
            }

            string serializedSettings = File.ReadAllText(_filePath);

            return(_stringSerializer.Deserialize <ApplicationSettings>(serializedSettings));
        }
Ejemplo n.º 12
0
        public override object Deserialize(TextReader tr)
        {
            string value = tr.ReadToEnd();

            IRequestStatus rs = CreateAndAssociate() as IRequestStatus;

            if (rs != null)
            {
                // Decode the value as needed
                value = Decode(rs, value);

                // Push the object onto the serialization stack
                SerializationContext.Push(rs);

                try
                {
                    ISerializerFactory factory = GetService <ISerializerFactory>();
                    if (factory != null)
                    {
                        Match match = Regex.Match(value, @"(.*?[^\\]);(.*?[^\\]);(.+)");
                        if (!match.Success)
                        {
                            match = Regex.Match(value, @"(.*?[^\\]);(.+)");
                        }

                        if (match.Success)
                        {
                            IStringSerializer serializer = factory.Build(typeof(IStatusCode), SerializationContext) as IStringSerializer;
                            if (serializer != null)
                            {
                                StringReader reader = new StringReader(Unescape(match.Groups[1].Value));
                                rs.StatusCode = serializer.Deserialize(reader) as IStatusCode;
                                reader.Dispose();

                                rs.Description = Unescape(match.Groups[2].Value);
                                if (match.Groups.Count == 4)
                                {
                                    rs.ExtraData = Unescape(match.Groups[3].Value);
                                }

                                return(rs);
                            }
                        }
                    }
                }
                finally
                {
                    // Pop the object off the serialization stack
                    SerializationContext.Pop();
                }
            }
            return(null);
        }
Ejemplo n.º 13
0
        public T Load <T>(string fileName, bool resetIds = false)
        {
            var xmlContent         = XmlHelper.XmlContentFromFile(fileName);
            var deserializedObject = _stringSerializer.Deserialize <T>(xmlContent);

            if (resetIds)
            {
                _objectIdResetter.ResetIdFor(deserializedObject);
            }

            return(deserializedObject);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Builds a <see cref="Response{T}"/> for a given <see cref="HttpWebResponse"/>
        /// containing a serialized representation of strongly-typed data in the body of
        /// the response.
        /// </summary>
        /// <typeparam name="T">The object model type for the data contained in the body of <paramref name="resp"/>.</typeparam>
        /// <param name="resp">The response from the REST request.</param>
        /// <param name="isError">Indicates whether the response is an error response. If the value is <c>true</c> the response
        /// will not be deserialized to <typeparamref name="T"/></param>
        /// <returns>A <see cref="Response{T}"/> instance representing the response from the REST API call.</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="resp"/> is <c>null</c>.</exception>
        /// <exception cref="StringSerializationException">
        /// If the body of <paramref name="resp"/> could not be deserialized to an object of type <typeparamref name="T"/>.
        /// </exception>
        private Response <T> BuildWebResponse <T>(HttpWebResponse resp, bool isError = false)
        {
            var baseReponse = BuildWebResponse(resp);
            T   data        = default(T);

            if (!isError)
            {
                if (baseReponse != null && !string.IsNullOrEmpty(baseReponse.RawBody))
                {
                    data = _stringSerializer.Deserialize <T>(baseReponse.RawBody);
                }
            }

            return(new Response <T>(baseReponse, data));
        }
Ejemplo n.º 15
0
        /// <inheritdoc cref="ISyncCacheStore{TCacheEntryOptions}.GetEntry{T}"/>
        public CacheEntry <T> GetEntry <T>(string key)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            var value = _distributedCache.GetString(key);

            if (value == null)
            {
                return(null);
            }

            try
            {
                return(_stringSerializer.Deserialize <CacheEntry <T> >(value));
            }
            catch
            {
                _distributedCache.Remove(key);
                throw;
            }
        }
        public static T Deserialize <T>(this IStringSerializer serializer, IDataStore serializedStore)
        {
            if (serializer == null)
            {
                throw new ArgumentNullException("serializer");
            }
            if (serializedStore == null)
            {
                throw new ArgumentNullException("serializedStore");
            }

            using (StreamReader reader = new StreamReader(serializedStore.OpenRead(), Encoding.UTF8))
            {
                string serialized = reader.ReadToEnd();
                return(serializer.Deserialize <T>(serialized));
            }
        }
Ejemplo n.º 17
0
        public IApplicationSettings Load()
        {
            try
            {
                foreach (var filePath in _configuration.ApplicationSettingsFilePaths.Where(FileHelper.FileExists))
                {
                    var xmlContent = XmlHelper.XmlContentFromFile(filePath);
                    return(_stringSerializer.Deserialize <IApplicationSettings>(xmlContent));
                }
            }
            //We do not want to have a crash if the user has edited the configuration by hand
            catch (Exception)
            {
                return(_defaultApplicationSettings);
            }

            return(_defaultApplicationSettings);
        }
Ejemplo n.º 18
0
        public override object Deserialize(TextReader tr)
        {
            IStringSerializer serializer = GetMappedSerializer();

            if (serializer != null)
            {
                string value       = tr.ReadToEnd();
                object returnValue = serializer.Deserialize(new StringReader(value));

                // Default to returning the string representation of the value
                // if the value wasn't formatted correctly.
                // FIXME: should this be a try/catch?  Should serializers be throwing
                // an InvalidFormatException?  This may have some performance issues
                // as try/catch is much slower than other means.
                return(returnValue ?? value);
            }
            return(null);
        }
Ejemplo n.º 19
0
        public override object Deserialize(TextReader tr)
        {
            string value = tr.ReadToEnd();

            // Create the day specifier and associate it with a calendar object
            IPeriodList        rdt     = CreateAndAssociate() as IPeriodList;
            ISerializerFactory factory = GetService <ISerializerFactory>();

            if (rdt != null && factory != null)
            {
                // Decode the value, if necessary
                value = Decode(rdt, value);

                IStringSerializer dtSerializer     = factory.Build(typeof(IDateTime), SerializationContext) as IStringSerializer;
                IStringSerializer periodSerializer = factory.Build(typeof(IPeriod), SerializationContext) as IStringSerializer;
                if (dtSerializer != null && periodSerializer != null)
                {
                    string[] values = value.Split(',');
                    foreach (string v in values)
                    {
                        StringReader reader = new StringReader(v);
                        IDateTime    dt     = dtSerializer.Deserialize(reader) as IDateTime;
                        reader.Dispose();
                        reader = new StringReader(v);
                        IPeriod p = periodSerializer.Deserialize(reader) as IPeriod;
                        reader.Dispose();

                        if (dt != null)
                        {
                            dt.AssociatedObject = rdt.AssociatedObject;
                            rdt.Add(dt);
                        }
                        else if (p != null)
                        {
                            p.AssociatedObject = rdt.AssociatedObject;
                            rdt.Add(p);
                        }
                    }
                    return(rdt);
                }
            }

            return(null);
        }
        public Task <T> LoadTemplateAsync <T>(Template template)
        {
            if (template.DatabaseType == TemplateDatabaseType.Remote)
            {
                return(_remoteTemplateRepository.LoadTemplateAsync <T>(template.DowncastTo <RemoteTemplate>()));
            }

            using (establishConnection(template.DatabaseType))
            {
                var connection = databaseConnection();
                try
                {
                    addTemplateNameParameter(template.Name, connection);

                    var sqlQuery = $"SELECT t.{TemplateTable.Columns.XML} FROM {TemplateTable.NAME} t WHERE t.{TemplateTable.Columns.TEMPLATE_TYPE} IN ({typeFrom(template.Type)}) AND t.{TemplateTable.Columns.NAME} = {_pName}";

                    var table = new DASDataTable(connection);
                    connection.FillDataTable(table, sqlQuery);

                    if (table.Rows.Count() > 0)
                    {
                        var serializationString = table.Rows.ItemByIndex(0)[TemplateTable.Columns.XML].ToString();
                        var objectFromTemplate  = _stringSerializer.Deserialize <T>(serializationString);
                        _objectIdResetter.ResetIdFor(objectFromTemplate);

                        //Rename the template according to the template name as the template might have been renamed
                        var withName = objectFromTemplate as IWithName;
                        if (withName != null)
                        {
                            withName.Name = template.Name;
                        }

                        return(Task.FromResult(objectFromTemplate));
                    }
                }
                finally
                {
                    removeNameParameter(connection);
                }

                return(default);
Ejemplo n.º 21
0
        /// <summary>
        /// Import a public key manually by the user. The key is also marked as imported by the user.
        /// </summary>
        /// <param name="publicKeyStore"></param>
        /// <returns>true if the import was successful</returns>
        public bool UserImport(IDataStore publicKeyStore)
        {
            UserPublicKey publicKey = null;

            try
            {
                publicKey = _serializer.Deserialize <UserPublicKey>(publicKeyStore);
            }
            catch (JsonException jex)
            {
                New <IReport>().Exception(jex);
            }
            if (publicKey == null)
            {
                return(false);
            }

            publicKey.IsUserImported = true;
            AddOrReplace(publicKey);

            return(true);
        }
Ejemplo n.º 22
0
        public override object Deserialize(TextReader tr)
        {
            ICalendarProperty p = SerializationContext.Peek() as ICalendarProperty;

            if (p != null)
            {
                // Get a serializer factory to deserialize the contents of this list
                ISerializerFactory sf = GetService <ISerializerFactory>();

                object listObj = Activator.CreateInstance(_ObjectType);
                if (listObj != null)
                {
                    // Get a serializer for the inner type
                    IStringSerializer stringSerializer = sf.Build(_InnerType, SerializationContext) as IStringSerializer;;

                    if (stringSerializer != null)
                    {
                        // Deserialize the inner object
                        string value    = tr.ReadToEnd();
                        object objToAdd = stringSerializer.Deserialize(new StringReader(value));

                        // If deserialization failed, pass the string value
                        // into the list.
                        if (objToAdd == null)
                        {
                            objToAdd = value;
                        }

                        if (objToAdd != null)
                        {
                            // FIXME: cache this
                            MethodInfo mi = _ObjectType.GetMethod("Add");
                            if (mi != null)
                            {
                                // Determine if the returned object is an IList<ObjectType>,
                                // rather than just an ObjectType.
                                if (objToAdd is IEnumerable &&
                                    objToAdd.GetType().Equals(typeof(List <>).MakeGenericType(_InnerType)))
                                {
                                    // Deserialization returned an IList<ObjectType>, instead of
                                    // simply an ObjectType.  So, let's enumerate through the
                                    // items in the list and add them individually to our
                                    // list.
                                    foreach (object innerObj in (IEnumerable)objToAdd)
                                    {
                                        mi.Invoke(listObj, new object[] { innerObj });
                                    }
                                }
                                else
                                {
                                    // Add the object to the list
                                    mi.Invoke(listObj, new object[] { objToAdd });
                                }
                                return(listObj);
                            }
                        }
                    }
                }
            }

            return(null);
        }
 /// <summary>
 /// Deserializes from reader.
 /// </summary>
 /// <returns>The serialized object from reader.</returns>
 /// <param name="reader">Reader to deserialize from.</param>
 public static T DeserializeFromReader <T>(this IStringSerializer serializer, TextReader reader)
 {
     return(serializer.Deserialize <T>(reader.ReadToEnd()));
 }
        /// <summary>
        /// Deserializes from stream.
        /// </summary>
        /// <returns>The deserialized object.</returns>
        /// <param name="serializer">The string serializer.</param>
        /// <param name="stream">Stream to deserialize from.</param>
        /// <typeparam name="T">The type of object to deserialize.</typeparam>
        public static T DeserializeFromStream <T>(this IStringSerializer serializer, Stream stream)
        {
            var text = new StreamReader(stream).ReadToEnd();

            return(serializer.Deserialize <T>(text));
        }
Ejemplo n.º 25
0
 public TObject Deserialize <TObject>(string serializationString)
 {
     return(_underlyingSerializationManager.Deserialize <TObject>(_compression.Decompress(serializationString)));
 }
Ejemplo n.º 26
0
 public override T ReadJson(JsonReader reader, Type objectType, T existingValue, bool hasExistingValue, JsonSerializer serializer)
 => _serializer.Deserialize(reader.Value.ToString());    //.Dump());
        /// <summary>
        /// Deserialize from stream.
        /// </summary>
        /// <returns>The deserialized object.</returns>
        /// <param name="serializer">The string serializer.</param>
        /// <param name="stream">Stream to deserialize from.</param>
        /// <param name="type">The type of object to deserialize.</param>
        public static object DeserializeFromStream(this IStringSerializer serializer, Stream stream, Type type)
        {
            var text = new StreamReader(stream).ReadToEnd();

            return(serializer.Deserialize(text, type));
        }
Ejemplo n.º 28
0
        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)
                                                r.Until = dt.Value;                                            
                                        }
                                    } 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;
                            }
                        }
                    }
                }
                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, 1, int.MaxValue);
                    CheckRange("COUNT", r.Count, 1, 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;            
        }
Ejemplo n.º 29
0
 private T ToTResult(IEnumerable <byte> bytes)
 => _serializer.Deserialize(new string(bytes.Select(Convert.ToChar).ToArray()));