Esempio n. 1
0
        /// <summary>
        /// Returns the ETag of the stream
        /// </summary>
        /// <param name="entity">Entity with the stream</param>
        /// <param name="operationContext">Gives the operation context</param>
        /// <returns>Returns the Stream ETag</returns>
        public virtual string GetStreamETag(object entity, DataServiceOperationContext operationContext)
        {
            ExceptionUtilities.CheckArgumentNotNull(entity, "entity");
            this.CheckOperationContext(operationContext);

            return(this.GetStreamETagInternal(entity, null));
        }
        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.");
            }

            PhotoInfo image = entity as PhotoInfo;

            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 = imageFilePath + "image" + image.PhotoId;

            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));
        }
Esempio n. 3
0
 internal void DeleteStream(object entity, DataServiceOperationContext operationContext)
 {
     InvokeApiCallAndValidateHeaders <bool>("IDataServiceStreamProvider.DeleteStream", delegate {
         this.LoadAndValidateStreamProvider().DeleteStream(entity, operationContext);
         return(true);
     }, operationContext);
 }
Esempio n. 4
0
 /// <summary>
 /// Initializes a new instance of the TestDataServiceInvokable class
 /// </summary>
 /// <param name="dataServiceInstance">Data Service Instance</param>
 /// <param name="dataServiceOperationContext">Data Service Operation Context</param>
 /// <param name="serviceAction">Service Action</param>
 /// <param name="parameters">Parameters to use</param>
 public TestDataServiceInvokable(object dataServiceInstance, DataServiceOperationContext dataServiceOperationContext, ServiceAction serviceAction, object[] parameters)
 {
     this.dataServiceOperationContext = dataServiceOperationContext;
     this.dataServiceInstance         = dataServiceInstance;
     this.serviceAction = serviceAction;
     this.parameters    = parameters;
 }
        /// <summary>
        /// Invokes an expression that represents the full request.
        /// </summary>
        /// <param name="requestExpression"> An expression that includes calls to
        /// one or more MethodInfo or one or more calls to 
        /// IDataServiceUpdateProvider2.InvokeAction(..) or 
        /// IDataServiceQueryProvider2.InvokeFunction(..)</param>
        /// <param name="operationContext"> Current context. </param>
        /// <returns>The result of the invoked expression.</returns>
        public object Execute(System.Linq.Expressions.Expression requestExpression, DataServiceOperationContext operationContext)
        {
            Debug.Assert(requestExpression != null, "requestExpression != null");
            Debug.Assert(operationContext != null, "operationContext != null");

            return ExpressionEvaluator.Evaluate(requestExpression);
        }
 public string GetStreamETag(object entity, DataServiceOperationContext operationContext)
 {
     // This sample provider does not support the eTag header with media resources.
     // This means that we do not track concurrency for a media resource
     // and last-in wins on updates.
     return(null);
 }
