Example #1
0
        public void RemoteApplication_GetRequest()
        {
            PathMap map =
                PathMap.CreateFromFile(
                    @"MappingTest\Mapping.xml");

            RemoteApplication.Initialize(map);

            HttpContext context = HttpContextHelper.CreateHttpContext("GET", "/localtest1/TestPage.aspx/someinfo", "name1=value1");

            using (new TraceScope(context))
            {
                RemoteApplication remoteApplication = RemoteApplication.GetRemoteApplication(context.Request);
                TrafficLogger     logger            = new TrafficLogger(remoteApplication.RemoteApplicationProxyPath, "UnitTest", new TraceScope(null), context.Request.Url);
                string            rightSideUrl      = remoteApplication.GetRightSideUrl(context.Request);
                Assert.AreEqual("http://egoratest/PvpTestApplication/1/TestPage.aspx/someinfo?name1=value1", rightSideUrl,
                                "RightSideUrl");

                using (Stream inputBuffer = CopyFilter.GetInputStream(context.Request))
                {
                    HttpWebRequest request = remoteApplication.CreateRightSideRequest(context.Request, inputBuffer, logger);
                    Assert.IsNotNull(request, "Request is null.");
                    Assert.AreEqual("GET", request.Method);
                }
            }
        }
        /// <summary>
        /// Create a new object that is an exact copy of source.
        /// Warning: This type must have a blank constructor.  If a special constructor
        /// is needed create the object and then call copyValue.
        /// </summary>
        /// <param name="source">The object to copy.</param>
        /// <returns>A new object with the same values as source.</returns>
        internal override object createCopy(object source, CopyFilter filter)
        {
            object destination = System.Activator.CreateInstance(source.GetType());

            copyValue(source, destination, null, filter);
            return(destination);
        }
Example #3
0
        public void RemoteApplication_ByPass()
        {
            PathMap map =
                PathMap.CreateFromFile(
                    @"MappingTest\Mapping.xml");

            RemoteApplication.Initialize(map);

            HttpContext context = HttpContextHelper.CreateHttpContext("GET", "/zmrres/images/somepicture.png",
                                                                      "name1=value1");

            RemoteApplication remoteApplication = RemoteApplication.GetRemoteApplication(context.Request);
            TrafficLogger     logger            = new TrafficLogger(remoteApplication.RemoteApplicationProxyPath, "UnitTest", new TraceScope(null), context.Request.Url);
            string            rightSideUrl      = remoteApplication.GetRightSideUrl(context.Request);

            Assert.AreEqual("https://portal.bmi.gv.at/images/somepicture.png?name1=value1", rightSideUrl,
                            "RightSideUrl");
            Assert.IsTrue(remoteApplication.ByPass(context.Request.Url.AbsolutePath));

            using (Stream inputBuffer = CopyFilter.GetInputStream(context.Request))
            {
                HttpWebRequest request = remoteApplication.CreateRightSideRequest(context.Request, inputBuffer, logger);
                Assert.IsNotNull(request, "Request is null.");
                Assert.AreEqual("GET", request.Method);
            }
        }
Example #4
0
        public List <Copy> ExecuteQuery()
        {
            if (ThreadCount == 0)
            {
                throw new InvalidOperationException("Threads property not set and default value 0 is not valid.");
            }

            var queryList = new List <Copy>(Library.Copies);

            CopyFilter f = (Copy x) =>
            {
                return(x.State != CopyState.OnLoan ||
                       x.Book.Shelf[2] > 'Q');
            };

            queryList.RemoveAll(x => f(x));

            // Array version

            //var filtArray = queryList.ToArray();
            //MergeSort.Sort(filtArray, new BooksComparer(), 1);
            //return new List<Copy>(filtArray);

            // List version
            MergeSort.Sort(queryList, new BooksComparer(), this.ThreadCount - 1);
            return(queryList);
        }
Example #5
0
        //--------------------------------------------------------------
        #region Creation & Cleanup
        //--------------------------------------------------------------

        public LightBufferRenderer(IGraphicsService graphicsService)
        {
            _graphicsService     = graphicsService;
            LightRenderer        = new LightRenderer(graphicsService);
            AmbientOcclusionType = AmbientOcclusionType.SSAO;
            _copyFilter          = new CopyFilter(graphicsService);
        }
