Exemplo n.º 1
0
        /********************
         *     utilities    *
         *********************/

        /* public methods */

        public string[] AddrDescToString(bool bMemOnly)
        {
            string[] sAddr = new string[AddrDesc.Length];
            for (int i = 0; i < sAddr.Length; ++i)
            {
                sAddr[i] = "BAR " + AddrDesc[i].dwAddrSpace.ToString() +
                           ((AddrDesc[i].fIsMemory)? " Memory " : " I/O ");

                if (wdc_lib_decl.WDC_AddrSpaceIsActive(Handle,
                                                       AddrDesc[i].dwAddrSpace))
                {
                    WD_ITEMS item =
                        m_wdcDevice.cardReg.Card.Item[AddrDesc[i].dwItemIndex];
                    UINT64 dwAddr = (UINT64)(AddrDesc[i].fIsMemory?
                                             item.I.Mem.dwPhysicalAddr : item.I.IO.dwAddr);

                    sAddr[i] += dwAddr.ToString("X") + " - " +
                                (dwAddr + AddrDesc[i].dwBytes - 1).ToString("X") +
                                " (" + AddrDesc[i].dwBytes.ToString("X") + " bytes)";
                }
                else
                {
                    sAddr[i] += "Inactive address space";
                }
            }
            return(sAddr);
        }
Exemplo n.º 2
0
        private async Task LogUnban(Server server, string userName, guid userId, SocketGuildUser issuedBy)
        {
            try
            {
                SocketTextChannel logChannel;
                if (!server.Config.LogBans || (logChannel = server.Guild.GetTextChannel(server.Config.ModChannelId)) == null)
                {
                    return;
                }

                this.RecentlyUnbannedUserIDs.Add(userId);                 //Don't trigger the on-event log message as well as this custom one.

                if (server.Config.ModChannelEmbeds)
                {
                    await logChannel.SendMessageAsync("", embed :
                                                      GetLogEmbed(new Color(server.Config.ModChannelColor), "", "User Unbanned",
                                                                  "by: " + (issuedBy?.GetUsername() ?? "<unknown>"),
                                                                  userName ?? "<unknown>", userId.ToString(),
                                                                  DateTime.UtcNow));
                }
                else
                {
                    await logChannel.SendMessageSafe(
                        GetLogMessage("User Unbanned", (issuedBy == null ? "by unknown" : "by " + issuedBy.GetUsername()),
                                      userName ?? "", userId.ToString(),
                                      Utils.GetTimestamp()));
                }
            }
            catch (HttpException) { }
            catch (Exception exception)
            {
                await this.HandleException(exception, "LogUnban", server.Id);
            }
        }
Exemplo n.º 3
0
		/// <summary>
		/// Handle ARP packets
		/// </summary>
		/// <param name="packet">The EthernetDatagram</param>
		/// <param name="arp">The ArpDatagram to parse</param>
		public static void HandleARP(Packet packet, ArpDatagram arp, 
			ref UInt64 frame_id, object[] ctrl)
		{
			ListViewItem item = new ListViewItem(frame_id.ToString());
			frame_id++;
			List<string> packet_info = new List<string>();
			ListView frames = (ListView)ctrl[0];
			EthernetDatagram ethernet = packet.Ethernet;

			packet_info.Add(packet.Timestamp.ToString("hh:mm:ss.fff tt"));
			packet_info.Add(arp.SenderProtocolIpV4Address.ToString());
			packet_info.Add(arp.TargetProtocolIpV4Address.ToString());
			packet_info.Add(ethernet.Source.ToString());
			packet_info.Add(ethernet.Destination.ToString());
			packet_info.Add("ARP");
			packet_info.Add(arp.Length.ToString());

			// update UI
			if (item != null) {
				item.SubItems.AddRange(packet_info.ToArray());
				object[] param = new object[2];
				param[0] = frames;
				object[] o = new object[3];
				o[0] = item;
				o[1] = ctrl[1];
				o[2] = packet;
				param[1] = o;
				frames.BeginInvoke(new ParserHelper.UIHandlerEx(ParserHelper.UpdateFrameUI), param);
			}

		}
Exemplo n.º 4
0
        // Builds a mesh shape in the physical world and updates prim.BSShape.
        // Dereferences previous shape in BSShape and adds a reference for this new shape.
        // Returns 'true' of a mesh was actually built. Otherwise .
        // Called at taint-time!
        private bool GetReferenceToMesh(BSPhysObject prim, ShapeDestructionCallback shapeCallback)
        {
            BulletShape newShape = new BulletShape();

            float lod;

            System.UInt64 newMeshKey = ComputeShapeKey(prim.Size, prim.BaseShape, out lod);

            // if this new shape is the same as last time, don't recreate the mesh
            if (newMeshKey == prim.PhysShape.shapeKey && prim.PhysShape.type == BSPhysicsShapeType.SHAPE_MESH)
            {
                return(false);
            }

            if (DDetail)
            {
                DetailLog("{0},BSShapeCollection.GetReferenceToMesh,create,oldKey={1},newKey={2}",
                          prim.LocalID, prim.PhysShape.shapeKey.ToString("X"), newMeshKey.ToString("X"));
            }

            // Since we're recreating new, get rid of the reference to the previous shape
            DereferenceShape(prim.PhysShape, true, shapeCallback);

            newShape = CreatePhysicalMesh(prim.PhysObjectName, newMeshKey, prim.BaseShape, prim.Size, lod);
            // Take evasive action if the mesh was not constructed.
            newShape = VerifyMeshCreated(newShape, prim);

            ReferenceShape(newShape);

            prim.PhysShape = newShape;

            return(true);   // 'true' means a new shape has been added to this prim
        }
Exemplo n.º 5
0
        // See that hull shape exists in the physical world and update prim.BSShape.
        // We could be creating the hull because scale changed or whatever.
        private bool GetReferenceToHull(BSPhysObject prim, ShapeDestructionCallback shapeCallback)
        {
            BulletShape newShape;

            float lod;

            System.UInt64 newHullKey = ComputeShapeKey(prim.Size, prim.BaseShape, out lod);

            // if the hull hasn't changed, don't rebuild it
            if (newHullKey == prim.PhysShape.shapeKey && prim.PhysShape.type == BSPhysicsShapeType.SHAPE_HULL)
            {
                return(false);
            }

            if (DDetail)
            {
                DetailLog("{0},BSShapeCollection.GetReferenceToHull,create,oldKey={1},newKey={2}",
                          prim.LocalID, prim.PhysShape.shapeKey.ToString("X"), newHullKey.ToString("X"));
            }

            // Remove usage of the previous shape.
            DereferenceShape(prim.PhysShape, true, shapeCallback);

            newShape = CreatePhysicalHull(prim.PhysObjectName, newHullKey, prim.BaseShape, prim.Size, lod);
            newShape = VerifyMeshCreated(newShape, prim);

            ReferenceShape(newShape);

            prim.PhysShape = newShape;
            return(true);   // 'true' means a new shape has been added to this prim
        }
Exemplo n.º 6
0
        /********************
         *     utilities    *
         *********************/

        /* public methods */

        public string[] AddrDescToString(bool bMemOnly)                     //地址装换输出字符 bar类型 范围和大小
        {
            string[] sAddr = new string[AddrDesc.Length];                   //声明sAddr字符串数组
            for (int i = 0; i < sAddr.Length; ++i)
            {                                                               //dwaddrspace  存储空间代号
                sAddr[i] = "BAR " + AddrDesc[i].dwAddrSpace.ToString() +    //fIsMemory BOOL TRUE: memory address space. FALSE: I/O address space
                           ((AddrDesc[i].fIsMemory)? " Memory " : " I/O "); //

                if (wdc_lib_decl.WDC_AddrSpaceIsActive(Handle,              //判断是否是active 的
                                                       AddrDesc[i].dwAddrSpace))
                {
                    WD_ITEMS item =
                        m_wdcDevice.cardReg.Card.Item[AddrDesc[i].dwItemIndex]; //Card resources information structure. 获得card信息
                    UINT64 dwAddr = (UINT64)(AddrDesc[i].fIsMemory?
                                             item.I.Mem.dwPhysicalAddr : item.I.IO.dwAddr);

                    sAddr[i] += dwAddr.ToString("X") + " - " +
                                (dwAddr + AddrDesc[i].dwBytes - 1).ToString("X") +
                                " (" + AddrDesc[i].dwBytes.ToString("X") + " bytes)";
                }
                else
                {
                    sAddr[i] += "Inactive address space";
                }
            }
            return(sAddr);
        }
Exemplo n.º 7
0
        internal ulong FetchIntPtrAt(Address address, int offset)
        {
            Debug.Assert(offset >= 0);
            address += (uint)offset;

TRY_AGAIN:
            // The fast path.
            long delta = (long)(address - m_dataStart);

            if (0 <= delta && delta < m_dataLength)
            {
                if (PointerSize == 4)
                {
                    return(*((uint *)(m_dataPtr + (int)delta)));
                }
                else
                {
                    return(*((ulong *)(m_dataPtr + (int)delta)));
                }
            }

            IntPtr readSizeIntPtr = IntPtr.Zero;

            m_dataStart = address;
            m_process.ReadMemory(m_dataStart, (uint)m_data.Length, m_data, out readSizeIntPtr);
            m_dataLength = (int)readSizeIntPtr - 8;        // Allows an intPtr size read (under all circumstances.
            Debug.Assert(m_dataLength >= 0);
            if (m_dataLength >= 0)
            {
                goto TRY_AGAIN;
            }

            throw new InvalidOperationException("Illegal fetch at " + address.ToString("x"));
        }
