public ResultadoMapa ListLugares(DataContract.PointDC tl, DataContract.PointDC br, byte zoom, FiltroMapa filtro)
 {
     if (zoom >= 8)
     {
         PersistenceManager persistence = new PersistenceManager();
         ICriteria criteria = persistence.CreateCriteria<Lugar>();
         List<Coordinate> coordenadas = new List<Coordinate>();
         coordenadas.Add(new Coordinate(tl.Longitud, tl.Latitud));
         coordenadas.Add(new Coordinate(br.Longitud, tl.Latitud));
         coordenadas.Add(new Coordinate(br.Longitud, br.Latitud));
         coordenadas.Add(new Coordinate(tl.Longitud, br.Latitud));
         coordenadas.Add(new Coordinate(tl.Longitud, tl.Latitud));
         Polygon p = new Polygon(new LinearRing(coordenadas.ToArray()));
         criteria.SetProjection(Projections.ProjectionList()
             .Add(Projections.Property<Lugar>(l => l.ID), "ID")
             .Add(Projections.Property<Lugar>(l => l.Posicion), "Point")
             .Add(Projections.Property<Lugar>(l => l.Nombre), "Nombre")
             );
         criteria.Add(SpatialRestrictions.Within("Posicion", p));
         criteria.SetResultTransformer(Transformers.AliasToBean<ItemLugar>());
         criteria.AddOrder(new Order(Projections.Property<Lugar>(l => l.Nombre), true));
         var list = criteria.List<ItemLugar>().ToList();
         HttpContext.Current.Session["Colegios"] = list;
         return new ResultadoMapa() { Items = list };
     }
     return new ResultadoMapa() { Items = new List<ItemLugar>() };
 }
        public DataContract.RemarkResponse AddRemark(string employeeId, DataContract.Remark remark)
        {
            RemarkResponse response = new RemarkResponse();
            try
            {
                var result = _manager.AddRemark(employeeId, remark.ToDomainModel());
                if (result == null)
                {
                    response.Status.StatusCode = "500";
                    response.Status.Message = "Error in creating employee";

                    return response;
                }
                response.Remark = result.ToDataContract();
                return response;
            }
            catch (Exception ex)
            {

                ExceptionPolicy.HandleException("service.policy", ex);
                response.Status.StatusCode = "500";
                response.Status.Message = "Error in creating Employee";
                return response;
            }
        }
        public DataContract.EmployeeResponse Create(DataContract.Employee employee)
        {
            EmployeeResponse response = new EmployeeResponse();
            try
            {
                employee.JoiningDate = DateTime.UtcNow;
                var result = _manager.Create(employee.ToDomainModel());
                if (result == null)
                {
                    response.Status.StatusCode = "500";
                    response.Status.Message = "Error in creating employee";

                    return response;
                }
                response.Employee = result.ToDataContract();
                return response;
            }
            catch (Exception ex)
            {

                ExceptionPolicy.HandleException("service.policy", ex);
                response.Status.StatusCode = "500";
                response.Status.Message = "Error in creating Employee";
                return response;
            }
        }
        public XmlObjectSerializerWriteContextComplexJson(DataContractJsonSerializer serializer, DataContract rootTypeDataContract)
            : base(null, int.MaxValue, new StreamingContext(), true)

        {
            _jsonSerializer = serializer;
            this.rootTypeDataContract = rootTypeDataContract;
            this.serializerKnownTypeList = serializer.knownTypeList;
        }
 internal XmlObjectSerializerWriteContextComplexJson(DataContractJsonSerializerImpl serializer, DataContract rootTypeDataContract)
     : base(serializer, serializer.MaxItemsInObjectGraph, new StreamingContext(), false)
 {
     _emitXsiType = serializer.EmitTypeInformation;
     this.rootTypeDataContract = rootTypeDataContract;
     this.serializerKnownTypeList = serializer.knownTypeList;
     this.serializeReadOnlyTypes = serializer.SerializeReadOnlyTypes;
     _useSimpleDictionaryFormat = serializer.UseSimpleDictionaryFormat;
 }
示例#6
0
        int IBlogService.CreateEntry(DataContract.Entry entry)
        {
			var entity = new Entity.Entry()
			{
				Content = entry.Content,
				Name = entry.Title,
				Id = new Random().Next(1000)
			};
			return entity.Id;
        }
 public XmlObjectSerializerReadContextComplexJson(DataContractJsonSerializer serializer, DataContract rootTypeDataContract)
     : base(serializer, serializer.MaxItemsInObjectGraph,
         new StreamingContext(StreamingContextStates.All),
         serializer.IgnoreExtensionDataObject)
 {
     this.rootTypeDataContract = rootTypeDataContract;
     this.serializerKnownTypeList = serializer.knownTypeList;
     this.dataContractSurrogate = serializer.DataContractSurrogate;
     this.dateTimeFormat = serializer.DateTimeFormat;
     this.useSimpleDictionaryFormat = serializer.UseSimpleDictionaryFormat;
 }
        public static void Translate(Repository.Item dbItem, DataContract.Item item)
        {
            dbItem.ItemAbstract = item.ItemAbstract;
            dbItem.ItemTitle = item.ItemTitle;
            dbItem.LastUpdated = DateTime.Now;

            if (item.Content != null)
            {
                dbItem.InternalUrl = item.Content.InternalUrl;
                dbItem.ExternalUrl = item.Content.ExternalUrl;
                dbItem.ItemText = item.Content.ItemText;
            }
        }
 public bool ChangePassword(DataContract.ChangePasswordRequest request)
 {
     try
     {
         return _manager.ChangePassword(request.Email, request.OldPassword, request.NewPassword);
     }
     catch (Exception ex)
     {
         Exception newEx;
         var rethrow = ExceptionPolicy.HandleException("service.policy", ex, out newEx);
         return false;
     }
 }
示例#10
0
		void IBlogService.AddEntry(int blogId, DataContract.Entry entry)
		{
			var entryEntity = new Entity.Entry()
			{
				Name = entry.Title,
				Content = entry.Content,
				//BlogId = blogId
			};
			if (_repository.Query<Entity.Blog>().Where(x => x.Id == blogId).Any())
			{
				_repository.Persist(entryEntity);
			}
		}
        public DataContract.EmployeeResponse Authenticate(DataContract.Credentials credentials)
        {
            EmployeeResponse response = new EmployeeResponse();
            var result = _manager.Authenticate(credentials.EmailId, credentials.Password);
            if (result == null)
            {
                response.Status.StatusCode = "500";
                response.Status.Message = "Error in creating employee";

                return response;
            }
            response.Employee = result.ToDataContract();
            return response;
        }
 public DataContract.Employee Authenticate(DataContract.Credential credential)
 {
     try
     {
         var result = _manager.Authenticate(credential.ToDomainModel());
         if (result == null) return null;
         return result.ToDataContract();
     }
     catch (Exception ex)
     {
         var rethrow = ExceptionPolicy.HandleException("service.policy", ex);
         if (rethrow) throw;
         return null;
     }
 }
 public DataContract.Employee Create(DataContract.Employee employee)
 {
     try
     {
         var result = _manager.Create(employee.ToDomainModel());
         if (result == null) return null;
         return result.ToDataContract();
     }
     catch (Exception ex)
     {
         Exception newEx;
         var rethrow = ExceptionPolicy.HandleException("service.policy", ex, out newEx);
         throw newEx;
     }
 }
 public DataContract.Remark AddRemark(string employeeId, DataContract.Remark remark)
 {
     try
     {
         var result = _manager.AddRemark(employeeId, remark.ToDomainModel());
         if (result == null) return null;
         return result.ToDataContract();
     }
     catch (Exception ex)
     {
         Exception newEx;
         var rethrow = ExceptionPolicy.HandleException("service.policy", ex, out newEx);
         throw newEx;
     }
 }
		public void WriteCollectionToJson (XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, CollectionDataContract dataContract)
		{
			this.writer = xmlWriter;
			this.obj = obj;
			this.context = context;
			this.dataContract = dataContract;

			InitArgs (collectionContract.UnderlyingType);			

			// DemandMemberAccessPermission(memberAccessFlag);
			if (collectionContract.IsReadOnlyContract)
			{
				DataContract.ThrowInvalidDataContractException (collectionContract.SerializationExceptionMessage, null);
			}

			WriteCollection (collectionContract);
		}
		public void WriteToJson (XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, ClassDataContract dataContract, XmlDictionaryString [] memberNames)
		{
			this.writer = xmlWriter;
			this.obj = obj;
			this.context = context;
			this.dataContract = dataContract;
			this.memberNames = memberNames;

			InitArgs (classContract.UnderlyingType);

			// DemandSerializationFormatterPermission (classContract) - irrelevant
			// DemandMemberAccessPermission (memberAccessFlag) - irrelevant

			if (classContract.IsReadOnlyContract)
			{
				DataContract.ThrowInvalidDataContractException (classContract.SerializationExceptionMessage, null);
			}

			WriteClass (classContract);
		}
