Example #1
0
        public NFXSlim(TestingSystem context, IConfigSectionNode conf)
            : base(context, conf)
        {
            Type[] known = ReadKnownTypes(conf);

              //we create type registry with well-known types that serializer does not have to emit every time
              m_TypeRegistry = new TypeRegistry(TypeRegistry.BoxedCommonTypes,
                                        TypeRegistry.BoxedCommonNullableTypes,
                                        TypeRegistry.CommonCollectionTypes,
                                        known);

              m_Serializer = new SlimSerializer(m_TypeRegistry);

              //batching allows to remember the encountered types and hence it is a "stateful" mode
              //where serialization part and deserialization part retain the type registries that
              //get auto-updated. This mode is not thread safe
              if (m_Batching)
              {
            m_BatchSer = new SlimSerializer(m_TypeRegistry);
            m_BatchSer.TypeMode = TypeRegistryMode.Batch;

            m_BatchDeser = new SlimSerializer(m_TypeRegistry);
            m_BatchDeser.TypeMode = TypeRegistryMode.Batch;
              }
        }
Example #2
0
        private static void InitialiseModules(IUnityContainer container)
        {
            var logger = new LoggerFactory().CreateLogger(typeof(Bootstrapper));
            logger.Trace("Initializing modules");
            var typeRegistry = new TypeRegistry(container);

            var moduleConfig = CallWallModuleSection.GetConfig();

            var modules = from moduleType in moduleConfig.Modules.Cast<ModuleElement>().Select(m => m.Type)
                          select (IModule)Activator.CreateInstance(moduleType);

            
            logger.Trace("Initializing modules...");
            foreach (var module in modules)
            {
                logger.Trace("Initializing module : {0}", module.GetType().Name);
                module.Initialise(typeRegistry);
            }
            logger.Trace("Modules Initialized");


            logger.Info("Starting processes");
            var processes = container.ResolveAll<IProcess>();
            Task.WhenAll(processes.Select(p => p.Run()))
                .Wait();
        }
Example #3
0
        public static string ArrayToDescriptor(Array array, 
            TypeRegistry treg,
            Type type = null,
            string th = null)
        {
            if (type==null)
                 type = array.GetType();

              if (array.LongLength>MAX_ELM_COUNT)
                throw new SlimSerializationException(StringConsts.SLIM_ARRAYS_OVER_MAX_ELM_ERROR.Args(array.LongLength, MAX_ELM_COUNT));

              if (type==typeof(object[]))//special case for object[], because this type is very often used in Glue and other places
               return "$1|"+array.Length.ToString();

              if (th==null)
                 th = treg.GetTypeHandle(type);

               var ar = array.Rank;
               if (ar>MAX_DIM_COUNT)
                throw new SlimSerializationException(StringConsts.SLIM_ARRAYS_OVER_MAX_DIMS_ERROR.Args(ar, MAX_DIM_COUNT));

               var descr = new StringBuilder(th);
               descr.Append('|');//separator char

               for(int i=0; i<ar; i++)
               {
                  descr.Append(array.GetLowerBound(i));
                  descr.Append('~');
                  descr.Append(array.GetUpperBound(i));
                  if (i<ar-1)
                   descr.Append(',');
               }

              return descr.ToString();
        }
Example #4
0
		public MessageMemberInfo(MemberInfo memberInfo, TypeRegistry typeRegistry)
		{
			this.order = PropertyOrderAttribute.Get(memberInfo);
			this.name = PropertyNameAttribute.Get(memberInfo);
			this.nameHash = Hash.Eval(this.name);
			this.propertyType = PropertyTypeAttribute.Get(memberInfo, typeRegistry);

			this.serializer = typeRegistry.ResolveSerializer(this.propertyType);
		}
Example #5
0
		public static int Get(ParameterInfo parameterInfo, TypeRegistry typeRegistry = null)
		{
			var v = GetCustomAttribute(parameterInfo, typeof(PropertyTypeAttribute)) as PropertyTypeAttribute;
			if (v != null)
			{
				return v.propertyType;
			}
			return GetDefaultType(parameterInfo.ParameterType, typeRegistry);
		}
 private void Initialize()
 {
     if (!base.JustInitialized) return;
     var typeList = new List<Type> {_primaryType};
     if (_secondaryTypes != null) typeList.AddRange(_secondaryTypes);
     var treg = new TypeRegistry(typeList, TypeRegistry.BoxedCommonNullableTypes, TypeRegistry.BoxedCommonTypes);
     _serializer = new SlimSerializer(treg);
     JustInitialized = false;
 }
 public TemplateContextGenerator(GeneratorConfig generatorConfig,
     TypeRegistry typeRegistry,
     TypeToJavaConverter typeConverter,
     string defaultNamespace)
 {
     this.generatorConfig = generatorConfig;
     this.typeRegistry = typeRegistry;
     this.defaultNamespace = defaultNamespace;
     this.typeConverter = typeConverter;
 }
Example #8
0
		public MessageMemberInfo(ParameterInfo par, TypeRegistry typeRegistry)
		{
			this.memberInfo = par;
			this.type = par.ParameterType;

			this.order = PropertyOrderAttribute.Get(par);
			this.name = PropertyNameAttribute.Get(par);
			this.nameHash = Hash.Eval(this.name);
			this.propertyType = PropertyTypeAttribute.Get(par, typeRegistry);
			this.serializer = typeRegistry.ResolveSerializer(this.propertyType);
		}
 public DocumentContext(Uri tripUri,
     string _namespace, GeneratorConfig generatorConfig,
     TypeRegistry typeRegistry)
 {
     Document = IdlParser.BuildDocument(tripUri);
     this.tripUri = tripUri;
     Namespace = _namespace;
     this.generatorConfig = generatorConfig;
     TypeRegistry = typeRegistry;
     TypeConverter = new TypeToJavaConverter(typeRegistry, _namespace, JavaPackage);
 }
Example #10
0
        public decimal Evaluate(decimal input, decimal paramY)
        {
            var registry = new TypeRegistry();
            registry.RegisterType("m", typeof (Math));
            registry.RegisterSymbol("x", input);
            registry.RegisterSymbol("y", paramY);

            var expression = new CompiledExpression<decimal>(Expression)
            {
                TypeRegistry = registry
            };
            return expression.Eval();
        }
Example #11
0
 private TypeRegistry InitTypeRegistry(Type contextType, params Type[] parents)
 {
     var t = new TypeRegistry();
     t.RegisterType("ViewModel", contextType);
     t.RegisterType("RootViewModel", parents.LastOrDefault() ?? contextType);
     t.RegisterType("Enumerable", typeof(Enumerable));
     for (int i = parents.Length - 1; i >= 0; i--)
     {
         if (!t.ContainsKey(parents[i].Name))
             t.RegisterType(parents[i].Name, parents[i]);
     }
     if (!t.ContainsKey(contextType.Name))
         t.RegisterType(contextType.Name, contextType);
     return t;
 }
Example #12
0
 internal static object HandleResult(SerializedEvaluation evaluation, Func<string, IRpcRoot> referenceResolver)
 {
     if (evaluation == null || string.IsNullOrEmpty(evaluation.Evaluation))
         return null;
     
     var reg = new TypeRegistry();
     for (int i = 0; i < evaluation.References.Length; i++)
     {
         reg.RegisterSymbol("r" + (i + 1), referenceResolver(evaluation.References[i]));
     }
     var p = new CompiledExpression(evaluation.Evaluation)
     {
         TypeRegistry = reg
     };
     return p.Eval();
 }
