public static void Constructor(string tool, string version)
        {
            GeneratedCodeAttribute gca = new GeneratedCodeAttribute(tool, version);

            Assert.Equal(tool, gca.Tool);
            Assert.Equal(version, gca.Version);
        }
Example #2
0
 public void TestGeneratedCodeAttributeTest()
 {
     GeneratedCodeAttribute gca = new GeneratedCodeAttribute("tool", "version");
     gca = new GeneratedCodeAttribute("tool", null);
     gca = new GeneratedCodeAttribute(null, "version");
     gca = new GeneratedCodeAttribute(null, null);
     Assert(gca.GetType().IsSubclassOf(typeof(System.Attribute)));
 }
        /// <summary>
        /// Generates the code.
        /// </summary>
        /// <param name="inputFileName">Name of the input file.</param>
        /// <param name="inputFileContent">Content of the input file.</param>
        /// <param name="renderMode">The render mode.</param>
        /// <param name="desiredNamespace">The desired namespace.</param>
        /// <returns></returns>
        public string GenerateCode(string inputFileName, string inputFileContent, RenderMode renderMode, string desiredNamespace)
        {
            inputFileContent = RemoveClass(inputFileContent);

            var parserContext = new ParserContext
            {
                BaseUri = new Uri(inputFileName, UriKind.Absolute)
            };

            object source = null;
            try
            {
                //source = XamlReader.Parse(inputFileContent); //, parserContext);
                using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(inputFileContent)))
                {
                    source = XamlReader.Load(stream, parserContext);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw;
            }

            if (source == null)
            {
                return "Source is empty. XAML file is not valid.";
            }

            Console.WriteLine();
            Console.WriteLine("Generating " + inputFileName);

            string resultCode = string.Empty;
            string className = Path.GetFileNameWithoutExtension(inputFileName);

            CodeNamespace ns = new CodeNamespace(desiredNamespace);
            ns.Imports.Add(new CodeNamespaceImport("System"));
            ns.Imports.Add(new CodeNamespaceImport("System.CodeDom.Compiler"));
            ns.Imports.Add(new CodeNamespaceImport("System.Collections.ObjectModel"));
            ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface"));
            ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Data"));
            ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Controls"));
            ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Controls.Primitives"));
            ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Input"));
            ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Media"));
            ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Media.Animation"));
            ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Media.Imaging"));
            ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Shapes"));
            ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Renderers"));
            ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Themes"));

            /*
            switch (renderMode)
            {
                case RenderMode.SunBurn:
                    ns.Imports.Add(new CodeNamespaceImport("SynapseGaming.SunBurn.Framework.Primitives"));
                    break;
                case RenderMode.MonoGame:
                    ns.Imports.Add(new CodeNamespaceImport("Microsoft.Xna.Framework"));
                    ns.Imports.Add(new CodeNamespaceImport("Microsoft.Xna.Framework.Graphics"));
                    break;
                default:
                    break;
            }
             */

            CodeTypeDeclaration classType = new CodeTypeDeclaration(className);

            GeneratedCodeAttribute generatedCodeAttribute =
            new GeneratedCodeAttribute("Empty Keys UI Generator", Assembly.GetExecutingAssembly().GetName().Version.ToString());

            CodeAttributeDeclaration codeAttrDecl =
                new CodeAttributeDeclaration(generatedCodeAttribute.GetType().Name,
                    new CodeAttributeArgument(
                        new CodePrimitiveExpression(generatedCodeAttribute.Tool)),
                    new CodeAttributeArgument(
                        new CodePrimitiveExpression(generatedCodeAttribute.Version)));
            classType.CustomAttributes.Add(codeAttrDecl);

            ns.Comments.Add(new CodeCommentStatement("-----------------------------------------------------------", false));
            ns.Comments.Add(new CodeCommentStatement(" ", false));
            ns.Comments.Add(new CodeCommentStatement(" This file was generated, please do not modify.", false));
            ns.Comments.Add(new CodeCommentStatement(" ", false));
            ns.Comments.Add(new CodeCommentStatement("-----------------------------------------------------------", false));

            CodeMemberMethod initMethod = null;
            if (source is UIRoot)
            {
                initMethod = CreateUIRootClass(ns, classType, renderMode);
                generator.ProcessGenerators(source, classType, initMethod, true);
            }
            else if (source is UserControl)
            {
                initMethod = CreateUserControlClass(ns, classType);
                generator.ProcessGenerators(source, classType, initMethod, true);
            }
            else if (source is ResourceDictionary)
            {
                initMethod = CreateDictionaryClass(ns, classType);

                ResourceDictionary dictionary = source as ResourceDictionary;
                if (dictionary != null)
                {
                    ResourceDictionaryGenerator resourcesGenerator = new ResourceDictionaryGenerator();
                    resourcesGenerator.Generate(dictionary, classType, initMethod, new CodeThisReferenceExpression());
                }
            }
            else
            {
                string errorText = "#error This type is not supported - " + source.GetType();
                Console.WriteLine(errorText);
                return errorText;
            }

            ImageAssets.Instance.GenerateManagerCode(initMethod);
            ImageAssets.Instance.ClearAssets();

            FontGenerator.Instance.GenerateManagerCode(initMethod);

            using (CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider())
            {
                string mappedFileName = memoryMappedFileName + className;
                using (MemoryMappedFile mappedFile = MemoryMappedFile.CreateNew(mappedFileName, nemoryMappedFileCapacity))
                {
                    MemoryMappedViewStream stream = mappedFile.CreateViewStream();

                    using (StreamWriter sw = new StreamWriter(stream))
                    {
                        provider.GenerateCodeFromNamespace(ns, sw, new CodeGeneratorOptions());
                    }

                    stream = mappedFile.CreateViewStream();

                    TextReader tr = new StreamReader(stream);
                    resultCode = tr.ReadToEnd();
                    resultCode = resultCode.Trim(new char());

                    tr.Close();
                }
            }

            return resultCode;
        }
		public void Constructor_Null_Version ()
		{
			GeneratedCodeAttribute gca = new GeneratedCodeAttribute ("Mono", null);
			Assert.AreEqual ("Mono", gca.Tool, "Tool");
			Assert.IsNull (gca.Version, "Version");
		}
		public void Constructor_Null_Tool ()
		{
			GeneratedCodeAttribute gca = new GeneratedCodeAttribute (null, "1.2");
			Assert.IsNull (gca.Tool, "Tool");
			Assert.AreEqual ("1.2", gca.Version, "Version");
		}
		public void Constructor ()
		{
			GeneratedCodeAttribute gca = new GeneratedCodeAttribute ("Mono", "1.2");
			Assert.AreEqual ("Mono", gca.Tool, "Tool");
			Assert.AreEqual ("1.2", gca.Version, "Version");
		}
