Compile and Run

using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
 
        private void displaySyntax(TreeNodeCollection target, SyntaxNode node)
        {
            TreeNode branch = new TreeNode ();
            branch.Text = node.ToString ();
            branch.Tag = node;
 
            target.Add (branch);
 
            foreach (SyntaxNode item in node.ChildNodes())
                displaySyntax (branch.Nodes, item);
        }
 
        private void runMenu_Click(object sender, EventArgs e)
        {
            info.Clear();
            tabs.SelectedTab = editorPage;
 
            string source = edit.Text;
            var syntaxTree = CSharpSyntaxTree.ParseText(source);
 
            string code = syntaxTree.ToString();
            // print(code);
            displaySyntax(tree.Nodes, syntaxTree.GetRoot());
 
            CSharpCompilation compilation = CSharpCompilation.Create(
                "assemblyName",
                new[] { syntaxTree },
                new[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location) },
                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
 
            using (var dllStream = new MemoryStream())
            using (var pdbStream = new MemoryStream())
            {
                var emitResult = compilation.Emit(dllStream, pdbStream);
                if (! emitResult.Success)
                {
                    print("ERROR");
                    foreach (var diagnostic in emitResult.Diagnostics)
                        print (diagnostic.ToString());
                }
                else
                {
                    print("O.K.");
                    dllStream.Seek(0, SeekOrigin.Begin);
 
                    // Load the compiled assembly
                    var assembly = Assembly.Load (dllStream.ToArray());
 
                    // Execute the library code
                    var libraryClassType = assembly.GetType("MyNamespace.MyClass");
                    var libraryInstance = Activator.CreateInstance (libraryClassType);
                    var libraryMethod = libraryClassType.GetMethod ("MyMethod");
                    var result = libraryMethod.Invoke (libraryInstance, null);
                    print ("RESULT: " + result);
                }
 
                foreach (var diagnostic in emitResult.Diagnostics)
                {
                    Console.WriteLine(diagnostic.ToString());
                }
            }
 
        }
            edit.Text = 
            @"
            namespace MyNamespace
            {
                public class MyClass
                {
                    public string MyMethod ()
                    {
                        return ""Hello, World!"";
                    }
                }
            }
            ";

nuget packages

https://dist.nuget.org/win-x86-commandline/latest/nuget.exe

nuget restore

Pripadne vymazat c:\Users\…\AppData\Roaming\NuGet\NuGet.Config

Registered Sources:
  1.  nuget.org [Enabled]
      https://api.nuget.org/v3/index.json
  ...
c:\Users\...\AppData\Roaming\NuGet\NuGet.Config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
  </packageSources>
</configuration>

Design-And-Compile from repository pw-2023

Designer.csproj from Visual Studio 2022
<Project Sdk="Microsoft.NET.Sdk">
 
  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net6.0-windows</TargetFramework>
    <Nullable>enable</Nullable>
    <UseWindowsForms>true</UseWindowsForms>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
 
  <ItemGroup>
    <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.8.0" />
  </ItemGroup>
 
</Project>
packages Microsoft.CodeAnalysis.CSharp (4.8.0)

Solution Explorer, Designer project, right click, Manage Nuget Packages

Compiler from repository pw-sharpdevelop

packages.config from pw-sharpdevelop
<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.CodeAnalysis.Analyzers" version="2.9.4" targetFramework="net472" developmentDependency="true" />
  <package id="Microsoft.CodeAnalysis.Common" version="3.3.1" targetFramework="net472" />
  <package id="Microsoft.CodeAnalysis.CSharp" version="3.3.1" targetFramework="net472" />
  <package id="System.Buffers" version="4.4.0" targetFramework="net472" />
  <package id="System.Collections.Immutable" version="1.5.0" targetFramework="net472" />
  <package id="System.Memory" version="4.5.3" targetFramework="net472" />
  <package id="System.Numerics.Vectors" version="4.4.0" targetFramework="net472" />
  <package id="System.Reflection.Metadata" version="1.6.0" targetFramework="net472" />
  <package id="System.Runtime.CompilerServices.Unsafe" version="4.5.2" targetFramework="net472" />
  <package id="System.Text.Encoding.CodePages" version="4.5.1" targetFramework="net472" />
  <package id="System.Threading.Tasks.Extensions" version="4.5.3" targetFramework="net472" />