Example #6
0
        [Ignore] // test no longer works since Framwork 3.0 installed
        public void RightSideHeader_FromCustomLeftSideHeader()
        {
            PathMap map =
                PathMap.CreateFromFile(
                    @"MappingTest\Mapping.xml");

            RemoteApplication.Initialize(map);

            HttpContext context =
                HttpContextHelper.CreateHttpContext("GET", "/localtest1/TestPage.aspx/someinfo", "name1=value1");


            RemoteApplication remoteApplication = RemoteApplication.GetRemoteApplication(context.Request);

            Assert.IsNotNull(remoteApplication, "remoteApplication");

            TrafficLogger       logger  = new TrafficLogger(remoteApplication.RemoteApplicationProxyPath, "UnitTest", new TraceScope(null), context.Request.Url);
            NameValueCollection headers = new NameValueCollection();

            headers.Add("X-Custom", "CustomValue");
            headers.Add("Range", "messages=1-20,25-30");
            HttpRequestHelper.AddHeaders(context.Request, headers);
            using (Stream inputBuffer = CopyFilter.GetInputStream(context.Request))
            {
                HttpWebRequest webRequest = remoteApplication.CreateRightSideRequest(context.Request, inputBuffer, logger);
                Assert.IsNotNull(webRequest, "Request is null.");
                Assert.AreEqual("GET", webRequest.Method);
                Assert.IsNotNull(webRequest.Headers["X-Custom"], "CustomHeader");
                Assert.AreEqual("CustomValue", webRequest.Headers["X-Custom"]);
                Assert.IsNotNull(webRequest.Headers["Range"], "Range");
                Assert.AreEqual("messages=1-20,25-30", webRequest.Headers["Range"]);
            }
        }
Example #7
0
        public void RemoteApplication_PostRequest()
        {
            PathMap map =
                PathMap.CreateFromFile(
                    @"MappingTest\Mapping.xml");

            RemoteApplication.Initialize(map);

            HttpContext context         = HttpContextHelper.CreateHttpContext("POST", "/localtest1/", null);
            HttpRequest leftSideRequest = context.Request;

            RemoteApplication remoteApplication = RemoteApplication.GetRemoteApplication(context.Request);
            TrafficLogger     logger            = new TrafficLogger(remoteApplication.RemoteApplicationProxyPath, "UnitTest", new TraceScope(null), context.Request.Url);
            string            rightSideUrl      = remoteApplication.GetRightSideUrl(context.Request);

            Assert.AreEqual("http://egoratest/PvpTestApplication/1/", rightSideUrl, "RightSideUrl");

            using (Stream inputBuffer = CopyFilter.GetInputStream(context.Request))
            {
                HttpWebRequest rightSideRequest = remoteApplication.CreateRightSideRequest(context.Request, inputBuffer, logger);
                Assert.IsNotNull(rightSideRequest, "Request is null.");
                Assert.AreEqual("POST", rightSideRequest.Method);
                // currently empty collection
                foreach (HttpHeader header in leftSideRequest.Headers)
                {
                    Assert.IsNotNull(rightSideRequest.Headers[header.Name], "header");
                    Assert.AreEqual(header.Value, rightSideRequest.Headers[header.Name]);
                }
            }
        }
        /// <summary>
        /// Create a new collection that is an exact copy of source.
        /// </summary>
        /// <param name="source">The source collection.</param>
        /// <returns>A new collection that is an exact copy of source.</returns>
        internal override object createCopy(object source, CopyFilter filter)
        {
            ICollection <T> sourceCollection      = (ICollection <T>)source;
            ICollection <T> destinationCollection = (ICollection <T>)System.Activator.CreateInstance(sourceCollection.GetType());
            MemberCopier    copier = MemberCopier.getCopyClass(sourceCollection.GetType().GetGenericArguments()[0]);

            foreach (T item in sourceCollection)
            {
                Object newObj = copier.createCopy(item, filter);
                destinationCollection.Add((T)newObj);
            }
            return(destinationCollection);
        }
Example #9
0
        public void CopyFilterLargeBuffer()
        {
            int          length = 10000;
            CopyFilter   filter = new CopyFilter(0);
            MemoryStream input  = new MemoryStream(length);

            input.Write(new byte[length], 0, length);
            input.Position = 0;
            MemoryStream output = new MemoryStream(length);

            filter.FilterStream(input, output);
            output.Position = 0;
            Assert.AreEqual(10000, output.Length);
        }
        public LightBufferRenderer(IGraphicsService graphicsService)
        {
            LightRenderer = new LightRenderer(graphicsService);

            _ssaoFilter = new SsaoFilter(graphicsService)
            {
                // Normally the SsaoFilter applies the occlusion values directly to the
                // source texture. But here the filter should ignore the input image and
                // create grayscale image (white = no occlusion, black = max occlusion).
                CombineWithSource = false,
            };

            _copyFilter = new CopyFilter(graphicsService);
        }
        public CopyFilterSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            // A filter that copies the current image to a low resolution render target.
            var copyFilterA = new CopyFilter(GraphicsService)
            {
                DefaultTargetFormat = new RenderTargetFormat(320, 240, false, SurfaceFormat.Color, DepthFormat.None),
            };

            GraphicsScreen.PostProcessors.Add(copyFilterA);

            // A filter that copies the result of the first filter to the back buffer.
            var copyFilterB = new CopyFilter(GraphicsService);

            GraphicsScreen.PostProcessors.Add(copyFilterB);
        }