Exemplo n.º 8
0
        protected static string ToString(Object o)
        {
            if (o == null)
            {
                return("null");
            }
            if (o is byte[])
            {
                string ret = "<";
                byte[] a   = (byte[])o;
                for (uint i = 0; i < a.Length; i++)
                {
                    if (i != 0)
                    {
                        ret += ".";
                    }
                    ret += a[i].ToString("X2");
                }
                ret += ">";
                return(ret);
            }
            else if (o is Object[])
            {
                Object[] a   = (Object[])o;
                string   ret = "[";

                for (uint i = 0; i < a.Length; i++)
                {
                    if (i != 0)
                    {
                        ret += " ";
                    }
                    ret += ToString(a[i]);
                }
                ret += "]";
                return(ret);
            }
            else if (o is System.Int64)
            {
                System.Int64 i = (System.Int64)o;
                return((i < 0 ? "s-0x" : "s0x") + i.ToString("X"));
            }
            else if (o is System.UInt64)
            {
                System.UInt64 i = (System.UInt64)o;
                return("u0x" + i.ToString("X"));
            }
            else if (o is System.String)
            {
                return("\"" + o.ToString() + "\"");
            }
            else if (o is System.Char)
            {
                return("\'" + o.ToString() + "\'");
            }
            else
            {
                return("WAT(" + o.GetType() + ")");
            }
        }
Exemplo n.º 9
0
    void OnGetReward(GameObject go)
    {
        GlobalAudioMgr.Instance.PlayOrdianryMusic(Audio.OrdianryMusic.m_BtnMusic);

        if (PlayerRole.Instance.RoleMonthCard.IsInMonthCard())
        {
            PlayerRole.Instance.RoleMonthCard.GetRoleMonthCardReward();
        }
        else
        {
            uint ItemID = 13;
            if (SDKMgr.IS_SDK_CHANNEL || SDKMgr.IS_APP_STORE_VER)
            {
                System.UInt64 user_item_id = PlayerRole.Instance.RoleInfo.RoleMe.GetUserID();
                user_item_id = (user_item_id << 32) | ItemID;
                if (FishConfig.Instance.m_FishRecharge.m_FishRechargeMap.ContainsKey(ItemID))
                {
                    int price = (int)FishConfig.Instance.m_FishRecharge.m_FishRechargeMap[13].dDisCountPrice * 100;
                    SDKMgr.Instance.SDK.Pay(price, "月卡", 1, ItemID.ToString(), user_item_id.ToString(), (int)ItemID);
                }
            }
            else
            {
                PlayerRole.Instance.RoleRecharge.SendRecharge(ItemID, SDKMgr.Instance.IsServerOrder);
            }
        }
    }
Exemplo n.º 10
0
        public string  GetField(int idx)
        {
            if (idx < numDataFields)
            {
                return(data[idx].ToString());
            }

            string field = "";

            switch (idx)
            {
            case  LatitudeIndex:
                field = latitude.ToString();
                break;

            case  LongitudeIndex:
                field = longitude.ToString();
                break;

            case  DateIndex:
                field = time.ToString("G");
                break;

            case  ActiveBatteryIndex:
                field = activeBattery.ToString();
                break;

            case  BatteryStatusesIndex:
                field = batteryStatuses;
                break;

            case  CTD_DateIndex:
                field = ctdDate.ToString("yy/MM/dd HH:mm:ss");
                break;

            case  ScanLineIndex:
                field = scanLine.ToString();
                break;

            case  ByteOffseIndex:
                field = byteOffset.ToString();
                break;

            case  CropLeftIndex:
                field = cropLeft.ToString();
                break;

            case  CropRightIndex:
                field = cropRight.ToString();
                break;

            case  ActiveColumnsIndex:
                field = activeColumns.ToString();
                break;
            }

            return(field);
        } /* GetField */
 /// <summary>
 /// Validación de una cuenta bancaria española
 /// </summary>
 /// <param name="banco">Código del banco</param>
 /// <param name="oficina">Código de la oficina</param>
 /// <param name="dc">Dígito de control</param>
 /// <param name="cuenta">Número de cuenta</param>
 /// <returns>true si el número de cuenta es correcto</returns>
 public static bool ValidaCuentaBancaria(UInt64 banco, UInt64 oficina, UInt64 dc, UInt64 cuenta)
 {
     return ValidaCuentaBancaria(
                         banco.ToString("0000")
                         , oficina.ToString("0000")
                         , dc.ToString("00")
                         , cuenta.ToString("0000000000")
                         );
 }
Exemplo n.º 12
0
 // Overload for Addresses to calculate a string resource representation
 public Conflict(string device1, string device2, UInt64 startAddress, UInt64 endAddress)
 {
     // Convert each address to hex
     string resource = "0x" + startAddress.ToString("X");
     resource += "-0x" + endAddress.ToString("X");
     this.Device1 = device1;
     this.Device2 = device2;
     this.Resource = resource;
 }
Exemplo n.º 13
0
 private UInt64 GetNext(UInt64 num)
 {
     string numAsString = num.ToString();
     UInt64 total = 0;
     for (int i = 0; i < numAsString.Length; i++) {
         UInt64 x = Convert.ToUInt64(numAsString.Substring(i, 1));
         total += x * x;
     }
     return total;
 }
Exemplo n.º 14
0
 public string GetAnswer()
 {
     _squareSize = 1;
     _number = 1;
     _diagonals.Add(1);
     do {
         AddNewLayer();
     } while (Convert.ToDecimal(_primeCount) / Convert.ToDecimal(_diagonals.Count) >= Convert.ToDecimal(.1));
     return _squareSize.ToString();
 }
Exemplo n.º 15
0
    public void SetPlayerId(System.UInt64 qwPlayerId)
    {
        m_qwPlayerId = qwPlayerId;

        m_pButton.onClick.AddListener(delegate()
        {
            InvitePlayer();
        });

        m_txtPlayerId.text = "invite : " + m_qwPlayerId.ToString();
    }
Exemplo n.º 16
0
		/// <summary>
		/// Handle IPV4 packets, including TCP and UDP packets
		/// </summary>
		/// <param name="packet">The IpV4Datagram to parse</param>
		public static void HandleIPV4(Packet packet, IpV4Datagram ip,
			ref UInt64 frame_id, object[] ctrl)
		{
			ListViewItem item = new ListViewItem(frame_id.ToString());
			frame_id++;
			List<string> packet_info = new List<string>();
			ListView frames = (ListView)ctrl[0];
			EthernetDatagram ethernet = packet.Ethernet;

			switch (ip.Protocol) {
				case IpV4Protocol.Udp: {
						UdpDatagram udp = ip.Udp;
						packet_info.Add(packet.Timestamp.ToString("hh:mm:ss.fff tt"));
						packet_info.Add(ip.Source + ":" + udp.SourcePort);
						packet_info.Add(ip.Destination + ":" + udp.DestinationPort);
						packet_info.Add(ethernet.Source.ToString());
						packet_info.Add(ethernet.Destination.ToString());
						packet_info.Add("UDP");
						packet_info.Add(udp.Length.ToString());

						break;
					}
				case IpV4Protocol.Tcp: {
						TcpDatagram tcp = ip.Tcp;
						packet_info.Add(packet.Timestamp.ToString("hh:mm:ss.fff tt"));
						packet_info.Add(ip.Source + ":" + tcp.SourcePort);
						packet_info.Add(ip.Destination + ":" + tcp.DestinationPort);
						packet_info.Add(ethernet.Source.ToString());
						packet_info.Add(ethernet.Destination.ToString());
						packet_info.Add("TCP");
						packet_info.Add(tcp.Length.ToString());

						break;
					}
				default: {
						item = null;
						break;
					}
			}

			// update UI
			if (item != null) {
				item.SubItems.AddRange(packet_info.ToArray());
				object[] param = new object[2];
				param[0] = frames;
				object[] o = new object[3];
				o[0] = item;
				o[1] = ctrl[1];
				o[2] = packet;
				param[1] = o;
 				frames.BeginInvoke(new ParserHelper.UIHandlerEx(ParserHelper.UpdateFrameUI), param);
			}
		}
Exemplo n.º 17
0
 public Address(string address,string offset)
 {
     address = FormatAddress(address);
     UInt64 off;
     if (!UInt64.TryParse(offset, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out off))
         throw new Exception("invalid address: " + offset);
     
     if (!UInt64.TryParse(address, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out _address))
         throw new Exception("invalid address: " + address);
     _address = _address + off;
     _hexaddress = _address.ToString("X");
 }
Exemplo n.º 18
0
    void UpdateMailItems()
    {
        if (null == m_curItemResObj)
        {
            return;
        }

        // 记录上次正在操作的邮件,重新加载时直接选中
        string lastKey = null;

        if (null != m_curSelectItem)
        {
            lastKey = m_curSelectItem.gameObject.name;
        }

        m_curSelectItem = null;
        Utils.CleanGrid(MailListGrid);
        for (int i = 0; i < m_sortMailList.Count; i++)
        {
            System.UInt64 curKey = m_sortMailList[i];
            if (!MailData.UserMailMap.ContainsKey(curKey))
            {
                continue;
            }
            MailListItem curItem = MailListItem.CreateItem(MailListGrid, m_curItemResObj, curKey.ToString(), this, MailData.UserMailMap[curKey]);
            if (null == curItem)
            {
                continue;
            }
            if (null == m_curSelectItem && curKey.ToString() == lastKey)
            {
                ShowMailItem(curItem);
            }
        }

        MailListGrid.GetComponent <UIGrid>().Reposition();
        //MailListGrid.GetComponent<UITopGrid>().Recenter(m_bFirstUpdate);
        m_bFirstUpdate = false;

        if (null == m_curSelectItem && MailListGrid.transform.childCount > 0)
        {
            ShowMailItem(MailListGrid.transform.GetChild(0).GetComponent <MailListItem>());
        }

        CurMailGroup.SetActive(null != m_curSelectItem);
        if (RelationLogic.Instance() != null)
        {
            RelationLogic.Instance().ShowNewEmailBigRed();
        }
        // 邮件上限提示
        // LabelRecvTips.text = StrDictionary.GetClientDictionaryString("#{1252}", MailData.UserMailMap.Count);
    }
