Exemplo n.º 1
0
        public string WriteIndented(Dump dump, int level = 0)
        {
            IDictionary<object, object> printedDump;

            if (dump.Count == 1 && dump.ContainsKey(Dump.Items)) {
                // special handling for enumerables
                List<object> list = dump[Dump.Items] as List<object>;
                printedDump = list.Select((x, i) => new { Item = x, Index = (object)i })
                    .ToDictionary(x => x.Index, x => x.Item);
            } else if (dump.Count == 1 && dump.ContainsKey(Dump.Entries)) {
                // special handling for lexicons
                List<object> list = dump[Dump.Entries] as List<object>;

                printedDump = new Dictionary<object, object>();

                for (int i = 0; 2 * i < list.Count; i++)
                {
                    printedDump[list[2 * i]] = list[2 * i + 1];
                }
            } else {
                printedDump = dump;
            }

            return WriteIndentedDump(printedDump, level);
        }
Exemplo n.º 2
0
        public override SerializableStructure CreateInstance(string typeFullName, Dump data)
        {
            var deserializedType = Type.GetType(typeFullName) ??
                                   Type.GetType(typeFullName + ", " + typeof(SafeSerializationMgr).Assembly.FullName);

            if (deserializedType == null)
            {
                throw new KOSSerializationException("Unrecognized type: " + typeFullName);
            }

            SerializableStructure instance = Activator.CreateInstance(deserializedType) as SerializableStructure;

            if (instance is IHasSharedObjects)
            {
                IHasSharedObjects withSharedObjects = instance as IHasSharedObjects;
                withSharedObjects.Shared = sharedObjects;
            }

            if (instance != null)
            {
                instance.LoadDump(data);
            }

            return instance;
        }
Exemplo n.º 3
0
 public EventTimelineModel(Dump dump)
 {
     foreach (KeyValuePair<uint, Event> pair in dump.Events)
     {
         m_nodes.Add(new EventNode(pair.Value));
     }
 }
Exemplo n.º 4
0
        public virtual IDumper CreateAndLoad(string typeFullName, Dump data)
        {
            IDumper instance = CreateInstance(typeFullName);

            instance.LoadDump(data);

            return instance;
        }
Exemplo n.º 5
0
 public CreatureInfo(Dump.SQL.Custom.creature_template creature_template)
 {
     Entry = creature_template.entry.GetValueOrDefault();
     Name = creature_template.name;
     SubName = creature_template.subname;
     IconName = creature_template.iconname;
     TypeFlags = (CreatureTypeFlags)creature_template.flags_extra.GetValueOrDefault();
     Type = (CreatureType)creature_template.type.GetValueOrDefault();
     Family = (CreatureFamily)creature_template.family.GetValueOrDefault();
     Rank = (CreatureRank)creature_template.rank.GetValueOrDefault();
 }
Exemplo n.º 6
0
        public string Write(Dump value)
        {
            string header = "";

            var withHeader = value as DumpWithHeader;
            if (withHeader != null)
            {
                header = withHeader.Header + Environment.NewLine;
            }

            return header + WriteIndented(value);
        }
Exemplo n.º 7
0
        public virtual SerializableStructure CreateInstance(string typeFullName, Dump data)
        {
            var deserializedType = Type.GetType(typeFullName);

            if (deserializedType == null)
            {
                throw new KOSSerializationException("Unrecognized type: " + typeFullName);
            }

            SerializableStructure instance = Activator.CreateInstance(deserializedType) as SerializableStructure;

            instance.LoadDump(data);

            return instance;
        }
Exemplo n.º 8
0
        public Dump FromConfigNode(ConfigNode configNode)
        {
            Dump result = new Dump();

            foreach (ConfigNode.Value val in configNode.values)
            {
                result[val.name] = PersistenceUtilities.DecodeLine(val.value);
            }

            foreach (ConfigNode subNode in configNode.GetNodes())
            {
                result[subNode.name] = ObjectFromConfigNode(subNode);
            }

            return result;
        }
Exemplo n.º 9
0
        public void SaveSearchBackground(int index, List<UInt32> resultsList, Dump searchDump)
        {
            SearchItem foo = new SearchItem();
            // make a copy in case the user starts deleting, sorting, etc the original list
            foo.resultsList = new List<uint>(resultsList);
            foo.searchDump = searchDump;
            foo.index = index;

            // block in the event of a rapid-fire double call
            while (backgroundWriting) ;

            Thread zipThread = new Thread(new ParameterizedThreadStart(SaveSearchBackground));

            // Set the state before calling the thread
            backgroundWriting = true;

            zipThread.Start(foo);
        }
Exemplo n.º 10
0
        public override IDumper CreateAndLoad(string typeFullName, Dump data)
        {
            IDumper instance = base.CreateInstance(typeFullName);

            if (instance is IHasSharedObjects)
            {
                IHasSharedObjects withSharedObjects = instance as IHasSharedObjects;
                withSharedObjects.Shared = sharedObjects;
            }
            else if (instance is IHasSafeSharedObjects)
            {
                IHasSafeSharedObjects withSharedObjects = instance as IHasSafeSharedObjects;
                withSharedObjects.Shared = sharedObjects;
            }

            if (instance != null)
            {
                instance.LoadDump(data);
            }

            return instance;
        }
Exemplo n.º 11
0
        public SerializableStructure CreateFromDump(Dump dump)
        {
            var data = new Dump();
            foreach (KeyValuePair<object, object> entry in dump)
            {
                if (entry.Key.Equals(TYPE_KEY))
                {
                    continue;
                }

                data [entry.Key] = CreateValue (entry.Value);
            }

            string typeFullName = dump[TYPE_KEY] as string;

            if (String.IsNullOrEmpty(typeFullName))
            {
                throw new KOSSerializationException("Type information missing");
            }

            return CreateInstance(typeFullName, data);
        }
Exemplo n.º 12
0
        public IDumper CreateFromDump(Dump dump)
        {
            var data = new Dump();

            foreach (KeyValuePair<object, object> entry in dump)
            {
                if (entry.Key.Equals(TYPE_KEY))
                {
                    continue;
                }

                data[entry.Key] = CreateValue(entry.Value);
            }

            if (!dump.ContainsKey(TYPE_KEY))
            {
                throw new KOSSerializationException("Type information missing");
            }

            string typeFullName = dump[TYPE_KEY] as string;

            return CreateAndLoad(typeFullName, data);
        }
Exemplo n.º 13
0
 public void LoadIndexIntoNewSearchDump(int index)
 {
     newDump = searchHistory.LoadSearchDump(index);
 }
Exemplo n.º 14
0
 public SearchHistoryItem()
 {
     resultsList = null;
     searchDump = null;
     backgroundWriting = false;
 }
Exemplo n.º 15
0
        private static async Task Login()
        {
            try
            {
                if (_isLoggedIn)
                {
                    return;
                }
                if (string.IsNullOrWhiteSpace(_sid))
                {
                    // buka homepage
                    var homepage = await WebClient.GetOrPostStringAsync(new WebRequest { Url = BaseAddress });

                    Dump.ToFile("Mobilism.html", homepage);

                    GetSidFromCookies();

                    // verifikasi login
                    if (!homepage.Contains(LoginPath))
                    {
                        _log.Ignore("Status: sudah login...");
                        _isLoggedIn = true;
                        return;
                    }
                }

                var auth     = ReadAccount();
                var redirect = WebUtility.UrlEncode(LoginPath);
                var content  = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair <string, string>("username", auth.Username),
                    new KeyValuePair <string, string>("password", auth.Password),
                    new KeyValuePair <string, string>("login", "Login"),
                    new KeyValuePair <string, string>("autologin", "on"),
                    new KeyValuePair <string, string>("viewonline", "on"),
                    new KeyValuePair <string, string>("redirect", redirect),
                    new KeyValuePair <string, string>("sid", _sid),
                    new KeyValuePair <string, string>("redirect", "index.php")
                });
                var headers = new List <WebHeader>
                {
                    new WebHeader {
                        Key = "Referer", Value = $"{LoginAddress}&sid={_sid}"
                    }
                };

                var loginRequest = new WebRequest
                {
                    Url     = LoginAddress,
                    Headers = headers,
                    Method  = WebMethod.Post,
                    Content = content
                };

                var loginpage = await WebClient.GetOrPostStringAsync(loginRequest);

                Dump.ToFile("Mobilism-Login.html", loginpage);

                GetSidFromCookies();

                // cek html atau kode alien?
                if (!loginpage.Contains("html"))
                {
                    throw new Exception("Result bukan html!");
                }

                // verifikasi login
                if (!loginpage.Contains(LoginPath))
                {
                    _log.Info("Status: berhasil login...");
                    _isLoggedIn = true;
                }
            }
            catch (Exception e)
            {
                _log.Error(e.Message);
            }
        }