示例#17
0
 public void InsertKeyOperationHistories(List<KeyInfo> keys, DataContract.KeyState targetKeyState, string @operator, string message)
 {
     using (var context = GetContext())
     {
         foreach (var keyInfo in keys)
         {
             KeyOperationHistory koh = new KeyOperationHistory()
             {
                 KeyId = keyInfo.KeyId,
                 ProductKey = keyInfo.ProductKey,
                 HardwareHash = keyInfo.HardwareHash,
                 KeyStateFrom = (byte)keyInfo.KeyState,
                 KeyStateTo = (byte)targetKeyState,
                 Message = message,
                 Operator = @operator,
                 CreatedDate = DateTime.UtcNow
             };
             context.KeyOperationHistories.Add(koh);
         }
         context.SaveChanges();
     }
 }
示例#18
0
        public int PutItem(DataContract.Item Item)
        {
            // Owner
            // UriTemplate = "PutItem/{Item}",
            int itemsChanged = 0;
            Notenet.Content.Data.Repository.Item dbItem = this.content.Items.Where(i => i.ItemID == Item.ItemID).Single();
            try
            {
                ItemTranslator.Translate(dbItem, Item);
                itemsChanged = this.content.SaveChanges();
            }
            catch (OptimisticConcurrencyException e)
            {
                this.content.Refresh(RefreshMode.ClientWins, dbItem);
                itemsChanged = this.content.SaveChanges();
                // log exception after operation called by some attributes?
            }

            // this.content.PutItem();

            return itemsChanged;
        }
 internal XmlObjectSerializerWriteContextComplexJson(DataContractJsonSerializerImpl serializer, DataContract rootTypeDataContract)
     : base(serializer, serializer.MaxItemsInObjectGraph, new StreamingContext(), false)
 {
     _emitXsiType = serializer.EmitTypeInformation;
     this.rootTypeDataContract    = rootTypeDataContract;
     this.serializerKnownTypeList = serializer.knownTypeList;
     this.serializeReadOnlyTypes  = serializer.SerializeReadOnlyTypes;
     _useSimpleDictionaryFormat   = serializer.UseSimpleDictionaryFormat;
 }
        private void VerifyType(DataContract dataContract, Type declaredType)
        {
            bool knownTypesAddedInCurrentScope = false;
            if (dataContract.KnownDataContracts != null)
            {
                scopedKnownTypes.Push(dataContract.KnownDataContracts);
                knownTypesAddedInCurrentScope = true;
            }

            if (!IsKnownType(dataContract, declaredType))
            {
                throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DcTypeNotFoundOnSerialize, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace));
            }

            if (knownTypesAddedInCurrentScope)
            {
                scopedKnownTypes.Pop();
            }
        }
        internal override void SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType)
        {
            bool verifyKnownType = false;
            Type declaredType = rootTypeDataContract.UnderlyingType;
            bool isDeclaredTypeInterface = declaredType.GetTypeInfo().IsInterface;

            if (!(isDeclaredTypeInterface && CollectionDataContract.IsCollectionInterface(declaredType))
                && !declaredType.IsArray)//Array covariance is not supported in XSD. If declared type is array do not write xsi:type. Instead write xsi:type for each item
            {
                verifyKnownType = WriteTypeInfo(xmlWriter, dataContract, rootTypeDataContract);
                HandleCollectionAssignedToObject(declaredType, ref dataContract, ref obj, ref verifyKnownType);
            }

            if (isDeclaredTypeInterface)
            {
                VerifyObjectCompatibilityWithInterface(dataContract, obj, declaredType);
            }
            SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, declaredType.TypeHandle, declaredType);
        }
 protected override void WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle declaredTypeHandle)
 {
     JsonDataContract jsonDataContract = JsonDataContract.GetJsonDataContract(dataContract);
     if (_emitXsiType == EmitTypeInformation.Always && !_perCallXsiTypeAlreadyEmitted && RequiresJsonTypeInfo(dataContract))
     {
         WriteTypeInfo(xmlWriter, jsonDataContract.TypeName);
     }
     _perCallXsiTypeAlreadyEmitted = false;
     DataContractJsonSerializerImpl.WriteJsonValue(jsonDataContract, xmlWriter, obj, this, declaredTypeHandle);
 }
示例#23
0
 protected JsonDataContract(DataContract traditionalDataContract)
 {
     _helper = new JsonDataContractCriticalHelper(traditionalDataContract);
 }
        private static string GetTypeName(DataContract dataContract)
        {
            string ns = XmlObjectSerializerWriteContextComplexJson.TruncateDefaultDataContractNamespace(dataContract.Namespace.Value);

            return(dataContract.Name.Value + ((ns.Length == 0) ? "" : (":" + ns)));
        }
        internal void WriteJsonISerializable(XmlWriterDelegator xmlWriter, ISerializable obj)
        {
            Type objType = obj.GetType();
            var  serInfo = new SerializationInfo(objType, XmlObjectSerializer.FormatterConverter);

            GetObjectData(obj, serInfo, GetStreamingContext());
            if (DataContract.GetClrTypeFullName(objType) != serInfo.FullTypeName)
            {
                throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ChangingFullTypeNameNotSupported, serInfo.FullTypeName, DataContract.GetClrTypeFullName(objType))));
            }
            else
            {
                base.WriteSerializationInfo(xmlWriter, objType, serInfo);
            }
        }
