public DataCollection Serialize (object obj, ITypeSerializer handler)
		{
			DataCollection data = handler.Serialize (obj);
			ProjectFile file = (ProjectFile) obj;
			
			//if the file is marked to copy to output, the deploy settings are useless, so strip them out and return
			if (file.CopyToOutputDirectory != FileCopyMode.None) {
				foreach (string key in keys) {
					data.Extract (key);
				}
				return data;
			}
			
			//if the file was FileCopyMode.None and is BuildAction.Content and is marked to deploy, then we can 
			//map it back to a FileCopy build action
			if (file.BuildAction == BuildAction.Content) {
				object val = file.ExtendedProperties ["DeployService.Deploy"];
				if (val != null && (bool) val) {
					data.Extract ("buildaction");
					data.Add (new DataValue ("buildaction", "FileCopy"));
				}
			}
			
			return data;
		}
        internal static Dictionary<string, TypeAccessor> GetTypeAccessorMap(TypeConfig typeConfig, ITypeSerializer serializer)
        {
            var type = typeConfig.Type;

            var propertyInfos = type.GetSerializableProperties();
            if (propertyInfos.Length == 0) return null;

            var map = new Dictionary<string, TypeAccessor>(StringComparer.OrdinalIgnoreCase);

            var isDataContract = type.IsDto();
            foreach (var propertyInfo in propertyInfos)
            {
                var propertyName = propertyInfo.Name;
                if (isDataContract)
                {
                    var dcsDataMember = propertyInfo.GetDataMember();
                    if (dcsDataMember != null && dcsDataMember.Name != null)
                    {
                        propertyName = dcsDataMember.Name;
                    }
                }
                map[propertyName] = TypeAccessor.Create(serializer, typeConfig, propertyInfo);
            }
            return map;
        }
        public void SetUp()
        {
            var rootTypes = typeof(U8Packet).Assembly.GetTypes().Where(t => PacketAttribute.IsCompatible(t)).ToArray();

            ITypeSerializer[] customSerializers = new ITypeSerializer[0];

            Serializer.Initialize(rootTypes, customSerializers);
        }
		public virtual DataCollection Serialize (object obj, ITypeSerializer handler)
		{
			if (obj is ProjectFile) {
				ProjectFile pf = (ProjectFile) obj;
				DataCollection data = handler.Serialize (obj);
				
				//Map the Content build action to the old FileCopy action if CopyToOutputDirectory is set
				if (pf.BuildAction == BuildAction.Content && pf.CopyToOutputDirectory != FileCopyMode.None) {
					DataValue value = data ["buildaction"] as DataValue;
					if (value != null) {
						data.Remove (value);
						data.Add (new DataValue ("buildaction", "FileCopy"));
						data.Extract ("copyToOutputDirectory");
					}
				}
				// Don't store the resource id if it matches the default.
				if (pf.BuildAction == BuildAction.EmbeddedResource && pf.ResourceId != Path.GetFileName (pf.FilePath))
					data.Add (new DataValue ("resource_id", pf.ResourceId));
				return data;
			}
			else if (obj is SolutionEntityItem) {
				DotNetProject project = obj as DotNetProject;
				if (project != null) {
					foreach (DotNetProjectConfiguration config in project.Configurations)
						config.ExtendedProperties ["Build/target"] = project.CompileTarget.ToString ();
				}
				DataCollection data = handler.Serialize (obj);
				SolutionEntityItem item = (SolutionEntityItem) obj;
				if (item.DefaultConfiguration != null) {
					DataItem confItem = data ["Configurations"] as DataItem;
					if (confItem != null) {
						confItem.UniqueNames = true;
						if (item.ParentSolution != null)
							confItem.ItemData.Add (new DataValue ("active", item.ParentSolution.DefaultConfigurationId));
					}
				}
				if (project != null) {
					data.Extract ("targetFramework");
					data.Add (new DataValue ("targetFramework", project.TargetFramework.Id.ToLegacyIdString ()));
				}
				WriteItems (handler, (SolutionEntityItem) obj, data);
				return data;
			}
			else if (obj is ProjectReference) {
				ProjectReference pref = (ProjectReference) obj;
				DataCollection data = handler.Serialize (obj);
				string refto = pref.Reference;
				if (pref.ReferenceType == ReferenceType.Assembly) {
					string basePath = Path.GetDirectoryName (handler.SerializationContext.BaseFile);
					refto = FileService.AbsoluteToRelativePath (basePath, refto);
				} else if (pref.ReferenceType == ReferenceType.Gac && pref.LoadedReference != null)
					refto = pref.LoadedReference;
	
				data.Add (new DataValue ("refto", refto));
				return data;
			}
			return handler.Serialize (obj);
		}
        public void SetUp()
        {
            List<System.Type> rootTypes = new List<System.Type>();
            rootTypes.Add(typeof(ParticipantBuiltinTopicData));

            ITypeSerializer[] customSerializers = new ITypeSerializer[0];
            
            Serializer.Initialize(rootTypes, customSerializers);
        }
		public DataCollection Serialize (ITypeSerializer handler)
		{
			DataCollection col = handler.Serialize (this);
			if (solutionConfiguration != null) {
				DataItem it = (DataItem) handler.SerializationContext.Serializer.Serialize (solutionConfiguration);
				col.Merge (it.ItemData);
			}
			return col;
		}
 public CouchbaseConfigContext(IBucketConfig bucketConfig, ClientConfiguration clientConfig,
     Func<IConnectionPool, IOStrategy> ioStrategyFactory,
     Func<PoolConfiguration, IPEndPoint, IConnectionPool> connectionPoolFactory,
     Func<string, string, IOStrategy, IByteConverter, ISaslMechanism> saslFactory,
     IByteConverter converter,
     ITypeSerializer serializer) 
     : base(bucketConfig, clientConfig, ioStrategyFactory, connectionPoolFactory, saslFactory, converter, serializer)
 {
 }
 public CarrierPublicationProvider(ClientConfiguration clientConfig,
     Func<IConnectionPool, IOStrategy> ioStrategyFactory,
     Func<PoolConfiguration, IPEndPoint, IConnectionPool> connectionPoolFactory,
     Func<string, string, IOStrategy, IByteConverter, ISaslMechanism> saslFactory, 
     IByteConverter converter,
     ITypeSerializer serializer) 
     : base(clientConfig, ioStrategyFactory, connectionPoolFactory, saslFactory, converter, serializer)
 {
 }
