예제 #1
0
        /// <summary>
        /// Serializes a value.
        /// </summary>
        /// <param name="context">The serialization context.</param>
        /// <param name="args">The serialization args.</param>
        /// <param name="value">The object.</param>
        protected override void SerializeValue(BsonSerializationContext context, BsonSerializationArgs args, BsonBinaryData value)
        {
            var bsonWriter = context.Writer;

            var subType = value.SubType;

            if (subType == BsonBinarySubType.UuidStandard || subType == BsonBinarySubType.UuidLegacy)
            {
                var writerGuidRepresentation = bsonWriter.Settings.GuidRepresentation;
                if (writerGuidRepresentation != GuidRepresentation.Unspecified)
                {
                    var bytes = value.Bytes;
                    var guidRepresentation = value.GuidRepresentation;

                    if (guidRepresentation == GuidRepresentation.Unspecified)
                    {
                        var message = string.Format(
                            "Cannot serialize BsonBinaryData with GuidRepresentation Unspecified to destination with GuidRepresentation {0}.",
                            writerGuidRepresentation);
                        throw new BsonSerializationException(message);
                    }
                    if (guidRepresentation != writerGuidRepresentation)
                    {
                        var guid = GuidConverter.FromBytes(bytes, guidRepresentation);
                        bytes              = GuidConverter.ToBytes(guid, writerGuidRepresentation);
                        subType            = (writerGuidRepresentation == GuidRepresentation.Standard) ? BsonBinarySubType.UuidStandard : BsonBinarySubType.UuidLegacy;
                        guidRepresentation = writerGuidRepresentation;
                        value              = new BsonBinaryData(bytes, subType, guidRepresentation);
                    }
                }
            }

            bsonWriter.WriteBinaryData(value);
        }
예제 #2
0
        /// <summary>
        /// Serializes a value.
        /// </summary>
        /// <param name="context">The serialization context.</param>
        /// <param name="args">The serialization args.</param>
        /// <param name="value">The object.</param>
        public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, Guid value)
        {
            var bsonWriter = context.Writer;

            switch (_representation)
            {
            case BsonType.Binary:
                var writerGuidRepresentation = bsonWriter.Settings.GuidRepresentation;
                if (writerGuidRepresentation == GuidRepresentation.Unspecified)
                {
                    throw new BsonSerializationException("GuidSerializer cannot serialize a Guid when GuidRepresentation is Unspecified.");
                }
                var bytes   = GuidConverter.ToBytes(value, writerGuidRepresentation);
                var subType = (writerGuidRepresentation == GuidRepresentation.Standard) ? BsonBinarySubType.UuidStandard : BsonBinarySubType.UuidLegacy;
                bsonWriter.WriteBinaryData(new BsonBinaryData(bytes, subType, writerGuidRepresentation));
                break;

            case BsonType.String:
                bsonWriter.WriteString(value.ToString());
                break;

            default:
                var message = string.Format("'{0}' is not a valid Guid representation.", _representation);
                throw new BsonSerializationException(message);
            }
        }
예제 #3
0
        private /*static*/ object readValue(XmlReader xmlReader, Type type, IFormatterConverter converter)
        {
            System.Diagnostics.Debug.Assert(null != xmlReader, "The 'xmlReader' argument cannot be null.");
            System.Diagnostics.Debug.Assert(null != type, "The 'type' argument cannot be null.");
            System.Diagnostics.Debug.Assert(this.isSimpleType(type), "The Type type is not a simple type.");
            System.Diagnostics.Debug.Assert(null != converter, "The 'converter' argument cannot be null.");

            object value = null;             // Return value
            string valueRepresentation = xmlReader.ReadString();

            if (type.IsPrimitive || typeof(System.String) == type)
            {
                value = converter.Convert(valueRepresentation, type);
            }
            else if (type.IsEnum)
            {
                value = Enum.Parse(type, valueRepresentation);
            }
            else if (typeof(System.Guid) == type)
            {
                value = new GuidConverter().ConvertFromInvariantString(valueRepresentation);
            }

            // When the value is the empty string the xml element is empty and there is not an xml end element.
            // Read the following element.
            if (xmlReader.IsEmptyElement)
            {
                xmlReader.ReadStartElement();
            }

            return(value);
        }
