Exemplo n.º 1
0
        private void VerificationMode_Click(object sender, RoutedEventArgs e)
        {
            bool VerificationMode;
            var  thisToggle = sender as ToggleButton;

            switch (thisToggle.IsChecked)
            {
            case true:
                VerificationMode = true;
                break;

            case false:
                VerificationMode = false;
                break;

            default:
                VerificationMode = true;
                break;
            }

            if (!SettingsHelper.ModifySettings(Data.ID.ST_VerificationMode, VerificationMode.ToString()))
            {
                Failed();
                return;
            }

            Succeed();
        }
Exemplo n.º 2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MultipleStreamReader"/> class.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <param name="args">The args.</param>
        public MultipleStreamReader(Stream input, MultipleStreamCreateArgs args)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }
            else if (args == null)
            {
                throw new ArgumentNullException("args");
            }

            _input            = input;
            _reader           = new QQnBinaryReader(_input);
            _verificationMode = args.VerificationMode;

            /*_maxCount =*/ _reader.ReadInt32();
            int count = _reader.ReadInt32();

            long nextHeader = _reader.ReadInt64();

            for (int i = 0; i < count; i++)
            {
                _items.Add(new MultiStreamItemHeader(_reader));
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Opens an existing stream and optionally verifies the stream
        /// </summary>
        /// <param name="stream">The stream to open</param>
        /// <param name="mode">The verification to use</param>
        public AssuredStream(Stream stream, VerificationMode mode)
            : this(stream, false)
        {
            _header = new AssuredStreamHeader(stream, mode);

            if (mode == VerificationMode.Full)
            {
                if (!_seekable)
                {
                    throw new InvalidOperationException("Can't fully verify unseekable streams");
                }

                _basePosition = stream.Position;
                if (!_header.VerifyHash(stream))
                {
                    throw new CryptographicException("Invalid hash value");
                }

                stream.Position = _basePosition;
            }
            else
            {
                _basePosition = stream.CanSeek ? stream.Position : 0;
            }
        }
Exemplo n.º 4
0
        /*public AssuredStreamHeader(Stream source)
         *      : this(source, VerificationMode.Full)
         * {
         * }*/

        public AssuredStreamHeader(Stream source, VerificationMode mode)
        {
            QQnBinaryReader br             = new QQnBinaryReader(source);
            uint            vFileSignature = br.ReadUInt32();

            if (vFileSignature != FileSignature)
            {
                throw new FormatException();
            }

            _fileType      = br.ReadString();
            _hashType      = (HashType)br.ReadByte();
            _fileHash      = br.ReadByteArray();
            _hashSignature = br.ReadByteArray();
            byte[] publicKey = br.ReadByteArray();

            if (publicKey.Length > 0)
            {
                _snk = StrongNameKey.LoadFrom(publicKey);

                if (mode != VerificationMode.None)
                {
                    if (!_snk.VerifyHash(_fileHash, _hashSignature))
                    {
                        throw new CryptographicException("Stream hash verification failed");
                    }
                }
            }
            _guid       = new Guid(br.ReadBytes(16));
            _bodyLength = br.ReadInt64();

            _hashPosition = source.Position;
        }
Exemplo n.º 5
0
 public TokenNode(TokenStream tokenStream, Token token, string val, VerificationMode verificationMode = VerificationMode.Is) : base(tokenStream)
 {
     this.type       = token.Type.ToString();
     this.mode       = verificationMode;
     this.doMatchVal = true;
     this.val        = val;
 }
Exemplo n.º 6
0
        /// <summary>
        /// Opens the specified stream.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <param name="verificationMode">The verification mode.</param>
        /// <returns></returns>
        static TPack Open(Stream stream, VerificationMode verificationMode)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            return(new TPack(stream, verificationMode, null));
        }
