コード例 #1
0
        public Expression IndexOfMethod(IndexOfMethod method, LiteralExpression[] arguments)
        {
            int result;

            if (LiteralUtil.IsAnyNull(arguments))
            {
                result = -1;
            }
            else
            {
                result = LiteralUtil.CoerceString(arguments[0]).IndexOf(
                    LiteralUtil.CoerceString(arguments[1]),
                    StringComparison.InvariantCultureIgnoreCase
                    );
            }

            if (result == -1)
            {
                return(new LiteralExpression(null, LiteralType.Null));
            }
            else
            {
                return(new LiteralExpression(result + 1, LiteralType.Int));
            }
        }
コード例 #2
0
        private ICriterion CreateLikeCriterion(Expression projectionExpression, Expression literalExpression, MatchMode matchMode)
        {
            var projection = ProjectionVisitor.CreateProjection(projectionExpression);
            var value      = LiteralUtil.CoerceString((LiteralExpression)literalExpression);

            return(_context.CaseSensitiveLike ? Restrictions.Like(projection, value, matchMode) : Restrictions.InsensitiveLike(projection, value, matchMode));
        }
コード例 #3
0
        public Expression CastMethod(CastMethod method, LiteralExpression[] arguments)
        {
            Debug.Assert(arguments[1].LiteralType == LiteralType.String);

            if (arguments[0].LiteralType == LiteralType.Null)
            {
                return(arguments[0]);
            }

            var type = LiteralUtil.GetCompatibleType((string)arguments[1].Value);

            try
            {
                return(new LiteralExpression(Convert.ChangeType(arguments[0].Value, type, CultureInfo.InvariantCulture)));
            }
            catch (Exception ex)
            {
                throw new ODataException(
                          String.Format(
                              ErrorMessages.Method_CannotCast, arguments[1].Value
                              ),
                          ex
                          );
            }
        }
コード例 #4
0
        public Expression ConcatMethod(ConcatMethod method, LiteralExpression[] arguments)
        {
            if (arguments.Length == 1)
            {
                return(arguments[0]);
            }
            else if (arguments[0].LiteralType == LiteralType.Null)
            {
                if (arguments[1].LiteralType == LiteralType.Null)
                {
                    return(new LiteralExpression(null, LiteralType.Null));
                }
                else
                {
                    return(arguments[1]);
                }
            }
            else if (arguments[1].LiteralType == LiteralType.Null)
            {
                return(arguments[0]);
            }
            else
            {
                string result =
                    LiteralUtil.CoerceString(arguments[0]) +
                    LiteralUtil.CoerceString(arguments[1]);

                return(new LiteralExpression(result, LiteralType.String));
            }
        }
コード例 #5
0
        private Expression ResolveArithmeticLiterals(ArithmeticExpression expression, LiteralExpression leftLiteral, LiteralExpression rightLiteral)
        {
            object left  = leftLiteral.Value;
            object right = rightLiteral.Value;
            object result;

            var type = LiteralUtil.CoerceLiteralValues(ref left, leftLiteral.LiteralType, ref right, rightLiteral.LiteralType);

            switch (expression.Operator)
            {
            case Operator.Add: result = ResolveAdd(left, right, type); break;

            case Operator.Div: result = ResolveDiv(left, right, type); break;

            case Operator.Mod: result = ResolveMod(left, right, type); break;

            case Operator.Mul: result = ResolveMul(left, right, type); break;

            case Operator.Sub: result = ResolveSub(left, right, type); break;

            default:
                throw new NotSupportedException();
            }

            if (result == null)
            {
                throw new ODataException(String.Format(
                                             ErrorMessages.Expression_IncompatibleTypes,
                                             expression.Operator,
                                             type
                                             ));
            }

            return(new LiteralExpression(result, type));
        }
コード例 #6
0
        public Expression SubStringOfMethod(SubStringOfMethod method, LiteralExpression[] arguments)
        {
            if (arguments.Length == 1)
            {
                return(arguments[0]);
            }
            else
            {
                bool result;

                if (LiteralUtil.IsAnyNull(arguments))
                {
                    result = false;
                }
                else
                {
                    result = LiteralUtil.CoerceString(arguments[1]).IndexOf(
                        LiteralUtil.CoerceString(arguments[0]),
                        StringComparison.InvariantCultureIgnoreCase
                        ) != -1;
                }

                return(new LiteralExpression(result, LiteralType.Boolean));
            }
        }
コード例 #7
0
        public Expression IsOfMethod(IsOfMethod method, LiteralExpression[] arguments)
        {
            Debug.Assert(arguments[1].LiteralType == LiteralType.String);

            var type = LiteralUtil.GetCompatibleType((string)arguments[1].Value);

            return(new LiteralExpression(type.IsInstanceOfType(arguments[0].Value), LiteralType.Boolean));
        }
コード例 #8
0
        public LiteralToken(object value, LiteralType literalType)
            : base(TokenType.Literal)
        {
            Value       = value;
            LiteralType = literalType;

            Debug.Assert(literalType == LiteralUtil.GetLiteralType(value));
        }
コード例 #9
0
 private bool ResolveEquals(object left, object right, LiteralType type)
 {
     if (type == LiteralType.Binary)
     {
         return(LiteralUtil.ByteArrayEquals((byte[])left, (byte[])right));
     }
     else
     {
         return(Equals(left, right));
     }
 }
コード例 #10
0
        public Expression LengthMethod(LengthMethod method, LiteralExpression[] arguments)
        {
            if (LiteralUtil.IsAnyNull(arguments))
            {
                return(new LiteralExpression(null, LiteralType.Null));
            }
            else
            {
                int result = LiteralUtil.CoerceString(arguments[0]).Length;

                return(new LiteralExpression(result, LiteralType.Int));
            }
        }
コード例 #11
0
        public Expression TrimMethod(TrimMethod method, LiteralExpression[] arguments)
        {
            if (LiteralUtil.IsAnyNull(arguments))
            {
                return(new LiteralExpression(null, LiteralType.Null));
            }
            else
            {
                string result = LiteralUtil.CoerceString(arguments[0]).Trim();

                return(new LiteralExpression(result, LiteralType.String));
            }
        }
コード例 #12
0
        public Expression ReplaceMethod(ReplaceMethod method, LiteralExpression[] arguments)
        {
            if (LiteralUtil.IsAnyNull(arguments))
            {
                return(new LiteralExpression(null, LiteralType.Null));
            }
            else
            {
                string result = LiteralUtil.CoerceString(arguments[0]).Replace(
                    LiteralUtil.CoerceString(arguments[1]),
                    LiteralUtil.CoerceString(arguments[2])
                    );

                return(new LiteralExpression(result, LiteralType.String));
            }
        }
コード例 #13
0
        public Expression EndsWithMethod(EndsWithMethod method, LiteralExpression[] arguments)
        {
            bool result;

            if (LiteralUtil.IsAnyNull(arguments))
            {
                result = false;
            }
            else
            {
                result = LiteralUtil.CoerceString(arguments[0]).EndsWith(
                    LiteralUtil.CoerceString(arguments[1]),
                    StringComparison.InvariantCultureIgnoreCase
                    );
            }

            return(new LiteralExpression(result, LiteralType.Boolean));
        }
コード例 #14
0
        public override IProjection CastMethod(CastMethod method, Expression[] arguments)
        {
            var projection = ProjectionVisitor.CreateProjection(arguments[0]);

            switch (LiteralUtil.CoerceString((LiteralExpression)arguments[1]))
            {
            case "Edm.Byte":
            case "Edm.SByte":
            case "Edm.Int16":
            case "Edm.Int32":
                return(new SqlFunctionProjection("round", NHibernateUtil.Int32, projection));

            case "Edm.Int64":
                return(new SqlFunctionProjection("round", NHibernateUtil.Int64, projection));

            default:
                return(projection);
            }
        }
コード例 #15
0
        public Expression SubStringMethod(SubStringMethod method, LiteralExpression[] arguments)
        {
            if (arguments[0].LiteralType == LiteralType.Null)
            {
                return(arguments[0]);
            }
            else
            {
                int    startIndex;
                int    length;
                string result;

                if (!LiteralUtil.TryCoerceInt(arguments[1], out startIndex))
                {
                    throw new ODataException(String.Format(
                                                 ErrorMessages.Method_InvalidArgumentType,
                                                 method.MethodType, 2, "Edm.Int32"
                                                 ));
                }

                if (arguments.Length == 3)
                {
                    if (!LiteralUtil.TryCoerceInt(arguments[2], out length))
                    {
                        throw new ODataException(String.Format(
                                                     ErrorMessages.Method_InvalidArgumentType,
                                                     method.MethodType, 3, "Edm.Int32"
                                                     ));
                    }

                    result = LiteralUtil.CoerceString(arguments[0]).Substring(startIndex - 1, length);
                }
                else
                {
                    result = LiteralUtil.CoerceString(arguments[0]).Substring(startIndex - 1);
                }

                return(new LiteralExpression(result, LiteralType.String));
            }
        }
コード例 #16
0
        private Expression ResolveComparisonLiterals(ComparisonExpression expression, LiteralExpression leftLiteral, LiteralExpression rightLiteral)
        {
            object left  = leftLiteral.Value;
            object right = rightLiteral.Value;
            bool   result;

            var type = LiteralUtil.CoerceLiteralValues(ref left, leftLiteral.LiteralType, ref right, rightLiteral.LiteralType);

            switch (expression.Operator)
            {
            case Operator.Eq:
                result = ResolveEquals(left, right, type);
                break;

            case Operator.Ne:
                result = !ResolveEquals(left, right, type);
                break;

            case Operator.Gt:
                result = ResolveCompare(left, right, type) > 0;
                break;

            case Operator.Ge:
                result = ResolveCompare(left, right, type) >= 0;
                break;

            case Operator.Lt:
                result = ResolveCompare(left, right, type) < 0;
                break;

            case Operator.Le:
                result = ResolveCompare(left, right, type) <= 0;
                break;

            default:
                throw new NotSupportedException();
            }

            return(new LiteralExpression(result, LiteralType.Boolean));
        }
コード例 #17
0
        private Expression NormalizeDatePart(DatePartMethod method, LiteralExpression[] arguments)
        {
            if (LiteralUtil.IsAnyNull(arguments))
            {
                return(new LiteralExpression(null, LiteralType.Null));
            }
            else if (arguments[0].LiteralType != LiteralType.DateTime)
            {
                throw new ODataException(String.Format(
                                             ErrorMessages.Method_InvalidArgumentType,
                                             method.MethodType, 1, "Edm.DateTime"
                                             ));
            }
            else
            {
                var argument = (DateTime)arguments[0].Value;
                int result;

                switch (method.MethodType)
                {
                case MethodType.Year: result = argument.Year; break;

                case MethodType.Month: result = argument.Month; break;

                case MethodType.Day: result = argument.Day; break;

                case MethodType.Hour: result = argument.Hour; break;

                case MethodType.Minute: result = argument.Minute; break;

                case MethodType.Second: result = argument.Second; break;

                default: throw new NotSupportedException();
                }

                return(new LiteralExpression(result, LiteralType.Int));
            }
        }
コード例 #18
0
        private static XElement AddProperty(string propertyName, IType propertyType, object value)
        {
            var propertyElement = new XElement(
                ODataService.NsDataServices + propertyName
                );

            if (propertyType.ReturnedClass != typeof(string))
            {
                propertyElement.Add(new XAttribute(ODataService.NsMetadata + "type", LiteralUtil.GetEdmType(propertyType.ReturnedClass)));
            }

            string serialized = LiteralUtil.SerializeValue(value);

            if (serialized == null)
            {
                propertyElement.Add(new XAttribute(ODataService.NsMetadata + "null", "true"));
            }
            else
            {
                propertyElement.Add(new XText(serialized));
            }
            return(propertyElement);
        }
コード例 #19
0
        public override bool Equals(object obj)
        {
            if (ReferenceEquals(this, obj))
            {
                return(true);
            }

            var other = obj as LiteralToken;

            if (other == null)
            {
                return(false);
            }

            var bytes      = Value as byte[];
            var otherBytes = other.Value as byte[];

            if (bytes != null && otherBytes != null)
            {
                return(LiteralUtil.ByteArrayEquals(bytes, otherBytes));
            }

            return(Equals(Value, other.Value));
        }
コード例 #20
0
        private string CreateMetadataResponse()
        {
            var schemaElement = new XElement(
                NsEdm + "Schema",
                new XAttribute(XNamespace.Xmlns + "d", NsDataServices),
                new XAttribute(XNamespace.Xmlns + "m", NsMetadata),
                new XAttribute("xmlns", NsEdm),
                new XAttribute("Namespace", SchemaNamespace)
                );

            var entityContainerElement = new XElement(
                NsEdm + "EntityContainer",
                new XAttribute("Name", ContainerName),
                new XAttribute(NsMetadata + "IsDefaultEntityContainer", "true")
                );

            var associations = new Dictionary <string, XElement>();

            foreach (var type in _sessionFactory.GetAllClassMetadata().Values)
            {
                var persister = GetPersister(type);

                string entityName = persister.EntityType.ReturnedClass.Name;

                var entityElement = new XElement(
                    NsEdm + "EntityType",
                    new XAttribute("Name", entityName),
                    new XElement(
                        NsEdm + "Key",
                        new XElement(
                            NsEdm + "PropertyRef",
                            new XAttribute("Name", persister.IdentifierPropertyName)
                            )
                        )
                    );

                schemaElement.Add(entityElement);

                entityElement.Add(new XElement(
                                      NsEdm + "Property",
                                      new XAttribute("Name", persister.IdentifierPropertyName),
                                      new XAttribute("Type", LiteralUtil.GetEdmType(persister.IdentifierType.ReturnedClass)),
                                      new XAttribute("Nullable", "false")
                                      ));

                foreach (var property in persister.EntityMetamodel.Properties)
                {
                    var collectionType = property.Type as CollectionType;
                    var manyToOneType  = property.Type as ManyToOneType;

                    var propertyType = property.Type.ReturnedClass;

                    if (collectionType != null || manyToOneType != null)
                    {
                        string fromRole;
                        string toRole;
                        string relationship;
                        string multiplicity;

                        if (collectionType != null)
                        {
                            propertyType = propertyType.GetGenericArguments()[0];

                            fromRole     = entityName + "_" + property.Name;
                            toRole       = propertyType.Name + "_" + entityName;
                            relationship = toRole + "_" + fromRole;
                            multiplicity = "*";
                        }
                        else
                        {
                            fromRole     = entityName + "_" + property.Name;
                            toRole       = propertyType.Name + "_" + Inflector.Pluralize(entityName);
                            relationship = fromRole + "_" + toRole;
                            multiplicity = "0..1";
                        }

                        entityElement.Add(new XElement(
                                              NsEdm + "NavigationProperty",
                                              new XAttribute("Name", property.Name),
                                              new XAttribute("Relationship", SchemaNamespace + "." + relationship),
                                              new XAttribute("FromRole", fromRole),
                                              new XAttribute("ToRole", toRole)
                                              ));

                        XElement association;

                        if (!associations.TryGetValue(relationship, out association))
                        {
                            association = new XElement(
                                NsEdm + "Association",
                                new XAttribute("Name", relationship)
                                );

                            associations.Add(relationship, association);
                        }

                        association.Add(new XElement(
                                            NsEdm + "End",
                                            new XAttribute("Role", toRole),
                                            new XAttribute("Type", SchemaNamespace + "." + propertyType.Name),
                                            new XAttribute("Multiplicity", multiplicity)
                                            ));
                    }
                    else
                    {
                        entityElement.Add(new XElement(
                                              NsEdm + "Property",
                                              new XAttribute("Name", property.Name),
                                              new XAttribute("Type", LiteralUtil.GetEdmType(propertyType)),
                                              new XAttribute("Nullable", property.IsNullable ? "true" : "false")
                                              ));
                    }
                }

                entityContainerElement.Add(new XElement(
                                               NsEdm + "EntitySet",
                                               new XAttribute("Name", Inflector.Pluralize(entityName)),
                                               new XAttribute("EntityType", SchemaNamespace + "." + entityName)
                                               ));
            }

            foreach (var association in associations.Values)
            {
                schemaElement.Add(association);
            }

            schemaElement.Add(entityContainerElement);

            var document = new XDocument(
                new XElement(
                    NsEdmx + "Edmx",
                    new XAttribute(XNamespace.Xmlns + "edmx", NsEdmx),
                    new XAttribute("Version", "1.0"),
                    new XElement(
                        NsEdmx + "DataServices",
                        new XAttribute(XNamespace.Xmlns + "m", NsMetadata),
                        new XAttribute(NsMetadata + "DataServiceVersion", "2.0"),
                        schemaElement
                        )
                    )
                );

            return(document.ToString(SaveOptions.DisableFormatting));
        }