예제 #4
0
 static Converter()
 {
     BoolConverter.Initialize();
     CharConverter.Initialize();
     ByteConverter.Initialize();
     SByteConverter.Initialize();
     Int16Converter.Initialize();
     UInt16Converter.Initialize();
     Int32Converter.Initialize();
     UInt32Converter.Initialize();
     Int64Converter.Initialize();
     UInt64Converter.Initialize();
     SingleConverter.Initialize();
     DoubleConverter.Initialize();
     DecimalConverter.Initialize();
     BigIntegerConverter.Initialize();
     BytesConverter.Initialize();
     CharsConverter.Initialize();
     StringConverter.Initialize();
     StringBuilderConverter.Initialize();
     DateTimeConverter.Initialize();
     TimeSpanConverter.Initialize();
     GuidConverter.Initialize();
     MemoryStreamConverter.Initialize();
     StreamConverter.Initialize();
 }
예제 #5
0
        public void PropertiesTest()
        {
            var converter = new GuidConverter();

            Assert.AreEqual(false, converter.AcceptsNativeType);
            Assert.AreEqual(typeof(Guid), converter.ConvertedType);
        }
예제 #6
0
        public void Explicit_decoding_with_standard_representation_should_work_as_expected()
        {
            GuidMode.Set(GuidRepresentationMode.V3);

            var guid       = new Guid("00112233445566778899aabbccddeeff");
            var bytes      = GuidConverter.ToBytes(guid, GuidRepresentation.Standard);
            var binaryData = new BsonBinaryData(bytes, BsonBinarySubType.UuidStandard);

            var exception = Record.Exception(() => binaryData.ToGuid(GuidRepresentation.Unspecified));

            exception.Should().BeOfType <ArgumentException>();

            foreach (var guidRepresentation in new[] { GuidRepresentation.CSharpLegacy, GuidRepresentation.JavaLegacy, GuidRepresentation.PythonLegacy })
            {
                exception = Record.Exception(() => binaryData.ToGuid(guidRepresentation));
                exception.Should().BeOfType <InvalidOperationException>();
            }

            var result = binaryData.ToGuid();

            result.Should().Be(guid);

            result = binaryData.ToGuid(GuidRepresentation.Standard);
            result.Should().Be(guid);
        }
예제 #7
0
        public string CreateKeyWithLocalKmsProvider()
        {
            // Read Master Key from file & Convert
            string localMasterKeyBase64 = File.ReadAllText(__localMasterKeyPath);
            var    localMasterKeyBytes  = Convert.FromBase64String(localMasterKeyBase64);

            // Set KMS Provider Settings
            // Client uses these settings to discover the master key
            var kmsProviders = new Dictionary <string, IReadOnlyDictionary <string, object> >();
            var localOptions = new Dictionary <string, object>
            {
                { "key", localMasterKeyBytes }
            };

            kmsProviders.Add("local", localOptions);

            // Create Data Encryption Key
            var clientEncryption = GetClientEncryption(kmsProviders);
            var dataKeyId        = clientEncryption.CreateDataKey("local", new DataKeyOptions(), CancellationToken.None);

            clientEncryption.Dispose();
            Console.WriteLine($"Local DataKeyId [UUID]: {dataKeyId}");

            var dataKeyIdBase64 = Convert.ToBase64String(GuidConverter.ToBytes(dataKeyId, GuidRepresentation.Standard));

            Console.WriteLine($"Local DataKeyId [base64]: {dataKeyIdBase64}");

            ValidateKey(dataKeyId);
            return(dataKeyIdBase64);
        }
        public void Deserialize_binary_data_should_return_expected_result_when_guid_representation_is_specified(
            [ClassValues(typeof(GuidModeValues))]
            GuidMode mode,
            [Values(-1, GuidRepresentation.Unspecified)]
            GuidRepresentation readerGuidRepresentation,
            [Values(GuidRepresentation.CSharpLegacy, GuidRepresentation.JavaLegacy, GuidRepresentation.PythonLegacy, GuidRepresentation.Standard)]
            GuidRepresentation guidRepresentation)
        {
#pragma warning disable 618
            mode.Set();
            var discriminatorConvention = BsonSerializer.LookupDiscriminatorConvention(typeof(object));
            var subject = new ObjectSerializer(discriminatorConvention, guidRepresentation);
            var bytes   = new byte[] { 29, 0, 0, 0, 5, 120, 0, 16, 0, 0, 0, 3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0 };
            var subType = GuidConverter.GetSubType(guidRepresentation);
            bytes[11] = (byte)subType;
            var readerSettings = new BsonBinaryReaderSettings();
            if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2)
            {
                readerSettings.GuidRepresentation = readerGuidRepresentation == (GuidRepresentation)(-1) ? guidRepresentation : GuidRepresentation.Unspecified;
            }
            using (var memoryStream = new MemoryStream(bytes))
                using (var reader = new BsonBinaryReader(memoryStream, readerSettings))
                {
                    var context = BsonDeserializationContext.CreateRoot(reader);

                    reader.ReadStartDocument();
                    reader.ReadName("x");
                    var result = subject.Deserialize <object>(context);

                    var guidBytes      = bytes.Skip(12).Take(16).ToArray();
                    var expectedResult = GuidConverter.FromBytes(guidBytes, guidRepresentation);
                    result.Should().Be(expectedResult);
                }
