Exemple #1
0
        public List <WriterBase> GetWriters()
        {
            var pw = new PropertyWriter($"Items", $"{Control.ClassName}[]")
            {
                PrivateGetter = false,
                PrivateSetter = true,
                HasSetter     = true,
                HasGetter     = true
            };

            pw.Help.Summary = $"Gets the array of <see cref=\"{Control.ClassName}\"/> items in the list.";

            var tw = new TextWriter($"Items = new {Control.ClassName}[{Quantity}]");

            tw.Text.Add("{");

            for (var i = 0; i < Quantity; i++)
            {
                var digital = (i * DigitalStep) + Control.DigitalOffset;
                var analog  = (i * AnalogStep) + Control.AnalogOffset;
                var serial  = (i * SerialStep) + Control.SerialOffset;
                tw.Text.Add($"\tnew {Control.ClassName}(ParentPanel, {digital}, {analog}, {serial}, {i}){(i < Quantity - 1 ? "," : "")}");
            }

            tw.Text.Add("};");
            return(new List <WriterBase>()
            {
                pw, tw
            });
        }
Exemple #2
0
        public void PropertyWriter()
        {
            PropertyWriter writer = new PropertyWriter();

            writer.Write(new PropertyTemplate(null, "test", Code.Type("type")), this.output);
            Assert.AreEqual("public type test { get; set; }", this.output.ToString());
        }
        public void Basics()
        {
            var property = new PropertyWriter {
                Name = "MyProperty", IsPublic = true, PropertyType = TypeReferenceWriter.IntPtr, HasGet = true, HasSet = true
            };

            property.GetBody.Add("return IntPtr.Zero;");
            property.SetBody.Add("this.Handle = value;");

            var sw     = new StringWriter();
            var writer = new CodeWriter(sw);

            property.Write(writer);

            Console.WriteLine(sw.ToString());

            var expected =
                @"public IntPtr MyProperty {
	get { return IntPtr.Zero; }
	set { this.Handle = value; }
}
";

            Assert.AreEqual(expected, sw.ToString());
        }
Exemple #4
0
        void AddProperties(Method method, CodeGenerationOptions opt)
        {
            foreach (var p in method.Parameters)
            {
                if (p.IsSender)
                {
                    continue;
                }

                // We've already added this property from a different overload
                if (Properties.Any(prop => prop.Name == p.PropertyName))
                {
                    continue;
                }

                Fields.Add(new FieldWriter {
                    Name = opt.GetSafeIdentifier(p.Name),
                    Type = new TypeReferenceWriter(opt.GetTypeReferenceName(p))
                });

                var prop = new PropertyWriter {
                    Name         = p.PropertyName,
                    PropertyType = new TypeReferenceWriter(opt.GetTypeReferenceName(p)),
                    IsPublic     = true,
                    HasGet       = true
                };

                prop.GetBody.Add($"return {opt.GetSafeIdentifier (p.Name)};");

                Properties.Add(prop);
            }
        }
