/// <summary>
        /// Writes the log.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="stream">The stream.</param>
        /// <param name="callback">The callback for UI updates.</param>
        public void WriteLog(IExecutionContext context, Stream stream, ProgressCallback callback)
        {
            using (StreamWriter s = new StreamWriter(stream))
            {
                foreach (PacketLog log in context.LogManager.Logs)
                {
                    for (int i = 0; i < log.Count; i++)
                    {
                        if (callback != null && (i & 0xFFF) == 0) // update progress every 4096th packet
                            callback(i, log.Count - 1);

                        StoC_0x02_InventoryUpdate invUpdate = log[i] as StoC_0x02_InventoryUpdate;
                        if (invUpdate == null) continue;

                        foreach (StoC_0x02_InventoryUpdate.Item item in invUpdate.Items)
                        {
                            if (item.name != null && item.name != "")
                                s.WriteLine(
                                    "level={0,-2} value1:{1,-3} value2:{2,-3} damageType:{3} objectType:{4,-2} weight:{5,-3} model={6,-5} color:{7,-3} effect:{8,-3} name={9}",
                                    item.level, item.value1, item.value2, item.damageType, item.objectType, item.weight, item.model, item.color,
                                    item.effect, item.name);
                        }
                    }
                }
            }
        }
Esempio n. 2
0
        public static void RegisterIntegerSaveProgress(this ZipFile zip, ProgressCallback callback)
        {
            int total = 0;
            zip.SaveProgress += (sender, eventArgs) =>
            {
                if (eventArgs.EntriesTotal != 0
                    && total == 0)
                {
                    total = eventArgs.EntriesTotal;
                }

                if (eventArgs.EntriesSaved == 0)
                {
                    return;
                }

                int progress;
                if (total == 0)
                {
                    progress = 0;
                }
                else
                {
                    progress = eventArgs.EntriesSaved;
                }

                callback(zip, progress, total);
            };
        }
Esempio n. 3
0
        public static void CopyStream(Stream source, Stream destination, ProgressCallback callback)
        {
            if (callback == null)
            {
                CopyStream(source, destination);
                return;
            }
            
            if (source == null)
                throw new ArgumentNullException("source");

            if (destination == null)
                throw new ArgumentNullException("destination");

            int count;
            byte[] buffer = new byte[2048];

            double percent = source.Length / 100d;
            double read = 0;

            while ((count = source.Read(buffer, 0, buffer.Length)) != 0)
            {
                read += count;
                destination.Write(buffer, 0, count);

                callback((int)(read / percent));
            }
        }
Esempio n. 4
0
 public override ThingList Load(BinaryReader BR, ProgressCallback ProgressCallback)
 {
     ThingList TL = new ThingList();
       if (ProgressCallback != null)
     ProgressCallback(I18N.GetText("FTM:CheckingFile"), 0);
       if (BR.BaseStream.Length < 0x40 || BR.BaseStream.Position != 0)
     return TL;
     FFXIEncoding E = new FFXIEncoding();
       if (E.GetString(BR.ReadBytes(8)) != "d_msg".PadRight(8, '\0'))
     return TL;
     ushort Flag1 = BR.ReadUInt16();
       if (Flag1 != 0 && Flag1 != 1)
     return TL;
     ushort Flag2 = BR.ReadUInt16();
       if (Flag2 != 0 && Flag2 != 1)
     return TL;
       if (BR.ReadUInt32() != 3 || BR.ReadUInt32() != 3)
     return TL;
     uint FileSize = BR.ReadUInt32();
       if (FileSize != BR.BaseStream.Length)
     return TL;
     uint HeaderBytes = BR.ReadUInt32();
       if (HeaderBytes != 0x40)
     return TL;
       if (BR.ReadUInt32() != 0)
     return TL;
     int BytesPerEntry = BR.ReadInt32();
       if (BytesPerEntry < 0)
     return TL;
     uint DataBytes = BR.ReadUInt32();
       if (FileSize != (HeaderBytes + DataBytes) || (DataBytes % BytesPerEntry) != 0)
     return TL;
     uint EntryCount = BR.ReadUInt32();
       if (EntryCount * BytesPerEntry != DataBytes)
     return TL;
       if (BR.ReadUInt32() != 1 || BR.ReadUInt64() != 0 || BR.ReadUInt64() != 0)
     return TL;
       if (ProgressCallback != null)
     ProgressCallback(I18N.GetText("FTM:LoadingData"), 0);
       for (uint i = 0; i < EntryCount; ++i) {
       BinaryReader EntryBR = new BinaryReader(new MemoryStream(BR.ReadBytes(BytesPerEntry)));
     EntryBR.BaseStream.Position = 0;
       bool ItemAdded = false;
     {
     Things.DMSGStringBlock SB = new Things.DMSGStringBlock();
       if (SB.Read(EntryBR, E, i)) {
     TL.Add(SB);
     ItemAdded = true;
       }
     }
     EntryBR.Close();
     if (!ItemAdded) {
       TL.Clear();
       break;
     }
     if (ProgressCallback != null)
       ProgressCallback(null, (double) (i + 1) / EntryCount);
       }
       return TL;
 }
Esempio n. 5
0
 public override ThingList Load(BinaryReader BR, ProgressCallback ProgressCallback)
 {
     ThingList TL = new ThingList();
     if (ProgressCallback != null)
     {
         ProgressCallback(I18N.GetText("FTM:CheckingFile"), 0);
     }
     if ((BR.BaseStream.Length % 0x20) != 0 || BR.BaseStream.Position != 0)
     {
         return TL;
     }
     long EntryCount = BR.BaseStream.Length / 0x20;
     if (ProgressCallback != null)
     {
         ProgressCallback(I18N.GetText("FTM:LoadingData"), 0);
     }
     try
     {
         int ZoneID = -1;
         for (int i = 0; i < EntryCount; ++i)
         {
             Things.MobListEntry MLE = new Things.MobListEntry();
             if (!MLE.Read(BR))
             {
                 TL.Clear();
                 break;
             }
             uint ThisID = (uint)MLE.GetFieldValue("id");
             if (i == 0 && (ThisID != 0 || MLE.GetFieldText("name") != "none"))
             {
                 TL.Clear();
                 break;
             }
             else if (i > 0)
             {
                 // Entire file should be for 1 specific zone
                 int ThisZone = (int)(ThisID & 0x000FF000);
                 if (ZoneID < 0)
                 {
                     ZoneID = ThisZone;
                 }
                 else if (ThisZone != ZoneID)
                 {
                     TL.Clear();
                     break;
                 }
             }
             if (ProgressCallback != null)
             {
                 ProgressCallback(null, (double)(i + 1) / EntryCount);
             }
             TL.Add(MLE);
         }
     }
     catch
     {
         TL.Clear();
     }
     return TL;
 }
Esempio n. 6
0
 public override ThingList Load(BinaryReader BR, ProgressCallback ProgressCallback)
 {
     ThingList TL = new ThingList();
     if (ProgressCallback != null)
     {
         ProgressCallback(I18N.GetText("FTM:CheckingFile"), 0);
     }
     if ((BR.BaseStream.Length % 0x400) != 0 || BR.BaseStream.Position != 0)
     {
         return TL;
     }
     long EntryCount = BR.BaseStream.Length / 0x400;
     if (ProgressCallback != null)
     {
         ProgressCallback(I18N.GetText("FTM:LoadingData"), 0);
     }
     for (int i = 0; i < EntryCount; ++i)
     {
         Things.SpellInfo SI = new Things.SpellInfo();
         if (!SI.Read(BR))
         {
             TL.Clear();
             break;
         }
         if (ProgressCallback != null)
         {
             ProgressCallback(null, (double)(i + 1) / EntryCount);
         }
         TL.Add(SI);
     }
     return TL;
 }
Esempio n. 7
0
        public Download(string url, string file, FileDownloaded completionCallback, ProgressCallback progressCallback, Files f)
        {
            try
            {
                m_Url = url;
                m_CompletionCallback = completionCallback;
                try
                {
                    m_Stream = new FileStream( file, FileMode.OpenOrCreate, FileAccess.Write );
                }
                catch (IOException e)
                {
                    file = String.Concat( file, ".new" );
                    m_Stream = new FileStream( file, FileMode.OpenOrCreate, FileAccess.Write );
                }

                m_ProgressCallback = progressCallback;
                m_File = f;
                m_Thread = new Thread(new ThreadStart(DownloadFile));
                m_Thread.Start();
            }
            catch (Exception)
            {
                throw;
            }
        }
Esempio n. 8
0
 public static ThingList LoadAll(string FileName, ProgressCallback ProgressCallback, bool FirstMatchOnly)
 {
     ThingList Results = new ThingList();
       if (ProgressCallback != null)
     ProgressCallback(I18N.GetText("FTM:OpeningFile"), 0);
     BinaryReader BR = null;
       try {
     BR = new BinaryReader(new FileStream(FileName, FileMode.Open, FileAccess.Read), Encoding.ASCII);
       } catch { }
       if (BR == null || BR.BaseStream == null)
     return Results;
       foreach (FileType FT in FileType.AllTypes) {
       ProgressCallback SubCallback = null;
     if (ProgressCallback != null) {
       SubCallback = new ProgressCallback(delegate (string Message, double PercentCompleted) {
       string SubMessage = null;
     if (Message != null)
       SubMessage = String.Format("[{0}] {1}", FT.Name, Message);
     ProgressCallback(SubMessage, PercentCompleted);
       });
     }
       ThingList SubResults = FT.Load(BR, SubCallback);
     if (SubResults != null) {
       Results.AddRange(SubResults);
       if (FirstMatchOnly && Results.Count > 0)
     break;
     }
     BR.BaseStream.Seek(0, SeekOrigin.Begin);
       }
       return Results;
 }
        /// <summary>
        /// Writes the log.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="stream">The stream.</param>
        /// <param name="callback">The callback for UI updates.</param>
        public void WriteLog(IExecutionContext context, Stream stream, ProgressCallback callback)
        {
            using (BinaryWriter s = new BinaryWriter(stream, Encoding.ASCII))
            {
                s.Write("[PacketLogConverter v1]");

                foreach (PacketLog log in context.LogManager.Logs)
                {
                    for (int i = 0; i < log.Count; i++)
                    {
                        if (callback != null && (i & 0xFFF) == 0) // update progress every 4096th packet
                            callback(i + 1, log.Count);

                        Packet packet = log[i];
                        if (context.FilterManager.IsPacketIgnored(packet))
                            continue;

                        byte[] buf = packet.GetBuffer();
                        s.Write((ushort) buf.Length);
                        s.Write(packet.GetType().FullName);
                        s.Write((ushort) packet.Code);
                        s.Write((byte) packet.Direction);
                        s.Write((byte) packet.Protocol);
                        s.Write(packet.Time.Ticks);
                        s.Write(buf);
                    }
                }
            }
        }
        /// <summary>
        /// Writes the log.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="stream">The stream.</param>
        /// <param name="callback">The callback for UI updates.</param>
        public void WriteLog(IExecutionContext context, Stream stream, ProgressCallback callback)
        {
            TimeSpan baseTime = new TimeSpan(0);
            using (StreamWriter s = new StreamWriter(stream))
            {
                foreach (PacketLog log in context.LogManager.Logs)
                {
                    // Log file name
                    s.WriteLine();
                    s.WriteLine();
                    s.WriteLine("Log file: " + log.StreamName);
                    s.WriteLine("==============================================");

                    for (int i = 0; i < log.Count; i++)
                    {
                        // Update progress every 4096th packet
                        if (callback != null && (i & 0xFFF) == 0)
                            callback(i, log.Count - 1);

                        Packet packet = log[i];
                        if (context.FilterManager.IsPacketIgnored(packet))
                            continue;

                        s.WriteLine(packet.ToHumanReadableString(baseTime, true));
                    }
                }
            }
        }
Esempio n. 11
0
 public override ThingList Load(BinaryReader BR, ProgressCallback ProgressCallback)
 {
     ThingList TL = new ThingList();
     if (ProgressCallback != null)
     {
         ProgressCallback(I18N.GetText("FTM:CheckingFile"), 0);
     }
     if (BR.BaseStream.Length < 0x38 || BR.BaseStream.Position != 0)
     {
         return TL;
     }
     FFXIEncoding E = new FFXIEncoding();
     // Read past the marker (32 bytes)
     if ((E.GetString(BR.ReadBytes(10)) != "XISTRING".PadRight(10, '\0')) || BR.ReadUInt16() != 2)
     {
         return TL;
     }
     foreach (byte B in BR.ReadBytes(20))
     {
         if (B != 0)
         {
             return TL;
         }
     }
     // Read The Header
     uint FileSize = BR.ReadUInt32();
     if (FileSize != BR.BaseStream.Length)
     {
         return TL;
     }
     uint EntryCount = BR.ReadUInt32();
     uint EntryBytes = BR.ReadUInt32();
     uint DataBytes = BR.ReadUInt32();
     BR.ReadUInt32(); // Unknown
     BR.ReadUInt32(); // Unknown
     if (EntryBytes != EntryCount * 12 || FileSize != 0x38 + EntryBytes + DataBytes)
     {
         return TL;
     }
     if (ProgressCallback != null)
     {
         ProgressCallback(I18N.GetText("FTM:LoadingData"), 0);
     }
     for (uint i = 0; i < EntryCount; ++i)
     {
         Things.XIStringTableEntry XSTE = new Things.XIStringTableEntry();
         if (!XSTE.Read(BR, E, i, EntryBytes, DataBytes))
         {
             TL.Clear();
             break;
         }
         if (ProgressCallback != null)
         {
             ProgressCallback(null, (double)(i + 1) / EntryCount);
         }
         TL.Add(XSTE);
     }
     return TL;
 }
