public void ReadJsonLight()
        {
            // Arrange
            var deserializer = new ODataEntityReferenceLinkDeserializer();
            MockODataRequestMessage requestMessage = new MockODataRequestMessage();
            ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings();
            writerSettings.SetContentType(ODataFormat.Json);
            IEdmModel model = CreateModel();
            ODataMessageWriter messageWriter = new ODataMessageWriter(requestMessage, writerSettings, model);
            messageWriter.WriteEntityReferenceLink(new ODataEntityReferenceLink { Url = new Uri("http://localhost/samplelink") });
            ODataMessageReader messageReader = new ODataMessageReader(new MockODataRequestMessage(requestMessage),
                new ODataMessageReaderSettings(), model);

            IEdmNavigationProperty navigationProperty = GetNavigationProperty(model);

            ODataDeserializerContext context = new ODataDeserializerContext
            {
                Request = new HttpRequestMessage(),
                Path = new ODataPath(new NavigationPathSegment(navigationProperty))
            };

            // Act
            Uri uri = deserializer.Read(messageReader, context) as Uri;

            // Assert
            Assert.NotNull(uri);
            Assert.Equal("http://localhost/samplelink", uri.AbsoluteUri);
        }
        public void ProcessRequest(HttpContext context, Uri serviceBaseUri)
        {
            var sparqlGenerator = new SparqlGenerator(_config.Map, _config.DefaultLanguageCode, _config.MaxPageSize);

            var messageWriterSettings = new ODataMessageWriterSettings(_config.BaseODataWriterSettings)
                {
                    BaseUri = serviceBaseUri
                };
            if (context.Request.AcceptTypes != null)
            {
                messageWriterSettings.SetContentType(String.Join(",", context.Request.AcceptTypes),
                                                     context.Request.Headers["Accept-Charset"]);
            }

            var requestMessage = new HttpDataRequestMessage(context.Request);
            ODataVersion effectiveVersion = GetEffectiveODataVersion(requestMessage);
            messageWriterSettings.Version = effectiveVersion;

            var metadataUri = new Uri(serviceBaseUri, "./$metadata");
            if (serviceBaseUri.Equals(context.Request.Url))
            {
                // We need to respond with the service document
                var responseMessage = new HttpDataResponseMessage(context.Response);
                context.Response.ContentType = "application/xml";
                context.Response.ContentEncoding = System.Text.Encoding.UTF8;
                var feedGenerator = new ODataFeedGenerator(requestMessage, responseMessage,
                                                           _config.Map, serviceBaseUri.ToString(),
                                                           messageWriterSettings);
                feedGenerator.WriteServiceDocument();
            }
            else if (serviceBaseUri.ToString().TrimEnd('/').Equals(context.Request.Url.ToString().TrimEnd('/')))
            {
                // Trimming of trailing slash to normalize - the serviceBaseUri should always have a trailing slash, 
                // but we will redirect requests that do not to the proper service document url
                context.Response.RedirectPermanent(serviceBaseUri.ToString(), true);
            }
            else if (metadataUri.Equals(context.Request.Url))
            {
                context.Response.ContentType = "application/xml";
                context.Response.WriteFile(_config.MetadataPath);
            }
            else
            {
                var parsedQuery = QueryDescriptorQueryNode.ParseUri(
                    context.Request.Url,
                    serviceBaseUri,
                    _config.Model);
                sparqlGenerator.ProcessQuery(parsedQuery);
                var responseMessage = new HttpDataResponseMessage(context.Response);
                var feedGenerator = new ODataFeedGenerator(
                    requestMessage,
                    responseMessage,
                    _config.Map,
                    serviceBaseUri.ToString(),
                    messageWriterSettings);
                sparqlGenerator.SparqlQueryModel.Execute(_config.SparqlEndpoint, feedGenerator);
                context.Response.ContentType = "application/atom+xml";
            }
        }
        public string UpdateDataToOData(Change[] changes, string tableName, string[] headers)
        {
            HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(this.odataEndpointURL, "$batch"));
            requestMessage.Headers.Add("DataServiceVersion", this.odataVersion);
            requestMessage.Headers.Add("MaxDataServiceVersion", this.odataMaxVersion);
            
            var setting = new ODataMessageWriterSettings();
            setting.SetContentType(ODataFormat.Batch);
            setting.BaseUri = this.odataEndpointURL;

            var odataHttpRequest = new ODataHttpRequest(requestMessage);
            var messageWriter = new ODataMessageWriter(odataHttpRequest, setting, this.metadata);

            var batchWriter = messageWriter.CreateODataBatchWriter();
            batchWriter.WriteStartBatch();
            
            for (int i = 0; i < changes.Length; i++)
            {
                batchWriter.WriteStartChangeset();
                if (changes[i].operation == "DELETE")
                {
                    createDeleteOperationRequestMessage(ref batchWriter, changes[i], tableName);
                }

                if (changes[i].operation == "UPDATE")
                {
                    createUpdateOperationRequestMessage(ref batchWriter, changes[i], tableName, headers);
                }
                batchWriter.WriteEndChangeset();
            }
            
            batchWriter.WriteEndBatch();
            batchWriter.Flush();
            odataHttpRequest.GetStream().Seek(0, SeekOrigin.Begin);

            HttpResponseMessage result = new HttpResponseMessage();

            using (HttpClient client = new HttpClient())
            {
                result = client.SendAsync(requestMessage).Result;
            }

            return parseResponseMessage(result);
        }
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }

            if (writeStream == null)
            {
                throw Error.ArgumentNull("writeStream");
            }

            if (_request == null)
            {
                throw Error.InvalidOperation(SRResources.WriteToStreamAsyncMustHaveRequest);
            }

            HttpContentHeaders contentHeaders = content == null ? null : content.Headers;
            return TaskHelpers.RunSynchronously(() =>
            {
                // get the most appropriate serializer given that we support inheritance.
                IEdmModel model = _request.GetEdmModel();
                if (model == null)
                {
                    throw Error.InvalidOperation(SRResources.RequestMustHaveModel);
                }

                type = value == null ? type : value.GetType();
                ODataSerializer serializer = _serializerProvider.GetODataPayloadSerializer(model, type);
                if (serializer == null)
                {
                    string message = Error.Format(SRResources.TypeCannotBeSerialized, type.Name, typeof(ODataMediaTypeFormatter).Name);
                    throw new SerializationException(message);
                }

                ODataPath path = _request.GetODataPath();
                IEdmEntitySet targetEntitySet = path == null ? null : path.EntitySet;

                // serialize a response
                HttpConfiguration configuration = _request.GetConfiguration();
                if (configuration == null)
                {
                    throw Error.InvalidOperation(SRResources.RequestMustContainConfiguration);
                }

                Uri baseAddress = new Uri(_request.RequestUri, configuration.VirtualPathRoot);

                IODataResponseMessage responseMessage = new ODataMessageWrapper(writeStream);

                ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings()
                {
                    BaseUri = baseAddress,
                    Version = _version,
                    Indent = true,
                    DisableMessageStreamDisposal = true,
                    MessageQuotas = MessageWriterQuotas
                };

                UrlHelper urlHelper = _request.GetUrlHelper();
                Contract.Assert(urlHelper != null);

                // The MetadataDocumentUri is never required for errors. Additionally, it sometimes won't be available
                // for errors, such as when routing itself fails. In that case, the route data property is not
                // available on the request, and due to a bug with HttpRoute.GetVirtualPath (bug #669) we won't be able
                // to generate a metadata link.
                if (serializer.ODataPayloadKind != ODataPayloadKind.Error)
                {
                    string metadataLink = urlHelper.ODataLink(new MetadataPathSegment());

                    if (metadataLink == null)
                    {
                        throw new SerializationException(SRResources.UnableToDetermineMetadataUrl);
                    }

                    writerSettings.SetMetadataDocumentUri(new Uri(metadataLink));
                }

                MediaTypeHeaderValue contentType = null;
                if (contentHeaders != null && contentHeaders.ContentType != null)
                {
                    contentType = contentHeaders.ContentType;
                    writerSettings.SetContentType(contentType.ToString(), contentType.CharSet);
                }

                using (ODataMessageWriter messageWriter = new ODataMessageWriter(responseMessage, writerSettings, model))
                {
                    ODataSerializerContext writeContext = new ODataSerializerContext()
                    {
                        Request = _request,
                        Url = urlHelper,
                        EntitySet = targetEntitySet,
                        Model = model,
                        RootElementName = GetRootElementName(path) ?? "root",
                        SkipExpensiveAvailabilityChecks = serializer.ODataPayloadKind == ODataPayloadKind.Feed,
                        Path = path,
                        MetadataLevel = ODataMediaTypes.GetMetadataLevel(contentType),
                        NextPageLink = _request.GetNextPageLink(),
                        InlineCount = _request.GetInlineCount()
                    };

                    serializer.WriteObject(value, messageWriter, writeContext);
                }
            });
        }
 private static ODataMessageWriterSettings CreateJsonLightSettings()
 {
     ODataMessageWriterSettings settings = new ODataMessageWriterSettings();
     settings.SetContentType(ODataFormat.Json);
     settings.SetMetadataDocumentUri(CreateFakeUri());
     return settings;
 }