Exemple #9
0
		DataCollection ICustomDataItem.Serialize (ITypeSerializer handler)
		{
			if (policies == null)
				return null;
			
			DataCollection dc = new DataCollection ();
			foreach (KeyValuePair<PolicyKey,object> p in policies)
				dc.Add (PolicyService.DiffSerialize (p.Key.PolicyType, p.Value, p.Key.Scope));
			return dc;
		}
 public N1QlQueryModelVisitor(IMemberNameResolver memberNameResolver, IMethodCallTranslatorProvider methodCallTranslatorProvider,
     ITypeSerializer serializer)
 {
     _queryGenerationContext = new N1QlQueryGenerationContext()
     {
         //MemberNameResolver = new JsonNetMemberNameResolver(ClusterHelper.Get().Configuration.SerializationSettings.ContractResolver),
         //MethodCallTranslatorProvider = new DefaultMethodCallTranslatorProvider()
         MemberNameResolver = memberNameResolver,
         MethodCallTranslatorProvider = methodCallTranslatorProvider,
         Serializer = serializer
     };
 }
 protected ConfigProviderBase(ClientConfiguration clientConfig,
     Func<IConnectionPool, IOStrategy> ioStrategyFactory,
     Func<PoolConfiguration, IPEndPoint, IConnectionPool> connectionPoolFactory,
     Func<string, string, IOStrategy, IByteConverter, ISaslMechanism> saslFactory, 
     IByteConverter converter,
     ITypeSerializer serializer)
 {
     _clientConfig = clientConfig;
     _ioStrategyFactory = ioStrategyFactory;
     _connectionPoolFactory = connectionPoolFactory;
     _saslFactory = saslFactory;
     Converter = converter;
     Serializer = serializer;
 }
		void ICustomDataItem.Deserialize (ITypeSerializer handler, DataCollection data)
		{
			handler.Deserialize (this, data);
			if (data["Url"] == null) {
				string dir = ((DataValue)data ["Dir"]).Value;
				string user = ((DataValue)data ["User"]).Value;
				string server = ((DataValue)data ["Server"]).Value;
				string method = ((DataValue)data ["Method"]).Value;
				int port = int.Parse (((DataValue)data ["Port"]).Value);
				UriBuilder ub = new UriBuilder (method, server, port, dir);
				url = ub.ToString ();
			}
			CreateUri ();
		}
 public N1QlQueryModelVisitor(IMemberNameResolver memberNameResolver, IMethodCallTranslatorProvider methodCallTranslatorProvider,
     ITypeSerializer serializer, ILoggerFactory loggerFactory)
 {
     _loggerFactory = loggerFactory;
     Log = _loggerFactory.CreateLogger<N1QlQueryModelVisitor>();
     _queryPartsAggregator = new QueryPartsAggregator(_loggerFactory);
     _queryGenerationContext = new N1QlQueryGenerationContext()
     {
         //MemberNameResolver = new JsonNetMemberNameResolver(ClusterHelper.Get().Configuration.SerializationSettings.ContractResolver),
         //MethodCallTranslatorProvider = new DefaultMethodCallTranslatorProvider()
         MemberNameResolver = memberNameResolver,
         MethodCallTranslatorProvider = methodCallTranslatorProvider,
         Serializer = serializer
     };
 }
 protected ConfigContextBase(IBucketConfig bucketConfig, ClientConfiguration clientConfig,
     Func<IConnectionPool, IOStrategy> ioStrategyFactory,
     Func<PoolConfiguration, IPEndPoint, IConnectionPool> connectionPoolFactory,
     Func<string, string, IOStrategy, IByteConverter, ISaslMechanism> saslFactory,
     IByteConverter converter,
     ITypeSerializer serializer)
 {
     _bucketConfig = bucketConfig;
     _clientConfig = clientConfig;
     IOStrategyFactory = ioStrategyFactory;
     ConnectionPoolFactory = connectionPoolFactory;
     _creationTime = DateTime.Now;
     SaslFactory = saslFactory;
     Converter = converter;
     Serializer = serializer;
 }
		public PropertyMap( Type type, ITypeSerializer serializer )
		{
			if (!type.IsClass)
			{
				throw new ArgumentException(@"Cannot construct a property map for a type that isn't a class.");
			}
				
			var propertyInfos = type.GetProperties();

			_setterMap = new Dictionary<string, SetPropertyDelegate>();
			_map = new Dictionary<string, ParseStringDelegate>();

			foreach (var propertyInfo in propertyInfos)
			{
				_map[propertyInfo.Name] = serializer.GetParseFn(propertyInfo.PropertyType);
				_setterMap[propertyInfo.Name] = ParseUtils.GetSetPropertyMethod(type, propertyInfo);
			}
		}
		public DataCollection Serialize (object obj, ITypeSerializer handler)
		{
			PackageBuilder pb = (PackageBuilder) obj;
			List<string> items = new List<string> ();
			foreach (SolutionItem sitem in pb.GetChildEntries ()) {
				string file = MD1ProjectService.GetItemFileName (sitem);
				if (file != null)
					items.Add (file);
				else if (handler.SerializationContext.ProgressMonitor != null)
					handler.SerializationContext.ProgressMonitor.ReportWarning ("Can't save reference to item '" + sitem.Name + "'");
			}
			string rootFile = MD1ProjectService.GetItemFileName (pb.RootSolutionItem);
			if (rootFile == null && handler.SerializationContext.ProgressMonitor != null)
				handler.SerializationContext.ProgressMonitor.ReportWarning ("Can't save reference to item '" + pb.RootSolutionItem.Name + "'");
			
			pb.SetSolutionItemMd1 (rootFile, items.ToArray ());
			return handler.Serialize (obj);
		}