Esempio n. 7
0
        public IEnumerable <OperationWrapper> GetVisibleOperations(DataServiceOperationContext operationContext)
        {
            HashSet <string> names = new HashSet <string>(EqualityComparer <string> .Default);
            IEnumerable <ServiceOperation> serviceOperations = this.metadataProvider.ServiceOperations;

            if (serviceOperations != null)
            {
                foreach (ServiceOperation iteratorVariable2 in serviceOperations)
                {
                    AddUniqueNameToSet((iteratorVariable2 != null) ? iteratorVariable2.Name : null, names, System.Data.Services.Strings.DataServiceProviderWrapper_MultipleServiceOperationsWithSameName(iteratorVariable2.Name));
                    OperationWrapper iteratorVariable3 = this.ValidateOperation(iteratorVariable2);
                    if (iteratorVariable3 != null)
                    {
                        yield return(iteratorVariable3);
                    }
                }
            }
            IEnumerator <OperationWrapper>  enumerator = this.dataService.ActionProvider.GetServiceActions(operationContext).GetEnumerator();
            Func <ResourceSetWrapper, bool> predicate  = null;
            OperationWrapper serviceAction;

            while (enumerator.MoveNext())
            {
                serviceAction = enumerator.Current;
                AddUniqueNameToSet(serviceAction.Name, names, System.Data.Services.Strings.DataServiceProviderWrapper_MultipleServiceOperationsWithSameName(serviceAction.Name));
                List <ResourceSetWrapper> source = new List <ResourceSetWrapper>();
                if (serviceAction.BindingParameter != null)
                {
                    ResourceType subType = serviceAction.BindingParameter.ParameterType;
                    if (subType.ResourceTypeKind == ResourceTypeKind.EntityCollection)
                    {
                        subType = ((EntityCollectionResourceType)subType).ItemType;
                    }
                    foreach (ResourceSetWrapper wrapper in this.GetResourceSets())
                    {
                        if (wrapper.ResourceType.IsAssignableFrom(subType))
                        {
                            source.Add(wrapper);
                        }
                    }
                    if (source.Count <ResourceSetWrapper>() == 0)
                    {
                        throw new InvalidOperationException(System.Data.Services.Strings.DataServiceProviderWrapper_ActionHasNoBindableSet(serviceAction.Name, serviceAction.BindingParameter.ParameterType.FullName));
                    }
                }
                if (serviceAction.ResultSetPathExpression != null)
                {
                    if (predicate == null)
                    {
                        predicate = set => serviceAction.ResultSetPathExpression.GetTargetSet(this, set) != null;
                    }
                    if (!source.Any <ResourceSetWrapper>(predicate))
                    {
                        throw new InvalidOperationException(System.Data.Services.Strings.DataServiceProviderWrapper_ActionHasNoVisibleSetReachableFromPathExpression(serviceAction.Name, serviceAction.ResultSetPathExpression.PathExpression));
                    }
                }
                yield return(serviceAction);
            }
        }
Esempio n. 8
0
        public string ResolveType(string entitySetName, DataServiceOperationContext operationContext)
        {
            CheckStringArgumentNull(entitySetName, "entitySetName");
            CheckArgumentNull(operationContext, "operationContext");

            this.ThrowIfDisposed();
            return(this.ResolveTypeInternal(entitySetName, operationContext));
        }
        /// <summary>
        /// Returns the resource type of the media link entry associated with the the media resource being created
        /// </summary>
        /// <param name="entitySetName">The name of the entity set</param>
        /// <param name="operationContext">The data service operation context</param>
        /// <returns>Returns the type of the media link entry</returns>
        public virtual string ResolveType(string entitySetName, DataServiceOperationContext operationContext)
        {
            ExceptionUtilities.CheckArgumentNotNull(entitySetName, "entitySetName");
            this.CheckOperationContext(operationContext);
            var entityTypeHint = operationContext.RequestHeaders[EntityTypeHintHeaderName];

            return(entityTypeHint != null?Uri.UnescapeDataString(entityTypeHint) : null);
        }
Esempio n. 10
0
 public Stream GetWriteStream(
     object entity,
     string etag,
     bool?checkETagForEquality,
     DataServiceOperationContext operationContext)
 {
     throw new NotSupportedException();
 }
Esempio n. 11
0
        /// <summary>
        /// Deletes a streams associated with an entity
        /// </summary>
        /// <param name="entity">Entity to delete streams from</param>
        /// <param name="operationContext">Gives the operation context</param>
        public virtual void DeleteStream(object entity, DataServiceOperationContext operationContext)
        {
            ExceptionUtilities.CheckArgumentNotNull(entity, "entity");
            this.CheckOperationContext(operationContext);

            // this will remove named streams as well
            BlobsStorage.Remove(entity);
        }