#pragma warning restore 618
        }
예제 #9
0
        public void ConvertTo_String_ReturnsExpected()
        {
            var converter = new GuidConverter();
            var value     = new Guid(0x30da92c0, 0x23e8, 0x42a0, 0xae, 0x7c, 0x73, 0x4a, 0x0e, 0x5d, 0x27, 0x82);

            Assert.Equal("30da92c0-23e8-42a0-ae7c-734a0e5d2782", converter.ConvertTo(value, typeof(string)));
        }
예제 #10
0
        private void txtSusID_TextChanged(object sender, EventArgs e)
        {
            // If we have a valid GUID, enable the Add button
            GuidConverter c = new GuidConverter();

            btnAdd.Enabled = c.IsValid(txtSusID.Text);
        }
        public void Deserializer_should_return_expected_result_when_representation_is_binary(
            GuidRepresentationMode defaultGuidRepresentationMode,
            GuidRepresentation defaultGuidRepresentation,
            GuidRepresentation serializerGuidRepresentation,
            GuidRepresentation readerGuidRepresentation,
            GuidRepresentation expectedGuidRepresentation)
        {
            GuidMode.Set(defaultGuidRepresentationMode, defaultGuidRepresentation);

            var subject         = new GuidSerializer(serializerGuidRepresentation);
            var documentBytes   = new byte[] { 29, 0, 0, 0, 5, 120, 0, 16, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0 };
            var documentSubType = GuidConverter.GetSubType(expectedGuidRepresentation);

            documentBytes[11] = (byte)documentSubType;
            var readerSettings = new BsonBinaryReaderSettings();

            if (defaultGuidRepresentationMode == GuidRepresentationMode.V2)
            {
#pragma warning disable 618
                readerSettings.GuidRepresentation = readerGuidRepresentation;
#pragma warning restore 618
            }
            var reader = new BsonBinaryReader(new MemoryStream(documentBytes), readerSettings);
            reader.ReadStartDocument();
            reader.ReadName("x");
            var context = BsonDeserializationContext.CreateRoot(reader);
            var args    = new BsonDeserializationArgs();

            var result = subject.Deserialize(context, args);

            var guidBytes    = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
            var expectedGuid = GuidConverter.FromBytes(guidBytes, expectedGuidRepresentation);
            result.Should().Be(expectedGuid);
        }
        public IHttpActionResult AdmitEnquiry(string referenceId, [FromBody] ResidentRequest resident)
        {
            if (resident == null || string.IsNullOrEmpty(referenceId))
            {
                return(BadRequest("Missing resident data or reference id"));
            }
            if (!GuidConverter.IsValid(resident.EnquiryReferenceId.ToString()))
            {
                return(BadRequest("Connot convert enquiry refence id"));
            }
            if (resident.AdmissionDate == null || resident.AdmissionDate.ToString() == "")
            {
                return(BadRequest("Missing admission date"));
            }

            // ensure enquiry exists?
            var enqExists = _enquiryService.GetByReferenceId(resident.EnquiryReferenceId);

            if (enqExists == null)
            {
                return(BadRequest("Cannot locate enquiry in database. Please verify data"));
            }

            var loggedInUser = HttpContext.Current.User as SecurityPrincipal;

            logger.Info($"Admit an enquiry by {loggedInUser.ForeName}");
            resident.UpdatedBy = loggedInUser.Id;

            var updEnquiry = _residentService.AdmitEnquiry(resident);

            return(Ok(updEnquiry));
        }