示例#26
0
 private void CopyMembersAndCheckDuplicateNames()
 {
     if (_traditionalClassDataContract.MemberNames != null)
     {
         int memberCount = _traditionalClassDataContract.MemberNames.Length;
         Dictionary <string, object> memberTable        = new Dictionary <string, object>(memberCount);
         XmlDictionaryString[]       decodedMemberNames = new XmlDictionaryString[memberCount];
         for (int i = 0; i < memberCount; i++)
         {
             if (memberTable.ContainsKey(_traditionalClassDataContract.MemberNames[i].Value))
             {
                 throw new SerializationException(SR.Format(SR.JsonDuplicateMemberNames, DataContract.GetClrTypeFullName(_traditionalClassDataContract.UnderlyingType), _traditionalClassDataContract.MemberNames[i].Value));
             }
             else
             {
                 memberTable.Add(_traditionalClassDataContract.MemberNames[i].Value, null);
                 decodedMemberNames[i] = DataContractJsonSerializerImpl.ConvertXmlNameToJsonName(_traditionalClassDataContract.MemberNames[i]);
             }
         }
         _memberNames = decodedMemberNames;
     }
 }
        private void ReadSimpleDictionary(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract, Type keyValueType, object dictionary)
        {
            Type[] keyValueTypes = keyValueType.GetGenericArguments();
            Type   keyType       = keyValueTypes[0];
            Type   valueType     = keyValueTypes[1];

            int keyTypeNullableDepth = 0;

            while (keyType.IsGenericType && keyType.GetGenericTypeDefinition() == Globals.TypeOfNullable)
            {
                keyTypeNullableDepth++;
                keyType = keyType.GetGenericArguments()[0];
            }

            ClassDataContract keyValueDataContract = (ClassDataContract)collectionContract.ItemContract;
            DataContract      keyDataContract      = keyValueDataContract.Members[0].MemberTypeContract;

            KeyParseMode keyParseMode = KeyParseMode.Fail;

            if (keyType == Globals.TypeOfString || keyType == Globals.TypeOfObject)
            {
                keyParseMode = KeyParseMode.AsString;
            }
            else if (keyType.IsEnum)
            {
                keyParseMode = KeyParseMode.UsingParseEnum;
            }
            else if (keyDataContract.ParseMethod != null)
            {
                keyParseMode = KeyParseMode.UsingCustomParse;
            }

            if (keyParseMode == KeyParseMode.Fail)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                          new InvalidOperationException(
                              SR.Format(SR.KeyTypeCannotBeParsedInSimpleDictionary,
                                        DataContract.GetClrTypeFullName(collectionContract.UnderlyingType),
                                        DataContract.GetClrTypeFullName(keyType))
                              ));
            }

            while (true)
            {
                XmlNodeType nodeType = xmlReader.MoveToContent();
                if (nodeType == XmlNodeType.EndElement)
                {
                    return;
                }
                if (nodeType != XmlNodeType.Element)
                {
                    throw XmlObjectSerializerReadContext.CreateUnexpectedStateException(XmlNodeType.Element, xmlReader);
                }

                context.IncrementItemCount(1);
                string keyString = XmlObjectSerializerReadContextComplexJson.GetJsonMemberName(xmlReader);
                object pairKey;

                if (keyParseMode == KeyParseMode.UsingParseEnum)
                {
                    pairKey = Enum.Parse(keyType, keyString);
                }
                else if (keyParseMode == KeyParseMode.UsingCustomParse)
                {
                    TypeCode typeCode = Type.GetTypeCode(keyDataContract.UnderlyingType);
                    pairKey = typeCode switch
                    {
                        TypeCode.Boolean => bool.Parse(keyString),
                        TypeCode.Int16 => short.Parse(keyString),
                        TypeCode.Int32 => int.Parse(keyString),
                        TypeCode.Int64 => long.Parse(keyString),
                        TypeCode.Char => char.Parse(keyString),
                        TypeCode.Byte => byte.Parse(keyString),
                        TypeCode.SByte => sbyte.Parse(keyString),
                        TypeCode.Double => double.Parse(keyString),
                        TypeCode.Decimal => decimal.Parse(keyString),
                        TypeCode.Single => float.Parse(keyString),
                        TypeCode.UInt16 => ushort.Parse(keyString),
                        TypeCode.UInt32 => uint.Parse(keyString),
                        TypeCode.UInt64 => ulong.Parse(keyString),
                        _ => keyDataContract.ParseMethod.Invoke(null, new object[] { keyString }),
                    };
                }
                else
                {
                    pairKey = keyString;
                }

                if (keyTypeNullableDepth > 0)
                {
                    throw new NotImplementedException(SR.Format(SR.MustBeGreaterThanZero, keyTypeNullableDepth));
                }

                object pairValue = ReflectionReadValue(xmlReader, context, valueType, string.Empty, string.Empty);


                ((IDictionary)dictionary).Add(pairKey, pairValue);
            }
        }
示例#28
0
 public static JsonDataContract GetJsonDataContract(DataContract traditionalDataContract)
 {
     return(JsonDataContractCriticalHelper.GetJsonDataContract(traditionalDataContract));
 }
示例#29
0
        internal static JsonReadWriteDelegates?TryGetReadWriteDelegatesFromGeneratedAssembly(DataContract c)
        {
            JsonReadWriteDelegates?result = GetGeneratedReadWriteDelegates(c);

            return(result);
        }
示例#30
0
        internal static JsonReadWriteDelegates GetReadWriteDelegatesFromGeneratedAssembly(DataContract c)
        {
            JsonReadWriteDelegates?result = GetGeneratedReadWriteDelegates(c);

            if (result == null)
            {
                throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, c.UnderlyingType));
            }
            else
            {
                return(result);
            }
        }
示例#31
0
 private static JsonDataContract CreateJsonDataContract(int id, DataContract traditionalDataContract)
 {
     lock (s_createDataContractLock)
     {
         JsonDataContract dataContract = s_dataContractCache[id];
         if (dataContract == null)
         {
             Type traditionalDataContractType = traditionalDataContract.GetType();
             if (traditionalDataContractType == typeof(ObjectDataContract))
             {
                 dataContract = new JsonObjectDataContract(traditionalDataContract);
             }
             else if (traditionalDataContractType == typeof(StringDataContract))
             {
                 dataContract = new JsonStringDataContract((StringDataContract)traditionalDataContract);
             }
             else if (traditionalDataContractType == typeof(UriDataContract))
             {
                 dataContract = new JsonUriDataContract((UriDataContract)traditionalDataContract);
             }
             else if (traditionalDataContractType == typeof(QNameDataContract))
             {
                 dataContract = new JsonQNameDataContract((QNameDataContract)traditionalDataContract);
             }
             else if (traditionalDataContractType == typeof(ByteArrayDataContract))
             {
                 dataContract = new JsonByteArrayDataContract((ByteArrayDataContract)traditionalDataContract);
             }
             else if (traditionalDataContract.IsPrimitive ||
                      traditionalDataContract.UnderlyingType == Globals.TypeOfXmlQualifiedName)
             {
                 dataContract = new JsonDataContract(traditionalDataContract);
             }
             else if (traditionalDataContractType == typeof(ClassDataContract))
             {
                 dataContract = new JsonClassDataContract((ClassDataContract)traditionalDataContract);
             }
             else if (traditionalDataContractType == typeof(EnumDataContract))
             {
                 dataContract = new JsonEnumDataContract((EnumDataContract)traditionalDataContract);
             }
             else if ((traditionalDataContractType == typeof(GenericParameterDataContract)) ||
                      (traditionalDataContractType == typeof(SpecialTypeDataContract)))
             {
                 dataContract = new JsonDataContract(traditionalDataContract);
             }
             else if (traditionalDataContractType == typeof(CollectionDataContract))
             {
                 dataContract = new JsonCollectionDataContract((CollectionDataContract)traditionalDataContract);
             }
             else if (traditionalDataContractType == typeof(XmlDataContract))
             {
                 dataContract = new JsonXmlDataContract((XmlDataContract)traditionalDataContract);
             }
             else
             {
                 throw new ArgumentException(SR.Format(SR.JsonTypeNotSupportedByDataContractJsonSerializer, traditionalDataContract.UnderlyingType), nameof(traditionalDataContract));
             }
         }
         return(dataContract);
     }
 }
示例#32
0
            internal XmlDataContractCriticalHelper(
                [DynamicallyAccessedMembers(ClassDataContract.DataContractPreserveMemberTypes)]
                Type type) : base(type)
            {
                if (type.IsDefined(Globals.TypeOfDataContractAttribute, false))
                {
                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IXmlSerializableCannotHaveDataContract, DataContract.GetClrTypeFullName(type))));
                }
                if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false))
                {
                    throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IXmlSerializableCannotHaveCollectionDataContract, DataContract.GetClrTypeFullName(type))));
                }
                bool             hasRoot;
                XmlSchemaType?   xsdType;
                XmlQualifiedName xmlName;

                SchemaExporter.GetXmlTypeInfo(type, out xmlName, out xsdType, out hasRoot);
                XmlName = xmlName;
                XsdType = xsdType;
                HasRoot = hasRoot;
                XmlDictionary dictionary = new XmlDictionary();

                Name      = dictionary.Add(XmlName.Name);
                Namespace = dictionary.Add(XmlName.Namespace);
                object[]? xmlRootAttributes = UnderlyingType?.GetCustomAttributes(Globals.TypeOfXmlRootAttribute, false).ToArray();
                if (xmlRootAttributes == null || xmlRootAttributes.Length == 0)
                {
                    if (hasRoot)
                    {
                        _topLevelElementName       = Name;
                        _topLevelElementNamespace  = (this.XmlName.Namespace == Globals.SchemaNamespace) ? DictionaryGlobals.EmptyString : Namespace;
                        _isTopLevelElementNullable = true;
                    }
                }
                else
                {
                    if (hasRoot)
                    {
                        XmlRootAttribute xmlRootAttribute = (XmlRootAttribute)xmlRootAttributes[0];
                        _isTopLevelElementNullable = xmlRootAttribute.IsNullable;
                        string elementName = xmlRootAttribute.ElementName;
                        _topLevelElementName = (elementName == null || elementName.Length == 0) ? Name : dictionary.Add(DataContract.EncodeLocalName(elementName));
                        string?elementNs = xmlRootAttribute.Namespace;
                        _topLevelElementNamespace = (elementNs == null || elementNs.Length == 0) ? DictionaryGlobals.EmptyString : dictionary.Add(elementNs);
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IsAnyCannotHaveXmlRoot, DataContract.GetClrTypeFullName(UnderlyingType !))));
                    }
                }
            }