Esempio n. 12
0
 public override ThingList Load(BinaryReader BR, ProgressCallback ProgressCallback)
 {
     ThingList TL = new ThingList();
       if (ProgressCallback != null)
     ProgressCallback(I18N.GetText("FTM:CheckingFile"), 0);
       if (BR.BaseStream.Length < 0x40 || BR.BaseStream.Position != 0)
     return TL;
     FFXIEncoding E = new FFXIEncoding();
       // Skip (presumably) fixed portion of the header
       if ((E.GetString(BR.ReadBytes(8)) != "d_msg".PadRight(8, '\0')) || BR.ReadUInt16() != 1 || BR.ReadUInt16() != 1 || BR.ReadUInt32() != 3 || BR.ReadUInt32() != 3)
     return TL;
       // Read the useful header fields
     uint FileSize = BR.ReadUInt32();
       if (FileSize != BR.BaseStream.Length)
     return TL;
     uint HeaderBytes = BR.ReadUInt32();
       if (HeaderBytes != 0x40)
     return TL;
     uint EntryBytes = BR.ReadUInt32();
       if (BR.ReadUInt32() != 0)
     return TL;
     uint DataBytes  = BR.ReadUInt32();
       if (FileSize != HeaderBytes + EntryBytes + DataBytes)
     return TL;
     uint EntryCount = BR.ReadUInt32();
       if (EntryBytes != EntryCount * 8)
     return TL;
       if (BR.ReadUInt32() != 1 || BR.ReadUInt64() != 0 || BR.ReadUInt64() != 0)
     return TL;
       if (ProgressCallback != null)
     ProgressCallback(I18N.GetText("FTM:LoadingData"), 0);
       for (uint i = 0; i < EntryCount; ++i) {
     BR.BaseStream.Position = HeaderBytes + i * 8;
       int Offset = ~BR.ReadInt32();
       int Length = ~BR.ReadInt32();
     if (Length < 0 || Offset < 0 || Offset + Length > DataBytes) {
       TL.Clear();
       break;
     }
     BR.BaseStream.Position = HeaderBytes + EntryBytes + Offset;
       BinaryReader EntryBR = new BinaryReader(new MemoryStream(BR.ReadBytes(Length)));
       bool ItemAdded = false;
     {
     Things.DMSGStringBlock SB = new Things.DMSGStringBlock();
       if (SB.Read(EntryBR, E, i)) {
     TL.Add(SB);
     ItemAdded = true;
       }
     }
     EntryBR.Close();
     if (!ItemAdded) {
       TL.Clear();
       break;
     }
     if (ProgressCallback != null)
       ProgressCallback(null, (double) (i + 1) / EntryCount);
       }
       return TL;
 }
Esempio n. 13
0
 public override ThingList Load(BinaryReader BR, ProgressCallback ProgressCallback)
 {
     ThingList TL = new ThingList();
     if (ProgressCallback != null)
     {
         ProgressCallback(I18N.GetText("FTM:CheckingFile"), 0);
     }
     if (BR.BaseStream.Length < 4)
     {
         return TL;
     }
     uint FileSizeMaybe = BR.ReadUInt32();
     if (FileSizeMaybe != (0x10000000 + BR.BaseStream.Length - 4))
     {
         return TL;
     }
     uint FirstTextPos = (BR.ReadUInt32() ^ 0x80808080);
     if ((FirstTextPos % 4) != 0 || FirstTextPos > BR.BaseStream.Length || FirstTextPos < 8)
     {
         return TL;
     }
     if (ProgressCallback != null)
     {
         ProgressCallback(I18N.GetText("FTM:LoadingData"), 0);
     }
     uint EntryCount = FirstTextPos / 4;
     // The entries are usually, but not always, sequential in the file.
     // Because we need to know how long one entry is (no clear end-of-message marker), we need them in
     // sequential order.
     List<uint> Entries = new List<uint>((int)EntryCount + 1);
     Entries.Add(FirstTextPos);
     for (int i = 1; i < EntryCount; ++i)
     {
         Entries.Add(BR.ReadUInt32() ^ 0x80808080);
     }
     Entries.Add((uint)BR.BaseStream.Length - 4);
     Entries.Sort();
     for (uint i = 0; i < EntryCount; ++i)
     {
         if (Entries[(int)i] < 4 * EntryCount || 4 + Entries[(int)i] >= BR.BaseStream.Length)
         {
             TL.Clear();
             break;
         }
         Things.DialogTableEntry DTE = new Things.DialogTableEntry();
         if (!DTE.Read(BR, i, Entries[(int)i], Entries[(int)i + 1]))
         {
             TL.Clear();
             break;
         }
         if (ProgressCallback != null)
         {
             ProgressCallback(null, (double)(i + 1) / EntryCount);
         }
         TL.Add(DTE);
     }
     return TL;
 }
Esempio n. 14
0
 /// <summary>
 /// Initalizes the cache to contain a specified amount of scintilla editors.
 /// The callback onProgress is called after each editor is created.
 /// </summary>
 /// <param name="amount"></param>
 /// <param name="onProgress"></param>
 public bool InitialCache(int amount, ProgressCallback onProgress)
 {
     for (int i = 0; i < amount; i += 1)
     {
         this.p_Scintillas.Push(new ScintillaNet.Scintilla());
         onProgress(i + 1);
     }
     return true;
 }
Esempio n. 15
0
 public static ulong FindHexString(IDataStream stream, String searchString, ulong start, ProgressCallback callback)
 {
     searchString = searchString.Replace(" ", "");
     Byte[] search = new Byte[searchString.Length / 2];
     for (int i = 0; i < search.Length; i++) {
         search[i] = Byte.Parse(searchString.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);
     }
     return FindBytes(stream, search, start, callback);
 }
        /// <summary>
        /// Writes the log.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="stream">The stream.</param>
        /// <param name="callback">The callback for UI updates.</param>
        public void WriteLog(IExecutionContext context, Stream stream, ProgressCallback callback)
        {
            StringBuilder header = new StringBuilder("<", 64);
            StringBuilder rawData = new StringBuilder(64);
            ArrayList lineBytes = new ArrayList();

            using (BinaryWriter s = new BinaryWriter(stream, Encoding.ASCII))
            {
                foreach (PacketLog log in context.LogManager.Logs)
                {
                    for (int i = 0; i < log.Count; i++)
                    {
                        if (callback != null && (i & 0xFFF) == 0) // update progress every 4096th packet
                            callback(i, log.Count - 1);

                        Packet packet = log[i];
                        if (context.FilterManager.IsPacketIgnored(packet))
                            continue;

                        header.Length = 1;

                        AppendHeader(header, packet);

                        s.Write(header.ToString().ToCharArray());
                        s.Write((byte) 0x0D);
                        s.Write((byte) 0x0A);

                        packet.Position = 0;
                        while (packet.Position < packet.Length)
                        {
                            int byteCount = rawData.Length = 0;
                            lineBytes.Clear();
                            for (; byteCount < 16 && packet.Position < packet.Length; byteCount++)
                            {
                                int b = packet.ReadByte();
                                rawData.Append(b.ToString("X2")).Append(' ');
                                lineBytes.Add((byte) b);
                            }

                            s.Write(string.Format("{0,-50}", rawData).ToCharArray());
                            for (int j = 0; j < lineBytes.Count; j++)
                            {
                                byte lineByte = (byte) lineBytes[j];
                                if (lineByte < 32)
                                    lineByte = (byte) '.';
                                s.Write(lineByte);
                            }
                            s.Write((byte) 0x0D);
                            s.Write((byte) 0x0A);
                        }

                        s.Write((byte) 0x0D);
                        s.Write((byte) 0x0A);
                    }
                }
            }
        }
Esempio n. 17
0
        public Progress(Form parentForm)
        {
            if (parentForm == null)
                throw new ArgumentNullException("parentForm");

            m_parentForm = parentForm;
            m_progressForm = new ProgressForm();
            m_progressCallback = new ProgressCallback(ProgressCallback);
        }
Esempio n. 18
0
 static unsafe extern ErrorCode GetPicture(
     byte* buf,
     int len,
     ApiFlags flag,
     [Out] out BITMAPINFO** pHBInfo,
     [Out] out byte** pHBm,
     ProgressCallback lpPrgressCallback,
     int lData
     );
        /// <summary>
        /// Writes the log.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="stream">The stream.</param>
        /// <param name="callback">The callback for UI updates.</param>
        public void WriteLog(IExecutionContext context, Stream stream, ProgressCallback callback)
        {
            TimeSpan baseTime = new TimeSpan(0);
            ArrayList oids = new ArrayList();
            Hashtable bitsByOid = new Hashtable();
            using (StreamWriter s = new StreamWriter(stream))
            {
                foreach (PacketLog log in context.LogManager.Logs)
                {
                    for (int i = 0; i < log.Count; i++)
                    {
                        if (callback != null && (i & 0xFFF) == 0) // update progress every 4096th packet
                            callback(i, log.Count - 1);

                        StoC_0xA1_NpcUpdate npcUpdate = log[i] as StoC_0xA1_NpcUpdate;
                        if (npcUpdate == null) continue;
                        if ((npcUpdate.Temp & 0xF000) == 0) continue;
                        if ((npcUpdate.Temp & 0x0FFF) != 0) continue;

                        s.WriteLine(npcUpdate.ToHumanReadableString(baseTime, true));
                        if (!oids.Contains(npcUpdate.NpcOid))
                            oids.Add(npcUpdate.NpcOid);
                        ArrayList bitsList = (ArrayList) bitsByOid[npcUpdate.NpcOid];
                        if (bitsList == null)
                        {
                            bitsList = new ArrayList();
                            bitsByOid[npcUpdate.NpcOid] = bitsList;
                        }
                        int bits = npcUpdate.Temp >> 12;
                        if (!bitsList.Contains(bits))
                            bitsList.Add(bits);
                    }

                    int regionId;
                    int zoneId;
                    SortedList oidInfo = ShowKnownOidAction.MakeOidList(log.Count - 1, log, out regionId, out zoneId);
                    s.WriteLine("\n\noids for region {0}, zone {1}\n", regionId, zoneId);
                    foreach (DictionaryEntry entry in oidInfo)
                    {
                        ushort oid = (ushort) entry.Key;
                        if (!oids.Contains(oid)) continue;
                        ShowKnownOidAction.ObjectInfo objectInfo = (ShowKnownOidAction.ObjectInfo) entry.Value;
                        s.Write("0x{0:X4}: ", oid);
                        s.Write(objectInfo.ToString());
                        foreach (int bits in (ArrayList) bitsByOid[oid])
                        {
                            s.Write("\t0b{0}", Convert.ToString(bits, 2));
                        }
                        s.WriteLine();
                    }
                }
            }
        }
Esempio n. 20
0
 public override ThingList Load(BinaryReader BR, ProgressCallback ProgressCallback)
 {
     ThingList TL = new ThingList();
       if (ProgressCallback != null)
     ProgressCallback(I18N.GetText("FTM:CheckingFile"), 0);
       if (Encoding.ASCII.GetString(BR.ReadBytes(4)) != "menu")
     return TL;
       if (BR.ReadInt32() != 0x101)
     return TL;
       if (BR.ReadInt64() != 0x000)
     return TL;
       if (BR.ReadInt64() != 0)
     return TL;
       if (BR.ReadInt64() != 0)
     return TL;
       if (ProgressCallback != null)
     ProgressCallback(I18N.GetText("FTM:LoadingData"), 0);
       while (BR.BaseStream.Position + 0x10 <= BR.BaseStream.Length) {
     if (ProgressCallback != null)
       ProgressCallback(null, ((double) (BR.BaseStream.Position + 1) / BR.BaseStream.Length));
       long   Offset    = BR.BaseStream.Position;
       string ShortName = Encoding.ASCII.GetString(BR.ReadBytes(4));
       uint   SizeInfo  = BR.ReadUInt32();
     if (BR.ReadUInt64() != 0) {
       TL.Clear();
       return TL;
     }
     if (BR.BaseStream.Position < BR.BaseStream.Length) {
       if (Encoding.ASCII.GetString(BR.ReadBytes(8)) != "menu    ") {
     TL.Clear();
     return TL;
       }
     string MenuName = Encoding.ASCII.GetString(BR.ReadBytes(8));
       // Used to be a full match but the JP data of 20061218 had pr_sc vs pr_1
       if (BR.ReadUInt32() != 0 || MenuName.Substring(0, 3) != ShortName.Substring(0, 3)) {
     TL.Clear();
     return TL;
       }
     int EntryCount = BR.ReadInt32();
       for (int i = 0; i < EntryCount; ++i) {
       Things.QuestInfo QI = new Things.QuestInfo();
     if (!QI.Read(BR, MenuName, Offset + 0x10)) {
       TL.Clear();
       return TL;
     }
     TL.Add(QI);
       }
     }
     BR.BaseStream.Position = Offset + ((SizeInfo & 0xFFFFFF80) >> 3);
       }
       return TL;
 }