</packages>
compiler.csproj from pw-sharpdevelop
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
 
    <Reference Include="Microsoft.CodeAnalysis.CSharp, Version=3.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>packages\Microsoft.CodeAnalysis.CSharp.3.3.1\lib\netstandard2.0\Microsoft.CodeAnalysis.CSharp.dll</HintPath>
    </Reference>
 
</Project>

https://stackoverflow.com/questions/32769630/how-to-compile-a-c-sharp-file-with-roslyn-programmatically

https://stackoverflow.com/questions/4181668/execute-c-sharp-code-at-runtime-from-code-file

https://www.linkedin.com/pulse/load-compile-run-c-code-dynamically-munib-butt

https://github.com/dotnet/roslyn/blob/main/src/Compilers/CSharp/Portable/Compilation/CSharpCompilation.cs#L340

dotnet7.0-7.0.104-1.fc38.src.rpm

https://github.com/roslynpad/roslynpad/blob/main/src/RoslynPad.Roslyn/Compiler.cs#L63

https://www.nuget.org/downloads

https://dist.nuget.org/win-x86-commandline/latest/nuget.exe

Selected properties

namespace Designer
{
    internal interface ISelectedProperties
    {
 
        List<string> selectedProperites();
    }
}
    public partial class Box : UserControl, ISelectedProperties
    {
        List<string> ISelectedProperties.selectedProperites()
        { 
            return new List<string> { "BackColor" };  
        }
    }
using System;
using System.Collections.Generic; // List
using System.ComponentModel; // ICustomTypeDescriptor
 
// https://www.codeproject.com/Articles/13342/Filtering-properties-in-a-PropertyGrid
 
namespace Designer
{ 
    public class ObjectWrapper : ICustomTypeDescriptor
    {
            private object obj = null;
 
            private List<string> selected_names = new List<string>() { "Name", "Text", "BackColor", "Size" };
 
            public ObjectWrapper (object param)
            {
                obj = param;
            }
 
            #region ICustomTypeDescriptor Members
            public PropertyDescriptorCollection GetProperties (Attribute[] attributes)
            {
                return GetProperties ();
            }
 
            public PropertyDescriptorCollection GetProperties ()
            {
               PropertyDescriptorCollection input = TypeDescriptor.GetProperties(obj);
               PropertyDescriptor[] inputArray = new PropertyDescriptor[input.Count];
               input.CopyTo (inputArray, 0);
 
               PropertyDescriptor[] outputArray = new PropertyDescriptor[1];
               outputArray[0] = inputArray[0];
 
               PropertyDescriptorCollection output = new PropertyDescriptorCollection(outputArray, true);
               List<string> names = selected_names;
 
               if (obj is ISelectedProperties)
                  names = (obj as ISelectedProperties).selectedProperites();
 
               foreach (PropertyDescriptor item in input)
                  if (names.Contains (item.Name))
                     output.Add (item);
 
               return output;
            }
 
            public AttributeCollection GetAttributes ()
            {
                return TypeDescriptor.GetAttributes (obj, true);
            }
 
            public String GetClassName ()
            {
                return TypeDescriptor.GetClassName (obj, true);
            }
 
            public String GetComponentName ()
            {
                return TypeDescriptor.GetComponentName (obj, true);
            }
 
            public TypeConverter GetConverter ()
            {
                return TypeDescriptor.GetConverter (obj, true);
            }
 
            public EventDescriptor GetDefaultEvent ()
            {
                return TypeDescriptor.GetDefaultEvent (obj, true);
            }
 
            public PropertyDescriptor GetDefaultProperty ()
            {
                return TypeDescriptor.GetDefaultProperty (obj, true);
            }
 
            public object GetEditor (Type editorBaseType)
            {
                return TypeDescriptor.GetEditor (this, editorBaseType, true);
            }
 
            public EventDescriptorCollection GetEvents (Attribute[] attributes)
            {
                return TypeDescriptor.GetEvents (obj, attributes, true);
            }
 
            public EventDescriptorCollection GetEvents ()
            {
                return TypeDescriptor.GetEvents (obj, true);
            }
 