Esempio n. 12
0
        public IEnumerable <ServiceAction> GetServiceActions(DataServiceOperationContext operationContext)
        {
            if (this.GetServiceActionsCallback != null)
            {
                return(this.GetServiceActionsCallback(operationContext));
            }

            throw new NotImplementedException();
        }
        public void GetQueryStringItemAsksHost()
        {
            var host = new DataServiceHost2Simulator();

            host.SetQueryStringItem("some-key", "test-value");
            DataServiceOperationContext context = new DataServiceOperationContext(host);

            context.GetQueryStringValue("some-key").Should().Be("test-value");
        }
        /// <summary>
        /// Builds up an instance oz <see cref="IDataServiceInvokable"/> for the given <paramref name="serviceAction"/> with the provided <paramref name="parameterTokens"/>.
        /// </summary>
        /// <param name="operationContext">The data service operation context instance.</param>
        /// <param name="serviceAction">The service action to invoke.</param>
        /// <param name="parameterTokens">The parameter tokens required to invoke the service action.</param>
        /// <returns>An instance of <see cref="IDataServiceInvokable"/> to invoke the action with.</returns>
        public IDataServiceInvokable CreateInvokable(DataServiceOperationContext operationContext, ServiceAction serviceAction, object[] parameterTokens)
        {
            if (DataServiceOverrides.ActionProvider.CreateInvokableFunc != null)
            {
                return(DataServiceOverrides.ActionProvider.CreateInvokableFunc(operationContext, serviceAction, parameterTokens));
            }

            return(new TestDataServiceInvokable(this.dataServiceInstance, operationContext, serviceAction, parameterTokens));
        }
        /// <summary>
        /// Gets a collection of actions having <paramref name="bindingParameterType"/> as the binding parameter type.
        /// </summary>
        /// <param name="operationContext">The data service operation context instance.</param>
        /// <param name="bindingParameterType">Instance of the binding parameter resource type (<see cref="ResourceType"/>) in question.</param>
        /// <returns>A list of actions having <paramref name="bindingParameterType"/> as the binding parameter type.</returns>
        public IEnumerable <ServiceAction> GetServiceActionsByBindingParameterType(DataServiceOperationContext operationContext, ResourceType bindingParameterType)
        {
            if (DataServiceOverrides.ActionProvider.GetServiceActionsByBindingParameterTypeFunc != null)
            {
                return(DataServiceOverrides.ActionProvider.GetServiceActionsByBindingParameterTypeFunc(operationContext, bindingParameterType));
            }

            return(this.GetServiceActionsInternal(operationContext).Where(sa => sa.BindingParameter != null && sa.BindingParameter.ParameterType.FullName == bindingParameterType.FullName));
        }
        /// <summary>
        /// Returns all service actions in the provider.
        /// </summary>
        /// <param name="operationContext">operation Context</param>
        /// <returns>An enumeration of all service actions.</returns>
        public IEnumerable <ServiceAction> GetServiceActions(DataServiceOperationContext operationContext)
        {
            if (DataServiceOverrides.ActionProvider.GetServiceActionsFunc != null)
            {
                return(DataServiceOverrides.ActionProvider.GetServiceActionsFunc(operationContext));
            }

            return(this.GetServiceActionsInternal(operationContext));
        }
Esempio n. 17
0
        public IEnumerable <ServiceAction> GetServiceActionsByBindingParameterType(DataServiceOperationContext operationContext, ResourceType bindingParameterType)
        {
            if (this.GetByBindingTypeCallback != null)
            {
                return(this.GetByBindingTypeCallback(operationContext, bindingParameterType));
            }

            throw new NotImplementedException();
        }
 private bool FailToResolveSpecificActionOnEntityType(DataServiceOperationContext operationContextFromProduct, ServiceActionResolverArgs resolverArgs, out ServiceAction serviceAction)
 {
     operationContextFromProduct.Should().BeSameAs(this.operationContext);
     resolverArgs.Should().NotBeNull();
     resolverArgs.ServiceActionName.Should().Be(this.action.Name);
     resolverArgs.BindingType.Should().BeSameAs(this.entityType);
     serviceAction = null;
     return(false);
 }
            /// <summary>
            /// Determines whether a given <paramref name="serviceAction"/> should be advertised as bindable to the given <paramref name="resourceInstance"/>.
            /// </summary>
            /// <param name="operationContext">The data service operation context instance.</param>
            /// <param name="serviceAction">Service action to be advertised.</param>
            /// <param name="resourceInstance">Instance of the resource to which the service action is bound.</param>
            /// <param name="resourceInstanceInFeed">true if the resource instance to be serialized is inside a feed; false otherwise. The value true
            /// suggests that this method might be called many times during serialization since it will get called once for every resource instance inside
            /// the feed. If it is an expensive operation to determine whether to advertise the service action for the <paramref name="resourceInstance"/>,
            /// the provider may choose to always advertise in order to optimize for performance.</param>
            /// <param name="actionToSerialize">The <see cref="ODataAction"/> to be serialized. The server constructs
            /// the version passed into this call, which may be replaced by an implementation of this interface.
            /// This should never be set to null unless returning false.</param>
            /// <returns>true if the service action should be advertised; false otherwise.</returns>
            public override bool AdvertiseServiceAction(DataServiceOperationContext operationContext, ServiceAction serviceAction, object resourceInstance, bool resourceInstanceInFeed, ref ODataAction actionToSerialize)
            {
                if (SubstituteAdvertiseServiceAction != null)
                {
                    return(SubstituteAdvertiseServiceAction(operationContext, serviceAction, resourceInstance, resourceInstanceInFeed, ref actionToSerialize));
                }

                return(base.AdvertiseServiceAction(operationContext, serviceAction, resourceInstance, resourceInstanceInFeed, ref actionToSerialize));
            }