예제 #13
0
        /// <summary>
        /// Serializes an object to a BsonWriter.
        /// </summary>
        /// <param name="bsonWriter">The BsonWriter.</param>
        /// <param name="nominalType">The nominal type.</param>
        /// <param name="value">The object.</param>
        /// <param name="options">The serialization options.</param>
        public override void Serialize(
            BsonWriter bsonWriter,
            Type nominalType,
            object value,
            IBsonSerializationOptions options)
        {
            var guid = (Guid)value;
            var representationSerializationOptions = EnsureSerializationOptions <RepresentationSerializationOptions>(options);

            switch (representationSerializationOptions.Representation)
            {
            case BsonType.Binary:
                var writerGuidRepresentation = bsonWriter.Settings.GuidRepresentation;
                if (writerGuidRepresentation == GuidRepresentation.Unspecified)
                {
                    throw new BsonSerializationException("GuidSerializer cannot serialize a Guid when GuidRepresentation is Unspecified.");
                }
                var bytes   = GuidConverter.ToBytes(guid, writerGuidRepresentation);
                var subType = (writerGuidRepresentation == GuidRepresentation.Standard) ? BsonBinarySubType.UuidStandard : BsonBinarySubType.UuidLegacy;
                bsonWriter.WriteBinaryData(new BsonBinaryData(bytes, subType, writerGuidRepresentation));
                break;

            case BsonType.String:
                bsonWriter.WriteString(guid.ToString());
                break;

            default:
                var message = string.Format("'{0}' is not a valid Guid representation.", representationSerializationOptions.Representation);
                throw new BsonSerializationException(message);
            }
        }
예제 #14
0
        // public methods
        /// <summary>
        /// Deserializes a value.
        /// </summary>
        /// <param name="context">The deserialization context.</param>
        /// <param name="args">The deserialization args.</param>
        /// <returns>A deserialized value.</returns>
        public override Guid Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
        {
            var    bsonReader = context.Reader;
            string message;

            var bsonType = bsonReader.GetCurrentBsonType();

            switch (bsonType)
            {
            case BsonType.Binary:
#pragma warning disable 618
                BsonBinaryData binaryData;
                if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2 && _guidRepresentation == GuidRepresentation.Unspecified)
                {
                    binaryData = bsonReader.ReadBinaryData();
                }
                else
                {
                    binaryData = bsonReader.ReadBinaryDataWithGuidRepresentationUnspecified();
                }
                var bytes              = binaryData.Bytes;
                var subType            = binaryData.SubType;
                var guidRepresentation = _guidRepresentation;
                if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2 && guidRepresentation == GuidRepresentation.Unspecified)
                {
                    guidRepresentation = binaryData.GuidRepresentation;
                }
                if (bytes.Length != 16)
                {
                    message = string.Format("Expected length to be 16, not {0}.", bytes.Length);
                    throw new FormatException(message);
                }
                if (subType != BsonBinarySubType.UuidStandard && subType != BsonBinarySubType.UuidLegacy)
                {
                    message = string.Format("Expected binary sub type to be UuidStandard or UuidLegacy, not {0}.", subType);
                    throw new FormatException(message);
                }
                if (guidRepresentation == GuidRepresentation.Unspecified)
                {
                    throw new BsonSerializationException("GuidSerializer cannot deserialize a Guid when GuidRepresentation is Unspecified.");
                }
                if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V3 || _guidRepresentation != GuidRepresentation.Unspecified)
                {
                    var expectedSubType = GuidConverter.GetSubType(guidRepresentation);
                    if (subType != expectedSubType)
                    {
                        throw new FormatException($"GuidSerializer cannot deserialize a Guid when GuidRepresentation is {guidRepresentation} and binary sub type is {subType}.");
                    }
                }
                return(GuidConverter.FromBytes(bytes, guidRepresentation));

#pragma warning restore 618

            case BsonType.String:
                return(new Guid(bsonReader.ReadString()));

            default:
                throw CreateCannotDeserializeFromBsonTypeException(bsonType);
            }
        }