示例#33
0
#pragma warning disable CS1998
        /// <summary>
        /// Yield return values for single or multiple resultsets.
        /// </summary>
        /// <typeparam name="X">Use with <typeparamref name="T"/> for single or <see cref="IEnumerable{T}"/> for multiple</typeparam>
        /// <param name="command">The command to execute</param>
        /// <param name="cancellationToken">Async <see cref="CancellationToken"/></param>
        /// <param name="behavior">The command behaviour</param>
        /// <param name="connection">Optional conneciton to use</param>
        /// <param name="outerReader">The outer reader when this is a call to the inner reader in QueryMultiple</param>
        /// <returns></returns>
        override protected async Task <IAsyncEnumerable <X> > QueryNWithParamsAsync <X>(DbCommand command, CancellationToken cancellationToken = default, CommandBehavior behavior = CommandBehavior.Default, DbConnection connection = null, DbDataReader outerReader = null)
        {
            return(new AsyncEnumerable <X>(async yield => {
                using (command)
                {
                    if (behavior == CommandBehavior.Default && typeof(X) == typeof(T))
                    {
                        // (= single result set, not single row...)
                        behavior = CommandBehavior.SingleResult;
                    }
                    // using is applied only to locally generated connection
                    using (var localConn = (connection == null ? await OpenConnectionAsync(cancellationToken).ConfigureAwait(false) : null))
                    {
                        if (command != null)
                        {
                            command.Connection = connection ?? localConn;
                        }
                        // manage wrapping transaction if required, and if we have not been passed an incoming connection
                        // in which case assume user can/should manage it themselves
                        using (var trans = (connection == null
#if NETFRAMEWORK
                                            // TransactionScope support
                                            && Transaction.Current == null
#endif
                                            && Plugin.RequiresWrappingTransaction(command) ? localConn.BeginTransaction() : null))
                        {
                            using (var reader = (outerReader == null ? await Plugin.ExecuteDereferencingReaderAsync(command, behavior, connection ?? localConn, cancellationToken).ConfigureAwait(false) : null))
                            {
                                if (typeof(X) == typeof(IAsyncEnumerable <T>))
                                {
                                    // query multiple pattern
                                    do
                                    {
                                        // cast is required because compiler doesn't see that we've just checked that X is IEnumerable<T>
                                        // first three params carefully chosen so as to avoid lots of checks about outerReader in the code above in this method
                                        var next = (X)(await QueryNWithParamsAsync <T>(null, cancellationToken, (CommandBehavior)(-1), connection ?? localConn, reader).ConfigureAwait(false));
                                        // yield.ReturnAsync does not take a cancellation token (it would have nothing to do
                                        // with it except pass it back to the caller who provided it in the first place, if it did)
                                        await yield.ReturnAsync(next).ConfigureAwait(false);
                                    }while (await reader.NextResultAsync(cancellationToken).ConfigureAwait(false));
                                }
                                else
                                {
                                    // Reasonably fast inner loop to yield-return objects of the required type from the DbDataReader.
                                    //
                                    // Used to be a separate function YieldReturnRows(), called here or within the loop above; but you can't do a yield return
                                    // for an outer function in an inner function (nor inside a delegate), so we're using recursion to avoid duplicating this
                                    // entire inner loop.
                                    //
                                    DbDataReader useReader = outerReader ?? reader;

                                    if (useReader.HasRows)
                                    {
                                        int fieldCount = useReader.FieldCount;
                                        object[] rowValues = new object[fieldCount];

                                        // this is for dynamic support
                                        string[] columnNames = null;
                                        // this is for generic<T> support
                                        DataContractMemberInfo[] memberInfo = null;

                                        if (!IsGeneric)
                                        {
                                            columnNames = new string[fieldCount];
                                        }
                                        else
                                        {
                                            memberInfo = new DataContractMemberInfo[fieldCount];
                                        }

                                        // for generic, we need array of properties to set; we find this
                                        // from fieldNames array, using a look up from lowered name -> property
                                        for (int i = 0; i < fieldCount; i++)
                                        {
                                            var columnName = useReader.GetName(i);
                                            if (string.IsNullOrEmpty(columnName))
                                            {
                                                throw new InvalidOperationException("Cannot autopopulate from anonymous column");
                                            }
                                            if (!IsGeneric)
                                            {
                                                // For dynamics, create fields using the case that comes back from the database
                                                // TO DO: Test how this is working now in Oracle
                                                // leaves as null if no match
                                                DataContract.TryGetDataMemberName(columnName, out columnNames[i], DataDirection.Read);
                                            }
                                            else
                                            {
                                                // leaves as null if no match
                                                DataContract.TryGetDataMemberInfo(columnName, out memberInfo[i], DataDirection.Read);
                                            }
                                        }
                                        while (await useReader.ReadAsync(cancellationToken).ConfigureAwait(false))
                                        {
                                            useReader.GetValues(rowValues);
                                            if (!IsGeneric)
                                            {
                                                ExpandoObject e = new ExpandoObject();
                                                IDictionary <string, object> d = e.ToDictionary();
                                                for (int i = 0; i < fieldCount; i++)
                                                {
                                                    var v = rowValues[i];
                                                    d.Add(columnNames[i], v == DBNull.Value ? null : v);
                                                }
                                                await yield.ReturnAsync((X)(object)e).ConfigureAwait(false);
                                            }
                                            else
                                            {
                                                T t = new T();
                                                for (int i = 0; i < fieldCount; i++)
                                                {
                                                    var v = rowValues[i];
                                                    memberInfo[i]?.SetValue(t, v == DBNull.Value ? null : v);
                                                }
                                                await yield.ReturnAsync((X)(object)t).ConfigureAwait(false);
                                            }
                                        }
                                    }
                                }
                            }
                            if (trans != null)
                            {
                                trans.Commit();
                            }
                        }
                    }
                }
            }));
        }