Esempio n. 20
0
        /// <summary>
        /// This method is invoked by the data services framework to retrieve the default stream associated
        /// with the Entity Type specified by the <paramref name="entity"/> parameter.
        /// Note that we set the response ETag in the host object before we return.
        /// </summary>
        /// <param name="entity">The stream returned should be the default stream associated with this entity.</param>
        /// <param name="operationContext">A reference to the context for the current operation.</param>
        /// <returns>A valid stream the data service use to query / read a streamed BLOB which is associated with the <paramref name="entity"/>.</returns>
        internal Stream GetReadStream(object entity, DataServiceOperationContext operationContext)
        {
            Debug.Assert(entity != null, "entity != null");
            Debug.Assert(operationContext != null, "operationContext != null");

            string etagFromHeader;
            bool?  checkETagForEquality;

            DataServiceStreamProviderWrapper.GetETagFromHeaders(operationContext, out etagFromHeader, out checkETagForEquality);
            Debug.Assert(
                string.IsNullOrEmpty(etagFromHeader) && !checkETagForEquality.HasValue || !string.IsNullOrEmpty(etagFromHeader) && checkETagForEquality.HasValue,
                "etag and checkETagForEquality parameters must both be set or not set at the same time.");

            Stream readStream = null;

            try
            {
                readStream = InvokeApiCallAndValidateHeaders("IDataServiceStreamProvider.GetReadStream", () => this.StreamProvider.GetReadStream(entity, etagFromHeader, checkETagForEquality, operationContext), operationContext);
            }
            catch (DataServiceException e)
            {
                if (e.StatusCode == (int)System.Net.HttpStatusCode.NotModified)
                {
                    // For status code 304, we MUST set the etag value.  Our Error handler will translate
                    // DataServiceException(304) to a normal response with status code 304 and an empty message-body.
#if DEBUG
                    WebUtil.WriteETagValueInResponseHeader(null, this.GetStreamETag(entity, operationContext), operationContext.Host);
#else
                    WebUtil.WriteETagValueInResponseHeader(this.GetStreamETag(entity, operationContext), operationContext.Host);
#endif
                }

                throw;
            }

            try
            {
                if (readStream == null || !readStream.CanRead)
                {
                    throw new InvalidOperationException(Strings.DataService_InvalidStreamFromGetReadStream);
                }

                // GetStreamETag can throw and we need to catch and dispose the stream.
#if DEBUG
                WebUtil.WriteETagValueInResponseHeader(null, this.GetStreamETag(entity, operationContext), operationContext.Host);
#else
                WebUtil.WriteETagValueInResponseHeader(this.GetStreamETag(entity, operationContext), operationContext.Host);
#endif
            }
            catch
            {
                WebUtil.Dispose(readStream);
                throw;
            }

            return(readStream);
        }
Esempio n. 21
0
        internal static string GetContentTypeFromHeaders(DataServiceOperationContext operationContext)
        {
            if (operationContext != null)
            {
                return(operationContext.RequestHeaders[HttpRequestHeader.ContentType]);
            }

            return(null);
        }
Esempio n. 22
0
        public ActionInvokable(DataServiceOperationContext operationContext, ServiceAction serviceAction, object site, object[] parameters, IParameterMarshaller marshaller)
        {
            _serviceAction = serviceAction;
            ActionInfo info       = serviceAction.CustomState as ActionInfo;
            var        marshalled = marshaller.Marshall(operationContext, serviceAction, parameters);

            info.AssertAvailable(site, marshalled[0], true);
            _action = () => CaptureResult(info.ActionMethod.Invoke(site, marshalled));
        }