            public object GetPropertyOwner (PropertyDescriptor pd)
            {
                return obj;
            }
 
            #endregion
        }
    }

ICustomTypeDescriptor

WinForms Designer

DesignSurface

Color button

namespace Designer
{
    public partial class ColorButton : ToolStripButton // UserControl
    {
        private Color color;
 
        public ColorButton (Color c, String name = "")
        {
            InitializeComponent ();
            color = c;
 
            const int size = 32;
            Bitmap img = new Bitmap (size, size);
            Graphics g = Graphics.FromImage (img);
            g.FillEllipse (new SolidBrush (color), 1, 1, size - 2, size - 2);
 
            this.Image = img;
            // this.Text = name;
            this.ToolTipText = name;
 
            this.MouseDown += ColorButton_MouseDown;
        }
 
        private void ColorButton_MouseDown (object sender, MouseEventArgs e)
        {
            DoDragDrop (color, DragDropEffects.All);
        }
    }
}

Factory button

namespace Designer
{
    public class Factory : ToolStripButton
    {
        private Type ComponentType;
        private string ComponentName;
 
        public Factory(Type type0)
        {
            ComponentType = type0;
            ComponentName = ComponentType.Name;
 
            this.Text = ComponentName;
            this.ToolTipText = ComponentName;
 
            // icon
            AttributeCollection attrCol = TypeDescriptor.GetAttributes (ComponentType);
            ToolboxBitmapAttribute imageAttr = attrCol [typeof (ToolboxBitmapAttribute)] as ToolboxBitmapAttribute;
            if (imageAttr != null)
            {
                this.Image = imageAttr.GetImage (ComponentType);
                this.Text = "";
            }
 
            this.MouseDown += this.Factory_MouseDown;
        }
        private void Factory_MouseDown(object sender, MouseEventArgs e)
        {
            DoDragDrop (this, DragDropEffects.All);
        }
 
        public object createInstance  ()
        {
            object result = Activator.CreateInstance (ComponentType);
 
            if (result is Box)
            {
                Box box = result as Box;
                box.Width = 80;
                box.Height = 40;
            }
            else if (result is Panel)
            {
                Panel p = result as Panel;
                p.Width = 80;
                p.Height = 40;
                p.BackColor = Color.CornflowerBlue;
                p.BorderStyle = BorderStyle.Fixed3D;
            }
 
            return result;
        }
 
    }
}

Drag and Drop

        private void Box_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(Color)))
                e.Effect = DragDropEffects.Move;
            else if (e.Data.GetDataPresent (DataFormats.Text))
                e.Effect = DragDropEffects.Copy;
            else if (e.Data.GetDataPresent(typeof (ToolStripItem)))
                e.Effect = DragDropEffects.Copy;
            // else
            //    e.Effect = DragDropEffects.None;
 
            /*
            if (info != null)
                foreach (var f in e.Data.GetFormats ())
                {
                    info.AppendText(f.ToString() + "\r\n");
                }
            */
        }
 
        private void Box_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(Color)))
            {
                BackColor = (Color) e.Data.GetData(typeof(Color));
            }
            else if (e.Data.GetDataPresent (DataFormats.Text))
            {
                string s = (string) e.Data.GetData(DataFormats.Text);
 
                Button btn = new Button();
                btn.Text = s;
                btn.Parent = this;
 
                Point location = PointToClient (new Point (e.X, e.Y));
                btn.Location = location;
            }
            else if (e.Data.GetDataPresent(typeof (ToolStripItem)))
            {
                ToolStripItem tool = e.Data.GetData (typeof (ToolStripItem)) as ToolStripItem;
                if (tool is Factory)
                {
                    Factory factory = tool as Factory;
                    Point location = PointToClient (new Point(e.X, e.Y));
 
                    Object obj = factory.createInstance ();
                    if (obj is Control)
                    {
                        Control ctl = obj as Control;
                        ctl.Location = location;
                        ctl.Parent = this;
 
                        // new Adapter (ctl);
                    }
                }
            }
 
        }
 
pw/compile.txt · Last modified: 2023/12/11 17:25 by 147.32.8.110
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki