Example #1
0
        private static void AppendGeoJsonPropertyValue(StringBuilder builder, object value)
        {
            if (value is string || value is double)
            {
                builder.Append(JsonPrimitiveTypesUtil.PrimitiveToString(value, null));
            }
            else if (value is IEnumerable <KeyValuePair <string, object> > )
            {
                AppendGeoJsonProperties(builder, (IEnumerable <KeyValuePair <string, object> >)value);
            }
            else if (value is IEnumerable)
            {
                builder.Append('[');
                bool first = true;
                foreach (var element in ((IEnumerable)value).Cast <object>())
                {
                    if (!first)
                    {
                        builder.Append(',');
                    }

                    first = false;

                    AppendGeoJsonPropertyValue(builder, element);
                }

                builder.Append(']');
            }
            else
            {
                throw new NotImplementedException();
            }
        }
Example #2
0
        protected override void GenerateJson(PayloadBuilder builder, bool topLevel = false)
        {
            this.WriteStartObject();
            this.WriteMetadata(builder.TypeName, builder.Uri);

            if (builder.Properties != null)
            {
                foreach (var pi in builder.Properties)
                {
                    if (pi.Value == null || pi.PropertyKind == PayloadBuilderPropertyKind.Primitive)
                    {
                        this.WriteKeyValuePair(pi.Name, JsonPrimitiveTypesUtil.PrimitiveToString(pi.Value, null));
                    }
                    else
                    {
                        this.WriteKey(pi.Name);
                        PayloadBuilder structuredPayload = pi.Value as PayloadBuilder;
                        if (structuredPayload != null)
                        {
                            this.GenerateJson(structuredPayload);
                        }
                        else if (pi.PropertyKind == PayloadBuilderPropertyKind.Collection)
                        {
                            this.WriteCollectionValue((CollectionPropertyPayloadBuilder)pi, writeCollectionTypeName: true);
                        }
                        else
                        {
                            PayloadBuilder[] collectionProperties = pi.Value as PayloadBuilder[];
                            this.WriteStartArray();
                            bool firstElement = true;
                            foreach (var element in collectionProperties)
                            {
                                if (!firstElement)
                                {
                                    this.WriteValue(",");
                                }
                                this.GenerateJson(element);
                                firstElement = false;
                            }

                            this.WriteEndArray();
                        }
                    }
                }
            }

            this.WriteEndObject();
        }
Example #3
0
        protected void WriteCollectionValue(CollectionPropertyPayloadBuilder propertyBuilder, bool writeCollectionTypeName)
        {
            var collectionItemEdmTypeName = propertyBuilder.CollectionEdmTypeName;
            var collectionItems           = (ICollection)propertyBuilder.Value;

            // In some cases we don't want to write the type name even if it's specified. E.g. we do write it with JSON Verbose even for collections inside of other objects
            // but with JSON Light we don't. So in that case the test case would specify the type name but the JSON Light generator would explicitly request it not to be written.
            bool wrapInComplexType = !String.IsNullOrEmpty(collectionItemEdmTypeName) && writeCollectionTypeName;

            if (wrapInComplexType)
            {
                this.WriteStartObject();
                this.WriteTypeMetadata(collectionItemEdmTypeName);
                this.WriteKey(this.CollectionWrapperPropertyName);
            }

            this.WriteStartArray();
            bool firstElement = true;

            foreach (object coll in collectionItems)
            {
                PayloadBuilder sp = coll as PayloadBuilder;
                if (sp != null)
                {
                    if (!firstElement)
                    {
                        this.WriteValue(",");
                    }
                    this.GenerateJson(sp);
                    firstElement = false;
                }
                else if (coll != null && coll.GetType().IsEnum)
                {
                    this.WriteValue(JsonPrimitiveTypesUtil.PrimitiveToString(coll.ToString(), null));
                }
                else
                {
                    this.WriteValue(JsonPrimitiveTypesUtil.PrimitiveToString(coll, null));
                }
            }

            this.WriteEndArray();

            if (wrapInComplexType)
            {
                this.WriteEndObject();
            }
        }