Exemplo n.º 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AssuredSubStream"/> class.
        /// </summary>
        /// <param name="parentStream">The parent stream.</param>
        /// <param name="verificationMode">The verification mode.</param>
        public AssuredSubStream(Stream parentStream, VerificationMode verificationMode)
            : base(parentStream, true)
        {
            AssuredStream signedParent = GetService <AssuredStream>();

            if (signedParent != null)
            {
                _snk      = signedParent.AssemblyStrongNameKey;
                _hashType = signedParent.HashType;
            }
            else
            {
                _hashType = HashType.SHA1;
            }

            _headerPosition = parentStream.Position;

            _streamHash    = new byte[QQnCryptoHelpers.GetHashBits(_hashType) / 8];
            _hashSignature = new byte[(_snk != null) ? _snk.SignatureLength : 0];

            if (parentStream.CanWrite && parentStream.CanSeek && parentStream.Position == parentStream.Length)
            {
                _updating = true;
                WriteHeader();
            }
            else
            {
                QQnBinaryReader br = new QQnBinaryReader(BaseStream);
                _streamHash    = br.ReadBytes(_streamHash.Length);
                _hashSignature = br.ReadBytes(_hashSignature.Length);
                _hashLength    = br.ReadInt64();
                _hashPosition  = BaseStream.Position;

                if (verificationMode != VerificationMode.None)
                {
                    if (_snk != null && !_snk.VerifyHash(_streamHash, _hashSignature))
                    {
                        throw new CryptographicException("Stream hash verification failed");
                    }
                }

                if (verificationMode == VerificationMode.Full)
                {
                    if (!VerifyHash())
                    {
                        throw new CryptographicException("Invalid hash value");
                    }
                }
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TPack"/> class.
        /// </summary>
        /// <param name="baseStream">The base stream.</param>
        /// <param name="verificationMode">The verification mode.</param>
        /// <param name="disposeAtClose">A list of objects to dispose in this order when the stream is closed</param>
        internal TPack(Stream baseStream, VerificationMode verificationMode, IDisposable[] disposeAtClose)
        {
            if (baseStream == null)
            {
                throw new ArgumentNullException("baseStream");
            }

            _assuredStream = new AssuredStream(baseStream, verificationMode);

            _disposeAtClose = new List <IDisposable>();
            _disposeAtClose.Add(_assuredStream);
            _disposeAtClose.Add(baseStream);
            if (disposeAtClose != null)
            {
                _disposeAtClose.AddRange(disposeAtClose);
            }

            MultipleStreamCreateArgs msa = new MultipleStreamCreateArgs();

            msa.VerificationMode = VerificationMode.Full;

            _reader = new MultipleStreamReader(_assuredStream, msa);

            Pack pack;

            using (Stream r = _reader.GetNextStream(PackageDefinitionId))
            {
                XPathDocument  doc = new XPathDocument(r);
                XPathNavigator nav = doc.CreateNavigator();
                nav.MoveToRoot();
                nav.MoveToFirstChild();

                TokenizerArgs ta = new TokenizerArgs();
                ta.SkipUnknownNamedItems = true;

                if (!Tokenizer.TryParseXml(nav, out pack) || pack == null)
                {
                    throw new IOException();
                }
                else
                {
                    _pack = pack;
                }
            }
        }
Exemplo n.º 9
0
        private void UpdateVerificationModeDescription(object sender, EventArgs e)
        {
            VerificationMode verificationMode = ((KeyValuePair <VerificationMode, string>)verifyModeComboBox.SelectedItem).Key;

            switch (verificationMode)
            {
            case VerificationMode.NONE:
                verifyModeDescription.Text = "Gesendete und empfangene Dateien werden nicht überprüft.";
                break;

            case VerificationMode.SIMPLE:
                verifyModeDescription.Text = "Die empfangenen Dateien werden überprüft. Diese Einstellung ist empfohlen.";
                break;

            case VerificationMode.BOTH:
                verifyModeDescription.Text = "Sowohl die gesendeten als auch die empfangenen Dateien werden überprüft.";
                break;
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Opens from.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="verificationMode">The verification mode.</param>
        /// <returns></returns>
        public static TPack OpenFrom(string file, VerificationMode verificationMode)
        {
            if (string.IsNullOrEmpty(file))
            {
                throw new ArgumentNullException("file");
            }

            Uri uri;

            if (Uri.TryCreate(file, UriKind.Absolute, out uri))
            {
                if (!uri.IsFile && !uri.IsUnc)
                {
                    return(OpenFrom(uri, verificationMode));
                }
                else
                {
                    file = uri.LocalPath;
                }
            }
            else
            {
                uri = null;
            }

            if (!File.Exists(file))
            {
                throw new FileNotFoundException("Package not found", file);
            }

            FileStream fs = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read);

            try
            {
                return(Open(fs, verificationMode));
            }
            catch (Exception)
            {
                fs.Close();
                throw;
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Opens a TurtlePackage from the specified uri with the specified credentials
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <param name="verificationMode">The verification mode.</param>
        /// <param name="credentials">The credentials.</param>
        /// <returns></returns>
        public static TPack OpenFrom(Uri uri, VerificationMode verificationMode, ICredentials credentials)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }

            WebRequest request = WebRequest.Create(uri);

            HttpWebRequest httpRequest = request as HttpWebRequest;

            if (httpRequest != null)
            {
                httpRequest.AllowAutoRedirect = true;
                httpRequest.CachePolicy       = new System.Net.Cache.RequestCachePolicy(RequestCacheLevel.Revalidate);
                if (credentials != null)
                {
                    httpRequest.Credentials = credentials;
                }

                httpRequest.Pipelined = true;
                httpRequest.Method    = "GET";
            }
            FtpWebRequest ftpRequest = request as FtpWebRequest;

            if (ftpRequest != null)
            {
                ftpRequest.CachePolicy = new System.Net.Cache.RequestCachePolicy(RequestCacheLevel.Revalidate);
                ftpRequest.EnableSsl   = true;
                if (credentials != null)
                {
                    ftpRequest.Credentials = credentials;
                }
            }

            WebResponse rsp = request.GetResponse();

            try
            {
                Stream sr = rsp.GetResponseStream();
                try
                {
                    if (!sr.CanSeek)
                    {
                        return(new TPack(new SeekableStream(sr, rsp.ContentLength), verificationMode,
                                         new IDisposable[] { sr, rsp }));
                    }
                    else
                    {
                        return(new TPack(sr, verificationMode, new IDisposable[] { rsp }));
                    }
                }
                catch (Exception)
                {
                    sr.Close();
                    throw;
                }
            }
            catch (Exception)
            {
                rsp.Close();
                throw;
            }
        }
Exemplo n.º 12
0
 /// <summary>
 /// Opens a TurtlePackage from the specified uri.
 /// </summary>
 /// <param name="uri">The URI.</param>
 /// <param name="verificationMode">The verification mode.</param>
 /// <returns></returns>
 public static TPack OpenFrom(Uri uri, VerificationMode verificationMode)
 {
     return(OpenFrom(uri, verificationMode, null));
 }
Exemplo n.º 13
0
 public TokenNode(TokenStream tokenStream, string type, VerificationMode verificationMode = VerificationMode.Is) : base(tokenStream)
 {
     this.type = type;
     this.mode = verificationMode;
 }
Exemplo n.º 14
0
 public TokenNode(TokenStream tokenStream, Token token, VerificationMode verificationMode = VerificationMode.Is) : base(tokenStream)
 {
     this.type = token.Type.ToString();
     this.mode = verificationMode;
 }
Exemplo n.º 15
0
        /// <summary>
        /// Opens the specified stream.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <param name="verificationMode">The verification mode.</param>
        /// <returns></returns>
        static TPack Open(Stream stream, VerificationMode verificationMode)
        {
            AssuredStream rootStream = new AssuredStream(stream, verificationMode);

            return(new TPack(rootStream, stream));
        }
Exemplo n.º 16
0
        private void StartTest()
        {
            // NAS directory
            string targetDir = targetDirInput.Path;

            if (!Path.IsPathRooted(targetDir))
            {
                MessageBox.Show(this, "Zielverzeichnis muss absolut sein.", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Test file directory
            string testFileDir = testFileDirInput.Path;

            if (!Path.IsPathRooted(testFileDir))
            {
                MessageBox.Show(this, "Verzeichnis für Testdateien muss absolut sein.", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Log file directory
            string logDir = logDirInput.Path;

            if (!Path.IsPathRooted(logDir))
            {
                MessageBox.Show(this, "Verzeichnis für Logdateien muss absolut sein.", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (Path.GetPathRoot(targetDir) == Path.GetPathRoot(testFileDir))
            {
                DialogResult r;
                r = MessageBox.Show(this, "Quell- und Zielverzeichnis befinden sich möglicherweise auf demselben Laufwerk. Möchten Sie dennoch fortfahren?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (r != DialogResult.Yes)
                {
                    return;
                }
            }

            // Remember the log directory so the log viewer can use it
            AppContext.Instance.CurrentLogFolder = logDir;

            // Whether to allow the system to buffer file contents interally
            bool allowSystemBuffer = false;

            // Whether to delete target files before copying
            bool deleteTargetFiles = true;

            // If set to true, only one test file will be created per group locally.
            // This allows to use tiny RAM drives instead of multiple gigs.
            bool singleFilePerGroup = singleFilePerGroupCheckbox.Checked;

            // Parse file groups
            int           nAllFiles     = 0;
            List <string> fileGroupList = new List <string>();

            for (int i = 0; i < fileGroupGrid.RowCount; i++)
            {
                DataGridViewRow row = fileGroupGrid.Rows[i];
                if (!WinForms.RowIsEmpty(row))
                {
                    string count = (string)row.Cells[0].Value, size = (string)row.Cells[1].Value;
                    fileGroupList.Add(count + "x" + size);
                    nAllFiles += int.Parse(count);
                }
            }

            // Fail if no file groups were specified
            if (fileGroupList.Count == 0)
            {
                MessageBox.Show(this, "Es wurden keine Testdateien festgelegt.", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Convert file groups to an array
            string[] fileGroups = fileGroupList.ToArray();

            // Calculate number of local test files
            int nLocalTestFiles = (singleFilePerGroup ? fileGroups.Length : nAllFiles);

            // See below for all three verification modes.
            VerificationMode verificationMode = ((KeyValuePair <VerificationMode, string>)verifyModeComboBox.SelectedItem).Key;

            // Ask for a base name for the log files
            LogFileNameInputDialog lfnDialog = new LogFileNameInputDialog();

            lfnDialog.LogFileName = DateTime.Now.ToString("yyyyMMddHHmmss");
            if (lfnDialog.ShowDialog(this) != DialogResult.OK)
            {
                return;
            }

            string logFileName = lfnDialog.LogFileName;

            // Determine path
            string assemblyLocation = Assembly.GetExecutingAssembly().Location;
            string assemblyDir      = Path.GetDirectoryName(assemblyLocation);
            string nbPath           = Path.Combine(assemblyDir, "fileperf2.exe");

            while (!File.Exists(nbPath))
            {
                DialogResult r;
                r = MessageBox.Show(this, "Das Programm fileperf2.exe wurde nicht gefunden. Bitte stellen Sie sicher, dass es sich unter " + nbPath + " befindet.", "", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
                if (r != DialogResult.Retry)
                {
                    return;
                }
            }

            // Create folders if necessary
            try
            {
                if (!Directory.Exists(targetDir))
                {
                    logBox.Log("Erstelle Verzeichnis auf NAS: " + targetDir);
                    Directory.CreateDirectory(targetDir);
                }
                if (!Directory.Exists(testFileDir))
                {
                    logBox.Log("Erstelle Verzeichnis für lokale Testdateien: " + testFileDir);
                    Directory.CreateDirectory(testFileDir);
                }
                if (!Directory.Exists(logDir))
                {
                    logBox.Log("Erstelle Verzeichnis für Logdateien: " + logDir);
                    Directory.CreateDirectory(logDir);
                }
            }
            catch (IOException e)
            {
                logBox.Log("Fehler: " + e.Message);
                MessageBox.Show(this, "Mindestens ein Verzeichnis existiert nicht und kann nicht angelegt werden: " + e.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Interface to the native binary. All tests will be performed in a separate process
            // to prevent any performance loss.
            NativeBenchmark benchmark = new NativeBenchmark(nbPath);

            benchmark.ParseLog = true;

            // Disable user inputs (not really necessary as long as the progress dialog is visible)
            setAllInputsEnabled(false);

            BenchmarkProgressDialog progressDialog = new BenchmarkProgressDialog();

            // Perform everything else in a new thread to prevent blocking the UI.
            // Note that we show the progress dialog *after* starting the thread as this
            // thread will actually be blocked until the progress dialog is closed.
            new Thread(() =>
            {
                // Mark this thread as a background thread
                Thread.CurrentThread.Name         = "TestRunner";
                Thread.CurrentThread.IsBackground = true;

                // We are parsing and writing the log at the same time. This
                // object is the current event handler so it can be removed
                // after the process has finished.
                NativeBenchmark.LogEntryEventHandler eventHandler;

                try
                {
                    var logFiles = new List <KeyValuePair <string, string> >();

                    WinForms.InvokeIfRequired(this, () =>
                    {
                        progressDialog.Text = "Überprüfe lokale Testdateien";
                        progressDialog.SubProgressEnabled = false;
                        // TODO: Add real progress calculation
                        progressDialog.MainProgressLabel     = "Überprüfe " + nLocalTestFiles + " Testdateien...";
                        progressDialog.MainProgressBar.Style = ProgressBarStyle.Marquee;
                    });

                    logBox.Log("Verifiziere lokale Testdateien...");

                    bool testFilesOkay = true;
                    eventHandler       = new NativeBenchmark.LogEntryEventHandler((sender, args) =>
                    {
                        switch (args.Entry.Tag)
                        {
                        case LogFile.Tag.VERIFY_INIT_DONE:
                            logBox.Log("fileperf2: Überprüfung lokaler Testdateien begonnen.");
                            break;

                        case LogFile.Tag.VERIFY_FAIL:
                            testFilesOkay = false;
                            break;
                        }
                    });

                    benchmark.LogEntryParsed += eventHandler;
                    benchmark.LogFilePath     = Path.Combine(logDir, logFileName + ".prever.log");
                    logFiles.Add(new KeyValuePair <string, string>("Überprüfung existierender Testdateien", benchmark.LogFilePath));
                    int exitCode              = benchmark.Verify(testFileDir, fileGroups, singleFilePerGroup);
                    benchmark.LogEntryParsed -= eventHandler;

                    if (exitCode != 0 || !testFilesOkay)
                    {
                        logBox.Log("Eine oder mehrere Testdateien fehlen oder wurden verändert. Erzeuge neue Testdateien.");
                        WinForms.InvokeIfRequired(this, () =>
                        {
                            progressDialog.Text = "Erzeuge Testdateien";
                            progressDialog.SubProgressEnabled = false;
                            // TODO: Add real progress calculation
                            progressDialog.MainProgressLabel     = "Erzeuge " + nLocalTestFiles + " Testdateien...";
                            progressDialog.MainProgressBar.Style = ProgressBarStyle.Marquee;
                        });

                        eventHandler = new NativeBenchmark.LogEntryEventHandler((sender, args) =>
                        {
                            switch (args.Entry.Tag)
                            {
                            case LogFile.Tag.GENERATE_INIT_DONE:
                                logBox.Log("fileperf2: Erzeugung der Testdateien begonnen.");
                                break;

                            case LogFile.Tag.GENERATE_FILE_DONE:
                                LogFile.GenerateFileEntry a = (LogFile.GenerateFileEntry)args.Entry;
                                logBox.Log("fileperf2: Testdatei erstellt: " + a.Path);
                                break;
                            }
                        });

                        benchmark.LogEntryParsed += eventHandler;
                        benchmark.LogFilePath     = Path.Combine(logDir, logFileName + ".gen.log");
                        logFiles.Add(new KeyValuePair <string, string>("Erzeugung der Testdateien", benchmark.LogFilePath));
                        exitCode = benchmark.Generate(testFileDir, fileGroups, singleFilePerGroup, true);
                        benchmark.LogEntryParsed -= eventHandler;

                        if (exitCode != 0)
                        {
                            // TODO: Show an error: Retry, cancel
                            logBox.Log("Fehler beim Erzeugen der Testdateien.");
                            return;
                        }
                    }

                    WinForms.InvokeIfRequired(this, () =>
                    {
                        progressDialog.Text = "Schreibe Dateien";
                        progressDialog.SubProgressEnabled = false;
                        // TODO: Add real progress calculation
                        progressDialog.MainProgressLabel     = "Schreibe " + nAllFiles + " Testdateien...";
                        progressDialog.MainProgressBar.Style = ProgressBarStyle.Marquee;
                    });

                    logBox.Log("Schreibe Dateien...");

                    eventHandler = new NativeBenchmark.LogEntryEventHandler((sender, args) =>
                    {
                        LogFile.CopyGroupEntry groupEntry;
                        LogFile.CopyFileEntry fileEntry;
                        switch (args.Entry.Tag)
                        {
                        case LogFile.Tag.COPY_GROUP_START:
                            groupEntry = (LogFile.CopyGroupEntry)args.Entry;
                            logBox.Log("fileperf2: Gruppe " + (groupEntry.GroupIndex + 1) + " von " + fileGroups.Count() + " begonnen.");
                            break;

                        case LogFile.Tag.COPY_GROUP_END:
                            groupEntry = (LogFile.CopyGroupEntry)args.Entry;
                            logBox.Log("fileperf2: Gruppe " + (groupEntry.GroupIndex + 1) + " von " + fileGroups.Count() + " fertig.");
                            break;

                        case LogFile.Tag.COPY_FILE_START:
                            fileEntry = (LogFile.CopyFileEntry)args.Entry;
                            logBox.Log("fileperf2: Schreiben von Datei " + (fileEntry.FileIndex + 1) + " begonnen: " + fileEntry.TargetPath);
                            break;

                        case LogFile.Tag.COPY_FILE_END:
                            fileEntry = (LogFile.CopyFileEntry)args.Entry;
                            logBox.Log("fileperf2: Schreiben von Datei " + (fileEntry.FileIndex + 1) + " fertig: " + fileEntry.TargetPath);
                            break;
                        }
                    });

                    benchmark.LogEntryParsed += eventHandler;
                    benchmark.LogFilePath     = Path.Combine(logDir, logFileName + ".write.log");
                    logFiles.Add(new KeyValuePair <string, string>("Schreiben (auf NAS)", benchmark.LogFilePath));
                    exitCode = benchmark.Copy(testFileDir, targetDir, fileGroups, singleFilePerGroup, false, deleteTargetFiles, allowSystemBuffer);
                    benchmark.LogEntryParsed -= eventHandler;

                    if (exitCode != 0)
                    {
                        // TODO: Show an error: Retry, ignore, cancel
                        logBox.Log("Fehler beim Schreiben.");
                        return;
                    }

                    WinForms.InvokeIfRequired(this, () =>
                    {
                        progressDialog.Text = "Lese Dateien";
                        progressDialog.SubProgressEnabled = false;
                        // TODO: Add real progress calculation
                        progressDialog.MainProgressLabel     = "Lese " + nAllFiles + " Testdateien...";
                        progressDialog.MainProgressBar.Style = ProgressBarStyle.Marquee;
                    });

                    logBox.Log("Lese Dateien...");

                    eventHandler = new NativeBenchmark.LogEntryEventHandler((sender, args) =>
                    {
                        LogFile.CopyGroupEntry groupEntry;
                        LogFile.CopyFileEntry fileEntry;
                        switch (args.Entry.Tag)
                        {
                        case LogFile.Tag.COPY_GROUP_START:
                            groupEntry = (LogFile.CopyGroupEntry)args.Entry;
                            logBox.Log("fileperf2: Gruppe " + (groupEntry.GroupIndex + 1) + " von " + fileGroups.Count() + " begonnen.");
                            break;

                        case LogFile.Tag.COPY_GROUP_END:
                            groupEntry = (LogFile.CopyGroupEntry)args.Entry;
                            logBox.Log("fileperf2: Gruppe " + (groupEntry.GroupIndex + 1) + " von " + fileGroups.Count() + " fertig.");
                            break;

                        case LogFile.Tag.COPY_FILE_START:
                            fileEntry = (LogFile.CopyFileEntry)args.Entry;
                            logBox.Log("fileperf2: Lesen von Datei " + (fileEntry.FileIndex + 1) + " begonnen: " + fileEntry.SourcePath);
                            break;

                        case LogFile.Tag.COPY_FILE_END:
                            fileEntry = (LogFile.CopyFileEntry)args.Entry;
                            logBox.Log("fileperf2: Lesen von Datei " + (fileEntry.FileIndex + 1) + " fertig: " + fileEntry.SourcePath);
                            break;
                        }
                    });

                    benchmark.LogEntryParsed += eventHandler;
                    benchmark.LogFilePath     = Path.Combine(logDir, logFileName + ".read.log");
                    logFiles.Add(new KeyValuePair <string, string>("Lesen (von NAS)", benchmark.LogFilePath));
                    exitCode = benchmark.Copy(targetDir, testFileDir, fileGroups, false, singleFilePerGroup, deleteTargetFiles, allowSystemBuffer);
                    benchmark.LogEntryParsed -= eventHandler;

                    if (exitCode != 0)
                    {
                        // TODO: Handle errors better
                        logBox.Log("Fehler beim Lesen");
                        // TODO: Show an error: Retry, ignore, cancel
                        return;
                    }

                    if (verificationMode == VerificationMode.BOTH)
                    {
                        WinForms.InvokeIfRequired(this, () =>
                        {
                            progressDialog.Text = "Überprüfe Dateien auf NAS";
                            progressDialog.SubProgressEnabled = false;
                            // TODO: Add real progress calculation
                            progressDialog.MainProgressLabel     = "Überprüfe " + nAllFiles + " Dateien...";
                            progressDialog.MainProgressBar.Style = ProgressBarStyle.Marquee;
                        });

                        logBox.Log("Überprüfe Dateien auf NAS...");

                        eventHandler = new NativeBenchmark.LogEntryEventHandler((sender, args) =>
                        {
                            switch (args.Entry.Tag)
                            {
                            case LogFile.Tag.VERIFY_INIT_DONE:
                                logBox.Log("fileperf2: Überprüfung gesendeter Testdateien begonnen.");
                                break;

                            case LogFile.Tag.VERIFY_OKAY:
                                logBox.Log("fileperf2: Überprüfung erfolgreich: " + ((LogFile.VerifyFileEntry)args.Entry).Path);
                                break;

                            case LogFile.Tag.VERIFY_FAIL:
                                testFilesOkay = false;
                                LogFile.VerifyFailEntry failure = (LogFile.VerifyFailEntry)args.Entry;
                                logBox.Log("fileperf2: Überprüfung fehlgeschlagen: " + failure.Path + ": " + failure.FailMessage);
                                break;
                            }
                        });

                        benchmark.LogEntryParsed += eventHandler;
                        benchmark.LogFilePath     = Path.Combine(logDir, logFileName + ".vwrite.log");
                        logFiles.Add(new KeyValuePair <string, string>("Überprüfung gesendeter Dateien", benchmark.LogFilePath));
                        exitCode = benchmark.Verify(targetDir, fileGroups, false);
                        benchmark.LogEntryParsed -= eventHandler;

                        if (exitCode != 0)
                        {
                            // TODO: Show an error: Retry, ignore, cancel
                            logBox.Log("Fehler beim Verifizieren");
                        }
                    }

                    if (verificationMode == VerificationMode.BOTH || verificationMode == VerificationMode.SIMPLE)
                    {
                        WinForms.InvokeIfRequired(this, () =>
                        {
                            progressDialog.Text = "Überprüfe lokale Dateien";
                            progressDialog.SubProgressEnabled = false;
                            // TODO: Add real progress calculation
                            progressDialog.MainProgressLabel     = "Überprüfe " + nAllFiles + " Dateien...";
                            progressDialog.MainProgressBar.Style = ProgressBarStyle.Marquee;
                        });

                        logBox.Log("Überprüfe lokale Dateien...");

                        eventHandler = new NativeBenchmark.LogEntryEventHandler((sender, args) =>
                        {
                            switch (args.Entry.Tag)
                            {
                            case LogFile.Tag.VERIFY_INIT_DONE:
                                logBox.Log("fileperf2: Überprüfung empfangener Testdateien begonnen.");
                                break;

                            case LogFile.Tag.VERIFY_OKAY:
                                logBox.Log("fileperf2: Überprüfung erfolgreich: " + ((LogFile.VerifyFileEntry)args.Entry).Path);
                                break;

                            case LogFile.Tag.VERIFY_FAIL:
                                testFilesOkay = false;
                                LogFile.VerifyFailEntry failure = (LogFile.VerifyFailEntry)args.Entry;
                                logBox.Log("fileperf2: Überprüfung fehlgeschlagen: " + failure.Path + ": " + failure.FailMessage);
                                break;
                            }
                        });

                        benchmark.LogEntryParsed += eventHandler;
                        benchmark.LogFilePath     = Path.Combine(logDir, logFileName + ".vread.log");
                        logFiles.Add(new KeyValuePair <string, string>("Überprüfung empfangener Dateien", benchmark.LogFilePath));
                        exitCode = benchmark.Verify(testFileDir, fileGroups, singleFilePerGroup);
                        benchmark.LogEntryParsed -= eventHandler;

                        if (exitCode != 0)
                        {
                            // TODO: Show an error: Retry, ignore, cancel
                            logBox.Log("Fehler beim Verifizieren");
                        }
                    }

                    WinForms.InvokeIfRequired(this, () =>
                    {
                        progressDialog.AllowClosing = true;
                        progressDialog.FormClosed  += new FormClosedEventHandler((sender, e) =>
                        {
                            BeginInvoke((ThreadStart) delegate()
                            {
                                new BenchmarkDoneDialog(logFiles).ShowDialog(this);
                            });
                        });
                        progressDialog.Close();
                    });
                }
                catch (Exception e)
                {
                    logBox.Log("Interner Fehler: " + e.Message);
                    logBox.Log(e.StackTrace);

                    WinForms.InvokeIfRequired(this, () =>
                    {
                        MessageBox.Show(this, "Ein interner Fehler ist während des Testvorgangs aufgetreten: " + e.Message + "\n" + e.StackTrace, "Fehler", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    });
                }
                finally
                {
                    WinForms.InvokeIfRequired(this, () =>
                    {
                        setAllInputsEnabled(true);
                        if (progressDialog.Visible)
                        {
                            progressDialog.AllowClosing = true;
                            progressDialog.Close();
                        }
                    });
                }
            }).Start();

            progressDialog.AllowClosing = false;
            progressDialog.ShowDialog(this);
        }
Exemplo n.º 17
0
 private void VerifyTrayAsync(Tray<Tablet> tray, VerificationMode mode)
 {
     Task.Run(() =>
         {
             Logger.Instance.Write(String.Format("[TrayVerifier] Detecting tray. Verification mode: {0}", mode));
             Tray<Tablet> detectedTray;
             bool isTrayVisible = _trayDetector.GetTabletsInTray(out detectedTray);
             VerificationResult verResult = VerificationResult.Invalid;
             if (isTrayVisible)
             {
                 if (mode == VerificationMode.Tray)
                 {
                     tray = new Tray<Tablet>();
                 }
                 verResult = DetermineValidity(tray, detectedTray);
             }
             Logger.Instance.Write(String.Format("[TrayVerifier] Is tray visible? {0}, tray validity: {1}",
                                     isTrayVisible, verResult));
             IsRunning = false;
             OnCompleted(new OnVerificationCompleteEventArgs
                 {
                     DetectedTray = detectedTray,
                     VerificationResult = verResult,
                     VerificationMode = mode,
                     OperationStatus = ControllerOperationStatus.Succeeded
                 });
         });
 }