public void DeleteStream(object entity, DataServiceOperationContext operationContext)
        {
            var attachment = entity as Attachment;
            if (attachment == null)
            {
                throw new DataServiceException(500, "No such attachment");
            }

            try
            {
                // Delete the requested file by using the key value.
                attachment.Person = null;
                attachment.PersonWithAvatar = null;
                attachment.Discussion = null;
                attachment.ArgPoint = null;
                var mediaData = attachment.MediaData;
                attachment.MediaData = null;
                if (mediaData != null)
                    context.DeleteObject(mediaData);
                context.DeleteObject(attachment);
            }
            catch (IOException ex)
            {
                throw new DataServiceException("Error during attachment removal: ", ex);
            }
        }
        public Stream GetReadStream(object entity, string etag, bool?
                                                                    checkETagForEquality,
                                    DataServiceOperationContext operationContext)
        {
            if (checkETagForEquality != null)
            {
                // This stream provider implementation does not support 
                // ETag headers for media resources. This means that we do not track 
                // concurrency for a media resource and last-in wins on updates.
                throw new DataServiceException(400,
                                               "This sample service does not support the ETag header for a media resource.");
            }

            Attachment attach = entity as Attachment;
            if (attach == null)
            {
                throw new DataServiceException(500, "No such attachment");
            }

            if (attach.MediaData == null || attach.MediaData.Data == null)
            {
                throw new DataServiceException(500, "Cannot find requested media resource");
            }

            return new MemoryStream(attach.MediaData.Data);
        }
        public override Stream GetWriteStream(object entity, string etag, bool? checkETagForEquality, DataServiceOperationContext operationContext)
        {
            var attachment = entity as Attachment;
            var tempFile = Path.Combine(Path.GetTempPath(), attachment.Id);

            return new FileStream(tempFile, FileMode.Create, FileAccess.ReadWrite);
        }
        Dictionary<string, string> GetQueryParameterBag(DataServiceOperationContext serviceOperationContext)
        {
            Dictionary<string, string> ParameterBag = null;
            string query = serviceOperationContext.AbsoluteRequestUri.Query;
            if (!string.IsNullOrEmpty(query))
            {
                ParameterBag = new Dictionary<string, string>();
                query = query.Remove(0, 1);
                string[] param = query.Split('&');

                string paramName;
                string paramValue;

                foreach (var item in param)
                {
                    //Skip OData supported parameters [see Ronald`s Comment]
                    if (!item.StartsWith("$"))
                    {
                        paramName = item.Substring(0, item.IndexOf("="));
                        paramValue = item.Substring(item.IndexOf("=") + 1);
                        ParameterBag.Add(paramName, paramValue);
                    }
                }
            }
            return ParameterBag;
        }
        //Named Resource using .NET Framework 4.0
        public Stream GetReadStream40(object entity, ResourceProperty resourceProperty, string etag, bool? checkETagForEquality, DataServiceOperationContext operationContext)
        {
            vProductCatalog image = entity as vProductCatalog;

            //ThumbnailPhoto and LargePhoto
            string imageFilePath = HostingEnvironment.MapPath("~/ProductImages/" + resourceProperty.Name);

            if (checkETagForEquality != null)
            {
                // This stream provider implementation does not support 
                // ETag headers for media resources. This means that we do not track 
                // concurrency for a media resource and last-in wins on updates.
                throw new DataServiceException(400, "This sample service does not support the ETag header for a media resource.");
            }

            if (image == null)
            {
                throw new DataServiceException(500, "Internal Server Error.");
            }

            // Build the full path to the stored image file, which includes the entity key.
            string fullImageFilePath = string.Format(@"{0}\{1}.gif", imageFilePath, this.ProductPhotoID(image.ProductID));

            if (!File.Exists(fullImageFilePath))
            {
                throw new DataServiceException(500, "The image could not be found.");
            }

            // Return a stream that contains the requested file.
            return new FileStream(fullImageFilePath, FileMode.Open);
        }
        private static void FixUpDataServiceUrisForCuratedFeedName(
            DataServiceOperationContext operationContext,
            string curatedFeedName)
        {
            // AVERT YOUR EYES!

            // This is an *evil* hack to get proper URIs into the data servive's output, e.g. /api/v2/curated-feeds/{name}.
            // Without this, the URIs in the data service will be wrong, and won't work if a client tried to use them.

            var fixedUpSeriveUri = operationContext.AbsoluteServiceUri.AbsoluteUri.Replace("/api/v2/curated-feed/", "/api/v2/curated-feeds/" + curatedFeedName + "/");
            var fixedUpRequestUri = operationContext.AbsoluteRequestUri.AbsoluteUri.Replace("/api/v2/curated-feed/", "/api/v2/curated-feeds/" + curatedFeedName + "/");

            // The URI needs to be fixed up both on the actual IDataService host (hostInterface) and the service host wrapper (hostWrapper)
            // Null checks aren't really worth much here. If it does break, it'll result in a 500 to the client.
            var hostInterfaceField = operationContext.GetType().GetField("hostInterface", BindingFlags.NonPublic | BindingFlags.Instance);
            var hostInterface = hostInterfaceField.GetValue(operationContext);
            var hostWrapperField = operationContext.GetType().GetField("hostWrapper", BindingFlags.NonPublic | BindingFlags.Instance);
            var hostWrapper = hostWrapperField.GetValue(operationContext);

            // Fix up the service URIs
            var interfaceServiceUriField = hostInterface.GetType().GetField("absoluteServiceUri", BindingFlags.NonPublic | BindingFlags.Instance);
            interfaceServiceUriField.SetValue(hostInterface, new Uri(fixedUpSeriveUri));
            var wrapperServiceUriField = hostWrapper.GetType().GetField("absoluteServiceUri", BindingFlags.NonPublic | BindingFlags.Instance);
            wrapperServiceUriField.SetValue(hostWrapper, new Uri(fixedUpSeriveUri));

            // Fix up the request URIs
            var interfaceRequestUriField = hostInterface.GetType().GetField("absoluteRequestUri", BindingFlags.NonPublic | BindingFlags.Instance);
            interfaceRequestUriField.SetValue(hostInterface, new Uri(fixedUpRequestUri));
            var wrapperRequestUriField = hostWrapper.GetType().GetField("absoluteRequestUri", BindingFlags.NonPublic | BindingFlags.Instance);
            wrapperRequestUriField.SetValue(hostWrapper, new Uri(fixedUpRequestUri));

            // Take a shower.
        }
 public Uri GetReadStreamUri(object entity, DataServiceOperationContext operationContext)
 {
     var publishedPackage = (PublishedPackage)entity;
     string absoluteUri = HttpContext.Current.Request.Url.AbsoluteUri;
     string siteRoot = absoluteUri.Substring(0, absoluteUri.IndexOf("/FeedService.svc/Packages"));
     string relativeUri = string.Format("{0}/Package/Download/{1}/{2}", siteRoot, publishedPackage.Id, publishedPackage.Version);
     return new Uri(relativeUri);
 }
Exemple #8
0
        /// <summary>Initalizes a new <see cref="ProcessRequestArgs"/> instance.</summary>
        /// <param name="requestUri">The uri for this request.</param>
        /// <param name="isBatchOperation">True if this request is a operation specified within a batch request, otherwise false.</param>
        /// <param name="operationContext">Context about the current operation being processed.</param>
        internal ProcessRequestArgs(Uri requestUri, bool isBatchOperation, DataServiceOperationContext operationContext)
        {
            System.Diagnostics.Debug.Assert(requestUri != null, "requestUri != null");

            this.requestUri       = requestUri;
            this.isBatchOperation = isBatchOperation;
            this.OperationContext = operationContext;
        }
Exemple #9
0
        /// <summary>Initalizes a new <see cref="ProcessRequestArgs"/> instance.</summary>
        /// <param name="requestUri">The uri for this request.</param>
        /// <param name="isBatchOperation">True if this request is a operation specified within a batch request, otherwise false.</param>
        /// <param name="operationContext">Context about the current operation being processed.</param>
        internal ProcessRequestArgs(Uri requestUri, bool isBatchOperation, DataServiceOperationContext operationContext)
        {
            System.Diagnostics.Debug.Assert(requestUri != null, "requestUri != null");

            this.requestUri = requestUri;
            this.isBatchOperation = isBatchOperation;
            this.OperationContext = operationContext;
        }
        public override Uri GetReadStreamUri(object entity, DataServiceOperationContext operationContext)
        {
            var package = (DataServicePackage)entity;
            
            var vpath = GetPackageDownloadPath(package);

            return new Uri(operationContext.AbsoluteRequestUri, vpath);
        }
 private void InitializeVersion(DataServiceOperationContext operationContext)
 {
     if (this.requestVersion == null)
     {
         this.requestVersion = operationContext.Host.RequestVersion;
     }
     if (this.requestMaxVersion == null)
     {
         this.requestMaxVersion = operationContext.Host.RequestMaxVersion;
     }
 }
        public Stream GetReadStream(object entity, string etag, bool? checkETagForEquality, DataServiceOperationContext operationContext) {
            if(checkETagForEquality != null) {
                throw new DataServiceException(400, "This sample service does not support the ETag header for a media resource.");
            }

            var imageSource = entity as IImageSource;
            if(imageSource == null) {
                throw new DataServiceException(500, "Internal Server Error.");
            }
            var image = imageSource.Image;
            return new MemoryStream(image);
        }
 public string ResolveType(string entitySetName, DataServiceOperationContext operationContext)
 {
     // Only be handle ProductCatalog types.
     if (entitySetName == "ProductCatalog")
     {
         return "AdventureWorks_ODataService.ProductCatalog";
     }
     else
     {
         // This will raise an DataServiceException.
         return null;
     }
 }