Esempio n. 23
0
        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));
        }
Esempio n. 24
0
        public bool TryResolveServiceAction(DataServiceOperationContext operationContext, string serviceActionName, out ServiceAction serviceAction)
        {
            if (this.TryResolveServiceActionCallback != null)
            {
                return(this.TryResolveServiceActionCallback(operationContext, serviceActionName, out serviceAction));
            }

            throw new NotImplementedException();
        }
Esempio n. 25
0
 public void ResolveType(string entitySetName, DataServiceOperationContext operationContext)
 {
     Parent.Add(new APICallLogEntry("IDataServiceStreamProvider.ResolveType",
                                    "entitySetName", (entitySetName == null ? "null" : entitySetName),
                                    "AbsoluteRequestUri", operationContext.AbsoluteRequestUri.ToString(),
                                    "AbsoluteServiceUri", operationContext.AbsoluteServiceUri.ToString(),
                                    "IsBatchRequest", operationContext.IsBatchRequest.ToString(),
                                    "RequestMethod", operationContext.RequestMethod.ToUpperInvariant()));
 }
Esempio n. 26
0
 public void GetStreamETag(object entity, DataServiceOperationContext operationContext)
 {
     Parent.Add(new APICallLogEntry("IDataServiceStreamProvider.GetStreamETag",
                                    "entity", this.Parent.Serialize(entity),
                                    "AbsoluteRequestUri", operationContext.AbsoluteRequestUri.ToString(),
                                    "AbsoluteServiceUri", operationContext.AbsoluteServiceUri.ToString(),
                                    "IsBatchRequest", operationContext.IsBatchRequest.ToString(),
                                    "RequestMethod", operationContext.RequestMethod.ToUpperInvariant()));
 }
        public override Uri GetReadStreamUri(object entity, DataServiceOperationContext operationContext)
        {
            var package   = (V2FeedPackage)entity;
            var urlHelper = new UrlHelper(new RequestContext(HttpContext, new RouteData()));

            string url = urlHelper.PackageDownload(FeedVersion, package.Id, package.Version);

            return(new Uri(url, UriKind.Absolute));
        }
Esempio n. 28
0
        public Uri GetReadStreamUri(object entity, DataServiceOperationContext operationContext)
        {
            var package = (Package)entity;

            var    rootUrl     = Helpers.GetRootUrl();
            string downloadUrl = PackageUtility.GetPackageDownloadUrl(package);

            return(new Uri(rootUrl + downloadUrl));
        }
            public bool TryResolveServiceAction(DataServiceOperationContext operationContext, ServiceActionResolverArgs resolverArgs, out ServiceAction serviceAction)
            {
                if (this.callback != null)
                {
                    return(this.callback(operationContext, resolverArgs, out serviceAction));
                }

                throw new NotImplementedException();
            }
Esempio n. 30
0
        /// <summary>
        /// Gets the ETag, ReadStreamUri and ContentType of the stream
        /// </summary>
        /// <param name="entity">MLE instance</param>
        /// <param name="operationContext">context of the current operation</param>
        /// <param name="mediaLinkEntryUri">Uri to the MLE</param>
        /// <param name="etag">returns the etag for the stream</param>
        /// <param name="readStreamUri">returns the read stream uri</param>
        /// <param name="contentType">returns the content type of the stream</param>
        internal void GetStreamDescription(object entity, DataServiceOperationContext operationContext, string mediaLinkEntryUri, out string etag, out Uri readStreamUri, out string contentType)
        {
            Debug.Assert(entity != null, "entity != null");
            Debug.Assert(operationContext != null, "operationContext != null");

            // Call order is part of our contract, do not change it.
            etag          = this.GetStreamETag(entity, operationContext);
            readStreamUri = this.GetReadStreamUri(entity, operationContext, mediaLinkEntryUri);
            contentType   = this.GetStreamContentType(entity, operationContext);
        }