Exemple #5
0
        public void SetValue_Indexer2D()
        {
            var reader = new PropertyWriter <Foo>();
            var foo    = new Foo();

            reader.SetValue(foo, null, 2, 1, 2);
            Assert.AreEqual(4, foo.Ints[1]);
        }
        /// <summary>
        /// Process the generator.
        /// </summary>
        /// <param name="projectFile">The project file to work from.</param>
        public void Generate(string projectFile)
        {
            this.logger.LogInformation($"Loading {Path.GetFileName(projectFile)}...");

            var projectFolder = Path.GetDirectoryName(projectFile);

            // First we need to register the project.
            var project = this.workspace.RegisterProject(projectFile);

            // Register the pattern interface.
            var patternInterfaceDeclaration = this.workspace.RegisterFile("./Patterns/Itf/IModelPattern.cs")
                                              .Declarations.Single() as IInterfaceDeclaration;

            // Register the pattern implementation.
            var patternImplementationDeclaration = this.workspace.RegisterFile("./Patterns/Impl/ModelPattern.cs")
                                                   .Declarations.Single() as IGenericDeclaration <SyntaxNode>;

            // Load the project and its project dependencies. (Note that for now we only load the sources.
            // The binary assembly dependencies are not taken into account)
            var resolver = this.workspace.DeepLoad();

            // Get the base interface in order to find all extended interfaces that need to be implemented.
            var modelBaseInterface = resolver.Find("SoloX.GeneratorTools.Core.CSharp.Examples.Core.IModelBase").Single() as IGenericDeclaration <SyntaxNode>;

            // Setup a locator that will tell the location where the generated classes must be written.
            var locator = new RelativeLocator(projectFolder, project.RootNameSpace, suffix: "Impl");

            // Create the Implementation Generator with a file generator, the locator and the pattern interface/class.
            var generator = new ImplementationGenerator(
                new FileGenerator(".generated.cs"),
                locator,
                patternInterfaceDeclaration,
                patternImplementationDeclaration);

            // Loop on all interface extending the base interface.
            foreach (var modelInterface in modelBaseInterface.ExtendedBy.Where(d => d != patternInterfaceDeclaration))
            {
                this.logger.LogInformation(modelInterface.FullName);

                var implName = GeneratorHelper.ComputeClassName(modelInterface.Name);

                // Create the property writer what will use all properties from the model interface to generate
                // and write the corresponding code depending on the given patterns.
                var propertyWriter = new PropertyWriter(
                    patternInterfaceDeclaration.Properties.Single(),
                    modelInterface.Properties);

                // Setup some basic text replacement writer.
                var itfNameWriter  = new StringReplaceWriter(patternInterfaceDeclaration.Name, modelInterface.Name);
                var implNameWriter = new StringReplaceWriter(patternImplementationDeclaration.Name, implName);

                // Create the writer selector.
                var writerSelector = new WriterSelector(propertyWriter, itfNameWriter, implNameWriter);

                // And generate the class implementation.
                generator.Generate(writerSelector, (IInterfaceDeclaration)modelInterface, implName);
            }
        }
Exemple #7
0
        public void PropertyDefaultValue()
        {
            PropertyTemplate template = new PropertyTemplate(null, "test", Code.Type("type"));

            template.DefaultValue = Code.String("value");
            PropertyWriter writer = new PropertyWriter();

            writer.Write(template, this.output);
            Assert.AreEqual("public type test { get; set; } = \"value\";", this.output.ToString());
        }
Exemple #8
0
        public void SetValue_Property()
        {
            var reader = new PropertyWriter <Foo>();
            var foo    = new Foo
            {
                Bar = "baz"
            };

            reader.SetValue(foo, nameof(Foo.Bar), "qux");

            Assert.AreEqual("qux", foo.Bar);
        }
Exemple #9
0
        void WriteArray(Array array, Type elementType, PropertyWriter writer)
        {
            stream.Write(array.Length);

            var  size     = array.Length * Marshal.SizeOf(elementType);
            bool compress = size >= CompressionThreshold;

            stream.Write(compress ? 1 : 0);

            var sw = stream;
            DeflateWithChecksum codec = null;

            var compressLengthPos = stream.BaseStream.Position;

            stream.Write(size);             // Placeholder compressed length
            var dataStart = stream.BaseStream.Position;

            if (compress)
            {
                stream.Write(new byte[] { 0x58, 0x85 }, 0, 2);                 // Header bytes for DeflateStream settings
                codec = new DeflateWithChecksum(stream.BaseStream, CompressionMode.Compress, true);
                sw    = new BinaryWriter(codec);
            }

            foreach (var obj in array)
            {
                writer(sw, obj);
            }

            if (compress)
            {
                codec.Close();                 // This is important - otherwise bytes can be incorrect
                var    checksum = codec.Checksum;
                byte[] bytes    =
                {
                    (byte)((checksum >> 24) & 0xFF),
                    (byte)((checksum >> 16) & 0xFF),
                    (byte)((checksum >> 8) & 0xFF),
                    (byte)(checksum & 0xFF),
                };

                stream.Write(bytes);
            }

            // Now we can write the compressed data length, since we know the size
            if (compress)
            {
                var dataEnd = stream.BaseStream.Position;
                stream.BaseStream.Position = compressLengthPos;
                stream.Write((int)(dataEnd - dataStart));
                stream.BaseStream.Position = dataEnd;
            }
        }