示例#34
0
    public async void M()
    {
        // Assignment, tainted
        var sink0 = "taint source";

        Check(sink0);

        // Assignment, not tainted
        var nonSink0 = "";

        Check(nonSink0);

        // Assignment (concatenation), tainted
        var sink1 = "abc";

        sink1 += sink0;
        Check(sink1);

        // Assignment (concatenation), not tainted
        nonSink0 += "abc";
        Check(nonSink0);

        // Assignment (indexer), tainted
        var sink2 = new Dictionary <int, string[]>();

        sink2[0][1] = sink1;
        Check(sink2);

        // Assignment (indexer), not tainted
        var nonSink1 = new Dictionary <string, string>();

        nonSink1[""]    = nonSink0;
        nonSink1[sink1] = ""; // do not track tainted keys
        Check(nonSink1);

        // Concatenation, tainted
        var sink5 = sink1 + "ok";

        Check(sink5);

        // Concatenation, not tainted
        nonSink0 = nonSink0 + "test";
        Check(nonSink0);

        // Parenthesized expression, tainted
        var sink6 = (sink5);

        Check(sink6);

        // Parenthesized expression, not tainted
        nonSink0 = (nonSink0);
        Check(nonSink0);

        // Conditional expression, tainted
        var sink7 = 1 > 2 ? "a" : sink6;

        Check(sink7);

        // Conditional expression, not tainted
        nonSink0 = 4 == 2 ? "abc" : "def";
        Check(nonSink0);

        // Cast, tainted
        var sink8 = (object)sink7;

        Check(sink8);

        // Cast, not tainted
        var nonSink3 = (object)nonSink0;

        Check(nonSink3);

        // Cast, tainted
        var sink9 = sink8 as string;

        Check(sink9);

        // Cast, not tainted
        nonSink3 = nonSink0 as object;
        Check(nonSink3);

        // Array creation (initializer), tainted
        var sink10 = new object[] { sink9 };

        Check(sink10);

        // Array creation (initializer), not tainted
        var nonSink4 = new object[] { 42 };

        Check(nonSink4);

        // Object creation (collection initializer), tainted
        var sink11 = new Dictionary <string, string> {
            { "", sink9 }
        };

        Check(sink11);

        // Object creation (collection initializer), not tainted
        nonSink1 = new Dictionary <string, string> {
            { sink9, "" }
        };
        Check(nonSink1);

        // Data-preserving LINQ, tainted
        var sink14 = sink11.First(x => x.Value != null);

        Check(sink14);

        // Data-preserving LINQ, not tainted
        nonSink3 = nonSink1.First(x => x.Value != null);
        Check(nonSink1);

        // Standard method with a tainted argument, tainted
        var sink15 = Int32.Parse(sink9);

        Check(sink15);
        int nonSink2;
        var sink16 = Int32.TryParse(sink9, out nonSink2);

        Check(sink16);
        var sink17 = nonSink0.Replace(" ", sink9);

        Check(sink17);
        var sink18 = String.Format(nonSink0, sink9);

        Check(sink18);
        var sink19 = String.Format(sink18, nonSink0);

        Check(sink19);
        var sink45 = bool.Parse(sink9);

        Check(sink45);
        bool nonSink13;
        var  sink46 = bool.TryParse(sink9, out nonSink13);

        Check(sink46);
        var sink47 = Convert.ToByte(sink46);

        Check(sink47);
        var sink49 = String.Concat("", sink47);

        Check(sink49);
        var sink50 = String.Copy(sink49);

        Check(sink50);
        var sink51 = String.Join(", ", "", sink50, "");

        Check(sink51);
        var sink52 = "".Insert(0, sink51);

        Check(sink52);

        // Standard method with a non-tainted argument, not tainted
        nonSink2 = Int32.Parse(nonSink0);
        Check(nonSink2);
        var nonSink7 = Int32.TryParse(nonSink0, out nonSink2);

        Check(nonSink7);
        nonSink0 = nonSink0.Replace(" ", nonSink0);
        Check(nonSink0);
        nonSink0 = String.Format(nonSink0, nonSink0);
        Check(nonSink0);
        nonSink7 = bool.Parse(nonSink0);
        Check(nonSink7);
        nonSink7 = bool.TryParse(nonSink0, out nonSink13);
        Check(nonSink7);
        var nonSink14 = Convert.ToByte(nonSink7);

        Check(nonSink14);
        nonSink0 = String.Concat("", nonSink7);
        Check(nonSink0);
        nonSink0 = String.Copy(nonSink0);
        Check(nonSink0);
        nonSink0 = String.Join(", ", "", nonSink0, "");
        Check(nonSink0);
        nonSink0 = "".Insert(0, nonSink0);
        Check(nonSink0);

        // Comparison with constant, tainted
        var sink20 = sink15 > 42;

        Check(sink20);
        var sink21 = sink9.Equals("abc");

        Check(sink21);
        var sink22 = sink8.Equals((object)41);

        Check(sink22);

        // Comparison with non-constant, not tainted
        nonSink7 = sink0.Equals(sink1);
        Check(nonSink7);
        nonSink7 = sink8.Equals(nonSink3);
        Check(nonSink7);

        // Indexer access, tainted
        var sink23 = sink11[""];

        Check(sink23);

        // Indexer access, not tainted
        nonSink0 = nonSink1[""];
        Check(nonSink0);

        // Array access, tainted
        var sink24 = sink10[0];

        Check(sink24);

        // Array access, not tainted
        nonSink3 = nonSink4[0];
        Check(nonSink3);

        // Logical operation using tainted operand, tainted
        var sink25 = sink20 || false;

        Check(sink25);

        // Logical operation using non-tainted operands, not tainted
        nonSink7 = nonSink7 || false;
        Check(nonSink7);

        // Ad hoc tracking (System.Uri), tainted
        var sink26 = new System.Uri(sink23);

        Check(sink26);
        var sink27 = sink26.ToString();

        Check(sink27);
        var sink28 = sink26.PathAndQuery;

        Check(sink28);
        var sink29 = sink26.Query;

        Check(sink29);
        var sink30 = sink26.OriginalString;

        Check(sink30);

        // Ad hoc tracking (System.Uri), not tainted
        var nonSink8 = new System.Uri(nonSink0);

        Check(nonSink8);
        nonSink0 = nonSink8.ToString();
        Check(nonSink0);
        nonSink0 = nonSink8.PathAndQuery;
        Check(nonSink0);
        nonSink0 = nonSink8.Query;
        Check(nonSink0);
        nonSink0 = nonSink8.OriginalString;
        Check(nonSink0);

        // Ad hoc tracking (System.IO.StringReader), tainted
        var sink31 = new System.IO.StringReader(sink30);

        Check(sink31);
        var sink32 = sink31.ReadToEnd();

        Check(sink32);

        // Ad hoc tracking (System.IO.StringReader), not tainted
        var nonSink9 = new System.IO.StringReader(nonSink0);

        Check(nonSink9);
        nonSink0 = nonSink9.ReadToEnd();
        Check(nonSink0);

        // Ad hoc tracking (System.String), tainted
        var sink33 = (string)sink32.Substring(0).ToLowerInvariant().ToUpper().Trim(' ').Replace("a", "b").Insert(0, "").Clone();

        Check(sink33);
        var sink48 = sink33.Normalize().Remove(4, 5).Split(' ');

        Check(sink48);

        // Ad hoc tracking (System.String), not tainted
        nonSink0 = (string)nonSink0.Substring(0).ToLowerInvariant().ToUpper().Trim(' ').Replace("a", "b").Insert(0, "").Clone();
        Check(nonSink0);
        var nonSink15 = nonSink0.Normalize().Remove(4, 5).Split(' ');

        Check(nonSink15);

        // Ad hoc tracking (System.Text.StringBuilder), tainted
        var sink34 = new StringBuilder(sink33);

        Check(sink34);
        var sink35 = sink34.ToString();

        Check(sink35);
        var sink36 = new StringBuilder("");

        sink36.AppendLine(sink35);
        Check(sink36);

        // Ad hoc tracking (System.Text.StringBuilder), not tainted
        var nonSink10 = new StringBuilder(nonSink0);

        Check(nonSink10);
        nonSink0 = nonSink10.ToString();
        Check(nonSink0);
        nonSink10.AppendLine(nonSink0);
        Check(nonSink10);

        // Ad hoc tracking (System.Lazy), tainted
        var sink40 = new Lazy <string>(TaintedMethod);

        Check(sink40);
        var sink41 = sink40.Value;

        Check(sink41);
        var sink42 = new Lazy <string>(() => "taint source");

        Check(sink42);
        var sink43 = sink42.Value;

        Check(sink43);

        // Ad hoc tracking (System.Lazy), not tainted
        var nonSink12 = new Lazy <string>(NonTaintedMethod);

        Check(nonSink12);
        nonSink0 = nonSink12.Value;
        Check(nonSink0);
        nonSink12 = new Lazy <string>(() => "");
        Check(nonSink12);
        nonSink0 = nonSink12.Value;
        Check(nonSink0);

        // Ad hoc tracking (collections), tainted
        var sink3 = new Dictionary <int, string>();

        sink3.Add(0, sink1);
        Check(sink3);
        var sink12 = sink3.Values;

        Check(sink12);
        var sink13 = sink12.Reverse();

        Check(sink13);

        // Ad hoc tracking (collections), not tainted
        nonSink1.Add("", nonSink0);
        nonSink1.Add(sink1, ""); // do not track tainted keys
        Check(nonSink1);
        var nonSink5 = nonSink1.Values;

        Check(nonSink5);
        var nonSink6 = nonSink5.Reverse();

        Check(nonSink6);

        // Ad hoc tracking (data contracts), tainted
        var taintedDataContract = new DataContract();
        var sink53 = taintedDataContract.AString;

        Check(sink53);
        var sink54 = taintedDataContract.AList[0].AString;

        Check(sink54);

        // Ad hoc tracking (data contracts), not tainted
        var nonTaintedDataContract = new DataContract();

        nonSink0 = nonTaintedDataContract.AString;
        Check(nonSink0);
        nonSink2 = taintedDataContract.AnInt;
        Check(nonSink2);
        nonSink2 = taintedDataContract.AList[0].AnInt;
        Check(nonSink2);

        // Ad hoc tracking (TextBox), tainted
        TextBox taintedTextBox = null;
        var     sink60         = taintedTextBox.Text;

        Check(sink60);

        // Ad hoc tracking (HttpRequest), not tainted
        TextBox nonTaintedTextBox = null;

        nonSink0 = nonTaintedTextBox.Text;
        Check(nonSink0);

        // Iteration over a tracked expression, tainted
        foreach (var sink61 in sink10)
        {
            Check(sink61);
        }
        IEnumerator sink62 = sink10.GetEnumerator();

        Check(sink62);
        var sink63 = sink62.Current;

        Check(sink63);
        IEnumerator <KeyValuePair <int, string> > sink64 = sink3.GetEnumerator();

        Check(sink64);
        var sink65 = sink64.Current;

        Check(sink65);
        var sink66 = sink65.Value;

        Check(sink66);

        // Iteration over a tracked expression, not tainted
        foreach (var nonSink17 in nonSink4)
        {
            Check(nonSink17);
        }
        IEnumerator nonSink18 = nonSink4.GetEnumerator();

        Check(nonSink18);
        nonSink3 = nonSink18.Current;
        Check(nonSink3);
        IEnumerator <KeyValuePair <string, string> > nonSink19 = nonSink1.GetEnumerator();

        Check(nonSink19);
        var nonSink20 = nonSink19.Current;

        Check(nonSink20);
        nonSink0 = nonSink20.Value;
        Check(nonSink0);

        // async await, tainted
        var sink67 = Task.Run(() => "taint source");

        Check(sink67);
        var sink68 = await sink67;

        Check(sink68);

        // async await, not tainted
        var nonSink21 = Task.Run(() => "");

        Check(nonSink21);
        nonSink0 = await nonSink21;
        Check(nonSink0);

        // Interpolated string, tainted
        var sink69 = $"test {sink1}";

        Check(sink69);

        // Interpolated string, not tainted
        nonSink0 = $"test {nonSink0}";
        Check(nonSink0);

        // Assignment expression, exact
        var sink70 = sink0 = sink0;

        Check(sink70);

        // Assignment expression, not tainted
        nonSink0 = nonSink0 = nonSink0;
        Check(nonSink0);

        // `is` pattern, tainted
        if (sink70 is string sink71)
        {
            Check(sink71);
        }

        // `is` pattern, not tainted
        if (nonSink0 is string nonSink16)
        {
            Check(nonSink16);
        }

        // `switch` pattern, tainted
        switch (sink70)
        {
        case string sink72:
            Check(sink72);
            break;
        }

        // `switch` pattern, not tainted
        switch (nonSink0)
        {
        case string nonSink17:
            Check(nonSink17);
            break;
        }
    }
 private static void AddTypeInformation(IDictionary dictionary, DataContract contract)
 {
     dictionary[JsonGlobals.ServerTypeString] = GetTypeName(contract);
 }
 internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, DataContract dataContract)
 {
     return(false);
 }
        protected override bool WriteTypeInfo(XmlWriterDelegator writer, DataContract contract, DataContract declaredContract)
        {
            if (!((object.ReferenceEquals(contract.Name, declaredContract.Name) &&
                   object.ReferenceEquals(contract.Namespace, declaredContract.Namespace)) ||
                 (contract.Name.Value == declaredContract.Name.Value &&
                 contract.Namespace.Value == declaredContract.Namespace.Value)) &&
                 (contract.UnderlyingType != Globals.TypeOfObjectArray) && 
                 (_emitXsiType != EmitTypeInformation.Never))
            {
                // We always deserialize collections assigned to System.Object as object[]
                // Because of its common and JSON-specific nature, 
                //    we don't want to validate known type information for object[]

                // Don't validate known type information when emitXsiType == Never because
                // known types are not used without type information in the JSON

                if (RequiresJsonTypeInfo(contract))
                {
                    _perCallXsiTypeAlreadyEmitted = true;
                    WriteTypeInfo(writer, contract.Name.Value, contract.Namespace.Value);
                }
                else
                {
                    // check if the declared type is System.Enum and throw because
                    // __type information cannot be written for enums since it results in invalid JSON.
                    // Without __type, the resulting JSON cannot be deserialized since a number cannot be directly assigned to System.Enum.
                    if (declaredContract.UnderlyingType == typeof(Enum))
                    {
                        throw new SerializationException(SR.Format(SR.EnumTypeNotSupportedByDataContractJsonSerializer, declaredContract.UnderlyingType));
                    }
                }

                // Return true regardless of whether we actually wrote __type information
                // E.g. We don't write __type information for enums, but we still want verifyKnownType
                //      to be true for them.
                return true;
            }
            return false;
        }