Example #4
0
        private void GeneratePropertyPayload(PayloadBuilder builder)
        {
            Assert.IsTrue(builder.Properties.Count() == 1, "There must be exactly one property specified");
            var property = builder.Properties.Single();

            var propertyValue = property.Value as PayloadBuilder;

            if (propertyValue != null)
            {
                this.GenerateJson(propertyValue);
            }
            else
            {
                this.WriteStartObject();

                // For open properties, we need to write the type name first as property annotation
                if (builder.OpenProperties != null && builder.OpenProperties.Exists(n => n == property.Name) && property.Value != null)
                {
                    PayloadGenerator payloadGenerator = property.Value as PayloadGenerator;
                    if (payloadGenerator == null)
                    {
                        // Write the type annotation
                        // TODO: make this work for byte[] and System.Linq.Binary types
                        string typeName = property.Value.GetType().ToString().Replace("System", "Edm");
                        this.WriteKeyValuePair("@odata.type", this.GetQuotedString(GetPrefixTypeName(RemoveEdmPrefixFromTypeName(typeName))));
                    }
                }

                if (property.Value == null)
                {
                    this.WriteKeyValuePair("@odata.null", "true");
                }
                else if (property.PropertyKind == PayloadBuilderPropertyKind.Primitive || property.Value == null)
                {
                    // Write primitive property value
                    this.WriteKeyValuePair("value", JsonPrimitiveTypesUtil.PrimitiveToString(property.Value, null));
                }

                this.WriteEndObject();
            }
        }
Example #5
0
        public void CreateFormattedResourceKeyInformation(out string keyProperties, out string keyPropertyTypes, out string keyPropertyValues)
        {
            keyProperties     = "";
            keyPropertyTypes  = "";
            keyPropertyValues = "";

            foreach (ResourceInstanceSimpleProperty property in this.KeyProperties)
            {
                if (keyProperties == "")
                {
                    keyProperties    = property.Name;
                    keyPropertyTypes = property.ClrType.ToString();
                    //TODO:Need to fix this up later
                    keyPropertyValues = JsonPrimitiveTypesUtil.PrimitiveToString(property.PropertyValue, property.ClrType);
                }
                else
                {
                    keyProperties    = keyProperties + "," + property.Name;
                    keyPropertyTypes = keyPropertyTypes + "," + property.ClrType.ToString();
                    //TODO:Need to fix this up later
                    keyPropertyValues = keyPropertyValues + "," + JsonPrimitiveTypesUtil.PrimitiveToString(property.PropertyValue, property.ClrType);
                }
            }
        }