コード例 #21
0
        private void PrepareDataResponse()
        {
            DataServiceVersion = "2.0;";

            string entityName;

            var path = new PathParser(_path).Parse();

            if (path.Members.Count > 2)
            {
                throw new ODataException(ErrorMessages.PathParser_InvalidPath);
            }

            entityName = Inflector.Singularize(path.Members[path.Members.Count - 1].Name);

            IEnumerable entities;
            object      parentEntity     = null;
            string      parentEntityName = Inflector.Singularize(path.Members[0].Name);

            if (path.Members[0].IdExpression != null)
            {
                object parentId = path.Members[0].IdExpression.Value;
                parentEntity = _session.Load(parentEntityName, parentId);
            }

            if (parentEntity != null && path.Members.Count == 1)
            {
                entities = new[] { parentEntity };
            }
            else
            {
                var criteria =
                    String.IsNullOrEmpty(_queryString)
                    ? _session.CreateCriteria(entityName)
                    : _session.ODataQuery(entityName, _queryString);

                if (path.Members.Count == 2)
                {
                    if (parentEntity == null || path.Members[1].IdExpression != null)
                    {
                        throw new ODataException(ErrorMessages.PathParser_InvalidPath);
                    }

                    var parentPersister = _service.GetPersister(parentEntityName);
                    var property        = GetProperty(parentPersister, path.Members[1].Name);
                    var collectionType  = property.Type as CollectionType;
                    var manyToOneType   = property.Type as ManyToOneType;

                    if (collectionType != null)
                    {
                        criteria.Add(Restrictions.Eq(parentEntityName, parentEntity));
                    }
                    else if (manyToOneType != null)
                    {
                        /**
                         * 01.06.2020: EntityMode.Poco removed; method GetPropertyValue supports only one parameter
                         */
                        var childEntity    = parentPersister.GetPropertyValue(parentEntity, property.Name /*, EntityMode.Poco*/);
                        var childPersister = _service.GetPersister(property.Type.ReturnedClass);

                        /**
                         * 01.06.2020: EntityMode.Poco removed; method GetIdentifier supports only one parameter
                         */
                        object idValue = childPersister.GetIdentifier(childEntity /*, EntityMode.Poco*/);

                        criteria.Add(Restrictions.Eq(childPersister.IdentifierPropertyName, idValue));
                    }
                    else
                    {
                        throw new ODataException(String.Format(ErrorMessages.ODataRequest_PropertyNotARelationship, path.Members[1].Name, parentPersister.EntityType.ReturnedClass.Name));
                    }
                }

                entities = criteria.List();
            }

            var feedElement = new XElement(
                ODataService.NsAtom + "feed",
                new XAttribute(XNamespace.Xml + "base", _service.ServiceNamespace),
                new XAttribute(XNamespace.Xmlns + "d", ODataService.NsDataServices),
                new XAttribute(XNamespace.Xmlns + "m", ODataService.NsMetadata),
                new XAttribute("xmlns", ODataService.NsAtom),
                new XElement(
                    ODataService.NsAtom + "title",
                    new XAttribute("type", "text"),
                    _path
                    ),
                new XElement(
                    ODataService.NsAtom + "id",
                    _service.ServiceNamespace.ToString().TrimEnd('/') + "/" + _path
                    ),
                new XElement(
                    ODataService.NsAtom + "updated",
                    DateTime.UtcNow.ToString("s") + "Z"
                    ),
                new XElement(
                    ODataService.NsAtom + "link",
                    new XAttribute("rel", "self"),
                    new XAttribute("title", _path),
                    new XAttribute("href", _path)
                    )
                );

            var persister = _service.GetPersister(entityName);

            foreach (var entity in entities)
            {
                var propertiesElement = new XElement(
                    ODataService.NsMetadata + "properties"
                    );

                /**
                 * 01.06.2020: EntityMode.Poco removed; method GetIdentifier supports only one parameter
                 */
                string id = Inflector.Pluralize(entityName) + "(" + LiteralUtil.EscapeValue(persister.GetIdentifier(entity /*, EntityMode.Poco*/)) + ")";

                var entryElement = new XElement(
                    ODataService.NsAtom + "entry",
                    new XElement(
                        ODataService.NsAtom + "id",
                        _service.ServiceNamespace.ToString().TrimEnd('/') + "/" + id
                        ),
                    new XElement(
                        ODataService.NsAtom + "author",
                        new XElement(ODataService.NsAtom + "name")
                        )
                    );

                feedElement.Add(entryElement);

                /**
                 * 01.06.2020: EntityMode.Poco removed; method GetIdentifier supports only one parameter
                 */
                propertiesElement.Add(AddProperty(persister.IdentifierPropertyName, persister.IdentifierType, persister.GetIdentifier(entity /*, EntityMode.Poco*/)));

                /**
                 * 01.06.2020: EntityMode.Poco removed; method GetPropertyValues supports only one parameter
                 */
                var values = persister.GetPropertyValues(entity /*, EntityMode.Poco*/);

                for (int i = 0; i < values.Length; i++)
                {
                    var    propertyType = persister.PropertyTypes[i];
                    string propertyName = persister.PropertyNames[i];

                    var collectionType = propertyType as CollectionType;
                    var manyToOneType  = propertyType as ManyToOneType;

                    if (collectionType != null || manyToOneType != null)
                    {
                        entryElement.Add(new XElement(
                                             ODataService.NsAtom + "link",
                                             new XAttribute("rel", ODataService.NsDataServices.ToString().TrimEnd('/') + "/related/" + propertyName),
                                             new XAttribute("type", "application/atom+xml;type=entry"),
                                             new XAttribute("title", propertyName),
                                             new XAttribute("href", id + "/" + propertyName)
                                             ));
                    }
                    else
                    {
                        propertiesElement.Add(AddProperty(propertyName, propertyType, values[i]));
                    }
                }

                entryElement.Add(
                    new XElement(
                        ODataService.NsAtom + "category",
                        new XAttribute("term", "SouthWind." + entityName),
                        new XAttribute("schema", ODataService.NsDataServices)
                        )
                    );

                entryElement.Add(
                    new XElement(
                        ODataService.NsAtom + "content",
                        new XAttribute("type", "application/xml"),
                        propertiesElement
                        )
                    );
            }

            Response = new XDocument(feedElement).ToString(SaveOptions.DisableFormatting);
        }
コード例 #22
0
 public LiteralToken(object value)
     : this(value, LiteralUtil.GetLiteralType(value))
 {
     // This overload is here just for unit testing.
 }