Exemplo n.º 19
0
        static StackObject *ToString_5(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 1);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.UInt64 instance_of_this_method = GetInstance(__domain, ptr_of_this_method, __mStack);

            var result_of_this_method = instance_of_this_method.ToString();

            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
Exemplo n.º 20
0
    MailData.UserMail GetMailByItem(MailListItem curItem)
    {
        if (null == curItem)
        {
            return(null);
        }
        System.UInt64 curMailID = 0;
        if (!System.UInt64.TryParse(curItem.gameObject.name, out curMailID))
        {
            LogModule.ErrorLog("can not parse cur mail id:" + curMailID.ToString() + " name : " + curItem.gameObject.name);
            CurMailGroup.SetActive(false);
            return(null);
        }

        if (!MailData.UserMailMap.ContainsKey(curMailID))
        {
            LogModule.ErrorLog("can not find cur mail id:" + curMailID.ToString());
            CurMailGroup.SetActive(false);
            return(null);
        }

        return(MailData.UserMailMap[curMailID]);
    }
Exemplo n.º 21
0
        private async Task LogKick(Server server, string userName, guid userId, string reason, SocketGuildUser issuedBy)
        {
            SocketTextChannel logChannel;

            if (!server.Config.LogBans || (logChannel = server.Guild.GetTextChannel(server.Config.ModChannelId)) == null)
            {
                return;
            }

            await logChannel.SendMessageSafe(
                GetLogMessage("User Kicked", (issuedBy == null ? "by unknown" : "by " + issuedBy.GetUsername()),
                              userName ?? "", userId.ToString(),
                              Utils.GetTimestamp(),
                              "Reason", reason));
        }
Exemplo n.º 22
0
        public override string ToString()
        {
            StringBuilder buff = new StringBuilder();

            buff.Append("<p=");
            buff.Append(AddrString);
            buff.Append(",s=");
            buff.Append(type.ToString());
            buff.Append(",k=");
            buff.Append(shapeKey.ToString("X"));
            buff.Append(",n=");
            buff.Append(isNativeShape.ToString());
            buff.Append(">");
            return(buff.ToString());
        }
Exemplo n.º 23
0
    public static BSShape GetReference(BSScene physicsScene, bool forceRebuild, BSPhysObject prim)
    {
        float lod;

        System.UInt64 newMeshKey = BSShape.ComputeShapeKey(prim.Size, prim.BaseShape, out lod);

        physicsScene.DetailLog("{0},BSShapeMesh,getReference,newKey={1},size={2},lod={3}",
                               prim.LocalID, newMeshKey.ToString("X"), prim.Size, lod);

        BSShapeConvexHull retConvexHull = null;

        lock (ConvexHulls)
        {
            if (ConvexHulls.TryGetValue(newMeshKey, out retConvexHull))
            {
                // The mesh has already been created. Return a new reference to same.
                retConvexHull.IncrementReference();
            }
            else
            {
                retConvexHull = new BSShapeConvexHull(new BulletShape());
                BulletShape convexShape = null;

                // Get a handle to a mesh to build the hull from
                BSShape baseMesh = BSShapeMesh.GetReference(physicsScene, false /* forceRebuild */, prim);
                if (baseMesh.physShapeInfo.isNativeShape)
                {
                    // We get here if the mesh was not creatable. Could be waiting for an asset from the disk.
                    // In the short term, we return the native shape and a later ForceBodyShapeRebuild should
                    //     get back to this code with a buildable mesh.
                    // TODO: not sure the temp native shape is freed when the mesh is rebuilt. When does this get freed?
                    convexShape = baseMesh.physShapeInfo;
                }
                else
                {
                    convexShape          = physicsScene.PE.BuildConvexHullShapeFromMesh(physicsScene.World, baseMesh.physShapeInfo);
                    convexShape.shapeKey = newMeshKey;
                    ConvexHulls.Add(convexShape.shapeKey, retConvexHull);
                }

                // Done with the base mesh
                baseMesh.Dereference(physicsScene);

                retConvexHull.physShapeInfo = convexShape;
            }
        }
        return(retConvexHull);
    }
        static StackObject *ToString_13(ILIntepreter __intp, StackObject *__esp, List <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 2);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.String format = (System.String) typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);
            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.UInt64 instance_of_this_method = GetInstance(__domain, ptr_of_this_method, __mStack);

            var result_of_this_method = instance_of_this_method.ToString(format);

            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
Exemplo n.º 25
0
        private async Task LogUnban(Server server, string userName, guid userId, SocketGuildUser issuedBy)
        {
            SocketTextChannel logChannel;

            if (!server.Config.LogBans || (logChannel = server.Guild.GetTextChannel(server.Config.ModChannelId)) == null)
            {
                return;
            }

            this.RecentlyUnbannedUserIDs.Add(userId);             //Don't trigger the on-event log message as well as this custom one.

            await logChannel.SendMessageSafe(
                GetLogMessage("User Unbanned", (issuedBy == null ? "by unknown" : "by " + issuedBy.GetUsername()),
                              userName ?? "", userId.ToString(),
                              Utils.GetTimestamp()));
        }
Exemplo n.º 26
0
        public string Print(IEvaluationService evaluationService = null)
        {
            const string separators        = "   +---+---+---+---+---+---+---+---+";
            const string fileMarkers       = "     A   B   C   D   E   F   G   H  ";
            const bool   useUnicodeSymbols = false;

            var infos = new List <string>();

            infos.Add("Hash key: " + Key.ToString("X").PadLeft(16, '0'));
            infos.Add("To move: " + (WhiteToMove ? "White" : "Black"));
            infos.Add("Material: " + (WhiteMaterial - BlackMaterial));
            infos.Add("White material: " + WhiteMaterial);
            infos.Add("Black material: " + BlackMaterial);
            if (evaluationService != null)
            {
                var score = evaluationService.Evaluate(this);
                if (!WhiteToMove)
                {
                    score = -score;
                }
                infos.Add("Evaluation: " + score);
            }

            var sb = new StringBuilder();

            for (var i = 7; i >= 0; i--)
            {
                sb.AppendLine(separators);
                sb.Append(" " + (i + 1) + " ");

                for (var j = 0; j < 8; j++)
                {
                    var piece     = ArrayBoard[i * 8 + j];
                    var pieceChar = useUnicodeSymbols ? ChessPiece.ChessPieceToSymbol(piece) : ChessPiece.ChessPieceToLetter(piece);
                    sb.Append($"| {pieceChar} ");
                }
                sb.Append("|   ");
                if (infos.Count > 7 - i)
                {
                    sb.Append(infos[7 - i]);
                }
                sb.AppendLine();
            }
            sb.AppendLine(separators);
            sb.AppendLine(fileMarkers);
            return(sb.ToString());
        }
Exemplo n.º 27
0
        /// <summary>
        /// Convert a number to another base system
        /// </summary>
        public static string Convert(UInt64 number, IdBase radix)
        {
            switch (radix)
            {
                case IdBase.Hexadecimal:
                    return number.ToString("X");
                case IdBase.Hexatrigesimal:
                    return Convert(number, Characters.Hexatrigesimal);
                case IdBase.Sexagesimal:
                    return Convert(number, Characters.Sexagesimal);
                case IdBase.Duosexagesimal:
                    return Convert(number, Characters.Duosexagesimal);
                case IdBase.WebId:
                    return Convert(number, Characters.ShortIdTable);
            }

            throw new Exception("Not handle " + radix);
        }
Exemplo n.º 28
0
        public static string FormatSizeString(System.UInt64 sizeBytes)
        {
            string[]    suffixes    = new string[] { "B", "KB", "MB", "GB", "TB" };
            const ulong denominator = 1024;
            ulong       comparator  = denominator;
            ulong       divider     = 1;

            foreach (string suffix in suffixes)
            {
                if (sizeBytes < comparator)
                {
                    return(((double)sizeBytes / (double)divider).ToString("F") + suffix);
                }
                divider     = comparator;
                comparator *= denominator;
            }

            return(sizeBytes.ToString());
        }
    private NodeTypeIndex GetTypeIndex(Address typeID, int objSize)
    {
        NodeTypeIndex ret;

        if (!m_typeID2TypeIndex.TryGetValue(typeID, out ret))
        {
            m_log.WriteLine("Error: Did not have a type definition for typeID 0x{0:x}", typeID);
            Trace.WriteLine(string.Format("Error: Did not have a type definition for typeID 0x{0:x}", typeID));

            var typeName = "UNKNOWN 0x" + typeID.ToString("x");
            ret = CreateType(typeName);
            m_typeID2TypeIndex[typeID] = ret;
        }

        if (objSize > 1000)
        {
            var type     = m_graph.GetType(ret, m_typeStorage);
            var suffix   = GetObjectSizeSuffix(objSize);    // indicates the size range
            var typeName = type.Name + suffix;

            // TODO FIX NOW worry about module collision
            if (!m_arrayNametoIndex.TryGetValue(typeName, out ret))
            {
                if (IsProjectN)
                {
                    ret = m_graph.CreateType(type.RawTypeID, type.Module, objSize, suffix);
                }
                else
                {
                    ret = CreateType(typeName, type.ModuleName);
                }

                m_arrayNametoIndex.Add(typeName, ret);
            }
        }
        return(ret);
    }