Example #12
0
        public void CopyFilterWithZeroLength()
        {
            CopyFilter   filter = new CopyFilter(0);
            MemoryStream input  = new MemoryStream(10);

            input.Write(Encoding.UTF8.GetBytes("1234567890"), 0, 10);
            input.Position = 0;
            MemoryStream output = new MemoryStream(10);

            filter.FilterStream(input, output);
            output.Position = 0;
            Assert.AreEqual(10, output.Length);
            string result = Encoding.UTF8.GetString(output.ToArray());

            Assert.AreEqual("1234567890", result);
        }
        public DownsampleSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            // Create a DownsampleFilter which downsamples the current screen to a 64x64 pixel buffer.
            _downsampleFilter = new DownsampleFilter(GraphicsService)
            {
                // The PostProcessorChain reads the DefaultTargetFormat property. Here,
                // we can define the downsampled resolution.
                DefaultTargetFormat = new RenderTargetFormat(64, 64, false, SurfaceFormat.Color, DepthFormat.None),
            };
            GraphicsScreen.PostProcessors.Add(_downsampleFilter);

            // This CopyFilter copies the downsampled image to the back buffer.
            _copyFilter = new CopyFilter(GraphicsService);
            GraphicsScreen.PostProcessors.Add(_copyFilter);
        }
Example #14
0
        public virtual long HandleRequestContent(Stream inputBuffer)
        {
            long length = 0;

            string method = _leftSideRequest.HttpMethod.ToUpper();

            if (_authorization == null || (_authorization != null && _authorization.SoapHeaderXmlFragment == null))
            {
                if (method == "POST" || method == "PUT")
                {
                    StreamFilterBase filter = new CopyFilter(_leftSideRequest.ContentLength);
                    _rightSideRequest.ContentLength = _leftSideRequest.ContentLength;

                    Stream requestStream = GetRequestStream();
                    if (_application.LogTraffic)
                    {
                        MemoryStream buffer = new MemoryStream((int)_rightSideRequest.ContentLength);
                        length = filter.FilterStream(inputBuffer, buffer);
                        _logger.LogRequestContent(buffer);
                        buffer.WriteTo(requestStream);
                    }
                    else
                    {
                        length = filter.FilterStream(inputBuffer, requestStream);
                    }
                }
            }
            else
            {
                if (method == "POST" || method == "M-POST")
                {
                    MemoryStream buffer = new MemoryStream();
                    SoapFilter   filter = new SoapFilter(_authorization, _leftSideRequest.ContentLength, _application.PvpInformationHandling, _leftSideRequest.Headers);
                    length = filter.FilterStream(inputBuffer, buffer);
                    _rightSideRequest.ContentLength = length;
                    if (_application.LogTraffic)
                    {
                        _logger.LogRequestContent(buffer);
                    }
                    buffer.WriteTo(GetRequestStream());
                }
            }

            return(length);
        }
Example #15
0
        /// <summary>
        /// Create a new dictionary that is an exact copy of source.
        /// </summary>
        /// <param name="source">The dictionary to clone.</param>
        /// <returns>A new dictionary that is an exact copy of source.</returns>
        internal override object createCopy(object source, CopyFilter filter)
        {
            IDictionary <Key, Value> sourceDictionary = (IDictionary <Key, Value>)source;
            Type dictionaryType = sourceDictionary.GetType();
            IDictionary <Key, Value> destDictionary = (IDictionary <Key, Value>)System.Activator.CreateInstance(dictionaryType);

            Type[]       keyValueTypes = dictionaryType.GetGenericArguments();
            MemberCopier keyCopier     = MemberCopier.getCopyClass(keyValueTypes[0]);
            MemberCopier valueCopier   = MemberCopier.getCopyClass(keyValueTypes[1]);

            foreach (Key key in sourceDictionary.Keys)
            {
                Key   copiedKey   = (Key)keyCopier.createCopy(key, filter);
                Value copiedValue = (Value)valueCopier.createCopy(sourceDictionary[key], filter);
                destDictionary.Add(copiedKey, copiedValue);
            }
            return(destDictionary);
        }
