Beispiel #1
0
        private static DateTimeOffset CreateDateTimeValue(object propertyValue, SyndicationItemProperty targetProperty, ODataWriterBehavior writerBehavior)
        {
            Debug.Assert(
                writerBehavior.FormatBehaviorKind != ODataBehaviorKind.WcfDataServicesClient,
                "CreateDateTimeValue should not be used in WCF DS client mode.");

            if (propertyValue == null)
            {
                return(DateTimeOffset.Now);
            }

            if (propertyValue is DateTimeOffset)
            {
                return((DateTimeOffset)propertyValue);
            }

            if (propertyValue is DateTime)
            {
                // DateTimeOffset takes care of DateTimes of Unspecified kind so we won't end up
                // with datetime without timezone info mapped to atom:updated or atom:published element.
                return(new DateTimeOffset((DateTime)propertyValue));
            }

            string stringValue = propertyValue as string;

            if (stringValue != null)
            {
                DateTimeOffset date;
                if (!DateTimeOffset.TryParse(stringValue, out date))
                {
                    DateTime result;
                    if (!DateTime.TryParse(stringValue, out result))
                    {
                        throw new ODataException(ODataErrorStrings.EpmSyndicationWriter_DateTimePropertyCanNotBeConverted(targetProperty.ToString()));
                    }

                    return(new DateTimeOffset(result));
                }

                return(date);
            }

            try
            {
                return(new DateTimeOffset(Convert.ToDateTime(propertyValue, CultureInfo.InvariantCulture)));
            }
            catch (Exception e)
            {
                if (!ExceptionUtils.IsCatchableExceptionType(e))
                {
                    throw;
                }

                throw new ODataException(ODataErrorStrings.EpmSyndicationWriter_DateTimePropertyCanNotBeConverted(targetProperty.ToString()));
            }
        }