Exemple #17
0
		/// <summary>
		/// Initialize NetSerializer
		/// </summary>
		/// <param name="rootTypes">Types to be (de)serialized</param>
		/// <param name="userTypeSerializers">Array of custom serializers</param>
		public Serializer(IEnumerable<Type> rootTypes, ITypeSerializer[] userTypeSerializers)
		{
			if (userTypeSerializers.All(s => s is IDynamicTypeSerializer || s is IStaticTypeSerializer) == false)
				throw new ArgumentException("TypeSerializers have to implement IDynamicTypeSerializer or  IStaticTypeSerializer");

			m_userTypeSerializers = userTypeSerializers;

			var typeDataMap = GenerateTypeData(rootTypes);

			GenerateDynamic(typeDataMap);

			m_typeIDMap = typeDataMap.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.TypeID);

#if GENERATE_DEBUGGING_ASSEMBLY
			// Note: GenerateDebugAssembly overwrites some fields from typeDataMap
			GenerateDebugAssembly(typeDataMap);
#endif
		}
Exemple #18
0
		void ICustomDataItem.Deserialize (ITypeSerializer handler, DataCollection data)
		{
			if (data.Count == 0)
				return;
			
			policies = new PolicyDictionary ();
			foreach (DataNode node in data) {
				try {
					if (!(node is DataItem))
						continue;
					ScopedPolicy val = PolicyService.DiffDeserialize ((DataItem)node);
					policies.Add (val);
				} catch (Exception ex) {
					if (handler.SerializationContext.ProgressMonitor != null)
						handler.SerializationContext.ProgressMonitor.ReportError (ex.Message, ex);
					else
						LoggingService.LogError (ex.Message, ex);
				}
			}
		}
		public override DataCollection Serialize (object obj, ITypeSerializer handler)
		{
			//serialise as normal
			DataCollection data = base.Serialize (obj, handler);
			
			AspNetAppProject proj = obj as AspNetAppProject;
			if (proj == null)
				return data;
			
			//for the old format we need to make sure each Content file that's a web type and is NOT set
			//to copy actually gets changed to the FileCopy build target
			DataItem files = data ["Contents"] as DataItem;
			if (files == null || !files.HasItemData)
				return data;
			
			foreach (object f in files.ItemData) {
				DataItem file = f as DataItem;
				if (file == null || !file.HasItemData)// || file.Name != "File")
					continue;
				
				DataValue ctod = file ["copyToOutputDirectory"] as DataValue;
				if (ctod != null && ctod.Value == "Never")
				{
					DataValue action = file ["buildaction"] as DataValue;
					DataValue name = file ["name"] as DataValue;
					if (action != null && name != null && action.Value == "Content")
					{
						WebSubtype type = AspNetAppProject.DetermineWebSubtype (name.Value);
						if (type != WebSubtype.None && type != WebSubtype.Code) {
							file.Extract ("copyToOutputDirectory");
							int index = file.ItemData.IndexOf (action);
							file.ItemData.Remove (action);
							file.ItemData.Insert (index, new DataValue ("buildaction", "FileCopy"));
						}
					}
				}
			}
			
			return data;
		}
Exemple #20
0
		/// <summary>
		/// Initialize NetSerializer
		/// </summary>
		/// <param name="rootTypes">Types to be (de)serialized</param>
		/// <param name="userTypeSerializers">Array of custom serializers</param>
		public static void Initialize(Type[] rootTypes, ITypeSerializer[] userTypeSerializers)
		{
			if (s_initialized)
				throw new InvalidOperationException("NetSerializer already initialized");

			if (userTypeSerializers.All(s => s is IDynamicTypeSerializer || s is IStaticTypeSerializer) == false)
				throw new ArgumentException("TypeSerializers have to implement IDynamicTypeSerializer or  IStaticTypeSerializer");

			s_userTypeSerializers = userTypeSerializers;

			var typeDataMap = GenerateTypeData(rootTypes);

			GenerateDynamic(typeDataMap);

			s_typeIDMap = typeDataMap.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.TypeID);

#if GENERATE_DEBUGGING_ASSEMBLY
			// Note: GenerateDebugAssembly overwrites some fields from typeDataMap
			GenerateDebugAssembly(typeDataMap);
#endif
			s_initialized = true;
		}