Example #16
0
        public static void CopyDirectory(string sourcePath, string destinationPath, string suffix = "",
                                         CopyFilter onFilter = null)
        {
            if (onFilter != null && onFilter(sourcePath))
            {
                return;
            }

            if (!Directory.Exists(destinationPath))
            {
                Directory.CreateDirectory(destinationPath);
            }

            foreach (string file in Directory.GetFileSystemEntries(sourcePath))
            {
                if (File.Exists(file))
                {
                    FileInfo info = new FileInfo(file);
                    if (string.IsNullOrEmpty(suffix) || file.ToLower().EndsWith(suffix.ToLower()))
                    {
                        string destName = Path.Combine(destinationPath, info.Name);
                        if (!(onFilter != null && onFilter(file)))
                        {
                            File.Copy(file, destName);
                        }
                    }
                }

                if (Directory.Exists(file))
                {
                    DirectoryInfo info     = new DirectoryInfo(file);
                    string        destName = Path.Combine(destinationPath, info.Name);
                    CopyDirectory(file, destName, suffix, onFilter);
                }
            }
        }
        /// <summary>
        /// PostProcessACL. MS-DTYP section 2.5.4.9
        /// </summary>
        /// <param name="acl">ACL on which to substitute SIDs.</param>
        /// <param name="copyFilter">The filter for post-processing the ACL.</param>
        /// <param name="owner">Owner to use in substituting the CreatorOwner SID.</param>
        /// <param name="group">Group to use in substituting the CreatorGroup SID.</param>
        /// <param name="genericMapping">
        /// Mapping of generic permissions to resource manager-specific 
        /// permissions supplied by the caller.
        /// </param>
        /// <returns>
        /// The computed ACL with the SID substitutions performed.
        /// </returns>
        public static _ACL PostProcessACL(
            _ACL acl,
            CopyFilter copyFilter,
            _SID owner,
            _SID group,
            GenericMapping genericMapping)
        {
            #region Pseudocode  v20110329

            //// Substitute CreatorOwner and CreatorGroup SIDs and do GenericMapping in ACL

            //Initialize NewACL to Empty ACL

            //FOR each ACE in ACL DO

            //    // Determine if this ACE passes the filter to be copied to the new ACL

            //    SET CopyThisAce = FALSE

            //    CASE CopyFilter OF

            //        CopyAllAces:
            //            BEGIN
            //                SET CopyThisAce = TRUE
            //            END

            //        CopyInheritedAces:
            //            BEGIN
            //                IF (ACE.AceFlags contains INHERITED_ACE) THEN
            //                    SET CopyThisAce = TRUE
            //                ENDIF
            //            END

            //        CopyExplicitAces:
            //            BEGIN
            //                IF (ACE.AceFlags does not contain INHERITED_ACE) THEN
            //                   SET CopyThisAce = TRUE
            //                ENDIF
            //            END

            //    ENDCASE

            //    Set NewACE to ACE

            //    IF (CopyThisAce) THEN

            //        CASE ACE.Sid OF

            //            CREATOR_OWNER:
            //                NewACE.Sid = Owner

            //            CREATOR_GROUP:
            //                NewACE.Sid = Group
            //        ENDCASE

            //        IF (ACE.Mask contains GENERIC_READ) THEN
            //            Add GenericMapping.GenericRead to NewACE.Mask
            //        ENDIF

            //        IF (ACE.Mask contains GENERIC_WRITE) THEN
            //            Add GenericMapping.GenericWrite to NewACE.Mask
            //        ENDIF

            //        IF (ACE.Mask contains GENERIC_EXECUTE) THEN
            //            Add GenericMapping.GenericExecute to NewACE.Mask
            //        ENDIF

            //        Append NewACE to NewACL
            //    ENDIF

            //END FOR

            //RETURN NewACL
            //// END PostProcessACL

            #endregion

            _ACL newAcl = new _ACL();
            newAcl.AclRevision = acl.AclRevision;
            newAcl.Aces = new object[] { };
            List<object> newAces = new List<object>();

            if (acl.Aces != null)
            {
                foreach (object ace in acl.Aces)
                {
                    object newAce = ObjectUtility.DeepClone(ace);
                    _ACE_HEADER header = (_ACE_HEADER)ObjectUtility.GetFieldValue(newAce, "Header");

                    bool copyThisAce = false;
                    switch (copyFilter)
                    {
                        case CopyFilter.CopyAllAces:
                            copyThisAce = true;
                            break;
                        case CopyFilter.CopyInheritedAces:
                            if ((header.AceFlags & ACE_FLAGS.INHERITED_ACE) == ACE_FLAGS.INHERITED_ACE)
                            {
                                copyThisAce = true;
                            }
                            break;
                        case CopyFilter.CopyExplicitAces:
                            if ((header.AceFlags & ACE_FLAGS.INHERITED_ACE) == ACE_FLAGS.None)
                            {
                                copyThisAce = true;
                            }
                            break;
                    }

                    if (copyThisAce)
                    {
                        #region Substitute CreatorOwner and CreatorGroup SIDs in ACL

                        _SID sid = (_SID)ObjectUtility.GetFieldValue(newAce, "Sid");
                        if (ObjectUtility.DeepCompare(sid, GetWellKnownSid(WellKnownSid.CREATOR_OWNER, null)))
                        {
                            ObjectUtility.SetFieldValue(newAce, "Sid", owner);
                            header.AceSize = (ushort)(header.AceSize
                                - (sid.SubAuthorityCount - owner.SubAuthorityCount) * sizeof(uint));
                            ObjectUtility.SetFieldValue(newAce, "Header", header);

                        }
                        else if (ObjectUtility.DeepCompare(sid, GetWellKnownSid(WellKnownSid.CREATOR_GROUP, null)))
                        {
                            ObjectUtility.SetFieldValue(newAce, "Sid", group);
                            header.AceSize = (ushort)(header.AceSize
                                - (sid.SubAuthorityCount - group.SubAuthorityCount) * sizeof(uint));
                            ObjectUtility.SetFieldValue(newAce, "Header", header);
                        }
                        #endregion

                        #region Do GenericMapping in ACL

                        uint mask = (uint)ObjectUtility.GetFieldValue(newAce, "Mask");

                        if ((mask & ACCESS_MASK_GENERIC_READ) == ACCESS_MASK_GENERIC_READ)
                        {
                            mask = mask | genericMapping.GenericRead;
                            ObjectUtility.SetFieldValue(newAce, "Mask", mask);
                        }
                        if ((mask & ACCESS_MASK_GENERIC_WRITE) == ACCESS_MASK_GENERIC_WRITE)
                        {
                            mask = mask | genericMapping.GenericWrite;
                            ObjectUtility.SetFieldValue(newAce, "Mask", mask);
                        }
                        if ((mask & ACCESS_MASK_GENERIC_EXECUTE) == ACCESS_MASK_GENERIC_EXECUTE)
                        {
                            mask = mask | genericMapping.GenericExecute;
                            ObjectUtility.SetFieldValue(newAce, "Mask", mask);
                        }
                        #endregion

                        //Append NewACE to NewACL
                        newAces.Add(newAce);
                    }
                }
            }
            newAcl.Aces = newAces.ToArray();
            newAcl.AceCount = (ushort)newAcl.Aces.Length;
            newAcl.AclSize = DtypUtility.CalculateAclSize(newAcl);

            return newAcl;
        }