예제 #15
0
        static Converter()
        {
            IsSealed = typeof(T).GetTypeInfo().IsSealed || typeof(T) == typeof(Type);

            (WriteAction, ReadAction) = typeof(T) switch
            {
                Type type when type == typeof(Type) => TypeConverter.GetActions <T>(),
                Type type when type.IsAbstract() => (null, null),
                Type type when type.IsArray => ArrayConverter.GetActions <T>(),
                Type type when type.IsList() => ListConverter.GetActions <T>(),
                Type type when type.IsDictionary() => DictionaryConverter.GetActions <T>(),
                Type type when type.IsEnum() => EnumConverter.GetActions <T>(),
                Type type when type == typeof(char) => GetActions((StreamWriterWrapper w, in char v) => w.Stream.WriteLine(v), s => s[0]),
                Type type when type == typeof(bool) => GetActions((StreamWriterWrapper w, in bool v) => w.Stream.WriteLine(v), bool.Parse),
                Type type when type == typeof(sbyte) => GetActions((StreamWriterWrapper w, in sbyte v) => w.Stream.WriteLine(v), i => sbyte.Parse(i)),
                Type type when type == typeof(byte) => GetActions((StreamWriterWrapper w, in byte v) => w.Stream.WriteLine(v), i => byte.Parse(i)),
                Type type when type == typeof(short) => GetActions((StreamWriterWrapper w, in short v) => w.Stream.WriteLine(v), i => short.Parse(i)),
                Type type when type == typeof(ushort) => GetActions((StreamWriterWrapper w, in ushort v) => w.Stream.WriteLine(v), i => ushort.Parse(i)),
                Type type when type == typeof(int) => GetActions((StreamWriterWrapper w, in int v) => w.Stream.WriteLine(v), i => int.Parse(i)),
                Type type when type == typeof(uint) => GetActions((StreamWriterWrapper w, in uint v) => w.Stream.WriteLine(v), i => uint.Parse(i)),
                Type type when type == typeof(long) => GetActions((StreamWriterWrapper w, in long v) => w.Stream.WriteLine(v), i => long.Parse(i)),
                Type type when type == typeof(ulong) => GetActions((StreamWriterWrapper w, in ulong v) => w.Stream.WriteLine(v), i => ulong.Parse(i)),
                Type type when type == typeof(decimal) => GetActions((StreamWriterWrapper w, in decimal v) => w.Stream.WriteLine(v), i => decimal.Parse(i)),
                Type type when type == typeof(double) => GetActions((StreamWriterWrapper w, in double v) => w.Stream.WriteLine(v), i => double.Parse(i)),
                Type type when type == typeof(float) => GetActions((StreamWriterWrapper w, in float v) => w.Stream.WriteLine(v), i => float.Parse(i)),
                Type type when type == typeof(string) => StringConverter.GetActions <T>(),
                Type type when type == typeof(Guid) => GuidConverter.GetActions <T>(),
                _ => ObjectConverter <T> .GetActions()
            };
        }
예제 #16
0
        private string GuidToString(BsonBinarySubType subType, byte[] bytes, GuidRepresentation guidRepresentation)
        {
            if (bytes.Length != 16)
            {
                var message = string.Format("Length of binary subtype {0} must be 16, not {1}.", subType, bytes.Length);
                throw new ArgumentException(message);
            }
            if (subType == BsonBinarySubType.UuidLegacy)
            {
                if (guidRepresentation == GuidRepresentation.Standard)
                {
                    throw new ArgumentException("GuidRepresentation for binary subtype UuidLegacy must not be Standard.");
                }
            }
            if (subType == BsonBinarySubType.UuidStandard)
            {
                if (guidRepresentation == GuidRepresentation.Unspecified)
                {
                    guidRepresentation = GuidRepresentation.Standard;
                }
                if (guidRepresentation != GuidRepresentation.Standard)
                {
                    var message = string.Format("GuidRepresentation for binary subtype UuidStandard must be Standard, not {0}.", guidRepresentation);
                    throw new ArgumentException(message);
                }
            }

            if (guidRepresentation == GuidRepresentation.Unspecified)
            {
                var s     = BsonUtils.ToHexString(bytes);
                var parts = new string[]
                {
                    s.Substring(0, 8),
                    s.Substring(8, 4),
                    s.Substring(12, 4),
                    s.Substring(16, 4),
                    s.Substring(20, 12)
                };
                return(string.Format("HexData({0}, \"{1}\")", (int)subType, string.Join("-", parts)));
            }
            else
            {
                string uuidConstructorName;
                switch (guidRepresentation)
                {
                case GuidRepresentation.CSharpLegacy: uuidConstructorName = "CSUUID"; break;

                case GuidRepresentation.JavaLegacy: uuidConstructorName = "JUUID"; break;

                case GuidRepresentation.PythonLegacy: uuidConstructorName = "PYUUID"; break;

                case GuidRepresentation.Standard: uuidConstructorName = "UUID"; break;

                default: throw new BsonInternalException("Unexpected GuidRepresentation");
                }
                var guid = GuidConverter.FromBytes(bytes, guidRepresentation);
                return(string.Format("{0}(\"{1}\")", uuidConstructorName, guid.ToString()));
            }
        }