Example #13
0
 /// <summary>
 /// Function to call when a server request is received
 /// </summary>
 /// <param name="evaluation">The incoming request</param>
 /// <param name="referenceResolver">Your reference loader: Resolves references to server-side objects</param>
 /// <returns></returns>
 public static SerializedEvaluation HandleIncomingRequest(SerializedEvaluation evaluation, Func<string, IRpcRoot> referenceResolver)
 {
     var reg = new TypeRegistry();
     for (int i = 0; i < evaluation.References.Length; i++)
     {
         reg.RegisterSymbol("r" + (i + 1), referenceResolver(evaluation.References[i]));
     }
     var p = new CompiledExpression(evaluation.Evaluation)
     {
         TypeRegistry = reg
     };
     var ret = p.Eval();
     if (ret == null)
         return null;
     return new RpcCallVisitor().Serialize(Expression.Constant(ret));
 }
 public TypeToCSharpConverter(TypeRegistry typeRegistry,
     string _namespace,
     string csharpNamespace)
 {
     Enforce.IsNotNull<TypeRegistry>(typeRegistry, "typeRegistry");
     Enforce.IsNotNull<string>(_namespace, "namespace");
     this.typeRegistry = typeRegistry;
     this._namespace = _namespace;
     this.csharpNamespace = csharpNamespace;
     converters = new List<Converter>();
     converters.Add(new BaseConverter());
     converters.Add(new IdentifierConverter(this));
     converters.Add(new SetConverter(this));
     converters.Add(new ListConverter(this));
     converters.Add(new MapConverter(this));
 }
Example #15
0
		private static int GetDefaultType(Type fieldType, TypeRegistry typeRegistry = null)
		{
			if (typeRegistry != null)
			{
				int res;
				if (typeRegistry.TryResolvePropertyType(fieldType, out res))
				{
					return res;
				}
			}
			if (fieldType == typeof(int))
			{
				return PropertyTypes.Int32;
			}
			if (fieldType == typeof(uint))
			{
				return PropertyTypes.Int32;
			}

			if (fieldType == typeof(byte))
			{
				return PropertyTypes.Int32;
			}
			if (fieldType == typeof(sbyte))
			{
				return PropertyTypes.Int32;
			}

			if (fieldType == typeof(ushort))
			{
				return PropertyTypes.Int32;
			}
			if (fieldType == typeof(short))
			{
				return PropertyTypes.Int32;
			}

			if (fieldType == typeof(float))
			{
				return PropertyTypes.Single;
			}
			if (fieldType == typeof(string))
			{
				return PropertyTypes.String;
			}
			return 0;
		}
Example #16
0
        internal static async Task<object> HandleResultAsync(SerializedEvaluation evaluation, Func<string, Task<IRpcRoot>> referenceResolver)
        {
            if (evaluation == null || string.IsNullOrEmpty(evaluation.Evaluation))
                return null;
            
            var reg = new TypeRegistry();

            for (int i = 0; i < evaluation.References.Length; i++)
            {
                reg.RegisterSymbol("r" + (i + 1), await referenceResolver(evaluation.References[i]).ConfigureAwait(false));
            }
            var p = new CompiledExpression(evaluation.Evaluation)
            {
                TypeRegistry = reg
            };
            return p.Eval();
        }
Example #17
0
		public static int Get(MemberInfo property, TypeRegistry typeRegistry = null)
		{
			var v = GetCustomAttribute(property, typeof(PropertyTypeAttribute)) as PropertyTypeAttribute;
			if (v != null)
			{
				return v.propertyType;
			}
			var propertyInfo = property as PropertyInfo;
			if (propertyInfo != null)
			{
				return GetDefaultType(propertyInfo.PropertyType, typeRegistry);
			}
			var fieldInfo = property as FieldInfo;
			if (fieldInfo != null)
			{
				return GetDefaultType(fieldInfo.FieldType, typeRegistry);
			}
			return PropertyTypes.Unknown;
		}
Example #18
0
        private ISerializer getSerializer()
        {
          if (m_Format!=FileObjectFormat.Slim)
          {
            return new MSBinaryFormatter();
          }


          var treg = new TypeRegistry(TypeRegistry.CommonCollectionTypes,
                                                TypeRegistry.RecordModelTypes,
                                                TypeRegistry.BoxedCommonTypes,
                                                TypeRegistry.BoxedCommonNullableTypes);
          
          foreach(var tn in m_KnownTypes)
          {
            var t = Type.GetType(tn, false);
            if (t!=null) 
             treg.Add(t);
            else
             WriteLog(MessageType.Warning, "Specified known type could not be found: " + tn, tn, "getSerializer(slim)"); 
          }
          return  new SlimSerializer(treg); 
        }
Example #19
0
 /// <summary>
 /// Creates a new <see cref="Settings"/> object with the specified formatting of default values
 /// and type registry.
 /// </summary>
 /// <param name="formatDefaultValues"><c>true</c> if default values (0, empty strings etc) should be formatted; <c>false</c> otherwise.</param>
 /// <param name="typeRegistry">The <see cref="TypeRegistry"/> to use when formatting <see cref="Any"/> messages.</param>
 public Settings(bool formatDefaultValues, TypeRegistry typeRegistry) : this(formatDefaultValues, typeRegistry, false)
 {
 }
Example #20
0
 protected override DocumentContext CreateDocumentContext(Uri uri, string idlNamespace, GeneratorConfig config,
                                                          TypeRegistry typeRegistry)
 {
     return(new CSharpDocumentContext(uri, idlNamespace, config, typeRegistry));
 }
Example #21
0
        private void parseDocument(Uri tripUri,
                                   Dictionary<string, DocumentContext> contexts,
                                   TypeRegistry typeRegistry)
        {
            if (tripUri == null || !tripUri.IsAbsoluteUri)
            {
                throw new ArgumentException("Only absolute URIs can be parsed!");
            }
            if (parentDocuments.Contains(tripUri))
            {
                throw new ArgumentException(string.Format("Input {0} recursively includes itself ({1})", tripUri, string.Join(" -> ", parentDocuments) + " -> " + tripUri));
            }

            if (parsedDocuments.Contains(tripUri))
            {
                LOG.Debug(string.Format("Skipping already parsed file {0}...", tripUri));
                return;
            }

            LOG.Debug(string.Format("Parsing {0}...", tripUri));

            var tripNamespace = extractLeanNamespace(tripUri);
            if (string.IsNullOrWhiteSpace(tripNamespace))
            {
                throw new ArgumentException(string.Format("Lean URI {0} can not be translated to a namespace", tripUri));
            }

            var context = new DocumentContext(tripUri, tripNamespace, generatorConfig, typeRegistry);

            var document = context.Document;
            var header = document.Header;

            var javaPackage = context.JavaPackage;

            // Make a note that this document is a parent of all the documents included, directly or recursively
            parentDocuments.Push(tripUri);

            try
            {
                if (header != null)
                {
                    foreach (var include in header.Includes)
                    {
                        Uri includeUri = null;
                        Uri.TryCreate(generatorConfig.InputBase, include, out includeUri);
                        parseDocument(includeUri,
                            // If the includes should also generate code, pass the list of
                            // contexts down to the include parser, otherwise pass a null in
                                      generatorConfig.GenerateIncludedCode ? contexts : null,
                                      typeRegistry);
                    }
                }
            }
            finally
            {
                // Done parsing this document's includes, remove it from the parent chain
                parentDocuments.Pop();
            }

            // Make a note that we've already passed this document
            parsedDocuments.Add(tripUri);

            new TypeVisitor(javaPackage, context).Visit(document);

            if (contexts != null)
            {
                if (contexts.ContainsKey(context.Namespace))
                {
                    LOG.Info(string.Format("Lean Namespace {0} included multiple times!", context.Namespace));
                }
                contexts[context.Namespace] = context;
            }
        }