Exemple #10
0
        private T ReadItem()
        {
            T item = Activator.CreateInstance <T>();
            PropertyWriter <T> writer = new PropertyWriter <T>(item);

            for (int i = 0; i < reader.FieldCount; i++)
            {
                String columnName = reader.GetName(i);
                Type   columnType = reader.GetFieldType(i);
                object value      = reader.GetValue(i);
                writer.Write(columnName, columnType, value);
            }

            return(item);
        }
        private static IWriterSelector SetupWriterSelector(
            IInterfaceDeclaration itfPatternDeclaration,
            IClassDeclaration implPatternDeclaration,
            IInterfaceDeclaration itfDeclaration,
            string implName)
        {
            var propertyWriter = new PropertyWriter(
                itfPatternDeclaration.Properties.Single(),
                itfDeclaration.Properties.ToArray());

            var itfNameWriter  = new StringReplaceWriter(itfPatternDeclaration.Name, itfDeclaration.Name);
            var implNameWriter = new StringReplaceWriter(implPatternDeclaration.Name, implName);

            return(new WriterSelector(propertyWriter, itfNameWriter, implNameWriter));
        }
        public bool MapValueItem(string item)
        {
            if (IsValueOptionDefined &&
                _valueOptionIndex < _valueOptionAttributeList.Count)
            {
                var valueOption = _valueOptionAttributeList[_valueOptionIndex++];

                var propertyWriter = new PropertyWriter(valueOption.Left, _parsingCulture);

                return ReflectionHelper.IsNullableType(propertyWriter.Property.PropertyType) ?
                    propertyWriter.WriteNullable(item, _target) :
                    propertyWriter.WriteScalar(item, _target);
            }

            return IsValueListDefined && AddValueItem(item);
        }
Exemple #13
0
            public void Write(StringBuilder sb, Type source)
            {
                PropertyInfo[] pis = source.GetProperties(BindingFlags.Public | BindingFlags.Instance);
                if (pis.IsEmptyList())
                {
                    return;
                }

                sb.Append("export interface ")
                .Append(source.Name)
                .Append(" { ");

                PropertyWriter pw = new PropertyWriter();

                foreach (PropertyInfo pi in pis)
                {
                    sb.AppendLine();
                    pw.Write(sb, pi);
                }

                sb.AppendLine().Append("}");
            }
        public OptionInfo(BaseOptionAttribute attribute, PropertyInfo property, CultureInfo parsingCulture)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException("attribute", SR.ArgumentNullException_AttributeCannotBeNull);
            }

            if (property == null)
            {
                throw new ArgumentNullException("property", SR.ArgumentNullException_PropertyCannotBeNull);
            }

            _required = attribute.Required;
            _shortName = attribute.ShortName;
            _longName = attribute.LongName;
            _mutuallyExclusiveSet = attribute.MutuallyExclusiveSet;
            _defaultValue = attribute.DefaultValue;
            _hasDefaultValue = attribute.HasDefaultValue;
            _attribute = attribute;
            _property = property;
            _parsingCulture = parsingCulture;
            _propertyWriter = new PropertyWriter(_property, _parsingCulture);
        }