Exemple #14
0
		public static void CorrelateWithClientRequestId(DataServiceOperationContext context)
		{
			Guid guid;
			string str = context.RequestHeaders.Get("client-request-id");
			if (!string.IsNullOrWhiteSpace(str) && Guid.TryParse(str, out guid))
			{
				TraceHelper.Current.CorrelateWithActivity(guid);
				if (TraceHelper.IsTestHookEnabled)
				{
					TraceHelper.TestHookClientRequestGuid = guid;
				}
			}
		}
        /// <summary>
        /// Returns the default stream that is associated with an entity that has a binary property.
        /// </summary>
        /// <param name="entity">The entity for which the descriptor object should be returned.</param>
        /// <param name="etag">The eTag value sent as part of the HTTP request that is sent to the data service.</param>
        /// <param name="checkETagForEquality">A nullable System.Boolean value that determines the type of eTag that is used.</param>
        /// <param name="operationContext">The System.Data.Services.DataServiceOperationContext instance that processes the request.</param>
        /// <returns>The data System.IO.Stream that contains the binary property data of the entity.</returns>
        public virtual Stream GetReadStream(object entity, string etag, bool? checkETagForEquality, DataServiceOperationContext operationContext)
        {
            var streameable = entity as IStreamEntity;

            if (streameable == null)
                return null;

            using (var client = new WebClient())
            {
                var bytes = client.DownloadData(streameable.GetUrlForStreaming());
                return new MemoryStream(bytes);
            }
        }
        public override Stream GetReadStream(object entity, string etag, bool? checkETagForEquality, DataServiceOperationContext operationContext)
        {
            var streameable = entity as IStreamEntity;
            if (streameable == null)
            {
                return null;
            }

            using (var client = new WebClient { Credentials = this.credentials })
            {
                var bytes = client.DownloadData(streameable.GetUrlForStreaming());
                return new MemoryStream(bytes);
            }
        }
 public IEnumerable<OperationWrapper> GetServiceActions(DataServiceOperationContext operationContext)
 {
     if (this.TryLoadActionProvider())
     {
         IEnumerable<ServiceAction> serviceActions = this.actionProvider.GetServiceActions(operationContext);
         if (serviceActions != null)
         {
             foreach (ServiceAction iteratorVariable1 in serviceActions)
             {
                 OperationWrapper iteratorVariable2 = this.dataService.Provider.ValidateOperation(iteratorVariable1);
                 if (iteratorVariable2 != null)
                 {
                     yield return iteratorVariable2;
                 }
             }
         }
     }
 }
        //Named Resource using .NET Framework 4.5
        public Stream GetReadStream(object entity, ResourceProperty resourceProperty, string etag, bool? checkETagForEquality, DataServiceOperationContext operationContext)
        {
            vProductCatalog image = entity as vProductCatalog;

            if (checkETagForEquality != null)
            {
                // This stream provider implementation does not support 
                // ETag headers for media resources. This means that we do not track 
                // concurrency for a media resource and last-in wins on updates.
                throw new DataServiceException(400, "This sample service does not support the ETag header for a media resource.");
            }

            if (image == null)
            {
                throw new DataServiceException(500, "Internal Server Error.");
            }

            // Return a stream that contains the requested ThumbnailPhoto or LargePhoto
            return ProductPhoto(image.ProductID, resourceProperty.Name);
        }
 public IEnumerable<OperationWrapper> GetServiceActionsByBindingParameterType(DataServiceOperationContext operationContext, ResourceType bindingParameterType)
 {
     Func<ServiceAction, OperationWrapper> selector = null;
     IEnumerable<OperationWrapper> emptyServiceOperationWrapperEnumeration = EmptyServiceOperationWrapperEnumeration;
     HashSet<string> existingActionNames = new HashSet<string>(EqualityComparer<string>.Default);
     do
     {
         IEnumerable<OperationWrapper> enumerable2;
         if (!this.ServiceActionByResourceTypeCache.TryGetValue(bindingParameterType, out enumerable2))
         {
             if (this.TryLoadActionProvider())
             {
                 IEnumerable<ServiceAction> serviceActionsByBindingParameterType = this.actionProvider.GetServiceActionsByBindingParameterType(operationContext, bindingParameterType);
                 if ((serviceActionsByBindingParameterType != null) && serviceActionsByBindingParameterType.Any<ServiceAction>())
                 {
                     if (selector == null)
                     {
                         selector = serviceAction => this.ValidateCanAdvertiseServiceAction(bindingParameterType, serviceAction, existingActionNames);
                     }
                     enumerable2 = (from serviceOperationWrapper in serviceActionsByBindingParameterType.Select<ServiceAction, OperationWrapper>(selector)
                         where serviceOperationWrapper != null
                         select serviceOperationWrapper).ToArray<OperationWrapper>();
                 }
             }
             if (enumerable2 == null)
             {
                 enumerable2 = EmptyServiceOperationWrapperEnumeration;
             }
             this.ServiceActionByResourceTypeCache[bindingParameterType] = enumerable2;
         }
         if (enumerable2.Any<OperationWrapper>())
         {
             emptyServiceOperationWrapperEnumeration = emptyServiceOperationWrapperEnumeration.Concat<OperationWrapper>(enumerable2);
         }
         bindingParameterType = bindingParameterType.BaseType;
     }
     while (bindingParameterType != null);
     return emptyServiceOperationWrapperEnumeration;
 }
        public string GetStreamContentType(object entity, DataServiceOperationContext operationContext)
        {
            // Get the PhotoInfo entity instance.
            Attachment attach = entity as Attachment;
            if (attach == null)
            {
                throw new DataServiceException(500, "Internal Server Error.");
            }

            switch ((AttachmentFormat) attach.Format)
            {
                case AttachmentFormat.Bmp:
                    return "image/x-ms-bmp";
                case AttachmentFormat.Jpg:
                    return "image/jpeg";
                case AttachmentFormat.Png:
                    return "image/x-png";
                case AttachmentFormat.Pdf:
                    return "application/pdf";
                default:
                    return "application/x-unknown";
            }
        }
 internal MetadataProviderEdmModel(DataServiceProviderWrapper provider, DataServiceOperationContext operationContext, DataServiceStreamProviderWrapper streamProviderWrapper)
 {
     this.metadataProvider = provider;
     this.operationContext = operationContext;
     this.streamProviderWrapper = streamProviderWrapper;
     this.schemaTypeCache = new Dictionary<string, IEdmSchemaType>(StringComparer.Ordinal);
     this.resourceTypesPerNamespaceCache = new Dictionary<string, HashSet<ResourceType>>(StringComparer.Ordinal);
     this.entityContainerCache = new Dictionary<string, MetadataProviderEdmEntityContainer>(StringComparer.Ordinal);
     this.primitiveOrComplexCollectionTypeCache = new Dictionary<ResourceType, IEdmCollectionType>(EqualityComparer<ResourceType>.Default);
     this.entityPrimitiveOrComplexCollectionTypeCache = new Dictionary<ResourceType, IEdmCollectionType>(EqualityComparer<ResourceType>.Default);
     this.derivedTypeMappings = new Dictionary<IEdmStructuredType, List<IEdmStructuredType>>(EqualityComparer<IEdmStructuredType>.Default);
     this.associationSetByKeyCache = new Dictionary<string, string>(StringComparer.Ordinal);
     Version version = this.metadataProvider.Configuration.DataServiceBehavior.MaxProtocolVersion.ToVersion();
     this.SetDataServiceVersion(version);
     Version version2 = null;
     if (!MetadataProviderUtils.DataServiceEdmVersionMap.TryGetValue(version, out version2))
     {
         this.SetEdmVersion(Microsoft.Data.Edm.Library.EdmConstants.EdmVersionLatest);
     }
     else
     {
         this.SetEdmVersion(version2);
     }
 }
        /// <summary>
        /// Returns the URI that is used to request the data stream that is associated with the binary property of an entity.
        /// </summary>
        /// <param name="entity">The entity that has the associated binary data stream.</param>
        /// <param name="operationContext">The System.Data.Services.DataServiceOperationContext 
        /// instance used by the data service to process the request.</param>
        /// <returns>A System.Uri value that is used to request the binary data stream.</returns>
        public virtual Uri GetReadStreamUri(object entity, DataServiceOperationContext operationContext)
        {
            var streameable = entity as IStreamEntity;

            return streameable != null ? streameable.GetUrlForStreaming() : null;
        }
 internal void AssertDebugStateDuringRequestProcessing(DataServiceOperationContext operationContext)
 {
 }
 /// <summary>
 /// This method is invoked by the data services framework to obtain metadata about the stream associated with the specified entity.
 /// </summary>
 /// <param name="entity">The entity for which the descriptor object should be returned.</param>
 /// <param name="operationContext">The System.Data.Services.DataServiceOperationContext instance that processes the request.</param>
 public virtual void DeleteStream(object entity, DataServiceOperationContext operationContext)
 {
     throw new NotImplementedException();
 }
 /// <summary>
 /// Returns a namespace-qualified type name that represents the type that the data service 
 /// runtime must create for the Media Link Entry that is associated with the data stream 
 /// for the Media Resource that is being inserted.
 /// </summary>
 /// <param name="entitySetName">Fully-qualified entity set name.</param>
 /// <param name="operationContext">The System.Data.Services.DataServiceOperationContext 
 /// instance that is used by the data service to process the request.</param>
 /// <returns>A namespace-qualified type name.</returns>
 public virtual string ResolveType(string entitySetName, DataServiceOperationContext operationContext)
 {
     throw new NotImplementedException();
 }
 /// <summary>
 /// Returns the stream that the data service uses to write the contents of a binary property that is associated with an entity.
 /// </summary>
 /// <param name="entity">The entity that has the associated binary stream.</param>
 /// <param name="etag">The eTag value that is sent as part of the HTTP request that is sent to the data service.</param>
 /// <param name="checkETagForEquality">A nullable System.Boolean value that determines the type of eTag is used.</param>
 /// <param name="operationContext">The System.Data.Services.DataServiceOperationContext 
 /// instance that is used by the data service to process the request.</param>
 /// <returns>A valid System.Stream the data service uses to write the contents of a 
 /// binary property that is associated with the entity.</returns>
 public virtual Stream GetWriteStream(object entity, string etag, bool? checkETagForEquality, DataServiceOperationContext operationContext)
 {
     throw new NotImplementedException();
 }