Exemple #21
0
        void GenerateDebugStubs(Type type, TypeBuilder tb)
        {
            var data = m_runtimeTypeMap[type];

            ITypeSerializer serializer = data.TypeSerializer;

            MethodInfo writer;
            MethodInfo reader;
            bool       writerNeedsInstance, readerNeedsInstance;

            if (serializer is IStaticTypeSerializer)
            {
                var sts = (IStaticTypeSerializer)serializer;

                writer = sts.GetStaticWriter(type);
                reader = sts.GetStaticReader(type);

                writerNeedsInstance = writer.GetParameters().Length == 3;
                readerNeedsInstance = reader.GetParameters().Length == 3;
            }
            else if (serializer is IDynamicTypeSerializer)
            {
                writer = Helpers.GenerateStaticSerializerStub(tb, type);
                reader = Helpers.GenerateStaticDeserializerStub(tb, type);

                writerNeedsInstance = readerNeedsInstance = true;
            }
            else
            {
                throw new Exception();
            }

            data.WriterMethodInfo         = writer;
            data.WriterNeedsInstanceDebug = writerNeedsInstance;

            data.ReaderMethodInfo         = reader;
            data.ReaderNeedsInstanceDebug = readerNeedsInstance;
        }
Exemple #22
0
        public void Deserialize(ITypeSerializer handler, DataCollection data)
        {
            DataItem item = new DataItem();

            item.Name = "SolutionConfiguration";
            DataCollection col = item.ItemData;

            foreach (DataNode val in data)
            {
                if (val.Name != "name" && val.Name != "ctype" && val.Name != "Entry")
                {
                    col.Add(val);
                }
            }

            handler.Deserialize(this, data);

            if (data.Count > 0)
            {
                solutionConfiguration = new SolutionConfiguration(name);
                handler.SerializationContext.Serializer.Deserialize(solutionConfiguration, item);
            }
        }
Exemple #23
0
        public static void WriteValue(XmlWriter writer, Object value, IXmlRpcStreamConfig config, ITypeSerializerFactory typeSerializerFactory, IList nestedObjs)
        {
            if (nestedObjs.Contains(value))
            {
                return;
            }
            nestedObjs.Add(value);
            ITypeSerializer serializer = typeSerializerFactory.GetSerializer(config, value);

            if (serializer == null)
            {
                throw new XmlRpcException("Unsupported type: " + value.GetType().Name);
            }
            if (serializer is RecursiveTypeSerializer)
            {
                ((RecursiveTypeSerializer)serializer).DoWrite(writer, value, config, typeSerializerFactory, nestedObjs);
            }
            else
            {
                serializer.Write(writer, value, config, typeSerializerFactory);
            }
            nestedObjs.RemoveAt(nestedObjs.Count - 1);
        }
		public override void Deserialize (object obj, ITypeSerializer handler, DataCollection data)
		{
			//deserialise as normal
			base.Deserialize (obj, handler, data);
			
			AspNetAppProject proj = obj as AspNetAppProject;
			if (proj == null)
				return;
			
			//find files that are web content and have been deserialised from the obsolete "FileCopy" BuildAction
			foreach (MonoDevelop.Projects.ProjectFile pf in proj.Files) {
				if (pf.BuildAction != MonoDevelop.Projects.BuildAction.Content
				    || pf.CopyToOutputDirectory != MonoDevelop.Projects.FileCopyMode.Always)
					continue;
				
				WebSubtype type = proj.DetermineWebSubtype (pf);
				if (type != WebSubtype.None && type != WebSubtype.Code) {
					//and mark them to not copy, since we don't actually want this; 
					// the obsolete behaviour was a hack
					pf.CopyToOutputDirectory = MonoDevelop.Projects.FileCopyMode.None;
				}
			}
		}
Exemple #25
0
        void ICustomDataItem.Deserialize(ITypeSerializer handler, DataCollection data)
        {
            if (data.Count == 0)
            {
                return;
            }

            var propertiesBuilder = ImmutableDictionary.CreateBuilder <string, object> ();

            context    = handler.SerializationContext.Serializer.DataContext;
            sourceFile = handler.SerializationContext.BaseFile;
            foreach (DataNode nod in data)
            {
                if (nod.Name != "ctype")
                {
                    propertiesBuilder.Add(UnescapeName(nod.Name), new DataNodeInfo {
                        DataNode = nod
                    });
                }
            }

            properties = propertiesBuilder.ToImmutable();
        }
Exemple #26
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="index"></param>
        /// <param name="value"></param>
        public void WriteValue <T>(int index, T value)
        {
            ITypeSerializer <T> serializer = InternalTypeCache <T> .Serializer;

            if (serializer is IBuiltinTypeSerializer)
            {
                Index = index;
                serializer.Serialize(value, ref this);
            }
            else
            {
                int          memSize = InternalTypeCache <T> .ApproximateMemorySize;
                NativeMemory mem     = NativeMemory.Allocate(ref memSize);
                AccelWriter  writer  = new AccelWriter(&mem, m_Encoding, m_IsLittleEndian);

                try
                {
                    serializer.Serialize(value, ref writer);

                    int        byteCount = writer.m_ByteCount;
                    ObjectType type      = GetObjectTypeByLength(byteCount);

                    WriteTag(index, type);

                    if (type == ObjectType.LengthPrefixed)
                    {
                        WriteUInt32Variant((uint)byteCount);
                    }

                    WriteBytes(writer.m_Memory->GetPointer(), byteCount);
                }
                finally
                {
                    mem.Dispose();
                }
            }
        }