Esempio n. 31
0
        public void DeleteStream(object entity, DataServiceOperationContext operationContext)
        {
            this.ThrowIfDisposed();

            CheckArgumentNull(entity, "entity");
            CheckArgumentNull(operationContext, "operationContext");

            ValidateEntity(entity);
            this.DeleteStreams(entity);
        }
Esempio n. 32
0
    string IDataServiceStreamProvider.GetStreamContentType(object entity,  DataServiceOperationContext host) 
    {
        if (entity is InternalPicture)
        {
            InternalPicture pict = entity as InternalPicture;

            this.LoadFileStorageIfItsNotLoaded(pict, "PT.FK_FileStorage_InternalPictures1", "FileStorage");
            
            return pict.FileStorage.ContentType;
        }
        else if (entity is ExternalPicture) 
        {
            ExternalPicture pict = entity as ExternalPicture;
            return string.IsNullOrEmpty(pict.ContentType) ? "text/plain" : pict.ContentType;
        }
        else 
        {
            throw new NotSupportedException("Unexpected entity type!");
        }
    }
Esempio n. 33
0
    string IDataServiceStreamProvider.GetStreamETag(object entity, DataServiceOperationContext host) 
    {
        if (entity is ExternalPicture) 
        {
            ExternalPicture pict = entity as ExternalPicture;
            return pict.BlobETag;
        }
        if (entity is InternalPicture) 
        {
            InternalPicture pict = entity as InternalPicture;
            // ETag value is timestamp of the storage file
            if (this.GetEntityState(pict) != EntityState.Added)
            {
                this.LoadFileStorageIfItsNotLoaded(pict, "PT.FK_FileStorage_InternalPictures1", "FileStorage");

                if (pict.FileStorage == null)
                    return null;

                var creationTime = System.Data.Test.Astoria.FullTrust.TrustedMethods.GetFileCreationTime(DataPath(pict.FileStorage.Location));
                return string.Concat("\"", creationTime.ToString("dd MMMM yyyy hh:mm:ss.ffffff", System.Globalization.DateTimeFormatInfo.InvariantInfo), "\"");
            }
        }
        return null;
    }
Esempio n. 34
0
    Stream IDataServiceStreamProvider.GetWriteStream(object entity, string Etag, bool? checkETagForEquality,  DataServiceOperationContext host) 
    {
        //Debug.Assert(entity is InternalPicture, "Unexpected entity type!");
        InternalPicture pict = entity as InternalPicture;
        if (pict != null) 
        {
            string filename = host.RequestHeaders.AllKeys.Contains("Slug") ? host.RequestHeaders["Slug"] : string.Format("{0}.txt", Guid.NewGuid());
            if (filename.Contains(@"FAIL")) 
                throw new InvalidOperationException("'FAIL' in Slug :: Test hook for exception!");

            string contentType = host.RequestHeaders.AllKeys.Contains("Content-Type") ? host.RequestHeaders["Content-Type"] : null;

            if (this.GetEntityState(pict) != EntityState.Added)
            {
                this.LoadFileStorageIfItsNotLoaded(pict, "PT.FK_FileStorage_InternalPictures1", "FileStorage");
                if (pict.FileStorage != null) {

                    if (checkETagForEquality != null)
                    {
                        // the value of checkETagForEquality should be "True" (if-match header). This code does not understand "False" value (if-none-match header).
                        if (!(bool)checkETagForEquality) 
                            throw new NotSupportedException("The service does not support if-none-match header !");

                        // if etag does not match, return 412 -> Precondition failed
                        // ETag value is timestamp of the storage file
                        var creationTime = System.Data.Test.Astoria.FullTrust.TrustedMethods.GetFileCreationTime(DataPath(pict.FileStorage.Location));
                        string fileCreationTimeStamp = string.Concat("\"", creationTime.ToString("dd MMMM yyyy hh:mm:ss.ffffff", System.Globalization.DateTimeFormatInfo.InvariantInfo), "\"");
                        if (fileCreationTimeStamp != Etag) 
                        {
                            throw new DataServiceException(412, string.Format("Etag values does not match, expected: {0}, actual: {1}", Etag, fileCreationTimeStamp));
                        }
                    }

                    pict.FileStorage.ContentType = contentType;
                    pict.FileStorage.Location = filename;
                }
                else 
                {
                    // else - trouble, incosistent data - 500(internal error)
                    throw new DataServiceException("Inconsistent data found, giving up!");
                }
            }
            else
            {
                FileStorage fs = new FileStorage { ContentType = contentType, Location = filename, Picture = pict };
                entityContext.AddObject("FileStorage", fs);
            }

            return new System.Data.Test.Astoria.FullTrust.TrustedFileStream(DataPath(filename), FileMode.Create, FileAccess.Write, FileShare.Write);
        }
        else 
        {
            throw new NotSupportedException("Unexpected entity type!");
        }
    }