예제 #6
0
 private static ODataMessageWriterSettings CreateMessageWriterSettings(Uri serviceUri, DataServiceProviderWrapper provider, Version responseVersion, bool disableDisposeStream, ODataFormat format)
 {
     ODataMessageWriterSettings settings = new ODataMessageWriterSettings {
         BaseUri = serviceUri,
         Version = new ODataVersion?(CommonUtil.ConvertToODataVersion(responseVersion)),
         Indent = false,
         CheckCharacters = false,
         DisableMessageStreamDisposal = disableDisposeStream
     };
     settings.EnableWcfDataServicesServerBehavior(provider.IsV1Provider);
     settings.SetContentType(format);
     return settings;
 }
        public void ODataEntityReferenceLinkSerializer_Serializes_UrisAndEntityReferenceLinks_Json(object uris)
        {
            // Arrange
            ODataEntityReferenceLinksSerializer serializer = new ODataEntityReferenceLinksSerializer();
            IEdmNavigationProperty navigationProperty = _customerSet.ElementType.NavigationProperties().First();
            ODataPath path = new ODataPath(new EntitySetPathSegment(_customerSet), new KeyValuePathSegment("1"),
                new NavigationPathSegment(navigationProperty));
            ODataSerializerContext writeContext = new ODataSerializerContext { Path = path };
            MemoryStream stream = new MemoryStream();
            IODataResponseMessage message = new ODataMessageWrapper(stream);

            ODataMessageWriterSettings settings = new ODataMessageWriterSettings
            {
                BaseUri = new Uri("http://any/")
            };
            settings.SetMetadataDocumentUri(new Uri("http://any/$metadata"));
            settings.SetContentType(ODataFormat.Json);

            // Act
            serializer.WriteObject(uris, typeof(ODataEntityReferenceLinks), new ODataMessageWriter(message, settings), writeContext);
            stream.Seek(0, SeekOrigin.Begin);
            string result = new StreamReader(stream).ReadToEnd();

            // Assert
            Assert.Equal(
                string.Format("{0},{1}",
                    "{\"odata.metadata\":\"http://any/$metadata#Default.Container.Customers/$links/Orders\"",
                    "\"value\":[{\"url\":\"http://uri1/\"},{\"url\":\"http://uri2/\"}]}"), result);
        }
        private IEnumerable<KeyValuePair<string, string>> GetResponseMessageHeaders(Type graphType, ODataFormat odataFormat, ODataVersion version)
        {
            IODataResponseMessage responseMessage = new ODataMessageWrapper();

            ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings()
            {
                BaseUri = new Uri(ODataFormatterConstants.DefaultNamespace),
                Version = version,
                Indent = false
            };
            writerSettings.SetContentType(odataFormat);
            using (ODataMessageWriter messageWriter = new ODataMessageWriter(responseMessage, writerSettings))
            {
                ODataSerializer serializer = ODataSerializerProvider.GetODataPayloadSerializer(graphType);

                // get the OData specific headers for the payloadkind
                ODataUtils.SetHeadersForPayload(messageWriter, serializer.ODataPayloadKind);
            }

            return responseMessage.Headers;
        }
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }

            if (writeStream == null)
            {
                throw Error.ArgumentNull("writeStream");
            }

            if (Request == null)
            {
                throw Error.NotSupported(SRResources.WriteToStreamAsyncMustHaveRequest);
            }

            HttpContentHeaders contentHeaders = content == null ? null : content.Headers;
            return TaskHelpers.RunSynchronously(() =>
            {
                // Get the format and version to use from the ODataServiceVersion content header or if not available use the
                // values configured for the specialized formatter instance.
                ODataVersion version;
                ODataFormat odataFormat;
                if (contentHeaders == null)
                {
                    version = _defaultODataVersion;
                    odataFormat = ODataFormatterConstants.DefaultODataFormat;
                }
                else
                {
                    version = GetODataVersion(contentHeaders, ODataFormatterConstants.ODataServiceVersion) ?? _defaultODataVersion;
                    odataFormat = GetODataFormat(contentHeaders);
                }

                ODataSerializer serializer = ODataSerializerProvider.GetODataPayloadSerializer(type);
                if (serializer == null)
                {
                    throw Error.InvalidOperation(SRResources.TypeCannotBeSerialized, type.Name, typeof(ODataMediaTypeFormatter).Name);
                }

                UrlHelper urlHelper = Request.GetUrlHelper();
                NameValueCollection queryStringValues = Request.RequestUri.ParseQueryString();

                IEdmEntitySet targetEntitySet = null;
                ODataUriHelpers.TryGetEntitySetAndEntityType(Request.RequestUri, Model, out targetEntitySet);

                ODataQueryProjectionNode rootProjectionNode = null;
                if (targetEntitySet != null)
                {
                    // TODO: Bug 467621: Move to ODataUriParser once it is done.
                    rootProjectionNode = ODataUriHelpers.GetODataQueryProjectionNode(queryStringValues["$select"], queryStringValues["$expand"], targetEntitySet);
                }

                // serialize a response
                Uri baseAddress = new Uri(Request.RequestUri, Request.GetConfiguration().VirtualPathRoot);

                // TODO: Bug 467617: figure out the story for the operation name on the client side and server side.
                // This is clearly a workaround. We are assuming that the operation name is the last segment in the request uri 
                // which works for most cases and fall back to the type name of the object being written.
                // We should rather use uri parser semantic tree to figure out the operation name from the request url.
                string operationName = ODataUriHelpers.GetOperationName(Request.RequestUri, baseAddress);
                operationName = operationName ?? type.Name;

                IODataResponseMessage responseMessage = new ODataMessageWrapper(writeStream);

                ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings()
                {
                    BaseUri = baseAddress,
                    Version = version,
                    Indent = true,
                    DisableMessageStreamDisposal = true,
                };
                if (contentHeaders != null && contentHeaders.ContentType != null)
                {
                    writerSettings.SetContentType(contentHeaders.ContentType.ToString(), Encoding.UTF8.WebName);
                }

                using (ODataMessageWriter messageWriter = new ODataMessageWriter(responseMessage, writerSettings, ODataDeserializerProvider.EdmModel))
                {
                    ODataSerializerContext writeContext = new ODataSerializerContext()
                                                                    {
                                                                        EntitySet = targetEntitySet,
                                                                        UrlHelper = urlHelper,
                                                                        RootProjectionNode = rootProjectionNode,
                                                                        CurrentProjectionNode = rootProjectionNode,
                                                                        ServiceOperationName = operationName
                                                                    };

                    serializer.WriteObject(value, messageWriter, writeContext);
                }
            });
        }
 private ODataMessageWriterSettings GetWriterSettings(bool isRawValue = false)
 {
     var settings = new ODataMessageWriterSettings()
     {
         BaseUri = _session.Settings.BaseUri,
         Indent = true,
         DisableMessageStreamDisposal = !IsBatch,
     };
     ODataFormat contentType;
     if (isRawValue)
     {
         contentType = ODataFormat.RawValue;
     }
     else
     {
         switch (_session.Settings.PayloadFormat)
         {
             case ODataPayloadFormat.Atom:
             default:
                 contentType = ODataFormat.Atom;
                 break;
             case ODataPayloadFormat.Json:
                 switch (_session.Adapter.ProtocolVersion)
                 {
                     case ODataProtocolVersion.V1:
                     case ODataProtocolVersion.V2:
                         contentType = ODataFormat.VerboseJson;
                         break;
                     default:
                         contentType = ODataFormat.Json;
                         break;
                 }
                 break;
         }
     }
     settings.SetContentType(contentType);
     return settings;
 }
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }

            if (writeStream == null)
            {
                throw Error.ArgumentNull("writeStream");
            }

            if (Request == null)
            {
                throw Error.NotSupported(SRResources.WriteToStreamAsyncMustHaveRequest);
            }

            HttpContentHeaders contentHeaders = content == null ? null : content.Headers;
            return TaskHelpers.RunSynchronously(() =>
            {
                // Get the format and version to use from the ODataServiceVersion content header or if not available use the
                // values configured for the specialized formatter instance.
                ODataVersion version;
                if (contentHeaders == null)
                {
                    version = _defaultODataVersion;
                }
                else
                {
                    version = GetODataVersion(contentHeaders, ODataFormatterConstants.ODataServiceVersion) ?? _defaultODataVersion;
                }

                // get the most appropriate serializer given that we support inheritance.
                type = value == null ? type : value.GetType();
                ODataSerializer serializer = ODataSerializerProvider.GetODataPayloadSerializer(type);
                if (serializer == null)
                {
                    throw Error.InvalidOperation(SRResources.TypeCannotBeSerialized, type.Name, typeof(ODataMediaTypeFormatter).Name);
                }

                UrlHelper urlHelper = Request.GetUrlHelper();

                IEdmEntitySet targetEntitySet = null;
                ODataUriHelpers.TryGetEntitySetAndEntityType(Request.RequestUri, Model, out targetEntitySet);

                // serialize a response
                Uri baseAddress = new Uri(Request.RequestUri, Request.GetConfiguration().VirtualPathRoot);

                // TODO: Bug 467617: figure out the story for the operation name on the client side and server side.
                // This is clearly a workaround. We are assuming that the operation name is the last segment in the request uri 
                // which works for most cases and fall back to the type name of the object being written.
                // We should rather use uri parser semantic tree to figure out the operation name from the request url.
                string operationName = ODataUriHelpers.GetOperationName(Request.RequestUri, baseAddress);
                operationName = operationName ?? type.Name;

                IODataResponseMessage responseMessage = new ODataMessageWrapper(writeStream);

                // TODO: Issue 483: http://aspnetwebstack.codeplex.com/workitem/483
                // We need to set the MetadataDocumentUri when this property is added to ODataMessageWriterSettings as 
                // part of the JSON Light work.
                // This is required so ODataLib can coerce AbsoluteUri's into RelativeUri's when appropriate in JSON Light.
                ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings()
                {
                    BaseUri = baseAddress,
                    Version = version,
                    Indent = true,
                    DisableMessageStreamDisposal = true
                };

                if (contentHeaders != null && contentHeaders.ContentType != null)
                {
                    writerSettings.SetContentType(contentHeaders.ContentType.ToString(), Encoding.UTF8.WebName);
                }

                using (ODataMessageWriter messageWriter = new ODataMessageWriter(responseMessage, writerSettings, ODataDeserializerProvider.EdmModel))
                {
                    ODataSerializerContext writeContext = new ODataSerializerContext()
                    {
                        EntitySet = targetEntitySet,
                        UrlHelper = urlHelper,
                        ServiceOperationName = operationName,
                        SkipExpensiveAvailabilityChecks = serializer.ODataPayloadKind == ODataPayloadKind.Feed,
                        Request = Request
                    };

                    serializer.WriteObject(value, messageWriter, writeContext);
                }
            });
        }
        public void ProcessRequest(HttpContext context)
        {
            if (!HttpContext.Current.Request.IsAuthenticated)
            {
                HttpContext.Current.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = HttpContext.Current.Request.FilePath }, "OAuth2Bearer");
                return;
            }
            MSRAHttpResponseMessage message = new MSRAHttpResponseMessage(this.ContextBase.Response);
            message.StatusCode = 200;
            message.SetHeader(ODataConstants.ContentTypeHeader, "application/json");
            // create the writer, indent for readability
            ODataMessageWriterSettings messageWriterSettings = new ODataMessageWriterSettings()
            {
                Indent = true,
                CheckCharacters = false,
                BaseUri = context.Request.Url

            };
            messageWriterSettings.SetContentType(ODataFormat.Json);
               messageWriterSettings.SetMetadataDocumentUri(new Uri("http://localhost:31435/odata/MSRAQuery/$metadata"));

            if (string.IsNullOrEmpty(QueryId))
            {
                AzureTestDBEntities db = new AzureTestDBEntities();
                var queries = db.MsrRecurringQueries.ToList().Take(1);

                ODataWorkspace workSpace = new ODataWorkspace();
                var collections = new List<ODataResourceCollectionInfo>();

                foreach (MsrRecurringQuery recurringQuery in queries)
                {

                    ODataResourceCollectionInfo collectionInfo = new ODataResourceCollectionInfo()
                    {
                        Name = "MsrRecurringQueries",
                        Url = new Uri(context.Request.Url+"data/" + recurringQuery.RecurringQueryID.ToString(), UriKind.Absolute)
                    };
                    collectionInfo.SetAnnotation<AtomResourceCollectionMetadata>(new AtomResourceCollectionMetadata()
                    {
                        Title = new AtomTextConstruct()
                        {
                            Text = "MsrRecurringQueries"//recurringQuery.RecurringQueryName
                        },
                    });
                    collections.Add(collectionInfo);

                }
                workSpace.Collections = collections.AsEnumerable<ODataResourceCollectionInfo>();

                using (ODataMessageWriter messageWriter = new ODataMessageWriter(message, messageWriterSettings))
                {
                    messageWriter.WriteServiceDocumentAsync(workSpace);
                }
            }

            else
            {
                EdmModel mainModel =(EdmModel) QueryMetadataHttpHandler.BuildODataModel();
                using (ODataMessageWriter messageWriter = new ODataMessageWriter(message, messageWriterSettings, mainModel))
                {
                    var msrRecurringQueryResultType = new EdmEntityType("mainNS", "MsrRecurringQuery", null);
                    IEdmPrimitiveType edmPrimitiveType1 = new MSRAEdmPrimitiveType("Int32", "Edm", EdmPrimitiveTypeKind.Int32, EdmSchemaElementKind.TypeDefinition, EdmTypeKind.Primitive);
                    IEdmPrimitiveType edmPrimitiveType2 = new MSRAEdmPrimitiveType("String", "Edm", EdmPrimitiveTypeKind.String, EdmSchemaElementKind.TypeDefinition, EdmTypeKind.Primitive);
                    IEdmPrimitiveType edmPrimitiveType3 = new MSRAEdmPrimitiveType("String", "Edm", EdmPrimitiveTypeKind.String, EdmSchemaElementKind.TypeDefinition, EdmTypeKind.Primitive);
                    IEdmPrimitiveType edmPrimitiveType4 = new MSRAEdmPrimitiveType("String", "Edm", EdmPrimitiveTypeKind.String, EdmSchemaElementKind.TypeDefinition, EdmTypeKind.Primitive);
                    IEdmPrimitiveType edmPrimitiveType5 = new MSRAEdmPrimitiveType("String", "Edm", EdmPrimitiveTypeKind.String, EdmSchemaElementKind.TypeDefinition, EdmTypeKind.Primitive);
                    IEdmPrimitiveType edmPrimitiveType6 = new MSRAEdmPrimitiveType("Decimal", "Edm", EdmPrimitiveTypeKind.Decimal, EdmSchemaElementKind.TypeDefinition, EdmTypeKind.Primitive);
                    msrRecurringQueryResultType.AddKeys(new EdmStructuralProperty(msrRecurringQueryResultType, "RowId", new EdmPrimitiveTypeReference(edmPrimitiveType1, false)));
                    msrRecurringQueryResultType.AddProperty(new EdmStructuralProperty(msrRecurringQueryResultType, "RowId", new EdmPrimitiveTypeReference(edmPrimitiveType1, false)));

                    msrRecurringQueryResultType.AddProperty(new EdmStructuralProperty(msrRecurringQueryResultType, "Pricing_Level", new EdmPrimitiveTypeReference(edmPrimitiveType2, false)));
                    msrRecurringQueryResultType.AddProperty(new EdmStructuralProperty(msrRecurringQueryResultType, "Business_Summary", new EdmPrimitiveTypeReference(edmPrimitiveType3, false)));
                    msrRecurringQueryResultType.AddProperty(new EdmStructuralProperty(msrRecurringQueryResultType, "Future_Flag", new EdmPrimitiveTypeReference(edmPrimitiveType4, false)));
                    msrRecurringQueryResultType.AddProperty(new EdmStructuralProperty(msrRecurringQueryResultType, "Fiscal_Month", new EdmPrimitiveTypeReference(edmPrimitiveType5, false)));
                    msrRecurringQueryResultType.AddProperty(new EdmStructuralProperty(msrRecurringQueryResultType, "MS_Sales_Amount_Const", new EdmPrimitiveTypeReference(edmPrimitiveType6, false)));
                    ODataWriter feedWriter = messageWriter.CreateODataFeedWriter(
                        mainModel.EntityContainers().Select(c => c.EntitySets().First()).First(), msrRecurringQueryResultType);
                    ODataFeed feed = new ODataFeed()
                    {
                        Id = "MsrRecurringQueries",

                    };

                    feedWriter.WriteStart(feed);

                    AzureTestDBEntities db = new AzureTestDBEntities();
                    var queries = db.T_annooli_231161891 ;
                    foreach (var recurringQuery in queries)
                    {
                        ODataEntry entry = this.GetODataEntry(recurringQuery);
                        feedWriter.WriteStart(entry);
                        feedWriter.WriteEnd();
                    }
                    feedWriter.WriteEnd();
                }
            }
        }
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }

            if (writeStream == null)
            {
                throw Error.ArgumentNull("writeStream");
            }

            if (_request == null)
            {
                throw Error.NotSupported(SRResources.WriteToStreamAsyncMustHaveRequest);
            }

            HttpContentHeaders contentHeaders = content == null ? null : content.Headers;
            return TaskHelpers.RunSynchronously(() =>
            {
                // get the most appropriate serializer given that we support inheritance.
                type = value == null ? type : value.GetType();
                ODataSerializer serializer = _serializerProvider.GetODataPayloadSerializer(type);
                if (serializer == null)
                {
                    throw Error.InvalidOperation(SRResources.TypeCannotBeSerialized, type.Name, typeof(ODataMediaTypeFormatter).Name);
                }

                UrlHelper urlHelper = _request.GetUrlHelper();

                ODataPath path = _request.GetODataPath();
                IEdmEntitySet targetEntitySet = path == null ? null : path.EntitySet;

                // serialize a response
                HttpConfiguration configuration = _request.GetConfiguration();
                Uri baseAddress = new Uri(_request.RequestUri, configuration.VirtualPathRoot);

                IODataResponseMessage responseMessage = new ODataMessageWrapper(writeStream);

                // TODO: Issue 483: http://aspnetwebstack.codeplex.com/workitem/483
                // We need to set the MetadataDocumentUri when this property is added to ODataMessageWriterSettings as 
                // part of the JSON Light work.
                // This is required so ODataLib can coerce AbsoluteUri's into RelativeUri's when appropriate in JSON Light.
                ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings()
                {
                    BaseUri = baseAddress,
                    Version = _version,
                    Indent = true,
                    DisableMessageStreamDisposal = true
                };

                if (contentHeaders != null && contentHeaders.ContentType != null)
                {
                    MediaTypeHeaderValue contentType = contentHeaders.ContentType;
                    writerSettings.SetContentType(contentType.ToString(), contentType.CharSet);
                }

                using (ODataMessageWriter messageWriter = new ODataMessageWriter(responseMessage, writerSettings, _deserializerProvider.EdmModel))
                {
                    ODataSerializerContext writeContext = new ODataSerializerContext()
                    {
                        EntitySet = targetEntitySet,
                        UrlHelper = urlHelper,
                        PathHandler = configuration.GetODataPathHandler() ?? new DefaultODataPathHandler(Model),
                        RootElementName = GetRootElementName(path) ?? ElementNameDefault,
                        SkipExpensiveAvailabilityChecks = serializer.ODataPayloadKind == ODataPayloadKind.Feed,
                        Request = _request
                    };

                    serializer.WriteObject(value, messageWriter, writeContext);
                }
            });
        }