System.Guid.ToByteArray()

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

679 Examples 7

19 View Source File : SmartNamePropertyData.cs
License : MIT License
Project Creator : atenfyr

public override int Write(replacedetBinaryWriter writer, bool includeHeader)
        {
            if (includeHeader)
            {
                writer.Write((byte)0);
            }

            long here = writer.BaseStream.Position;

            writer.Write(DisplayName);
            if (writer.replacedet.GetCustomVersion<FAnimPhysObjectVersion>() < FAnimPhysObjectVersion.RemoveUIDFromSmartNameSerialize)
            {
                writer.Write(SmartNameID);
            }
            if (writer.replacedet.GetCustomVersion<FAnimPhysObjectVersion>() < FAnimPhysObjectVersion.SmartNameRefactorForDeterministicCooking)
            {
                writer.Write(TempGUID.ToByteArray());
            }

            return (int)(writer.BaseStream.Position - here);
        }

19 View Source File : SlimWriter.cs
License : MIT License
Project Creator : azist

public override void Write(Guid value)
    {
      this.Write(value.ToByteArray());
    }

19 View Source File : JsonReader.cs
License : MIT License
Project Creator : akaskela

public virtual byte[] ReadAsBytes()
        {
            JsonToken t = GetContentToken();

            if (t == JsonToken.None)
            {
                return null;
            }

            if (TokenType == JsonToken.StartObject)
            {
                ReadIntoWrappedTypeObject();

                byte[] data = ReadAsBytes();
                ReaderReadAndreplacedert();

                if (TokenType != JsonToken.EndObject)
                {
                    throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
                }

                SetToken(JsonToken.Bytes, data, false);
                return data;
            }

            switch (t)
            {
                case JsonToken.String:
                {
                    // attempt to convert possible base 64 or GUID string to bytes
                    // GUID has to have format 00000000-0000-0000-0000-000000000000
                    string s = (string)Value;

                    byte[] data;

                    Guid g;
                    if (s.Length == 0)
                    {
                        data = new byte[0];
                    }
                    else if (ConvertUtils.TryConvertGuid(s, out g))
                    {
                        data = g.ToByteArray();
                    }
                    else
                    {
                        data = Convert.FromBase64String(s);
                    }

                    SetToken(JsonToken.Bytes, data, false);
                    return data;
                }
                case JsonToken.Null:
                case JsonToken.EndArray:
                    return null;
                case JsonToken.Bytes:
                    if (ValueType == typeof(Guid))
                    {
                        byte[] data = ((Guid)Value).ToByteArray();
                        SetToken(JsonToken.Bytes, data, false);
                        return data;
                    }

                    return (byte[])Value;
                case JsonToken.StartArray:
                    return ReadArrayIntoByteArray();
            }

            throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
        }

19 View Source File : GuidFieldMapping.cs
License : MIT License
Project Creator : aquilahkj

public override object ToInsert(object enreplacedy, bool refreshField)
        {
            var value = Handler.Get(enreplacedy);
            if (Equals(value, null))
            {
                if (_defaultValue != null)
                {
                    if (refreshField)
                    {
                        Handler.Set(enreplacedy, _default);
                    }

                    return _defaultValue;
                }

                if (IsNullable)
                {
                    return null;
                }

                if (refreshField)
                {
                    Handler.Set(enreplacedy, _min);
                }

                return _minValue;
            }

            var guid = (Guid) value;
            if (_mode == GuidStoreMode.Raw)
            {
                value = guid.ToByteArray();
            }
            else
            {
                value = guid.ToString();
            }

            return value;
        }

19 View Source File : GuidUtils.cs
License : Apache License 2.0
Project Creator : AmpScm

public static Guid CreateGuid(Guid baseUuid, byte[] hashData)
        {
            if (baseUuid == Guid.Empty)
                throw new ArgumentNullException("baseUuid");
            else if (hashData == null)
                throw new ArgumentNullException("hashData");

            // See RFC 4122 for C implementation examples

            byte[] hash;
            using (SHA1 sha1 = SHA1.Create())
            {
                sha1.TransformBlock(GuidToNetworkOrder(baseUuid.ToByteArray()), 0, 16, null, 0);
                sha1.TransformFinalBlock(hashData, 0, hashData.Length);

                hash = sha1.Hash;
            }

            hash = ToHostOrder(hash); // Treat as guid

            Int32 timeLow = BitConverter.ToInt32(hash, 0);
            Int16 timeMid = BitConverter.ToInt16(hash, 4);
            Int16 timeHiAndVersion = BitConverter.ToInt16(hash, 6);
            Byte clockSeqHi = hash[8];
            Byte clockSeqLow = hash[9];

            return new Guid(
                timeLow,
                timeMid,
                (short)((timeHiAndVersion & 0xFFF) | (5 << 12)),
                (byte)((clockSeqHi & 0x3F) | 0x80),
                clockSeqLow,
                hash[10],
                hash[11],
                hash[12],
                hash[13],
                hash[14],
                hash[15]);
        }

19 View Source File : GuidHelper.cs
License : MIT License
Project Creator : aishang2015

public Guid Next()
        {
            var guidBytes = Guid.NewGuid().ToByteArray();
            var counterBytes = BitConverter.GetBytes(Interlocked.Increment(ref _counter));

            if (!BitConverter.IsLittleEndian)
            {
                Array.Reverse(counterBytes);
            }

            guidBytes[08] = counterBytes[1];
            guidBytes[09] = counterBytes[0];
            guidBytes[10] = counterBytes[7];
            guidBytes[11] = counterBytes[6];
            guidBytes[12] = counterBytes[5];
            guidBytes[13] = counterBytes[4];
            guidBytes[14] = counterBytes[3];
            guidBytes[15] = counterBytes[2];

            return new Guid(guidBytes);
        }

19 View Source File : Export.cs
License : MIT License
Project Creator : atenfyr

public object Clone()
        {
            var res = (Export)MemberwiseClone();
            res.Extras = (byte[])this.Extras.Clone();
            res.PackageGuid = new Guid(this.PackageGuid.ToByteArray());
            return res;
        }

19 View Source File : EndianUtilities.cs
License : MIT License
Project Creator : ADeltaX

public static void WriteBytesBigEndian(Guid val, byte[] buffer, int offset)
        {
            byte[] le = val.ToByteArray();
            WriteBytesBigEndian(ToUInt32LittleEndian(le, 0), buffer, offset + 0);
            WriteBytesBigEndian(ToUInt16LittleEndian(le, 4), buffer, offset + 4);
            WriteBytesBigEndian(ToUInt16LittleEndian(le, 6), buffer, offset + 6);
            Array.Copy(le, 8, buffer, offset + 8, 8);
        }

19 View Source File : MiscUtilsTest.cs
License : MIT License
Project Creator : azist