Esempio n. 21
0
        /// <summary>
        ///  ascii version of the image loader. works fine. 
        /// but is dog-slow (when debugging only).  Would go faster if it read the whole file in at once instead
        /// of line by line? 
        /// </summary>
        /// <param name="filename">file containing the image to load.</param>
        /// <returns>string</returns>
        private void loadAscii(Stream file, out string segmentationPoints, ProgressCallback callback)
        {
            using (StreamReader sr = new StreamReader(file))
            {
                // grok out the magic number etc, which are in plain text.
                String line = sr.ReadLine();
                if (line != "P2")
                    throw new ApplicationException("unsupported PGM filetype, try type P2 or P5 only.");

                // spin through comments if any.
                segmentationPoints = string.Empty;
                while ((line = sr.ReadLine()).StartsWith("#"))
                    if (Regex.IsMatch(line, frmMain.SegmentPointRegex))
                        segmentationPoints = line.Substring(line.IndexOf("("));

                // parse out the width and height.
                string[] pieces;
                pieces = line.Split(' ');
                int imgCols = Int32.Parse(pieces[0]);
                int imgRows = Int32.Parse(pieces[1]);

                // Initialize the image with the size just read in.
                bitmap = new Bitmap(imgCols, imgRows);
                using (DirectBitmapWriter dba = new DirectBitmapWriter(bitmap))
                {

                    // get the max gray value.
                    maximumGrayValue = Int32.Parse(sr.ReadLine());

                    // Prepare to receive pixels: first row, first column
                    int pixelRow = 0, pixelColumn = 0;
                    while (pixelRow < imgRows)
                    {
                        // Each line will contain only a few of the pixels on a single row of the image.
                        line = sr.ReadLine();
                        string[] colEntries = line.Split(' ');
                        for (int ii = 0; ii < colEntries.Length; ii++)
                        {
                            if (colEntries[ii].Length == 0) continue; // skip "  " double spaces
                            byte thisColor = byte.Parse(colEntries[ii]);
                            dba.SetGrayPixel(pixelColumn, pixelRow, thisColor);
                            if (++pixelColumn == imgCols)
                            {
                                pixelColumn = 0;
                                pixelRow++;
                                callback(pixelRow * 100 / imgRows);
                            }
                        }
                    }
                }
            }
        }
        public async Task FindReferencesAsync(SerializableSymbolAndProjectId symbolAndProjectIdArg, DocumentId[] documentArgs)
        {
            var solution = await GetSolutionAsync().ConfigureAwait(false);

            var symbolAndProjectId = await symbolAndProjectIdArg.RehydrateAsync(
                solution, CancellationToken).ConfigureAwait(false);
            var documents = documentArgs?.Select(solution.GetDocument)
                                         .ToImmutableHashSet();

            var progressCallback = new ProgressCallback(this);
            await SymbolFinder.FindReferencesInCurrentProcessAsync(
                symbolAndProjectId, solution, progressCallback, documents, CancellationToken).ConfigureAwait(false);
        }
		/// <summary>
		/// Writes the log.
		/// </summary>
		/// <param name="context">The context.</param>
		/// <param name="stream">The stream.</param>
		/// <param name="callback">The callback for UI updates.</param>
		public void WriteLog(IExecutionContext context, Stream stream, ProgressCallback callback)
		{
			int playerOid = -1;
			byte playerLevel = 0;
			string playerClassName = "";
			Skills playerSkills = new Skills();
			
			using (StreamWriter s = new StreamWriter(stream))
			{
				foreach (PacketLog log in context.LogManager.Logs)
				{
					for (int i = 0; i < log.Count; i++)
					{
						if (callback != null && (i & 0xFFF) == 0) // update progress every 4096th packet
							callback(i, log.Count - 1);

						Packet pak = log[i];
						if (pak is StoC_0x20_PlayerPositionAndObjectID)
						{
							StoC_0x20_PlayerPositionAndObjectID plr = (StoC_0x20_PlayerPositionAndObjectID) pak;
							playerOid = plr.PlayerOid;
#if SHOW_PACKETS
							s.WriteLine("playerOid:0x{0:X4}", playerOid);
#endif
						}
						else if (pak is StoC_0x16_VariousUpdate)
						{
							// Name, level, class
							StoC_0x16_VariousUpdate stat = (StoC_0x16_VariousUpdate) pak;
							if (stat.SubCode == 3)
							{
								StoC_0x16_VariousUpdate.PlayerUpdate subData = (StoC_0x16_VariousUpdate.PlayerUpdate) stat.SubData;
								playerLevel = subData.playerLevel;
								playerClassName = subData.className;
#if SHOW_PACKETS
								s.WriteLine("{0, -16} 0x16:3 class:{1} level:{2}", pak.Time.ToString(), playerClassName, playerLevel);
#endif
							}
						}
						else if (pak is StoC_0xAF_Message)
						{
							StoC_0xAF_Message msg = (StoC_0xAF_Message) pak;
#if SHOW_PACKETS
//							s.WriteLine("{0, -16} 0xAF 0x{1:X2} {2}", pak.Time.ToString(), msg.Type, msg.Text);
#endif
						}
					}
				}
			}
		}
        /// <summary>
        /// Writes the log.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="stream">The stream.</param>
        /// <param name="callback">The callback for UI updates.</param>
        public void WriteLog(IExecutionContext context, Stream stream, ProgressCallback callback)
        {
            using (StreamWriter s = new StreamWriter(stream))
            {
                int region = 0;
                Hashtable keeps = new Hashtable();
                s.WriteLine("<KeepComponent>");
                foreach (PacketLog log in context.LogManager.Logs)
                {
                    for (int i = 0; i < log.Count; i++)
                    {
                        if (callback != null && (i & 0xFFF) == 0) // update progress every 4096th packet
                            callback(i, log.Count - 1);

                        Packet pak = log[i];
                        if (pak is StoC_0x20_PlayerPositionAndObjectID_171)
                        {
                            StoC_0x20_PlayerPositionAndObjectID_171 reg20 = (StoC_0x20_PlayerPositionAndObjectID_171)pak;
                            region = reg20.Region;
                        }
                        else if (pak is StoC_0xB7_RegionChange)
                        {
                            StoC_0xB7_RegionChange regB7 = (StoC_0xB7_RegionChange)pak;
                            region = regB7.RegionId;
                        }
                        else if (pak is StoC_0x6C_KeepComponentOverview)
                        {
                            StoC_0x6C_KeepComponentOverview partCreate = (StoC_0x6C_KeepComponentOverview)pak;
            //							if (region != 163) continue;
            //							if (partCreate.KeepId < 256) continue;
                            string key = "KEEPID-" + partCreate.KeepId + "-WALLID-" + partCreate.ComponentId;
                            if (keeps.ContainsKey(key)) continue;
                            keeps[key] = partCreate;
                            s.WriteLine("  <KeepComponent>");
                            s.WriteLine(string.Format("    <KeepComponent_ID>{0}</KeepComponent_ID>", key));
                            s.WriteLine(string.Format("    <X>{0}</X>", (sbyte)partCreate.X));
                            s.WriteLine(string.Format("    <Y>{0}</Y>", (sbyte)partCreate.Y));
                            s.WriteLine(string.Format("    <Heading>{0}</Heading>", partCreate.Heading));
            //							s.WriteLine(string.Format("    <Height>{0}</Height>", partCreate.Height)); // in DOL height calced depended on keep level
                            s.WriteLine(string.Format("    <Health>{0}</Health>", /*partCreate.Health*/100));
                            s.WriteLine(string.Format("    <Skin>{0}</Skin>", partCreate.Skin));
                            s.WriteLine(string.Format("    <KeepID>{0}</KeepID>", partCreate.KeepId));
                            s.WriteLine(string.Format("    <ID>{0}</ID>", partCreate.ComponentId));
                            s.WriteLine("  </KeepComponent>");
                        }
                    }
                }
                s.WriteLine("</KeepComponent>");
            }
        }
Esempio n. 25
0
		public void DoFilter(FilterParams filterParams, int startLine, int maxCount, ProgressCallback progressCallback)
		{
			FilterResultLines.Clear();
			LastFilterLinesList.Clear();
			FilterHitList.Clear();
			_filterHitDict.Clear();
			_filterReadyList.Clear();
			_filterResultDict.Clear();
			_lastFilterLinesDict.Clear();
			_filterReadyList.Clear();
			_filterWorkerList.Clear();
			_shouldStop = false;
				
			int interval = maxCount / ThreadCount;
			if (interval < 1)
			{
				interval = 1;
			}
			int workStartLine = startLine;
			List<WaitHandle> handleList = new List<WaitHandle>();
			_progressLineCount = 0;
			_progressCallback = progressCallback;
			while (workStartLine < startLine + maxCount)
			{
				if (workStartLine + interval > maxCount)
				{
					interval = maxCount - workStartLine;
					if (interval == 0)
					{
						break;
					}
				}
				Logger.logInfo("FilterStarter starts worker for line " + workStartLine + ", lineCount " + interval);
				WorkerFx workerFx = new WorkerFx(DoWork);
				IAsyncResult ar = workerFx.BeginInvoke(filterParams, workStartLine, interval, ThreadProgressCallback, FilterDoneCallback, workerFx);
				workStartLine += interval;
				handleList.Add(ar.AsyncWaitHandle);
			}
			WaitHandle[] handles = handleList.ToArray();
			// wait for worker threads completion
			if (handles.Length > 0)
			{
				WaitHandle.WaitAll(handles);
			}
		
			MergeResults();
		}
Esempio n. 26
0
        public virtual void Load(ProgressCallback progressNotifier, OnContinueExceptionCallback exceptionNotifier)
        {
            bool needLoadData = Producer != null;

            if (needLoadData)
                Verify();

            OnLoadStart();

            if (needLoadData)
            {
                #region RDF TableColumnsMetadata
                foreach (TableColumnsMetadataItem item in Params.TableColumnsMetadata.PropertyToTypeColumnsMetadata.Mappings)
                {
                    item.EntitySet = Params.TableMetadataEntity.EntitySet;
                    Entity TableColumnsMetadataEntity = TableColumnsMetadata.GetSchemaEntity(item);
                    Processor.ProcessRdfMetadataEntity(DataLoaderConstants.TableColumnsMetadataTableName, TableColumnsMetadataEntity);
                }
                #endregion

                int count = 0;
                int loadThreadsCount = int.Parse(ConfigurationManager.AppSettings["LoadThreadsCount"]);
                var options = new ParallelOptions { MaxDegreeOfParallelism = loadThreadsCount };

                Parallel.ForEach(Producer.GetEntitiesEnumerator(exceptionNotifier, Params), options, i =>
                {
                    try
                    {
                        Processor.ProcessEntity(Params.TableMetadataEntity.EntitySet, i);
                    }
                    catch (Exception ex)
                    {
                        if (exceptionNotifier != null)
                            exceptionNotifier(new EntityProcessingException(i.ToString(), ex));
                    }
                    if (progressNotifier != null)
                        progressNotifier(Producer.EntityCount, Interlocked.Increment(ref count));
                });
            }

            Processor.ProcessTableMetadataEntity(DataLoaderConstants.EntitySetTableMetadata, Params.TableMetadataEntity);

            if (needLoadData)
            {
                Processor.ProcessEntityMetadataEntity(DataLoaderConstants.EntitySetEntityMetadata, Producer.SchemaEntity);
            }
        }
        public async Task FindReferencesAsync(
            SerializableSymbolAndProjectId symbolAndProjectIdArg, SerializableDocumentId[] documentArgs, 
            byte[] solutionChecksum)
        {
            var solution = await RoslynServices.SolutionService.GetSolutionAsync(
                new Checksum(solutionChecksum), CancellationToken).ConfigureAwait(false);

            var symbolAndProjectId = await symbolAndProjectIdArg.RehydrateAsync(
                solution, CancellationToken).ConfigureAwait(false);
            var documents = documentArgs?.Select(a => a.Rehydrate())
                                         .Select(solution.GetDocument)
                                         .ToImmutableHashSet();

            var progressCallback = new ProgressCallback(this);
            await SymbolFinder.FindReferencesInCurrentProcessAsync(
                symbolAndProjectId, solution, progressCallback, documents, CancellationToken).ConfigureAwait(false);
        }
        public Form1() : base()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // need to add any constructor code after InitializeComponent call
            //
            m_callback_NewText  = new NewTextCallback ( this.Callback_NewText  );
            m_callback_Progress = new ProgressCallback( this.Callback_Progress );


            m_usbDiscovery = new _DBG.UsbDeviceDiscovery();

            m_usbDiscovery.OnDeviceChanged += new _DBG.UsbDeviceDiscovery.DeviceChangedEventHandler( OnDeviceChanged );
        }