Esempio n. 35
0
 Uri IDataServiceStreamProvider.GetReadStreamUri(object entity,  DataServiceOperationContext host) 
 {
     Uri uri = null;
     if (entity is ExternalPicture) 
     {
         ExternalPicture pict = entity as ExternalPicture;
         if (!string.IsNullOrEmpty(pict.URL)) 
         {
             string url = pict.URL;
             if (url.Contains("${")) 
             {
                 url = replaceParams(url, GetParamsTable(host));
             }
             uri = new Uri(url, UriKind.RelativeOrAbsolute);
         }
     }
     return uri;
 }
Esempio n. 36
0
    void IDataServiceStreamProvider.DeleteStream(object entity,  DataServiceOperationContext host) 
    {
        //Debug.Assert(entity is InternalPicture || entity is ExternalPicture, "Unexpected entity type!");
        if (entity is InternalPicture) 
        {
            InternalPicture pict = entity as InternalPicture;

            FileStorage fs = pict.FileStorage ?? entityContext.FileStorage.FirstOrDefault(f => f.Picture.Id == pict.Id);

            if (fs != null) 
            {
                System.Data.Test.Astoria.FullTrust.TrustedMethods.DeleteFileIfExists(DataPath(fs.Location));
                entityContext.DeleteObject(fs);
            }
        }
    }
Esempio n. 37
0
 private IDictionary<string, string> GetParamsTable( DataServiceOperationContext host) 
 {
     Dictionary<string, string> dict = new Dictionary<string, string>();
     string absServicePath = host.AbsoluteServiceUri.ToString().TrimEnd(new char[] { ' ', '/' });
     string absServiceFolder = absServicePath.Substring(0, absServicePath.LastIndexOf('/') + 1);
     dict.Add("${AbsServicePath}", absServicePath);
     dict.Add("${AbsServiceFolder}", absServiceFolder);
     return dict;
 }
Esempio n. 38
0
    Stream IDataServiceStreamProvider.GetReadStream(object entity, string Etag, bool? checkETagForEquality,  DataServiceOperationContext host) 
    {
        //Debug.Assert(entity is InternalPicture || entity is ExternalPicture, "Unexpected entity type!");
        if (entity is InternalPicture) 
        {
            InternalPicture pict = entity as InternalPicture;
            this.LoadFileStorageIfItsNotLoaded(pict, "PT.FK_FileStorage_InternalPictures1", "FileStorage");

            if (pict.FileStorage.ContentDisposition != null) host.ResponseHeaders.Add("Content-Disposition", pict.FileStorage.ContentDisposition);
            if (host.RequestHeaders.AllKeys.Contains("B4C-Sleep")) 
            {
                string[] slData = host.RequestHeaders["B4C-Sleep"].Split(',', ';', ' ');
                int lockId = Int32.Parse(slData[0]);
                int buffSize = Int32.Parse(slData[1]);
                return new BlockedFileStream(DataPath(pict.FileStorage.Location), FileMode.Open, FileAccess.Read, FileShare.Read, buffSize, lockId);
            }
            return new System.Data.Test.Astoria.FullTrust.TrustedFileStream(DataPath(pict.FileStorage.Location), FileMode.Open, FileAccess.Read, FileShare.Read);
        }
        else if (entity is ExternalPicture) 
        {
            return new MemoryStream(Encoding.UTF8.GetBytes("This is a replacement for external entity link."), false);
        }
        else 
        {
            throw new NotSupportedException("Unexpected entity type!");
        }
    }
Esempio n. 39
0
 string IDataServiceStreamProvider.ResolveType(string entitySetName, DataServiceOperationContext host) 
 {
     return typeof(InternalPicture).FullName;
 }