[Run]
    public void GuidToNetworkByteOrder()
    {
      var guid = Guid.Parse("AECBF3B2-C90E-4F2D-B51C-4EBABECF4338");
      var std = guid.ToByteArray();

      Aver.AreEqual(0xB2, std[0]); // aver MSFT improper LE byte order
      Aver.AreEqual(0xAE, std[3]); // aver MSFT improper LE byte order

      var azos = guid.ToNetworkByteOrder();

      Aver.AreEqual(0xAE, azos[0]);
      Aver.AreEqual(0xCB, azos[1]);
      Aver.AreEqual(0xF3, azos[2]);
      Aver.AreEqual(0xB2, azos[3]);

      Aver.AreEqual(0xC9, azos[4]);
      Aver.AreEqual(0x0E, azos[5]);

      Aver.AreEqual(0x4F, azos[6]);
      Aver.AreEqual(0x2D, azos[7]);

      Aver.AreEqual(0xB5, azos[8]);
      Aver.AreEqual(0x1C, azos[9]);

      Aver.AreEqual(0x4E, azos[10]);
      Aver.AreEqual(0xBA, azos[11]);
      Aver.AreEqual(0xBE, azos[12]);
      Aver.AreEqual(0xCF, azos[13]);
      Aver.AreEqual(0x43, azos[14]);
      Aver.AreEqual(0x38, azos[15]);
    }

19 View Source File : BloomTests.cs
License : MIT License
Project Creator : AElfProject

[Fact]
        public void Length_Test()
        {
            var bloom = new Bloom();
            bloom.Data.Length.ShouldBe(0);
            
            var bloomData = Guid.NewGuid().ToByteArray();
            Should.Throw<InvalidOperationException>(
                () =>
                {
                    new Bloom(bloomData);
                });
        }

19 View Source File : GuidHeap.cs
License : GNU General Public License v3.0
Project Creator : anydream

public IEnumerable<KeyValuePair<uint, byte[]>> GetAllRawData() {
			uint offset = 0;
			foreach (var guid in guids) {
				yield return new KeyValuePair<uint, byte[]>(offset, guid.ToByteArray());
				offset += 16;
			}
		}

19 View Source File : GuidExtensions.cs
License : GNU General Public License v3.0
Project Creator : AndreiFedarets

public static Guid ReverseBits(this Guid guid)
        {
            byte[] data = guid.ToByteArray();
            for (int i = 0; i < data.Length; i++)
            {
                data[i] = (byte)(data[i] ^ 255);
            }
            Guid result = new Guid(data);
            return result;
        }

19 View Source File : Snapshot.cs
License : GNU General Public License v3.0
Project Creator : aiportal

[Obsolete]
		public byte[] ToBinary()
		{
			using (MemoryStream ms = new MemoryStream())
			using(BinaryWriter bw = new BinaryWriter(ms))
			{
				bw.Write(new byte[] { 1, 2, 6, 0 });
				bw.Write(new Guid(SessionId).ToByteArray());		// 16 bytes.
				bw.Write(new Guid(SnapshotId).ToByteArray());		// 16 bytes.
				bw.Write(SnapTime.ToBinary());						// 8 bytes.
				
				bw.Write(ProcessId);
				bw.Write(ProcessName);
				bw.Write(FileName);

				bw.Write(WindowHandle);
				bw.Write(WindowRect.X);
				bw.Write(WindowRect.Y);
				bw.Write(WindowRect.Width);
				bw.Write(WindowRect.Height);
				bw.Write(Windowreplacedle);
				bw.Write(WindowUrl);

				bw.Write(ControlText);
				bw.Write(InputText);

				//bw.Write((int)Mouse.ClickOption);
				//bw.Write(Mouse.X);
				//bw.Write(Mouse.Y);

				bw.Write(IsGrayScale);
				bw.Write(ImageData.Length);
				bw.Write(ImageData);
				bw.Write(EventsData.Length);
				bw.Write(EventsData);

				bw.Flush();
				return ms.ToArray();
			}
		}

19 View Source File : GuidFieldMapping.cs
License : MIT License
Project Creator : aquilahkj

public override object ToUpdate(object enreplacedy, bool refreshField)
        {
            var value = Handler.Get(enreplacedy);
            if (Equals(value, null))
            {
                if (IsNullable)
                {
                    return null;
                }

                if (refreshField)
                {
                    Handler.Set(enreplacedy, _min);
                }

                return _minValue;
            }

            var guid = (Guid) value;
            if (_mode == GuidStoreMode.Raw)
            {
                value = guid.ToByteArray();
            }
            else
            {
                value = guid.ToString();
            }

            return value;
        }

19 View Source File : Serializer.cs
License : MIT License
Project Creator : ADeltaX

public static byte[] FromGuid(Guid data, DateTimeOffset? timestamp = null)
            => data.ToByteArray().AppendTimestamp(timestamp);

19 View Source File : StructPropertyData.cs
License : MIT License
Project Creator : atenfyr

protected override void HandleCloned(PropertyData res)
        {
            StructPropertyData cloningProperty = (StructPropertyData)res;
            cloningProperty.StructType = (FName)this.StructType.Clone();
            cloningProperty.StructGUID = new Guid(this.StructGUID.ToByteArray());

            List<PropertyData> newData = new List<PropertyData>(this.Value.Count);
            for (int i = 0; i < this.Value.Count; i++)
            {
                newData.Add((PropertyData)this.Value[i].Clone());
            }
            cloningProperty.Value = newData;
        }

19 View Source File : JsonTextReader.cs
License : MIT License
Project Creator : akaskela

private void ParseString(char quote, ReadType readType)
        {
            _charPos++;

            ShiftBufferIfNeeded();
            ReadStringIntoBuffer(quote);
            SetPostValueState(true);

            switch (readType)
            {
                case ReadType.ReadAsBytes:
                    Guid g;
                    byte[] data;
                    if (_stringReference.Length == 0)
                    {
                        data = new byte[0];
                    }
                    else if (_stringReference.Length == 36 && ConvertUtils.TryConvertGuid(_stringReference.ToString(), out g))
                    {
                        data = g.ToByteArray();
                    }
                    else
                    {
                        data = Convert.FromBase64CharArray(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length);
                    }

                    SetToken(JsonToken.Bytes, data, false);
                    break;
                case ReadType.Readreplacedtring:
                    string text = _stringReference.ToString();

                    SetToken(JsonToken.String, text, false);
                    _quoteChar = quote;
                    break;
                case ReadType.ReadAsInt32:
                case ReadType.ReadAsDecimal:
                case ReadType.ReadAsBoolean:
                    // caller will convert result
                    break;
                default:
                    if (_dateParseHandling != DateParseHandling.None)
                    {
                        DateParseHandling dateParseHandling;
                        if (readType == ReadType.ReadAsDateTime)
                        {
                            dateParseHandling = DateParseHandling.DateTime;
                        }
#if !NET20
                        else if (readType == ReadType.ReadAsDateTimeOffset)
                        {
                            dateParseHandling = DateParseHandling.DateTimeOffset;
                        }
#endif
                        else
                        {
                            dateParseHandling = _dateParseHandling;
                        }

                        if (dateParseHandling == DateParseHandling.DateTime)
                        {
                            DateTime dt;
                            if (DateTimeUtils.TryParseDateTime(_stringReference, DateTimeZoneHandling, DateFormatString, Culture, out dt))
                            {
                                SetToken(JsonToken.Date, dt, false);
                                return;
                            }
                        }
#if !NET20
                        else
                        {
                            DateTimeOffset dt;
                            if (DateTimeUtils.TryParseDateTimeOffset(_stringReference, DateFormatString, Culture, out dt))
                            {
                                SetToken(JsonToken.Date, dt, false);
                                return;
                            }
                        }
#endif
                    }

                    SetToken(JsonToken.String, _stringReference.ToString(), false);
                    _quoteChar = quote;
                    break;
            }
        }