예제 #17
0
        public void GetString_FormatSpecified_IsValid()
        {
            GuidConverter converter = new GuidConverter("N");

            string result = converter.GetString(new Guid(new byte[16]));

            Assert.Equal("00000000000000000000000000000000", result);
        }
예제 #18
0
        public void GetString_FormatSpecified_IsValid()
        {
            GuidConverter converter = new GuidConverter("N");

            string result = converter.GetString(new Guid(new byte[16]));

            Assert.Equal("00000000000000000000000000000000", result);
        }
예제 #19
0
        public void GetValue_NullFormat_IsValid(string value)
        {
            IConverter <Guid> converter = new GuidConverter();

            Guid result = converter.GetValue(value);

            Assert.Equal(new Guid(new byte[16]), result);
        }
 public static ConverterOutputClientModel ToOutputClientModel(this ConverterIoEntity entity)
 {
     return(new ConverterOutputClientModel
     {
         Id = GuidConverter.EncodeGuid(entity.Id),
         UnitSymbol = entity.Unit.Symbol
     });
 }
예제 #21
0
        public void GetValue_FormatSpecified_IsValid()
        {
            IConverter <Guid> converter = new GuidConverter("N");

            Guid result = converter.GetValue("00000000000000000000000000000000");

            Assert.Equal(new Guid(new byte[16]), result);
        }
예제 #22
0
        public void GetValue_ValueDosentMatchFormat_ThrowsFormatException()
        {
            IConverter <Guid> converter = new GuidConverter("N");

            Action action = () => converter.GetValue("00000000-0000-0000-0000-000000000000");

            Assert.Throws <FormatException>(action);
        }
예제 #23
0
        public void GetValue_ValueDosentMatchFormat_ThrowsFormatException()
        {
            IConverter<Guid> converter = new GuidConverter("N");

            Action action = () => converter.GetValue("00000000-0000-0000-0000-000000000000");

            Assert.Throws<FormatException>(action);
        }
예제 #24
0
        public void GetString_NullFormat_IsValid()
        {
            GuidConverter converter = new GuidConverter();

            string result = converter.GetString(new Guid(new byte[16]));

            Assert.Equal("00000000-0000-0000-0000-000000000000", result);
        }
예제 #25
0
        public void GetValue_FormatSpecified_IsValid()
        {
            IConverter<Guid> converter = new GuidConverter("N");

            Guid result = converter.GetValue("00000000000000000000000000000000");

            Assert.Equal(new Guid(new byte[16]), result);
        }
예제 #26
0
        public void GetString_NullFormat_IsValid()
        {
            GuidConverter converter = new GuidConverter();

            string result = converter.GetString(new Guid(new byte[16]));

            Assert.Equal("00000000-0000-0000-0000-000000000000", result);
        }
        public virtual TEntity GetById(Guid id)
        {
            var bytes  = GuidConverter.ToBytes(id, GuidRepresentation.CSharpLegacy);
            var csuuid = new Guid(bytes);

            return(Collection.Find(x => x.Id == csuuid).FirstOrDefault());
            //return GetAllRows().FirstOrDefault(x => x.Id.Equals(id));
        }