Exemple #27
0
        /// <summary>
        ///
        /// </summary>
        /// <exception cref="System.Xml.XmlException"></exception>
        public static Object ReadValue(XmlReader reader, IXmlRpcStreamConfig config, ITypeSerializerFactory typeFactory)
        {
            CheckTag(reader, XmlRpcSpec.VALUE_TAG);

            Object value = null;

            do
            {
                reader.Read();
                if (reader.NodeType == XmlNodeType.Element)
                {
                    if (reader.IsEmptyElement)
                    {
                        continue;
                    }
                    ITypeSerializer parser = typeFactory.GetSerializer(config, reader.NamespaceURI, reader.LocalName);
                    if (parser == null)
                    {
                        throw new XmlException("Unknown type: " + new XmlQualifiedName(reader.LocalName, reader.NamespaceURI));
                    }
                    else
                    {
                        value = parser.Read(reader, config, typeFactory);
                    }
                }
                else if (reader.NodeType == XmlNodeType.Text)
                {
                    ITypeSerializer parser = typeFactory.GetSerializer(config, reader.NamespaceURI, String.Empty);
                    if (parser != null)
                    {
                        value = parser.Read(reader, config, typeFactory);
                    }
                }
            } while (reader.NodeType != XmlNodeType.EndElement || !XmlRpcSpec.VALUE_TAG.Equals(reader.LocalName));

            return(value);
        }
        public static Type ExtractType(ITypeSerializer Serializer, StringSegment strType)
        {
            if (!strType.HasValue || strType.Length <= 1)
            {
                return(null);
            }

            var hasWhitespace = Json.JsonUtils.WhiteSpaceChars.Contains(strType.GetChar(1));

            if (hasWhitespace)
            {
                var pos = strType.IndexOf('"');
                if (pos >= 0)
                {
                    strType = new StringSegment($"{{{strType.Substring(pos)}");
                }
            }

            var typeAttrInObject = Serializer.TypeAttrInObject;

            if (strType.Length > typeAttrInObject.Length &&
                strType.Substring(0, typeAttrInObject.Length) == typeAttrInObject)
            {
                var propIndex = typeAttrInObject.Length;
                var typeName  = Serializer.EatValue(strType, ref propIndex).Value;
                var type      = JsConfig.TypeFinder(typeName);

                if (type == null)
                {
                    Tracer.Instance.WriteWarning($"Could not find type: {typeName}");
                }

                return(type);
            }

            return(null);
        }
Exemple #29
0
        // if MtouchDebug element is not present, this handler migrates args
        // and sets default values for the new Mtouch* properties
        public void Deserialize(ITypeSerializer handler, DataCollection data)
        {
            var argsToMigrate   = data.Extract("ExtraMtouchArgs") as DataValue;
            var mtouchDebugData = data.Extract("MtouchDebug") as DataValue;

            handler.Deserialize(this, data);

            if (mtouchDebugData == null || string.IsNullOrEmpty(mtouchDebugData.Value))
            {
                if (Name == "Debug")
                {
                    MtouchDebug = true;
                    if (IsSimPlatform)
                    {
                        MtouchLink = MtouchLinkMode.None;
                    }
                }
                if (argsToMigrate != null && string.IsNullOrEmpty(argsToMigrate.Value))
                {
                    if (argsToMigrate.Value.Contains("-debug"))
                    {
                        MtouchDebug = true;
                    }
                    if (argsToMigrate.Value.Contains("-nolink"))
                    {
                        MtouchLink = MtouchLinkMode.None;
                    }
                    MtouchExtraArgs = new StringBuilder(argsToMigrate.Value)
                                      .Replace("-nolink", "").Replace("-linksdkonly", "").Replace("-debug", "").Replace("  ", " ")
                                      .ToString();
                }
            }
            else
            {
                MtouchDebug = mtouchDebugData.Value.Equals("true", StringComparison.OrdinalIgnoreCase);
            }
        }
        public static Type ExtractType(ITypeSerializer Serializer, ReadOnlySpan <char> strType)
        {
            if (strType.IsEmpty || strType.Length <= 1)
            {
                return(null);
            }

            var hasWhitespace = Json.JsonUtils.WhiteSpaceChars.Contains(strType[1]);

            if (hasWhitespace)
            {
                var pos = strType.IndexOf('"');
                if (pos >= 0)
                {
                    strType = ("{" + strType.Substring(pos)).AsSpan();
                }
            }

            var typeAttrInObject = Serializer.TypeAttrInObject;

            if (strType.Length > typeAttrInObject.Length &&
                strType.Slice(0, typeAttrInObject.Length).EqualsOrdinal(typeAttrInObject))
            {
                var propIndex = typeAttrInObject.Length;
                var typeName  = Serializer.EatValue(strType, ref propIndex).ToString();
                var type      = JsConfig.TypeFinder(typeName);

                if (type == null)
                {
                    Tracer.Instance.WriteWarning("Could not find type: " + typeName);
                }

                return(type);
            }
            return(null);
        }
Exemple #31
0
        private static void WriteValue(ITypeSerializer serializer, TextWriter writer, object value)
        {
            var type     = value.GetType();
            var typeInfo = type.GetTypeInfo();

            if (typeInfo.IsValueType)
            {
                WriteValueTypeToString(serializer, writer, value);
                return;
            }

            if (typeInfo.IsArray)
            {
                var elementType = type.GetElementType();
                if (!elementType.GetTypeInfo().IsValueType)
                {
                    throw new NotSupportedException("数组的类型包含了非值类型,当前不受支持");
                }

                if (type == typeof(byte[]))
                {
                    serializer.WriteBytes(writer, value);
                }
                else if (type == typeof(string[]))
                {
                    WriteStringArray(serializer, writer, value);
                }
                else
                {
                    WriteGenericArrayValueType(serializer, writer, value);
                }
                return;
            }

            serializer.WriteBuiltIn(writer, value);
        }
Exemple #32
0
        public static Type ExtractType(ITypeSerializer Serializer, string strType)
        {
            if (strType == null || strType.Length <= 1)
            {
                return(null);
            }

            var hasWhitespace = JsonUtils.WhiteSpaceChars.Contains(strType[1]);

            if (hasWhitespace)
            {
                var pos = strType.IndexOf('"');
                if (pos >= 0)
                {
                    strType = "{" + strType.Substring(pos);
                }
            }

            var typeAttrInObject = Serializer.TypeAttrInObject;

            if (strType.Length > typeAttrInObject.Length &&
                strType.Substring(0, typeAttrInObject.Length) == typeAttrInObject)
            {
                var propIndex = typeAttrInObject.Length;
                var typeName  = Serializer.EatValue(strType, ref propIndex);
                var type      = JsConfig.TypeFinder(typeName);

                if (type == null)
                {
                    Tracer.Instance.WriteWarning("Could not find type: " + typeName);
                }

                return(type);
            }
            return(null);
        }
