Beispiel #1
0
        internal void ExecuteScanToDestination(DestinationType destinationType)
        {
            const int MaxPageCountThresholdForProcessingNotificationError = 2;
            int       expectedNumberOfGeneratedFiles = 1;
            int       step        = 0;
            string    uiContextId = "<Missing uiContextId>";

            _owner.OnUpdateStatus(this, $"Step {++step}: Setup {destinationType} scan ticket.");
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;

            var tree        = DiscoveryTreeTranslator.GetOXPdDiscoveryTree(_deviceDat.Address);
            var scanFactory = new ScanProxyFactory();
            var scanProxy   = scanFactory.CreateProxy(tree, _deviceDat.Address, _deviceDat.AdminPassword);
            var uiFactory   = new UIConfigurationProxyFactory();
            var uiProxy     = uiFactory.CreateProxy(tree, _deviceDat.Address, _deviceDat.AdminPassword);
            var testFactory = new TestProxyFactory();
            var testProxy   = testFactory.CreateProxy(tree, _deviceDat.Address, _deviceDat.AdminPassword);

            ScanTicket jobTicket = new ScanTicket();

            jobTicket.transmissionMode         = TransmissionMode.Job;
            jobTicket.basicOptions             = scanProxy.GetDefaultBasicOptions(jobTicket.transmissionMode);
            jobTicket.basicOptions.mediaSource = MediaSource.Flatbed;
            jobTicket.destination = new OXPd.Common.WebResourceWithTimeoutAndRetry();
            jobTicket.destination.connectionTimeout = 60;
            jobTicket.destination.responseTimeout   = 300;
            jobTicket.destination.retryInterval     = 1;
            jobTicket.destination.binding           = OXPd.Common.Binding.Plain;

            switch (destinationType)
            {
            case DestinationType.Ftp:
                jobTicket.destination.uri = _endpointManager.FtpServer.EndpointAddress;
                jobTicket.destination.networkCredentials = new OXPd.Common.NetworkCredentials()
                {
                    userName = _userCredential.UserName, password = _userCredential.Password
                };
                break;

            case DestinationType.Http:
                jobTicket.destination.uri = _endpointManager.HttpScanReceiver.EndpointAddress;
                jobTicket.destination.networkCredentials = new OXPd.Common.NetworkCredentials()
                {
                    userName = "******", password = "******"
                };
                break;

            case DestinationType.NetworkFolder:
                jobTicket.destination.uri = _endpointManager.NetworkFolder.EndpointAddress;
                jobTicket.destination.networkCredentials = new OXPd.Common.NetworkCredentials()
                {
                    domain = _userCredential.Domain, userName = _userCredential.UserName, password = _userCredential.Password
                };
                break;
            }

            jobTicket.fileOptions      = scanProxy.GetDefaultFileOptions(jobTicket.basicOptions.fileType, jobTicket.basicOptions.colorMode);
            jobTicket.metadata         = null;
            jobTicket.scanFileNameBase = DateTimeStampForNaming + "_" + EndpointPath.GetProtocolAsString(destinationType);
            _owner.OnUpdateStatus(this, $"Target Folder as URI (PathManager): {_endpointManager.PathManager.GetEndpointPath(destinationType).GetPathAsUrl()}");
            _owner.OnUpdateStatus(this, $"Target Folder as URI (JobTicket): {jobTicket.destination.uri}");
            _owner.OnUpdateStatus(this, $"Target Folder as Path: {_endpointManager.PathManager.GetEndpointPath(destinationType).CorrespondingFileSystemPath}");
            _owner.OnUpdateStatus(this, $"Target File as Path: {_endpointManager.PathManager.GetEndpointPath(destinationType).CorrespondingFileSystemPath + @"\" + jobTicket.scanFileNameBase + "*.*"}");
            string qualifiedUserName = (jobTicket.destination.networkCredentials.domain == null) ? jobTicket.destination.networkCredentials.userName : $"{jobTicket.destination.networkCredentials.domain}\\{jobTicket.destination.networkCredentials.userName}";

            _owner.OnUpdateStatus(this, $"Credentials: Username = { qualifiedUserName}; Password = { jobTicket.destination.networkCredentials.password}");

            try
            {
                var    targetFolder         = new DirectoryInfo(_endpointManager.PathManager.GetEndpointPath(destinationType).CorrespondingFileSystemPath);
                int    preexistingFileCount = 0;
                string increaseCountMessage = $"This job is expected to create {expectedNumberOfGeneratedFiles} more file(s).";
                if (targetFolder.Exists)
                {
                    _owner.OnUpdateStatus(this, $"Step {++step}: Get pre-existing file count on destination folder.");
                    preexistingFileCount = CurrentFileCount(targetFolder);
                    _owner.OnUpdateStatus(this, $"Found {preexistingFileCount} files. {increaseCountMessage}");
                }
                else
                {
                    _owner.OnUpdateStatus(this, $"Step {++step}: Found {preexistingFileCount} files because destination folder does not exist. {increaseCountMessage}");
                    targetFolder.Create();
                }

                _owner.OnUpdateStatus(this, $"Step {++step}: Reserve UI context.");
                uiContextId = uiProxy.ReserveUIContext(_endpointManager.HttpServerSim.EndpointAddress);
                _owner.OnUpdateStatus(this, $"Step {++step}: Wait for OXPd browser state to be {BrowserState.Idle}.");
                Wait.ForTrue(() => testProxy.GetBrowserState() == BrowserState.Idle, new TimeSpan(0, 0, 30), new TimeSpan(0, 0, 1));
                _owner.OnUpdateStatus(this, $"Step {++step}: Start scan job.");
                string scanJobId = scanProxy.StartScanJob(uiContextId, null, jobTicket);

                _owner.OnUpdateStatus(this, $"Step {++step}: Wait for scan progress window.");
                const string NotificationText = "Processing";
                if (!JediOmniDeviceHelper.WaitForValue(_deviceDat, ".hp-popup-content:visible", "innerHTML", OmniPropertyType.Property, NotificationText, StringMatch.Contains, StringComparison.InvariantCulture, new TimeSpan(0, 0, 5), new TimeSpan(0, 0, 5)))
                {
                    string message = $"Step {step} '{NotificationText}' notification was not detected.";
                    if (expectedNumberOfGeneratedFiles <= MaxPageCountThresholdForProcessingNotificationError)
                    {
                        message += $"  This is probably okay since this is a small scan job.";
                    }
                    else
                    {
                        message = $"Non-fatal error.  {message}  Enough pages are being scanned that this should not happen.";
                    }
                    _owner.OnUpdateStatus(this, message);
                }

                _owner.OnUpdateStatus(this, $"Step {++step}: Verify {nameof(ResultCode)} returned by device scan service.  (Expecting: {ResultCode.Succeeded}).");
                Wait.ForTrue(() => scanProxy.GetScanJobStatus(scanJobId).resultCode == ResultCode.Succeeded, new TimeSpan(0, 0, 30), new TimeSpan(0, 0, 1));

                switch (destinationType)
                {
                case DestinationType.Http:
                    try
                    {
                        _owner.OnUpdateStatus(this, $"Step {++step}: Verify webserver received {expectedNumberOfGeneratedFiles} requests(s).");
                        _endpointManager.HttpScanReceiver.WaitForRequests(expectedNumberOfGeneratedFiles, new TimeSpan(0, 0, 5 * 60));
                        _owner.OnUpdateStatus(this, $"Step {++step}: Verify webserver requests resulted in {expectedNumberOfGeneratedFiles} uploaded file(s).");
                        var webServerFiles = _endpointManager.HttpScanReceiver.SaveUploadedFiles(targetFolder).ToList();

                        if (webServerFiles.Count() != expectedNumberOfGeneratedFiles)
                        {
                            string paramMessage = $"Expected: {expectedNumberOfGeneratedFiles}; Actual: {webServerFiles.Count}";
                            throw new ActualVsExpectedException($"Web server reports incorrect uploaded file count. {paramMessage}");
                        }

                        _endpointManager.HttpScanReceiver.RequestsReceived.Clear();
                    }
                    catch (ThreadAbortException tax)
                    {
                        _owner.OnUpdateStatus(this, $"{tax.GetType().Name} in Step {step}{Environment.NewLine}{tax.ToString()}.");
                        _owner.OnUpdateStatus(this, $"Will attempt to continue.");
                    }
                    break;
                }

                _owner.OnUpdateStatus(this, $"Step {++step}: Verify that {expectedNumberOfGeneratedFiles} file(s) arrived on server.");
                VerifyFileCount(targetFolder, preexistingFileCount, expectedNumberOfGeneratedFiles, new TimeSpan(0, 5, 0));
            }
            catch (Exception x)
            {
                _owner.OnUpdateStatus(this, $"{x.GetType().Name} in Step {step}{Environment.NewLine}{x.ToString()}");
                throw;
            }
            finally
            {
                try
                {
                    _owner.OnUpdateStatus(this, $"Step {++step}: Release UI Context ID.");
                    uiProxy.ReleaseUIContext(uiContextId);
                }
                catch (Exception idX)
                {
                    _owner.OnUpdateStatus(this, $"Could not release uiContextId: {idX.Message}.");
                }

                _owner.OnUpdateStatus(this, $"Step {++step}: Wait for home screen.");
                JediOmniDeviceHelper.WaitForHome(_deviceDat, new TimeSpan(0, 0, 30));
            }
        }
        public void Noid(string param)
        {
            var     p = TestProxyFactory.Create();
            Session sessionToExamine = null;

            p.BeforeRequest += session =>
            {
                sessionToExamine = session;
                string pathAndQuery;
                string host;
                string q = session.PathAndQuery.TrimStart('/');

                host = Utilities.TrimAfter(q, "/");
                if (q.IndexOf('/') > -1)
                {
                    pathAndQuery = "/" + Utilities.TrimBefore(q, "/");
                }
                else
                {
                    pathAndQuery = "/";
                }
                session.host         = host;
                session.PathAndQuery = pathAndQuery;
            };

            p.Start();

            try
            {
                new WebClient().UploadString("http://localhost.:" + TestProxyFactory.Port + "/httpbin.org/post?foo=" + param, "bar=" + param);

                // lets try to round-trip the captured session

                Tape tape       = HttpArchiveTranscoder.Export(new[] { sessionToExamine });
                var  json       = JsonConvert.SerializeObject(tape.log.entries[0], Formatting.Indented);
                var  sessionOut = HttpArchiveTranscoder.Import(tape)[0];
                bool fail       = false;
                if (sessionToExamine.PathAndQuery != sessionOut.PathAndQuery)
                {
                    fail = true;
                    Console.WriteLine("PathAndQuery");
                }
                if (!CompareByteArrays(sessionToExamine.RequestBody, sessionOut.RequestBody, "RequestBody"))
                {
                    fail = true;
                    Console.WriteLine("RequestBody");

                    Console.WriteLine("--------------------------------------------------------");
                    Console.WriteLine(Encoding.UTF8.GetString(sessionToExamine.RequestBody));
                    Console.WriteLine("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");

                    Console.WriteLine(Encoding.UTF8.GetString(sessionOut.RequestBody));
                    Console.WriteLine("--------------------------------------------------------");
                }
                if (!CompareByteArrays(sessionToExamine.ResponseBody, sessionOut.ResponseBody, "ResponseBody"))
                {
                    fail = true;
                    Console.WriteLine("ResponseBody");
                    Console.WriteLine("--------------------------------------------------------");
                    Console.WriteLine(Encoding.UTF8.GetString(sessionToExamine.ResponseBody));
                    Console.WriteLine("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");

                    Console.WriteLine(Encoding.UTF8.GetString(sessionOut.ResponseBody));
                    Console.WriteLine("--------------------------------------------------------");
                }
                // fiddler static inc if (sessionToExamine.SuggestedFilename != sessionOut.SuggestedFilename) Console.WriteLine("SuggestedFilename");
                if (sessionToExamine.TunnelEgressByteCount != sessionOut.TunnelEgressByteCount)
                {
                    fail = true;
                    Console.WriteLine("TunnelEgressByteCount");
                }
                if (sessionToExamine.TunnelIngressByteCount != sessionOut.TunnelIngressByteCount)
                {
                    fail = true;
                    Console.WriteLine("TunnelIngressByteCount");
                }
                if (sessionToExamine.TunnelIsOpen != sessionOut.TunnelIsOpen)
                {
                    fail = true;
                    Console.WriteLine("TunnelIsOpen");
                }
                if (sessionToExamine.bHasResponse != sessionOut.bHasResponse)
                {
                    fail = true;
                    Console.WriteLine("bHasResponse");
                }
                if (sessionToExamine.bypassGateway != sessionOut.bypassGateway)
                {
                    fail = true;
                    Console.WriteLine("bypassGateway");
                }
                if (sessionToExamine.fullUrl != sessionOut.fullUrl)
                {
                    fail = true;
                    Console.WriteLine("fullUrl");
                }
                if (sessionToExamine.host != sessionOut.host)
                {
                    fail = true;
                    Console.WriteLine("host");
                }
                if (sessionToExamine.hostname != sessionOut.hostname)
                {
                    fail = true;
                    Console.WriteLine("hostname");
                }
                // fiddler static inc if (sessionToExamine.id != sessionOut.id) Console.WriteLine("id");
                if (sessionToExamine.isFTP != sessionOut.isFTP)
                {
                    fail = true;
                    Console.WriteLine("isFTP");
                }
                if (sessionToExamine.isHTTPS != sessionOut.isHTTPS)
                {
                    fail = true;
                    Console.WriteLine("isHTTPS");
                }
                if (sessionToExamine.isTunnel != sessionOut.isTunnel)
                {
                    fail = true;
                    Console.WriteLine("isTunnel");
                }


                if (sessionToExamine.port != sessionOut.port)
                {
                    fail = true;
                    Console.WriteLine("port");
                }
                if (!CompareByteArrays(sessionToExamine.requestBodyBytes, sessionOut.requestBodyBytes, "requestBodyBytes"))
                {
                    fail = true;
                    Console.WriteLine("requestBodyBytes");
                    Console.WriteLine("--------------------------------------------------------");
                    Console.WriteLine(Encoding.UTF8.GetString(sessionToExamine.requestBodyBytes));
                    Console.WriteLine("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");

                    Console.WriteLine(Encoding.UTF8.GetString(sessionOut.requestBodyBytes));
                    Console.WriteLine("--------------------------------------------------------");
                }
                if (!CompareByteArrays(sessionToExamine.responseBodyBytes, sessionOut.responseBodyBytes, "responseBodyBytes"))
                {
                    fail = true;
                    Console.WriteLine("responseBodyBytes");
                    Console.WriteLine("--------------------------------------------------------");
                    Console.WriteLine(Encoding.UTF8.GetString(sessionToExamine.responseBodyBytes));
                    Console.WriteLine("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");

                    Console.WriteLine(Encoding.UTF8.GetString(sessionOut.responseBodyBytes));
                    Console.WriteLine("--------------------------------------------------------");
                }
                if (sessionToExamine.responseCode != sessionOut.responseCode)
                {
                    fail = true;
                    Console.WriteLine("responseCode");
                }
                if (sessionToExamine.state != sessionOut.state)
                {
                    fail = true;
                    Console.WriteLine("state");
                }
                if (sessionToExamine.url != sessionOut.url)
                {
                    fail = true;
                    Console.WriteLine("url");
                }

                // not tx if (sessionToExamine.clientIP != sessionOut.clientIP) Console.WriteLine("clientIP");
                // not tx if (sessionToExamine.clientPort != sessionOut.clientPort) Console.WriteLine("clientPort");
                // not tx  if (sessionToExamine.m_clientIP != sessionOut.m_clientIP) Console.WriteLine("m_clientIP");
                // not tx if (sessionToExamine.m_clientPort != sessionOut.m_clientPort) Console.WriteLine("m_clientPort");
                // not tx ?? if (sessionToExamine.m_hostIP != sessionOut.m_hostIP) Console.WriteLine("m_hostIP");
                // #TODO: compare hashtables
                //if (sessionToExamine.oFlags != sessionOut.oFlags) Console.WriteLine("oFlags");
                // object comparison if (sessionToExamine.oRequest != sessionOut.oRequest) Console.WriteLine("oRequest");
                // object comparison if (sessionToExamine.oResponse != sessionOut.oResponse) Console.WriteLine("oResponse");

                //#TODO check export "!string.IsNullOrEmpty(session["ui-comments"])
                //if (sessionToExamine.BitFlags != sessionOut.BitFlags) Console.WriteLine("BitFlags");
                //if (sessionToExamine.LocalProcessID != sessionOut.LocalProcessID) Console.WriteLine("LocalProcessID");

                Assert.False(fail, "round trip failed");
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
            finally
            {
                p.Stop();
            }
        }