예제 #28
0
        public void GetValue_NullFormat_IsValid(string value)
        {
            IConverter<Guid> converter = new GuidConverter();

            Guid result = converter.GetValue(value);

            Assert.Equal(new Guid(new byte[16]), result);
        }
        public void DoWork(IRequest request)
        {
            // If an asyncState object already exists, an exception is thrown as the performer only accepts
            // one call after each other. The Request receiver has to manage a queued execution.

            // Before calling the performers execution implementation method a new AsyncState object is created
            // and set to an initial tracking state.

            lock (_asyncStateObj)
            {
                if (null != _asyncStateObj.Tracking)
                {
                    throw new InvalidOperationException("The performer cannot be executed because it is already running.");
                }

                SyncTracking tracking = new SyncTracking();
                tracking.ElapsedSeconds   = 1;
                tracking.Phase            = TrackingPhase.INIT;
                tracking.PhaseDetail      = "Tracking Id was: " + _requestContext.TrackingId.ToString();
                tracking.PollingMillis    = 100;
                tracking.RemainingSeconds = 100;

                _asyncStateObj.Tracking = tracking;
            }


            // *** Initialization for the async execution ***
            // - Read Feed from request stream.
            // - Read trackingId from request URL

            // convert tracking ID from request to type Guid
            string strTrackingId = request.Uri.TrackingID;

            if (String.IsNullOrEmpty(strTrackingId))
            {
                throw new RequestException("TrackingId is missing");
            }

            GuidConverter converter = new GuidConverter();

            this.TrackingId = (Guid)converter.ConvertFrom(strTrackingId);


            //read feed
            SyncFeed  feed   = new SyncFeed();
            XmlReader reader = XmlReader.Create(request.Stream);

            feed.ReadXml(reader, ResourceKindHelpers.GetPayloadType(_requestContext.ResourceKind));


            // *** Do work asynchronously ***
            _asyncPerformer = new InternalAsyncPerformer(this);
            _asyncPerformer.DoWork(_requestContext.Config, feed);


            // *** set the tracking to the request response ***
            this.GetTrackingState(request);
        }
예제 #30
0
        /// <summary>
        /// Extends ConvertTo so that methods that return a specific type object given a Type parameter can be
        /// used as generic method and casting is not required.
        /// <example>
        /// typeconverter.ConvertTo<int>(value);
        /// </example>
        /// </summary>
        public static T ConvertTo <T>(this GuidConverter typeconverter, Object value)
        {
            if (typeconverter == null)
            {
                throw new ArgumentNullException("typeconverter");
            }

            return((T)typeconverter.ConvertTo(value, typeof(T)));
        }
예제 #31
0
        /// <summary>
        /// Extends ConvertTo so that methods that return a specific type object given a Type parameter can be
        /// used as generic method and casting is not required.
        /// <example>
        /// guidconverter.ConvertTo<int>(context, culture, value);
        /// </example>
        /// </summary>
        public static T ConvertTo <T>(this GuidConverter guidconverter, ITypeDescriptorContext context, System.Globalization.CultureInfo culture, Object value)
        {
            if (guidconverter == null)
            {
                throw new ArgumentNullException("guidconverter");
            }

            return((T)guidconverter.ConvertTo(context, culture, value, typeof(T)));
        }
예제 #32
0
 public static ConverterListClientModel ToClientModel(this ConverterListEntity entity)
 {
     return(new ConverterListClientModel
     {
         Id = GuidConverter.EncodeGuid(entity.Id),
         DisplayName = entity.DisplayName,
         Converters = entity.Converters.ToClientModels()
     });
 }
예제 #33
0
        public void StringToGuidTest()
        {
            var guid    = new Guid();
            var guidStr = guid.ToString();

            var guid2 = GuidConverter.ToGuid(guidStr);

            Assert.Equal(guid, guid2);
        }
예제 #34
0
 public static int NullableGuidToURI(char[] buf, int pos, Guid?value)
 {
     if (value == null)
     {
         return(pos);
     }
     GuidConverter.Serialize(value.Value, buf, pos);
     return(pos + 36);
 }
예제 #35
0
        public static Guid ToCSUUid(this Guid guid)
        {
            BsonDefaults.GuidRepresentation = GuidRepresentation.PythonLegacy;
            var luuid  = new Guid(guid.ToString());
            var bytes  = GuidConverter.ToBytes(luuid, GuidRepresentation.PythonLegacy);
            var csuuid = new Guid(bytes);

            return(csuuid);
        }