Exemplo n.º 30
0
        private async Task <ITextChannel> FindOrCreateThread(guid userId, bool sendUserInfo, bool sendCustomMessage = false)
        {
            IGuildUser user   = null;
            Server     server = this.Client.Servers.Values.FirstOrDefault(s => (user = s.Guild.Users.FirstOrDefault(u => u.Id == userId)) != null || (user = this.Client.DiscordClient.Rest.GetGuildUserAsync(s.Id, userId).GetAwaiter().GetResult()) != null);

            if (server == null || !this.Client.Servers.ContainsKey(this.Client.Config.ModmailServerId) || (server = this.Client.Servers[this.Client.Config.ModmailServerId]) == null)
            {
                return(null);
            }

            IChannel channel = server.Guild.Channels.FirstOrDefault(c => c is SocketTextChannel cc && (cc.Topic?.Contains(userId.ToString()) ?? false));

            if (channel == null)
            {
                channel = await server.Guild.CreateTextChannelAsync(user.GetUsername().Replace('#', '-'), c => {
                    c.Topic      = $"UserId: {userId}";
                    c.CategoryId = this.Client.Config.ModmailCategoryId;
                });

                if (sendUserInfo)
                {
                    string message = null;
                    if (sendCustomMessage && !string.IsNullOrEmpty(this.Client.Config.ModmailNewThreadMessage))
                    {
                        message = this.Client.Config.ModmailNewThreadMessage;
                    }
                    Embed embed = GetUserInfoEmbed(user);
                    ((ITextChannel)channel)?.SendMessageAsync(message, embed: embed);
                }
            }
            else
            {
                SocketGuildChannel socketGuildChannel = channel as SocketGuildChannel;
                await socketGuildChannel.ModifyAsync(c => c.CategoryId = this.Client.Config.ModmailCategoryId);
            }


            return(channel as ITextChannel);
        }
Exemplo n.º 31
0
 /// <summary>
 /// Converts the value of the specified 64-bit unsigned integer to its equivalent String representation.
 /// </summary>
 /// <param name="value">A 64-bit unsigned integer.</param>
 /// <returns>The String equivalent of the 64-bit unsigned integer value.</returns>
 
 public static String ToString(UInt64 value) { return value.ToString(); }
Exemplo n.º 32
0
 public void setTotal(UInt64 newTotal)
 {
     string strTotal = (this.txbxTotalClicks.Text);
     UInt64 total = Convert.ToUInt64(strTotal);
     total = newTotal;
     this.txbxTotalClicks.Text = total.ToString();
 }
Exemplo n.º 33
0
 public TypeUUID(UInt64 myUInt64)
     : this(myUInt64.ToString())
 {
 }
Exemplo n.º 34
0
        public IEnumerable <String> JsonSerializationClient(UInt64 Hash, List <TypeDef> Commands, ISchemaClosureGenerator SchemaClosureGenerator, String NamespaceName)
        {
            yield return("private class ApplicationClient implements IApplicationClient");

            yield return("{");

            yield return("    public var s : IJsonSender;");

            yield return("    public var clientCommandCallbacks : Map<String, Array<{commandHash : String, _callback : String -> Void}>>;");

            yield return("");

            yield return("    public function new()");

            yield return("    {");

            yield return("    }");

            yield return("");

            yield return("    public var hash(get, null) : String;");

            yield return("    public function get_hash() : String");

            yield return("    {");

            foreach (var _Line in Combine(Combine(Combine(Begin(), "        return \""), Hash.ToString("X16", System.Globalization.CultureInfo.InvariantCulture)), "\";"))
            {
                yield return(_Line);
            }
            yield return("    }");

            yield return("");

            yield return("    public function dequeueCallback(commandName : String) : Void");

            yield return("    {");

            yield return("        clientCommandCallbacks.get(commandName).shift();");

            yield return("    }");

            yield return("");

            yield return("    private function addCallback(commandName : String, commandHash : String, _callback : String -> Void) : Void");

            yield return("    {");

            yield return("        if (clientCommandCallbacks.exists(commandName))");

            yield return("        {");

            yield return("            clientCommandCallbacks.get(commandName).push({commandHash : commandHash, _callback : _callback});");

            yield return("        }");

            yield return("        else");

            yield return("        {");

            yield return("            var q = new Array<{commandHash : String, _callback : String -> Void}>();");

            yield return("            q.push({commandHash : commandHash, _callback : _callback});");

            yield return("            clientCommandCallbacks.set(commandName, q);");

            yield return("        }");

            yield return("    }");

            yield return("");

            foreach (var c in Commands)
            {
                if (c.OnClientCommand)
                {
                    var CommandNameString = GetEscapedStringLiteral(c.ClientCommand.FullName());
                    var RequestTypeString = GetSuffixedTypeString(c.ClientCommand.Name, c.ClientCommand.Version, "Request", NamespaceName);
                    var ReplyTypeString   = GetSuffixedTypeString(c.ClientCommand.Name, c.ClientCommand.Version, "Reply", NamespaceName);
                    var RequestName       = GetSuffixedTypeName(c.ClientCommand.Name, c.ClientCommand.Version, "Request", NamespaceName);
                    var ReplyName         = GetSuffixedTypeName(c.ClientCommand.Name, c.ClientCommand.Version, "Reply", NamespaceName);
                    var Name        = c.ClientCommand.GetTypeSpec().SimpleName(NamespaceName);
                    var CommandHash = ((UInt32)(SchemaClosureGenerator.GetSubSchema(new List <TypeDef> {
                        c
                    }, new List <TypeSpec> {
                    }).GetNonversioned().GetNonattributed().Hash().Bits(31, 0))).ToString("X8", System.Globalization.CultureInfo.InvariantCulture);
                    foreach (var _Line in Combine(Combine(Combine(Combine(Combine(Combine(Combine(Begin(), "public function "), GetEscapedIdentifier(LowercaseCamelize(Name))), "(r : "), RequestTypeString), ", _callback : "), ReplyTypeString), " -> Void) : Void"))
                    {
                        yield return(_Line == "" ? "" : "    " + _Line);
                    }
                    yield return("    " + "{");

                    foreach (var _Line in Combine(Combine(Combine(Begin(), "    var request = Json.stringify(JsonTranslator."), GetEscapedIdentifier(Combine(Combine(Begin(), LowercaseCamelize(RequestName)), "ToJson"))), "(r));"))
                    {
                        yield return(_Line == "" ? "" : "    " + _Line);
                    }
                    foreach (var _Line in Combine(Combine(Combine(Combine(Combine(Combine(Combine(Begin(), "    addCallback("), CommandNameString), ", \""), CommandHash), "\", function(parameters) { return _callback(JsonTranslator."), GetEscapedIdentifier(Combine(Combine(Begin(), LowercaseCamelize(ReplyName)), "FromJson"))), "(Json.parse(parameters))); });"))
                    {
                        yield return(_Line == "" ? "" : "    " + _Line);
                    }
                    foreach (var _Line in Combine(Combine(Combine(Combine(Combine(Begin(), "    s.send("), CommandNameString), ", \""), CommandHash), "\", request);"))
                    {
                        yield return(_Line == "" ? "" : "    " + _Line);
                    }
                    yield return("    " + "}");
                }
                else if (c.OnServerCommand)
                {
                    var Name            = c.ServerCommand.GetTypeSpec().SimpleName(NamespaceName);
                    var EventTypeString = GetSuffixedTypeString(c.ServerCommand.Name, c.ServerCommand.Version, "Event", NamespaceName);
                    foreach (var _Line in Combine(Combine(Combine(Combine(Combine(Begin(), "public var "), GetEscapedIdentifier(LowercaseCamelize(Name))), " : "), EventTypeString), " -> Void;"))
                    {
                        yield return(_Line == "" ? "" : "    " + _Line);
                    }
                    foreach (var _Line in Combine(Combine(Combine(Combine(Combine(Combine(Combine(Combine(Combine(Begin(), "public function "), GetEscapedIdentifier(Combine(Combine(Begin(), "raise"), Name))), "(e : "), EventTypeString), ") : Void { if ("), GetEscapedIdentifier(LowercaseCamelize(Name))), " != null) { "), GetEscapedIdentifier(LowercaseCamelize(Name))), "(e); } }"))
                    {
                        yield return(_Line == "" ? "" : "    " + _Line);
                    }
                }
            }
            yield return("}");

            yield return("");

            yield return("@:final");

            yield return("class JsonSerializationClient");

            yield return("{");

            yield return("    public function getApplicationClient() : IApplicationClient");

            yield return("    {");

            yield return("        return c;");

            yield return("    }");

            yield return("");

            yield return("    private var c : ApplicationClient;");

            yield return("    private var serverCommands : Map<String, {commandHash : String, _callback : String -> Void}>;");

            yield return("");

            yield return("    public function new(s : IJsonSender)");

            yield return("    {");

            yield return("        c = new ApplicationClient();");

            yield return("        c.s = s;");

            yield return("        c.clientCommandCallbacks = new Map<String, Array<{commandHash : String, _callback : String -> Void}>>();");

            yield return("        serverCommands = new Map<String, {commandHash : String, _callback : String -> Void}>();");

            foreach (var c in Commands)
            {
                if (c.OnServerCommand)
                {
                    var CommandNameString = GetEscapedStringLiteral(c.ServerCommand.FullName());
                    var EventTypeString   = GetSuffixedTypeString(c.ServerCommand.Name, c.ServerCommand.Version, "Event", NamespaceName);
                    var EventName         = GetSuffixedTypeName(c.ServerCommand.Name, c.ServerCommand.Version, "Event", NamespaceName);
                    var Name        = c.ServerCommand.GetTypeSpec().SimpleName(NamespaceName);
                    var CommandHash = ((UInt32)(SchemaClosureGenerator.GetSubSchema(new List <TypeDef> {
                        c
                    }, new List <TypeSpec> {
                    }).GetNonversioned().GetNonattributed().Hash().Bits(31, 0))).ToString("X8", System.Globalization.CultureInfo.InvariantCulture);
                    foreach (var _Line in Combine(Combine(Combine(Combine(Combine(Combine(Combine(Combine(Combine(Begin(), "serverCommands.set("), CommandNameString), ", {commandHash : \""), CommandHash), "\", _callback : function(parameters) { c."), GetEscapedIdentifier(Combine(Combine(Begin(), "raise"), Name))), "(JsonTranslator."), GetEscapedIdentifier(Combine(Combine(Begin(), LowercaseCamelize(EventName)), "FromJson"))), "(Json.parse(parameters))); }});"))
                    {
                        yield return(_Line == "" ? "" : "        " + _Line);
                    }
                }
            }
            yield return("    }");

            yield return("");

            yield return("    public function handleResult(commandName : String, commandHash : String, parameters : String) : Void");

            yield return("    {");

            yield return("        if (c.clientCommandCallbacks.exists(commandName))");

            yield return("        {");

            yield return("            var q = c.clientCommandCallbacks.get(commandName);");

            yield return("            if (q.length == 0)");

            yield return("            {");

            yield return("                throw \"InvalidOperationException: \" + commandName + \"@\" + commandHash;");

            yield return("            }");

            yield return("            var callbackPair = q[0];");

            yield return("            if (callbackPair.commandHash != commandHash)");

            yield return("            {");

            yield return("                throw \"InvalidOperationException: \" + commandName + \"@\" + commandHash;");

            yield return("            }");

            yield return("            q.shift();");

            yield return("            var _callback = callbackPair._callback;");

            yield return("            _callback(parameters);");

            yield return("            return;");

            yield return("        }");

            yield return("");

            yield return("        if (serverCommands.exists(commandName))");

            yield return("        {");

            yield return("            var callbackPair = serverCommands.get(commandName);");

            yield return("            if (callbackPair.commandHash != commandHash)");

            yield return("            {");

            yield return("                throw \"InvalidOperationException: \" + commandName + \"@\" + commandHash;");

            yield return("            }");

            yield return("            var _callback = callbackPair._callback;");

            yield return("            _callback(parameters);");

            yield return("            return;");

            yield return("        }");

            yield return("");

            yield return("        throw \"InvalidOperationException: \" + commandName + \"@\" + commandHash;");

            yield return("    }");

            yield return("}");
        }
Exemplo n.º 35
0
 static public int ToChars(UInt64 value, byte[] buffer, int offset)
 {
     return ToAsciiChars(value.ToString(null, NumberFormatInfo.InvariantInfo), buffer, offset);
 }
 public Boolean TestToString(UInt64 testSubject) {
 strLoc = "3498d";
 String b1 = "";
 String b2 = "";
 Boolean pass = false;
 Boolean excthrown = false;
 Object exc1 = null;
 Object exc2 = null;
 try {
 b1 = testSubject.ToString();
 pass = true;
 excthrown = false;
 } catch (Exception exc) {
 exc1 = exc;
 pass = false;
 excthrown = true;
 }
 try {
 b2 = Convert.ToString(testSubject);
 pass = pass & true;
 excthrown = false;
 } catch (Exception exc) {
 exc2 = exc;
 pass = false;
 excthrown = excthrown & true;
 }
 if(excthrown)
   if(exc1.GetType() == exc2.GetType())
     return true;
   else
     return false;
 else if(pass && b1.Equals(b2))
   return true;
 else
   return false;
 }	
Exemplo n.º 37
0
		public static SqlChars ToSqlChars(UInt64? p)         { return p.HasValue? new SqlChars(p.ToString().ToCharArray()): SqlChars.Null; }
Exemplo n.º 38
0
    private BulletShape CreatePhysicalMesh(BSScene physicsScene, BSPhysObject prim, System.UInt64 newMeshKey,
                                           PrimitiveBaseShape pbs, OMV.Vector3 size, float lod)
    {
        BulletShape newShape = new BulletShape();

        IMesh meshData = physicsScene.mesher.CreateMesh(prim.PhysObjectName, pbs, size, lod,
                                                        false, // say it is not physical so a bounding box is not built
                                                        false  // do not cache the mesh and do not use previously built versions
                                                        );

        if (meshData != null)
        {
            if (prim.PrimAssetState == BSPhysObject.PrimAssetCondition.Fetched)
            {
                // Release the fetched asset data once it has been used.
                pbs.SculptData      = new byte[0];
                prim.PrimAssetState = BSPhysObject.PrimAssetCondition.Unknown;
            }

            int[]   indices          = meshData.getIndexListAsInt();
            int     realIndicesIndex = indices.Length;
            float[] verticesAsFloats = meshData.getVertexListAsFloat();

            if (BSParam.ShouldRemoveZeroWidthTriangles)
            {
                // Remove degenerate triangles. These are triangles with two of the vertices
                //    are the same. This is complicated by the problem that vertices are not
                //    made unique in sculpties so we have to compare the values in the vertex.
                realIndicesIndex = 0;
                for (int tri = 0; tri < indices.Length; tri += 3)
                {
                    // Compute displacements into vertex array for each vertex of the triangle
                    int v1 = indices[tri + 0] * 3;
                    int v2 = indices[tri + 1] * 3;
                    int v3 = indices[tri + 2] * 3;
                    // Check to see if any two of the vertices are the same
                    if (!((verticesAsFloats[v1 + 0] == verticesAsFloats[v2 + 0] &&
                           verticesAsFloats[v1 + 1] == verticesAsFloats[v2 + 1] &&
                           verticesAsFloats[v1 + 2] == verticesAsFloats[v2 + 2]) ||
                          (verticesAsFloats[v2 + 0] == verticesAsFloats[v3 + 0] &&
                           verticesAsFloats[v2 + 1] == verticesAsFloats[v3 + 1] &&
                           verticesAsFloats[v2 + 2] == verticesAsFloats[v3 + 2]) ||
                          (verticesAsFloats[v1 + 0] == verticesAsFloats[v3 + 0] &&
                           verticesAsFloats[v1 + 1] == verticesAsFloats[v3 + 1] &&
                           verticesAsFloats[v1 + 2] == verticesAsFloats[v3 + 2]))
                        )
                    {
                        // None of the vertices of the triangles are the same. This is a good triangle;
                        indices[realIndicesIndex + 0] = indices[tri + 0];
                        indices[realIndicesIndex + 1] = indices[tri + 1];
                        indices[realIndicesIndex + 2] = indices[tri + 2];
                        realIndicesIndex += 3;
                    }
                }
            }
            physicsScene.DetailLog("{0},BSShapeMesh.CreatePhysicalMesh,key={1},origTri={2},realTri={3},numVerts={4}",
                                   BSScene.DetailLogZero, newMeshKey.ToString("X"), indices.Length / 3, realIndicesIndex / 3, verticesAsFloats.Length / 3);

            if (realIndicesIndex != 0)
            {
                newShape = physicsScene.PE.CreateMeshShape(physicsScene.World,
                                                           realIndicesIndex, indices, verticesAsFloats.Length / 3, verticesAsFloats);
            }
            else
            {
                // Force the asset condition to 'failed' so we won't try to keep fetching and processing this mesh.
                prim.PrimAssetState = BSPhysObject.PrimAssetCondition.Failed;
                physicsScene.Logger.DebugFormat("{0} All mesh triangles degenerate. Prim {1} at {2} in {3}",
                                                LogHeader, prim.PhysObjectName, prim.RawPosition, physicsScene.Name);
                physicsScene.DetailLog("{0},BSShapeMesh.CreatePhysicalMesh,allDegenerate,key={1}", prim.LocalID, newMeshKey);
            }
        }
        newShape.shapeKey = newMeshKey;

        return(newShape);
    }
Exemplo n.º 39
0
 public static string IntToHex(UInt64 value, int digits)
 {
     return value.ToString("X").PadLeft(digits, '0');
 }