19 View Source File : EthernetPort.cs
License : MIT License
Project Creator : Azer0s

public void Init()
        {
            var vendorBytes = new byte[] {0x10, 0x14, 0x20};
            var guid = Guid.NewGuid().ToByteArray();
            MACAddress = new[] {vendorBytes[0], vendorBytes[1], vendorBytes[2], guid[0], guid[1], guid[2]};
            Log.Trace(_device.Hostname, $"Initialized port {Name} with MAC Address {MACAddress.ToMACAddressString()}");
        }

19 View Source File : BclHelpers.cs
License : MIT License
Project Creator : 404Lcc

public static void WriteGuid(Guid value, ProtoWriter dest)
        {
            byte[] blob = value.ToByteArray();

            SubItemToken token = ProtoWriter.StartSubItem(null, dest);
            if (value != Guid.Empty)
            {
                ProtoWriter.WriteFieldHeader(FieldGuidLow, WireType.Fixed64, dest);
                ProtoWriter.WriteBytes(blob, 0, 8, dest);
                ProtoWriter.WriteFieldHeader(FieldGuidHigh, WireType.Fixed64, dest);
                ProtoWriter.WriteBytes(blob, 8, 8, dest);
            }
            ProtoWriter.EndSubItem(token, dest);
        }

19 View Source File : IOUtilsTests.cs
License : MIT License
Project Creator : azist

[Run("!guidbench", "")]
    public void BenchmarkFastGuidEncoding()
    {
      const int CNT = 25_000_000;
      var v = Guid.Parse("3FAF3D3E-1DEA-43E8-8684-DF046CC10498");
      var buf = new byte[32];

      var t = Azos.Time.Timeter.StartNew();
      for (var i = 0; i < CNT; i++)
      {
        v.ToByteArray();
      }
      t.Stop();

      var e1 = t.ElapsedSec;
      t = Azos.Time.Timeter.StartNew();
      for (var i = 0; i < CNT; i++)
      {
        buf.FastEncodeGuid(0, v);
        //  IOUtils.CastGuidToLongs(v);
      }
      t.Stop();
      var e2 = t.ElapsedSec;

      "\nToByteArray() does {0:n0} ops/sec".SeeArgs(CNT / e1);
      "\nFastEncodeGuid() does {0:n0} ops/sec".SeeArgs(CNT / e2);
    }

19 View Source File : JsonSerializer.cs
License : MIT License
Project Creator : AlenToma

private void WriteGuid(Guid g)
        {
            if (_params.UseFastGuid == false)
                WriteStringFast(g.ToString());
            else
                WriteBytes(g.ToByteArray());
        }

19 View Source File : GuidFormatter.cs
License : MIT License
Project Creator : Alprog

public int Serialize(ref byte[] bytes, int offset, Guid guid, IFormatterResolver formatterResolver)
        {
            if (Serializer.Instance.State.IsText)
            {
                return MessagePackBinary.WriteString(ref bytes, offset, guid.ToString());
            }
            else
            {
                return MessagePackBinary.WriteBytes(ref bytes, offset, guid.ToByteArray());
            }
        }

19 View Source File : FdbConverters.cs
License : MIT License
Project Creator : abdullin