示例#38
0
 internal JsonDataContractCriticalHelper(DataContract traditionalDataContract)
 {
     _traditionalDataContract = traditionalDataContract;
     AddCollectionItemContractsToKnownDataContracts();
     _typeName = string.IsNullOrEmpty(traditionalDataContract.Namespace.Value) ? traditionalDataContract.Name.Value : string.Concat(traditionalDataContract.Name.Value, JsonGlobals.NameValueSeparatorString, XmlObjectSerializerWriteContextComplexJson.TruncateDefaultDataContractNamespace(traditionalDataContract.Namespace.Value));
 }
        private static void WriteClassDataContractMembers(DataContractJsonSerializer serializer, ClassDataContract dataContract, ref Dictionary <string, object> classToDictionary, object value, XmlObjectSerializerWriteContextComplexJson context)
        {
            if (dataContract.BaseContract != null)
            {
                WriteClassDataContractMembers(serializer, dataContract.BaseContract, ref classToDictionary, value, context);
            }

            for (int i = 0; i < dataContract.Members.Count; i++)
            {
                DataMember member      = dataContract.Members[i];
                object     memberValue = GetMemberValue(value, dataContract.Members[i].MemberInfo, dataContract.UnderlyingType);
                string     memberName  = System.Xml.XmlConvert.DecodeName(member.Name);

                if (classToDictionary.ContainsKey(memberName))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.Format(SR.JsonDuplicateMemberNames,
                                                                                                                   DataContract.GetClrTypeFullName(dataContract.UnderlyingType), memberName)));
                }

                if (!member.EmitDefaultValue)
                {
                    //Dont emit value if its null or default(valuetype)
                    if (memberValue == null || (member.MemberTypeContract.IsValueType && object.Equals(memberValue, Activator.CreateInstance(member.MemberType))))
                    {
                        continue;
                    }
                }
                if (memberValue == null || IsTypePrimitive(member.MemberType))
                {
                    classToDictionary[memberName] = memberValue;
                }
                else
                {
                    Type memberValueType = memberValue.GetType();
                    if (member.MemberType == memberValueType ||
                        //Special case Nullable<DateTimeOffset> and Nullable<Struct>
                        (member.IsNullable && !EmitTypeInformation(member.MemberTypeContract, memberValueType)))
                    {
                        classToDictionary[memberName] = serializer.ConvertDataContractToObject(memberValue, member.MemberTypeContract, context, false, member.MemberTypeContract.UnderlyingType.TypeHandle);
                    }
                    else
                    {
                        //Push KnownTypes of this DataContract
                        context.PushKnownTypes(dataContract);
                        DataContract memberValueContract = DataContract.GetDataContract(memberValue.GetType());
                        if (member.MemberType.GetTypeInfo().IsInterface)
                        {
                            XmlObjectSerializerWriteContextComplexJson.VerifyObjectCompatibilityWithInterface(memberValueContract, memberValue, member.MemberType);
                        }
                        context.CheckIfTypeNeedsVerifcation(member.MemberTypeContract, memberValueContract);
                        classToDictionary[memberName] = serializer.ConvertDataContractToObject(memberValue, memberValueContract, context, true, member.MemberTypeContract.UnderlyingType.TypeHandle);
                        context.PopKnownTypes(dataContract);
                    }
                }
            }
        }
示例#40
0
        private DataContract ConvertMessage(MessageDescriptor messageDescriptor)
        {
            if (IsWellKnownType(messageDescriptor))
            {
                if (IsWrapperType(messageDescriptor))
                {
                    var field = messageDescriptor.Fields[Int32Value.ValueFieldNumber];

                    return(_innerContractResolver.GetDataContractForType(MessageDescriptorHelpers.ResolveFieldType(field)));
                }
                if (messageDescriptor.FullName == Timestamp.Descriptor.FullName ||
                    messageDescriptor.FullName == Duration.Descriptor.FullName ||
                    messageDescriptor.FullName == FieldMask.Descriptor.FullName)
                {
                    return(new DataContract(DataType.String, messageDescriptor.ClrType));
                }
                if (messageDescriptor.FullName == Struct.Descriptor.FullName)
                {
                    return(new DataContract(DataType.Object, messageDescriptor.ClrType, additionalPropertiesType: typeof(Value)));
                }
                if (messageDescriptor.FullName == ListValue.Descriptor.FullName)
                {
                    return(new DataContract(DataType.Array, messageDescriptor.ClrType, arrayItemType: typeof(Value)));
                }
                if (messageDescriptor.FullName == Value.Descriptor.FullName)
                {
                    return(new DataContract(DataType.Unknown, messageDescriptor.ClrType));
                }
                if (messageDescriptor.FullName == Any.Descriptor.FullName)
                {
                    var anyProperties = new List <DataProperty>
                    {
                        new DataProperty("@type", typeof(string), isRequired: true)
                    };
                    return(new DataContract(DataType.Object, messageDescriptor.ClrType, properties: anyProperties, additionalPropertiesType: typeof(Value)));
                }
            }

            var properties = new List <DataProperty>();

            foreach (var field in messageDescriptor.Fields.InFieldNumberOrder())
            {
                // Enum type will later be used to call this contract resolver.
                // Register the enum type so we know to resolve its names from the descriptor.
                if (field.FieldType == FieldType.Enum)
                {
                    _enumTypeMapping.TryAdd(field.EnumType.ClrType, field.EnumType);
                }

                Type fieldType;
                if (field.IsMap)
                {
                    var mapFields = field.MessageType.Fields.InFieldNumberOrder();
                    var valueType = MessageDescriptorHelpers.ResolveFieldType(mapFields[1]);
                    fieldType = typeof(IDictionary <,>).MakeGenericType(typeof(string), valueType);
                }
                else if (field.IsRepeated)
                {
                    fieldType = typeof(IList <>).MakeGenericType(MessageDescriptorHelpers.ResolveFieldType(field));
                }
                else
                {
                    fieldType = MessageDescriptorHelpers.ResolveFieldType(field);
                }

                properties.Add(new DataProperty(field.JsonName, fieldType));
            }

            var schema = new DataContract(DataType.Object, messageDescriptor.ClrType, properties: properties);

            return(schema);
        }
 private static bool RequiresJsonTypeInfo(DataContract contract)
 {
     return (contract is ClassDataContract);
 }
        public XmlObjectSerializerWriteContextComplexJson(DataContractJsonSerializer serializer, DataContract rootTypeDataContract)
            : base(null, int.MaxValue, new StreamingContext(), true)

        {
            _jsonSerializer              = serializer;
            this.rootTypeDataContract    = rootTypeDataContract;
            this.serializerKnownTypeList = serializer.knownTypeList;
        }
 private void HandleCollectionAssignedToObject(Type declaredType, ref DataContract dataContract, ref object obj, ref bool verifyKnownType)
 {
     if ((declaredType != dataContract.UnderlyingType) && (dataContract is CollectionDataContract))
     {
         if (verifyKnownType)
         {
             VerifyType(dataContract, declaredType);
             verifyKnownType = false;
         }
         if (((CollectionDataContract)dataContract).Kind == CollectionKind.Dictionary)
         {
             // Convert non-generic dictionary to generic dictionary
             IDictionary dictionaryObj = obj as IDictionary;
             Dictionary<object, object> genericDictionaryObj = new Dictionary<object, object>();
             foreach (DictionaryEntry entry in dictionaryObj)
             {
                 genericDictionaryObj.Add(entry.Key, entry.Value);
             }
             obj = genericDictionaryObj;
         }
         dataContract = GetDataContract(Globals.TypeOfIEnumerable);
     }
 }
 internal void CheckIfTypeNeedsVerifcation(DataContract declaredContract, DataContract runtimeContract)
 {
     if (WriteTypeInfo(null, runtimeContract, declaredContract))
     {
         VerifyType(runtimeContract);
     }
 }