Exemple #33
0
        HashSet <Type> Collect(Type rootType)
        {
            var          l     = new HashSet <Type>();
            Stack <Type> stack = new Stack <Type>();

            stack.Push(rootType);

            while (stack.Count > 0)
            {
                var type = stack.Pop();

                if (type.IsAbstract || type.IsInterface)
                {
                    continue;
                }

                if (type.ContainsGenericParameters)
                {
                    throw new NotSupportedException(String.Format("Type {0} contains generic parameters", type.FullName));
                }

                ITypeSerializer serializer = m_runtimeTypeMap[type].TypeSerializer;

                foreach (var t in serializer.GetSubtypes(type))
                {
                    if (l.Contains(t) == false)
                    {
                        stack.Push(t);
                    }
                }

                l.Add(type);
            }

            return(l);
        }
        DataCollection ICustomDataItem.Serialize(ITypeSerializer handler)
        {
            DataCollection data = new DataCollection();

            if (IsEmpty)
            {
                return(data);
            }

            foreach (KeyValuePair <string, object> entry in properties)
            {
                DataNode val;
                if (entry.Value == null)
                {
                    continue;
                }
                else if (entry.Value is XmlElement)
                {
                    DataItem xit = new DataItem();
                    XmlConfigurationReader sr = new XmlConfigurationReader();
                    xit.ItemData.Add(sr.Read((XmlElement)entry.Value));
                    val = xit;
                }
                else if (entry.Value is DataNode)
                {
                    val = (DataNode)entry.Value;
                }
                else
                {
                    val = handler.SerializationContext.Serializer.Serialize(entry.Value, entry.Value.GetType());
                }
                val.Name = EscapeName(entry.Key);
                data.Add(val);
            }
            return(data);
        }
		//always set the MtouchDebug element
		public DataCollection Serialize (ITypeSerializer handler)
		{
			var collection = handler.Serialize (this);
			collection.Add (new DataValue ("MtouchDebug", MtouchDebug.ToString ()));
			return collection;
		}
Exemple #36
0
 public TypeData(Type type, uint typeID, ITypeSerializer typeSerializer)
 {
     this.Type           = type;
     this.TypeID         = typeID;
     this.TypeSerializer = typeSerializer;
 }
Exemple #37
0
 public static Type ExtractType(ITypeSerializer Serializer, string strType)
 => ExtractType(Serializer, new StringSegment(strType));
 public static void WriteIListString(ITypeSerializer serializer, TextWriter writer, object list)
 {
     WriteIListString(serializer, writer, (IList <string>)list);
 }
        internal static Dictionary <HashedStringSegment, TypeAccessor> GetTypeAccessorMap(TypeConfig typeConfig, ITypeSerializer serializer)
        {
            var type           = typeConfig.Type;
            var isDataContract = type.IsDto();

            var propertyInfos = type.GetSerializableProperties();
            var fieldInfos    = type.GetSerializableFields();

            if (propertyInfos.Length == 0 && fieldInfos.Length == 0)
            {
                return(null);
            }

            var map = new Dictionary <HashedStringSegment, TypeAccessor>();

            if (propertyInfos.Length != 0)
            {
                foreach (var propertyInfo in propertyInfos)
                {
                    var propertyName = propertyInfo.Name;
                    if (isDataContract)
                    {
                        var dcsDataMember = propertyInfo.GetDataMember();
                        if (dcsDataMember?.Name != null)
                        {
                            propertyName = dcsDataMember.Name;
                        }
                    }
                    map[new HashedStringSegment(propertyName)] = TypeAccessor.Create(serializer, typeConfig, propertyInfo);
                }
            }

            if (fieldInfos.Length != 0)
            {
                foreach (var fieldInfo in fieldInfos)
                {
                    var fieldName = fieldInfo.Name;
                    if (isDataContract)
                    {
                        var dcsDataMember = fieldInfo.GetDataMember();
                        if (dcsDataMember?.Name != null)
                        {
                            fieldName = dcsDataMember.Name;
                        }
                    }
                    map[new HashedStringSegment(fieldName)] = TypeAccessor.Create(serializer, typeConfig, fieldInfo);
                }
            }
            return(map);
        }
 DataCollection ICustomDataItem.Serialize(ITypeSerializer handler)
 {
     return(handler.Serialize(this));
 }
 public T ContentAs <T>(ITypeSerializer serializer)
 {
     throw new NotImplementedException();
 }
 public override void Deserialize(ITypeSerializer handler, DataCollection data)
 {
     base.Deserialize (handler, data);
     languageBinding = FindLanguage (language);
 }
Exemple #43
0
 public DefaultTranscoder(IByteConverter converter, ITypeSerializer serializer)
 {
     Serializer = serializer;
     Converter  = converter;
 }
		public void Deserialize (ITypeSerializer handler, DataCollection data)
		{
			DataItem item = new DataItem ();
			item.Name = "SolutionConfiguration";
			DataCollection col = item.ItemData;
			
			foreach (DataNode val in data) {
				if (val.Name != "name" && val.Name != "ctype" && val.Name != "Entry")
					col.Add (val);
			}
			
			handler.Deserialize (this, data);
			
			if (data.Count > 0) {
				solutionConfiguration = new SolutionConfiguration (name);
				handler.SerializationContext.Serializer.Deserialize (solutionConfiguration, item);
			}
		}