Example #6
0
        protected virtual string Visit(ExpNode caller, ExpNode node)
        {
            if (node == null)
            {
                throw new ArgumentNullException("node");
            }

            if (node is KeyedResourceInstance && (!(node is AssociationResourceInstance)))
            {
                KeyedResourceInstance e = (KeyedResourceInstance)node;
                _resourceType = this.GetResourceType(e);

                _typeStack.Push(_resourceType);

                string properties = null;
                if (this.RequestVerb == RequestVerb.Post &&
                    e.ResourceInstanceKey != null)
                {
                    foreach (ResourceInstanceProperty resourceProperty in e.ResourceInstanceKey.KeyProperties)
                    {
                        if (properties != null)
                        {
                            properties += "," + this.Visit(e, resourceProperty);
                        }
                        else
                        {
                            properties = this.Visit(e, resourceProperty);
                        }
                    }
                }
                foreach (ResourceInstanceProperty resourceProperty in e.Properties)
                {
                    if (properties != null)
                    {
                        properties += "," + this.Visit(e, resourceProperty);
                    }
                    else
                    {
                        properties = this.Visit(e, resourceProperty);
                    }
                }

                _resourceType = _typeStack.Pop();


                string typeAttribute = null;

                //if( Workspace.DataLayerProviderKind == DataLayerProviderKind.NonClr )
                //    typeAttribute = String.Format("type:\"{0}\" ", e.ResourceTypeName);
                //else
                typeAttribute = String.Format("type:\"{0}.{1}\" ", this.Workspace.ContextNamespace, e.TypeName);

                string uriAttribute   = null;
                string metadataString = null;
                if (e.ResourceInstanceKey != null && this.RequestVerb != RequestVerb.Post)
                {
                    uriAttribute = String.Format("uri:\"{0}\"", CreateCanonicalUri(e.ResourceInstanceKey));
                }

                if (uriAttribute != null)
                {
                    if (e.IncludeTypeMetadataHint)
                    {
                        metadataString = String.Format("__metadata: {{ {0}, {1}}}", typeAttribute, uriAttribute);
                    }
                    else
                    {
                        metadataString = String.Format("__metadata: {{ {0} }}", uriAttribute);
                    }
                }
                else
                {
                    if (e.IncludeTypeMetadataHint)
                    {
                        metadataString = String.Format("__metadata: {{ {0} }}", typeAttribute);
                    }
                }

                //if (uriAttribute != null && e.IncludeTypeMetadataHint)
                //    metadataString = String.Format("__metadata: {{ {0}, {1}}}", typeAttribute, uriAttribute);
                //else if (e.IncludeTypeMetadataHint && uriAttribute == null)
                //    metadataString = String.Format("__metadata: {{ {0} }}", typeAttribute);

                string payload = null;
                if (properties == null)
                {
                    payload = ApplyErrors(node, String.Format("{{{0}}}", metadataString));
                }
                else
                if (metadataString != null)
                {
                    payload = ApplyErrors(node, String.Format("{{{0}, {1}}}", metadataString, properties));
                }
                else
                {
                    payload = ApplyErrors(node, String.Format("{{{0}}}", properties));
                }
                return(payload);
            }
            else if (node is AssociationResourceInstance)
            {
                AssociationResourceInstance e = (AssociationResourceInstance)node;

                if (e.Operation == AssociationOperation.Add)
                {
                    string uri     = CreateCanonicalUri(e.ResourceInstanceKey);
                    string payload = null;
                    if (caller == null)
                    {
                        payload = "{ uri:\"" + uri + "\"}";
                    }
                    else if (e.IncludeTypeInBind)
                    {
                        payload = String.Format("__metadata: {{ uri:\"{0}\", type:\"{1}.{2}\"}}", uri, this.Workspace.ContextNamespace, e.ResourceInstanceKey.ResourceTypeName);
                    }
                    else
                    {
                        payload = String.Format("__metadata: {{ uri:\"{0}\"}}", uri);
                    }
                    return(ApplyErrors(node, payload));
                }
                else
                {
                    string navString = null;
                    if (caller != null)
                    {
                        navString = e.Name + ": null";
                    }
                    else
                    {
                        navString = "{ uri: null }";
                    }
                    return(ApplyErrors(node, navString));
                }
            }

            /*
             * else if (node is ResourceInstanceKey)
             * {
             * ResourceInstanceKey e = (ResourceInstanceKey)node;
             * if (RequestVerb == RequestVerb.Post)
             * {
             *  string payload = String.Format("__metadata: {{ type:\"{0}.{1}\" }}", this.Workspace.ContextNamespace, e.ResourceTypeName);
             *  if (e.KeyProperties != null)
             *  {
             *      foreach (ResourceInstanceProperty resourceProperty in e.KeyProperties)
             *      {
             *          payload += String.Format(", {0}", this.Visit(e, resourceProperty));
             *      }
             *  }
             *  return ApplyErrors(node, payload);
             * }
             * else if (RequestVerb == RequestVerb.Put)
             * {
             *  string keyValues = WriteCommaDelimitedKeyValues(e);
             *
             *  string payloadUri = String.Format("/{0}({1})", e.ResourceSetName, keyValues);
             *  return ApplyErrors(node, String.Format("__metadata: {{uri:\"{0}\" }}", payloadUri));
             * }
             * throw new ArgumentException("Request Verb is incorrect can't build an update payload:" + this.RequestVerb.ToString());
             * }*/
            else if (node is ResourceInstanceSimpleProperty)
            {
                ResourceInstanceSimpleProperty e = (ResourceInstanceSimpleProperty)node;
                Type   clrType = e.ClrType;
                object val     = e.PropertyValue;

                if (val != null)
                {
                    clrType = val.GetType();
                }

                if (e.CreateDollarValue)
                {
                    if (val == null)
                    {
                        return(null);
                    }
                    else if (clrType == typeof(byte[]))
                    {
                        return((new System.Text.UTF8Encoding()).GetString((byte[])val));
                    }
                    else
                    {
                        return(AstoriaUnitTests.Data.TypeData.XmlValueFromObject(val));
                    }
                }

                string jsonStringValue;

                if (clrType == typeof(DateTime) && val is DateTime)
                {
                    if (e.UseTickCountForJsonDateTime)
                    {
                        jsonStringValue = "'" + JsonPrimitiveTypesUtil.GetJsonDateTimeStringValue((DateTime)val) + "'";
                    }
                    else
                    {
                        jsonStringValue = JsonPrimitiveTypesUtil.DateTimeToString(val);
                    }
                }
                else
                {
                    jsonStringValue = JsonPrimitiveTypesUtil.PrimitiveToString(val, clrType);

                    if (clrType == typeof(double) || clrType == typeof(float))
                    {
                        // PrimitiveToString will lose the trailing .0 if its a whole number
                        long temp;
                        if (long.TryParse(jsonStringValue, out temp))
                        {
                            jsonStringValue += ".0";
                        }
                    }
                }

                if (caller == null)
                {
                    return("{" + ApplyErrors(node, String.Format("{0}: {1}", e.Name, jsonStringValue)) + "}");
                }
                else
                {
                    return(ApplyErrors(node, String.Format("{0}: {1}", e.Name, jsonStringValue)));
                }
            }
            else if (node is ResourceInstanceComplexProperty)
            {
                ResourceInstanceComplexProperty e = (ResourceInstanceComplexProperty)node;
                string properties = null;

                if (e.IncludeTypeMetadataHint)
                {
                    properties += String.Format("__metadata: {{ type:\"{0}.{1}\" }}", this.Workspace.ContextNamespace, e.TypeName);
                }

                foreach (ResourceInstanceProperty resourceProperty in e.ComplexResourceInstance.Properties)
                {
                    if (string.IsNullOrEmpty(properties))
                    {
                        properties += this.Visit(e, resourceProperty);
                    }
                    else
                    {
                        properties += "," + this.Visit(e, resourceProperty);
                    }
                }
                string results = null;
                if (caller == null)
                {
                    results = "{" + e.Name + ": {" + properties + "}" + "}";
                }
                else
                {
                    results = e.Name + ": {" + properties + "}";
                }
                return(ApplyErrors(node, results));
            }
            else if (node is ResourceInstanceNavRefProperty)
            {
                ResourceInstanceNavRefProperty e = (ResourceInstanceNavRefProperty)node;
                AssociationResourceInstance    associationResourceInstance = e.TreeNode as AssociationResourceInstance;
                string navString = null;
                if ((associationResourceInstance != null && associationResourceInstance.Operation != AssociationOperation.Remove))
                {
                    navString  = e.Name + ": {";
                    navString += this.Visit(e, e.TreeNode);
                    navString += "}";
                }
                else if (associationResourceInstance != null && associationResourceInstance.Operation == AssociationOperation.Remove)
                {
                    if (caller != null)
                    {
                        navString = e.Name + ": null";
                    }
                    else
                    {
                        navString = "null";
                    }
                }
                else
                {
                    navString  = e.Name + ": ";
                    navString += this.Visit(e, e.TreeNode);
                }
                return(ApplyErrors(node, navString));
            }
            else if (node is ResourceInstanceNavColProperty)
            {
                ResourceInstanceNavColProperty e = (ResourceInstanceNavColProperty)node;

                //string navString = String.Format("{0}: {", e.Name);
                string navString = e.Name + ": [";
                foreach (NamedNode namedNode in e.Collection.NodeList)
                {
                    if (!(namedNode is AssociationResourceInstance))
                    {
                        navString += this.Visit(e, namedNode) + ",";
                    }
                    else
                    {
                        navString += "{" + this.Visit(e, namedNode) + "},";
                    }
                }
                navString  = navString.TrimEnd(',');
                navString += "]";

                return(ApplyErrors(node, navString));
            }

            else
            {
                throw new Exception("Unknown node type: " + node.GetType());
            }
        }