Example #22
0
        public void AnyWellKnownType()
        {
            var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithTypeRegistry(TypeRegistry.FromMessages(Timestamp.Descriptor)));
            var timestamp = new DateTime(1673, 6, 19, 12, 34, 56, DateTimeKind.Utc).ToTimestamp();
            var any       = Any.Pack(timestamp);

            AssertJson("{ '@type': 'type.googleapis.com/google.protobuf.Timestamp', 'value': '1673-06-19T12:34:56Z' }", formatter.Format(any));
        }
 /// <inheritdoc/>
 protected DomainTypeRegistry(TypeRegistry source)
     : base(source)
 {
 }
Example #24
0
 public RelinqQueryExecutor(TypeRegistry typeRegistry, Func <BuiltQuery, IEnumerable> execute)
 {
     this.typeRegistry = typeRegistry;
     this.execute      = execute;
 }
Example #25
0
 public QueryBuilder(TypeRegistry typeRegistry)
 {
     this.typeRegistry = typeRegistry;
 }
 /// <summary>
 /// Deserialize an object from a byte array
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="bytes"></param>
 /// <param name="typeRegistry">A list of type mappings</param>
 /// <returns></returns>
 public object Deserialize(Type type, byte[] bytes, TypeRegistry typeRegistry)
 {
     return(Deserialize(type, bytes, SerializerOptions.None, typeRegistry));
 }
        /// <summary>
        /// Deserialize an object from a byte array
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="bytes"></param>
        /// <param name="options">The serialization options</param>
        /// <param name="typeRegistry">A list of type mappings</param>
        /// <returns></returns>
        public object Deserialize(Type type, byte[] bytes, SerializerOptions options, TypeRegistry typeRegistry)
        {
            if (bytes == null)
            {
                throw new ArgumentNullException(nameof(bytes));
            }
            if (bytes.Length == 0)
            {
                return(null);
            }

            return(_deserializer.InspectAndDeserialize(type, bytes, Constants.DefaultMaxDepth, options, _ignoreAttributes, typeRegistry));
        }
 /// <summary>
 /// Deserialize an object from a byte array
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="bytes"></param>
 /// <param name="typeRegistry">A list of type mappings</param>
 /// <returns></returns>
 public T Deserialize <T>(byte[] bytes, TypeRegistry typeRegistry)
 {
     return(Deserialize <T>(bytes, SerializerOptions.None, typeRegistry));
 }
Example #29
0
 /// <summary>
 /// Creates a new <see cref="Settings"/> object with the specified formatting of default values
 /// and type registry.
 /// </summary>
 /// <param name="formatDefaultValues"><c>true</c> if default values (0, empty strings etc) should be formatted; <c>false</c> otherwise.</param>
 /// <param name="typeRegistry">The <see cref="TypeRegistry"/> to use when formatting <see cref="Any"/> messages.</param>
 public Settings(bool formatDefaultValues, TypeRegistry typeRegistry)
 {
     FormatDefaultValues = formatDefaultValues;
     TypeRegistry        = ProtoPreconditions.CheckNotNull(typeRegistry, "typeRegistry");
 }
Example #30
0
 /// <summary>
 /// Creates a new <see cref="Settings"/> object with the specified type registry and the current settings.
 /// </summary>
 /// <param name="typeRegistry">The <see cref="TypeRegistry"/> to use when formatting <see cref="Any"/> messages.</param>
 public Settings WithTypeRegistry(TypeRegistry typeRegistry) => new Settings(FormatDefaultValues, typeRegistry, FormatEnumsAsIntegers);
Example #31
0
          private byte[] serialize(object payload, out int payloadSize, out byte serVersion)
          {
            var stream = getTLWriteStream();
            var serializer = ts_WriteSerializer;
            if (serializer==null || serializer.Owner != this)
            {
                serializer = new SlimSerializer(m_CurrentTypeRegistry, SlimFormat.Instance);
                serializer.Owner = this;
                serializer.TypeMode = TypeRegistryMode.Batch;
                ts_WriteSerializer = serializer;
            }
            
            while(Running)
            {
              stream.Position = 0;
              serializer.Serialize(stream, payload);
              if (!serializer.BatchTypesAdded) break;
              
              TypeRegistry newReg;
              lock(m_CurrentTypeRegistryLock)
              {
                newReg = new TypeRegistry( m_CurrentTypeRegistry );
                foreach(var t in serializer.BatchTypeRegistry)
                  newReg.Add( t );

                m_CurrentTypeRegistry = newReg;
              }
              //re-allocate serializer with the new type registry
              serializer = new SlimSerializer(newReg, SlimFormat.Instance);
              serializer.Owner = this;
              serializer.TypeMode = TypeRegistryMode.Batch;
              ts_WriteSerializer = serializer;
            }//while

            payloadSize = (int)stream.Position;
            serVersion = 0;//not used for now
            return stream.GetBuffer();
          }
Example #32
0
 /// <summary>
 /// Creates a new <see cref="Settings"/> object with the specified recursion limit and type registry.
 /// </summary>
 /// <param name="recursionLimit">The maximum depth of messages to parse</param>
 /// <param name="typeRegistry">The type registry used to parse <see cref="Any"/> messages</param>
 public Settings(int recursionLimit, TypeRegistry typeRegistry)
 {
     RecursionLimit = recursionLimit;
     TypeRegistry   = ProtoPreconditions.CheckNotNull(typeRegistry, "TypeRegistry");
 }
Example #33
0
        public void AnyMessageType()
        {
            var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithTypeRegistry(TypeRegistry.FromMessages(TestAllTypes.Descriptor)));
            var message   = new TestAllTypes {
                SingleInt32 = 10, SingleNestedMessage = new TestAllTypes.Types.NestedMessage {
                    Bb = 20
                }
            };
            var any = Any.Pack(message);

            AssertJson("{ '@type': 'type.googleapis.com/protobuf_unittest3.TestAllTypes', 'singleInt32': 10, 'singleNestedMessage': { 'bb': 20 } }", formatter.Format(any));
        }