Exemplo n.º 40
0
 public static unsafe string OSUInt64ToString(UInt64 n, string s, CultureInfo ci)
 {
     if (Utilities.IsWindows)
     {
         NumberFormatInfo nfi = NumberFormatInfoFromLCID(LCIDFromCultureInfo(ci));
         return n.ToString(s, nfi);
     }
     else
     {
         return OSNumberToStringMac(new IntPtr((void*)&n), s, ci, CFNumberType.kCFNumberLongLongType, n);
     }
 }
    /// <summary>
    /// Sets up the callbacks needed to do a heap dump (work need before processing the events()
    /// </summary>
    internal void SetupCallbacks(MemoryGraph memoryGraph, TraceEventDispatcher source, string processNameOrId = null, double startTimeRelativeMSec = 0)
    {
        m_graph            = memoryGraph;
        m_typeID2TypeIndex = new Dictionary <Address, NodeTypeIndex>(1000);
        m_moduleID2Name    = new Dictionary <Address, string>(16);
        m_arrayNametoIndex = new Dictionary <string, NodeTypeIndex>(32);
        m_objectToRCW      = new Dictionary <Address, RCWInfo>(100);
        m_nodeBlocks       = new Queue <GCBulkNodeTraceData>();
        m_edgeBlocks       = new Queue <GCBulkEdgeTraceData>();
        m_typeBlocks       = new Queue <GCBulkTypeTraceData>();
        m_staticVarBlocks  = new Queue <GCBulkRootStaticVarTraceData>();
        m_ccwBlocks        = new Queue <GCBulkRootCCWTraceData>();
        m_typeIntern       = new Dictionary <string, NodeTypeIndex>();
        m_root             = new MemoryNodeBuilder(m_graph, "[.NET Roots]");
        m_typeStorage      = m_graph.AllocTypeNodeStorage();

        // We also keep track of the loaded modules in the target process just in case it is a project N scenario.
        // (Not play for play but it is small).
        m_modules = new Dictionary <Address, Module>(32);

        m_ignoreEvents    = true;
        m_ignoreUntilMSec = startTimeRelativeMSec;

        m_processId = 0;        // defaults to a wildcard.
        if (processNameOrId != null)
        {
            if (!int.TryParse(processNameOrId, out m_processId))
            {
                m_processId   = -1;     // an illegal value.
                m_processName = processNameOrId;
            }
        }

        // Remember the module IDs too.
        Action <ModuleLoadUnloadTraceData> moduleCallback = delegate(ModuleLoadUnloadTraceData data)
        {
            if (data.ProcessID != m_processId)
            {
                return;
            }

            if (!m_moduleID2Name.ContainsKey((Address)data.ModuleID))
            {
                m_moduleID2Name[(Address)data.ModuleID] = data.ModuleILPath;
            }

            m_log.WriteLine("Found Module {0} ID 0x{1:x}", data.ModuleILFileName, (Address)data.ModuleID);
        };

        source.Clr.AddCallbackForEvents <ModuleLoadUnloadTraceData>(moduleCallback); // Get module events for clr provider
        // TODO should not be needed if we use CAPTURE_STATE when collecting.
        var clrRundown = new ClrRundownTraceEventParser(source);

        clrRundown.AddCallbackForEvents <ModuleLoadUnloadTraceData>(moduleCallback); // and its rundown provider.

        DbgIDRSDSTraceData lastDbgData = null;
        var symbolParser = new SymbolTraceEventParser(source);

        symbolParser.ImageIDDbgID_RSDS += delegate(DbgIDRSDSTraceData data)
        {
            if (data.ProcessID != m_processId)
            {
                return;
            }

            lastDbgData = (DbgIDRSDSTraceData)data.Clone();
        };

        source.Kernel.ImageGroup += delegate(ImageLoadTraceData data)
        {
            if (m_processId == 0)
            {
                return;
            }

            if (data.ProcessID != m_processId)
            {
                return;
            }

            Module module = new Module(data.ImageBase);
            module.Path      = data.FileName;
            module.Size      = data.ImageSize;
            module.BuildTime = data.BuildTime;
            if (lastDbgData != null && data.TimeStampRelativeMSec == lastDbgData.TimeStampRelativeMSec)
            {
                module.PdbGuid = lastDbgData.GuidSig;
                module.PdbAge  = lastDbgData.Age;
                module.PdbName = lastDbgData.PdbFileName;
            }
            m_modules[module.ImageBase] = module;
        };

        // TODO this does not work in the circular case
        source.Kernel.ProcessGroup += delegate(ProcessTraceData data)
        {
            if (0 <= m_processId || m_processName == null)
            {
                return;
            }

            if (string.Compare(data.ProcessName, processNameOrId, StringComparison.OrdinalIgnoreCase) == 0)
            {
                m_log.WriteLine("Found process id {0} for process Name {1}", processNameOrId, data.ProcessName);
                m_processId = data.ProcessID;
            }
            else
            {
                m_log.WriteLine("Found process {0} but does not match {1}", data.ProcessName, processNameOrId);
            }
        };

        source.Clr.GCStart += delegate(GCStartTraceData data)
        {
            // If this GC is not part of a heap dump, ignore it.
            // TODO FIX NOW if (data.ClientSequenceNumber == 0)
            //     return;

            if (data.TimeStampRelativeMSec < m_ignoreUntilMSec)
            {
                return;
            }

            if (m_processId == 0)
            {
                m_processId = data.ProcessID;
                m_log.WriteLine("Process wildcard selects process id {0}", m_processId);
            }
            if (data.ProcessID != m_processId)
            {
                m_log.WriteLine("GC Start found but Process ID {0} != {1} desired ID", data.ProcessID, m_processId);
                return;
            }

            if (!IsProjectN && data.ProviderGuid == ClrTraceEventParser.NativeProviderGuid)
            {
                IsProjectN = true;
            }

            if (data.Depth < 2 || data.Type != GCType.NonConcurrentGC)
            {
                m_log.WriteLine("GC Start found but not a Foreground Gen 2 GC");
                return;
            }

            if (data.Reason != GCReason.Induced)
            {
                m_log.WriteLine("GC Start not induced. Skipping.");
                return;
            }

            if (!m_seenStart)
            {
                m_gcID = data.Count;
                m_log.WriteLine("Found a Gen2 Induced non-background GC Start at {0:n3} msec GC Count {1}", data.TimeStampRelativeMSec, m_gcID);
                m_ignoreEvents      = false;
                m_seenStart         = true;
                memoryGraph.Is64Bit = (data.PointerSize == 8);
            }
        };



        source.Clr.GCStop += delegate(GCEndTraceData data)
        {
            if (m_ignoreEvents || data.ProcessID != m_processId)
            {
                return;
            }

            if (data.Count == m_gcID)
            {
                m_log.WriteLine("Found a GC Stop at {0:n3} for GC {1}, ignoring events from now on.", data.TimeStampRelativeMSec, m_gcID);
                m_ignoreEvents = true;

                if (m_nodeBlocks.Count == 0 && m_typeBlocks.Count == 0 && m_edgeBlocks.Count == 0)
                {
                    m_log.WriteLine("Found no node events, looking for another GC");
                    m_seenStart = false;
                    return;
                }

                // TODO we have to continue processing to get the module rundown events.
                // If we could be sure to get these early, we could optimized this.
                // source.StopProcessing();
            }
            else
            {
                m_log.WriteLine("Found a GC Stop at {0:n3} but id {1} != {2} Target ID", data.TimeStampRelativeMSec, data.Count, m_gcID);
            }
        };

        source.Clr.TypeBulkType += delegate(GCBulkTypeTraceData data)
        {
            // Don't check m_ignoreEvents here, as BulkType events can be emitted by other events...such as the GC allocation event.
            // This means that when setting m_processId to 0 in the command line may still lose type events.
            if (data.ProcessID != m_processId)
            {
                return;
            }

            m_typeBlocks.Enqueue((GCBulkTypeTraceData)data.Clone());
        };

        source.Clr.GCBulkNode += delegate(GCBulkNodeTraceData data)
        {
            if (m_ignoreEvents || data.ProcessID != m_processId)
            {
                return;
            }

            m_nodeBlocks.Enqueue((GCBulkNodeTraceData)data.Clone());
        };

        source.Clr.GCBulkEdge += delegate(GCBulkEdgeTraceData data)
        {
            if (m_ignoreEvents || data.ProcessID != m_processId)
            {
                return;
            }

            m_edgeBlocks.Enqueue((GCBulkEdgeTraceData)data.Clone());
        };

        source.Clr.GCBulkRootEdge += delegate(GCBulkRootEdgeTraceData data)
        {
            if (m_ignoreEvents || data.ProcessID != m_processId)
            {
                return;
            }

            MemoryNodeBuilder staticRoot = m_root.FindOrCreateChild("[static vars]");
            for (int i = 0; i < data.Count; i++)
            {
                var value = data.Values(i);
                var flags = value.GCRootFlag;
                if ((flags & GCRootFlags.WeakRef) == 0)     // ignore weak references. they are not roots.
                {
                    GCRootKind        kind = value.GCRootKind;
                    MemoryNodeBuilder root = m_root;
                    string            name;
                    if (kind == GCRootKind.Stack)
                    {
                        name = "[local vars]";
                    }
                    else
                    {
                        root = m_root.FindOrCreateChild("[other roots]");

                        if ((flags & GCRootFlags.RefCounted) != 0)
                        {
                            name = "[COM/WinRT Objects]";
                        }
                        else if (kind == GCRootKind.Finalizer)
                        {
                            name = "[finalizer Handles]";
                        }
                        else if (kind == GCRootKind.Handle)
                        {
                            if (flags == GCRootFlags.Pinning)
                            {
                                name = "[pinning Handles]";
                            }
                            else
                            {
                                name = "[strong Handles]";
                            }
                        }
                        else
                        {
                            name = "[other Handles]";
                        }

                        // Remember the root for later processing.
                        if (value.RootedNodeAddress != 0)
                        {
                            Address gcRootId = value.GCRootID;
                            if (gcRootId != 0 && IsProjectN)
                            {
                                Module gcRootModule = GetModuleForAddress(gcRootId);
                                if (gcRootModule != null)
                                {
                                    var staticRva     = (int)(gcRootId - gcRootModule.ImageBase);
                                    var staticTypeIdx = m_graph.CreateType(staticRva, gcRootModule, 0, " (static var)");
                                    var staticNodeIdx = m_graph.CreateNode();
                                    m_children.Clear();
                                    m_children.Add(m_graph.GetNodeIndex(value.RootedNodeAddress));
                                    m_graph.SetNode(staticNodeIdx, staticTypeIdx, 0, m_children);
                                    staticRoot.AddChild(staticNodeIdx);
                                    Trace.WriteLine("Got Static 0x" + gcRootId.ToString("x") + " pointing at 0x" + value.RootedNodeAddress.ToString("x") + " kind " + value.GCRootKind + " flags " + value.GCRootFlag);
                                    continue;
                                }
                            }

                            Trace.WriteLine("Got GC Root 0x" + gcRootId.ToString("x") + " pointing at 0x" + value.RootedNodeAddress.ToString("x") + " kind " + value.GCRootKind + " flags " + value.GCRootFlag);
                        }
                    }

                    root = root.FindOrCreateChild(name);
                    Address objId = value.RootedNodeAddress;
                    root.AddChild(m_graph.GetNodeIndex(objId));
                }
            }
        };

        source.Clr.GCBulkRCW += delegate(GCBulkRCWTraceData data)
        {
            if (m_ignoreEvents || data.ProcessID != m_processId)
            {
                return;
            }

            for (int i = 0; i < data.Count; i++)
            {
                GCBulkRCWValues comInfo = data.Values(i);
                m_objectToRCW[comInfo.ObjectID] = new RCWInfo(comInfo);
            }
        };

        source.Clr.GCBulkRootCCW += delegate(GCBulkRootCCWTraceData data)
        {
            if (m_ignoreEvents || data.ProcessID != m_processId)
            {
                return;
            }

            m_ccwBlocks.Enqueue((GCBulkRootCCWTraceData)data.Clone());
        };

        source.Clr.GCBulkRootStaticVar += delegate(GCBulkRootStaticVarTraceData data)
        {
            if (m_ignoreEvents || data.ProcessID != m_processId)
            {
                return;
            }

            m_staticVarBlocks.Enqueue((GCBulkRootStaticVarTraceData)data.Clone());
        };

        source.Clr.GCBulkRootConditionalWeakTableElementEdge += delegate(GCBulkRootConditionalWeakTableElementEdgeTraceData data)
        {
            if (m_ignoreEvents || data.ProcessID != m_processId)
            {
                return;
            }

            var otherRoots       = m_root.FindOrCreateChild("[other roots]");
            var dependentHandles = otherRoots.FindOrCreateChild("[Dependent Handles]");
            for (int i = 0; i < data.Count; i++)
            {
                var value = data.Values(i);
                // TODO fix this so that they you see this as an arc from source to target.
                // The target is alive only if the source ID (which is a weak handle) is alive (non-zero)
                if (value.GCKeyNodeID != 0)
                {
                    dependentHandles.AddChild(m_graph.GetNodeIndex(value.GCValueNodeID));
                }
            }
        };

        source.Clr.GCGenerationRange += delegate(GCGenerationRangeTraceData data)
        {
            if (m_ignoreEvents || data.ProcessID != m_processId)
            {
                return;
            }

            if (m_dotNetHeapInfo == null)
            {
                return;
            }

            // We want the 'after' ranges so we wait
            if (m_nodeBlocks.Count == 0)
            {
                return;
            }

            Address start = data.RangeStart;
            Address end   = start + data.RangeUsedLength;

            if (m_dotNetHeapInfo.Segments == null)
            {
                m_dotNetHeapInfo.Segments = new List <GCHeapDumpSegment>();
            }

            GCHeapDumpSegment segment = new GCHeapDumpSegment();
            segment.Start = start;
            segment.End   = end;

            switch (data.Generation)
            {
            case 0:
                segment.Gen0End = end;
                break;

            case 1:
                segment.Gen1End = end;
                break;

            case 2:
                segment.Gen2End = end;
                break;

            case 3:
                segment.Gen3End = end;
                break;

            default:
                throw new Exception("Invalid generation in GCGenerationRangeTraceData");
            }
            m_dotNetHeapInfo.Segments.Add(segment);
        };
    }