Example #7
0
        protected override void GenerateJson(PayloadBuilder builder, bool topLevel = false)
        {
            if (builder.IsComplex && topLevel)
            {
                this.GeneratePropertyPayload(builder);
                return;
            }

            this.WriteStartObject();

            if (!String.IsNullOrEmpty(builder.Metadata))
            {
                this.WriteKeyValuePair("@odata.context", this.GetQuotedString(builder.Metadata));
            }

            if (!String.IsNullOrEmpty(builder.TypeName))
            {
                this.WriteTypeMetadata(builder.TypeName);
            }

            if (!builder.IsComplex && !String.IsNullOrEmpty(builder.Uri))
            {
                this.WriteKeyValuePair("@odata.editLink", this.GetQuotedString(builder.Uri));
            }

            // Write the operations
            foreach (var operation in builder.Operations)
            {
                this.WriteKey(this.GetQuotedString(operation.Metadata));

                this.WriteStartObject();

                if (!String.IsNullOrEmpty(operation.Title))
                {
                    this.WriteKeyValuePair("title", this.GetQuotedString(operation.Title));
                }

                if (!String.IsNullOrEmpty(operation.Target))
                {
                    this.WriteKeyValuePair("target", this.GetQuotedString(operation.Target));
                }

                this.WriteEndObject();
            }

            if (builder.Properties != null)
            {
                foreach (var pi in builder.Properties)
                {
                    // For open properties, we need to write the type name first as property annotation
                    if (builder.OpenProperties != null && builder.OpenProperties.Exists(n => n == pi.Name) && pi.Value != null)
                    {
                        PayloadGenerator payloadGenerator = pi.Value as PayloadGenerator;
                        if (payloadGenerator == null)
                        {
                            // Write the type annotation
                            // TODO: make this work for byte[] and System.Linq.Binary types
                            string typeName = pi.Value.GetType().ToString().Replace("System", "Edm");
                            this.WriteKeyValuePair(pi.Name + "@odata.type", this.GetQuotedString(GetPrefixTypeName(RemoveEdmPrefixFromTypeName(typeName))));
                        }
                    }

                    if (pi.PropertyKind == PayloadBuilderPropertyKind.Primitive || pi.Value == null)
                    {
                        // Write primitive property value
                        this.WriteKeyValuePair(pi.Name, JsonPrimitiveTypesUtil.PrimitiveToString(pi.Value, null));
                    }
                    else if (pi.PropertyKind == PayloadBuilderPropertyKind.Enum)
                    {
                        // Write enum property value
                        this.WriteKeyValuePair(pi.Name, pi.Value + "");
                    }
                    else
                    {
                        PayloadBuilder structuredPropertyValue = pi.Value as PayloadBuilder;
                        if (structuredPropertyValue != null)
                        {
                            if (IsEntityBindingPayload(structuredPropertyValue))
                            {
                                this.WriteKeyValuePair(pi.Name + "@odata.bind", this.GetQuotedString(structuredPropertyValue.Uri));
                            }
                            else
                            {
                                this.WriteKey(pi.Name);
                                this.GenerateJson(structuredPropertyValue);
                            }
                        }
                        else if (pi.PropertyKind == PayloadBuilderPropertyKind.Collection)
                        {
                            var collectionPropertyPayloadBuilder = (CollectionPropertyPayloadBuilder)pi;
                            if (!String.IsNullOrEmpty(collectionPropertyPayloadBuilder.CollectionEdmTypeName))
                            {
                                this.WriteKeyValuePair(pi.Name + "@odata.type", this.GetQuotedString(GetPrefixTypeName(RemoveEdmPrefixFromTypeName(collectionPropertyPayloadBuilder.CollectionEdmTypeName))));
                            }
                            this.WriteKey(pi.Name);
                            this.WriteCollectionValue(collectionPropertyPayloadBuilder, writeCollectionTypeName: false);
                        }
                        else
                        {
                            IEnumerable <PayloadBuilder> payloads = pi.Value as IEnumerable <PayloadBuilder>;
                            if (payloads != null)
                            {
                                var bindingPayloads = payloads.Where(p => IsEntityBindingPayload(p)).ToList();
                                if (bindingPayloads.Count > 0)
                                {
                                    this.WriteKey(pi.Name + "@odata.bind");
                                    this.WriteStartArray();
                                    foreach (var url in bindingPayloads)
                                    {
                                        this.WriteValue(this.GetQuotedString(url.Uri));
                                    }

                                    this.WriteEndArray();
                                }

                                var insertPayloads = payloads.Where(p => IsEntityInsertPayload(p)).ToList();
                                if (insertPayloads.Count > 0)
                                {
                                    this.WriteKey(pi.Name);
                                    this.WriteStartArray();
                                    bool first = true;
                                    foreach (var insert in insertPayloads)
                                    {
                                        if (!first)
                                        {
                                            this.WriteValue(",");
                                        }

                                        this.GenerateJson(insert);
                                        first = false;
                                    }

                                    this.WriteEndArray();
                                }
                            }
                        }
                    }
                }
            }

            this.WriteEndObject();
        }