Example #34
0
        public void ParseAssemblyAndRegisterRosMessages(Assembly assembly)
        {
            foreach (Type othertype in assembly.GetTypes())
            {
                var messageInfo = othertype.GetTypeInfo();
                if (othertype == typeof(RosMessage) || !messageInfo.IsSubclassOf(typeof(RosMessage)) || othertype == typeof(InnerActionMessage))
                {
                    continue;
                }

                var        goalAttribute     = messageInfo.GetCustomAttribute <ActionGoalMessageAttribute>();
                var        resultAttribute   = messageInfo.GetCustomAttribute <ActionResultMessageAttribute>();
                var        feedbackAttribute = messageInfo.GetCustomAttribute <ActionFeedbackMessageAttribute>();
                var        ignoreAttribute   = messageInfo.GetCustomAttribute <IgnoreRosMessageAttribute>();
                RosMessage message;
                if (goalAttribute != null || resultAttribute != null || feedbackAttribute != null || ignoreAttribute != null)
                {
                    Type actionType;
                    if (goalAttribute != null)
                    {
                        actionType = typeof(GoalActionMessage <>);
                    }
                    else if (resultAttribute != null)
                    {
                        actionType = typeof(ResultActionMessage <>);
                    }
                    else if (feedbackAttribute != null)
                    {
                        actionType = typeof(FeedbackActionMessage <>);
                    }
                    else if (ignoreAttribute != null)
                    {
                        continue;
                    }
                    else
                    {
                        throw new InvalidOperationException($"Could create Action Message for {othertype}");
                    }

                    Type[] innerType       = { othertype };
                    var    goalMessageType = actionType.MakeGenericType(innerType);
                    message = (Activator.CreateInstance(goalMessageType)) as RosMessage;
                }
                else
                {
                    message = Activator.CreateInstance(othertype) as RosMessage;
                    if ((message != null) && (message.MessageType == "undefined/unknown"))
                    {
                        throw new Exception("Invalid message type. Message type field (msgtype) was not initialized correctly.");
                    }
                }

                var packageName = message.MessageType.Split('/')[0];
                if (!PackageNames.Contains(packageName))
                {
                    PackageNames.Add(packageName);
                }

                Logger.LogDebug($"Register {message.MessageType}");
                if (!TypeRegistry.ContainsKey(message.MessageType))
                {
                    TypeRegistry.Add(message.MessageType, message.GetType());
                }
                else
                {
                    var messageFromRegistry = CreateMessage(message.MessageType);
                    if (messageFromRegistry.MD5Sum() != message.MD5Sum())
                    {
                        throw new InvalidOperationException($"The message of type {message.MessageType} has already been " +
                                                            $"registered and the MD5 sums do not match. Already registered: {messageFromRegistry.MD5Sum()} " +
                                                            $"new message: {message.MD5Sum()}.");
                    }
                    else
                    {
                        Logger.LogDebug($"The message of type {message.MessageType} has already been registered. Since the" +
                                        "MD5 sums do match, the new message is ignored.");
                    }
                }
            }
        }
Example #35
0
 public DistinctTypeEmitter(TypeRegistry typeRegistry, TypeReferenceEmitter typeReferenceEmitter) =>
 (this.TypeRegistry, this.TypeReferenceEmitter) = (typeRegistry, typeReferenceEmitter);
        protected override bool Execute(ConfigFile config)
        {
            var group = SharpGen.CppModel.CppModule.Read(CppModule.ItemSpec);

            config.ExpandDynamicVariables(SharpGenLogger, group);

            var docLinker    = new DocumentationLinker();
            var typeRegistry = new TypeRegistry(SharpGenLogger, docLinker);
            var namingRules  = new NamingRulesManager();

            var globalNamespace = new GlobalNamespaceProvider();

            foreach (var nameOverride in GlobalNamespaceOverrides ?? Enumerable.Empty <ITaskItem>())
            {
                var wellKnownName = nameOverride.ItemSpec;
                var overridenName = nameOverride.GetMetadata("Override");
                if (overridenName != null && Enum.TryParse(wellKnownName, out WellKnownName name))
                {
                    globalNamespace.OverrideName(name, overridenName);
                }
            }

            // Run the main mapping process
            var transformer = new TransformManager(
                globalNamespace,
                namingRules,
                SharpGenLogger,
                typeRegistry,
                docLinker,
                new ConstantManager(namingRules, docLinker)
                );

            var(solution, defines) = transformer.Transform(group, config);

            solution.Write(CSharpModel.ItemSpec);

            var consumerConfig = ConfigFile.Load(CppConsumerConfigCache.ItemSpec, new string[0], SharpGenLogger);

            consumerConfig.Id = ConsumerBindMappingConfigId;

            consumerConfig.Extension = new List <ExtensionBaseRule>(defines);

            var(bindings, generatedDefines) = transformer.GenerateTypeBindingsForConsumers();

            consumerConfig.Bindings.AddRange(bindings);
            consumerConfig.Extension.AddRange(generatedDefines);

            consumerConfig.Mappings.AddRange(
                docLinker.GetAllDocLinks().Select(
                    link => new MappingRule
            {
                DocItem          = link.cppName,
                MappingNameFinal = link.cSharpName
            }));

            if (GenerateConsumerConfig)
            {
                GenerateConfigForConsumers(consumerConfig);
            }

            SaveDocLinks(docLinker);

            return(!Log.HasLoggedErrors);
        }
Example #37
0
        private static ConformanceResponse PerformRequest(ConformanceRequest request, TypeRegistry typeRegistry)
        {
            ProtobufTestMessages.Proto3.TestAllTypesProto3 message;
            try
            {
                switch (request.PayloadCase)
                {
                case ConformanceRequest.PayloadOneofCase.JsonPayload:
                    if (request.TestCategory == global::Conformance.TestCategory.JsonIgnoreUnknownParsingTest)
                    {
                        return(new ConformanceResponse {
                            Skipped = "CSharp doesn't support skipping unknown fields in json parsing."
                        });
                    }
                    var parser = new JsonParser(new JsonParser.Settings(20, typeRegistry));
                    message = parser.Parse <ProtobufTestMessages.Proto3.TestAllTypesProto3>(request.JsonPayload);
                    break;

                case ConformanceRequest.PayloadOneofCase.ProtobufPayload:
                {
                    if (request.MessageType.Equals("protobuf_test_messages.proto3.TestAllTypesProto3"))
                    {
                        message = ProtobufTestMessages.Proto3.TestAllTypesProto3.Parser.ParseFrom(request.ProtobufPayload);
                    }
                    else if (request.MessageType.Equals("protobuf_test_messages.proto2.TestAllTypesProto2"))
                    {
                        return(new ConformanceResponse {
                                Skipped = "CSharp doesn't support proto2"
                            });
                    }
                    else
                    {
                        throw new Exception(" Protobuf request doesn't have specific payload type");
                    }
                    break;
                }

                case ConformanceRequest.PayloadOneofCase.TextPayload:
                {
                    return(new ConformanceResponse {
                            Skipped = "CSharp doesn't support text format"
                        });
                }

                default:
                    throw new Exception("Unsupported request payload: " + request.PayloadCase);
                }
            }
            catch (InvalidProtocolBufferException e)
            {
                return(new ConformanceResponse {
                    ParseError = e.Message
                });
            }
            catch (InvalidJsonException e)
            {
                return(new ConformanceResponse {
                    ParseError = e.Message
                });
            }
            try
            {
                switch (request.RequestedOutputFormat)
                {
                case global::Conformance.WireFormat.Json:
                    var formatter = new JsonFormatter(new JsonFormatter.Settings(false, typeRegistry));
                    return(new ConformanceResponse {
                        JsonPayload = formatter.Format(message)
                    });

                case global::Conformance.WireFormat.Protobuf:
                    return(new ConformanceResponse {
                        ProtobufPayload = message.ToByteString()
                    });

                default:
                    throw new Exception("Unsupported request output format: " + request.PayloadCase);
                }
            }
            catch (InvalidOperationException e)
            {
                return(new ConformanceResponse {
                    SerializeError = e.Message
                });
            }
        }
 static TemplateNamespaceParser()
 {
     TypeRegistry.RegisterType(TemplateTypePrefix + TemplateDefinitionConstants.NVelocityElement, typeof(VelocityEngineFactoryObject));
 }