Exemplo n.º 42
0
        private void ReadWriteReg()
        {
            WDC_REG reg      = m_regs[0];
            DWORD   dwStatus = (DWORD)wdc_err.WD_STATUS_SUCCESS;
            BOOL    bIsRead  = (m_direction == RW.READ);

            if (!IsLegalDirection(0))
            {
                txtData.Text += "you have chosen to " + (bIsRead?
                                                         "read from" : "write to") + " a register which is " +
                                (bIsRead? "write-only" : "read-only") + Environment.NewLine;
                return;
            }

            switch (reg.dwSize)
            {
            case wdc_lib_consts.WDC_SIZE_8:
            {
                if (RW.READ == m_direction)
                {
                    dwStatus = (m_regType == ACTION_TYPE.CFG) ?
                               wdc_lib_decl.WDC_PciReadCfg8(m_device.Handle,
                                                            reg.dwOffset, ref m_bData) :
                               wdc_lib_decl.WDC_ReadAddr8(m_device.Handle,
                                                          reg.dwAddrSpace, reg.dwOffset, ref m_bData);
                }
                else
                {
                    dwStatus = (m_regType == ACTION_TYPE.CFG) ?
                               wdc_lib_decl.WDC_PciWriteCfg8(m_device.Handle,
                                                             reg.dwOffset, m_bData) :
                               wdc_lib_decl.WDC_WriteAddr8(m_device.Handle,
                                                           reg.dwAddrSpace, reg.dwOffset, m_bData);
                }
                break;
            }

            case wdc_lib_consts.WDC_SIZE_16:
            {
                if (RW.READ == m_direction)
                {
                    dwStatus = (m_regType == ACTION_TYPE.CFG) ?
                               wdc_lib_decl.WDC_PciReadCfg16(m_device.Handle,
                                                             reg.dwOffset, ref m_wData) :
                               wdc_lib_decl.WDC_ReadAddr16(m_device.Handle,
                                                           reg.dwAddrSpace, reg.dwOffset, ref m_wData);
                }
                else
                {
                    dwStatus = (m_regType == ACTION_TYPE.CFG) ?
                               wdc_lib_decl.WDC_PciWriteCfg16(m_device.Handle,
                                                              reg.dwOffset, m_wData) :
                               wdc_lib_decl.WDC_WriteAddr16(m_device.Handle,
                                                            reg.dwAddrSpace, reg.dwOffset, m_wData);
                }
                break;
            }

            case wdc_lib_consts.WDC_SIZE_32:
            {
                if (RW.READ == m_direction)
                {
                    dwStatus = (m_regType == ACTION_TYPE.CFG) ?
                               wdc_lib_decl.WDC_PciReadCfg32(m_device.Handle,
                                                             reg.dwOffset, ref m_u32Data) :
                               wdc_lib_decl.WDC_ReadAddr32(m_device.Handle,
                                                           reg.dwAddrSpace, reg.dwOffset, ref m_u32Data);
                }
                else
                {
                    dwStatus = (m_regType == ACTION_TYPE.CFG) ?
                               wdc_lib_decl.WDC_PciWriteCfg32(m_device.Handle,
                                                              reg.dwOffset, m_u32Data) :
                               wdc_lib_decl.WDC_WriteAddr32(m_device.Handle,
                                                            reg.dwAddrSpace, reg.dwOffset, m_u32Data);
                }
                break;
            }

            case wdc_lib_consts.WDC_SIZE_64:
            {
                if (RW.READ == m_direction)
                {
                    dwStatus = (m_regType == ACTION_TYPE.CFG) ?
                               wdc_lib_decl.WDC_PciReadCfg64(m_device.Handle,
                                                             reg.dwOffset, ref m_u64Data) :
                               wdc_lib_decl.WDC_ReadAddr64(m_device.Handle,
                                                           reg.dwAddrSpace, reg.dwOffset, ref m_u64Data);
                }
                else
                {
                    dwStatus = (m_regType == ACTION_TYPE.CFG) ?
                               wdc_lib_decl.WDC_PciWriteCfg64(m_device.Handle,
                                                              reg.dwOffset, m_u64Data) :
                               wdc_lib_decl.WDC_WriteAddr64(m_device.Handle,
                                                            reg.dwAddrSpace, reg.dwOffset, m_u64Data);
                }
                break;
            }
            }
            TraceLog((((DWORD)wdc_err.WD_STATUS_SUCCESS == dwStatus)?
                      (bIsRead? "read " : "wrote ") + "0x" +
                      ((reg.dwSize == wdc_lib_consts.WDC_SIZE_8)?
                       m_bData.ToString("X2"):
                       ((reg.dwSize == wdc_lib_consts.WDC_SIZE_16)?
                        m_wData.ToString("X4") :
                        ((reg.dwSize == wdc_lib_consts.WDC_SIZE_32)?
                         m_u32Data.ToString("X8") : m_u64Data.ToString("X16")))) +
                      (bIsRead? " from " : " to ") + "register " + reg.sName :
                      "failed to complete the transaction on register" + reg.sName),
                     (wdc_err)dwStatus);
        }
 public override void WriteUInt64(UInt64 value)
 {
     Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
     ed.WriteMessage(MethodInfo.GetCurrentMethod().Name + " = ");
     ed.WriteMessage(value.ToString() + "\n");
 }
Exemplo n.º 44
0
 public void WriteTag(string Tag, string Attribute, UInt64 Value)
 {
     WriteTag(Tag, Attribute, Value.ToString());
 }
Exemplo n.º 45
0
        private static void CodeHookCallback(Unicorn u, UInt64 addr, Int32 size, Object userData)
        {
            Console.Write("Tracing >>> 0x{0} ", addr.ToString("X"));

            var eipBuffer = new Byte[4];
            Utils.CheckError(u.RegRead(X86.UC_X86_REG_EIP, eipBuffer));

            var effectiveSize = Math.Min(16, size);
            var tmp = new Byte[effectiveSize];
            Utils.CheckError(u.MemRead(addr, tmp));

            foreach (var t in tmp)
            {
                Console.Write("{0} ", (0xFF & t).ToString("X"));
            }

            Console.WriteLine();
        }
Exemplo n.º 46
0
		public static SqlString ToSqlString(UInt64          p) { return p.ToString();                                                                     }
Exemplo n.º 47
0
 static public string ToString(UInt64 value) { return value.ToString(NumberFormatInfo.InvariantInfo); }
Exemplo n.º 48
0
		/// <summary>
		/// Reads an INI value as an <see cref="UInt64"/>.
		/// </summary>
		/// <param name="section">The section containing the value to be read.</param>
		/// <param name="key">The key of the value to be read.</param>
		/// <param name="def">The default value to use if the key is not present in the INI file.</param>
		/// <param name="path">The absolute path of the INI file.</param>
		/// <returns>The sepecifed INI value, as an <see cref="UInt64"/>.</returns>
		public static UInt64 GetPrivateProfileUInt64(string section, string key, UInt64 def, string path)
		{
			string strValue = GetPrivateProfileString(section, key, def.ToString(), path);
			return UInt64.Parse(strValue);
		}
Exemplo n.º 49
0
 public IEnumerable <String> GetTypeVersion(String SimpleName, UInt64 Hash)
 {
     foreach (var _Line in Combine(Combine(Combine(Combine(Combine(Begin(), "constexpr static std::uint64_t "), GetEscapedIdentifier(SimpleName)), " = 0x"), Hash.ToString("X16", System.Globalization.CultureInfo.InvariantCulture)), "ull;"))
     {
         yield return(_Line);
     }
 }
Exemplo n.º 50
0
 /// <summary>
 /// Converts the value of the specified nullable 64-bit unsigned integer to its equivalent SqlChars representation.
 /// </summary>
 /// <param name="value">A nullable 64-bit unsigned integer.</param>
 /// <returns>The equivalent SqlChars.</returns>
 
 public static SqlChars ToSqlChars(UInt64? value) { return value.HasValue ? new SqlChars(value.ToString().ToCharArray()) : SqlChars.Null; }