Example #18
0
        /// <summary>
        /// Copy source into destination.
        /// </summary>
        /// <param name="source">The source dictionary.</param>
        /// <param name="destination">The destination dictionary.</param>
        /// <param name="info">The member wrapper to set data.</param>
        internal override void copyValue(object source, object destination, MemberWrapper info, CopyFilter filter)
        {
            IDictionary <Key, Value> sourceDictionary = (IDictionary <Key, Value>)info.getValue(source, null);

            if (sourceDictionary != null)
            {
                Type dictionaryType = sourceDictionary.GetType();
                IDictionary <Key, Value> destDictionary = (IDictionary <Key, Value>)System.Activator.CreateInstance(dictionaryType);
                Type[]       keyValueTypes = dictionaryType.GetGenericArguments();
                MemberCopier keyCopier     = MemberCopier.getCopyClass(keyValueTypes[0]);
                MemberCopier valueCopier   = MemberCopier.getCopyClass(keyValueTypes[1]);
                foreach (Key key in sourceDictionary.Keys)
                {
                    Key   copiedKey   = (Key)keyCopier.createCopy(key, filter);
                    Value copiedValue = (Value)valueCopier.createCopy(sourceDictionary[key], filter);
                    destDictionary.Add(copiedKey, copiedValue);
                }
                info.setValue(destination, destDictionary, null);
            }
        }
        /// <summary>
        /// Copy the values from source into destination.
        /// </summary>
        /// <param name="source">The source collection.</param>
        /// <param name="destination">The destination collection.</param>
        /// <param name="info">The member wrapper to set the info.</param>
        internal override void copyValue(object source, object destination, MemberWrapper info, CopyFilter filter)
        {
            ICollection <T> sourceCollection      = (ICollection <T>)info.getValue(source, null);
            ICollection <T> destinationCollection = (ICollection <T>)System.Activator.CreateInstance(sourceCollection.GetType());
            MemberCopier    copier = MemberCopier.getCopyClass(sourceCollection.GetType().GetGenericArguments()[0]);

            foreach (T item in sourceCollection)
            {
                Object newObj = copier.createCopy(item, filter);
                destinationCollection.Add((T)newObj);
            }
            info.setValue(destination, destinationCollection, null);
        }