private static void RegisterDefaultConverters()
		{
			//TODO: there is too much generic type combinations! need to refactor this ...

			RegisterUnsafe<bool, Slice>((value) => Slice.FromByte(value ? (byte)1 : default(byte)));
			RegisterUnsafe<bool, byte[]>((value) => Slice.FromByte(value ? (byte)1 : default(byte)).GetBytes());
			RegisterUnsafe<bool, string>((value) => value ? "true" : "false");
			RegisterUnsafe<bool, sbyte>((value) => value ? (sbyte)1 : default(sbyte));
			RegisterUnsafe<bool, byte>((value) => value ? (byte)1 : default(byte));
			RegisterUnsafe<bool, short>((value) => value ? (short)1 : default(short));
			RegisterUnsafe<bool, ushort>((value) => value ? (ushort)1 : default(ushort));
			RegisterUnsafe<bool, int>((value) => value ? 1 : default(int));
			RegisterUnsafe<bool, uint>((value) => value ? 1U : default(uint));
			RegisterUnsafe<bool, long>((value) => value ? 1L : default(long));
			RegisterUnsafe<bool, ulong>((value) => value ? 1UL : default(ulong));
			RegisterUnsafe<bool, double>((value) => value ? 0.0d : 1.0d);
			RegisterUnsafe<bool, float>((value) => value ? 0.0f : 1.0f);

			RegisterUnsafe<int, Slice>((value) => Slice.FromInt32(value));
			RegisterUnsafe<int, byte[]>((value) => Slice.FromInt32(value).GetBytes());
			RegisterUnsafe<int, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<int, bool>((value) => value != 0);
			RegisterUnsafe<int, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<int, byte>((value) => checked((byte)value));
			RegisterUnsafe<int, short>((value) => checked((short)value));
			RegisterUnsafe<int, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<int, uint>((value) => (uint)value);
			RegisterUnsafe<int, long>((value) => value);
			RegisterUnsafe<int, ulong>((value) => (ulong)value);
			RegisterUnsafe<int, double>((value) => value);
			RegisterUnsafe<int, float>((value) => checked((float)value));
			RegisterUnsafe<int, FdbTupleAlias>((value) => (FdbTupleAlias)value);

			RegisterUnsafe<uint, Slice>((value) => Slice.FromUInt64(value));
			RegisterUnsafe<uint, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
			RegisterUnsafe<uint, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<uint, bool>((value) => value != 0);
			RegisterUnsafe<uint, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<uint, byte>((value) => checked((byte)value));
			RegisterUnsafe<uint, short>((value) => checked((short)value));
			RegisterUnsafe<uint, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<uint, int>((value) => (int)value);
			RegisterUnsafe<uint, long>((value) => value);
			RegisterUnsafe<uint, ulong>((value) => value);
			RegisterUnsafe<uint, double>((value) => value);
			RegisterUnsafe<uint, float>((value) => checked((float)value));

			RegisterUnsafe<long, Slice>((value) => Slice.FromInt64(value));
			RegisterUnsafe<long, byte[]>((value) => Slice.FromInt64(value).GetBytes());
			RegisterUnsafe<long, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<long, bool>((value) => value != 0);
			RegisterUnsafe<long, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<long, byte>((value) => checked((byte)value));
			RegisterUnsafe<long, short>((value) => checked((short)value));
			RegisterUnsafe<long, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<long, int>((value) => checked((int)value));
			RegisterUnsafe<long, uint>((value) => (uint)value);
			RegisterUnsafe<long, ulong>((value) => (ulong)value);
			RegisterUnsafe<long, double>((value) => checked((double)value));
			RegisterUnsafe<long, float>((value) => checked((float)value));
			RegisterUnsafe<long, TimeSpan>((value) => TimeSpan.FromTicks(value));
			RegisterUnsafe<long, Uuid64>((value) => new Uuid64(value));
			RegisterUnsafe<long, System.Net.IPAddress>((value) => new System.Net.IPAddress(value));

			RegisterUnsafe<ulong, Slice>((value) => Slice.FromUInt64(value));
			RegisterUnsafe<ulong, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
			RegisterUnsafe<ulong, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<ulong, bool>((value) => value != 0);
			RegisterUnsafe<ulong, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<ulong, byte>((value) => checked((byte)value));
			RegisterUnsafe<ulong, short>((value) => checked((short)value));
			RegisterUnsafe<ulong, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<ulong, int>((value) => checked((int)value));
			RegisterUnsafe<ulong, uint>((value) => checked((uint)value));
			RegisterUnsafe<ulong, long>((value) => checked((long)value));
			RegisterUnsafe<ulong, double>((value) => checked((double)value));
			RegisterUnsafe<ulong, float>((value) => checked((float)value));
			RegisterUnsafe<ulong, Uuid64>((value) => new Uuid64(value));
			RegisterUnsafe<ulong, TimeSpan>((value) => TimeSpan.FromTicks(checked((long)value)));

			RegisterUnsafe<short, Slice>((value) => Slice.FromInt32(value));
			RegisterUnsafe<short, byte[]>((value) => Slice.FromInt32(value).GetBytes());
			RegisterUnsafe<short, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<short, bool>((value) => value != 0);
			RegisterUnsafe<short, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<short, byte>((value) => checked((byte)value));
			RegisterUnsafe<short, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<short, int>((value) => value);
			RegisterUnsafe<short, uint>((value) => checked((uint)value));
			RegisterUnsafe<short, long>((value) => value);
			RegisterUnsafe<short, ulong>((value) => checked((ulong)value));
			RegisterUnsafe<short, double>((value) => value);
			RegisterUnsafe<short, float>((value) => value);
			RegisterUnsafe<short, FdbTupleAlias>((value) => (FdbTupleAlias)value);

			RegisterUnsafe<ushort, Slice>((value) => Slice.FromUInt64(value));
			RegisterUnsafe<ushort, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
			RegisterUnsafe<ushort, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<ushort, bool>((value) => value != 0);
			RegisterUnsafe<ushort, byte>((value) => checked((byte)value));
			RegisterUnsafe<ushort, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<ushort, short>((value) => checked((short)value));
			RegisterUnsafe<ushort, int>((value) => value);
			RegisterUnsafe<ushort, uint>((value) => value);
			RegisterUnsafe<ushort, long>((value) => value);
			RegisterUnsafe<ushort, ulong>((value) => value);
			RegisterUnsafe<ushort, double>((value) => value);
			RegisterUnsafe<ushort, float>((value) => value);

			RegisterUnsafe<byte, Slice>((value) => Slice.FromInt32(value));
			RegisterUnsafe<byte, byte[]>((value) => Slice.FromInt32(value).GetBytes());
			RegisterUnsafe<byte, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<byte, bool>((value) => value != 0);
			RegisterUnsafe<byte, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<byte, short>((value) => value);
			RegisterUnsafe<byte, ushort>((value) => value);
			RegisterUnsafe<byte, int>((value) => value);
			RegisterUnsafe<byte, uint>((value) => value);
			RegisterUnsafe<byte, long>((value) => value);
			RegisterUnsafe<byte, ulong>((value) => value);
			RegisterUnsafe<byte, double>((value) => value);
			RegisterUnsafe<byte, float>((value) => value);
			RegisterUnsafe<byte, FdbTupleAlias>((value) => (FdbTupleAlias)value);

			RegisterUnsafe<sbyte, Slice>((value) => Slice.FromInt64(value));
			RegisterUnsafe<sbyte, byte[]>((value) => Slice.FromInt64(value).GetBytes());
			RegisterUnsafe<sbyte, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<sbyte, bool>((value) => value != 0);
			RegisterUnsafe<sbyte, byte>((value) => checked((byte)value));
			RegisterUnsafe<sbyte, short>((value) => value);
			RegisterUnsafe<sbyte, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<sbyte, int>((value) => value);
			RegisterUnsafe<sbyte, uint>((value) => checked((uint)value));
			RegisterUnsafe<sbyte, long>((value) => value);
			RegisterUnsafe<sbyte, ulong>((value) => checked((ulong)value));
			RegisterUnsafe<sbyte, double>((value) => value);
			RegisterUnsafe<sbyte, float>((value) => value);

			RegisterUnsafe<float, Slice>((value) => Slice.FromSingle(value));
			RegisterUnsafe<float, byte[]>((value) => Slice.FromSingle(value).GetBytes());
			RegisterUnsafe<float, string>((value) => value.ToString("R", CultureInfo.InvariantCulture));
			RegisterUnsafe<float, bool>((value) => !(value == 0f || float.IsNaN(value)));
			RegisterUnsafe<float, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<float, byte>((value) => checked((byte)value));
			RegisterUnsafe<float, short>((value) => checked((short)value));
			RegisterUnsafe<float, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<float, int>((value) => checked((int)value));
			RegisterUnsafe<float, uint>((value) => (uint)value);
			RegisterUnsafe<float, long>((value) => checked((long)value));
			RegisterUnsafe<float, ulong>((value) => (ulong)value);
			RegisterUnsafe<float, double>((value) => value);

			RegisterUnsafe<double, Slice>((value) => Slice.FromDouble(value));
			RegisterUnsafe<double, byte[]>((value) => Slice.FromDouble(value).GetBytes());
			RegisterUnsafe<double, string>((value) => value.ToString("R", CultureInfo.InvariantCulture));
			RegisterUnsafe<double, bool>((value) => !(value == 0d || double.IsNaN(value)));
			RegisterUnsafe<double, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<double, byte>((value) => checked((byte)value));
			RegisterUnsafe<double, short>((value) => checked((short)value));
			RegisterUnsafe<double, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<double, int>((value) => checked((int)value));
			RegisterUnsafe<double, uint>((value) => (uint)value);
			RegisterUnsafe<double, long>((value) => checked((long)value));
			RegisterUnsafe<double, ulong>((value) => (ulong)value);
			RegisterUnsafe<double, float>((value) => checked((float)value));

			RegisterUnsafe<string, Slice>((value) => Slice.FromString(value));
			RegisterUnsafe<string, byte[]>((value) => Slice.FromString(value).GetBytes());
			RegisterUnsafe<string, bool>((value) => !string.IsNullOrEmpty(value));
			RegisterUnsafe<string, sbyte>((value) => string.IsNullOrEmpty(value) ? default(sbyte) : SByte.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, byte>((value) => string.IsNullOrEmpty(value) ? default(byte) : Byte.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, short>((value) => string.IsNullOrEmpty(value) ? default(short) : Int16.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, ushort>((value) => string.IsNullOrEmpty(value) ? default(ushort) : UInt16.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, int>((value) => string.IsNullOrEmpty(value) ? default(int) : Int32.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, uint>((value) => string.IsNullOrEmpty(value) ? default(uint) : UInt32.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, long>((value) => string.IsNullOrEmpty(value) ? default(long) : Int64.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, ulong>((value) => string.IsNullOrEmpty(value) ? default(ulong) : UInt64.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, float>((value) => string.IsNullOrEmpty(value) ? default(float) : Single.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, double>((value) => string.IsNullOrEmpty(value) ? default(double) : Double.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, Guid>((value) => string.IsNullOrEmpty(value) ? default(Guid) : Guid.Parse(value));
			RegisterUnsafe<string, Uuid128>((value) => string.IsNullOrEmpty(value) ? default(Uuid128) : Uuid128.Parse(value));
			RegisterUnsafe<string, Uuid64>((value) => string.IsNullOrEmpty(value) ? default(Uuid64) : Uuid64.Parse(value));
			RegisterUnsafe<string, System.Net.IPAddress>((value) => string.IsNullOrEmpty(value) ? default(System.Net.IPAddress) : System.Net.IPAddress.Parse(value));

			RegisterUnsafe<byte[], Slice>((value) => Slice.Create(value));
			RegisterUnsafe<byte[], string>((value) => value == null ? default(string) : value.Length == 0 ? String.Empty : System.Convert.ToBase64String(value));
			RegisterUnsafe<byte[], bool>((value) => value != null && value.Length > 0);
			RegisterUnsafe<byte[], sbyte>((value) => value == null ? default(sbyte) : Slice.Create(value).ToSByte());
			RegisterUnsafe<byte[], byte>((value) => value == null ? default(byte) : Slice.Create(value).ToByte());
			RegisterUnsafe<byte[], short>((value) => value == null ? default(short) : Slice.Create(value).ToInt16());
			RegisterUnsafe<byte[], ushort>((value) => value == null ? default(ushort) : Slice.Create(value).ToUInt16());
			RegisterUnsafe<byte[], int>((value) => value == null ? 0 : Slice.Create(value).ToInt32());
			RegisterUnsafe<byte[], uint>((value) => value == null ? 0U : Slice.Create(value).ToUInt32());
			RegisterUnsafe<byte[], long>((value) => value == null ? 0L : Slice.Create(value).ToInt64());
			RegisterUnsafe<byte[], ulong>((value) => value == null ? 0UL : Slice.Create(value).ToUInt64());
			RegisterUnsafe<byte[], Guid>((value) => value == null || value.Length == 0 ? default(Guid) : new Uuid128(value).ToGuid());
			RegisterUnsafe<byte[], Uuid128>((value) => value == null || value.Length == 0 ? default(Uuid128) : new Uuid128(value));
			RegisterUnsafe<byte[], Uuid64>((value) => value == null || value.Length == 0 ? default(Uuid64) : new Uuid64(value));
			RegisterUnsafe<byte[], TimeSpan>((value) => value == null ? TimeSpan.Zero : TimeSpan.FromTicks(Slice.Create(value).ToInt64()));
			RegisterUnsafe<byte[], System.Net.IPAddress>((value) => value == null || value.Length == 0 ? default(System.Net.IPAddress) : new System.Net.IPAddress(value));

			RegisterUnsafe<Guid, Slice>((value) => Slice.FromGuid(value));
			RegisterUnsafe<Guid, byte[]>((value) => Slice.FromGuid(value).GetBytes());
			RegisterUnsafe<Guid, string>((value) => value.ToString("D", null));
			RegisterUnsafe<Guid, Uuid128>((value) => new Uuid128(value));
			RegisterUnsafe<Guid, bool>((value) => value != Guid.Empty);
			RegisterUnsafe<Guid, System.Net.IPAddress>((value) => new System.Net.IPAddress(new Uuid128(value).ToByteArray()));

			RegisterUnsafe<Uuid128, Slice>((value) => value.ToSlice());
			RegisterUnsafe<Uuid128, byte[]>((value) => value.ToByteArray());
			RegisterUnsafe<Uuid128, string>((value) => value.ToString("D", null));
			RegisterUnsafe<Uuid128, Guid>((value) => value.ToGuid());
			RegisterUnsafe<Uuid128, bool>((value) => value != Uuid128.Empty);
			RegisterUnsafe<Guid, System.Net.IPAddress>((value) => new System.Net.IPAddress(value.ToByteArray()));

			RegisterUnsafe<Uuid64, Slice>((value) => value.ToSlice());
			RegisterUnsafe<Uuid64, byte[]>((value) => value.ToByteArray());
			RegisterUnsafe<Uuid64, string>((value) => value.ToString("D", null));
			RegisterUnsafe<Uuid64, long>((value) => value.ToInt64());
			RegisterUnsafe<Uuid64, ulong>((value) => value.ToUInt64());
			RegisterUnsafe<Uuid64, bool>((value) => value.ToInt64() != 0L);

			RegisterUnsafe<TimeSpan, Slice>((value) => Slice.FromInt64(value.Ticks));
			RegisterUnsafe<TimeSpan, byte[]>((value) => Slice.FromInt64(value.Ticks).GetBytes());
			RegisterUnsafe<TimeSpan, long>((value) => value.Ticks);
			RegisterUnsafe<TimeSpan, ulong>((value) => checked((ulong)value.Ticks));
			RegisterUnsafe<TimeSpan, double>((value) => value.TotalSeconds);
			RegisterUnsafe<TimeSpan, bool>((value) => value == TimeSpan.Zero);

			RegisterUnsafe<System.Net.IPAddress, Slice>((value) => value != null ? Slice.Create(value.GetAddressBytes()) : Slice.Nil);
			RegisterUnsafe<System.Net.IPAddress, byte[]>((value) => value != null ? value.GetAddressBytes() : null);
			RegisterUnsafe<System.Net.IPAddress, string>((value) => value != null ? value.ToString() : null);

			RegisterUnsafe<FdbTupleAlias, byte>((value) => (byte)value);
			RegisterUnsafe<FdbTupleAlias, int>((value) => (int)value);
			RegisterUnsafe<FdbTupleAlias, Slice>((value) => Slice.FromByte((byte)value));

			//REVIEW: this should go in the Tuples layer !
			RegisterUnsafe<Slice, byte[]>((value) => value.GetBytes());
			RegisterUnsafe<Slice, string>((value) => value.ToUnicode());
			RegisterUnsafe<Slice, bool>((value) => value.ToBool());
			RegisterUnsafe<Slice, sbyte>((value) => value.ToSByte());
			RegisterUnsafe<Slice, byte>((value) => value.ToByte());
			RegisterUnsafe<Slice, short>((value) => value.ToInt16());
			RegisterUnsafe<Slice, ushort>((value) => value.ToUInt16());
			RegisterUnsafe<Slice, int>((value) => value.ToInt32());
			RegisterUnsafe<Slice, uint>((value) => value.ToUInt32());
			RegisterUnsafe<Slice, long>((value) => value.ToInt64());
			RegisterUnsafe<Slice, ulong>((value) => value.ToUInt64());
			RegisterUnsafe<Slice, Guid>((value) => value.ToGuid());
			RegisterUnsafe<Slice, Uuid128>((value) => value.ToUuid128());
			RegisterUnsafe<Slice, Uuid64>((value) => value.ToUuid64());
			RegisterUnsafe<Slice, TimeSpan>((value) => TimeSpan.FromTicks(value.ToInt64()));
			RegisterUnsafe<Slice, FdbTupleAlias>((value) => (FdbTupleAlias)value.ToByte());
			RegisterUnsafe<Slice, System.Net.IPAddress>((value) => !value.IsNullOrEmpty ? new System.Net.IPAddress(value.GetBytes()) : null);
		}

19 View Source File : GuidMarshaler.cs
License : GNU General Public License v3.0
Project Creator : AndreiFedarets

public static void Marshal(Guid value, Stream stream)
        {
            byte[] data = value.ToByteArray();
            Debug.replacedert(data.Length == GuidSize, "Size of System.Guid should be 16");
            stream.Write(data, 0, GuidSize);
        }

19 View Source File : TsonSerializerBase.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public void WriteGuidValue(Guid value)
        {
            Stream.Write(value.ToByteArray(), 0, 16);
        }

19 View Source File : GuidHeap.cs
License : GNU General Public License v3.0
Project Creator : anydream

protected override void WriteToImpl(BinaryWriter writer) {
			uint offset = 0;
			foreach (var guid in guids) {
				byte[] rawData;
				if (userRawData == null || !userRawData.TryGetValue(offset, out rawData))
					rawData = guid.ToByteArray();
				writer.Write(rawData);
				offset += 16;
			}
		}

19 View Source File : StringHelper.cs
License : Apache License 2.0
Project Creator : anjoy8

public static long GetGuidToLongID()
        {
            byte[] buffer = Guid.NewGuid().ToByteArray();
            return BitConverter.ToInt64(buffer, 0);
        }

19 View Source File : SessionInfo.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public byte[] ToBinary()
		{
			Debug.replacedert(Domain.Length < byte.MaxValue && UserName.Length < byte.MaxValue && ClientName.Length < byte.MaxValue && ClientAddress.Length < byte.MaxValue);
			using (MemoryStream ms = new MemoryStream())
			using (BinaryWriter bw = new BinaryWriter(ms, Encoding.UTF8))
			{
				bw.Write(new byte[] { 1, 2, 6, 0 });
				bw.Write(new Guid(SessionId).ToByteArray());		// 16 bytes.
				bw.Write(CreateTime.ToBinary());					// 8 bytes.
				bw.Write(Domain);
				bw.Write(UserName);
				bw.Write(ClientName);
				bw.Write(ClientAddress);

				bw.Flush();
				return ms.ToArray();
			}
		}

19 View Source File : CoumpundDocumentItem.cs
License : Apache License 2.0
Project Creator : Appdynamics

internal void Write(BinaryWriter bw)
        {
            var name = Encoding.Unicode.GetBytes(Name);
            bw.Write(name);
            bw.Write(new byte[0x40 - (name.Length)]);
            bw.Write((Int16)(name.Length + 2));

            bw.Write(ObjectType);
            bw.Write(ColorFlag);
            bw.Write(LeftSibling);
            bw.Write(RightSibling);
            bw.Write(ChildID);
            bw.Write(ClsID.ToByteArray());
            bw.Write(StatBits);
            bw.Write(CreationTime);
            bw.Write(ModifiedTime);
            bw.Write(StartingSectorLocation);
            bw.Write(StreamSize);
        }

19 View Source File : GuidGenerator.cs
License : MIT License
Project Creator : abock

static string FormatGuid(GuidFormat format, Guid guid)
        {
            switch (format)
            {
                case GuidFormat.N:
                    return guid.ToString("N");
                case GuidFormat.B:
                    return guid.ToString("B");
                case GuidFormat.P:
                    return guid.ToString("P");
                case GuidFormat.X:
                    return guid.ToString("X");
                case GuidFormat.Base64:
                    return Convert.ToBase64String(guid.ToByteArray());
                case GuidFormat.Short:
                    return Convert.ToBase64String(guid.ToByteArray())
                        .Replace("/", "_")
                        .Replace("+", "-")
                        .Substring(0, 22);
                case GuidFormat.D:
                default:
                    return guid.ToString("D");
            }
        }

19 View Source File : GuidFieldMapping.cs
License : MIT License
Project Creator : aquilahkj

public override object ToParameter(object value)
        {
            if (Equals(value, null))
            {
                return null;
            }

            var guid = (Guid) value;
            if (_mode == GuidStoreMode.Raw)
            {
                value = guid.ToByteArray();
            }
            else
            {
                value = guid.ToString();
            }

            return value;
        }

19 View Source File : CaptchaHelper.cs
License : MIT License
Project Creator : aishang2015

public static string GetValidateCode(int length = 4)
        {
            // 产生的随机字符串
            var result = string.Empty;

            // 字符集 todo配置到文件
            char[] chars = _characters;

            // 生成字节数组,利用BitConvert方法把字节数组转换为整数
            byte[] buffer = Guid.NewGuid().ToByteArray();
            var iRoot = BitConverter.ToInt32(buffer, 0);
            var random = new Random(iRoot);
            for (int i = 0; i < length; i++)
            {
                var index = random.Next(0, chars.Length);
                result += chars[index];
            }
            return result;
        }

19 View Source File : Encryption.cs
License : MIT License
Project Creator : arsium

public static byte[] RSMEncrypt(byte[] input, byte[] key)
            {
                Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(key, new byte[8], 1);

                RijndaelManaged rijndaelManaged = new RijndaelManaged();

                rijndaelManaged.Mode = CipherMode.CBC;

                rijndaelManaged.Key = rfc2898DeriveBytes.GetBytes(16);

                rijndaelManaged.IV = rfc2898DeriveBytes.GetBytes(16);

                byte[] array = new byte[input.Length + 16];

                Buffer.BlockCopy(Guid.NewGuid().ToByteArray(), 0, array, 0, 16);

                Buffer.BlockCopy(input, 0, array, 16, input.Length);

                return rijndaelManaged.CreateEncryptor().TransformFinalBlock(array, 0, array.Length);
            }

19 View Source File : WaveFormatExtensible.cs
License : MIT License
Project Creator : 3wz

public override void Serialize(System.IO.BinaryWriter writer)
        {
            base.Serialize(writer);
            writer.Write(wValidBitsPerSample);
            writer.Write(dwChannelMask);
            byte[] guid = subFormat.ToByteArray();
            writer.Write(guid, 0, guid.Length);
        }

19 View Source File : StructPropertyData.cs
License : MIT License
Project Creator : atenfyr

public override int Write(replacedetBinaryWriter writer, bool includeHeader)
        {
            if (includeHeader)
            {
                writer.Write(StructType);
                writer.Write(StructGUID.ToByteArray());
                writer.Write((byte)0);
            }

            MainSerializer.PropertyTypeRegistry.TryGetValue(StructType.Value.Value, out RegistryEntry targetEntry);
            bool hasCustomStructSerialization = targetEntry != null && targetEntry.HasCustomStructSerialization;

            if (StructType.Value.Value == "RichCurveKey" && writer.replacedet.EngineVersion < UE4Version.VER_UE4_SERIALIZE_RICH_CURVE_KEY) hasCustomStructSerialization = false;

            if (targetEntry != null && hasCustomStructSerialization) return WriteOnce(writer);
            if (Value.Count == 0 && !SerializeNone) return 0;
            return WriteNTPL(writer);
        }

19 View Source File : BsonWriter.cs
License : MIT License
Project Creator : akaskela

public override void WriteValue(Guid value)
        {
            base.WriteValue(value);
            AddToken(new BsonBinary(value.ToByteArray(), BsonBinaryType.Uuid));
        }

19 View Source File : UAPUtils.cs
License : MIT License
Project Creator : atenfyr

public static uint[] ToUnsignedInts(this Guid value)
        {
            byte[] vals = value.ToByteArray();
            uint[] res = new uint[4];
            res[0] = BitConverter.ToUInt32(vals, 0);
            res[1] = BitConverter.ToUInt32(vals, sizeof(uint));
            res[2] = BitConverter.ToUInt32(vals, sizeof(uint) * 2);
            res[3] = BitConverter.ToUInt32(vals, sizeof(uint) * 3);
            return res;
        }

19 View Source File : EndianUtilities.cs
License : MIT License
Project Creator : ADeltaX

public static void WriteBytesLittleEndian(Guid val, byte[] buffer, int offset)
        {
            byte[] le = val.ToByteArray();
            Array.Copy(le, 0, buffer, offset, 16);
        }

19 View Source File : PipeClient.cs
License : GNU General Public License v3.0
Project Creator : AutoDarkMode

public string SendMessageAndGetReply(string message, int timeoutSeconds = 5)
        {
            string pipeId = $"C#_{Convert.ToBase64String(Guid.NewGuid().ToByteArray())}";
            using NamedPipeClientStream clientPipeRequest = new(".", Address.PipePrefix + Address.PipeRequest, PipeDirection.Out);
            try
            {
                clientPipeRequest.Connect(timeoutSeconds * 1000);
                StreamWriter sw = new(clientPipeRequest) { AutoFlush = true };
                using (sw)
                {
                    sw.WriteLine(message);
                    sw.WriteLine(pipeId);
                }
            }
            catch (Exception ex)
            {
                return new ApiResponse()
                {
                    StatusCode = StatusCode.Timeout,
                    Message = "The service did not acknowledge the req in time",
                    Details = $"{ex.GetType()} {ex.Message}"
                }.ToString();
            }

            using NamedPipeClientStream clientPipeResponse = new(".", Address.PipePrefix + Address.PipeResponse + $"_{pipeId}", PipeDirection.In);
            try
            {
                clientPipeResponse.Connect(timeoutSeconds * 1000);
                if (clientPipeResponse.IsConnected && clientPipeResponse.CanRead)
                {
                    using StreamReader sr = new(clientPipeResponse);
                    //sr.BaseStream.ReadTimeout = timeoutSeconds * 1000;
                    string msg = sr.ReadToEnd();
                    if (msg == null)
                    {
                        return StatusCode.Timeout;
                    }
                    return msg;
                }
                else
                {
                    return new ApiResponse()
                    {
                        StatusCode = StatusCode.Err,
                        Message = "Pipe not connected or can't read"
                    }.ToString();
                }
            }
            catch (Exception ex)
            {
                return new ApiResponse()
                {
                    StatusCode = StatusCode.Timeout,
                    Message = "The service did not respond in time",
                    Details = $"{ex.GetType()} {ex.Message}"
                }.ToString();
            }
        }

19 View Source File : ConvertUtils.cs
License : MIT License
Project Creator : akaskela

private static ConvertResult TryConvertInternal(object initialValue, CultureInfo culture, Type targetType, out object value)
        {
            if (initialValue == null)
            {
                throw new ArgumentNullException(nameof(initialValue));
            }

            if (ReflectionUtils.IsNullableType(targetType))
            {
                targetType = Nullable.GetUnderlyingType(targetType);
            }

            Type initialType = initialValue.GetType();

            if (targetType == initialType)
            {
                value = initialValue;
                return ConvertResult.Success;
            }

            // use Convert.ChangeType if both types are IConvertible
            if (ConvertUtils.IsConvertible(initialValue.GetType()) && ConvertUtils.IsConvertible(targetType))
            {
                if (targetType.IsEnum())
                {
                    if (initialValue is string)
                    {
                        value = Enum.Parse(targetType, initialValue.ToString(), true);
                        return ConvertResult.Success;
                    }
                    else if (IsInteger(initialValue))
                    {
                        value = Enum.ToObject(targetType, initialValue);
                        return ConvertResult.Success;
                    }
                }

                value = System.Convert.ChangeType(initialValue, targetType, culture);
                return ConvertResult.Success;
            }

#if !NET20
            if (initialValue is DateTime && targetType == typeof(DateTimeOffset))
            {
                value = new DateTimeOffset((DateTime)initialValue);
                return ConvertResult.Success;
            }
#endif

            if (initialValue is byte[] && targetType == typeof(Guid))
            {
                value = new Guid((byte[])initialValue);
                return ConvertResult.Success;
            }

            if (initialValue is Guid && targetType == typeof(byte[]))
            {
                value = ((Guid)initialValue).ToByteArray();
                return ConvertResult.Success;
            }

            string s = initialValue as string;
            if (s != null)
            {
                if (targetType == typeof(Guid))
                {
                    value = new Guid(s);
                    return ConvertResult.Success;
                }
                if (targetType == typeof(Uri))
                {
                    value = new Uri(s, UriKind.RelativeOrAbsolute);
                    return ConvertResult.Success;
                }
                if (targetType == typeof(TimeSpan))
                {
                    value = ParseTimeSpan(s);
                    return ConvertResult.Success;
                }
                if (targetType == typeof(byte[]))
                {
                    value = System.Convert.FromBase64String(s);
                    return ConvertResult.Success;
                }
                if (targetType == typeof(Version))
                {
                    Version result;
                    if (VersionTryParse(s, out result))
                    {
                        value = result;
                        return ConvertResult.Success;
                    }
                    value = null;
                    return ConvertResult.NoValidConversion;
                }
                if (typeof(Type).IsreplacedignableFrom(targetType))
                {
                    value = Type.GetType(s, true);
                    return ConvertResult.Success;
                }
            }

#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
            if (targetType == typeof(BigInteger))
            {
                value = ToBigInteger(initialValue);
                return ConvertResult.Success;
            }
            if (initialValue is BigInteger)
            {
                value = FromBigInteger((BigInteger)initialValue, targetType);
                return ConvertResult.Success;
            }
#endif

#if !(PORTABLE40 || PORTABLE)
            // see if source or target types have a TypeConverter that converts between the two
            TypeConverter toConverter = GetConverter(initialType);

            if (toConverter != null && toConverter.CanConvertTo(targetType))
            {
                value = toConverter.ConvertTo(null, culture, initialValue, targetType);
                return ConvertResult.Success;
            }

            TypeConverter fromConverter = GetConverter(targetType);

            if (fromConverter != null && fromConverter.CanConvertFrom(initialType))
            {
                value = fromConverter.ConvertFrom(null, culture, initialValue);
                return ConvertResult.Success;
            }
#endif
#if !(DOTNET || PORTABLE40 || PORTABLE)
            // handle DBNull and INullable
            if (initialValue == DBNull.Value)
            {
                if (ReflectionUtils.IsNullable(targetType))
                {
                    value = EnsureTypereplacedignable(null, initialType, targetType);
                    return ConvertResult.Success;
                }

                // cannot convert null to non-nullable
                value = null;
                return ConvertResult.CannotConvertNull;
            }
#endif
#if !(DOTNET || PORTABLE40 || PORTABLE)
            if (initialValue is INullable)
            {
                value = EnsureTypereplacedignable(ToValue((INullable)initialValue), initialType, targetType);
                return ConvertResult.Success;
            }
#endif

            if (targetType.IsInterface() || targetType.IsGenericTypeDefinition() || targetType.IsAbstract())
            {
                value = null;
                return ConvertResult.NotInstantiableType;
            }

            value = null;
            return ConvertResult.NoValidConversion;
        }

19 View Source File : WireData.cs
License : MIT License
Project Creator : azist

public int Serialize(Stream stream)
      {
         if (m_Host.IsNullOrWhiteSpace())
          throw new GlueException(StringConsts.ARGUMENT_ERROR + "CallSite.Host==null|empty");

         var buf = TEXT_ENCODING.GetBytes(m_Host);
         var blen = buf.Length;
         if (blen > MAX_HOST_NAME_BYTE_LEN)
           throw new ProtocolException(
                           StringConsts.GLUE_BAD_PROTOCOL_CLIENT_SITE_ERROR + "Requested host name '{0}' exceeds the limit of {1} bytes"
                                                                        .Args(m_Host, MAX_HOST_NAME_BYTE_LEN));

         var size = sizeof(short) + //TOTAL
                    sizeof(int)   + //MAGIC
                    sizeof(short) + //host name byte length
                    blen          + //h name (blen) bytes
                    GUID_SIZE;      //GUID

         stream.WriteBEShort((short)(size-sizeof(short)));
         stream.WriteBEInt32(MAGIC);
         stream.WriteBEShort((short)blen);
         stream.Write(buf, 0, blen);
         stream.Write( m_AppInstanceID.ToByteArray(), 0, GUID_SIZE );

         return size;
      }

19 View Source File : Huid.cs
License : MIT License
Project Creator : 3F

public static int GetVersionOf(Guid g) => g.ToByteArray()[7] >> 4;

19 View Source File : IOUtils.cs
License : MIT License
Project Creator : azist

public static byte[] ToNetworkByteOrder(this Guid guid)
    {
      var result = guid.ToByteArray();

      var t = result[3];
      result[3] = result[0];
      result[0] = t;

      t = result[2];
      result[2] = result[1];
      result[1] = t;

      t = result[5];
      result[5] = result[4];
      result[4] = t;

      t = result[7];
      result[7] = result[6];
      result[6] = t;

      return result;
    }

19 View Source File : BaseNode.cs
License : MIT License
Project Creator : alelievr

public void Initialize(BaseGraph graph)
		{
			if (debug)
				Debug.LogWarning("Node " + GetType() + "Initialize !");

			//generate "unique" id for node:
			byte[] bytes = System.Guid.NewGuid().ToByteArray();
			id = (int)bytes[0] | (int)bytes[1] << 8 | (int)bytes[2] << 16 | (int)bytes[3] << 24;

			//set the node name:
			name = NodeTypeProvider.GetNodeName(GetType());

			//set the name of the scriptableObject
			base.name = name;

			//set the graph reference:
			graphRef = graph;

			//Initialize the rest of the node
			OnAfterNodeAndGraphDeserialized(false);

			//call virtual NodeCreation method
			OnNodeCreation();
		}

19 View Source File : SecretSharingHelper.cs
License : MIT License
Project Creator : AElfProject

public static List<byte[]> EncodeSecret(byte[] secretMessage, int threshold, int totalParts)
        {
            // Polynomial construction.
            var coefficients = new BigInteger[threshold];
            // Set p(0) = secret message.
            coefficients[0] = secretMessage.ToBigInteger();
            for (var i = 1; i < threshold; i++)
            {
                var foo = new byte[32];
                Array.Copy(HashHelper.ComputeFrom(Guid.NewGuid().ToByteArray()).ToArray(), foo, 32);
                coefficients[i] = BigInteger.Abs(new BigInteger(foo));
            }

            var result = new List<byte[]>();
            for (var i = 1; i < totalParts + 1; i++)
            {
                var secretBigInteger = coefficients[0];
                for (var j = 1; j < threshold; j++)
                {
                    secretBigInteger += coefficients[j] * BigInteger.Pow(new BigInteger(i), j);
                    secretBigInteger %= SecretSharingConsts.FieldPrime;
                }

                result.Add(secretBigInteger.ToByteArray());
            }

            return result;
        }

19 View Source File : Huid.cs
License : MIT License
Project Creator : 3F

public static Guid NewGuid(Guid ns, string input)
        {
            if(ns == Guid.Empty) return NewGuid(NS_HUID_H, NS_HUID_L, input);

            byte[] v = ns.ToByteArray();

            // RFC 4122; '4.1.2. Layout and Byte Order'
            // ... each field encoded with the Most Significant Byte first(known as network byte order).
            // See `void format_uuid_v3or5(uuid_t *uuid, unsigned char hash[16], int v)`

            /*Eg.:
                [0xC2 0xB9 0xA2 0x30] [0xA5 0x0B] [0x45 0x24]    0xA7 0x32 0x54 0xC9 0xB4 0x2E 0x8C 0xA5

                  3    2    1    0      5    4      7    6        8    9    10   11   12   13   14   15
            */
            // We'll use BitConverter which works around the IsLittleEndian check
            return NewGuid
            (
                BitConverter.ToUInt64(v, 0),
                BitConverter.ToUInt64(v, 8), //TODO: actually here we can use any byte order
                input
            );
        }

19 View Source File : GuidMd5OrSha1.cs
License : MIT License
Project Creator : 3F

internal static Guid NewGuid(string input, AlgoVersion version)
        {
            const int _FMT = 16; // The UUID format is 16 octets

            if(input == null) return Guid.Empty;

            byte[] ret = new byte[_FMT];
            using(HashAlgorithm alg = (version == AlgoVersion.Md5) ? MD5.Create() : (HashAlgorithm)SHA1.Create())
            {
                byte[] ns = NamespaceTest.ToByteArray();

                alg.TransformBlock(ChangeByteOrder(ns), 0, _FMT, null, 0);

                byte[] strBytes = Encoding.UTF8.GetBytes(input);
                alg.TransformFinalBlock(strBytes, 0, strBytes.Length);

                Array.Copy(alg.Hash, 0, ret, 0, _FMT);
            }

            ret[6] &= 0x0F;
            ret[6] |= (byte)((byte)version << 4);

            ret[8] &= 0x3F;
            ret[8] |= 0x80;

            return new Guid(ChangeByteOrder(ret));
        }

19 View Source File : GuidGenerator.cs
License : MIT License
Project Creator : abock

static Guid ToMixedEndian(Guid guid)
        {
            var bytes = guid.ToByteArray();
            Array.Reverse(bytes, 0, 4);
            Array.Reverse(bytes, 4, 2);
            Array.Reverse(bytes, 6, 2);
            return new Guid(bytes);
        }

19 View Source File : TsonSerializerBase.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public void WriteValue(Guid value)
        {
            Stream.Write(value.ToByteArray(), 0, 16);
        }

19 View Source File : ShortGuid.cs
License : MIT License
Project Creator : AnkiTools

public static string Encode(Guid guid)
        {
            string encoded = Convert.ToBase64String(guid.ToByteArray());
            encoded = encoded
              .Replace("/", "_")
              .Replace("+", "-");
            return encoded.Substring(0, 22);
        }

See More Examples