Exemplo n.º 16
0
Arquivo: Dump.cs Projeto: paulyc/Aaru
        public static int Invoke(bool debug, bool verbose, string cicmXml, string devicePath, bool resume,
                                 string encoding, bool firstPregap, bool fixOffset, bool force, bool metadata,
                                 bool trim, string outputPath, string options, bool persistent, ushort retryPasses,
                                 uint skip, byte speed, bool stopOnError, string format, string subchannel,
                                 bool @private, bool fixSubchannelPosition, bool retrySubchannel, bool fixSubchannel,
                                 bool fixSubchannelCrc, bool generateSubchannels, bool skipCdiReadyHole, bool eject,
                                 uint maxBlocks, bool useBufferedReads, bool storeEncrypted,
                                 bool titleKeys)
        {
            MainClass.PrintCopyright();

            if (debug)
            {
                AaruConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
            }

            if (verbose)
            {
                AaruConsole.VerboseWriteLineEvent += System.Console.WriteLine;
            }

            if (fixSubchannelCrc)
            {
                fixSubchannel = true;
            }

            if (retrySubchannel || fixSubchannel)
            {
                fixSubchannelPosition = true;
            }

            if (maxBlocks == 0)
            {
                maxBlocks = 64;
            }

            Statistics.AddCommand("dump-media");

            AaruConsole.DebugWriteLine("Dump-Media command", "--cicm-xml={0}", cicmXml);
            AaruConsole.DebugWriteLine("Dump-Media command", "--debug={0}", debug);
            AaruConsole.DebugWriteLine("Dump-Media command", "--device={0}", devicePath);
            AaruConsole.DebugWriteLine("Dump-Media command", "--encoding={0}", encoding);
            AaruConsole.DebugWriteLine("Dump-Media command", "--first-pregap={0}", firstPregap);
            AaruConsole.DebugWriteLine("Dump-Media command", "--fix-offset={0}", fixOffset);
            AaruConsole.DebugWriteLine("Dump-Media command", "--force={0}", force);
            AaruConsole.DebugWriteLine("Dump-Media command", "--format={0}", format);
            AaruConsole.DebugWriteLine("Dump-Media command", "--metadata={0}", metadata);
            AaruConsole.DebugWriteLine("Dump-Media command", "--options={0}", options);
            AaruConsole.DebugWriteLine("Dump-Media command", "--output={0}", outputPath);
            AaruConsole.DebugWriteLine("Dump-Media command", "--persistent={0}", persistent);
            AaruConsole.DebugWriteLine("Dump-Media command", "--resume={0}", resume);
            AaruConsole.DebugWriteLine("Dump-Media command", "--retry-passes={0}", retryPasses);
            AaruConsole.DebugWriteLine("Dump-Media command", "--skip={0}", skip);
            AaruConsole.DebugWriteLine("Dump-Media command", "--stop-on-error={0}", stopOnError);
            AaruConsole.DebugWriteLine("Dump-Media command", "--trim={0}", trim);
            AaruConsole.DebugWriteLine("Dump-Media command", "--verbose={0}", verbose);
            AaruConsole.DebugWriteLine("Dump-Media command", "--subchannel={0}", subchannel);
            AaruConsole.DebugWriteLine("Dump-Media command", "--private={0}", @private);
            AaruConsole.DebugWriteLine("Dump-Media command", "--fix-subchannel-position={0}", fixSubchannelPosition);
            AaruConsole.DebugWriteLine("Dump-Media command", "--retry-subchannel={0}", retrySubchannel);
            AaruConsole.DebugWriteLine("Dump-Media command", "--fix-subchannel={0}", fixSubchannel);
            AaruConsole.DebugWriteLine("Dump-Media command", "--fix-subchannel-crc={0}", fixSubchannelCrc);
            AaruConsole.DebugWriteLine("Dump-Media command", "--generate-subchannels={0}", generateSubchannels);
            AaruConsole.DebugWriteLine("Dump-Media command", "--skip-cdiready-hole={0}", skipCdiReadyHole);
            AaruConsole.DebugWriteLine("Dump-Media command", "--eject={0}", eject);
            AaruConsole.DebugWriteLine("Dump-Media command", "--max-blocks={0}", maxBlocks);
            AaruConsole.DebugWriteLine("Dump-Media command", "--use-buffered-reads={0}", useBufferedReads);
            AaruConsole.DebugWriteLine("Dump-Media command", "--store-encrypted={0}", storeEncrypted);
            AaruConsole.DebugWriteLine("Dump-Media command", "--title-keys={0}", titleKeys);

            // TODO: Disabled temporarily
            //AaruConsole.DebugWriteLine("Dump-Media command", "--raw={0}",           raw);

            Dictionary <string, string> parsedOptions = Core.Options.Parse(options);

            AaruConsole.DebugWriteLine("Dump-Media command", "Parsed options:");

            foreach (KeyValuePair <string, string> parsedOption in parsedOptions)
            {
                AaruConsole.DebugWriteLine("Dump-Media command", "{0} = {1}", parsedOption.Key, parsedOption.Value);
            }

            Encoding encodingClass = null;

            if (encoding != null)
            {
                try
                {
                    encodingClass = Claunia.Encoding.Encoding.GetEncoding(encoding);

                    if (verbose)
                    {
                        AaruConsole.VerboseWriteLine("Using encoding for {0}.", encodingClass.EncodingName);
                    }
                }
                catch (ArgumentException)
                {
                    AaruConsole.ErrorWriteLine("Specified encoding is not supported.");

                    return((int)ErrorNumber.EncodingUnknown);
                }
            }

            DumpSubchannel wantedSubchannel = DumpSubchannel.Any;

            switch (subchannel?.ToLowerInvariant())
            {
            case "any":
            case null:
                wantedSubchannel = DumpSubchannel.Any;

                break;

            case "rw":
                wantedSubchannel = DumpSubchannel.Rw;

                break;

            case "rw-or-pq":
                wantedSubchannel = DumpSubchannel.RwOrPq;

                break;

            case "pq":
                wantedSubchannel = DumpSubchannel.Pq;

                break;

            case "none":
                wantedSubchannel = DumpSubchannel.None;

                break;

            default:
                AaruConsole.WriteLine("Incorrect subchannel type \"{0}\" requested.", subchannel);

                break;
            }

            string filename = Path.GetFileNameWithoutExtension(outputPath);

            bool isResponse = filename.StartsWith("#", StringComparison.OrdinalIgnoreCase) &&
                              File.Exists(Path.Combine(Path.GetDirectoryName(outputPath),
                                                       Path.GetFileNameWithoutExtension(outputPath)));

            TextReader resReader;

            if (isResponse)
            {
                resReader = new StreamReader(Path.Combine(Path.GetDirectoryName(outputPath),
                                                          Path.GetFileNameWithoutExtension(outputPath)));
            }
            else
            {
                resReader = new StringReader(Path.GetFileNameWithoutExtension(outputPath));
            }

            if (isResponse)
            {
                eject = true;
            }

            PluginBase            plugins    = GetPluginBase.Instance;
            List <IWritableImage> candidates = new List <IWritableImage>();
            string extension = Path.GetExtension(outputPath);

            // Try extension
            if (string.IsNullOrEmpty(format))
            {
                candidates.AddRange(plugins.WritableImages.Values.Where(t => t.KnownExtensions.Contains(extension)));
            }

            // Try Id
            else if (Guid.TryParse(format, out Guid outId))
            {
                candidates.AddRange(plugins.WritableImages.Values.Where(t => t.Id.Equals(outId)));
            }

            // Try name
            else
            {
                candidates.AddRange(plugins.WritableImages.Values.Where(t => string.Equals(t.Name, format,
                                                                                           StringComparison.
                                                                                           InvariantCultureIgnoreCase)));
            }

            if (candidates.Count == 0)
            {
                AaruConsole.WriteLine("No plugin supports requested extension.");

                return((int)ErrorNumber.FormatNotFound);
            }

            if (candidates.Count > 1)
            {
                AaruConsole.WriteLine("More than one plugin supports requested extension.");

                return((int)ErrorNumber.TooManyFormats);
            }

            while (true)
            {
                string responseLine = resReader.ReadLine();

                if (responseLine is null)
                {
                    break;
                }

                if (responseLine.Any(c => c < 0x20))
                {
                    AaruConsole.ErrorWriteLine("Invalid characters found in list of files, exiting...");

                    return((int)ErrorNumber.InvalidArgument);
                }

                if (isResponse)
                {
                    AaruConsole.WriteLine("Please insert media with title {0} and press any key to continue...",
                                          responseLine);

                    System.Console.ReadKey();
                    Thread.Sleep(1000);
                }

                responseLine = responseLine.Replace('/', '/');

                // Replace Windows forbidden filename characters with Japanese equivalents that are visually the same, but bigger.
                if (DetectOS.IsWindows)
                {
                    responseLine = responseLine.Replace('<', '\uFF1C').Replace('>', '\uFF1E').Replace(':', '\uFF1A').
                                   Replace('"', '\u2033').Replace('\\', '\').Replace('|', '|').
                                   Replace('?', '?').Replace('*', '*');
                }

                if (devicePath.Length == 2 &&
                    devicePath[1] == ':' &&
                    devicePath[0] != '/' &&
                    char.IsLetter(devicePath[0]))
                {
                    devicePath = "\\\\.\\" + char.ToUpper(devicePath[0]) + ':';
                }

                Devices.Device dev;

                try
                {
                    dev = new Devices.Device(devicePath);

                    if (dev.IsRemote)
                    {
                        Statistics.AddRemote(dev.RemoteApplication, dev.RemoteVersion, dev.RemoteOperatingSystem,
                                             dev.RemoteOperatingSystemVersion, dev.RemoteArchitecture);
                    }

                    if (dev.Error)
                    {
                        AaruConsole.ErrorWriteLine(Error.Print(dev.LastError));

                        if (isResponse)
                        {
                            continue;
                        }

                        return((int)ErrorNumber.CannotOpenDevice);
                    }
                }
                catch (DeviceException e)
                {
                    AaruConsole.ErrorWriteLine(e.Message ?? Error.Print(e.LastError));

                    if (isResponse)
                    {
                        continue;
                    }

                    return((int)ErrorNumber.CannotOpenDevice);
                }

                Statistics.AddDevice(dev);

                string outputPrefix = Path.Combine(Path.GetDirectoryName(outputPath), responseLine);

                Resume resumeClass = null;
                var    xs          = new XmlSerializer(typeof(Resume));

                if (File.Exists(outputPrefix + ".resume.xml") && resume)
                {
                    try
                    {
                        var sr = new StreamReader(outputPrefix + ".resume.xml");
                        resumeClass = (Resume)xs.Deserialize(sr);
                        sr.Close();
                    }
                    catch
                    {
                        AaruConsole.ErrorWriteLine("Incorrect resume file, not continuing...");

                        if (isResponse)
                        {
                            continue;
                        }

                        return((int)ErrorNumber.InvalidResume);
                    }
                }

                if (resumeClass != null &&
                    resumeClass.NextBlock > resumeClass.LastBlock &&
                    resumeClass.BadBlocks.Count == 0 &&
                    !resumeClass.Tape &&
                    (resumeClass.BadSubchannels is null || resumeClass.BadSubchannels.Count == 0) &&
                    (resumeClass.MissingTitleKeys is null || resumeClass.MissingTitleKeys.Count == 0))
                {
                    AaruConsole.WriteLine("Media already dumped correctly, not continuing...");

                    if (isResponse)
                    {
                        continue;
                    }

                    return((int)ErrorNumber.AlreadyDumped);
                }

                CICMMetadataType sidecar = null;
                var sidecarXs            = new XmlSerializer(typeof(CICMMetadataType));

                if (cicmXml != null)
                {
                    if (File.Exists(cicmXml))
                    {
                        try
                        {
                            var sr = new StreamReader(cicmXml);
                            sidecar = (CICMMetadataType)sidecarXs.Deserialize(sr);
                            sr.Close();
                        }
                        catch
                        {
                            AaruConsole.ErrorWriteLine("Incorrect metadata sidecar file, not continuing...");

                            if (isResponse)
                            {
                                continue;
                            }

                            return((int)ErrorNumber.InvalidSidecar);
                        }
                    }
                    else
                    {
                        AaruConsole.ErrorWriteLine("Could not find metadata sidecar, not continuing...");

                        if (isResponse)
                        {
                            continue;
                        }

                        return((int)ErrorNumber.FileNotFound);
                    }
                }

                plugins    = GetPluginBase.Instance;
                candidates = new List <IWritableImage>();

                // Try extension
                if (string.IsNullOrEmpty(format))
                {
                    candidates.AddRange(plugins.WritableImages.Values.Where(t =>
                                                                            t.KnownExtensions.
                                                                            Contains(Path.
                                                                                     GetExtension(outputPath))));
                }

                // Try Id
                else if (Guid.TryParse(format, out Guid outId))
                {
                    candidates.AddRange(plugins.WritableImages.Values.Where(t => t.Id.Equals(outId)));
                }

                // Try name
                else
                {
                    candidates.AddRange(plugins.WritableImages.Values.Where(t => string.Equals(t.Name, format,
                                                                                               StringComparison.
                                                                                               InvariantCultureIgnoreCase)));
                }

                IWritableImage outputFormat = candidates[0];

                var dumpLog = new DumpLog(outputPrefix + ".log", dev, @private);

                if (verbose)
                {
                    dumpLog.WriteLine("Output image format: {0} ({1}).", outputFormat.Name, outputFormat.Id);
                    AaruConsole.VerboseWriteLine("Output image format: {0} ({1}).", outputFormat.Name, outputFormat.Id);
                }
                else
                {
                    dumpLog.WriteLine("Output image format: {0}.", outputFormat.Name);
                    AaruConsole.WriteLine("Output image format: {0}.", outputFormat.Name);
                }

                var errorLog = new ErrorLog(outputPrefix + ".error.log");

                var dumper = new Dump(resume, dev, devicePath, outputFormat, retryPasses, force, false, persistent,
                                      stopOnError, resumeClass, dumpLog, encodingClass, outputPrefix,
                                      outputPrefix + extension, parsedOptions, sidecar, skip, metadata, trim,
                                      firstPregap, fixOffset, debug, wantedSubchannel, speed, @private,
                                      fixSubchannelPosition, retrySubchannel, fixSubchannel, fixSubchannelCrc,
                                      skipCdiReadyHole, errorLog, generateSubchannels, maxBlocks, useBufferedReads,
                                      storeEncrypted, titleKeys);

                dumper.UpdateStatus         += Progress.UpdateStatus;
                dumper.ErrorMessage         += Progress.ErrorMessage;
                dumper.StoppingErrorMessage += Progress.ErrorMessage;
                dumper.UpdateProgress       += Progress.UpdateProgress;
                dumper.PulseProgress        += Progress.PulseProgress;
                dumper.InitProgress         += Progress.InitProgress;
                dumper.EndProgress          += Progress.EndProgress;
                dumper.InitProgress2        += Progress.InitProgress2;
                dumper.EndProgress2         += Progress.EndProgress2;
                dumper.UpdateProgress2      += Progress.UpdateProgress2;

                System.Console.CancelKeyPress += (sender, e) =>
                {
                    e.Cancel = true;
                    dumper.Abort();
                };

                dumper.Start();

                if (eject && dev.IsRemovable)
                {
                    switch (dev.Type)
                    {
                    case DeviceType.ATA:
                        dev.DoorUnlock(out _, dev.Timeout, out _);
                        dev.MediaEject(out _, dev.Timeout, out _);

                        break;

                    case DeviceType.ATAPI:
                    case DeviceType.SCSI:
                        switch (dev.ScsiType)
                        {
                        case PeripheralDeviceTypes.DirectAccess:
                        case PeripheralDeviceTypes.SimplifiedDevice:
                        case PeripheralDeviceTypes.SCSIZonedBlockDevice:
                        case PeripheralDeviceTypes.WriteOnceDevice:
                        case PeripheralDeviceTypes.OpticalDevice:
                        case PeripheralDeviceTypes.OCRWDevice:
                            dev.SpcAllowMediumRemoval(out _, dev.Timeout, out _);
                            dev.EjectTray(out _, dev.Timeout, out _);

                            break;

                        case PeripheralDeviceTypes.MultiMediaDevice:
                            dev.AllowMediumRemoval(out _, dev.Timeout, out _);
                            dev.EjectTray(out _, dev.Timeout, out _);

                            break;

                        case PeripheralDeviceTypes.SequentialAccess:
                            dev.SpcAllowMediumRemoval(out _, dev.Timeout, out _);
                            dev.LoadUnload(out _, true, false, false, false, false, dev.Timeout, out _);

                            break;
                        }

                        break;
                    }
                }

                dev.Close();
            }

            return((int)ErrorNumber.NoError);
        }
Exemplo n.º 17
0
        public void SaveSearch(string filepath, List<UInt32> resultsList, Dump searchDump)
        {
            ZipOutputStream outstream = new ZipOutputStream(filepath);
            outstream.CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed;
            BinaryFormatter formatter = new BinaryFormatter();

            // First entry is the dump
            outstream.PutNextEntry("dump");

            //DateTime start = Logger.WriteLineTimedStarted("compressing search dump");

            // Must put the addresses first, so that it can derive the right number of bytes to read for the dump
            formatter.Serialize(outstream, searchDump.StartAddress);
            formatter.Serialize(outstream, searchDump.EndAddress);
            outstream.Write(searchDump.mem, 0, (int)(searchDump.EndAddress - searchDump.StartAddress));

            //Logger.WriteLineTimedFinished("compressing search dump", start);

            // Second entry is the list
            outstream.PutNextEntry("list");

            //start = Logger.WriteLineTimedStarted("compressing search list");

            formatter.Serialize(outstream, resultsList);

            //Logger.WriteLineTimedFinished("compressing search list", start);

            outstream.Close();
            outstream.Dispose();
        }
Exemplo n.º 18
0
 public override void LoadDump(Dump dump)
 {
     Message = dump[DumpMessage] as Message;
 }
Exemplo n.º 19
0
 public override void LoadDump(Dump dump)
 {
     span = Convert.ToDouble(dump[DumpSpan]);
 }
Exemplo n.º 20
0
 public override void LoadDump(Dump dump)
 {
     X = Convert.ToDouble(dump[DumpX]);
     Y = Convert.ToDouble(dump[DumpY]);
     Z = Convert.ToDouble(dump[DumpZ]);
 }
Exemplo n.º 21
0
 public abstract void LoadDump(Dump dump);
Exemplo n.º 22
0
 public BaseMessage(Dump content, double sentAt, double receivedAt)
 {
     Content    = content;
     SentAt     = sentAt;
     ReceivedAt = receivedAt;
 }
Exemplo n.º 23
0
        private void RunAssembly(string assemblyPath, IGrouping <string, TestCase> testCases, TestFilter filter)
        {
            string actionText    = Debugger.IsAttached ? "Debugging " : "Running ";
            string selectionText = filter == null || filter == TestFilter.Empty ? "all" : "selected";

            TestLog.Info(actionText + selectionText + " tests in " + assemblyPath);
            RestoreRandomSeed(assemblyPath);
            Dump = DumpXml.CreateDump(assemblyPath, testCases, Settings);

            try
            {
                var package = CreateTestPackage(assemblyPath, testCases);
                NUnitEngineAdapter.CreateRunner(package);
                CreateTestOutputFolder();
                Dump?.StartDiscoveryInExecution(testCases, filter, package);

                // var discoveryResults = RunType == RunType.CommandLineCurrentNUnit ? null : NUnitEngineAdapter.Explore(filter);
                var discoveryResults = NUnitEngineAdapter.Explore(filter);
                Dump?.AddString(discoveryResults?.AsString() ?? " No discovery");

                if (discoveryResults?.IsRunnable ?? true)
                {
                    var discovery = new DiscoveryConverter(TestLog, Settings);
                    discovery.Convert(discoveryResults, assemblyPath);
                    var ea = ExecutionFactory.Create(this);
                    ea.Run(filter, discovery, this);
                }
                else
                {
                    TestLog.Info(discoveryResults.HasNoNUnitTests
                            ? "   NUnit couldn't find any tests in " + assemblyPath
                            : "   NUnit failed to load " + assemblyPath);
                }
            }
            catch (BadImageFormatException)
            {
                // we skip the native c++ binaries that we don't support.
                TestLog.Warning("   Assembly not supported: " + assemblyPath);
            }
            catch (NUnitEngineException e)
            {
                if (e.InnerException is BadImageFormatException)
                {
                    // we skip the native c++ binaries that we don't support.
                    TestLog.Warning("   Assembly not supported: " + assemblyPath);
                }
                throw;
            }
            catch (FileNotFoundException ex)
            {
                // Probably from the GetExportedTypes in NUnit.core, attempting to find an assembly, not a problem if it is not NUnit here
                TestLog.Warning("   Dependent Assembly " + ex.FileName + " of " + assemblyPath + " not found. Can be ignored if not an NUnit project.");
            }
            catch (Exception ex)
            {
                if (ex is TargetInvocationException)
                {
                    ex = ex.InnerException;
                }
                TestLog.Warning("   Exception thrown executing tests in " + assemblyPath, ex);
            }
            finally
            {
                Dump?.DumpForExecution();
                try
                {
                    NUnitEngineAdapter?.CloseRunner();
                }
                catch (Exception ex)
                {
                    // can happen if CLR throws CannotUnloadAppDomainException, for example
                    // due to a long-lasting operation in a protected region (catch/finally clause).
                    if (ex is TargetInvocationException)
                    {
                        ex = ex.InnerException;
                    }
                    TestLog.Warning($"   Exception thrown unloading tests from {assemblyPath}", ex);
                }
            }
        }
Exemplo n.º 24
0
 public void LoadIndexIntoOldSearchDump(int index)
 {
     oldDump = searchHistory.LoadSearchDump(index);
 }
Exemplo n.º 25
0
        public bool SearchRefactored(uint sAddress, uint eAddress, List <SearchComparisonInfo> comparisons, SearchSize searchSize, uint val)
        {
            blockDump = false;

            resLab.Text = "Searching";
            byte bufferlength = 0;

            switch (searchSize)
            {
            case (SearchSize.Bit8): bufferlength = 1; break;

            case (SearchSize.Bit16): bufferlength = 2; break;

            default: bufferlength = 4; break;
            }

            this.sSize = searchSize;

            bool floatCompare = searchSize == SearchSize.Single;

            int                  oldSortedColumn = 0;
            SortOrder            oldSortOrder    = SortOrder.Ascending;
            SearchResultComparer comparer        = new SearchResultComparer();

            if (gView.SortedColumn != null)
            {
                oldSortedColumn = gView.SortedColumn.Index;
                oldSortOrder    = gView.SortOrder;
            }
            if (oldSortedColumn != 0 || oldSortOrder != SortOrder.Ascending)
            {
                comparer.sortedColumn = 0;
                comparer.descending   = false;
                resultAddressList.Sort(comparer);
            }

            SearchType sType = comparisons[0].searchType;

            bool doBlockSearch = false;
            bool doCompare     = false;

            Dump searchDump = newDump;
            uint dumpStart, dumpEnd, dumpOffset;

            dumpStart  = sAddress;
            dumpEnd    = eAddress;
            dumpOffset = 0;

            if (NewSearch || (UnknownStart && sType == SearchType.Exact))
            {
                InitialSearch = true;
                dumpNum       = 0;

                if (newDump != null)
                {
                    newDump = null;
                }
                resultAddressList.Clear();
                if (oldDump != null)
                {
                    oldDump = null;
                }

                if (sType == SearchType.Exact)
                {
                    doCompare = true;
                }
                else
                {
                    UnknownLAddress = sAddress;
                    UnknownHAddress = eAddress;
                    UnknownStart    = true;
                    NewSearch       = false;
                }
            }
            else
            {
                InitialSearch = false;
                doCompare     = true;
                if (UnknownStart)
                {
                    dumpStart  = Math.Max(UnknownLAddress, sAddress);
                    dumpEnd    = Math.Min(UnknownHAddress, eAddress);
                    dumpOffset = dumpStart - UnknownLAddress;
                }
                else
                {
                    doBlockSearch = true;
                }
            }

            undoDump = oldDump;
            oldDump  = newDump;
            undoList = resultAddressList;

            if (doBlockSearch)
            {
                uint startAddress, endAddress;
                int  startAddressIndex, endAddressIndex;
                FindPairs(dumpStart, dumpEnd, bufferlength, out startAddress, out endAddress, out startAddressIndex, out endAddressIndex);
                List <DumpRange> dumpRanges = FindDumpRanges(startAddress, bufferlength, startAddressIndex, endAddressIndex);
                newDump = new Dump(startAddress, endAddress, dumpNum);
                PerformBlockSearch(newDump, dumpRanges);
            }
            else
            {
                newDump = new Dump(dumpStart, dumpEnd, dumpNum);
                SafeDump(dumpStart, dumpEnd, newDump);
            }

            if (doCompare)
            {
                uint cmpVal;
                cmpVal = comparisons[0].value;

                if (resultAddressList.Count > 0)
                {
                    List <uint> tempAddressList = new List <uint>();
                    foreach (uint compareAddress in resultAddressList)
                    {
                        uint newDumpVal = newDump.ReadAddress(compareAddress, bufferlength);
                        uint oldDumpVal = oldDump.ReadAddress(compareAddress, bufferlength);
                        uint UndoDumpVal;
                        if (undoDump != null)
                        {
                            UndoDumpVal = undoDump.ReadAddress(compareAddress, bufferlength);
                        }
                        else
                        {
                            UndoDumpVal = oldDumpVal;
                        }
                        if (CompareRefactored(newDumpVal, oldDumpVal, UndoDumpVal, comparisons, floatCompare))
                        {
                            tempAddressList.Add(compareAddress);
                        }
                    }

                    resultAddressList = tempAddressList;
                }
                else
                {
                    for (uint i = newDump.StartAddress; i < newDump.EndAddress; i += bufferlength)
                    {
                        uint newDumpVal  = newDump.ReadAddress(i, bufferlength);
                        uint oldDumpVal  = newDumpVal;
                        uint UndoDumpVal = newDumpVal;
                        if (sType != SearchType.Exact)
                        {
                            oldDumpVal  = oldDump.ReadAddress(i, bufferlength);
                            UndoDumpVal = oldDumpVal;
                        }

                        if (CompareRefactored(newDumpVal, oldDumpVal, UndoDumpVal, comparisons, floatCompare))
                        {
                            resultAddressList.Add(i);
                        }
                    }
                }
            }

            if (UnknownStart && !InitialSearch)
            {
                UnknownStart = false;
            }

            dumpNum++;

            if (resultAddressList.Count == 0 && !UnknownStart)
            {
                DialogResult result      = MessageBox.Show(null, "No search results!\n\nTo undo, press Yes\nTo restart, press No", "No search results!", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
                bool         UndoSuccess = false;
                if (result == DialogResult.Yes)
                {
                    UndoSuccess = UndoSearch();
                    if (!UndoSuccess)
                    {
                        MessageBox.Show("Could not undo!  Restarting search");
                    }
                }

                if (!UndoSuccess)
                {
                    NewSearch         = true;
                    nxButton.Enabled  = false;
                    prvButton.Enabled = false;
                    resLab.Text       = "No results found";
                    Reset();
                    return(false);
                }
            }

            NewSearch = false;

            UpdateGridViewPage(true);

            return(true);
        }
Exemplo n.º 26
0
 public new String ToString()
 {
     return(Dump.GetMessage(this));
 }
Exemplo n.º 27
0
 /// <summary>
 /// Constructs an instance of a state handler
 /// </summary>
 /// <param name="target">The Guid of the target object who owns the states</param>
 /// <param name="dump">The delegate method to call whenever the total number of storable states is exceded</param>
 /// <param name="states">The number of states this handler will store before dumping them to storage (using the dump delegate)</param>
 public StateHandler(Guid target, Dump dump, int states)
 {
     this.target = target;
     this.states = new IState[states];
 }
Exemplo n.º 28
0
 public abstract void LoadDump(Dump dump);
Exemplo n.º 29
0
        public bool Search(uint sAddress, uint eAddress, uint lValue, uint hValue,
                           bool useHValue, SearchType sType, SearchSize sSize, ComparisonType cType,
                           uint differentBy)
        {
            blockDump = false;

            resLab.Text = "Searching";
            byte bufferlength = 0;

            switch (sSize)
            {
            case (SearchSize.Bit8): bufferlength = 1; break;

            case (SearchSize.Bit16): bufferlength = 2; break;

            default: bufferlength = 4; break;
            }

            bool floatCompare = sSize == SearchSize.Single;

            int                  oldSortedColumn = 0;
            SortOrder            oldSortOrder    = SortOrder.Ascending;
            SearchResultComparer comparer        = new SearchResultComparer();

            if (gView.SortedColumn != null)
            {
                oldSortedColumn = gView.SortedColumn.Index;
                oldSortOrder    = gView.SortOrder;
            }
            if (oldSortedColumn != 0 || oldSortOrder != SortOrder.Ascending)
            {
                comparer.sortedColumn = 0;
                comparer.descending   = false;
                resultAddressList.Sort(comparer);
            }

            this.sSize = sSize;

            bool doBlockSearch = false;
            bool doCompare     = false;

            Dump searchDump = newDump;
            uint dumpStart, dumpEnd, dumpOffset;

            dumpStart  = sAddress;
            dumpEnd    = eAddress;
            dumpOffset = 0;

            if (NewSearch || (UnknownStart && sType == SearchType.Exact))
            {
                InitialSearch = true;
                dumpNum       = 0;

                if (newDump != null)
                {
                    newDump = null;
                }
                resultAddressList.Clear();
                if (oldDump != null)
                {
                    oldDump = null;
                }

                if (sType == SearchType.Exact)
                {
                    doCompare = true;
                }
                else
                {
                    UnknownLAddress = sAddress;
                    UnknownHAddress = eAddress;
                    UnknownStart    = true;
                    NewSearch       = false;
                }
            }
            else
            {
                InitialSearch = false;
                doCompare     = true;
                if (UnknownStart)
                {
                    dumpStart  = Math.Max(UnknownLAddress, sAddress);
                    dumpEnd    = Math.Min(UnknownHAddress, eAddress);
                    dumpOffset = dumpStart - UnknownLAddress;
                }
                else
                {
                    doBlockSearch = true;
                }
            }

            if (undoDump != null)
            {
            }
            undoDump = oldDump;
            oldDump  = newDump;

            if (undoList != resultAddressList)
            {
                undoList.Clear();
            }
            undoList = resultAddressList;

            try
            {
                if (doBlockSearch)
                {
                    uint startAddress, endAddress;
                    int  startAddressIndex, endAddressIndex;
                    FindPairs(sAddress, eAddress, bufferlength, out startAddress, out endAddress, out startAddressIndex, out endAddressIndex);
                    List <DumpRange> dumpRanges = FindDumpRanges(startAddress, bufferlength, startAddressIndex, endAddressIndex);
                    newDump = new Dump(startAddress, endAddress, dumpNum);
                    PerformBlockSearch(newDump, dumpRanges);
                }
                else
                {
                    newDump = new Dump(dumpStart, dumpEnd, dumpNum);
                    gecko.Dump(newDump);
                }
            }
            catch (ETCPGeckoException e)
            {
                exceptionHandling.HandleException(e);
            }

            if (doCompare)
            {
                if (sType != SearchType.Exact && sType != SearchType.Diff)
                {
                    hValue    = 0;
                    useHValue = false;
                }

                uint val, cmpVal;
                cmpVal = lValue;

                if (resultAddressList.Count > 0)
                {
                    List <uint> tempAddressList = new List <uint>();
                    foreach (uint compareAddress in resultAddressList)
                    {
                        val = newDump.ReadAddress(compareAddress, bufferlength);
                        if (sType == SearchType.Unknown)
                        {
                            cmpVal = oldDump.ReadAddress(compareAddress, bufferlength);
                        }
                        else if (sType == SearchType.Old)
                        {
                            cmpVal = undoDump.ReadAddress(compareAddress, bufferlength);
                        }
                        else if (sType == SearchType.Diff)
                        {
                            val = val - oldDump.ReadAddress(compareAddress, bufferlength);
                        }

                        if (Compare(val, cmpVal, hValue, useHValue, cType, differentBy, floatCompare))
                        {
                            tempAddressList.Add(compareAddress);
                        }
                    }

                    resultAddressList = tempAddressList;
                }
                else
                {
                    for (uint i = newDump.StartAddress; i < newDump.EndAddress; i += bufferlength)
                    {
                        val = newDump.ReadAddress(i, bufferlength);
                        if (sType != SearchType.Exact)
                        {
                            cmpVal = oldDump.ReadAddress(i, bufferlength);
                        }

                        if (Compare(val, cmpVal, hValue, useHValue, cType, differentBy, floatCompare))
                        {
                            resultAddressList.Add(i);
                        }
                    }
                }
            }


            if (UnknownStart && !InitialSearch)
            {
                UnknownStart = false;
            }

            dumpNum++;


            if (resultAddressList.Count == 0 && !UnknownStart)
            {
                NewSearch         = true;
                nxButton.Enabled  = false;
                prvButton.Enabled = false;
                resLab.Text       = "No results found";
                Reset();
                return(false);
            }

            NewSearch = false;

            UpdateGridViewPage(true);

            return(true);
        }
Exemplo n.º 30
0
 public virtual void LoadDump(Dump dump)
 {
     SentAt     = Convert.ToDouble(dump[DumpSentAt]);
     ReceivedAt = Convert.ToDouble(dump[DumpReceivedAt]);
     content    = dump[DumpContent];
 }
Exemplo n.º 31
0
        /// Evaluate the operation against stack
        public void Eval(IEvaluationContext context, Stack <object> stack)
        {
            var o2 = stack.Pop();
            var o1 = o2;

            if (!IsUnary(_operator))
            {
                o1 = stack.Pop();
            }
            switch (_operator)
            {
            default:
                var o1isStr = (o1 is string || o1 is char || o1 is char?);
                var o2isStr = (o2 is string || o2 is char || o2 is char?);
                if (_operator == OperatorType.Plus)
                {
                    if (o1 == null)
                    {
                        stack.Push(o2);
                        return;
                    }
                    if (o2 == null)
                    {
                        stack.Push(o1);
                        return;
                    }
                }
                if (o1 != null && (!(o1.GetType().IsPrimitive || o1 is decimal) || (o1isStr && o2isStr)))
                {
                    if (_operator == OperatorType.Plus && o1isStr)
                    {
                        stack.Push(string.Concat(o1, o2));
                        return;
                    }
                    if (o1isStr && o2isStr)
                    {
                        stack.Push(stringMath(o1.ToString(), (o2 ?? string.Empty).ToString()));
                        return;
                    }


                    if (_operator == OperatorType.Equal)
                    {
                        stack.Push(o1.Equals(o2));
                        return;
                    }
                    if (_operator == OperatorType.NotEqual)
                    {
                        stack.Push(!o1.Equals(o2));
                        return;
                    }
                }
                if (o1 == null || o2 == null)
                {
                    if (_operator == OperatorType.Equal)
                    {
                        stack.Push(o1 == o2);
                        return;
                    }
                    if (_operator == OperatorType.NotEqual)
                    {
                        stack.Push(o1 != o2);
                        return;
                    }
                    throw new NullReferenceException();
                }

                if (o1 is decimal || o2 is decimal)
                {
                    stack.Push(decimalMath(Utils.To <decimal>(o1), Utils.To <decimal>(o2)));
                }
                else if (o1 is double || o2 is double || o1 is float || o2 is float)
                {
                    stack.Push(doubleMath(Utils.To <double>(o1), Utils.To <double>(o2)));
                }
                else
                {
                    var v = longMath(Utils.To <long>(o1), Utils.To <long>(o2));
                    if (o1 is int && o2 is int)
                    {
                        v = Utils.To <int>(v);
                    }
                    stack.Push(v);
                }
                return;

            case OperatorType.Dump:
                stack.Push(Dump.ToDump(o1));
                break;

            case OperatorType.Throw:
                if (o1 is Exception)
                {
                    throw (Exception)o1;
                }
                throw new ApplicationException((o1 ?? string.Empty).ToString());
            }
        }
Exemplo n.º 32
0
 private void VerifyEvents(Dump dump)
 {
     Assert.That(dump.Events.Count, Is.EqualTo(3));
     Assert.That(dump.Events.Keys, Is.EquivalentTo(new uint[] { 1, 83, 140 }));
     Assert.That(dump.Events[1].Id, Is.EqualTo(1));
     Assert.That(dump.Events[83].Id, Is.EqualTo(83));
     Assert.That(dump.Events[140].Id, Is.EqualTo(140));
 }
Exemplo n.º 33
0
 public override void LoadDump(Dump dump)
 {
     Message = dump[DumpMessage] as Message;
 }
Exemplo n.º 34
0
        public override void LoadDump(Dump dump)
        {
            string name = dump[DumpName] as string;

            if (name == null)
            {
                throw new KOSSerializationException("Body's name is null or invalid");
            }

            CelestialBody body = VesselUtils.GetBodyByName(name);

            if (body == null)
            {
                throw new KOSSerializationException("Body with the given name does not exist");
            }

            Body = body;
        }
Exemplo n.º 35
0
 public override void LoadDump(Dump dump)
 {
     Frequency = Convert.ToSingle(dump["freq"]);
     EndFrequency = Convert.ToSingle(dump["endfreq"]);
     Volume = Convert.ToSingle(dump["vol"]);
     KeyDownLength = Convert.ToSingle(dump["keydown"]);
     Duration = Convert.ToSingle(dump["duration"]);
 }
Exemplo n.º 36
0
 public override void LoadDump(Dump dump)
 {
     Body = (dump[DumpBody] as BodyTarget).Body;
     lat = Convert.ToDouble(dump[DumpLat]);
     lng = Convert.ToDouble(dump[DumpLng]);
 }
Exemplo n.º 37
0
 internal void DumpUndoService()
 {
     Dump.Write(this.UndoService.ToString());
 }
Exemplo n.º 38
0
 public override void LoadDump(Dump dump)
 {
     Body = (dump[DumpBody] as BodyTarget).Body;
     lat  = Convert.ToDouble(dump[DumpLat]);
     lng  = Convert.ToDouble(dump[DumpLng]);
 }
Exemplo n.º 39
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Options">Command line parameters</param>
        public override void Dump(Dump Options) {
            SetReporting(Options.Report, Options.Verbose);
            GetProfile(Options.Portal, Options.UDF);

            Report(RegistrationPersonal, true);
            }
Exemplo n.º 40
0
 public override string ToString()
 {
     return(Dump.Props(this));
 }
Exemplo n.º 41
0
        public override void LoadDump(Dump dump)
        {
            string guid = dump[DumpGuid] as string;

            if (guid == null)
            {
                throw new KOSSerializationException("Vessel's guid is null or invalid");
            }

            Vessel vessel = FlightGlobals.Vessels.Find((v) => v.id.ToString().Equals(guid));

            if (vessel == null)
            {
                throw new KOSSerializationException("Vessel with the given id does not exist");
            }

            Vessel = vessel;
        }
Exemplo n.º 42
0
        public IDumper Deserialize(string input, IFormatReader formatter)
        {
            Dump dump = formatter.Read(input);

            return(dump == null ? null : CreateFromDump(dump));
        }
Exemplo n.º 43
0
    private void dumpLoader_LoadCompleted(object sender, LoadCompletedEventArgs e)
    {
        if (m_curTask != null)
            m_curTask.Completed();

        if (e.Cancelled)
            return;

        try
        {
            Dump newDump = e.Dump;

            if (m_curDump != null)
                m_curDump = null; // Dummy placeholder, switch dump here
            m_curDump = newDump;
        }
        catch (Exception ex)
        {
            ShowErrorMessage("Error opening dump. Please file a bug.\n\nDetails:\n" + ex.ToString());
        }
    }
Exemplo n.º 44
0
        public override void Visit(UnionAllOp op, Node n)
        {
#if DEBUG
            var input = Dump.ToXml(n);
#endif
            //DEBUG

            // Ensure we have keys pulled up on each branch of the union all.
            VisitChildren(n);

            // Create the setOp var we'll use to output the branch discriminator value; if
            // any of the branches are already surfacing a branchDiscriminator var to the
            // output of this operation then we won't need to use this but we construct it
            // early to simplify logic.
            Var outputBranchDiscriminatorVar = m_command.CreateSetOpVar(m_command.IntegerType);

            // Now ensure that we're outputting the key vars from this op as well.
            var allKeyVarsMissingFromOutput = Command.CreateVarList();
            var keyVarsMissingFromOutput    = new VarVec[n.Children.Count];

            for (var i = 0; i < n.Children.Count; i++)
            {
                var branchNode     = n.Children[i];
                var branchNodeInfo = m_command.GetExtendedNodeInfo(branchNode);

                // Identify keys that aren't in the output list of this operation. We
                // determine these by remapping the keys that are found through the node's
                // VarMap, which gives us the keys in the same "varspace" as the outputs
                // of the UnionAll, then we subtract out the outputs of this UnionAll op,
                // leaving things that are not in the output vars.  Of course, if they're
                // not in the output vars, then we didn't really remap.
                var existingKeyVars = branchNodeInfo.Keys.KeyVars.Remap(op.VarMap[i]);

                keyVarsMissingFromOutput[i] = m_command.CreateVarVec(existingKeyVars);
                keyVarsMissingFromOutput[i].Minus(op.Outputs);

                // Special Case: if the branch is a UnionAll, it will already have it's
                // branch discriminator var added in the keys; we don't want to add that
                // a second time...
                if (OpType.UnionAll
                    == branchNode.Op.OpType)
                {
                    var branchUnionAllOp = (UnionAllOp)branchNode.Op;

                    keyVarsMissingFromOutput[i].Clear(branchUnionAllOp.BranchDiscriminator);
                }

                allKeyVarsMissingFromOutput.AddRange(keyVarsMissingFromOutput[i]);
            }

            // Construct the setOp vars we're going to map to output.
            var allKeyVarsToAddToOutput = Command.CreateVarList();

            foreach (var v in allKeyVarsMissingFromOutput)
            {
                Var newKeyVar = m_command.CreateSetOpVar(v.Type);
                allKeyVarsToAddToOutput.Add(newKeyVar);
            }

            // Now that we've identified all the keys we need to add, ensure that each branch
            // has both the branch discrimination var and the all the keys in them, even when
            // the keys are just going to null (which we construct, as needed)
            for (var i = 0; i < n.Children.Count; i++)
            {
                var branchNode     = n.Children[i];
                var branchNodeInfo = m_command.GetExtendedNodeInfo(branchNode);

                var branchOutputVars = m_command.CreateVarVec();
                var varDefNodes      = new List <Node>();

                // If the branch is a UnionAllOp that has a branch discriminator var then we can
                // use it, otherwise we'll construct a new integer constant with the next value
                // of the branch discriminator value from the command object.
                Var branchDiscriminatorVar;

                if (OpType.UnionAll == branchNode.Op.OpType &&
                    null != ((UnionAllOp)branchNode.Op).BranchDiscriminator)
                {
                    branchDiscriminatorVar = ((UnionAllOp)branchNode.Op).BranchDiscriminator;

                    // If the branch has a discriminator var, but we haven't added it to the
                    // varmap yet, then we do so now.
                    if (!op.VarMap[i].ContainsValue(branchDiscriminatorVar))
                    {
                        op.VarMap[i].Add(outputBranchDiscriminatorVar, branchDiscriminatorVar);
                        // We don't need to add this to the branch outputs, because it's already there,
                        // otherwise we wouln't have gotten here, yes?
                    }
                    else
                    {
                        // In this case, we're already outputting the branch discriminator var -- we'll
                        // just use it for both sides.  We should never have a case where only one of the
                        // two branches are outputting the branch discriminator var, because it can only
                        // be constructed in this method, and we wouldn't need it for any other purpose.
                        PlanCompiler.Assert(0 == i, "right branch has a discriminator var that the left branch doesn't have?");
                        var reverseVarMap = op.VarMap[i].GetReverseMap();
                        outputBranchDiscriminatorVar = reverseVarMap[branchDiscriminatorVar];
                    }
                }
                else
                {
                    // Not a unionAll -- we have to add a BranchDiscriminator var.
                    varDefNodes.Add(
                        m_command.CreateVarDefNode(
                            m_command.CreateNode(
                                m_command.CreateConstantOp(m_command.IntegerType, m_command.NextBranchDiscriminatorValue)),
                            out branchDiscriminatorVar));

                    branchOutputVars.Set(branchDiscriminatorVar);
                    op.VarMap[i].Add(outputBranchDiscriminatorVar, branchDiscriminatorVar);
                }

                // Append all the missing keys to the branch outputs.  If the missing key
                // is not from this branch then create a null.
                for (var j = 0; j < allKeyVarsMissingFromOutput.Count; j++)
                {
                    var keyVar = allKeyVarsMissingFromOutput[j];

                    if (!keyVarsMissingFromOutput[i].IsSet(keyVar))
                    {
                        varDefNodes.Add(
                            m_command.CreateVarDefNode(
                                m_command.CreateNode(
                                    m_command.CreateNullOp(keyVar.Type)), out keyVar));

                        branchOutputVars.Set(keyVar);
                    }

                    // In all cases, we're adding a key to the output so we need to update the
                    // varmap.
                    op.VarMap[i].Add(allKeyVarsToAddToOutput[j], keyVar);
                }

                // If we got this far and didn't add anything to the branch, then we're done.
                // Otherwise we'll have to construct the new projectOp around the input branch
                // to add the stuff we've added.
                if (branchOutputVars.IsEmpty)
                {
                    // Actually, we're not quite done -- we need to update the key vars for the
                    // branch to include the branch discriminator var we
                    branchNodeInfo.Keys.KeyVars.Set(branchDiscriminatorVar);
                }
                else
                {
                    PlanCompiler.Assert(varDefNodes.Count != 0, "no new nodes?");

                    // Start by ensuring all the existing outputs from the branch are in the list.
                    foreach (var v in op.VarMap[i].Values)
                    {
                        branchOutputVars.Set(v);
                    }

                    // Now construct a project op to project out everything we've added, and
                    // replace the branchNode with it in the flattened ladder.
                    n.Children[i] = m_command.CreateNode(
                        m_command.CreateProjectOp(branchOutputVars),
                        branchNode,
                        m_command.CreateNode(m_command.CreateVarDefListOp(), varDefNodes));

                    // Finally, ensure that we update the Key info for the projectOp to include
                    // the original branch's keys, along with the branch discriminator var.
                    m_command.RecomputeNodeInfo(n.Children[i]);
                    var projectNodeInfo = m_command.GetExtendedNodeInfo(n.Children[i]);
                    projectNodeInfo.Keys.KeyVars.InitFrom(branchNodeInfo.Keys.KeyVars);
                    projectNodeInfo.Keys.KeyVars.Set(branchDiscriminatorVar);
                }
            }

            // All done with the branches, now it's time to update the UnionAll op to indicate
            // that we've got a branch discriminator var.
            n.Op = m_command.CreateUnionAllOp(op.VarMap[0], op.VarMap[1], outputBranchDiscriminatorVar);

            // Finally, the thing we've all been waiting for -- computing the keys.  We cheat here and let
            // nodeInfo do it so we don't have to duplicate the logic...
            m_command.RecomputeNodeInfo(n);

#if DEBUG
            input = input.Trim();
            var output = Dump.ToXml(n);
#endif
            //DEBUG
        }
Exemplo n.º 45
0
 public override void LoadDump(Dump dump)
 {
     Path = GlobalPath.FromString(dump[DumpPath] as string);
 }
Exemplo n.º 46
0
 public override void LoadDump(Dump dump)
 {
     Vessel = VesselFromDump(dump);
 }
Exemplo n.º 47
0
 public override void LoadDump(Dump dump)
 {
     seconds = Convert.ToDouble(dump[DumpName]);
 }
Exemplo n.º 48
0
    //This function actually creates the object associated with each Instruction by using a long switch statement. The object
    //created is polymorphed up to an IInstruction and then returned from the function to be stored in the encodedInstrs list.
    //Ugly? Very. Effective? Extremely.
    private IInstruction createObject(string comm, int valToUse, int currentInstruc)
    {
        IInstruction retVal = null;

        switch (comm)
        {
        case "exit":
            retVal = new Exit(valToUse) as IInstruction;
            break;

        case "swap":
            retVal = new Swap() as IInstruction;
            break;

        case "inpt":
            retVal = new Inpt() as IInstruction;
            break;

        case "nop":
            retVal = new Nop() as IInstruction;
            break;

        case "pop":
            retVal = new Pop() as IInstruction;
            break;

        case "add":
            retVal = new Add() as IInstruction;
            break;

        case "sub":
            retVal = new Sub() as IInstruction;
            break;

        case "mul":
            retVal = new Mul() as IInstruction;
            break;

        case "div":
            retVal = new Div() as IInstruction;
            break;

        case "rem":
            retVal = new Rem() as IInstruction;
            break;

        case "and":
            retVal = new And() as IInstruction;
            break;

        case "or":
            retVal = new Or() as IInstruction;
            break;

        case "xor":
            retVal = new Xor() as IInstruction;
            break;

        case "neg":
            retVal = new Neg() as IInstruction;
            break;

        case "not":
            retVal = new Not() as IInstruction;
            break;

        case "goto":
            retVal = new Goto(valToUse) as IInstruction;
            break;

        case "ifeq":
            retVal = new If1(0, valToUse, currentInstruc) as IInstruction;
            break;

        case "ifne":
            retVal = new If1(1, valToUse, currentInstruc) as IInstruction;
            break;

        case "iflt":
            retVal = new If1(2, valToUse, currentInstruc) as IInstruction;
            break;

        case "ifgt":
            retVal = new If1(3, valToUse, currentInstruc) as IInstruction;
            break;

        case "ifle":
            retVal = new If1(4, valToUse, currentInstruc) as IInstruction;
            break;

        case "ifge":
            retVal = new If1(5, valToUse, currentInstruc) as IInstruction;
            break;

        case "ifez":
            retVal = new If2(0, valToUse, currentInstruc) as IInstruction;
            break;

        case "ifnz":
            retVal = new If2(1, valToUse, currentInstruc) as IInstruction;
            break;

        case "ifmi":
            retVal = new If2(2, valToUse, currentInstruc) as IInstruction;
            break;

        case "ifpl":
            retVal = new If2(3, valToUse, currentInstruc) as IInstruction;
            break;

        case "dup":
            retVal = new Dup(valToUse) as IInstruction;
            break;

        case "print":
            retVal = new Print() as IInstruction;
            break;

        case "dump":
            retVal = new Dump() as IInstruction;
            break;

        case "push":
            retVal = new Push(valToUse) as IInstruction;
            break;
        }
        return(retVal);
    }
Exemplo n.º 49
0
        public Dump LoadSearchDump(string filepath)
        {
            // spin while background writing to prevent us from reading a file that has yet to be written
            while (BackgroundWriting) ;

            ZipInputStream instream = new ZipInputStream(filepath);
            BinaryFormatter formatter = new BinaryFormatter();

            // First entry is the dump
            instream.GetNextEntry();
            Dump searchDump = new Dump((uint)formatter.Deserialize(instream), (uint)formatter.Deserialize(instream));
            instream.Read(searchDump.mem, 0, (int)(searchDump.EndAddress - searchDump.StartAddress));

            instream.Close();
            instream.Dispose();

            return searchDump;
        }
Exemplo n.º 50
0
 public Message(Dump content, double sentAt, double receivedAt, VesselTarget sender)
     : base(content, sentAt, receivedAt)
 {
     Vessel = sender.GetGuid().ToString();
 }
Exemplo n.º 51
0
        public void ReadCompressedZip(string filepath)
        {
            while (BackgroundWriting) ;

            ZipInputStream instream = new ZipInputStream(filepath);
            BinaryFormatter formatter = new BinaryFormatter();
            instream.GetNextEntry();
            searchDump = new FTDIUSBGecko.Dump((uint)formatter.Deserialize(instream), (uint)formatter.Deserialize(instream));
            instream.Read(searchDump.mem, 0, (int)(searchDump.EndAddress - searchDump.StartAddress));

            instream.GetNextEntry();
            resultsList = (System.Collections.Generic.List<UInt32>)formatter.Deserialize(instream);

            instream.Close();
            instream.Dispose();
        }
Exemplo n.º 52
0
        public override void LoadDump(Dump dump)
        {
            base.LoadDump(dump);

            Vessel = dump[DumpVessel] as string;
        }
Exemplo n.º 53
0
        public void SaveSearch(int index, List<UInt32> resultsList, Dump searchDump)
        {
            // TODO subdir?  check file exists?
			char delim = Path.DirectorySeparatorChar;
            SaveSearch("DumpHistory" + delim + "DumpHistory" + index + ".zip", resultsList, searchDump);
        }
Exemplo n.º 54
0
        void OnBtnDumpClick(object sender, EventArgs e)
        {
            txtLog.Text            = "";
            btnClose.Visible       = false;
            btnStart.Visible       = false;
            btnStop.Visible        = true;
            btnStop.Enabled        = true;
            stkProgress.Visible    = true;
            btnDestination.Visible = false;
            stkOptions.Visible     = false;

            UpdateStatus("Opening device...");

            try
            {
                _dev = new Device(_devicePath);

                if (_dev.IsRemote)
                {
                    Statistics.AddRemote(_dev.RemoteApplication, _dev.RemoteVersion, _dev.RemoteOperatingSystem,
                                         _dev.RemoteOperatingSystemVersion, _dev.RemoteArchitecture);
                }

                if (_dev.Error)
                {
                    StoppingErrorMessage($"Error {_dev.LastError} opening device.");

                    return;
                }
            }
            catch (Exception exception)
            {
                StoppingErrorMessage($"Exception {exception.Message} opening device.");

                return;
            }

            Statistics.AddDevice(_dev);
            Statistics.AddCommand("dump-media");

            if (!(cmbFormat.SelectedValue is IWritableImage outputFormat))
            {
                StoppingErrorMessage("Cannot open output plugin.");

                return;
            }

            Encoding encoding = null;

            if (cmbEncoding.SelectedValue is CommonEncodingInfo encodingInfo)
            {
                try
                {
                    encoding = Claunia.Encoding.Encoding.GetEncoding(encodingInfo.Name);
                }
                catch (ArgumentException)
                {
                    StoppingErrorMessage("Specified encoding is not supported.");

                    return;
                }
            }

            Dictionary <string, string> parsedOptions = new Dictionary <string, string>();

            if (grpOptions.Content is StackLayout stkFormatOptions)
            {
                foreach (Control option in stkFormatOptions.Children)
                {
                    string value;

                    switch (option)
                    {
                    case CheckBox optBoolean:
                        value = optBoolean.Checked?.ToString();

                        break;

                    case NumericStepper optNumber:
                        value = optNumber.Value.ToString(CultureInfo.CurrentCulture);

                        break;

                    case TextBox optString:
                        value = optString.Text;

                        break;

                    default: continue;
                    }

                    string key = option.ID.Substring(3);

                    parsedOptions.Add(key, value);
                }
            }

            var dumpLog = new DumpLog(_outputPrefix + ".log", _dev);

            dumpLog.WriteLine("Output image format: {0}.", outputFormat.Name);

            _dumper = new Dump(chkResume.Checked == true, _dev, _devicePath, outputFormat,
                               (ushort)stpRetries.Value,
                               chkForce.Checked == true, false, chkPersistent.Checked == true,
                               chkStopOnError.Checked == true, _resume, dumpLog, encoding, _outputPrefix,
                               txtDestination.Text, parsedOptions, _sidecar, (uint)stpSkipped.Value,
                               chkExistingMetadata.Checked == false, chkTrim.Checked == false,
                               chkTrack1Pregap.Checked == true, true, false, DumpSubchannel.Any, 0);

            new Thread(DoWork).Start();
        }