Example #20
0
 /// <summary>
 /// Create a new instance of the copy type that is a clone of source.
 /// </summary>
 /// <param name="source">The source object.</param>
 /// <param name="filter">The filter to use when copying.  Can be null.</param>
 /// <returns>An exact copy of source.</returns>
 internal abstract Object createCopy(Object source, CopyFilter filter);
Example #21
0
        public static void CopyDirectory(string sourcePath, string destinationPath, string suffix = "", CopyFilter onFilter = null)
        {
            if (onFilter != null && onFilter(sourcePath))
            {
                return;
            }

            Directory.CreateDirectory(destinationPath);
            DirectoryInfo info = new DirectoryInfo(sourcePath);

            foreach (FileSystemInfo fsi in info.GetFileSystemInfos())
            {
                string destName = Path.Combine(destinationPath, fsi.Name);
                if (fsi is System.IO.FileInfo)
                {
                    File.Copy(fsi.FullName, destName);
                }
                else
                {
                    Directory.CreateDirectory(destName);
                    CopyDirectory(fsi.FullName, destName);
                }
            }
        }
Example #22
0
 /// <summary>
 /// This will copy source into destination.
 /// </summary>
 /// <param name="source">The source object.</param>
 /// <param name="destination">The destination object.</param>
 /// <param name="info">The info to use to set the value.</param>
 /// <param name="filter">The filter to use when copying.  Can be null.</param>
 internal abstract void copyValue(Object source, Object destination, MemberWrapper info, CopyFilter filter);
 /// <summary>
 /// Create a new object that is an exact copy of source.
 /// </summary>
 /// <param name="source">The object to copy.</param>
 /// <returns>A new object that is a copy of source.</returns>
 internal override object createCopy(object source, CopyFilter filter)
 {
     return(source);
 }
 /// <summary>
 /// Copy source to destination.
 /// </summary>
 /// <param name="source">The source object.</param>
 /// <param name="destination">The destination object.</param>
 /// <param name="info">The info to use to set the value.</param>
 internal override void copyValue(object source, object destination, MemberWrapper info, CopyFilter filter)
 {
     info.setValue(destination, info.getValue(source, null), null);
 }