Exemple #45
0
        public DataCollection Serialize(ITypeSerializer handler)
        {
            tempIncludes.Clear ();
            foreach (var p in LocalIncludeCache.ParsedDirectories)
                tempIncludes.Add (p);

            var ret = handler.Serialize (this);

            return ret;
        }
 internal MemcachedBucket(IClusterManager clusterManager, string bucketName, IByteConverter converter, ITypeSerializer serializer)
 {
     _clusterManager = clusterManager;
     _converter      = converter;
     _serializer     = serializer;
     Name            = bucketName;
 }
        public virtual DataCollection Serialize(object obj, ITypeSerializer handler)
        {
            if (obj is ProjectFile)
            {
                ProjectFile    pf   = (ProjectFile)obj;
                DataCollection data = handler.Serialize(obj);

                //Map the Content build action to the old FileCopy action if CopyToOutputDirectory is set
                if (pf.BuildAction == BuildAction.Content && pf.CopyToOutputDirectory != FileCopyMode.None)
                {
                    DataValue value = data ["buildaction"] as DataValue;
                    if (value != null)
                    {
                        data.Remove(value);
                        data.Add(new DataValue("buildaction", "FileCopy"));
                        data.Extract("copyToOutputDirectory");
                    }
                }
                // Don't store the resource id if it matches the default.
                if (pf.BuildAction == BuildAction.EmbeddedResource && pf.ResourceId != Path.GetFileName(pf.FilePath))
                {
                    data.Add(new DataValue("resource_id", pf.ResourceId));
                }
                return(data);
            }
            else if (obj is SolutionEntityItem)
            {
                DotNetProject project = obj as DotNetProject;
                if (project != null)
                {
                    foreach (DotNetProjectConfiguration config in project.Configurations)
                    {
                        config.ExtendedProperties ["Build/target"] = project.CompileTarget.ToString();
                    }
                }
                DataCollection     data = handler.Serialize(obj);
                SolutionEntityItem item = (SolutionEntityItem)obj;
                if (item.DefaultConfiguration != null)
                {
                    DataItem confItem = data ["Configurations"] as DataItem;
                    if (confItem != null)
                    {
                        confItem.UniqueNames = true;
                        if (item.ParentSolution != null)
                        {
                            confItem.ItemData.Add(new DataValue("active", item.ParentSolution.DefaultConfigurationId));
                        }
                    }
                }
                if (project != null)
                {
                    data.Extract("targetFramework");
                    data.Add(new DataValue("targetFramework", project.TargetFramework.Id.ToLegacyIdString()));
                }
                WriteItems(handler, (SolutionEntityItem)obj, data);
                return(data);
            }
            else if (obj is ProjectReference)
            {
                ProjectReference pref  = (ProjectReference)obj;
                DataCollection   data  = handler.Serialize(obj);
                string           refto = pref.Reference;
                if (pref.ReferenceType == ReferenceType.Assembly)
                {
                    string basePath = Path.GetDirectoryName(handler.SerializationContext.BaseFile);
                    refto = FileService.AbsoluteToRelativePath(basePath, refto);
                }
                else if (pref.ReferenceType == ReferenceType.Gac && pref.LoadedReference != null)
                {
                    refto = pref.LoadedReference;
                }

                data.Add(new DataValue("refto", refto));
                return(data);
            }
            return(handler.Serialize(obj));
        }
        public virtual void Deserialize(object obj, ITypeSerializer handler, DataCollection data)
        {
            if (obj is ProjectFile)
            {
                ProjectFile pf = (ProjectFile)obj;

                //Map the old FileCopy action to the Content BuildAction with CopyToOutputDirectory set to "always"
                //BuildActionDataType handles mapping the BuildAction to "Content"
                DataValue value      = data ["buildaction"] as DataValue;
                bool      isFileCopy = value != null && value.Value == "FileCopy";

                DataValue resourceId = data.Extract("resource_id") as DataValue;

                handler.Deserialize(obj, data);
                if (isFileCopy)
                {
                    pf.CopyToOutputDirectory = FileCopyMode.Always;
                }

                if (resourceId != null)
                {
                    pf.ResourceId = resourceId.Value;
                }
            }
            else if (obj is SolutionEntityItem)
            {
                DataValue ac       = null;
                DataItem  confItem = data ["Configurations"] as DataItem;
                if (confItem != null)
                {
                    ac = (DataValue)confItem.ItemData.Extract("active");
                }

                DataItem items = data.Extract("Items") as DataItem;
                if (items != null)
                {
                    ReadItems(handler, (SolutionEntityItem)obj, items);
                }

                handler.Deserialize(obj, data);
                if (ac != null)
                {
                    SolutionEntityItem item = (SolutionEntityItem)obj;
                    item.DefaultConfigurationId = ac.Value;
                }
                DotNetProject np = obj as DotNetProject;
                if (np != null)
                {
                    // Import the framework version
                    TargetFrameworkMoniker fx = null;
                    DataValue vfx             = data["targetFramework"] as DataValue;
                    if (vfx != null)
                    {
                        fx = TargetFrameworkMoniker.Parse(vfx.Value);
                    }
                    else
                    {
                        vfx = data ["clr-version"] as DataValue;
                        if (vfx != null && vfx.Value == "Net_2_0")
                        {
                            fx = TargetFrameworkMoniker.NET_2_0;
                        }
                        else if (vfx != null && vfx.Value == "Net_1_1")
                        {
                            fx = TargetFrameworkMoniker.NET_1_1;
                        }
                    }
                    if (fx != null)
                    {
                        np.TargetFramework = Runtime.SystemAssemblyService.GetTargetFramework(fx);
                    }

                    // Get the compile target from one of the configurations
                    if (np.Configurations.Count > 0)
                    {
                        np.CompileTarget = (CompileTarget)Enum.Parse(typeof(CompileTarget), (string)np.Configurations [0].ExtendedProperties ["Build/target"]);
                    }
                }
            }
            else if (obj is ProjectReference)
            {
                ProjectReference pref  = (ProjectReference)obj;
                DataValue        refto = data.Extract("refto") as DataValue;
                handler.Deserialize(obj, data);
                if (refto != null)
                {
                    pref.Reference = refto.Value;
                    if (pref.ReferenceType == ReferenceType.Assembly)
                    {
                        string basePath = Path.GetDirectoryName(handler.SerializationContext.BaseFile);
                        pref.Reference = FileService.RelativeToAbsolutePath(basePath, pref.Reference);
                    }
                }
            }
            else
            {
                handler.Deserialize(obj, data);
            }
        }
		// if MtouchDebug element is not present, this handler migrates args
		// and sets default values for the new Mtouch* properties
		public void Deserialize (ITypeSerializer handler, DataCollection data)
		{
			var argsToMigrate = data.Extract ("ExtraMtouchArgs") as DataValue;
			var mtouchDebugData = data.Extract ("MtouchDebug") as DataValue;
			handler.Deserialize (this, data);
			
			if (mtouchDebugData == null || string.IsNullOrEmpty (mtouchDebugData.Value)) {
				if (Name == "Debug") {
					MtouchDebug = true;
					if (Platform == IPhoneProject.PLAT_SIM)
						MtouchLink = MtouchLinkMode.None;
				}
				if (argsToMigrate != null && string.IsNullOrEmpty (argsToMigrate.Value)) {
					if (argsToMigrate.Value.Contains ("-debug"))
						MtouchDebug = true;
					if (argsToMigrate.Value.Contains ("-nolink"))
						MtouchLink = MtouchLinkMode.None;
					MtouchExtraArgs = new StringBuilder (argsToMigrate.Value)
						.Replace ("-nolink", "").Replace ("-linksdkonly", "").Replace ("-debug", "").Replace ("  ", " ")
						.ToString ();
				}
			} else {
				MtouchDebug = mtouchDebugData.Value.Equals ("true", StringComparison.OrdinalIgnoreCase);
			}
		}
		DataCollection ICustomDataItem.Serialize (ITypeSerializer handler)
		{
			return handler.Serialize (this);
		}
 public BlockQueryResult(Stream responseStream, ITypeSerializer deserializer)
     : base(responseStream)
 {
     _deserializer = deserializer ?? throw new ArgumentNullException(nameof(deserializer));
 }