Example #39
0
 public override void Setup(TypeRegistry r)
 {
     m_stringSerializer = (SerializerBase <string>)r.GetSerializer <String>();
 }
Example #40
0
		public void TypeRegistry()
		{
			TypeRegistry<object> myTypeRegistry = new TypeRegistry<object>();
			ExpectArgumentNull("key", delegate { myTypeRegistry.Register(null, 1); });
			ExpectArgumentNull("value", delegate { myTypeRegistry.Register(typeof(int), null); });
			ExpectArgumentNull("key", delegate { myTypeRegistry.Unregister((Type)null); });
			ExpectArgumentNull("value", delegate { myTypeRegistry.Unregister((object)null); });
			ExpectArgumentNull("key", delegate { myTypeRegistry.GetValue(null); });
			ExpectArgumentNull("key", delegate { myTypeRegistry.IsRegistered(null); });
			ExpectArgumentNull("key", delegate { myTypeRegistry[null] = 1; });
			ExpectArgumentNull("value", delegate { myTypeRegistry[typeof(int)] = null; });
		}
Example #41
0
 public KasbahNpgsqlQueryProvider(ILoggerFactory loggerFactory, Type targetType, NpgsqlSettings settings, TypeRegistry typeRegistry, TypeMapper typeMapper)
 {
     _log          = loggerFactory.CreateLogger <KasbahNpgsqlQueryProvider>();
     _targetType   = targetType;
     _settings     = settings;
     _typeRegistry = typeRegistry;
     _typeMapper   = typeMapper;
 }
Example #42
0
        private void button2_Click(object sender, EventArgs e)
        {
            var tr = new TypeRegistry(TypeRegistry.RecordModelTypes,
                                  TypeRegistry.CommonCollectionTypes,
                                  TypeRegistry.BoxedCommonTypes,
                                  TypeRegistry.BoxedCommonNullableTypes);
             tr.Add(typeof(PatientRecord));
             tr.Add(typeof(Person2));
             tr.Add(typeof(System.Drawing.Point));
             tr.Add(typeof(TimeSpan));
             tr.Add(typeof(Kozel));

              var p1 = PatientRecord.Make<PatientRecord>();// make();

              using (var ms = new FileStream(@"c:\NFX\PERSON2.slim", FileMode.Create) )//new MemoryStream())
              {
                var s = new SlimSerializer(tr);

                s.Serialize(ms, p1);

                var clk = Stopwatch.StartNew();

                for(var i=1; i<4000; i++)
                {
                  ms.Seek(0, SeekOrigin.Begin);
                  var p2 = s.Deserialize(ms);
                }
                Text = clk.ElapsedMilliseconds.ToString();

                //Text = p2.Name;
              }

              //BINARY formatterr

              using (var ms = new FileStream(@"c:\NFX\PERSON2.bin", FileMode.Create) ) //new MemoryStream())
              {
                var s = new BinaryFormatter();

                s.Serialize(ms, p1);

                var clk = Stopwatch.StartNew();

                for(var i=1; i<4000; i++)
                {
                  ms.Seek(0, SeekOrigin.Begin);
                  var p2 = s.Deserialize(ms);
                }
                Text += "        Binary formatter: " + clk.ElapsedMilliseconds.ToString();
              }
        }
Example #43
0
        /// <summary>
        /// Emits MetaHandle that contains type handle for reference handle only when this referenced is added to pool for the first time.
        /// Emits inlined string for strings and inlined value types for boxed objects.
        /// Emits additional array dimensions info for array refernces who's types are emitted for the first time
        /// </summary>
        public MetaHandle GetHandle(object reference, TypeRegistry treg, SlimFormat format, out Type type)
        {
            Debug.Assert(m_Mode == SerializationOperation.Serializing, "GetHandle() called while deserializing", DebugAction.Throw);

             if (reference==null)
             {
               type = null;
               return new MetaHandle(0);
             }

             type = reference.GetType();

             if (type == typeof(string))
             {
               return MetaHandle.InlineString(reference as string);
             }

             if (reference is Type)
             {
               var thandle = treg.GetTypeHandle(reference as Type);
               return MetaHandle.InlineTypeValue(thandle);
             }

             if (type.IsValueType)
             {
               var vth = treg.GetTypeHandle(type);
               return MetaHandle.InlineValueType(vth);
             }

             bool added;

             uint handle = (uint)getIndex(reference, out added);

             if (added)
             {
              var th =  treg.GetTypeHandle(type);

              if (format.IsRefTypeSupported(type))//20150305 Refhandle inline
                return MetaHandle.InlineRefType(th);

              if (type.IsArray)//write array header like so:  "System.int[,]|0~10,0~12" or "$3|0~10,0~12"
              {
                //DKh 20130712 Removed repetitive code that was refactored into Arrays class
                var arr = (Array)reference;
                th = new VarIntStr( Arrays.ArrayToDescriptor(arr, type, th) );
              }

              return new MetaHandle(handle, th);
             }
             return new MetaHandle(handle);
        }
Example #44
0
        public void AnyMessageType_CustomPrefix()
        {
            var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithTypeRegistry(TypeRegistry.FromMessages(TestAllTypes.Descriptor)));
            var message   = new TestAllTypes {
                SingleInt32 = 10
            };
            var any = Any.Pack(message, "foo.bar/baz");

            AssertJson("{ '@type': 'foo.bar/baz/protobuf_unittest3.TestAllTypes', 'singleInt32': 10 }", formatter.Format(any));
        }
Example #45
0
 /// <summary>
 /// Constructor of the client, initializes serializer types.
 /// </summary>
 /// <param name="serverCertificate">The server certificate.</param>
 protected Client(X509Certificate2 serverCertificate)
 {
     _serverCertificate = serverCertificate;
     _readBuffer        = new byte[BUFFER_SIZE];
     TypeRegistry.AddTypesToSerializer(typeof(IMessage), TypeRegistry.GetPacketTypes(typeof(IMessage)).ToArray());
 }
        /** <summary>
         *  Register a renderer for all objects of a particular type for all
         *  templates in this group.
         *  </summary>
         */
        public virtual void RegisterRenderer( Type objectType, IAttributeRenderer renderer )
        {
            if (_attributeRenderers == null)
                _attributeRenderers = new TypeRegistry<IAttributeRenderer>();

            _attributeRenderers[objectType] = renderer;
        }