Exemple #27
0
 internal static Uri GetResultUri(DataServiceOperationContext operationContext)
 {
     UriBuilder builder = new UriBuilder(operationContext.AbsoluteRequestUri) {
         Query = null
     };
     if (builder.Path.EndsWith("()", StringComparison.Ordinal))
     {
         builder.Path = builder.Path.Substring(0, builder.Path.Length - 2);
     }
     return builder.Uri;
 }
 public virtual string GetStreamContentType(object entity, DataServiceOperationContext operationContext)
 {
     return ContentType;
 }
Exemple #29
0
 /// <summary>
 /// Constructs a new instance of DataServicePipelineEventArgs object
 /// </summary>
 /// <param name="operationContext">Context for the operation which the current event is fired for.</param>
 internal DataServiceProcessingPipelineEventArgs(DataServiceOperationContext operationContext)
 {
     Debug.Assert(operationContext != null, "operationContext != null");
     this.operationContext = operationContext;
 }
Exemple #30
0
 internal static Uri GetAbsoluteUriFromReference(string reference, DataServiceOperationContext operationContext)
 {
     return GetAbsoluteUriFromReference(reference, operationContext.AbsoluteServiceUri, operationContext.Host.RequestVersion);
 }
 internal void AssertDebugStateDuringRequestProcessing(DataServiceOperationContext operationContext)
 {
 }
 public virtual string GetStreamETag(object entity, DataServiceOperationContext operationContext)
 {
     return ETag;
 }
 internal DataServiceProcessingPipelineEventArgs(DataServiceOperationContext operationContext)
 {
     this.operationContext = operationContext;
 }
        /// <summary>
        /// Returns the eTag of the data stream that is associated with the specified entity.
        /// </summary>
        /// <param name="entity">The entity that has the associated binary data stream.</param>
        /// <param name="operationContext">The System.Data.Services.DataServiceOperationContext 
        /// instance used by the data service to process the request.</param>
        /// <returns>ETag of the stream associated with the entity.</returns>
        public virtual string GetStreamETag(object entity, DataServiceOperationContext operationContext)
        {
            var streameable = entity as IStreamEntity;

            return streameable != null ? streameable.GetStreamETag() : null;
        }
 internal static void UpdateMetadataVersion(DataServiceProviderWrapper provider, DataServiceOperationContext operationContext, out Version metadataVersion, out MetadataEdmSchemaVersion edmSchemaVersion)
 {
     metadataVersion  = Version1Dot0;
     edmSchemaVersion = MetadataEdmSchemaVersion.Version1Dot0;
     if (!provider.IsV1Provider)
     {
         edmSchemaVersion = WebUtil.RaiseMetadataEdmSchemaVersion(edmSchemaVersion, MetadataEdmSchemaVersion.Version1Dot1);
     }
     foreach (ResourceType type in provider.GetVisibleTypes(operationContext))
     {
         UpdateMetadataVersionForResourceType(type, ref metadataVersion, ref edmSchemaVersion);
     }
     if (provider.HasAnnotations(operationContext))
     {
         edmSchemaVersion = WebUtil.RaiseMetadataEdmSchemaVersion(edmSchemaVersion, MetadataEdmSchemaVersion.Version3Dot0);
     }
     foreach (OperationWrapper wrapper in provider.GetVisibleOperations(operationContext))
     {
         if (wrapper.Kind == OperationKind.Action)
         {
             edmSchemaVersion = WebUtil.RaiseMetadataEdmSchemaVersion(edmSchemaVersion, MetadataEdmSchemaVersion.Version3Dot0);
             metadataVersion  = WebUtil.RaiseVersion(metadataVersion, Version3Dot0);
             break;
         }
         if (((wrapper.ResultKind == ServiceOperationResultKind.Void) || (wrapper.ResultKind == ServiceOperationResultKind.QueryWithSingleResult)) || (((wrapper.ResultKind == ServiceOperationResultKind.DirectValue) || (wrapper.ResultType.ResourceTypeKind == ResourceTypeKind.ComplexType)) || (wrapper.ResultType.ResourceTypeKind == ResourceTypeKind.Primitive)))
         {
             edmSchemaVersion = WebUtil.RaiseMetadataEdmSchemaVersion(edmSchemaVersion, MetadataEdmSchemaVersion.Version1Dot1);
             break;
         }
     }
 }
 public virtual Uri GetReadStreamUri(object entity, DataServiceOperationContext operationContext)
 {
     throw new NotSupportedException();
 }
Exemple #37
0
 internal ProcessRequestArgs(Uri requestUri, bool isBatchOperation, DataServiceOperationContext operationContext)
 {
     this.requestUri       = requestUri;
     this.isBatchOperation = isBatchOperation;
     this.OperationContext = operationContext;
 }