Exemple #52
0
        public void Deserialize(ITypeSerializer handler, DataCollection data)
        {
            handler.Deserialize (this, data);

            foreach (var p in tempIncludes)
                LocalIncludeCache.ParsedDirectories.Add (ProjectBuilder.EnsureCorrectPathSeparators (p));
        }
Exemple #53
0
 internal LookupInResult(IList <OperationSpec> specs, ulong cas, TimeSpan?expiry, ITypeSerializer typeSerializer)
 {
     _specs      = specs;
     Cas         = cas;
     Expiry      = expiry;
     _serializer = typeSerializer ?? throw new ArgumentNullException(nameof(typeSerializer));
 }
		void WriteItems (ITypeSerializer handler, SolutionEntityItem item, DataCollection data)
		{
			DataItem items = new DataItem ();
			items.Name = "Items";
			foreach (object it in item.Items) {
				if (it is ProjectFile || it is ProjectReference)
					continue; // Already handled by serializer
				DataNode node = handler.SerializationContext.Serializer.Serialize (it, it.GetType ());
				items.ItemData.Add (node);
			}
			if (items.HasItemData)
				data.Add (items);
		}
Exemple #55
0
        public void Deserialize(ITypeSerializer handler, DataCollection data)
        {
            handler.Deserialize(this, data);

            referenceCollection.InitRefCollection(tempProjectDependencies, tempIncludes);
        }
		void ReadItems (ITypeSerializer handler, SolutionEntityItem item, DataItem items)
		{
			foreach (DataNode node in items.ItemData) {
				DataType dtype = handler.SerializationContext.Serializer.DataContext.GetConfigurationDataType (node.Name);
				if (dtype != null && typeof(ProjectItem).IsAssignableFrom (dtype.ValueType)) {
					ProjectItem it = (ProjectItem) handler.SerializationContext.Serializer.Deserialize (dtype.ValueType, node);
					item.Items.Add (it);
				}
			}
		}
Exemple #57
0
 public void WriteTo(ITypeSerializer serializer, TextWriter writer) => writer.Write(this.json ?? JsonUtils.Null);
Exemple #58
0
 public static T?Deserialize <T>(this ITypeSerializer typeSerializer, byte[] buffer, int offset, int length)
 {
     return(typeSerializer.Deserialize <T>(buffer.AsMemory(offset, length)));
 }
Exemple #59
0
 public MutateInResult(IList <OperationSpec> specs, ulong cas, MutationToken token, ITypeSerializer serializer)
 {
     _specs        = specs ?? throw new ArgumentNullException(nameof(specs));
     Cas           = cas;
     MutationToken = token ?? throw new ArgumentNullException(nameof(token));
     _serializer   = serializer ?? throw new ArgumentNullException(nameof(serializer));
 }
 public static void FireLanEvent(
     this Node node,
     string @event,
     object?payload,
     ITypeSerializer serializer) => node.GetLanEventBus().Emit(@event, payload, serializer);