Exemplo n.º 51
0
 /// <summary>
 /// Set bits within an integer.
 /// </summary>
 /// <param name="raw">Integer to modify</param>
 /// <param name="offset">Offset of least-significant bit to modify</param>
 /// <param name="length">Number of bits to modify</param>
 /// <param name="value">Value to assign to target bits</param>
 /// <param name="desc">Human-readable description of bits (for error messages)</param>
 public static void SetBits(ref UInt64 raw, int offset, int length, UInt64 value, string desc)
 {
     UInt64 valueMask = MakeBitMask(0, length);
     if ((value & valueMask) != value)
     {
         throw new ArgumentOutOfRangeException(String.Format(
             "{0} value does not fit within {1} bits: {2}",
             desc, length, "0x" + value.ToString("X")
             ));
     }
     UInt64 mask = MakeBitMask(offset, length);
     raw &= ~mask;
     raw |= value << offset;
 }
Exemplo n.º 52
0
 /// <summary>
 /// Converts the value of the specified nullable 64-bit unsigned integer to its equivalent SqlString representation.
 /// </summary>
 /// <param name="value">A nullable 64-bit unsigned integer.</param>
 /// <returns>The SqlString equivalent of the nullable 64-bit unsigned integer value.</returns>
 
 public static SqlString ToSqlString(UInt64? value) { return value.HasValue ? value.ToString() : SqlString.Null; }
Exemplo n.º 53
0
		static void PrintValue(UInt64 v)
		{
			string s = v.ToString();
			for (int i = 0; i + s.Length < 6; i++)
				System.Console.Write(" ");
			System.Console.Write(s);
		}
Exemplo n.º 54
0
        private static String InternalFormattedHexString(Object value)
        {
            TypeCode typeCode = Convert.GetTypeCode(value);

            switch (typeCode)
            {
            case TypeCode.SByte:
            {
                Byte result = (byte)(sbyte)value;
                return(result.ToString("X2", null));
            }

            case TypeCode.Byte:
            {
                Byte result = (byte)value;
                return(result.ToString("X2", null));
            }

            case TypeCode.Int16:
            {
                UInt16 result = (UInt16)(Int16)value;
                return(result.ToString("X4", null));
            }

            case TypeCode.UInt16:
            {
                UInt16 result = (UInt16)value;
                return(result.ToString("X4", null));
            }

            case TypeCode.UInt32:
            {
                UInt32 result = (UInt32)value;
                return(result.ToString("X8", null));
            }

            case TypeCode.Int32:
            {
                UInt32 result = (UInt32)(int)value;
                return(result.ToString("X8", null));
            }

            case TypeCode.UInt64:
            {
                UInt64 result = (UInt64)value;
                return(result.ToString("X16", null));
            }


            case TypeCode.Int64:
            {
                UInt64 result = (UInt64)(Int64)value;
                return(result.ToString("X16", null));
            }


            // All unsigned types will be directly cast
            default:
                BCLDebug.Assert(false, "Invalid Object type in Format");
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
            }
        }
Exemplo n.º 55
0
        public override ulong GetSize(Address objRef)
        {
            ulong size;
            uint pointerSize = (uint)DesktopHeap.PointerSize;
            if (_componentSize == 0)
            {
                size = _baseSize;
            }
            else
            {
                uint count = 0;
                uint countOffset = pointerSize;
                ulong loc = objRef + countOffset;

                var cache = DesktopHeap.MemoryReader;
                if (!cache.Contains(loc))
                {
                    var runtimeCache = DesktopHeap.DesktopRuntime.MemoryReader;
                    if (runtimeCache.Contains(loc))
                        cache = DesktopHeap.DesktopRuntime.MemoryReader;
                }

                if (!cache.ReadDword(loc, out count))
                    throw new Exception("Could not read from heap at " + objRef.ToString("x"));

                // Strings in v4+ contain a trailing null terminator not accounted for.
                if (DesktopHeap.StringType == this && DesktopHeap.DesktopRuntime.CLRVersion != DesktopVersion.v2)
                    count++;

                size = count * (ulong)_componentSize + _baseSize;
            }

            uint minSize = pointerSize * 3;
            if (size < minSize)
                size = minSize;
            return size;
        }
Exemplo n.º 56
0
    /// <summary>
    /// This demo shows you how to create a a graph of memory and turn it into a stackSource with MemoryGraphStackSource.
    /// </summary>
    public void DemoMemoryGraph()
    {
        // Make a custom stack source that was created out of nothing.   InternStackSouce is your friend here.
        MemoryGraph myGraph = new MemoryGraph(1000);

        // Create a memory graph out of 'nothing'.  In the example below we create a graph where the root which points at
        // 'base' which has a bunch of children, each of which have a child that points back to the base node (thus it has lots of cycles)

        var baseIdx = myGraph.GetNodeIndex(0);                                       // Define the NAME (index) for the of the graph (but we have not defined what is in it)

        GrowableArray <NodeIndex> children     = new GrowableArray <NodeIndex>(1);   // This array is reused again and again for each child.
        GrowableArray <NodeIndex> rootChildren = new GrowableArray <NodeIndex>(100); // This is used to create the children of the root;

        //Here I make up a graph of memory addresses at made up locations
        for (Address objAddr = 0x100000; objAddr < 0x200000; objAddr += 0x10000)
        {
            NodeIndex nodeIdx = myGraph.GetNodeIndex(objAddr);                          // Create the name (node index) for the child
            // Make a type for the child.  In this case we make a new type for each node, normally you keep these in a interning table so that
            // every distinct type name has exactly one type index.   Interning is not STRICTLLY needed, but the representation assumes that
            // there are many more nodes than there are types.
            NodeTypeIndex nodeTypeIdx = myGraph.CreateType("MyType_" + objAddr.ToString(), "MyModule");
            // Create a list of children for this node in this case, each node has exactly one child, which is the root node.
            children.Clear();
            children.Add(baseIdx);
            // Actually define the node with the given name (nodeIdx), type, size (100 in our case) and children;
            myGraph.SetNode(nodeIdx, nodeTypeIdx, 100, children);

            rootChildren.Add(nodeIdx);      // Remember this node name as belonging to the things that the root points at.
        }

        // At this point we have everything we need to define the base node, do it here.
        myGraph.SetNode(baseIdx, myGraph.CreateType("[Base]"), 0, rootChildren);

        // Create a root node that points at the base node.
        myGraph.RootIndex = myGraph.GetNodeIndex(1);
        children.Clear();
        children.Add(baseIdx);
        myGraph.SetNode(myGraph.RootIndex, myGraph.CreateType("[ROOT]"), 0, children);

        // Note that the raw graph APIs force you to know all the children of a particular node before you can define
        // the node.  There is a class call MemoryNodeBuilder which makes this a bit nicer in that you can incrementally
        // add children to nodes and then 'finalize' them all at once at the end.   Ideally, however you don't have many
        // nodes that need MemoryNodeBuilder as they are more expensive to build.

        // So far, the graph is in 'write mode' where only creation APIs are allowed.   Change to 'Read Mode' which no writes
        // are allowed by read APIs are allowed.  (We may lift this restriction at some point).
        myGraph.AllowReading();

        // I can  dump it as XML to look at it.
        using (var writer = File.CreateText("MyGraph.dump.xml"))
        {
            myGraph.WriteXml(writer);
        }

        // I can write the graph out as a file and read it back in later.
        // myGraph.WriteAsBinaryFile("myGraph.gcGraph");
        // var roundTrip = MemoryGraph.ReadFromBinaryFile("myGraph.gcGraph");

        // OK we have a graph, turn it into a stack source so that I can view it.
        MemoryGraphStackSource myStackSource = new MemoryGraphStackSource(myGraph, LogFile);

        // Create a Stacks class (which remembers all the Filters, Scaling policy and other things the viewer wants.
        Stacks stacks = new Stacks(myStackSource);

        // If you wanted to, you can change the filtering ...
        stacks.Filter.GroupRegExs             = "";
        stacks.Filter.MinInclusiveTimePercent = "";

        // And view it.
        OpenStackViewer(stacks);
    }
Exemplo n.º 57
0
 private string decToHex( UInt64 dec )
 {
     return String.Concat( "0x", dec.ToString( "X" ) );
 }
Exemplo n.º 58
0
		public static string ToString(UInt64 value)
		{
			return value.ToString(CultureInfo.InvariantCulture);
		}
Exemplo n.º 59
0
        public static INode AddNode(this IGraph myIGraph, UInt64 myUInt64Id)
        {
            if (myIGraph == null)
                throw new ArgumentNullException("myIGraph must not be null!");

            return myIGraph.AddNode(myUInt64Id.ToString());
        }
Exemplo n.º 60
0
    void OnClickOnOK(GameObject go)
    {
        GlobalAudioMgr.Instance.PlayOrdianryMusic(Audio.OrdianryMusic.m_BtnMusic);

        if (SDKMgr.IS_SDK_CHANNEL || SDKMgr.IS_APP_STORE_VER)
        {
            System.UInt64 user_item_id = PlayerRole.Instance.RoleInfo.RoleMe.GetUserID();
            user_item_id = (user_item_id << 32) | m_ItemID;
            const int change = 100;
            if (m_PayType == PayType.Diamond)
            {
                SDKMgr.Instance.SDK.Pay(m_Amount * change, "钻石", m_Count, m_ItemID.ToString(), user_item_id.ToString(), m_ItemID);
            }
            else if (m_PayType == PayType.Gold)
            {
                SDKMgr.Instance.SDK.Pay(m_Amount * change, "金币", m_Count, m_ItemID.ToString(), user_item_id.ToString(), m_ItemID);
            }
        }
        else
        {
            PlayerRole.Instance.RoleRecharge.SendRecharge(m_ItemID, SDKMgr.Instance.IsServerOrder);
        }

        ShutDown();
        GlobalHallUIMgr.Instance.ShutDownPayWnd();
        //SDKMgr.Instance.SDK.Pay();
        GlobalAudioMgr.Instance.PlayOrdianryMusic(Audio.OrdianryMusic.m_CloseUI);
        // ShutDown();
    }