Esempio n. 29
0
 public override ThingList Load(BinaryReader BR, ProgressCallback ProgressCallback)
 {
     ThingList TL = new ThingList();
       if (ProgressCallback != null)
     ProgressCallback(I18N.GetText("FTM:CheckingFile"), 0);
       if (BR.BaseStream.Length < 0x38 || BR.BaseStream.Position != 0)
     return TL;
     FFXIEncoding E = new FFXIEncoding();
       // Skip (presumably) fixed portion of the header
       if ((E.GetString(BR.ReadBytes(8)) != "d_msg".PadRight(8, '\0')) || BR.ReadUInt16() != 1 || BR.ReadUInt32() != 0 || BR.ReadUInt16() != 2 || BR.ReadUInt32() != 3)
     return TL;
       // Read the useful header fields
     uint EntryCount = BR.ReadUInt32();
       if (BR.ReadUInt32() != 1)
     return TL;
     uint FileSize = BR.ReadUInt32();
       if (FileSize != BR.BaseStream.Length)
     return TL;
     uint HeaderSize = BR.ReadUInt32();
       if (HeaderSize != 0x38)
     return TL;
     uint EntryBytes = BR.ReadUInt32();
       if (EntryBytes != EntryCount * 36)
     return TL;
     uint DataBytes  = BR.ReadUInt32();
       if (FileSize != 0x38 + EntryBytes + DataBytes)
     return TL;
       // 12 NUL bytes
       if (BR.ReadUInt32() != 0 || BR.ReadUInt32() != 0 || BR.ReadUInt32() != 0)
     return TL;
       if (ProgressCallback != null)
     ProgressCallback(I18N.GetText("FTM:LoadingData"), 0);
       for (uint i = 0; i < EntryCount; ++i) {
       Things.DMSGStringTableEntry DSTE = new Things.DMSGStringTableEntry();
     if (!DSTE.Read(BR, E, i, EntryBytes, DataBytes)) {
       TL.Clear();
       break;
     }
     if (ProgressCallback != null)
       ProgressCallback(null, (double) (i + 1) / EntryCount);
     TL.Add(DSTE);
       }
       return TL;
 }
Esempio n. 30
0
 public override ThingList Load(BinaryReader BR, ProgressCallback ProgressCallback)
 {
     ThingList TL = new ThingList();
     if (ProgressCallback != null)
     {
         ProgressCallback(I18N.GetText("FTM:CheckingFile"), 0);
     }
     if ((BR.BaseStream.Length % 0xC00) != 0 || BR.BaseStream.Length < 0xc000 || BR.BaseStream.Position != 0)
     {
         return TL;
     }
     // First deduce the type of item data is in the file.
     Item.Type T;
     Item.DeduceType(BR, out T);
     // Now read the items
     if (ProgressCallback != null)
     {
         ProgressCallback(I18N.GetText("FTM:LoadingData"), 0);
     }
     long ItemCount = BR.BaseStream.Length / 0xC00;
     long CurrentItem = 0;
     while (BR.BaseStream.Position < BR.BaseStream.Length)
     {
         Item I = new Item();
         if (!I.Read(BR, T))
         {
             TL.Clear();
             break;
         }
         if (ProgressCallback != null)
         {
             ProgressCallback(null, (double)++CurrentItem / ItemCount);
         }
         TL.Add(I);
         // A currency DAT currently has 1 "real" item and 15 dummy entries (all NULs); a better thing to do would be to break if such a dummy entry
         // is seen, but since we currently detect currency from its 0xFFFF ID, this is safe enough for now.
         if (BR.BaseStream.Length == 0xc000 && T == Item.Type.Currency)
         {
             break;
         }
     }
     return TL;
 }
Esempio n. 31
0
 public BitwiseOperation(ByteBuffer bb, byte[] ba, Util.Range range, BitwiseOperationsWidget.OperationType ot, ProgressCallback pc,
                         AsyncCallback ac, bool glibIdle) : base(pc, ac, glibIdle)
 {
     byteBuffer    = bb;
     byteArray     = ba;
     this.range    = range;
     operationType = ot;
     currentOffset = range.Start;
 }
Esempio n. 32
0
 public int DoFilter(FilterParams filterParams, int startLine, int maxCount, ProgressCallback progressCallback)
 {
     return(DoFilter(filterParams, startLine, maxCount, this.FilterResultLines, this.LastFilterLinesList,
                     this.FilterHitList, progressCallback));
 }
Esempio n. 33
0
        //Розкодувує файли, перед викликом не забути присвоїти потрібний IV
        //streamOffset	- _stream.Position
        //outputStream	- куди зберігати розшифровані дані
        //dataSize		- read count
        public void ReadDecrypt(long streamOffset, Stream outputStream, long dataSize, AesCryptoServiceProvider AES, ProgressCallback Progress)
        {
            byte[]       buffer   = new byte[1048576];
            CryptoStream cs       = new CryptoStream(_stream, AES.CreateDecryptor(), CryptoStreamMode.Read);
            long         max      = dataSize;
            long         position = streamOffset;

            while (max > 0)
            {
                lock (_ReadWriteLock)
                {
                    _stream.Position = position;
                    int count = cs.Read(buffer, 0, (int)Math.Min(buffer.Length, max));
                    outputStream.Write(buffer, 0, count);
                    position = _stream.Position;
                    max     -= count;
                }

                Progress?.Invoke((dataSize - max) / (double)dataSize * 100.0);
            }
        }
Esempio n. 34
0
        //Кодує файли, перед викликом не забути присвоїти потрібний IV
        public void WriteEncrypt(long streamOffset, Stream inputStream, AesCryptoServiceProvider AES, out byte[] Hash, ProgressCallback Progress)
        {
            lock (_WriteLock)
            {
                if (streamOffset > _stream.Length)
                {
                    throw new Exception("");
                }

                if (AES.Padding == PaddingMode.None)
                {
                    _Length = streamOffset + inputStream.Length - inputStream.Position;                     //Якщо файл кодується з доповненням, то тут може бути менше значення чим потрібно.
                }
                else
                {
                    _Length = streamOffset + (long)Crypto.GetMod16((UInt64)(inputStream.Length - inputStream.Position));
                }

                byte[]       buffer   = new byte[1048576];
                CryptoStream cs       = new CryptoStream(_stream, AES.CreateEncryptor(), CryptoStreamMode.Write);
                MD5          md5      = MD5.Create();
                long         position = streamOffset;

                while (inputStream.Position < inputStream.Length)
                {
                    int count = inputStream.Read(buffer, 0, buffer.Length);
                    lock (_ReadWriteLock)
                    {
                        _stream.Position = position;
                        cs.Write(buffer, 0, count);
                        position = _stream.Position;
                    }

                    if (inputStream.Position < inputStream.Length)
                    {
                        md5.TransformBlock(buffer, 0, count, buffer, 0);
                    }
                    else
                    {
                        md5.TransformFinalBlock(buffer, 0, count);
                    }

                    Progress?.Invoke(inputStream.Position / (double)inputStream.Length * 100.0);
                }

                lock (_ReadWriteLock)
                {
                    _stream.Position = position;
                    cs.FlushFinalBlock();
                }

                Hash = md5.Hash;
            }
        }
