public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel, InstanceContext instanceContext)
    {
        Uri originalURI = null;

        if (request.Properties.ContainsKey("OriginalHttpRequestUri"))
        {
            originalURI = request.Properties["OriginalHttpRequestUri"] as Uri;
        }
        else
        {
            //When running in WCF ServiceHost mode , the OriginalHttpRequestUri is inaccissible as the host does not support it
            originalURI = request.Properties.Via;
        }

        #region Log only interesting operations
        string lastSegment = originalURI.Segments.Last();
        if (ignorePoints.Any(fo => lastSegment.Contains(fo)))
        {
            return(null);
        }
        #endregion

        HttpRequestMessageProperty httpmsg = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
        if (httpmsg != null && httpmsg.Headers != null && httpmsg.Headers.AllKeys.Contains(LogIndexHeader))
        {
            PTEntities ctx = new PTEntities();
            int        LogIndex;
            if (!Int32.TryParse(httpmsg.Headers[LogIndexHeader], out LogIndex))
            {
                return(null);
            }

            TestOperation t = ctx.TestOperations.FirstOrDefault(to => (to.Id == LogIndex));
            if (t == null)
            {
                return(null);
            }

            LogEntry le = new LogEntry {
                TestOperation = t, URI = originalURI.ToString(), Verb = httpmsg.Method
            };
            ctx.AddObject("LogEntries", le);

            // skip loging of the logIndex header
            foreach (var key in httpmsg.Headers.AllKeys.Where(k => !k.Equals(LogIndexHeader, StringComparison.OrdinalIgnoreCase)))
            {
                ctx.AddObject("LogEntryHeaders", new LogEntryHeader {
                    LogEntry = le, Header = key, Value = httpmsg.Headers[key]
                });
            }
            ctx.SaveChanges();
            return(new MyCorrelation {
                Uri = originalURI, LogIndex = httpmsg.Headers[LogIndexHeader]
            });
        }
        return(null);
    }
    public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
    {
        if (correlationState != null && correlationState is MyCorrelation)
        {
            MyCorrelation myCor = correlationState as MyCorrelation;
            HttpResponseMessageProperty httpmsg = (HttpResponseMessageProperty)reply.Properties[HttpResponseMessageProperty.Name];
            if (httpmsg != null && httpmsg.Headers != null)
            {
                PTEntities ctx = new PTEntities();
                int        LogIndex;
                if (!Int32.TryParse(myCor.LogIndex, out LogIndex))
                {
                    return;
                }

                TestOperation t = ctx.TestOperations.FirstOrDefault(to => (to.Id == LogIndex));
                if (t == null)
                {
                    return;
                }

                LogEntry le = new LogEntry {
                    TestOperation = t, URI = myCor.Uri.ToString(), Verb = "RESPONSE"
                };
                ctx.AddObject("LogEntries", le);

                // skip loging of the logIndex header
                foreach (var key in httpmsg.Headers.AllKeys.Where(k => !k.Equals(LogIndexHeader, StringComparison.OrdinalIgnoreCase)))
                {
                    ctx.AddObject("LogEntryHeaders", new LogEntryHeader {
                        LogEntry = le, Header = key, Value = httpmsg.Headers[key]
                    });
                }
                ctx.SaveChanges();
            }
        }
    }
    public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState) {
        if (correlationState != null && correlationState is MyCorrelation) {
            MyCorrelation myCor = correlationState as MyCorrelation;
            HttpResponseMessageProperty httpmsg = (HttpResponseMessageProperty)reply.Properties[HttpResponseMessageProperty.Name];
            if (httpmsg != null && httpmsg.Headers != null) {
                PTEntities ctx = new PTEntities();
                int LogIndex;
                if (!Int32.TryParse(myCor.LogIndex, out LogIndex)) return;

                TestOperation t = ctx.TestOperations.FirstOrDefault(to => (to.Id == LogIndex));
                if (t == null) return;

                LogEntry le = new LogEntry { TestOperation = t, URI = myCor.Uri.ToString(), Verb = "RESPONSE" };
                ctx.AddObject("LogEntries", le);

                // skip loging of the logIndex header
                foreach (var key in httpmsg.Headers.AllKeys.Where(k => !k.Equals(LogIndexHeader, StringComparison.OrdinalIgnoreCase))) {
                    ctx.AddObject("LogEntryHeaders", new LogEntryHeader { LogEntry = le, Header = key, Value = httpmsg.Headers[key] });
                }
                ctx.SaveChanges();
            }
        }
    }
    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!");
        }
    }
    public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel, InstanceContext instanceContext) {
        Uri originalURI = null;
        if (request.Properties.ContainsKey("OriginalHttpRequestUri"))
        {
            originalURI = request.Properties["OriginalHttpRequestUri"] as Uri;
        }
        else
        {
            //When running in WCF ServiceHost mode , the OriginalHttpRequestUri is inaccissible as the host does not support it 
            originalURI = request.Properties.Via;
        }

        #region Log only interesting operations
        string lastSegment = originalURI.Segments.Last();
        if (ignorePoints.Any(fo => lastSegment.Contains(fo))) return null;
        #endregion

        HttpRequestMessageProperty httpmsg = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
        if (httpmsg != null && httpmsg.Headers != null && httpmsg.Headers.AllKeys.Contains(LogIndexHeader)) {


            PTEntities ctx = new PTEntities();
            int LogIndex;
            if (!Int32.TryParse(httpmsg.Headers[LogIndexHeader], out LogIndex)) return null;

            TestOperation t = ctx.TestOperations.FirstOrDefault(to => (to.Id == LogIndex));
            if (t == null) return null;

            LogEntry le = new LogEntry { TestOperation = t, URI = originalURI.ToString(), Verb = httpmsg.Method };
            ctx.AddObject("LogEntries", le);

            // skip loging of the logIndex header
            foreach (var key in httpmsg.Headers.AllKeys.Where(k => !k.Equals(LogIndexHeader, StringComparison.OrdinalIgnoreCase))) {
                ctx.AddObject("LogEntryHeaders", new LogEntryHeader { LogEntry = le, Header = key, Value = httpmsg.Headers[key] });
            }
            ctx.SaveChanges();
            return new MyCorrelation { Uri = originalURI, LogIndex = httpmsg.Headers[LogIndexHeader] };
        }
        return null;
    }