Example #47
0
        private void button1_Click(object sender, EventArgs e)
        {
            var Frank = new Person
                          {
                            Name = "Frank Frankfurter",
                            Age = 99,
                            IsHappy = true,
                            MarriageDate = App.LocalizedTime,

                            Father = new Person { Name = "Zaxar Mai", Age = 44},

                            Type = typeof(System.Reflection.Assembly)
                          };

               var Marry = new Person
                          {
                            Name = "Marry Morra",
                            Age = 44,
                            IsHappy = false,
                            MarriageDate = App.LocalizedTime,

                            Father = Frank.Father,

                            Type = typeof(System.Diagnostics.Stopwatch)
                            //Buffer = new byte[] {10,13,65,65,65,65,65,65,65,65,66,66,66,66,66,66,66,66},
                            //Chars = new char[] {'i', ' ', 'a', 'm', ' ','!'}
                          };

               var Dodik = new Person
                          {
                            Name = "Dodik Kutzhenbukher",
                            Age = 12,
                            IsHappy = true,
                            MarriageDate = App.LocalizedTime.AddDays(-100),
                            Father = Frank,
                            Mother = Marry
                          };

              Marry.Mother = Dodik;//Cycle

              var rec = PatientRecord.Make<PatientRecord>();

            //Frank.Father.Items["Absukov"] = 123;
            //Frank.Father.Items["Bosurxevich"] = true;
            //Frank.Father.Items["Corshunovich"] = "ya est tot kto mojet byt";
            //Frank.Father.Items["Zmejukka"] = " do svazi!";

            //Dodik.IntArray = new int[10,10,10];

            //Dodik.IntArray[5,3,4] = 67;
            //Dodik.IntArray[9,9,9] = 65;

            //Dodik.ObjArray = new object[10];
            //for(int i=0; i<Dodik.ObjArray.Length; i++)
            // Dodik.ObjArray[i] = new Person{ Name = "Chelovek-"+(i%4).ToString(), Age = 1, Father = Dodik, IsHappy = true, MarriageDate = App.TimeSource.UTCNow};

            //for(int i=0; i<10; i++)
            // Dodik.Relatives.Add( new Person{ Name = "Solovei-"+(i%4).ToString(), Age = 1, Father = Dodik, IsHappy = true, MarriageDate = App.TimeSource.UTCNow} );

            //for(int i=0; i<1000; i++)
            // Dodik.Numbers.Add( 10000-i );

            var tr = new TypeRegistry(TypeRegistry.RecordModelTypes,
                                  TypeRegistry.CommonCollectionTypes,
                                  TypeRegistry.BoxedCommonTypes,
                                  TypeRegistry.BoxedCommonNullableTypes);

            tr.Add(typeof(PatientRecord));
            tr.Add(typeof(Person));
            tr.Add(typeof(Person2));
            tr.Add(typeof(Person[]));
            tr.Add(typeof(System.Collections.Generic.List<Person>));
            tr.Add(typeof(System.Drawing.Point));
            tr.Add(typeof(int[]));
            tr.Add(typeof(int[,,]));

            var data = PatientRecord.Make<PatientRecord>();// make();

             var clk = Stopwatch.StartNew();
            // for(var i=1; i<1000; i++)
               using (var fs = new FileStream(@"c:\NFX\SLIM.slim", FileMode.Create))
              {
                var s = new SlimSerializer(tr);

                for(var i=1; i<1000; i++)
                {
                  s.Serialize(fs,  data);//Dodik);
                }
              }
             Text = clk.ElapsedMilliseconds.ToString();

             clk.Restart();
               using (var fs = new FileStream(@"c:\NFX\FORMATTER.bin", FileMode.Create))
              {
                var bf = new BinaryFormatter();

                for(var i=1; i<1000; i++)
                {
                 bf.Serialize(fs, data);//Dodik);
                }
              }
             Text += "        Binary formatter: " + clk.ElapsedMilliseconds.ToString();
        }
Example #48
0
 private ApiMetadata(string name)
 {
     GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name));
     Name = name;
     _typeRegistryProvider = new Lazy <TypeRegistry>(() => TypeRegistry.FromFiles(ProtobufDescriptors));
 }
Example #49
0
        private void button3_Click(object sender, EventArgs e)
        {
            const int CNT = 1000;

              var lst = new TwitterMsg[CNT];
              for(var i=0; i<CNT; i++)
               lst[i] = ( new TwitterMsg
               {
             ID = new GDID(0, (ulong)i),
             AuthorID = new GDID(0, (ulong)i*251),
             Banned = i%45==0,
             Rating = i%5,
             ResponseToMsg = new GDID(0, (ulong)i),
             MsgText = NFX.Parsing.NaturalTextGenerator.Generate(0),
             When = DateTime.Now,
             ri_Deleted = false,
             ri_Host = "Zukini1234",
             ri_Version = DateTime.Now
               });

               var tr = new TypeRegistry(TypeRegistry.RecordModelTypes,
                                  TypeRegistry.CommonCollectionTypes,
                                  TypeRegistry.BoxedCommonTypes,
                                  TypeRegistry.BoxedCommonNullableTypes);
               tr.Add( typeof(GDID));
               tr.Add( typeof(TwitterMsg));

               var clk = Stopwatch.StartNew();
               using (var fs = new FileStream(@"c:\NFX\SLIM.slim", FileMode.Create, FileAccess.Write, FileShare.None, 1024*1024))
               {
                var s = new SlimSerializer(tr);

                s.Serialize(fs,  lst);
               }
               Text = "SLIM took {0} ms ".Args(clk.ElapsedMilliseconds);

              clk.Restart();
               using (var fs = new FileStream(@"c:\NFX\FORMATTER.bin", FileMode.Create, FileAccess.Write, FileShare.None, 1024*1024))
               {
             var bf = new BinaryFormatter();
             bf.Serialize(fs,  lst);
               }
               Text += "        Binary formatter took {0}ms ".Args(clk.ElapsedMilliseconds);
        }