Example #25
0
        void IHttpHandler.ProcessRequest(HttpContext context)
        {
            using (TraceScope traceScope = new TraceScope(context))
            {
                traceScope.TraceEvent(TraceEventType.Verbose, (int)Event.ProcessingRequest,
                                      "Processing request started.");
                if (context.Request == null)
                {
                    //happens when application starts first time
                    traceScope.TraceEvent(TraceEventType.Verbose, (int)Event.ProcessingRequest, "Context is null.");
                    return;
                }

                using (var executionScope = new ExecutionScope(nameof(IHttpHandler.ProcessRequest)))
                {
                    if (!s_initialized)
                    {
                        Initialize();
                    }

                    Authentication auth = new Authentication(context.Request);
                    if (ProcessUiPage(context, auth))
                    {
                        return;
                    }

                    RemoteApplication remoteApplication = RemoteApplication.GetRemoteApplication(context.Request);

                    if (remoteApplication == null)
                    {
                        traceScope.TraceEvent(TraceEventType.Warning, (int)Event.NotFound,
                                              "No RemoteApplication found. Ending with 404.");
                        context.Response.StatusCode = 404;
                        context.Response.End();
                    }

                    TrafficLogger logger = GetLogger(context, remoteApplication, traceScope);
                    executionScope.SetLogger(logger);

                    HttpWebRequest  webRequest  = null;
                    HttpWebResponse webResponse = null;

                    using (Stream inputBuffer = CopyFilter.GetInputStream(context.Request))
                    {
                        for (int tries = 0; tries <= Properties.Settings.Default.NetworkRetryCount; tries++)
                        {
                            if (tries > 0)
                            {
                                System.Threading.Thread.Sleep(Properties.Settings.Default.NetworkRetryDelay);
                                traceScope.TraceEvent(TraceEventType.Error, (int)Event.ProcessingResponse,
                                                      "trying again.");
                                inputBuffer.Position = 0;
                            }

                            using (new ExecutionScope(nameof(remoteApplication.CreateRightSideRequest)))
                            {
                                try
                                {
                                    webRequest = remoteApplication.CreateRightSideRequest(context.Request, inputBuffer, logger);

                                    if (remoteApplication.LogTraffic)
                                    {
                                        logger.LogRequestInformation(webRequest);
                                    }
                                }
                                catch (AuthorizationException e)
                                {
                                    traceScope.TraceEvent(TraceEventType.Verbose, (int)Event.NotAuthorized, e.Message);
                                    context.Response.StatusCode = 403;
                                    context.Response.End();
                                }
                            }

                            traceScope.TraceEvent(TraceEventType.Verbose, (int)Event.ProcessingRequest,
                                                  "Processing request finished.");

                            using (new ExecutionScope(nameof(auth.GetWebResponse)))
                            {
                                try
                                {
                                    webResponse = auth.GetWebResponse(webRequest, traceScope);
                                }
                                catch (WebException ex)
                                {
                                    traceScope.TraceEvent(TraceEventType.Error, (int)Event.ProcessingResponse,
                                                          "Could not get right side response: {0}", ex.Message);
                                    if (ex.Response == null)
                                    {
                                        if (IsRetryable(ex, remoteApplication.IsSoap))
                                        {
                                            if (webRequest != null)
                                            {
                                                webRequest.Abort();
                                                webRequest = null;
                                            }
                                            continue;
                                        }
                                        else if (ex.Status == WebExceptionStatus.Timeout)
                                        {
                                            traceScope.TraceEvent(TraceEventType.Error, (int)Event.ProcessingResponse,
                                                                  "Ending with 408 Timeout.");
                                            context.Response.StatusCode = 408;
                                            context.Response.End();

                                            /*
                                             * 408 Request Timeout Der Server hat eine erwartete Anfrage nicht innerhalb des dafür festgelegten Maximalzeitraums erhalten. Die Verbindung zum anfragenden Browser wird deshalb abgebaut. Angeforderte Daten werden nicht übertragen.
                                             * 412 Precondition Failed Eine oder mehrere Bedingungen, die bei der Anfrage gestellt wurden, treffen nicht zu. Die angeforderten Daten werden deshalb nicht übertragen.
                                             * 500 Internal Server Error Der Server kann die angeforderten Daten nicht senden, weil auf dem Server ein Fehler aufgetreten ist. Beispielsweise konnte das aufgerufene CGI-Script nicht gestartet werden.
                                             * 502 Bad Gateway Zum Bearbeiten der Anfrage musste der Server einen anderen Server aufrufen, erhielt dabei jedoch eine Fehlermeldung. Die angeforderten Daten können deshalb nicht gesendet werden.
                                             * 503 Service Unavailable Der Server kann die Anfrage wegen Überlastung nicht bearbeiten. Die angeforderten Daten können deshalb nicht gesendet werden. In der Statusmeldung kann stehen, wann die Anfrage frühestens wieder bearbeitet werden kann. Im Gegensatz zum Status-Code 202 verarbeitet der Server die Daten nicht, sobald er wieder Kapazitäten hat.
                                             * 504 Gateway Timeout Zum Bearbeiten der Anfrage musste der Server einen anderen Server aufrufen, erhielt dabei jedoch nach einem festgelegten Maximalzeitraum keine Antwort. Die angeforderten Daten können deshalb nicht gesendet werden.
                                             */
                                        }
                                        else
                                        {
                                            traceScope.TraceEvent(TraceEventType.Error, (int)Event.ProcessingResponse, "Ending with 500.");
                                            traceScope.TraceEvent(TraceEventType.Error, (int)Event.ProcessingResponse,
                                                                  "No response available.");
                                            traceScope.TraceEvent(TraceEventType.Error, (int)Event.ProcessingResponse,
                                                                  "Input stream follows.");
                                            LogInputStream(context, inputBuffer, traceScope);
                                            context.Response.StatusCode        = 500;
                                            context.Response.StatusDescription = ex.Message;
                                            context.Response.End();
                                        }
                                    }
                                    else
                                    {
                                        webResponse = (HttpWebResponse)ex.Response;
                                    }
                                } // end catch webResponse = auth.GetWebResponse (webRequest);
                            }

                            if (ShouldRetry(webResponse, remoteApplication.IsSoap))
                            {
                                traceScope.TraceEvent(TraceEventType.Error, (int)Event.ProcessingResponse,
                                                      "Received " + webResponse.StatusCode);
                                if (tries < Properties.Settings.Default.NetworkRetryCount)
                                {
                                    webResponse.Close();
                                }
                                webRequest = null;
                                continue;
                            }
                            break;
                        } // end for tries
                    }     // end using inputBuffer

                    if (webResponse == null)
                    {
                        traceScope.TraceEvent(TraceEventType.Verbose, (int)Event.ProcessingResponse,
                                              "Response is null.");
                        context.Response.StatusCode        = 502;
                        context.Response.StatusDescription = "No response reveived from upstream server.";
                        context.Response.End();
                    }

                    bool errorEncountered = webResponse.StatusCode.Equals(HttpStatusCode.InternalServerError);
                    bool bufferResponse   = Settings.Default.BufferRightSide || errorEncountered || remoteApplication.LogTraffic;
                    using (Stream output = GetOutputStream(context.Response, webResponse.ContentLength, bufferResponse))
                    {
                        using (HttpWebResponse response = webResponse)
                        {
                            traceScope.TraceEvent(TraceEventType.Verbose, (int)Event.ProcessingResponse,
                                                  "Processing response started.");
                            if (remoteApplication.LogTraffic)
                            {
                                logger.LogResponseInformation(response);
                            }

                            remoteApplication.ShapeHttpResponse(response, context.Response);

                            Stream rightSideResponseStream = response.GetResponseStream();

                            CopyFilter filter = new CopyFilter(response.ContentLength);
                            filter.FilterStream(rightSideResponseStream, output);

                            traceScope.TraceEvent(TraceEventType.Verbose, (int)Event.ProcessingResponse,
                                                  "Processing response finished.");
                        }

                        if (errorEncountered)
                        {
                            output.Position = 0;
                            byte[] buffer = new byte[output.Length];
                            output.Read(buffer, 0, (int)output.Length);
                            Encoding encoding = Encoding.UTF8;
                            if (context.Response.ContentEncoding != null)
                            {
                                encoding = context.Response.ContentEncoding;
                            }
                            traceScope.TraceEvent(TraceEventType.Error, (int)Event.ProcessingResponse,
                                                  "Response stream follows.");
                            traceScope.TraceData(TraceEventType.Error, (int)Event.ProcessingResponse,
                                                 encoding.GetString(buffer));
                        }

                        if (remoteApplication.LogTraffic)
                        {
                            logger.LogResponseContent((MemoryStream)output);
                        }

                        if (bufferResponse)
                        {
                            output.Position = 0;
                            CopyFilter filter = new CopyFilter(output.Length);
                            filter.FilterStream(output, context.Response.OutputStream);
                        }

                        context.Response.End();
                    }
                }
            }
        }
        /// <summary>
        /// This function will copy all the values from source into object.
        /// </summary>
        /// <param name="source">The source object.</param>
        /// <param name="destination">The destination object.</param>
        /// <param name="info">The member wrapper that allows the values to be set.</param>
        internal override void copyValue(object source, object destination, MemberWrapper info, CopyFilter filter)
        {
            Object deepCopySource;
            Object deepCopyDestination;

            //Find the source and destination objects if no info is provided use the given objects
            if (info != null)
            {
                deepCopySource      = info.getValue(source, null);
                deepCopyDestination = info.getValue(destination, null);
            }
            else
            {
                deepCopySource      = source;
                deepCopyDestination = destination;
            }
            //Validate that there is a source.
            if (deepCopySource != null)
            {
                performCopy(destination, info, deepCopySource, deepCopyDestination, filter);
            }
        }
        /// <summary>
        /// Helper function, actually does the copy.
        /// </summary>
        /// <param name="destination"></param>
        /// <param name="info"></param>
        /// <param name="deepCopySource"></param>
        /// <param name="deepCopyDestination"></param>
        internal void performCopy(object destination, MemberWrapper info, Object deepCopySource, Object deepCopyDestination, CopyFilter filter)
        {
            Type type = deepCopySource.GetType();

            //Make sure the destination exists, if it does not create it
            if (deepCopyDestination == null)
            {
                deepCopyDestination = System.Activator.CreateInstance(type);
                info.setValue(destination, deepCopyDestination, null);
            }
            //Scan and copy all properties.
            IEnumerable <MemberWrapper> members = CopyMemberScanner.Scanner.getMatchingMembers(type);

            foreach (MemberWrapper member in members)
            {
                if (filter == null || filter.allowCopy(member))
                {
                    MemberCopier copier = MemberCopier.getCopyClass(member.getWrappedType());
                    copier.copyValue(deepCopySource, deepCopyDestination, member, filter);
                }
            }
        }