Exemple #15
0
		void WriteArray(Array array, Type elementType, PropertyWriter writer)
		{
			stream.Write(array.Length);
			
			var size = array.Length*Marshal.SizeOf(elementType);
			bool compress = size >= CompressionThreshold;
			stream.Write(compress ? 1 : 0);

			var sw = stream;
			DeflateWithChecksum codec = null;

			var compressLengthPos = stream.BaseStream.Position;
			stream.Write(0); // Placeholder compressed length
			var dataStart = stream.BaseStream.Position;
			if (compress)
			{
				stream.Write(new byte[] { 0x58, 0x85 }, 0, 2); // Header bytes for DeflateStream settings
				codec = new DeflateWithChecksum(stream.BaseStream, CompressionMode.Compress, true);
				sw = new BinaryWriter(codec);
			}
			foreach (var obj in array)
				writer(sw, obj);
			if (compress)
			{
				codec.Close(); // This is important - otherwise bytes can be incorrect
				var checksum = codec.Checksum;
				byte[] bytes =
				{
					(byte)((checksum >> 24) & 0xFF),
					(byte)((checksum >> 16) & 0xFF),
					(byte)((checksum >> 8) & 0xFF),
					(byte)(checksum & 0xFF),
				};
				stream.Write(bytes);
			}
			
			// Now we can write the compressed data length, since we know the size
			if (compress)
			{
				var dataEnd = stream.BaseStream.Position;
				stream.BaseStream.Position = compressLengthPos;
				stream.Write((int)(dataEnd - dataStart));
				stream.BaseStream.Position = dataEnd;
			}
		}
 public static void Blank(this PropertyWriter ignored)
 {
     Console.WriteLine();
 }
Exemple #17
0
        void WriteArray(Array array, Type elementType, PropertyWriter writer)
        {
            stream.Write(array.Length);

            int itemSize;

            if (elementType.Equals(typeof(byte)))
            {
                itemSize = sizeof(byte);
            }
            else if (elementType.Equals(typeof(int)))
            {
                itemSize = sizeof(int);
            }
            else if (elementType.Equals(typeof(long)))
            {
                itemSize = sizeof(long);
            }
            else if (elementType.Equals(typeof(float)))
            {
                itemSize = sizeof(float);
            }
            else if (elementType.Equals(typeof(double)))
            {
                itemSize = sizeof(double);
            }
            else if (elementType.Equals(typeof(bool)))
            {
                itemSize = sizeof(bool);
            }
            else
            {
                throw new NotSupportedException("Unsupported type");
            }

            var  size     = array.Length * itemSize;
            bool compress = size >= CompressionThreshold;

            stream.Write(compress ? 1 : 0);
            if (compress)
            {
                var compressLengthPos = stream.BaseStream.Position;
                stream.Write(0);                 // Placeholder
                var dataStart = stream.BaseStream.Position;
                stream.Write(new byte[] { 0x58, 0x85 }, 0, 2);

                uint checksum;

                using (var codec = new DeflateStream(stream.BaseStream, CompressionMode.Compress, true))
                    using (var binaryWriter = new ChecksumBinaryWriter(codec))
                    {
                        foreach (var obj in array)
                        {
                            writer(binaryWriter, obj);
                        }
                        checksum = binaryWriter.Checksum;
                    }

                byte[] bytes =
                {
                    (byte)((checksum >> 24) & 0xFF),
                    (byte)((checksum >> 16) & 0xFF),
                    (byte)((checksum >> 8) & 0xFF),
                    (byte)(checksum & 0xFF),
                };
                stream.Write(bytes);

                var dataEnd = stream.BaseStream.Position;
                stream.BaseStream.Position = compressLengthPos;
                var compressedLength = (int)(dataEnd - dataStart);
                stream.Write(compressedLength);
                stream.BaseStream.Position = dataEnd;
            }
            else
            {
                stream.Write(array.Length * itemSize);
                foreach (var obj in array)
                {
                    writer(stream, obj);
                }
            }
        }
Exemple #18
0
 private void CreateMapIfNotDone()
 {
     _setter = PropertyCallerCache.SetterOfType(_typeofT);
 }
Exemple #19
0
 public static PropertyWriter And <T>(this PropertyWriter ignored, Expression <Func <T> > expr)
 {
     ConsoleHelper.WritePropertyToConsole(expr);
     return(null);
 }
Exemple #20
0
 public WriterInfo(char id, PropertyWriter writer)
 {
     this.id     = id;
     this.writer = writer;
 }
Exemple #21
0
			public WriterInfo(char id, PropertyWriter writer)
			{
				this.id = id;
				this.writer = writer;
			}