Example #50
0
        private bool Execute(ConfigFile config)
        {
            config.GetFilesWithIncludesAndExtensionHeaders(
                out var configsWithHeaders,
                out var configsWithExtensionHeaders
                );

            var cppHeaderGenerator = new CppHeaderGenerator(SharpGenLogger, OutputPath);

            var cppHeaderGenerationResult = cppHeaderGenerator.GenerateCppHeaders(config, configsWithHeaders, configsWithExtensionHeaders);

            if (SharpGenLogger.HasErrors)
            {
                return(false);
            }

            var resolver = new IncludeDirectoryResolver(SharpGenLogger);

            resolver.Configure(config);

            var castXml = new CastXmlRunner(SharpGenLogger, resolver, CastXmlExecutable.ItemSpec, CastXmlArguments)
            {
                OutputPath = OutputPath
            };

            var macroManager = new MacroManager(castXml);

            var cppExtensionGenerator = new CppExtensionHeaderGenerator();

            var module = config.CreateSkeletonModule();

            macroManager.Parse(Path.Combine(OutputPath, config.HeaderFileName), module);

            cppExtensionGenerator.GenerateExtensionHeaders(
                config, OutputPath, module, configsWithExtensionHeaders, cppHeaderGenerationResult.UpdatedConfigs
                );

            GenerateInputsCache(
                macroManager.IncludedFiles
                .Concat(config.ConfigFilesLoaded.Select(x => x.AbsoluteFilePath))
                .Concat(configsWithExtensionHeaders.Select(x => Path.Combine(OutputPath, x.ExtensionFileName)))
                .Select(s => Utilities.FixFilePath(s, Utilities.EmptyFilePathBehavior.Ignore))
                .Where(x => x != null)
                .Distinct()
                );

            if (SharpGenLogger.HasErrors)
            {
                return(false);
            }

            // Run the parser
            var parser = new CppParser(SharpGenLogger, config)
            {
                OutputPath = OutputPath
            };

            if (SharpGenLogger.HasErrors)
            {
                return(false);
            }

            CppModule group;

            using (var xmlReader = castXml.Process(parser.RootConfigHeaderFileName))
            {
                // Run the C++ parser
                group = parser.Run(module, xmlReader);
            }

            if (SharpGenLogger.HasErrors)
            {
                return(false);
            }

            config.ExpandDynamicVariables(SharpGenLogger, group);

            var docLinker    = new DocumentationLinker();
            var typeRegistry = new TypeRegistry(SharpGenLogger, docLinker);
            var namingRules  = new NamingRulesManager();

            var globalNamespace = new GlobalNamespaceProvider();

            foreach (var nameOverride in GlobalNamespaceOverrides)
            {
                var wellKnownName = nameOverride.ItemSpec;
                var overridenName = nameOverride.GetMetadata("Override");

                if (string.IsNullOrEmpty(overridenName))
                {
                    continue;
                }

                if (Enum.TryParse(wellKnownName, out WellKnownName name))
                {
                    globalNamespace.OverrideName(name, overridenName);
                }
                else
                {
                    SharpGenLogger.Warning(
                        LoggingCodes.InvalidGlobalNamespaceOverride,
                        "Invalid override of \"{0}\": unknown class name, ignoring the override.",
                        wellKnownName
                        );
                }
            }

            // Run the main mapping process
            var transformer = new TransformManager(
                globalNamespace,
                namingRules,
                SharpGenLogger,
                typeRegistry,
                docLinker,
                new ConstantManager(namingRules, docLinker)
                );

            var(solution, defines) = transformer.Transform(group, config);

            var consumerConfig = new ConfigFile
            {
                Id            = ConsumerBindMappingConfigId,
                IncludeProlog = { cppHeaderGenerationResult.Prologue },
                Extension     = new List <ExtensionBaseRule>(defines)
            };

            var(bindings, generatedDefines) = transformer.GenerateTypeBindingsForConsumers();

            consumerConfig.Bindings.AddRange(bindings);
            consumerConfig.Extension.AddRange(generatedDefines);

            consumerConfig.Mappings.AddRange(
                docLinker.GetAllDocLinks().Select(
                    link => new MappingRule
            {
                DocItem          = link.cppName,
                MappingNameFinal = link.cSharpName
            }
                    )
                );

            GenerateConfigForConsumers(consumerConfig);

            if (SharpGenLogger.HasErrors)
            {
                return(false);
            }

            var documentationCacheItemSpec = DocumentationCache.ItemSpec;

            Utilities.RequireAbsolutePath(documentationCacheItemSpec, nameof(DocumentationCache));

            var cache = File.Exists(documentationCacheItemSpec)
                            ? DocItemCache.Read(documentationCacheItemSpec)
                            : new DocItemCache();

            DocumentationLogger docLogger = new(SharpGenLogger) { MaxLevel = LogLevel.Warning };
            var docContext = new Lazy <DocumentationContext>(() => new DocumentationContext(docLogger));

            ExtensibilityDriver.Instance.DocumentModule(SharpGenLogger, cache, solution, docContext).Wait();

            if (docContext.IsValueCreated)
            {
                Regex[] silencePatterns    = null;
                var     docLogLevelDefault = DocumentationFailuresAsErrors ? LogLevel.Error : LogLevel.Warning;

                foreach (var queryFailure in docContext.Value.Failures)
                {
                    if (silencePatterns == null)
                    {
                        silencePatterns = new Regex[SilenceMissingDocumentationErrorIdentifierPatterns.Length];
                        for (var i = 0; i < silencePatterns.Length; i++)
                        {
                            silencePatterns[i] = new Regex(
                                SilenceMissingDocumentationErrorIdentifierPatterns[i].ItemSpec,
                                RegexOptions.CultureInvariant
                                );
                        }
                    }

                    if (silencePatterns.Length != 0)
                    {
                        bool SilencePredicate(Regex x) => x.Match(queryFailure.Query).Success;

                        if (silencePatterns.Any(SilencePredicate))
                        {
                            continue;
                        }
                    }

                    var providerName = queryFailure.FailedProviderName ?? "<null>";

                    var docLogLevel = queryFailure.TreatProviderFailuresAsErrors
                                          ? docLogLevelDefault
                                          : docLogLevelDefault > LogLevel.Warning
                                              ? LogLevel.Warning
                                              : docLogLevelDefault;

                    if (queryFailure.Exceptions == null || queryFailure.Exceptions.Count <= 1)
                    {
                        SharpGenLogger.LogRawMessage(
                            docLogLevel,
                            LoggingCodes.DocumentationProviderInternalError,
                            "Documentation provider [{0}] query for \"{1}\" failed.",
                            queryFailure.Exceptions?.FirstOrDefault(),
                            providerName,
                            queryFailure.Query
                            );
                    }
                    else
                    {
                        var exceptionsCount = queryFailure.Exceptions.Count;
                        for (var index = 0; index < exceptionsCount; index++)
                        {
                            var exception = queryFailure.Exceptions[index];

                            SharpGenLogger.LogRawMessage(
                                docLogLevel,
                                LoggingCodes.DocumentationProviderInternalError,
                                "Documentation provider [{0}] query for \"{1}\" failed ({2}/{3}).",
                                exception,
                                providerName,
                                queryFailure.Query,
                                index + 1,
                                exceptionsCount
                                );
                        }
                    }
                }
            }

            cache.WriteIfDirty(documentationCacheItemSpec);

            if (SharpGenLogger.HasErrors)
            {
                return(false);
            }

            var documentationFiles = new Dictionary <string, XmlDocument>();

            foreach (var file in ExternalDocumentation)
            {
                using var stream = File.OpenRead(file.ItemSpec);

                var xml = new XmlDocument();
                xml.Load(stream);
                documentationFiles.Add(file.ItemSpec, xml);
            }

            PlatformDetectionType platformMask = 0;

            foreach (var platform in Platforms)
            {
                if (!Enum.TryParse <PlatformDetectionType>(platform.ItemSpec, out var parsedPlatform))
                {
                    SharpGenLogger.Warning(
                        LoggingCodes.InvalidPlatformDetectionType,
                        "The platform type {0} is an unknown platform to SharpGenTools. Falling back to Any platform detection.",
                        platform
                        );
                    platformMask = PlatformDetectionType.Any;
                }
                else
                {
                    platformMask |= parsedPlatform;
                }
            }

            if (platformMask == 0)
            {
                platformMask = PlatformDetectionType.Any;
            }

            if (SharpGenLogger.HasErrors)
            {
                return(false);
            }

            var generator = new RoslynGenerator(
                SharpGenLogger,
                globalNamespace,
                docLinker,
                new ExternalDocCommentsReader(documentationFiles),
                new GeneratorConfig
            {
                Platforms = platformMask
            }
                );

            generator.Run(solution, GeneratedCodeFolder);

            return(!SharpGenLogger.HasErrors);
        }
Example #51
0
 public TypeChecker(TypeRegistry typeRegistry)
 {
     unifier = new TypeUnifier();
     this.typeRegistry = typeRegistry;
     errorLog = new List<CompilerError>();
 }
Example #52
0
 public void Setup()
 {
     m_r = new TypeRegistry();
 }
Example #53
0
 private void ctor()
 {
    m_CurrentTypeRegistry = new TypeRegistry(
       TypeRegistry.BoxedCommonTypes,
       TypeRegistry.BoxedCommonNullableTypes,
       TypeRegistry.CommonCollectionTypes
    );
 }
Example #54
0
 /// <summary>
 /// Creates a new <see cref="Settings"/> instance.
 /// </summary>
 /// <param name="typeRegistry">
 /// Type registry to use when parsing <see cref="TypeConvertedValueExpressionAttribute"/> instances,
 /// or <c>null</c> to use <see cref="ValueExpressionParser.DefaultTypeRegistry"/>.
 /// </param>
 public Settings(TypeRegistry typeRegistry) : base("systemSettings", typeRegistry)
 {
 }
Example #55
0
 /// <summary>
 /// Registers the framework types with the given game IDs
 /// </summary>
 /// <param name="games">The game IDs to register the framework types with</param>
 public static void Register(params string[] games)
 {
     TypeRegistry.RegisterAssemblyTypes(typeof(SpeedFramework).Assembly, games);
 }
Example #56
0
 public virtual TypeRegistry AddTypes(TypeRegistry reg) => reg;
Example #57
0
        /// <summary>
        /// Returns object reference for supplied metahandle
        /// </summary>
        public object HandleToReference(MetaHandle handle, TypeRegistry treg, SlimFormat format, SlimReader reader)
        {
            Debug.Assert(m_Mode == SerializationOperation.Deserializing, "HandleToReference() called while serializing", DebugAction.Throw);

             if (handle.IsInlinedString) return handle.Metadata.Value.StringValue;
             if (handle.IsInlinedTypeValue)
             {
               var tref = treg[ handle.Metadata.Value ];//adding this type to registry if it is not there yet
               return tref;
             }

             if (handle.IsInlinedRefType)
             {
             var tref = treg[ handle.Metadata.Value ];//adding this type to registry if it is not there yet
             var ra = format.GetReadActionForRefType(tref);
             if (ra!=null)
             {
               var inst = ra(reader);
               m_List.Add(inst);
               return inst;
             }
             else
              throw new SlimDeserializationException("Internal error HandleToReference: no read action for ref type, but ref mhandle is inlined");
             }

             int idx = (int)handle.Handle;
             if (idx<m_List.Count) return m_List[idx];

             if (!handle.Metadata.HasValue)
              throw new SlimDeserializationException(StringConsts.SLIM_HNDLTOREF_MISSING_TYPE_NAME_ERROR + handle.ToString());

             Type type;
             var metadata = handle.Metadata.Value;

             if (metadata.StringValue!=null)//need to search for possible array descriptor
             {
            var ip = metadata.StringValue.IndexOf('|');//array descriptor start
            if (ip>0)
            {
              var tname =  metadata.StringValue.Substring(0, ip);
              if (TypeRegistry.IsNullHandle(tname)) return null;
              type = treg[ tname ];
            }
            else
            {
              if (TypeRegistry.IsNullHandle(metadata)) return null;
              type = treg[ metadata ];
            }
             }
             else
             {
            if (TypeRegistry.IsNullHandle(metadata)) return null;
            type = treg[ metadata ];
             }

             object instance = null;

             if (type.IsArray)
              //DKh 20130712 Removed repetitive code that was refactored into Arrays class
              instance = Arrays.DescriptorToArray(metadata.StringValue, type);
             else
              //20130715 DKh
              instance = SerializationUtils.MakeNewObjectInstance(type);

             m_List.Add(instance);
             return instance;
        }
 protected BaseNetworkObjectListManager(TypeRegistry typeRegistry)
 {
     TypeRegistry = typeRegistry ?? throw new ArgumentNullException(nameof(typeRegistry));
 }
        public virtual void RegisterTypeProxyFactory(Type originalObjectType, ITypeProxyFactory proxyFactory)
        {
            if (_proxyFactories == null)
                _proxyFactories = new TypeRegistry<ITypeProxyFactory>();

            _proxyFactories[originalObjectType] = proxyFactory;
        }
Example #60
0
        private void button1_Click(object sender, EventArgs e)
        {
            var Frank = new Person
            {
                Name         = "Frank Frankfurter",
                Age          = 99,
                IsHappy      = true,
                MarriageDate = App.LocalizedTime,

                Father = new Person {
                    Name = "Zaxar Mai", Age = 44
                },

                Type = typeof(System.Reflection.Assembly)
            };

            var Marry = new Person
            {
                Name         = "Marry Morra",
                Age          = 44,
                IsHappy      = false,
                MarriageDate = App.LocalizedTime,

                Father = Frank.Father,

                Type = typeof(System.Diagnostics.Stopwatch)
                       //Buffer = new byte[] {10,13,65,65,65,65,65,65,65,65,66,66,66,66,66,66,66,66},
                       //Chars = new char[] {'i', ' ', 'a', 'm', ' ','!'}
            };


            var Dodik = new Person
            {
                Name         = "Dodik Kutzhenbukher",
                Age          = 12,
                IsHappy      = true,
                MarriageDate = App.LocalizedTime.AddDays(-100),
                Father       = Frank,
                Mother       = Marry
            };

            Marry.Mother = Dodik;//Cycle



            //Frank.Father.Items["Absukov"] = 123;
            //Frank.Father.Items["Bosurxevich"] = true;
            //Frank.Father.Items["Corshunovich"] = "ya est tot kto mojet byt";
            //Frank.Father.Items["Zmejukka"] = " do svazi!";


            //Dodik.IntArray = new int[10,10,10];

            //Dodik.IntArray[5,3,4] = 67;
            //Dodik.IntArray[9,9,9] = 65;


            //Dodik.ObjArray = new object[10];
            //for(int i=0; i<Dodik.ObjArray.Length; i++)
            // Dodik.ObjArray[i] = new Person{ Name = "Chelovek-"+(i%4).ToString(), Age = 1, Father = Dodik, IsHappy = true, MarriageDate = App.TimeSource.UTCNow};

            //for(int i=0; i<10; i++)
            // Dodik.Relatives.Add( new Person{ Name = "Solovei-"+(i%4).ToString(), Age = 1, Father = Dodik, IsHappy = true, MarriageDate = App.TimeSource.UTCNow} );

            //for(int i=0; i<1000; i++)
            // Dodik.Numbers.Add( 10000-i );


            var tr = new TypeRegistry(TypeRegistry.CommonCollectionTypes,
                                      TypeRegistry.BoxedCommonTypes,
                                      TypeRegistry.BoxedCommonNullableTypes);

            tr.Add(typeof(Person));
            tr.Add(typeof(Person2));
            tr.Add(typeof(Person[]));
            tr.Add(typeof(System.Collections.Generic.List <Person>));
            tr.Add(typeof(System.Drawing.Point));
            tr.Add(typeof(int[]));
            tr.Add(typeof(int[, , ]));



            var data = make();

            var clk = Stopwatch.StartNew();

            // for(var i=1; i<1000; i++)
            using (var fs = new FileStream(@"c:\NFX\SLIM.slim", FileMode.Create))
            {
                var s = new SlimSerializer(tr);

                for (var i = 1; i < 1000; i++)
                {
                    s.Serialize(fs, data);//Dodik);
                }
            }
            Text = clk.ElapsedMilliseconds.ToString();

            clk.Restart();
            using (var fs = new FileStream(@"c:\NFX\FORMATTER.bin", FileMode.Create))
            {
                var bf = new BinaryFormatter();

                for (var i = 1; i < 1000; i++)
                {
                    bf.Serialize(fs, data);//Dodik);
                }
            }
            Text += "        Binary formatter: " + clk.ElapsedMilliseconds.ToString();
        }