Example #8
0
        private static string GeneratePayload <TServer, TClient>(TServer serverPropertyValue, string contentType, bool complex, bool collection)
        {
            if (contentType == UnitTestsUtil.AtomFormat)
            {
                const string atomTemplate = @"<?xml version=""1.0"" encoding=""utf-8"" standalone=""yes""?>
<entry xml:base=""/"" xmlns:ads=""http://docs.oasis-open.org/odata/ns/data"" xmlns:adsm=""http://docs.oasis-open.org/odata/ns/metadata"" xmlns=""http://www.w3.org/2005/Atom"">
  <id>http://temp.org/Entities(0)</id>
  <content type=""application/xml"">
    <adsm:properties>
      <ads:ID>0</ads:ID>
      <ads:Property{0}>{1}</ads:Property>
    </adsm:properties>
  </content>
</entry>";

                string attributes    = " adsm:type=\"Edm." + GetPrimitiveTypeKind <TServer>() + "\"";
                string propertyValue = null;
                if (serverPropertyValue == null)
                {
                    attributes += " adsm:null=\"true\"";
                }
                else if (typeof(ISpatial).IsAssignableFrom(typeof(TServer)))
                {
                    var xelement = new XElement("fake");
                    using (var writer = xelement.CreateWriter())
                    {
                        GmlFormatter.Create().Write((ISpatial)serverPropertyValue, writer);
                    }

                    propertyValue = xelement.Elements().Single().ToString();
                }
                else
                {
                    propertyValue = TypeData.XmlValueFromObject(serverPropertyValue).Replace(".0", null);
                }

                const string complexTemplate = "<ads:Property{0}>{1}</ads:Property>";
                if (complex)
                {
                    propertyValue = string.Format(complexTemplate, attributes, propertyValue);
                    attributes    = null;
                }

                const string collectionTemplate = "<adsm:element{0}>{1}</adsm:element>";
                if (collection)
                {
                    propertyValue = string.Format(collectionTemplate, attributes, propertyValue);
                    attributes    = null;
                }

                return(string.Format(atomTemplate, attributes, propertyValue));
            }
            else
            {
                const string jsonTemplate = @"{{ @odata.context:""http://temp.org/$metadata#Fake.Container.Entities/$entity"", ID:0,{0} Property:{1} }}";

                string attributes = "\"[email protected]\":\"Edm." + GetPrimitiveTypeKind <TServer>() + "\",";
                string propertyValue;

                if (typeof(TServer) == typeof(DateTime))
                {
                    propertyValue = '"' + XmlConvert.ToString((DateTime)(object)serverPropertyValue, XmlDateTimeSerializationMode.RoundtripKind) + '"';
                }
                else if (typeof(TServer) == typeof(DateTimeOffset))
                {
                    propertyValue = '"' + XmlConvert.ToString((DateTimeOffset)(object)serverPropertyValue) + '"';
                }
                else if (serverPropertyValue == null)
                {
                    propertyValue = "null";
                }
                else if (typeof(ISpatial).IsAssignableFrom(typeof(TServer)))
                {
                    var           properties = GeoJsonObjectFormatter.Create().Write((ISpatial)serverPropertyValue);
                    StringBuilder builder    = new StringBuilder();
                    AppendGeoJsonProperties(builder, properties);

                    propertyValue = builder.ToString();
                }
                else
                {
                    propertyValue = JsonPrimitiveTypesUtil.PrimitiveToString(serverPropertyValue, null).Replace(".0", null);
                }

                const string complexTemplate = "{{{0}\"Property\":{1}}}";
                if (complex)
                {
                    propertyValue = string.Format(complexTemplate, attributes, propertyValue);
                    attributes    = null;
                }

                const string collectionTemplate = "[ {0} ]";
                if (collection)
                {
                    propertyValue = string.Format(collectionTemplate, propertyValue);
                    attributes    = null;
                }

                return(string.Format(jsonTemplate, attributes, propertyValue));
            }
        }