示例#45
0
        private static void FindRefHandleCollectionDataContractMembers(object data, DataContract dataContract, ref Dictionary <DataContract, List <RefData> > alreadyRefdValues, ref Dictionary <DataContract, List <RefData> > nonRefdValues)
        {
            CollectionDataContract collectionContract = dataContract as CollectionDataContract;

            if (!collectionContract.IsDictionary)
            {
                foreach (object obj in (IEnumerable)data)
                {
                    if (obj != null)
                    {
                        FindAndAddRefd(obj, DataContract.GetDataContract(obj.GetType(), supportCollectionDataContract), ref alreadyRefdValues, ref nonRefdValues);
                    }
                }
            }
            else
            {
                IDictionary dictionary = data as IDictionary;
                if (dictionary != null)
                {
                    foreach (object key in dictionary.Keys)
                    {
                        if (key != null)
                        {
                            FindAndAddRefd(key, DataContract.GetDataContract(key.GetType(), supportCollectionDataContract), ref alreadyRefdValues, ref nonRefdValues);
                        }
                    }
                    foreach (object value in dictionary.Values)
                    {
                        if (value != null)
                        {
                            FindAndAddRefd(value, DataContract.GetDataContract(value.GetType(), supportCollectionDataContract), ref alreadyRefdValues, ref nonRefdValues);
                        }
                    }
                }
                else
                {
                    if (collectionContract.GetEnumeratorMethod != null)
                    {
                        object dictEnumObj = null;
                        try
                        {
                            dictEnumObj = collectionContract.GetEnumeratorMethod.Invoke(data, new object[] { });
                        }
                        catch (Exception) { }
                        IDictionaryEnumerator dictEnum = dictEnumObj as IDictionaryEnumerator;
                        if (dictEnum != null)
                        {
                            while (dictEnum.MoveNext())
                            {
                                FindAndAddRefd(dictEnum.Key, DataContract.GetDataContract(dictEnum.Key.GetType(), supportCollectionDataContract), ref alreadyRefdValues, ref nonRefdValues);
                            }
                            dictEnum.Reset();
                            while (dictEnum.MoveNext())
                            {
                                if (dictEnum.Value != null)
                                {
                                    FindAndAddRefd(dictEnum.Value, DataContract.GetDataContract(dictEnum.Value.GetType(), supportCollectionDataContract), ref alreadyRefdValues, ref nonRefdValues);
                                }
                            }
                        }
                    }
                    else
                    {
                        throw new Exception("TestDriver Exception: Dictionary CollectionDataCotnract Type Not Supported");
                    }
                }
            }
        }
 internal static DataContract GetRevisedItemContract(DataContract oldItemContract)
 {
     if ((oldItemContract != null) &&
         oldItemContract.UnderlyingType.GetTypeInfo().IsGenericType &&
         (oldItemContract.UnderlyingType.GetGenericTypeDefinition() == Globals.TypeOfKeyValue))
     {
         return ClassDataContract.CreateClassDataContractForKeyValue(oldItemContract.UnderlyingType, oldItemContract.Namespace, new string[] { JsonGlobals.KeyString, JsonGlobals.ValueString });
     }
     return oldItemContract;
 }
        internal static void VerifyObjectCompatibilityWithInterface(DataContract contract, object graph, Type declaredType)
        {
            Type contractType = contract.GetType();
            if ((contractType == typeof(XmlDataContract)) && !Globals.TypeOfIXmlSerializable.IsAssignableFrom(declaredType))
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.XmlObjectAssignedToIncompatibleInterface, graph.GetType(), declaredType)));
            }

            if ((contractType == typeof(CollectionDataContract)) && !CollectionDataContract.IsCollectionInterface(declaredType))
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CollectionAssignedToIncompatibleInterface, graph.GetType(), declaredType)));
            }
        }
 internal static XmlObjectSerializerWriteContextComplexJson CreateContext(DataContractJsonSerializerImpl serializer, DataContract rootTypeDataContract)
 {
     return(new XmlObjectSerializerWriteContextComplexJson(serializer, rootTypeDataContract));
 }
        internal void VerifyType(DataContract dataContract)
        {
            bool knownTypesAddedInCurrentScope = false;
            if (dataContract.KnownDataContracts != null)
            {
                scopedKnownTypes.Push(dataContract.KnownDataContracts);
                knownTypesAddedInCurrentScope = true;
            }

            DataContract knownContract = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null /*memberTypeContract*/);
            if (knownContract == null || knownContract.UnderlyingType != dataContract.UnderlyingType)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DcTypeNotFoundOnSerialize, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace)));
            }

            if (knownTypesAddedInCurrentScope)
            {
                scopedKnownTypes.Pop();
            }
        }
 private static bool RequiresJsonTypeInfo(DataContract contract)
 {
     return(contract is ClassDataContract);
 }
 internal static XmlObjectSerializerWriteContextComplexJson CreateContext(DataContractJsonSerializerImpl serializer, DataContract rootTypeDataContract)
 {
     return new XmlObjectSerializerWriteContextComplexJson(serializer, rootTypeDataContract);
 }
        protected override bool WriteTypeInfo(XmlWriterDelegator writer, DataContract contract, DataContract declaredContract)
        {
            if (!((object.ReferenceEquals(contract.Name, declaredContract.Name) &&
                   object.ReferenceEquals(contract.Namespace, declaredContract.Namespace)) ||
                  (contract.Name.Value == declaredContract.Name.Value &&
                   contract.Namespace.Value == declaredContract.Namespace.Value)) &&
                (contract.UnderlyingType != Globals.TypeOfObjectArray) &&
                (_emitXsiType != EmitTypeInformation.Never))
            {
                // We always deserialize collections assigned to System.Object as object[]
                // Because of its common and JSON-specific nature,
                //    we don't want to validate known type information for object[]

                // Don't validate known type information when emitXsiType == Never because
                // known types are not used without type information in the JSON

                if (RequiresJsonTypeInfo(contract))
                {
                    _perCallXsiTypeAlreadyEmitted = true;
                    WriteTypeInfo(writer, contract.Name.Value, contract.Namespace.Value);
                }
                else
                {
                    // check if the declared type is System.Enum and throw because
                    // __type information cannot be written for enums since it results in invalid JSON.
                    // Without __type, the resulting JSON cannot be deserialized since a number cannot be directly assigned to System.Enum.
                    if (declaredContract.UnderlyingType == typeof(Enum))
                    {
                        throw new SerializationException(SR.Format(SR.EnumTypeNotSupportedByDataContractJsonSerializer, declaredContract.UnderlyingType));
                    }
                }

                // Return true regardless of whether we actually wrote __type information
                // E.g. We don't write __type information for enums, but we still want verifyKnownType
                //      to be true for them.
                return(true);
            }
            return(false);
        }
 internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, DataContract dataContract)
 {
     return false;
 }
示例#54
0
        public void GenerateAnswersTest()
        {
            var input = new DataContract();

            input.AddRomanSymbolsValues("itt", "I");
            input.AddRomanSymbolsValues("vtt", "V");
            input.AddRomanSymbolsValues("xtt", "X");
            input.AddRomanSymbolsValues("ltt", "L");
            input.AddRomanSymbolsValues("ctt", "C");
            input.AddRomanSymbolsValues("dtt", "D");
            input.AddRomanSymbolsValues("mtt", "M");
            input.AddMetalValues("Metal", 10.0F);
            input.AddMetalValues("TestMetal", 10.0F);
            input.AddMetalValues("AnotherTestMetal", 20.0F);

            var question1 = new Question
            {
                PuzzlePart = "mtt mtt mtt ctt mtt dtt dtt dtt ctt dtt ctt ctt ctt xtt ctt ltt ltt ltt xtt ltt xtt xtt xtt itt xtt vtt vtt vtt itt vtt itt itt itt",
                Type       = QuestionType.RomanToCredit
            };

            var question2 = new Question
            {
                PuzzlePart = "xtt ltt vtt itt Metal",
                Type       = QuestionType.RomanMetalToCredit
            };

            var question3 = new Question
            {
                PuzzlePart = "ctt ctt ctt xtt ctt xtt ltt TestMetal",
                Type       = QuestionType.RomanMetalToCredit
            };

            var question4 = new Question
            {
                PuzzlePart = "AnotherTestMetal",
                Type       = QuestionType.RomanMetalToCredit
            };

            input.AddQuestion(question1);
            input.AddQuestion(question2);
            input.AddQuestion(question3);
            input.AddQuestion(question4);

            var expected = new List <string>
            {
                "mtt mtt mtt ctt mtt dtt dtt dtt ctt dtt ctt ctt ctt xtt ctt ltt ltt ltt xtt ltt xtt xtt xtt itt xtt vtt vtt vtt itt vtt itt itt itt is 6441",
                "xtt ltt vtt itt Metal is 460 Credits",
                "ctt ctt ctt xtt ctt xtt ltt TestMetal is 4300 Credits",
                "AnotherTestMetal is 20 Credits"
            };

            var actual = _answerGenerator.GenerateAnswers(input);

            Assert.IsNotNull(actual);
            Assert.AreEqual(expected.Count, actual.Count);

            foreach (var ans in expected)
            {
                Assert.IsTrue(actual.Contains(ans));
            }
        }
 internal DataMember(DataContract memberTypeContract, string name, bool isNullable, bool isRequired, bool emitDefaultValue, int order)
 {
     helper = new CriticalHelper(memberTypeContract, name, isNullable, isRequired, emitDefaultValue, order);
 }
        private void VerifyType(DataContract dataContract, Type declaredType)
        {
            bool knownTypesAddedInCurrentScope = false;

            if (dataContract.KnownDataContracts != null)
            {
                scopedKnownTypes.Push(dataContract.KnownDataContracts);
                knownTypesAddedInCurrentScope = true;
            }

            if (!IsKnownType(dataContract, declaredType))
            {
                throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DcTypeNotFoundOnSerialize, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace));
            }

            if (knownTypesAddedInCurrentScope)
            {
                scopedKnownTypes.Pop();
            }
        }