Esempio n. 35
0
        /// <summary>
        /// Adds all files within a specified directory to the archive.
        /// </summary>
        /// <param name="pathInTar">Relative path in tar file.</param>
        /// <param name="directory">The root directory to be searched for files.</param>
        /// <param name="fileMask">The file mask.</param>
        /// <param name="search">The search option.</param>
        /// <param name="callback">The callback used during stream copy.</param>
        /// <param name="userItem">A user item for the callback.</param>
        /// <returns>Returns true if the operation completed, false if the callback used <see cref="ProgressEventArgs.Break"/>.</returns>
        public bool AddDirectory(string pathInTar, string directory, string fileMask = "*.*", SearchOption search = SearchOption.AllDirectories, ProgressCallback callback = null, object userItem = null)
        {
            if (tarStream == null)
            {
                throw new ObjectDisposedException(nameof(TarWriter));
            }

            foreach (var file in Directory.GetFiles(directory, fileMask, search))
            {
                if (!file.StartsWith(directory))
                {
                    throw new InvalidOperationException("Invalid relative path!");
                }

                var name = pathInTar + '/' + file.Substring(directory.Length);
                using (var stream = File.OpenRead(file))
                {
                    var result = AddFile(name, stream, (int)stream.Length, callback, userItem);
                    if (!result)
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Esempio n. 36
0
        public static bool GenerateISOImage(string isopath, string cdroot, string volumelabel, ProgressCallback progressCallback)
        {
            var runningDirectory = Process.GetCurrentProcess().MainModule.FileName.Contains("\\") ? string.Join("\\", Process.GetCurrentProcess().MainModule.FileName.Split('\\').Reverse().Skip(1).Reverse()) : "";

            string cdimagepath = Path.Combine(runningDirectory, "CDImage", "cdimage.exe");

            var setupexe     = Path.Combine(cdroot, "setup.exe");
            var creationtime = File.GetCreationTimeUtc(setupexe);
            var timestamp    = creationtime.ToString("MM/dd/yyyy,hh:mm:ss");

            ProcessStartInfo processStartInfo = new ProcessStartInfo(cdimagepath,
                                                                     $"\"-bootdata:2#p0,e,b{cdroot}\\boot\\etfsboot.com#pEF,e,b{cdroot}\\efi\\Microsoft\\boot\\efisys.bin\" -o -h -m -u2 -udfver102 -t{timestamp} -l{volumelabel}  \"{cdroot}\" \"{isopath}\"");

            processStartInfo.UseShellExecute       = false;
            processStartInfo.WindowStyle           = ProcessWindowStyle.Hidden;
            processStartInfo.RedirectStandardError = true;
            processStartInfo.CreateNoWindow        = true;

            Process process = new Process();

            process.StartInfo = processStartInfo;

            try
            {
                process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) =>
                {
                    if (e.Data != null && e.Data.Contains("%"))
                    {
                        var percent = int.Parse(e.Data.Split(' ').First(x => x.Contains("%")).Replace("%", ""));
                        progressCallback?.Invoke($"Building {isopath}", percent, false);
                    }
                };
                process.Start();
                process.BeginErrorReadLine();
                process.WaitForExit();
                return(process.ExitCode == 0);
            }
            catch
            {
                return(false);
            }
        }
Esempio n. 37
0
 static extern int ChangePIN(string szPIN, string szNewPIN, int[] attempts, ProgressCallback progressCallBack);
Esempio n. 38
0
 static extern int AbbinaCIE(string szPAN, string szPIN, int[] attempts, ProgressCallback progressCallBack, CompletedCallback completedCallBack);
Esempio n. 39
0
        /// <param name="a">Параметр алгоритма для вычисления весовых коэффициентов</param>
        /// <param name="relax">
        ///     При использовании метода релаксации задействовано в два раза меньше памяти и вычисления производятся
        ///     на-месте. Для устанения коллизий с совместным доступом производится раскраска точек красное-чёрное для обработки
        ///     их по-очереди
        /// </param>
        /// <param name="epsilon">Точность вычислений</param>
        /// <param name="gridSize"></param>
        /// <param name="blockSize"></param>
        /// <param name="trace"></param>
        public static IEnumerable <double> ExecuteLaplaceSolver(double epsilon, double a, bool relax, int gridSize = 0,
                                                                int blockSize = 0,
                                                                ITrace trace  = null)
        {
            AppendLineCallback appendLineCallback = trace != null ? trace.AppendLineCallback : null;
            ProgressCallback   progressCallback   = trace != null ? trace.ProgressCallback : null;
            CompliteCallback   compliteCallback   = trace != null ? trace.CompliteCallback : null;

            if (gridSize > 0)
            {
                _gridSize3 = gridSize;
                _gridSize2 = blockSize;
                _gridSize1 = blockSize;
            }
            if (blockSize > 0)
            {
                _blockSize3 = blockSize;
                _blockSize2 = blockSize;
                _blockSize1 = blockSize;
            }

            Debug.Assert(_sizes.Length == _lengths.Length);
            Debug.Assert(_sizes.Aggregate(Int32.Mul) > 0);
            Debug.Assert(_lengths.Aggregate(Double.Mul) > 0.0);

            if (appendLineCallback != null)
            {
                appendLineCallback("Размер массива:");
            }
            for (int i = 0; i < _sizes.Length; i++)
            {
                if (appendLineCallback != null)
                {
                    appendLineCallback(string.Format("Размер массива по оси № {0}:\t{1}", i, _sizes[i]));
                }
            }

            // Степень дифференциального оператора
            // Реализовано только для оператора Лапласа
            // Для больших степеней надо использовать соответствующие полиномы большей степени
            // Для дифференциального оператора степени 2 (оператора Лапласа) полином имеет степень 1
            // Для дифференциального оператора степени rank полином имеет степень rank-1
            const int rank = 2;

            _extV    = new int[_sizes.Length + 1];
            _intV    = new int[_sizes.Length + 1];
            _intV[0] = _extV[0] = 1;

            for (int i = 1; i <= _sizes.Length; i++)
            {
                _extV[i] = _extV[i - 1] * _sizes[i - 1];
                _intV[i] = _intV[i - 1] * (_sizes[i - 1] - rank);
            }

            // Расчёт коэффициентов слагаемых
            if (appendLineCallback != null)
            {
                appendLineCallback("Расчёт коэффициентов слагаемых");
            }
            _w = new double[_sizes.Length + 1];
            double sum2 = 0;

            for (int i = 0; i < _sizes.Length; i++)
            {
                sum2 += (_sizes[i] - 1) * (_sizes[i] - 1) / (_lengths[i] * _lengths[i]);
            }
            for (int i = 0; i < _sizes.Length; i++)
            {
                _w[i] = (_sizes[i] - 1) * (_sizes[i] - 1) / (_lengths[i] * _lengths[i]) / sum2 / (1.0 + a);
            }
            _w[_sizes.Length] = (a - 1.0) / (1.0 + a);

            if (appendLineCallback != null)
            {
                appendLineCallback("Коэффициенты:");
            }
            for (int i = 0; i < _sizes.Length; i++)
            {
                if (appendLineCallback != null)
                {
                    appendLineCallback(string.Format("Коэффициенты по оси № {0} (у двух точек):\t{1}", i, _w[i]));
                }
            }
            if (appendLineCallback != null)
            {
                appendLineCallback(string.Format("Коэффициент у средней точки:\t{0}", _w[_sizes.Length]));
            }

            if (appendLineCallback != null && relax)
            {
                appendLineCallback("Используется релаксация");
            }

            CudafyModule km = CudafyTranslator.Cudafy();

            GPGPU gpu = CudafyHost.GetDevice();

            gpu.LoadModule(km);

            if (appendLineCallback != null)
            {
                appendLineCallback("Выделяем видеоресурсы");
            }

            //  При использовании метода релаксации задействовано в два раза меньше памяти и вычисления производятся
            //  на-месте. Для устанения коллизий с совместным доступом производится раскраска точек красное-чёрное для обработки
            //  их по-очереди
            double[][] devA = relax
                ? new[] { gpu.Allocate <double>(_a.Length) }
                : new[] { gpu.Allocate <double>(_a.Length), gpu.Allocate <double>(_a.Length) };

            double[][] devB =
            {
                gpu.Allocate <double>(_gridSize3 * _blockSize3),
                gpu.Allocate(_b)
            };
            double[][] devC =
            {
                gpu.Allocate <double>(_gridSize3 * _blockSize3),
                gpu.Allocate(_c)
            };
            int[]   devSizes = gpu.Allocate(_sizes);
            int[][] devV     =
            {
                gpu.Allocate(_extV),
                gpu.Allocate(_intV)
            };
            double[] devW = gpu.Allocate(_w);

            if (appendLineCallback != null)
            {
                appendLineCallback("Копируем данные в видеопамять");
            }
            gpu.CopyToDevice(_a, devA[0]);
            gpu.CopyToDevice(_sizes, devSizes);
            gpu.CopyToDevice(_extV, devV[0]);
            gpu.CopyToDevice(_intV, devV[1]);
            gpu.CopyToDevice(_w, devW);

            if (!relax)
            {
                if (appendLineCallback != null)
                {
                    appendLineCallback("Дублируем массив в видеопамяти");
                }
                gpu.Launch(_gridSize3, _blockSize3, "Copy", devA[0], devA[1]);
            }
            var queue = new StackListQueue <double>();

            for (int step = 0;; step++)
            {
                //if (AppendLineCallback != null) AppendLineCallback(string.Format("Шаг итерации № {0}", step));

                // Вычисляем среднее взвешенное соседних точек
                //if (AppendLineCallback != null) AppendLineCallback("Вычисляем среднее взвешенное соседних точек");
                if (!relax)
                {
                    gpu.Launch(_gridSize3, _blockSize3, "LaplaceSolver", devA[step & 1], devA[1 - (step & 1)],
                               devSizes,
                               devV[0], devV[1],
                               devW,
                               devB[0], devC[0]);
                }
                else
                {
                    gpu.Launch(_gridSize3, _blockSize3, "Clear", devB[0]);
                    gpu.Launch(_gridSize3, _blockSize3, "Clear", devC[0]);

                    for (int p = 0; p < 2; p++)
                    {
                        gpu.Launch(_gridSize3, _blockSize3, "LaplaceSolverWithRelax", devA[0],
                                   devSizes,
                                   devV[0], devV[1],
                                   devW,
                                   devB[0], devC[0],
                                   p);
                    }
                }

                // Суммируем амплитуды изменений, посчитанные в каждом процессе
                gpu.Launch(_gridSize1, _blockSize1, "Sum", devB[0], devB[1]);
                gpu.Launch(_gridSize1, _blockSize1, "Sum", devC[0], devC[1]);

                gpu.CopyFromDevice(devB[1], _b);
                gpu.CopyFromDevice(devC[1], _c);
                double deltaSum  = _b[0];
                double squareSum = _c[0];

                //if (AppendLineCallback != null)
                //    AppendLineCallback(string.Format("Амплитуда изменений = {0}/{1}", deltaSum, squareSum));

                queue.Enqueue(deltaSum / squareSum);

                if (deltaSum > epsilon * squareSum)
                {
                    continue;
                }

                if (appendLineCallback != null)
                {
                    appendLineCallback(string.Format("Потребовалось {0} итераций", step + 1));
                }

                // Если изменения меньше заданной величины, то возвращаем вычисленные значения
                if (appendLineCallback != null)
                {
                    appendLineCallback("Копируем массив из видеопамяти в массив на компьютере");
                }
                if (!relax)
                {
                    gpu.CopyFromDevice(devA[1 - (step & 1)], _a);
                }
                else
                {
                    gpu.CopyFromDevice(devA[0], _a);
                }

                break;
            }
            // free the memory allocated on the GPU
            if (appendLineCallback != null)
            {
                appendLineCallback("Освобождаем видеоресурсы");
            }
            gpu.FreeAll();
            return(queue);
        }
Esempio n. 40
0
 public HttpDownloadHandler(FileStream fileStream, ProgressCallback downloadCallback, FinishedCallback finishedCallback)
 {
     mFileStream       = fileStream;
     mDownloadCallback = downloadCallback;
     mFinishedCallback = finishedCallback;
 }
Esempio n. 41
0
        public static string Download(string URL_, string ToPath_, HttpFileExistOption existOpt, ProgressCallback progressCallback, FinishedCallback finishedCallback)
        {
            var guid = System.Guid.NewGuid().ToString();

            GameObject go     = new GameObject("HttpSender(" + HttpMethod.DOWNLOAD.ToString() + ")" + guid);
            var        sender = go.AddComponent <HttpSender>();

            sender.GUID              = guid;
            sender.Url               = URL_;
            sender.Data              = null;
            sender.Method            = HttpMethod.DOWNLOAD;
            sender.Timeout           = 60;
            sender.RefHold           = ReferenceHold.WaitForComplete;
            sender.FilePath          = ToPath_;
            sender.mProgressCallback = progressCallback;
            sender.mFinishedCallback = finishedCallback;
            sender.ExistOption       = existOpt;
            sender.Completion        = null;
            if (!Instance._senders.ContainsKey(guid))
            {
                Instance._senders.Add(guid, sender);
            }
            sender.Send();

            return(guid);
        }
Esempio n. 42
0
 public static extern void OnAction([MarshalAs(UnmanagedType.FunctionPtr)] ProgressCallback callbackPointer);
Esempio n. 43
0
        /// <summary>
        /// Copy the contents of one <see cref="Stream"/> to another.
        /// </summary>
        /// <param name="source">The stream to source data from.</param>
        /// <param name="destination">The stream to write data to.</param>
        /// <param name="buffer">The buffer to use during copying.</param>
        /// <param name="progressHandler">The <see cref="ProgressCallback">progress handler delegate</see> to use.</param>
        /// <param name="updateInterval">The minimum <see cref="TimeSpan"/> between progress updates.</param>
        /// <param name="sender">The source for this event.</param>
        /// <param name="name">The name to use with the event.</param>
        /// <param name="fixedTarget">A predetermined fixed target value to use with progress updates.
        /// If the value is negative the target is calculated by looking at the stream.</param>
        /// <remarks>This form is specialised for use within #Zip to support events during archive operations.</remarks>
        public static void Copy(Stream source, Stream destination, byte[] buffer, ProgressCallback progressHandler, TimeSpan updateInterval, object sender, string name, long fixedTarget)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            if (destination == null)
            {
                throw new ArgumentNullException(nameof(destination));
            }

            if (buffer == null)
            {
                throw new ArgumentNullException(nameof(buffer));
            }

            // Ensure a reasonable size of buffer is used without being prohibitive.
            if (buffer.Length < 128)
            {
                throw new ArgumentException("Buffer is too small", nameof(buffer));
            }

            if (progressHandler == null)
            {
                throw new ArgumentNullException(nameof(progressHandler));
            }

            var  marker    = DateTime.Now;
            long processed = 0;
            long target    = 0;

            if (fixedTarget >= 0)
            {
                target = fixedTarget;
            }
            else if (source.CanSeek)
            {
                target = source.Length - source.Position;
            }

            // Always fire 0% progress..
            var args = new ProgressEventArgs(name, processed, 0, target, true);

            progressHandler(sender, args);
            var copying = !args.Break;

            var progressFired = true;
            var done          = 0;

            while (copying)
            {
                var bytesRead = source.Read(buffer, 0, buffer.Length);
                if (bytesRead > 0)
                {
                    processed    += bytesRead;
                    progressFired = false;
                    destination.Write(buffer, 0, bytesRead);
                    done += bytesRead;
                }
                else
                {
                    destination.Flush();
                    copying = false;
                }

                if (DateTime.Now - marker > updateInterval)
                {
                    progressFired = true;
                    marker        = DateTime.Now;
                    args          = new ProgressEventArgs(name, processed, done, target, true);
                    progressHandler(sender, args);
                    done    = 0;
                    copying = !args.Break;
                }
            }

            if (!progressFired)
            {
                args = new ProgressEventArgs(name, processed, done, target, false);
                progressHandler(sender, args);
            }
        }
Esempio n. 44
0
 protected abstract GameEngineSearchResult DoSearch(PositionWithHistory curPositionAndMoves,
                                                    SearchLimit searchLimit,
                                                    List <GameMoveStat> gameMoveHistory,
                                                    ProgressCallback callback,
                                                    bool verbose);
Esempio n. 45
0
 protected Request(ProgressCallback progress)
 {
     m_Progress = progress;
 }
Esempio n. 46
0
 static extern int UnlockPIN(string szPUK, string szNewPIN, int[] attempts, ProgressCallback progressCallBack);
Esempio n. 47
0
        public override ThingList Load(BinaryReader BR, ProgressCallback ProgressCallback)
        {
            ThingList TL = new ThingList();

            if (ProgressCallback != null)
            {
                ProgressCallback(I18N.GetText("FTM:CheckingFile"), 0);
            }
            if (BR.BaseStream.Position != 0)
            {
                goto Failed;
            }
            if (Encoding.ASCII.GetString(BR.ReadBytes(4)) != "menu")
            {
                goto Failed;
            }
            if (BR.ReadInt32() != 0x101)
            {
                goto Failed;
            }
            if (BR.ReadInt64() != 0)
            {
                goto Failed;
            }
            if (BR.ReadInt64() != 0)
            {
                goto Failed;
            }
            if (BR.ReadInt64() != 0)
            {
                goto Failed;
            }
            if (ProgressCallback != null)
            {
                ProgressCallback(I18N.GetText("FTM:LoadingData"), (double)BR.BaseStream.Position / BR.BaseStream.Length);
            }
            string firstFourBytes = Encoding.ASCII.GetString(BR.ReadBytes(4));

            {
                // Part 0: Monster?
                if (firstFourBytes != "mon_")
                {
                    goto Part1;
                }
                uint SizeInfo = BR.ReadUInt32();
                if (BR.ReadInt64() != 0)
                {
                    goto Failed;
                }
                uint BlockSize = (SizeInfo & 0xFFFFFF80) >> 3;
                if ((BlockSize - 0x10) % 0x58 != 0)
                {
                    goto Failed;
                }
                uint EntryCount = (BlockSize - 0x10) / 0x58;
                while (EntryCount-- > 0)
                {
                    Things.MonsterSpellInfo2 MSI2 = new Things.MonsterSpellInfo2();
                    if (!MSI2.Read(BR))
                    {
                        goto Failed;
                    }
                    if (ProgressCallback != null)
                    {
                        ProgressCallback(null, (double)BR.BaseStream.Position / BR.BaseStream.Length);
                    }
                    TL.Add(MSI2);
                }
            }
            firstFourBytes = Encoding.ASCII.GetString(BR.ReadBytes(4));
Part1:
            {
                // Part 1: Spell Info
                if (firstFourBytes != "mgc_")
                {
                    goto Failed;
                }
                uint SizeInfo = BR.ReadUInt32();
                if (BR.ReadInt64() != 0)
                {
                    goto Failed;
                }
                uint BlockSize = (SizeInfo & 0xFFFFFF80) >> 3;
                if ((BlockSize - 0x10) % 0x58 != 0)
                {
                    goto Failed;
                }
                uint EntryCount = (BlockSize - 0x10) / 0x58;
                while (EntryCount-- > 0)
                {
                    Things.SpellInfo2 SI2 = new Things.SpellInfo2();
                    if (!SI2.Read(BR))
                    {
                        goto Failed;
                    }
                    if (ProgressCallback != null)
                    {
                        ProgressCallback(null, (double)BR.BaseStream.Position / BR.BaseStream.Length);
                    }
                    TL.Add(SI2);
                }
            }
            {
                // Part 2: Ability Info
                if (Encoding.ASCII.GetString(BR.ReadBytes(4)) != "comm")
                {
                    goto Failed;
                }
                uint SizeInfo = BR.ReadUInt32();
                if (BR.ReadInt64() != 0)
                {
                    goto Failed;
                }
                uint BlockSize = (SizeInfo & 0xFFFFFF80) >> 3;
                if ((BlockSize - 0x10) % 0x30 != 0)
                {
                    goto Failed;
                }
                uint EntryCount = (BlockSize - 0x10) / 0x30;
                while (EntryCount-- > 0)
                {
                    Things.AbilityInfo2 AI2 = new Things.AbilityInfo2();
                    if (!AI2.Read(BR))
                    {
                        goto Failed;
                    }
                    if (ProgressCallback != null)
                    {
                        ProgressCallback(null, (double)BR.BaseStream.Position / BR.BaseStream.Length);
                    }
                    TL.Add(AI2);
                }
            }
            {
                // Part 3: End Marker
                if (Encoding.ASCII.GetString(BR.ReadBytes(4)) != "end\0")
                {
                    goto Failed;
                }
                uint SizeInfo = BR.ReadUInt32();
                if (BR.ReadInt64() != 0)
                {
                    goto Failed;
                }
                uint BlockSize = (SizeInfo & 0xFFFFFF80) >> 3;
                if (BlockSize != 0x10) // Header only
                {
                    goto Failed;
                }
                if (ProgressCallback != null)
                {
                    ProgressCallback(null, (double)BR.BaseStream.Position / BR.BaseStream.Length);
                }
            }
            goto Done;
Failed:
            TL.Clear();
Done:
            return(TL);
        }
        /// <summary>
        /// Writes the log.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="stream">The stream.</param>
        /// <param name="callback">The callback for UI updates.</param>
        public void WriteLog(IExecutionContext context, Stream stream, ProgressCallback callback)
        {
            SortedList oidInfo           = new SortedList();
            IList      CombatWaitMessage = new ArrayList();
            Hashtable  styleIcons        = new Hashtable();
            Hashtable  plrInfo           = new Hashtable();

            weapons = new StoC_0x02_InventoryUpdate.Item[4];
            PlayerInfo playerInfo = null;            // = new PlayerInfo();

            int    playerOid = -1;
            string nameKey   = "";
            string statKey   = "";
            string plrName   = "";
            string plrClass  = "";
            int    plrLevel  = 0;
            int    countBC   = 0;

            using (StreamWriter s = new StreamWriter(stream))
            {
                foreach (PacketLog log in context.LogManager.Logs)
                {
                    for (int i = 0; i < log.Count; i++)
                    {
                        if (callback != null && (i & 0xFFF) == 0)                         // update progress every 4096th packet
                        {
                            callback(i, log.Count - 1);
                        }

                        Packet pak = log[i];
                        // Enter region (get new self OID)
                        if (pak is StoC_0x20_PlayerPositionAndObjectID)
                        {
                            StoC_0x20_PlayerPositionAndObjectID plr = (StoC_0x20_PlayerPositionAndObjectID)pak;
                            playerOid = plr.PlayerOid;
                            oidInfo.Clear();
                            oidInfo[plr.PlayerOid] = new ObjectInfo(eObjectType.player, "You", 0);
                            s.WriteLine("{0, -16} playerOid:0x{1:X4}", pak.Time.ToString(), playerOid);
                        }
                        // Fill objects OID
                        else if (pak is StoC_0xD4_PlayerCreate)
                        {
                            StoC_0xD4_PlayerCreate player = (StoC_0xD4_PlayerCreate)pak;
                            oidInfo[player.Oid] = new ObjectInfo(eObjectType.player, player.Name, player.Level);
                        }
                        else if (pak is StoC_0x4B_PlayerCreate_172)
                        {
                            StoC_0x4B_PlayerCreate_172 player = (StoC_0x4B_PlayerCreate_172)pak;
                            oidInfo[player.Oid] = new ObjectInfo(eObjectType.player, player.Name, player.Level);
                        }
                        else if (pak is StoC_0x12_CreateMovingObject)
                        {
                            StoC_0x12_CreateMovingObject obj = (StoC_0x12_CreateMovingObject)pak;
                            oidInfo[obj.ObjectOid] = new ObjectInfo(eObjectType.movingObject, obj.Name, 0);
                        }
                        else if (pak is StoC_0x6C_KeepComponentOverview)
                        {
                            StoC_0x6C_KeepComponentOverview keep = (StoC_0x6C_KeepComponentOverview)pak;
                            oidInfo[keep.Uid] =
                                new ObjectInfo(eObjectType.keep, string.Format("keepId:0x{0:X4} componentId:{1}", keep.KeepId, keep.ComponentId),
                                               0);
                        }
                        else if (pak is StoC_0xDA_NpcCreate)
                        {
                            StoC_0xDA_NpcCreate npc = (StoC_0xDA_NpcCreate)pak;
                            oidInfo[npc.Oid] = new ObjectInfo(eObjectType.npc, npc.Name, npc.Level);
                        }
                        else if (pak is StoC_0xD9_ItemDoorCreate)
                        {
                            StoC_0xD9_ItemDoorCreate item = (StoC_0xD9_ItemDoorCreate)pak;
                            eObjectType type = eObjectType.staticObject;
                            if (item.ExtraBytes > 0)
                            {
                                type = eObjectType.door;
                            }
                            oidInfo[item.Oid] = new ObjectInfo(type, item.Name, 0);
                        }
                        // Fill current weapons
                        else if (pak is StoC_0x02_InventoryUpdate)
                        {
                            StoC_0x02_InventoryUpdate invPack = (StoC_0x02_InventoryUpdate)pak;
                            if (invPack.PreAction == 1 || invPack.PreAction == 0)
                            {
                                VisibleSlots = invPack.VisibleSlots;
                                for (int j = 0; j < invPack.SlotsCount; j++)
                                {
                                    StoC_0x02_InventoryUpdate.Item item = (StoC_0x02_InventoryUpdate.Item)invPack.Items[j];
                                    switch (item.slot)
                                    {
                                    case 10:
                                        weapons[0] = item;
                                        break;

                                    case 11:
                                        weapons[1] = item;
                                        break;

                                    case 12:
                                        weapons[2] = item;
                                        break;

                                    case 13:
                                        weapons[3] = item;
                                        break;

                                    default:
                                        break;
                                    }
                                }
                            }
                        }
                        // Fill character stats
                        else if (pak is StoC_0x16_VariousUpdate)
                        {
                            // name, level, class
                            StoC_0x16_VariousUpdate stat = (StoC_0x16_VariousUpdate)pak;
                            if (stat.SubCode == 3)
                            {
                                StoC_0x16_VariousUpdate.PlayerUpdate subData = (StoC_0x16_VariousUpdate.PlayerUpdate)stat.SubData;
                                nameKey  = "N:" + subData.playerName + "L:" + subData.playerLevel;
                                statKey  = "";
                                plrName  = subData.playerName;
                                plrLevel = subData.playerLevel;
                                plrClass = subData.className;
                                s.WriteLine("{0, -16} 0x16:3 nameKey:{1} plrName:{2} {3} {4}", pak.Time.ToString(), nameKey, plrName, plrLevel,
                                            plrClass);
                            }
                            // mainhand spec, mainhand DPS
                            else if (stat.SubCode == 5)
                            {
                                StoC_0x16_VariousUpdate.PlayerStateUpdate subData = (StoC_0x16_VariousUpdate.PlayerStateUpdate)stat.SubData;
                                string key =
                                    string.Format("WD:{0}.{1}WS:{2}", subData.weaponDamageHigh, subData.weaponDamageLow,
                                                  (subData.weaponSkillHigh << 8) + subData.weaponSkillLow);
                                if (nameKey != "")
                                {
                                    if (plrInfo.ContainsKey(nameKey + key))
                                    {
                                        playerInfo = (PlayerInfo)plrInfo[nameKey + key];
                                    }
                                    else
                                    {
                                        playerInfo              = new PlayerInfo();
                                        playerInfo.name         = plrName;
                                        playerInfo.level        = plrLevel;
                                        playerInfo.className    = plrClass;
                                        playerInfo.weaponDamage = string.Format("{0,2}.{1,-3}", subData.weaponDamageHigh, subData.weaponDamageLow);
                                        playerInfo.weaponSkill  = (subData.weaponSkillHigh << 8) + subData.weaponSkillLow;
                                        plrInfo.Add(nameKey + key, playerInfo);
                                    }
                                    plrInfo[nameKey + key] = playerInfo;
                                }
                                statKey = key;
                                s.WriteLine("{0, -16} 0x16:5 S:{1} {2} {3} {4} {5}", pak.Time.ToString(), statKey, playerInfo.name,
                                            playerInfo.level, playerInfo.weaponDamage, playerInfo.weaponSkill);
                            }
                            // Fill styles
                            if (stat.SubCode == 1)
                            {
                                StoC_0x16_VariousUpdate.SkillsUpdate subData = (StoC_0x16_VariousUpdate.SkillsUpdate)stat.SubData;
                                styleIcons.Clear();
                                if (log.Version < 186)
                                {
                                    styleIcons.Add((ushort)0x01F4, "Bow prepare");
                                    styleIcons.Add((ushort)0x01F5, "Lefthand hit");
                                    styleIcons.Add((ushort)0x01F6, "Bothhands hit");
                                    styleIcons.Add((ushort)0x01F7, "Bow shoot");
//									styleIcons.Add((ushort)0x01F9, "Volley aim ?");
//									styleIcons.Add((ushort)0x01FA, "Volley ready ?");
//									styleIcons.Add((ushort)0x01FB, "Volley shoot ?");
                                }
                                else
                                {
                                    styleIcons.Add((ushort)0x3E80, "Bow prepare");
                                    styleIcons.Add((ushort)0x3E81, "Lefthand hit");
                                    styleIcons.Add((ushort)0x3E82, "Bothhands hit");
                                    styleIcons.Add((ushort)0x3E83, "Bow shoot");
//									styleIcons.Add((ushort)0x3E85, "Volley aim ?");
//									styleIcons.Add((ushort)0x3E86, "Volley ready ?");
//									styleIcons.Add((ushort)0x3E87, "Volley shoot ?");
                                }
                                foreach (StoC_0x16_VariousUpdate.Skill skill in subData.data)
                                {
                                    if (skill.page == StoC_0x16_VariousUpdate.eSkillPage.Styles)
                                    {
                                        styleIcons[skill.icon] = skill.name;
//										s.WriteLine("{0, -16} 0x16:1 icon:0x{1:X4} name:{2}", pak.Time.ToString(), skill.icon, styleIcons[skill.icon]);
                                    }
                                }

/*                              foreach (DictionaryEntry entry in styleIcons)
 *                                                              {
 *                                                                      ushort icon = (ushort)entry.Key;
 *                                                                      s.WriteLine("{0, -16} 0x16:1 icon:0x{1:X4} name:{2}", pak.Time.ToString(), icon, entry.Value);
 *                                                              }*/
                            }
                        }
                        // Combat animation
                        else if (pak is StoC_0xBC_CombatAnimation && (playerInfo != null))
                        {
                            StoC_0xBC_CombatAnimation combat = (StoC_0xBC_CombatAnimation)pak;
                            CombatWaitMessage.Clear();
                            ObjectInfo targetObj = oidInfo[combat.DefenderOid] as ObjectInfo;
                            string     styleName = (combat.StyleId == 0 /*  || (combat.Result & 0x7F) != 0x0B)*/)
                                                                                ? ""
                                                                                : (styleIcons[combat.StyleId] == null
                                                                                        ? "not found " + combat.StyleId.ToString()
                                                                                        : (styleIcons[combat.StyleId]).ToString());
                            string targetName = targetObj == null ? "" : " target:" + targetObj.name + " (" + targetObj.type + ")";
                            if (combat.Stance == 0 && combat.AttackerOid == playerOid /* && combat.DefenderOid != 0*/)
                            {
                                switch (combat.Result & 0x7F)
                                {
                                case 0:
                                    CombatWaitMessage.Add(new WaitMessage(0x11, "You miss!"));
                                    CombatWaitMessage.Add(new WaitMessage(0x11, "You were strafing in combat and miss!"));
                                    break;

                                case 1:
                                    if (targetObj != null)
                                    {
                                        CombatWaitMessage.Add(new WaitMessage(0x11, targetObj.GetFirstFullName + " parries your attack!"));
                                    }
                                    break;

                                case 2:
//										if (targetObj != null)//TODO
//											CombatWaitMessage.Add(new WaitMessage(0x11, targetObj.GetFirstFullName + " The Midgardian Assassin attacks you and you block the blow!"));
                                    break;

                                case 3:
                                    if (targetObj != null)
                                    {
                                        CombatWaitMessage.Add(new WaitMessage(0x11, targetObj.GetFirstFullName + " evades your attack!"));
                                    }
                                    break;

                                case 4:
                                    CombatWaitMessage.Add(new WaitMessage(0x11, "You fumble the attack and take time to recover!"));
                                    break;

                                case 0xA:
                                    if (targetObj != null)
                                    {
                                        CombatWaitMessage.Add(
                                            new WaitMessage(0x11, "You attack " + targetObj.GetFullName + " with your % and hit for % damage!"));
                                    }
                                    break;

                                case 0xB:
                                    CombatWaitMessage.Add(new WaitMessage(0x11, "You perform your " + styleName + " perfectly. %"));
                                    if (targetObj != null)
                                    {
                                        CombatWaitMessage.Add(
                                            new WaitMessage(0x11, "You attack " + targetObj.GetFullName + " with your % and hit for % damage!"));
                                    }
                                    break;

                                case 0x14:
                                    if (targetObj != null)
                                    {
                                        CombatWaitMessage.Add(new WaitMessage(0x11, "You hit " + targetObj.GetFullName + " for % damage!"));
                                    }
                                    break;

                                default:
                                    break;
                                }
                            }
                            if (combat.AttackerOid == playerOid)
                            {
                                s.WriteLine("{0, -16} 0xBC attackerOid:0x{1:X4}(You) defenderOid:0x{2:X4} style:0x{4:X4} result:0x{3:X2}{5}{6}",
                                            pak.Time.ToString(), combat.AttackerOid, combat.DefenderOid, combat.Result, combat.StyleId,
                                            styleName == "" ? "" : " styleName:" + styleName, targetName);
                                foreach (WaitMessage msg in CombatWaitMessage)
                                {
                                    s.WriteLine("         WAITING 0xAF 0x{0:X2} {1}", msg.msgType, msg.message);
                                }
                                countBC++;
                            }
                        }
                        // Messages
                        else if (pak is StoC_0xAF_Message)
                        {
                            StoC_0xAF_Message msg = (StoC_0xAF_Message)pak;
                            switch (msg.Type)
                            {
//								case 0x10: // Your cast combat
                            case 0x11:                                     // Your Melee combat
//								case 0x1B: // resist
//								case 0x1D: // X hits you
//								case 0x1E: // X miss you
                                s.WriteLine("{0, -16} 0xAF 0x{1:X2} {2} ", pak.Time.ToString(), msg.Type, msg.Text);
                                break;

                            default:
                                break;
                            }
                        }
                    }
                }
                if (nameKey != "" && statKey != "")
                {
                    plrInfo[nameKey + statKey] = playerInfo;
                }
            }
        }
Esempio n. 49
0
    IEnumerator Download(IEnumerable <string> names, ProgressCallback onProgress, DownloadCallback onFinish)
    {
        bool   success = true;
        string postfix = "";
        string folder  = "android";

//        if (Constants.DEVELOPMENT_MODE) {
//#if UNITY_IPHONE
//			folder = "ios_beta";
//#elif UNITY_ANDROID
//			folder = "android_beta";
//#endif
//        } else {
#if UNITY_IPHONE
        folder = "ios";
#elif UNITY_ANDROID
        folder = "android";
#endif
        //}

        string url       = null;
        long   fileSize  = 0;
        int    fileIndex = 0;

        foreach (var name in names)
        {
            //
            string configKey = string.Format("AssetHash_{0}", name);
            string crc;

            //
            url = CurrentServiceType.updateURL_Prefix + folder + "/" + name + postfix + ".md5?t=" + _version;
            using (var www = new WWW(url)) {
                yield return(www);

                if (www.error != null)
                {
                    Debug.LogWarning(www.error);
                    success = false;
                    break;
                }

                string[] contents = www.text.Split('/');
                crc = contents.GetSafe(2, contents.GetSafe(0));
                Debug.Log(string.Format("Patch CRC {0}.unity3d = {1}", name, crc));

                //
                if (PlayerPrefs.GetString(configKey, null) == crc)
                {
                    Debug.Log(string.Format("Skipping {0}.unity3d = {1}", name, PlayerPrefs.GetString(configKey, null)));

                    fileIndex++;
                    if (onProgress != null)
                    {
                        onProgress(fileIndex / (float)names.Count());
                    }
                    continue;
                }

                fileSize = long.Parse(contents[1]);
            }

            //
            var path = Path.Combine(persistentDataPath, name + ".unity3d");
            url = CurrentServiceType.updateURL_Prefix + folder + "/" + name + postfix + ".unity3d?t=" + _version;
            using (var www = new UnityWebRequest(url, UnityWebRequest.kHttpVerbGET)) {
                www.downloadHandler = new DownloadHandlerFile(path);

                //
                var op = www.SendWebRequest();
                while (!op.isDone)
                {
                    yield return(null);

                    //
                    if (onProgress != null)
                    {
                        onProgress((fileIndex + Mathf.Clamp01(www.downloadedBytes / (float)fileSize)) / (float)names.Count());
                    }
                }

                if (www.isNetworkError || www.isHttpError)
                {
                    Debug.LogWarning(string.Format("Failed to download {0}.unity3d", name));
                    success = false;
                    break;
                }
            }

            //				if(md5.CompareTo(Utility.MD5(bytes)) != 0) {
            //					Debug.LogWarning(string.Format("Failed to download {0}.unity3d", name));
            //					success = false;
            //					break;
            //				}

            try {
#if UNITY_IPHONE
                UnityEngine.iOS.Device.SetNoBackupFlag(path);
#endif
            } catch (Exception e) {
                Debug.LogException(e);
                Debug.LogWarning(string.Format("Failed to save {0}.unity3d", name));
                success = false;
                break;
            }

            fileIndex++;
            if (onProgress != null)
            {
                onProgress(fileIndex / (float)names.Count());
            }
            PlayerPrefs.SetString(configKey, crc);

            //
            Debug.Log(string.Format("Downloaded {0}.unity3d", name));
        }

        PlayerPrefs.Save();
        onFinish(success, null);
    }
Esempio n. 50
0
 /// <summary>
 /// Copy the contents of one <see cref="Stream"/> to another.
 /// </summary>
 /// <param name="source">The stream to source data from.</param>
 /// <param name="destination">The stream to write data to.</param>
 /// <param name="buffer">The buffer to use during copying.</param>
 /// <param name="progressHandler">The <see cref="ProgressCallback">progress handler delegate</see> to use.</param>
 /// <param name="updateInterval">The minimum <see cref="TimeSpan"/> between progress updates.</param>
 /// <param name="sender">The source for this event.</param>
 /// <param name="name">The name to use with the event.</param>
 /// <remarks>This form is specialised for use within #Zip to support events during archive operations.</remarks>
 public static void Copy(Stream source, Stream destination, byte[] buffer, ProgressCallback progressHandler, TimeSpan updateInterval, object sender, string name)
 {
     Copy(source, destination, buffer, progressHandler, updateInterval, sender, name, -1);
 }
Esempio n. 51
0
        /// <summary>
        /// Writes the log.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="stream">The stream.</param>
        /// <param name="callback">The callback for UI updates.</param>
        public void WriteLog(IExecutionContext context, Stream stream, ProgressCallback callback)
        {
            StoC_0x16_VariousUpdate.CraftingSkillsUpdate lastCraftingSkill = null;
            StoC_0xF3_TimerWindow lastCraftBeginTimerPacket = null;
            StoC_0xF3_TimerWindow lastCloseTimerPacket      = null;
            ushort     lastReceipId = 0;
            SortedList recpToSkill  = new SortedList();

            //Alb receipts
            recpToSkill.Add(1, 4);                      // Alchemy
            recpToSkill.Add(701, 2);                    // Armorcraft
            recpToSkill.Add(1401, 8);                   // Clothworking
            recpToSkill.Add(1801, 15);                  // Basic Crafting
            recpToSkill.Add(2051, 12);                  // Fletching
            recpToSkill.Add(2751, 7);                   // Leatherworking
            recpToSkill.Add(3001, 11);                  // Tailoring
            recpToSkill.Add(3451, 6);                   // Metalworking
            recpToSkill.Add(4165, 3);                   // Siegecraft
            recpToSkill.Add(4201, 13);                  // Spellcraft
            recpToSkill.Add(4901, 11);                  // Tailoring
            recpToSkill.Add(5601, 1);                   // Weaponcrafting
            recpToSkill.Add(6501, 14);                  // Woodworking
            //Mid receipts
            recpToSkill.Add(7001, 4);                   // Alchemy
            recpToSkill.Add(7701, 2);                   // Armorcraft
            recpToSkill.Add(8401, 8);                   // Clothworking
            recpToSkill.Add(8801, 15);                  // Basic Crafting
            recpToSkill.Add(9051, 12);                  // Fletching
            recpToSkill.Add(9751, 7);                   // Leatherworking
            recpToSkill.Add(10001, 11);                 // Tailoring
            recpToSkill.Add(10451, 6);                  // Metalworking
            recpToSkill.Add(11165, 3);                  // Siegecraft
            recpToSkill.Add(11201, 13);                 // Spellcraft
            recpToSkill.Add(11901, 11);                 // Tailoring
            recpToSkill.Add(12601, 1);                  // Weaponcrafting
            recpToSkill.Add(13301, 14);                 // Woodworking
            //Hib receipts
            recpToSkill.Add(14001, 4);                  // Alchemy
            recpToSkill.Add(14701, 2);                  // Armorcraft
            recpToSkill.Add(15401, 8);                  // Clothworking
            recpToSkill.Add(15801, 15);                 // Basic Crafting
            recpToSkill.Add(16051, 12);                 // Fletching
            recpToSkill.Add(16751, 7);                  // Leatherworking
            recpToSkill.Add(17001, 11);                 // Tailoring
            recpToSkill.Add(17451, 6);                  // Metalworking
            recpToSkill.Add(18165, 3);                  // Siegecraft
            recpToSkill.Add(18201, 13);                 // Spellcraft
            recpToSkill.Add(18901, 11);                 // Tailoring
            recpToSkill.Add(19601, 1);                  // Weaponcrafting
            recpToSkill.Add(20301, 14);                 // Woodworking
            using (StreamWriter s = new StreamWriter(stream))
            {
                foreach (PacketLog log in context.LogManager.Logs)
                {
                    for (int i = 0; i < log.Count; i++)
                    {
                        if (callback != null && (i & 0xFFF) == 0)                         // update progress every 4096th packet
                        {
                            callback(i, log.Count - 1);
                        }

                        Packet pak = log[i];
                        if (pak is StoC_0x16_VariousUpdate)
                        {
                            StoC_0x16_VariousUpdate stat = pak as StoC_0x16_VariousUpdate;
                            if (stat.SubCode == 8)
                            {
                                lastCraftingSkill = (StoC_0x16_VariousUpdate.CraftingSkillsUpdate)stat.SubData;
                            }
                        }
                        else if (pak is CtoS_0xED_CraftItem)
                        {
                            CtoS_0xED_CraftItem craft = pak as CtoS_0xED_CraftItem;
                            lastReceipId = craft.ReceptId;
                        }
                        else if (pak is StoC_0xF3_TimerWindow)
                        {
                            StoC_0xF3_TimerWindow timer = pak as StoC_0xF3_TimerWindow;
                            if (timer.Flag == 1 && timer.Message.StartsWith("Making: "))
                            {
                                lastCraftBeginTimerPacket = timer;
                            }
                            else if (timer.Flag == 0)
                            {
                                lastCloseTimerPacket = timer;
                            }
                        }
                        else if (pak is StoC_0xAF_Message)
                        {
                            StoC_0xAF_Message message = pak as StoC_0xAF_Message;
                            if (message.Text.StartsWith("You successfully make "))
                            {
                                byte craftSkill = (byte)FindSkill(recpToSkill, lastReceipId);
                                //							StringBuilder str = new StringBuilder();
                                //							lastCraftingSkill.MakeString(str, true);
                                //							s.WriteLine(str);
                                bool found = false;
                                foreach (StoC_0x16_VariousUpdate.CraftingSkill cs in lastCraftingSkill.skills)
                                {
                                    if (cs.icon == craftSkill)
                                    {
                                        s.WriteLine(string.Format("{0}, crafting skill:{1}({3}:{4}) receptId:{2} (time:{5}, pakDiffTime:{6})",
                                                                  message.Text, craftSkill, lastReceipId, cs.name, cs.points,
                                                                  lastCraftBeginTimerPacket.Timer,
                                                                  lastCloseTimerPacket.Time - lastCraftBeginTimerPacket.Time));
                                        found = true;
                                        break;
                                    }
                                }
                                if (!found)
                                {
                                    s.WriteLine(string.Format("{0}, crafting skill:{1} receptId:{2}", message.Text, craftSkill, lastReceipId));
                                }
                            }
                            else if (message.Text.StartsWith("You gain skill in"))
                            {
                                s.WriteLine(message.Text);
                            }
                        }
                    }             // for (log.packets)
                }                 // foreach(context.logs)
            }
        }
Esempio n. 52
0
 /// <summary>
 /// Save to the cloud asynchronously data in a byte array with a specified key
 /// </summary>
 /// <param name="key"> string that uniquely identifies this instance of the type. </param>
 /// <param name="bytes">Bytes array of the object being saved</param>
 /// <param name="callback"> a callback when the asynchronous call is done to show whether it was successful,
 /// with the response code and string. </param>
 /// <param name="progress">Called every frame while the request is in progress with two 0-1 values indicating
 /// upload and download progress, respectively</param>
 /// <param name="timeout">The timeout duration (in seconds) for this request</param>
 /// <returns>A handle to this request which can be used to cancel it</returns>
 public RequestHandle CloudSaveAsync(string key, byte[] bytes, Action <bool, long, string> callback = null,
                                     ProgressCallback progress = null, int timeout = CloudStorageDefaults.DefaultTimeout)
 {
     return(CloudSaveAsyncBytes(key, bytes, timeout, callback, progress));
 }
Esempio n. 53
0
        public void MultithreadDecrypt(long streamOffset, Stream outputStream, long dataSize, AesCryptoServiceProvider AES, ProgressCallback Progress)
        {
            byte[] buffer       = new byte[1048576];
            byte[] outputBuffer = new byte[buffer.Length];
            byte[] IV           = AES.IV;
            long   max          = (long)Crypto.GetMod16((ulong)dataSize);
            long   position     = streamOffset;

            while (max > 0)
            {
                lock (_ReadWriteLock)
                {
                    _stream.Position = position;
                    bool lastBlock = (max - buffer.Length) <= 0;
                    int  length    = _stream.Read(buffer, 0, (int)Math.Min(buffer.Length, max));
                    MultithreadDecryptBufer(buffer, ref outputBuffer, length, AES, lastBlock, ref IV);
                    outputStream.Write(outputBuffer, 0, outputBuffer.Length);
                    position = _stream.Position;
                    max     -= length;
                }

                Progress?.Invoke((dataSize - max) / (double)dataSize * 100.0);
            }
        }
Esempio n. 54
0
 /// <summary>
 /// Save to the cloud asynchronously the data of an object of a certain type with a specified key
 /// </summary>
 /// <param name="key"> string that uniquely identifies this instance of the type. </param>
 /// <param name="serializedObject"> string serialization of the object being saved. </param>
 /// <param name="callback"> a callback when the asynchronous call is done to show whether it was successful,
 /// with the response code and string. </param>
 /// <param name="progress">Called every frame while the request is in progress with two 0-1 values indicating
 /// upload and download progress, respectively</param>
 /// <param name="timeout">The timeout duration (in seconds) for this request</param>
 /// <returns>A handle to this request which can be used to cancel it</returns>
 public RequestHandle CloudSaveAsync(string key, string serializedObject, Action <bool, long, string> callback = null,
                                     ProgressCallback progress = null, int timeout = CloudStorageDefaults.DefaultTimeout)
 {
     return(CloudSaveAsyncBytes(key, Encoding.UTF8.GetBytes(serializedObject), timeout, callback, progress));
 }
Esempio n. 55
0
        private int DoFilter(FilterParams filterParams, int startLine, int maxCount, List <int> filterResultLines,
                             List <int> lastFilterLinesList, List <int> filterHitList, ProgressCallback progressCallback)
        {
            int lineNum         = startLine;
            int count           = 0;
            int callbackCounter = 0;

            try
            {
                filterParams.Reset();
                while ((count++ < maxCount || filterParams.isInRange) && !this.ShouldCancel)
                {
                    if (lineNum >= this.callback.GetLineCount())
                    {
                        return(count);
                    }
                    ILogLine line = this.callback.GetLogLine(lineNum);
                    if (line == null)
                    {
                        return(count);
                    }
                    this.callback.LineNum = lineNum;
                    if (Util.TestFilterCondition(filterParams, line, callback))
                    {
                        AddFilterLine(lineNum, false, filterParams, filterResultLines, lastFilterLinesList,
                                      filterHitList);
                    }
                    lineNum++;
                    callbackCounter++;
                    if (lineNum % PROGRESS_BAR_MODULO == 0)
                    {
                        progressCallback(callbackCounter);
                        callbackCounter = 0;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.logError("Exception while filtering. Please report to developer: \n\n" + ex + "\n\n" +
                                ex.StackTrace);
                MessageBox.Show(null,
                                "Exception while filtering. Please report to developer: \n\n" + ex + "\n\n" + ex.StackTrace,
                                "LogExpert");
            }
            return(count);
        }
Esempio n. 56
0
 public TextureRequest(LoadTextureCallback callback, ProgressCallback progress = null) : base(progress)
 {
     m_Callback = callback;
 }
Esempio n. 57
0
        public async Task GetBytesWithProgressAsync(ProgressCallback callback)
        {
            if ((_requestMessage == null) || (callback == null))
            {
                return;
            }

            int noOfBytesRead    = 0;
            int totalBytesToRead = 0;

            try
            {
                Task <HttpResponseMessage> httpResponseTask = Task.Run(async() => await _httpClient
                                                                       .GetAsync(_httpURLString,
                                                                                 HttpCompletionOption.ResponseHeadersRead,
                                                                                 _tokenSource.Token));

                await httpResponseTask;
                HttpResponseMessage responseMessage = httpResponseTask.Result;

                Task <byte[]> responseByteTask = Task.Run(async() => await
                                                          responseMessage.Content.ReadAsByteArrayAsync());
                await responseByteTask;

                Task <Stream> responseStreamTask = Task.Run(async() => await responseMessage.Content.ReadAsStreamAsync());
                await         responseStreamTask;

                Stream responseStream = responseStreamTask.Result;
                byte[] responseBytes  = responseByteTask.Result;
                totalBytesToRead = responseBytes.Length;

                string          responseString = null;
                byte[]          buffer         = null;
                CMPHttpResponse httpResponse   = null;

                while (true)
                {
                    buffer = new byte[_chunkBufferSize];
                    int bytesRead = 0;

                    bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length);

                    if (bytesRead == 0)
                    {
                        break;
                    }

                    noOfBytesRead += bytesRead;
                    responseString = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);

                    httpResponse = new CMPHttpResponse(responseString, responseMessage.StatusCode, 0);
                    callback.Invoke(httpResponse, noOfBytesRead, totalBytesToRead);
                }
            }
            catch (WebException ex)
            {
                var httpResponse = new CMPHttpResponse(ex.Message, 0, ex.Status);
                callback.Invoke(httpResponse, noOfBytesRead, totalBytesToRead);
            }
            catch (AggregateException ex)
            {
                var httpResponse = new CMPHttpResponse(ex.Message, 0, 0);
                callback.Invoke(httpResponse, noOfBytesRead, totalBytesToRead);
            }
            catch (Exception ex)
            {
                var httpResponse = new CMPHttpResponse(ex.Message, 0, 0);
                callback.Invoke(httpResponse, noOfBytesRead, totalBytesToRead);
            }
        }
Esempio n. 58
0
 public BytesRequest(Action <bool, long, byte[]> callback, ProgressCallback progress = null) : base(progress)
 {
     m_Callback = callback;
 }
Esempio n. 59
0
        /// <summary>
        /// Collects statistics on how much space savings minimizing will achieve, and (if outStream
        /// is not null) writes out the minimized cache file.
        /// </summary>
        public void Minimize(Settings settings, ProgressCallback progressCallback, Stream outStream,
                             FileStream outStreamScans = null, FileStream outStreamPeaks = null, FileStream outStreamScores = null)
        {
            var  writer = outStream == null ? null : new Writer(ChromatogramCache, settings.CacheFormat, outStream, outStreamScans, outStreamPeaks, outStreamScores);
            var  statisticsCollector = new MinStatisticsCollector(this);
            bool readChromatograms   = settings.NoiseTimeRange.HasValue || writer != null;

            var chromGroupHeaderToIndex = new Dictionary <long, int>(ChromGroupHeaderInfos.Count);

            for (int i = 0; i < ChromGroupHeaderInfos.Count; i++)
            {
                var cghi = ChromGroupHeaderInfos[i];
                chromGroupHeaderToIndex.Add(cghi.LocationPoints, i);
            }
            var chromGroups      = new ChromatogramGroupInfo[ChromGroupHeaderInfos.Count];
            var transitionGroups = new List <TransitionGroupDocNode> [ChromGroupHeaderInfos.Count];

            foreach (var nodePep in Document.Molecules)
            {
                foreach (var nodeGroup in nodePep.TransitionGroups)
                {
                    foreach (var chromGroupInfo in ChromatogramCache.LoadChromatogramInfos(nodePep, nodeGroup, _tolerance, null))
                    {
                        int headerIndex = chromGroupHeaderToIndex[chromGroupInfo.Header.LocationPoints];
                        if (chromGroups[headerIndex] == null)
                        {
                            chromGroups[headerIndex]      = chromGroupInfo;
                            transitionGroups[headerIndex] = new List <TransitionGroupDocNode>();
                        }
                        transitionGroups[headerIndex].Add(nodeGroup);
                    }
                }
            }

            var minimizer = new QueueWorker <MinimizeParams>(null, MinimizeAndWrite);

            minimizer.RunAsync(MINIMIZING_THREADS, @"Minimizing/Writing", MAX_GROUP_READ_AHEAD);

            for (int iHeader = 0; iHeader < ChromGroupHeaderInfos.Count; iHeader++)
            {
                var chromGroupInfo = chromGroups[iHeader];
                IList <TransitionGroupDocNode> transitionGroupDocNodes;
                if (chromGroupInfo == null)
                {
                    chromGroupInfo          = ChromatogramCache.LoadChromatogramInfo(ChromGroupHeaderInfos[iHeader]);
                    transitionGroupDocNodes = new TransitionGroupDocNode[0];
                }
                else
                {
                    transitionGroupDocNodes = transitionGroups[iHeader];
                }

                if (readChromatograms)
                {
                    try
                    {
                        chromGroupInfo.ReadChromatogram(ChromatogramCache, true);
                    }
                    catch (Exception exception)
                    {
                        Trace.TraceWarning(@"Unable to read chromatogram {0}", exception);
                    }
                }

                if (minimizer.Exception != null)
                {
                    break;
                }

                minimizer.Add(new MinimizeParams(writer, settings, chromGroupInfo, transitionGroupDocNodes, progressCallback, statisticsCollector));

                // Null out the ChromGroup in our array so it can be garbage collected.
                chromGroups[iHeader] = null;
            }

            minimizer.DoneAdding(true);
            if (minimizer.Exception != null)
            {
                throw minimizer.Exception;
            }

            statisticsCollector.ReportProgress(progressCallback, true);

            if (writer != null)
            {
                writer.WriteEndOfFile();
            }
        }
Esempio n. 60
0
        protected virtual void LoadDo(ProgressCallback callback = null)
        {
            bool            reportProgress = callback != null;
            List <FileInfo> files          = null;

#if !NETSTANDARD1_3
            Thread thread = new Thread(() =>
            {
                try
                {
                    var fs = WorkDir.EnumerateFiles("*.tpac", SearchOption.AllDirectories).ToList();
                    files  = fs;
                }
                catch (ThreadAbortException)
                {
                }
            });
            thread.Name         = "Tpac Searcher";
            thread.IsBackground = true;
            thread.Start();
            while (true)
            {
                if (reportProgress && !callback(-1, -1, String.Empty, false))
                {
                    if (thread.ThreadState != ThreadState.Stopped)
                    {
                        thread.Abort();
                    }
                    InterruptLoading();
                    return;
                }
                if (files != null)
                {
                    break;
                }
                Thread.Sleep(100);
                Thread.Yield();
            }
#else
            files = WorkDir.EnumerateFiles("*.tpac", SearchOption.AllDirectories).ToList();
#endif

            var packageCount = files.Count;
            int i            = 0;
            foreach (var file in files)
            {
                if (reportProgress && !callback(i++, packageCount, file.Name, false))
                {
                    InterruptLoading();
                    return;
                }
                var package = new AssetPackage(file.FullName);
                package.IsGuidLocked = true;
                _loadedPackages.Add(package);
                _packageLookup[package.Guid] = package;
                foreach (var assetItem in package.Items)
                {
                    _assetLookup[assetItem.Guid] = assetItem;
                    _loadedAssets.Add(assetItem);
                }
            }

            if (reportProgress && !callback(packageCount, packageCount, String.Empty, true))
            {
                InterruptLoading();
                return;
            }
        }