Example #7
0
        private CodeTypeDeclaration CreateClass(string className)
        {
            CodeTypeDeclaration classType = new CodeTypeDeclaration(className);

            GeneratedCodeAttribute generatedCodeAttribute =
            new GeneratedCodeAttribute("Empty Keys UI Generator", Assembly.GetExecutingAssembly().GetName().Version.ToString());

            CodeAttributeDeclaration codeAttrDecl =
                new CodeAttributeDeclaration(generatedCodeAttribute.GetType().Name,
                    new CodeAttributeArgument(
                        new CodePrimitiveExpression(generatedCodeAttribute.Tool)),
                    new CodeAttributeArgument(
                        new CodePrimitiveExpression(generatedCodeAttribute.Version)));
            classType.CustomAttributes.Add(codeAttrDecl);

            classType.BaseTypes.Add(new CodeTypeReference("IPropertyInfo"));

            return classType;
        }
Example #8
0
		public virtual void Compile(IEnumerable<IColumInfoModel> columnInfos, Stream to = null)
		{
			if (to != null)
			{
				if (!to.CanSeek)
					throw new InvalidOperationException("The stream must be seekable");
				if (!to.CanWrite)
					throw new InvalidOperationException("The stream must be writeable");
			}

			this.PreCompile();
			if (string.IsNullOrEmpty(TableName))
			{
				TableName = TargetCsName;
			}

			var comments = (new[]
			{
				new CodeCommentStatement("Created by " + Environment.UserDomainName + @"\" + Environment.UserName),
				new CodeCommentStatement("Created on " + DateTime.Now.ToString("yyyy MMMM dd"))
			}).ToArray();

			//Create DOM class
			_base.Name = TargetCsName;

			if (CompileHeader)
				_base.Comments.AddRange(comments);

			//Write static members
			_base.TypeAttributes = TypeAttributes.Sealed | TypeAttributes.Public;
			_base.IsPartial = true;

			CodeNamespace importNameSpace;

			if (string.IsNullOrEmpty(Namespace))
			{
				importNameSpace = new CodeNamespace("JPB.DataAccess.EntryCreator.AutoGeneratedEntrys");
			}
			else
			{
				importNameSpace = new CodeNamespace(Namespace);
			}

			//Add Code Generated Attribute
			var generatedCodeAttribute = new GeneratedCodeAttribute(AttrbuteHeader, "1.0.0.8");
			var codeAttrDecl = new CodeAttributeDeclaration(generatedCodeAttribute.GetType().Name,
				new CodeAttributeArgument(
					new CodePrimitiveExpression(generatedCodeAttribute.Tool)),
				new CodeAttributeArgument(
					new CodePrimitiveExpression(generatedCodeAttribute.Version)));

			_base.CustomAttributes.Add(codeAttrDecl);
			//Add members

			if (GenerateConfigMethod)
			{
				GenerateConfigMehtod(columnInfos, importNameSpace);
			}
			else
			{
				if (!string.IsNullOrEmpty(TableName) && TableName != TargetCsName)
				{
					var forModel = new ForModelAttribute(TableName);
					var codeAttributeDeclaration = new CodeAttributeDeclaration(forModel.GetType().Name,
						new CodeAttributeArgument(new CodePrimitiveExpression(forModel.AlternatingName)));
					_base.CustomAttributes.Add(codeAttributeDeclaration);
				}
			}

			var compileUnit = new CodeCompileUnit();

			using (var memStream = new MemoryStream())
			{
				using (var writer = new StreamWriter(memStream, Encoding.UTF8, 128, true))
				{
					writer.NewLine = Environment.NewLine;

					var cp = new CompilerParameters();
					cp.ReferencedAssemblies.Add("System.dll");
					cp.ReferencedAssemblies.Add("System.Core.dll");
					cp.ReferencedAssemblies.Add("System.Data.dll");
					cp.ReferencedAssemblies.Add("System.Xml.dll");
					cp.ReferencedAssemblies.Add("System.Xml.Linq.dll");
					cp.ReferencedAssemblies.Add("JPB.DataAccess.dll");
					
					importNameSpace.Imports.Add(new CodeNamespaceImport("System"));
					importNameSpace.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
					importNameSpace.Imports.Add(new CodeNamespaceImport("System.CodeDom.Compiler"));
					importNameSpace.Imports.Add(new CodeNamespaceImport("System.Linq"));
					importNameSpace.Imports.Add(new CodeNamespaceImport("System.Data"));
					importNameSpace.Imports.Add(new CodeNamespaceImport(typeof(ForModelAttribute).Namespace));
					importNameSpace.Types.Add(_base);
					compileUnit.Namespaces.Add(importNameSpace);

					Provider.GenerateCodeFromCompileUnit(compileUnit, writer, new CodeGeneratorOptions() {
						BlankLinesBetweenMembers = false,
						BracingStyle = "C",
						IndentString = "	",
						VerbatimOrder = true,
						ElseOnClosing = true
					});

					Console.WriteLine("Generated class" + _base.Name);
					writer.Flush();
				}

				Console.WriteLine("Compute changes");
				//check if hascodes are diverent
				var hasher = MD5.Create();
				var neuHash = hasher.ComputeHash(memStream.ToArray());
				var targetFileName = Path.Combine(TargetDir, _base.Name + ".cs");
				if (to == null)
				{
					using (var fileStream = new FileStream(targetFileName, FileMode.OpenOrCreate))
					{
						var exisitingHash = hasher.ComputeHash(fileStream);
						if (!exisitingHash.SequenceEqual(neuHash))
						{
							Console.WriteLine("Class changed. Old file will be kept and new contnt will be written");
							fileStream.SetLength(0);
							fileStream.Flush();
							fileStream.Seek(0, SeekOrigin.Begin);
							memStream.WriteTo(fileStream);
							memStream.Flush();
							fileStream.Flush();
						}
					}
					
				}
				else
				{
					var exisitingHash = hasher.ComputeHash(to);
					if (WriteAllways || !exisitingHash.SequenceEqual(neuHash))
					{
						Console.WriteLine("Class changed. Old file will be kept and new contnt will be written");
						to.SetLength(0);
						to.Flush();
						to.Seek(0, SeekOrigin.Begin);
						memStream.WriteTo(to);
						memStream.Flush();
						to.Flush();
					}
				}
			}
		}
        private static void AddGeneratedCodeAttribute(CodeTypeDeclaration targetClass)
        {
            GeneratedCodeAttribute generatedCodeAttribute =
                new GeneratedCodeAttribute(typeof(HttpRestClientCodeGenerator).FullName, "1.0.0.0");

            // Use the generated code attribute members in the attribute declaration
            CodeAttributeDeclaration codeAttrDecl =
                new CodeAttributeDeclaration(generatedCodeAttribute.GetType().FullName,
                                             new CodeAttributeArgument(
                                                 new CodePrimitiveExpression(generatedCodeAttribute.Tool)),
                                             new CodeAttributeArgument(
                                                 new CodePrimitiveExpression(generatedCodeAttribute.Version)));
            targetClass.CustomAttributes.Add(codeAttrDecl);
        }