Пример #1
0
 public RequestNetworkStream(EndpointAddress to)
 {
     _to = to;
     if (!InternalLog)
     {
         InternalLogger.GetInstance().SwitchOffForCurrentThread();
     }
 }
Пример #2
0
        /// <summary>
        /// Perform common initialization/finalization. Run test action.
        /// </summary>
        /// <param name="action">Test "body"</param>
        /// <param name="cleanUpAction">Clean-up </param>
        protected void RunTest(Action action, Action cleanUpAction)
        {
            if (allPassedModeOn())
            {
                return;
            }

            try
            {
                _halted = false;
                Exception exc = null;

                try
                {
                    System.Diagnostics.Debug.WriteLine("Begin test - inside 1");
                    BeginTest();

                    if (this is IBaseOnvifService)
                    {
                        (this as IBaseOnvifService).GeneralInitialize();
                    }

                    System.Diagnostics.Debug.WriteLine("Begin test - do action");
                    action();
                    System.Diagnostics.Debug.WriteLine("Begin test - action done");

                    if (cleanUpAction == null)
                    {
                        System.Diagnostics.Debug.WriteLine("Begin test - to end test");
                        EndTest(TestStatus.Passed);
                        return;
                    }
                }
                catch (StopEventException)
                {
                    System.Diagnostics.Debug.WriteLine("HALT");

                    if (_videoForm != null)
                    {
                        _videoForm.CloseWindow();
                    }
                    if (NewGenVideo != null)
                    {
                        NewGenVideo.CloseWindow();
                    }

                    Release();
                    _halted = true;

                    LogStepEvent("Halted");
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Begin test - Exception in action");
                    StepFailed(ex);
                    System.Diagnostics.Debug.WriteLine("Begin test - fail reported");

                    if (InternalLog)
                    {
                        InternalLogger.GetInstance().SwitchOnForCurrentThread();
                    }
                    else
                    {
                        InternalLogger.GetInstance().SwitchOffForCurrentThread();
                    }

                    InternalLogger.GetInstance().LogMessage("Uncaught exception is thrown during the test!");
                    InternalLogger.GetInstance().LogException(ex);

                    if (cleanUpAction == null)
                    {
                        System.Diagnostics.Debug.WriteLine("Begin test - doing Release");
                        Release();
                        TestFailed(ex);
                        return;
                    }
                    else
                    {
                        exc = ex;
                    }
                }

                if (cleanUpAction != null && !_halted)
                {
                    try
                    {
                        System.Diagnostics.Debug.WriteLine("Clean up");
                        cleanUpAction();
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine("Exception when trying to restore settings");
                        StepFailed(ex);
                        exc = ex;
                    }

                    if (exc == null)
                    {
                        System.Diagnostics.Debug.WriteLine("End test - passed");
                        EndTest(TestStatus.Passed);
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("Test failed");
                        try
                        {
                            Release();
                        }
                        catch (Exception)
                        {
                        }
                        TestFailed(exc);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("new catch - Test failed");
                TestFailed(ex);
            }
        }
Пример #3
0
        /// <summary>
        /// Perform common initialization/finalization. Run test action.
        /// </summary>
        /// <param name="action">Test "body"</param>
        /// <param name="cleanUpAction">Clean-up </param>
        protected void RunTest(Action action, Action cleanUpAction)
        {
            if (allPassedModeOn())
            {
                return;
            }

            try
            {
                _halted = false;
                Exception exc = null;

                try
                {
                    System.Diagnostics.Debug.WriteLine("Begin test - inside 1");
                    BeginTest();

                    System.Diagnostics.Debug.WriteLine("Begin test - do action");
                    action();
                    System.Diagnostics.Debug.WriteLine("Begin test - action done");

                    if (cleanUpAction == null)
                    {
                        System.Diagnostics.Debug.WriteLine("Begin test - to end test");
                        EndTest(TestStatus.Passed);
                        return;
                    }
                }
                catch (StopEventException)
                {
                    System.Diagnostics.Debug.WriteLine("HALT");

                    if (_videoForm != null)
                    {
                        _videoForm.CloseWindow();
                    }

                    Release();
                    _halted = true;

                    LogStepEvent("Halted");
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Begin test - Exception in action");
                    StepFailed(ex);
                    System.Diagnostics.Debug.WriteLine("Begin test - fail reported");

                    if (InternalLog)
                    {
                        InternalLogger.GetInstance().SwitchOnForCurrentThread();
                    }
                    else
                    {
                        InternalLogger.GetInstance().SwitchOffForCurrentThread();
                    }

                    InternalLogger.GetInstance().LogMessage("Uncaught exception is thrown during the test!");
                    InternalLogger.GetInstance().LogMessage("Exception stack below:");
                    var prefix = "    ";
                    for (var e = ex; null != e; e = e.InnerException)
                    {
                        InternalLogger.GetInstance().LogMessage(string.Format("{0}{1}: {2}", prefix, e.GetType().Name, e.Message));
                    }
                    InternalLogger.GetInstance().LogMessage(ex.StackTrace);

                    if (cleanUpAction == null)
                    {
                        System.Diagnostics.Debug.WriteLine("Begin test - doing Release");
                        Release();
                        TestFailed(ex);
                        return;
                    }
                    else
                    {
                        exc = ex;
                    }
                }

                if (cleanUpAction != null && !_halted)
                {
                    try
                    {
                        System.Diagnostics.Debug.WriteLine("Clean up");
                        cleanUpAction();
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine("Exception when trying to restore settings");
                        StepFailed(ex);
                        exc = ex;
                    }

                    if (exc == null)
                    {
                        System.Diagnostics.Debug.WriteLine("End test - passed");
                        EndTest(TestStatus.Passed);
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("Test failed");
                        try
                        {
                            Release();
                        }
                        catch (Exception)
                        {
                        }
                        TestFailed(exc);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("new catch - Test failed");
                TestFailed(ex);
            }
        }
Пример #4
0
        public void EnsureOpen(EndpointAddress address)
        {
            InternalLogger.GetInstance().LogMessage("Entered EnsureOpen");
            try
            {
                //bool close = false;
                bool close = _to != address;

                if (close && null != _to)
                {
                    InternalLogger.GetInstance().LogMessage(string.Format("Endpoint address changed. Old: {0}. New: {1}.", _to, address));
                }

                _to = address;

                var createFlag = false;
                if (_socket == null)
                {
                    close      = true;
                    createFlag = true;
                    InternalLogger.GetInstance().LogMessage(string.Format("Socket for endpoint with address {0} does not exist.", _to));
                }
                else
                {
                    InternalLogger.GetInstance().LogMessage(string.Format("Socket exists and is{0} connected to remote host.", _socket.Connected ? "" : "n't"));
                    if (_socket.Connected)
                    {
                        var  timeout   = 500;
                        bool writePoll = _socket.Poll(timeout, SelectMode.SelectWrite);
                        InternalLogger.GetInstance().LogMessage(string.Format("Socket.Poll({0}, SelectMode.SelectWrite): {1}.", timeout, writePoll));
                        if (writePoll)
                        {
                            try
                            {
                                _socket.Send(new byte[0]);
                                InternalLogger.GetInstance().LogMessage("Socket.Send is called successfully.");
                            }
                            catch (SocketException e)
                            {
                                InternalLogger.GetInstance().LogMessage(string.Format("Socket.Send has thrown an exception: {0}", e.Message));
                                if (!e.NativeErrorCode.Equals(SocketError.WouldBlock))
                                {
                                    InternalLogger.GetInstance().LogMessage(string.Format("    The socket is dead because thrown exception isn't WSAEWOULDBLOCK."));
                                    close = true;
                                }
                                else
                                {
                                    InternalLogger.GetInstance().LogMessage(string.Format("    The socket is alive because thrown exception is WSAEWOULDBLOCK."));
                                }
                            }

                            var readPoll = _socket.Poll(timeout, SelectMode.SelectRead);
                            if (!close && readPoll)
                            {
                                InternalLogger.GetInstance().LogMessage(string.Format("Socket.Poll({0}, SelectMode.SelectRead): {1}.", timeout, readPoll));
                                var T = _socket.ReceiveTimeout;
                                try
                                {
                                    //By MSDN _socket.Poll(timeout, SelectMode.SelectRead) can return true if the connection has been closed, reset, or terminated.
                                    //For example, if socket receives TCP packet with flags [FIN, ACK] _socket.Poll(timeout, SelectMode.SelectRead) returns true.
                                    //To check this case we perform fake Receive with ReceiveTimeout = 1.
                                    //If ec == SocketError.Success then the connection has been closed, reset, or terminated.
                                    //For example, if connection is still alive then ec after fake Receive will be SocketError.TimedOut.
                                    SocketError ec;
                                    _socket.ReceiveTimeout = 1;
                                    _socket.Receive(new byte[0], 0, 0, SocketFlags.Peek, out ec);
                                    InternalLogger.GetInstance().LogMessage(string.Format("Socket.Receive is called successfully. Socket Error: {0}.", ec));
                                    close = SocketError.Success == ec;
                                }
                                catch (Exception e)
                                {
                                    InternalLogger.GetInstance().LogMessage(string.Format("    The socket is dead because Socket.Send has thrown an exception: {0}.", e.Message));
                                    close = true;
                                }
                                finally
                                {
                                    _socket.ReceiveTimeout = T;
                                }
                            }
                        }
                        else
                        {
                            close = true;
                        }
                    }
                    else
                    {
                        close = true;
                    }
                }
                if (close || AlwaysReconnect)
                {
                    if (AlwaysReconnect)
                    {
                        InternalLogger.GetInstance().LogMessage(string.Format("AlwaysReconnect is set. Socket for endpoint with address {0} will be recreated.", _to));
                    }
                    else
                    {
                        InternalLogger.GetInstance().LogMessage(string.Format("Socket for endpoint with address {0} will be {1}created.", _to, createFlag ? "re" : ""));
                    }

                    Close();
                    Connect();
                }
            }
            finally
            {
                InternalLogger.GetInstance().LogMessage("Exited EnsureOpen");
            }
        }
Пример #5
0
        public Message Request(Message message, TimeSpan timeout)
        {
            // check input parameters
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }
            if (timeout < TimeSpan.Zero)
            {
                throw new ArgumentOutOfRangeException("timeout");
            }

            _currentMessage = message;

            if (_endpointController != null)
            {
                _to = _endpointController.Address;
            }

            if (_wsaController != null)
            {
                _wsaController.ProcessRequest(message);
                message.Headers.To = _endpointController.Address.Uri;
            }
            else
            {
                // clear headers since not all cameras understand them.
                message.Headers.Action    = null;
                message.Headers.ReplyTo   = null;
                message.Headers.MessageId = null;
            }

            // check if underlying stream has not been closed by the server
            NetworkStream.EnsureOpen(_to);

            base.ThrowIfDisposedOrNotOpen();

            _currentMessageBytes = null;

            // send message
            // Start reading
            // Wait first byte for timeout.TotalMilliseconds
            int readTimeout = (int)timeout.TotalMilliseconds;

            // initialize variables
            MemoryStream responseStream = null;
            HttpPacket   header         = null;
            var          messageCopy    = message.CreateBufferedCopy(int.MaxValue);

            try
            {
                WriteMessageToStream(messageCopy.CreateMessage());

                do
                {
                    responseStream = new MemoryStream();
                    GetResponse(responseStream, out header, readTimeout);
                } while (header.StatusCode == (int)System.Net.HttpStatusCode.Continue);
            }
            catch (ApplicationException)
            {
                throw;
            }
            catch (Exception e)
            {
                if (InternalLog)
                {
                    InternalLogger.GetInstance().SwitchOnForCurrentThread();
                }
                else
                {
                    InternalLogger.GetInstance().SwitchOffForCurrentThread();
                }
                InternalLogger.GetInstance().LogMessage("During sending request to the DUT exception has been thrown!");
                InternalLogger.GetInstance().LogException(e);
                InternalLogger.GetInstance().LogMessage("EnsureOpen was called. Trying to forcibly reopen the network stream and send the request again.");
                NetworkStream.Close();
                NetworkStream.Connect();
                WriteMessageToStream(messageCopy.CreateMessage());

                do
                {
                    responseStream = new MemoryStream();
                    GetResponse(responseStream, out header, readTimeout);
                } while (header.StatusCode == (int)System.Net.HttpStatusCode.Continue);
            }

            // check status 401
            bool digestEnabled = false;

            if (CredentialsProvider != null)
            {
                digestEnabled = CredentialsProvider.Security == Security.Digest ||
                                CredentialsProvider.Security == Security.DigestTesting;
            }

            if (header.StatusCode == (int)System.Net.HttpStatusCode.Unauthorized)
            {
                if (digestEnabled)
                {
                    System.Diagnostics.Debug.WriteLine("HTTP 401 received");

                    foreach (string connectionHeader in header.Connection)
                    {
                        if (StringComparer.InvariantCultureIgnoreCase.Compare(connectionHeader, "close") == 0)
                        {
                            NetworkStream.Close();
                            NetworkStream.EnsureOpen(_to);
                            break;
                        }
                    }

                    // Send request once more.
                    _digestAuthChallenge = header;

                    // uses _digestAuthChallenge (and _currentMessageBytes), so behaviour will be different
                    // (_digestAuthChallenge might be not null by the first attempt, but if we get status 401,
                    // it will be updated)
                    WriteMessageToStream(message);

                    do
                    {
                        responseStream = new MemoryStream();
                        GetResponse(responseStream, out header, readTimeout);
                    } while (header.StatusCode == (int)System.Net.HttpStatusCode.Continue);

                    if (header.StatusCode == (int)System.Net.HttpStatusCode.Unauthorized)
                    {
                        LogResponse(responseStream, header);
                        NetworkStream.Close();
                        throw new AccessDeniedException("Digest authentication FAILED (HTTP status 401 received)");
                    }
                }
                else
                {
                    NetworkStream.Close();
                    LogResponse(responseStream, header);
                    throw new AccessDeniedException("Access denied (HTTP status 401 received)");
                }
            }

            // 2011/12/06: optimization postponed to the next project.
            // 2012/04/13: restore
            foreach (string connectionHeader in header.Connection)
            {
                if (StringComparer.InvariantCultureIgnoreCase.Compare(connectionHeader, "close") == 0)
                {
                    NetworkStream.Close();
                    break;
                }
            }

            int count = (int)responseStream.Length - header.BodyOffset;

            // parse response and notify listeners
            LogResponse(responseStream, header);

            if (header.ContentLength < count)
            {
                if (header.Headers.ContainsKey(HttpHelper.CONTENTLENGTH))
                {
                    throw new HttpProtocolException(
                              string.Format("An error occurred while receiving packet. Expected length: {0}, received: {1}",
                                            header.ContentLength, count));
                }
                else
                {
                    if (!header.NoBodySupposed)
                    {
                        if (header.StatusCode != (int)System.Net.HttpStatusCode.OK)
                        {
                            throw new HttpProtocolException(
                                      string.Format("An error returned. Error code: {0}, error description: {1}",
                                                    header.StatusCode, header.StatusDescription));
                        }
                        else
                        {
                            throw new HttpProtocolException("Content-Length header is missing");
                        }
                    }
                }
            }

            // validate headers
            HttpHelper.ValidateHttpHeaders(header);

            return(ReadMessage(responseStream, header));
        }