Beispiel #1
0
        static void Main(string[] args)
        {
            var libDir = args.Length == 0 ? GetLibraryDirectory() : args[0];

            if (!Directory.Exists(libDir))
            {
                throw new DirectoryNotFoundException("指定されたディレクトリが見つかりません。");
            }

            var srcDir      = Path.Combine(libDir, "src");
            var snippetsDir = Path.Combine(libDir, "snippets");

            Directory.CreateDirectory(snippetsDir);
            Directory.CreateDirectory(srcDir);

            var snippets = new CodeSnippets();

            foreach (var path in Directory.GetFiles(srcDir, "*.csx", SearchOption.AllDirectories))
            {
                using StreamReader reader = new StreamReader(path);
                var parsed = CodeSnippet.Parse(reader);
                if (parsed is null)
                {
                    continue;
                }
                snippets.CodeSnippet.Add(parsed);
            }

            var serializer = new XmlSerializer(typeof(CodeSnippets));

            using StreamWriter writer = new StreamWriter(Path.Combine(snippetsDir, "snippet.snippet"));
            serializer.Serialize(writer, snippets);
        }
Beispiel #2
0
 public void New()
 {
     DocumentId = Guid.NewGuid();
     TreeNodes.Clear();
     CodeSnippets.Clear();
     Defaults();
 }
Beispiel #3
0
        private void Defaults()
        {
            CodeSnippets.Add(CodeSnippet.TrashcanSnippet());
            CodeSnippets.Add(CodeSnippet.ClipboardMonitorSnippet());
            var _root = CodeSnippet.NewRoot("", CodeType.Folder, Constants.SNIPPETS);

            CodeSnippets.Add(_root);
        }
        public Index()
        {
            Snippet = new CodeSnippets();

            Snippet.CodeSnippet.Header.OnChanged += OnSnippetChanged;
            Snippet.CodeSnippet.Snippet.Declarations.OnChanged += OnSnippetChanged;
            Snippet.CodeSnippet.Snippet.Imports.OnChanged      += OnSnippetChanged;
            Snippet.CodeSnippet.Snippet.Code.OnChanged         += OnSnippetChanged;
        }
Beispiel #5
0
        public static int Main()
        {
            bool success =
                new CodeSnippets().Execute() &&
                new DocStrings().Execute() &&
                new ExamplesMarkup().Execute() &&
                new TestsForExamples().Execute() &&
                new TestsForApiPages().Execute();

            return(success ? 0 : 1);
        }
Beispiel #6
0
        public void Load(CodeSnippetCollection collection)
        {
            BeginUpdate();

            Counter = collection.Counter;

            try
            {
                foreach (CodeSnippet snippet in collection.Items)
                {
                    if (string.IsNullOrWhiteSpace(snippet.GetPath()))
                    {
                        snippet.SetPath(Constants.UNNAMED, out bool _changed);
                    }

                    snippet.Refresh();
                }
            }
            catch { }


            TreeNodes.Clear();
            CodeSnippets.Clear();
            CodeSnippets.AddRange(collection.Items);
            if (collection.DocumentId.Equals(Guid.Empty))
            {
                DocumentId = Guid.NewGuid();
            }
            else
            {
                DocumentId = collection.DocumentId;
            }

            if (Counter < collection.Items.Count)
            {
                Counter = collection.Items.Count;
            }

            if (ClipboardMonitor != null)
            {
                ClipboardMonitor.Order = -1;
                ClipboardMonitor.SetPath("Clipboard Monitor", out bool _changed);
            }
            if (Trashcan != null)
            {
                Trashcan.Order = -2;
                Trashcan.SetPath("Trashcan", out bool _changed);
            }

            EndUpdate();
        }
Beispiel #7
0
        CodeSnippets GetCodeSnippets(HtmlNode node)
        {
            const string TYPESCRIPT = "highlight-source-ts";
            const string CSS        = "highlight-source-css";
            const string HTML       = "highlight-text-html-basic";

            var result = new CodeSnippets();

            if (node.Name == "pre")
            {
                var sb       = new StringBuilder();
                var children = node.Descendants().ToList();
                foreach (var child in children)
                {
                    var decoded = WebUtility.HtmlDecode(child.InnerText);
                    //Debug.WriteLine(child.Name);
                    if (child.Name == "span")
                    {
                        sb.Append(string.Empty);
                    }
                    else if (child.Name == "#text")
                    {
                        sb.Append(decoded);
                    }

                    new object();
                }

                if (node.ParentNode.HasClass(TYPESCRIPT))
                {
                    result.TypeScriptSnippet = sb.ToString();
                }
                else if (node.ParentNode.HasClass(CSS))
                {
                    result.CssSnippet = sb.ToString();
                }
                else if (node.ParentNode.HasClass(HTML))
                {
                    result.HtmlSnippet = sb.ToString();
                }
                //Debug.WriteLine(sb.ToString());


                //Debug.WriteLine(sb.ToString());
                sb.Clear();
                //Debug.WriteLine(string.Empty);
                new object();
            }

            return(result);
        }
Beispiel #8
0
 public IEnumerable <IDemoCommand> GetCommands(CodeSnippets script) =>
 new IDemoCommand[]
 {
     new OpenDocument(this.File),
     new ActivateDocument(this.File),
     new MoveToLine(this.File, this.LineIndex),
     new ShowMessage(this.Logger, (int)this.Ordinal, this.TotalSnippetsCount, this.Text),
     this.SelectLineCommand,
     new Pause(),
     new VerifyActiveDocument(this.File),
     new VerifyCursorPosition(this.File, this.HasCode ? this.LineIndex : this.LineIndex + 1),
     new VerifyLineContent(this.File, this.LineIndex, this.LineContent),
     this.ReplacementCommand
 };
Beispiel #9
0
 public IEnumerable <IDemoCommand> GetCommands(CodeSnippets script) =>
 new IDemoCommand[]
 {
     new OpenDocument(this.File),
     new ActivateDocument(this.File),
     new MoveToLine(this.File, this.StartLineIndex),
     new ShowMessage(this.Logger, this.Snippet.Number, this.TotalSnippetsCount, this.Text),
     new Pause(),
     new SelectMultipleLines(this.File, this.StartLineIndex, this.StartLineIndex + this.LinesCount),
     new Pause(),
     new VerifyActiveDocument(this.File),
     new VerifySelectionText(this.File, this.SelectedText),
     new ExpandSelection(this.File, this.SnippetContent)
 };
Beispiel #10
0
    protected override void EmitApiDeclarations(CodeBuilder b)
    {
        if (ExportFunctions.Length > 0)
        {
            foreach (var f in this.ExportFunctions)
            {
                f.EmitPInvokeDeclaration(b);
            }
            b.AppendLine();
        }

        foreach (var cb in CallbackFunctions)
        {
            b.AppendComment(cb.Signature.NativeFunctionHeader(CfxName + "_" + cb.Name));
            CodeSnippets.EmitPInvokeDelegate(b, CfxName + "_" + cb.Name, cb.Signature);
            b.AppendLine();
        }
    }
        private void WhenDeleting(object sender, RoutedEventArgs e)
        {
            View.SelectionChanged -= Selector_OnSelected;
            var bye = View.SelectedItem as CodeSnippet;

            if (bye == null)
            {
                return;
            }
            var resoult =
                MessageBox.Show($"Are you SURE you want to delete this POOR snippet ({bye.ShortenedCalling}) ?",
                                "Deletion confirmation for noobs", MessageBoxButton.YesNo, MessageBoxImage.Question);

            if (resoult == MessageBoxResult.Yes)
            {
                CodeSnippets.Remove(bye);
            }
            View.SelectionChanged += Selector_OnSelected;
        }
        public string Serialize(CodeSnippets snippet)
        {
            var xmlNamespaces = new XmlSerializerNamespaces();

            xmlNamespaces.Add(string.Empty, DefaultNamespace);

            var settings = new XmlWriterSettings
            {
                IndentChars = new string(' ', 4),
                Indent      = true
            };

            using var memoryStream = new MemoryStream();
            using var streamWriter = new StreamWriter(memoryStream, Encoding.UTF8);
            using var xmlWriter    = XmlWriter.Create(streamWriter, settings);

            _xmlSerializer.Serialize(xmlWriter, snippet, xmlNamespaces);
            return(Encoding.UTF8.GetString(memoryStream.ToArray()));
        }
 private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
 {
     CodeSnippets.Add(new CodeSnippet("newSnippet", ""));
 }
    private void BuildPInvokeApi(GeneratedFileManager fileManager)
    {
        var b = new CodeBuilder();

        b.AppendLine("using System.Runtime.InteropServices;");
        b.AppendLine();
        b.BeginCfxNamespace();
        b.BeginClass("CfxApi", "internal partial");

        b.AppendLine();

        b.BeginClass("Runtime", "internal static");

        foreach (var f in decls.ExportFunctions)
        {
            f.EmitPInvokeDeclaration(b);
        }
        b.AppendLine();

        foreach (var f in decls.StringCollectionFunctions)
        {
            f.EmitPInvokeDeclaration(b);
        }
        b.EndBlock();

        b.AppendLine();

        foreach (var t in decls.CefStructTypes)
        {
            t.ClassBuilder.EmitApiClass(b);
            b.AppendLine();
        }

        b.EndBlock();
        b.EndBlock();

        fileManager.WriteFileIfContentChanged("CfxApi.cs", b.ToString());
        b.Clear();

        var cfxfuncs = decls.GetCfxApiFunctionNames();

        b.BeginCfxNamespace();
        b.BeginClass("CfxApiLoader", "internal partial");
        b.BeginBlock("internal enum FunctionIndex");
        foreach (var f in cfxfuncs)
        {
            b.AppendLine(f + ",");
        }

        b.EndBlock();
        b.AppendLine();

        b.BeginFunction("void LoadCfxRuntimeApi()", "internal static");
        foreach (var f in decls.ExportFunctions)
        {
            if (f.Platform != CefPlatform.Independent)
            {
                b.BeginIf("CfxApi.PlatformOS == CfxPlatformOS.{0}", f.Platform.ToString());
            }
            CodeSnippets.EmitPInvokeDelegateInitialization(b, "Runtime", f.CfxApiFunctionName);
            if (f.Platform != CefPlatform.Independent)
            {
                b.EndBlock();
            }
        }
        b.EndBlock();
        b.AppendLine();

        b.BeginFunction("void LoadStringCollectionApi()", "internal static");
        b.AppendLine("CfxApi.Probe();");
        foreach (var f in decls.StringCollectionFunctions)
        {
            CodeSnippets.EmitPInvokeDelegateInitialization(b, "Runtime", f.CfxApiFunctionName);
        }
        b.EndBlock();
        b.AppendLine();

        foreach (var cefStruct in decls.CefStructTypes)
        {
            b.BeginBlock("internal static void Load{0}Api()", cefStruct.ClassName);
            b.AppendLine("CfxApi.Probe();");

            var apiClassName = cefStruct.ClassName.Substring(3);

            switch (cefStruct.ClassBuilder.Category)
            {
            case StructCategory.Library:
                foreach (var f in cefStruct.ClassBuilder.ExportFunctions)
                {
                    CodeSnippets.EmitPInvokeDelegateInitialization(b, f.PublicClassName.Substring(3), f.CfxApiFunctionName);
                }
                foreach (var cb in cefStruct.ClassBuilder.CallbackFunctions)
                {
                    CodeSnippets.EmitPInvokeDelegateInitialization(b, cb.PublicClassName.Substring(3), cb.CfxApiFunctionName);
                }

                break;

            case StructCategory.Client:
                b.AppendLine("CfxApi.{0}.{1}_ctor = (CfxApi.cfx_ctor_with_gc_handle_delegate)CfxApi.GetDelegate(FunctionIndex.{1}_ctor, typeof(CfxApi.cfx_ctor_with_gc_handle_delegate));", apiClassName, cefStruct.CfxName);
                if (cefStruct.ClassBuilder.NeedsWrapFunction)
                {
                    b.AppendLine("CfxApi.{0}.{1}_get_gc_handle = (CfxApi.cfx_get_gc_handle_delegate)CfxApi.GetDelegate(FunctionIndex.{1}_get_gc_handle, typeof(CfxApi.cfx_get_gc_handle_delegate));", apiClassName, cefStruct.CfxName);
                }
                b.AppendLine("CfxApi.{0}.{1}_set_callback = (CfxApi.cfx_set_callback_delegate)CfxApi.GetDelegate(FunctionIndex.{1}_set_callback, typeof(CfxApi.cfx_set_callback_delegate));", apiClassName, cefStruct.CfxName);
                b.AppendLine("{0}.SetNativeCallbacks();", cefStruct.ClassName);
                break;

            case StructCategory.Values:
                b.AppendLine("CfxApi.{0}.{1}_ctor = (CfxApi.cfx_ctor_delegate)CfxApi.GetDelegate(FunctionIndex.{1}_ctor, typeof(CfxApi.cfx_ctor_delegate));", apiClassName, cefStruct.CfxName);
                b.AppendLine("CfxApi.{0}.{1}_dtor = (CfxApi.cfx_dtor_delegate)CfxApi.GetDelegate(FunctionIndex.{1}_dtor, typeof(CfxApi.cfx_dtor_delegate));", apiClassName, cefStruct.CfxName);

                foreach (var sm in cefStruct.ClassBuilder.StructMembers)
                {
                    CodeSnippets.EmitPInvokeDelegateInitialization(b, apiClassName, cefStruct.CfxName + "_set_" + sm.Name);
                    CodeSnippets.EmitPInvokeDelegateInitialization(b, apiClassName, cefStruct.CfxName + "_get_" + sm.Name);
                }

                break;
            }
            b.EndBlock();
            b.AppendLine();
        }

        b.EndBlock();
        b.EndBlock();

        fileManager.WriteFileIfContentChanged("CfxApiLoader.cs", b.ToString());
    }
    private void BuildPInvokeApi(GeneratedFileManager fileManager)
    {
        var b = new CodeBuilder();

        b.AppendLine("using System.Runtime.InteropServices;");
        b.AppendLine();
        b.BeginCfxNamespace();
        b.BeginClass("CfxApi", "internal partial");

        b.AppendLine();

        b.AppendComment("global cef export functions");
        b.AppendLine();

        foreach (var f in decls.ExportFunctions)
        {
            f.EmitPInvokeDeclaration(b);
        }
        b.AppendLine();

        foreach (var f in decls.StringCollectionFunctions)
        {
            f.EmitPInvokeDeclaration(b);
        }
        b.AppendLine();

        b.AppendLine();

        foreach (var t in decls.CefStructTypes)
        {
            t.ClassBuilder.EmitApiDeclarations(b);
            b.AppendLine();
        }

        b.EndBlock();
        b.EndBlock();

        fileManager.WriteFileIfContentChanged("CfxApi.cs", b.ToString());
        b.Clear();

        var cfxfuncs = decls.GetCfxApiFunctionNames();

        b.BeginCfxNamespace();
        b.BeginClass("CfxApiLoader", "internal partial");
        b.BeginBlock("internal enum FunctionIndex");
        foreach (var f in cfxfuncs)
        {
            b.AppendLine(f + ",");
        }

        b.EndBlock();
        b.AppendLine();

        b.BeginFunction("void LoadCfxRuntimeApi()", "internal static");
        foreach (var f in decls.ExportFunctions)
        {
            if (f.Platform != CefPlatform.Independent)
            {
                b.BeginIf("CfxApi.PlatformOS == CfxPlatformOS.{0}", f.Platform.ToString());
            }
            CodeSnippets.EmitPInvokeDelegateInitialization(b, f.CfxName);
            if (f.Platform != CefPlatform.Independent)
            {
                b.EndBlock();
            }
        }
        b.EndBlock();
        b.AppendLine();

        b.BeginFunction("void LoadStringCollectionApi()", "internal static");
        b.AppendLine("CfxApi.Probe();");
        foreach (var f in decls.StringCollectionFunctions)
        {
            CodeSnippets.EmitPInvokeDelegateInitialization(b, f.CfxName);
        }
        b.EndBlock();
        b.AppendLine();

        foreach (var cefStruct in decls.CefStructTypes)
        {
            b.AppendLine("private static bool {0}ApiLoaded;", cefStruct.ClassName);
            b.BeginBlock("internal static void Load{0}Api()", cefStruct.ClassName);
            b.AppendLine("if({0}ApiLoaded) return;", cefStruct.ClassName);
            b.AppendLine("{0}ApiLoaded = true;", cefStruct.ClassName);
            b.AppendLine("CfxApi.Probe();");
            switch (cefStruct.ClassBuilder.Category)
            {
            case StructCategory.ApiCalls:
                if (cefStruct.ClassBuilder.ExportFunctions.Count() > 0)
                {
                    foreach (var f in cefStruct.ClassBuilder.ExportFunctions)
                    {
                        CodeSnippets.EmitPInvokeDelegateInitialization(b, f.CfxName);
                    }
                }
                foreach (var sm in cefStruct.ClassBuilder.StructMembers)
                {
                    if (sm.MemberType.IsCefCallbackType)
                    {
                        CodeSnippets.EmitPInvokeDelegateInitialization(b, cefStruct.CfxName + "_" + sm.Name);
                    }
                }

                break;

            case StructCategory.ApiCallbacks:
                b.AppendLine("CfxApi.{0}_ctor = (CfxApi.cfx_ctor_with_gc_handle_delegate)CfxApi.GetDelegate(FunctionIndex.{0}_ctor, typeof(CfxApi.cfx_ctor_with_gc_handle_delegate));", cefStruct.CfxName);
                b.AppendLine("CfxApi.{0}_get_gc_handle = (CfxApi.cfx_get_gc_handle_delegate)CfxApi.GetDelegate(FunctionIndex.{0}_get_gc_handle, typeof(CfxApi.cfx_get_gc_handle_delegate));", cefStruct.CfxName);
                b.AppendLine("CfxApi.{0}_set_managed_callback = (CfxApi.cfx_set_callback_delegate)CfxApi.GetDelegate(FunctionIndex.{0}_set_managed_callback, typeof(CfxApi.cfx_set_callback_delegate));", cefStruct.CfxName);
                if (cefStruct.ClassBuilder.ExportFunctions.Count() > 0)
                {
                    System.Diagnostics.Debugger.Break();
                }
                break;

            case StructCategory.Values:
                b.AppendLine("CfxApi.{0}_ctor = (CfxApi.cfx_ctor_delegate)CfxApi.GetDelegate(FunctionIndex.{0}_ctor, typeof(CfxApi.cfx_ctor_delegate));", cefStruct.CfxName);
                b.AppendLine("CfxApi.{0}_dtor = (CfxApi.cfx_dtor_delegate)CfxApi.GetDelegate(FunctionIndex.{0}_dtor, typeof(CfxApi.cfx_dtor_delegate));", cefStruct.CfxName);

                foreach (var sm in cefStruct.ClassBuilder.StructMembers)
                {
                    if (sm.Name != "size")
                    {
                        CodeSnippets.EmitPInvokeDelegateInitialization(b, cefStruct.CfxName + "_set_" + sm.Name);
                        CodeSnippets.EmitPInvokeDelegateInitialization(b, cefStruct.CfxName + "_get_" + sm.Name);
                    }
                }

                if (cefStruct.ClassBuilder.ExportFunctions.Count() > 0)
                {
                    System.Diagnostics.Debugger.Break();
                }

                break;
            }
            b.EndBlock();
            b.AppendLine();
        }

        b.EndBlock();
        b.EndBlock();

        fileManager.WriteFileIfContentChanged("CfxApiLoader.cs", b.ToString());
    }
Beispiel #16
0
 public void Refresh()
 {
     CodeSnippets.Refresh();
     TreeNodes.Refresh();
 }
 public void EmitPInvokeDeclaration(CodeBuilder b)
 {
     b.AppendComment(this.ToString());
     CodeSnippets.EmitPInvokeDelegate(b, CfxName, Signature);
 }
Beispiel #18
0
        private async Task Generate(Dictionary <string, object> dataContext, IProgress <Tuple <int, string, Color> > p)
        {
            await Task.Run(async() =>
            {
                var apiProjectName        = dataContext["ApiProjectName"].ToString();
                var repositoryProjectName = dataContext["RepositoryProjectName"].ToString();
                var options = (Dictionary <string, object>)dataContext["Options"];

                // VARIABLES
                var bootstrapper = true;
                var sameProjects = repositoryProjectName == apiProjectName;
                var _onlineNugetPackageLocation = "https://packages.nuget.org/api/v2";
                //worker.ReportProgress(0, " ---ACG process start---");
                Send(p, 0, " ---ACG process started---");
                //----------------------------------------------------------------------------------------------------------------
                // WORKSPACE GETTING
                Send(p, 0, " - Trying to get workspace");
                var workspace = GetWorkspace();
                Send(p, 5, " - Workspace loaded", Color.Green);

                //----------------------------------------------------------------------------------------------------------------
                // SOLUTION GETTING
                Send(p, 5, " - Trying to get solution");
                Solution solution;
                GetCurrentSolution(out solution);
                Send(p, 10, " - Current solution loaded", Color.Green);

                //----------------------------------------------------------------------------------------------------------------
                // API AND REPOSITORY PROJECT GETTING
                Send(p, 10, " - Trying to get API project named '" + apiProjectName + "'");
                var apiProject = solution.Projects.First(o => o.Name == apiProjectName);
                if (apiProject != null)
                {
                    Send(p, 15, " - '" + apiProjectName + "' project loaded", Color.Green);
                }
                else
                {
                    Send(p, 15, " - '" + apiProjectName + "' project not found", Color.Red);
                }

                Project repositoryProject;
                // if the api and repository are different projects
                if (!sameProjects)
                {
                    Send(p, 15, " - Trying to get repository project named '" + repositoryProjectName + "'");
                    repositoryProject = solution.Projects.First(o => o.Name == repositoryProjectName);
                    if (apiProject != null)
                    {
                        Send(p, 15, " - '" + repositoryProjectName + "' project loaded", Color.Green);
                    }
                    else
                    {
                        Send(p, 15, " - '" + repositoryProjectName + "' project not found", Color.Red);
                    }
                }
                // if are the same project
                else
                {
                    repositoryProject = apiProject;
                }
                //----------------------------------------------------------------------------------------------------------------
                // AUTO INSTALL NUGET PACKAGES
                Send(p, 25, " - Trying to install NuGet packages");
                // get project
                DTE dte                   = (DTE)this.ServiceProvider.GetService(typeof(DTE));
                var solution2             = (Solution2)dte.Solution;
                Projects dteProjects      = dte.Solution.Projects;
                EnvDTE.Project dteProject = null;

                for (int i = 1; i <= dteProjects.Count; i++)
                {
                    if (dteProjects.Item(i).Name == apiProjectName)
                    {
                        dteProject = dteProjects.Item(i);
                    }
                }

                string packageID = "EntityFramework";

                //Connect to the official package repository
                IPackageRepository repo = PackageRepositoryFactory.Default.CreateRepository("https://packages.nuget.org/api/v2");

                //PackageManager packageManager = new PackageManager(repo, path);
                var componentModel = (IComponentModel)ServiceProvider.GetService(typeof(SComponentModel));
                IVsPackageInstaller pckInstaller = componentModel.GetService <IVsPackageInstaller>();

                var packagesToInstall = new Dictionary <string, SemanticVersion>();

                var packages = new Dictionary <string, string>();

                packages.Add("EntityFramework", "EntityFramework");

                if ((bool)options["Unity"])
                {
                    packages.Add("Unity", "Unity.WebApi");
                }

                if ((bool)options["CORS"])
                {
                    packages.Add("CORS", "Microsoft.AspNet.WebApi.Cors");
                }


                foreach (var pkg in packages)
                {
                    List <IPackage> package = repo.FindPackagesById(pkg.Value).ToList();
                    var lastVersion         = package.Where(o => o.IsLatestVersion).Select(o => o.Version).FirstOrDefault();

                    packagesToInstall.Add(pkg.Value, lastVersion);
                }


                foreach (var pkg in packagesToInstall)
                {
                    Send(p, 25, " - Installing " + pkg.Key + " " + pkg.Value.Version);
                    try
                    {
                        pckInstaller.InstallPackage(_onlineNugetPackageLocation, dteProject, pkg.Key, pkg.Value.Version, false);
                        Send(p, 25, " - " + pkg.Key + " " + pkg.Value.Version + " installed", Color.Green);
                    }
                    catch (Exception)
                    {
                        Send(p, 25, " - Error on installing " + pkg.Key + " " + pkg.Value.Version, Color.Red);
                    }
                }

                //----------------------------------------------------------------------------------------------------------------
                // CHECK REFERENCES INTEGRITY
                Send(p, 35, " - Checking references integrity of '" + apiProjectName + "'");
                GetCurrentSolution(out solution);
                apiProject        = solution.Projects.First(o => o.Name == apiProjectName);
                var allReferences = apiProject.MetadataReferences;

                var refStatus = new Dictionary <string, bool> {
                    { "EntityFramework", false }
                };

                foreach (var op in options)
                {
                    if (op.Key == "Unity" && (bool)op.Value)
                    {
                        refStatus.Add("Unity", false);
                    }
                    else if (op.Key == "CORS" && (bool)op.Value)
                    {
                        refStatus.Add("CORS", false);
                    }
                }

                foreach (var reference in allReferences)
                {
                    if (reference.Display.Contains("EntityFramework"))
                    {
                        refStatus["EntityFramework"] = true;
                    }

                    if (refStatus.ContainsKey("Unity"))
                    {
                        if (reference.Display.Contains("Unity.WebApi"))
                        {
                            refStatus["Unity"] = true;
                        }
                    }

                    if (refStatus.ContainsKey("CORS"))
                    {
                        if (reference.Display.Contains("System.Web.Http.Cors"))
                        {
                            refStatus["CORS"] = true;
                        }
                    }
                }
                var allRequiredRefsOk = true;
                foreach (var rs in refStatus)
                {
                    if (rs.Key == "EntityFramework")
                    {
                        if (rs.Value)
                        {
                            Send(p, 40, " - EntityFramework reference checked", Color.Green);
                        }
                        else
                        {
                            allRequiredRefsOk = false;
                            Send(p, 40, " - EntityFramework reference not found, please, download it in NuGet Package manager", Color.Red);
                        }
                    }
                    if (rs.Key == "Unity")
                    {
                        if (rs.Value)
                        {
                            Send(p, 40, " - Unity.WebApi reference checked", Color.Green);
                        }
                        else
                        {
                            allRequiredRefsOk = false;
                            Send(p, 40, " - Unity.WebApi reference not found, please, download it in NuGet Package manager", Color.Red);
                        }
                    }
                    if (rs.Key == "CORS")
                    {
                        if (rs.Value)
                        {
                            Send(p, 40, " - CORS reference checked", Color.Green);
                        }
                        else
                        {
                            allRequiredRefsOk = false;
                            Send(p, 40, " - CORS reference not found, please, download it in NuGet Package manager (Microsoft.AspNet.WebApi.Cors)", Color.Red);
                        }
                    }
                }


                //----------------------------------------------------------------------------------------------------------------
                // START TO GENERATE
                if (repositoryProject != null && apiProject != null && allRequiredRefsOk)
                {
                    string dbContext = "";

                    //----------------------------------------------------------------------------------------------------------------
                    //CONNECTION STRINGS IMPORT
                    try
                    {
                        // only import if they are different projects
                        if (!sameProjects)
                        {
                            Send(p, 50, " - Trying to import connection strings from '" +
                                 repositoryProjectName + "'");

                            // App.config file
                            var xmlRepDoc  = new XmlDocument();
                            var apiRepPath =
                                Path.Combine(
                                    solution.Projects.First(o => o.Name == repositoryProjectName)
                                    .FilePath.Replace(repositoryProjectName + ".csproj", ""), "App.Config");
                            xmlRepDoc.Load(apiRepPath);
                            var repConnectionStrings =
                                xmlRepDoc.DocumentElement.ChildNodes.Cast <XmlElement>()
                                .First(x => x.Name == "connectionStrings");

                            // if App.config contains connectionStrings element
                            if (repConnectionStrings != null)
                            {
                                var csdata = repConnectionStrings.ChildNodes.Cast <XmlElement>().First(x => x.Name == "add");

                                // Web.config file
                                var xmlApiDoc  = new XmlDocument();
                                var apiApiPath =
                                    Path.Combine(
                                        solution.Projects.First(o => o.Name == apiProjectName)
                                        .FilePath.Replace(apiProjectName + ".csproj", ""), "Web.config");
                                xmlApiDoc.Load(apiApiPath);
                                var apiConnectionStrings =
                                    xmlApiDoc.DocumentElement.ChildNodes.Cast <XmlElement>()
                                    .FirstOrDefault(x => x.Name == "connectionStrings");

                                // DbContext getting
                                dbContext = csdata.GetAttribute("name");
                                Send(p, 50, " - Connection strings loaded with '" + dbContext + "' as DbContext ",
                                     Color.Green);
                                Send(p, 50, " - Trying to import connection strings  on '" +
                                     apiProjectName + "'");

                                var csnode = xmlApiDoc.ImportNode(repConnectionStrings, true);

                                // if API Web.config doesnt contain any connectionStrings element
                                if (apiConnectionStrings == null)
                                {
                                    xmlApiDoc.DocumentElement.AppendChild(csnode);
                                }
                                // if Web.config alrealy contains that element
                                else
                                {
                                    var addElement =
                                        apiConnectionStrings.ChildNodes.Cast <XmlElement>()
                                        .FirstOrDefault(x => x.Name == "add");
                                    // if contains 'add' element
                                    if (addElement != null)
                                    {
                                        // if 'add' elements name  is the same as dbContext
                                        if (addElement.GetAttribute("name").Equals(dbContext))
                                        {
                                            Send(p, 55,
                                                 " - API Web.Config file already contains a 'connectionStrings' element named '" +
                                                 dbContext + "'", Color.Orange);
                                        }
                                        else
                                        {
                                            apiConnectionStrings.AppendChild(xmlApiDoc.ImportNode(csdata, true));
                                        }
                                    }
                                    else
                                    {
                                        apiConnectionStrings.AppendChild(xmlApiDoc.ImportNode(csdata, true));
                                    }
                                }

                                xmlApiDoc.Save(apiApiPath);
                                Send(p, 60, " - Connection strings successfully imported to '" + apiProjectName + "'",
                                     Color.Green);
                            }
                            else
                            {
                                Send(p, 60, " - Connection strings not found in App.config file of '" +
                                     repositoryProjectName + "' project", Color.Red);
                            }
                        }
                        else
                        {
                            var xmlApiDoc  = new XmlDocument();
                            var apiApiPath =
                                Path.Combine(
                                    solution.Projects.First(o => o.Name == apiProjectName)
                                    .FilePath.Replace(apiProjectName + ".csproj", ""), "Web.config");
                            xmlApiDoc.Load(apiApiPath);
                            var apiConnectionStrings =
                                xmlApiDoc.DocumentElement.ChildNodes.Cast <XmlElement>()
                                .FirstOrDefault(x => x.Name == "connectionStrings");
                            var addElement = apiConnectionStrings.ChildNodes.Cast <XmlElement>().FirstOrDefault(x => x.Name == "add");
                            dbContext      = addElement.GetAttribute("name");
                        }
                    }
                    catch (Exception)
                    {
                        Send(p, 60, " - Problems to import connection strings from '" + repositoryProjectName + "' to '" + apiProjectName + "' , make sure that Repository project contains App.Config file with 'connectionStrings' element", Color.Red);
                    }


                    CodeSnippets.ApiProjectName        = apiProjectName;
                    CodeSnippets.RepositoryProjectName = repositoryProjectName;

                    //----------------------------------------------------------------------------------------------------------------
                    // ADD REPOSITORY PROJECT REFERENCE
                    if (!sameProjects)
                    {
                        Send(p, 65, " - Trying to reference '" + repositoryProjectName + "' on '" + apiProjectName + "'");

                        var alreadyReference = apiProject.ProjectReferences.Any(o => o.ProjectId == repositoryProject.Id);

                        if (!alreadyReference)
                        {
                            var projectWithReference = apiProject.AddProjectReference(new ProjectReference(repositoryProject.Id));
                            var res = workspace.TryApplyChanges(projectWithReference.Solution);
                            if (res)
                            {
                                Send(p, 65, " - Reference added successfully", Color.Green);
                            }
                            else
                            {
                                Send(p, 65, " - Can't add the reference, you must add it manually after process end",
                                     Color.Red);
                            }
                        }
                        else
                        {
                            Send(p, 65, " - Reference was already added before process start", Color.Orange);
                        }
                    }

                    //----------------------------------------------------------------------------------------------------------------
                    // GET REPOSITORY VIEWMODELS
                    var viewModels = repositoryProject.Documents.Where(o => o.Folders.Contains("ViewModels") && o.Name != "IViewModel.cs");
                    Send(p, 70, " - Trying to get all ViewModels");
                    if (viewModels.Any())
                    {
                        Send(p, 75, " - ViewModels loaded", Color.Green);
                        // save here all classnames to create the bootstraper file with unity registerType
                        var classesNameList = new List <string>();

                        // max number of PK from one properties
                        var maxPkSize = 1;

                        //Get the PK (name - type) of the current ViewModel and creates his controller

                        //----------------------------------------------------------------------------------------------------------------
                        // CONTROLLERS GENERATE
                        Send(p, 80, " - Trying to generate all controllers");

                        // if BaseController is enabled
                        if ((bool)options["BaseController"])
                        {
                            var controllerName = "BaseController";
                            CodeSnippets.ControllerInheritance = controllerName;
                            GetCurrentSolution(out solution);
                            apiProject = solution.Projects.First(o => o.Name == apiProjectName);
                            var res    = apiProject.AddDocument(controllerName, CodeSnippets.GetBaseController(controllerName), new[] { apiProjectName, "Controllers" });
                            workspace.TryApplyChanges(res.Project.Solution);
                        }

                        foreach (var vm in viewModels)
                        {
                            GetCurrentSolution(out solution);
                            apiProject = solution.Projects.First(o => o.Name == apiProjectName);

                            var data         = await vm.GetSemanticModelAsync();
                            var currentClass = data.SyntaxTree.GetRoot().DescendantNodes().OfType <ClassDeclarationSyntax>().First();
                            var className    = currentClass.Identifier.Text.Replace("ViewModel", "");

                            var methods       = data.SyntaxTree.GetRoot().DescendantNodes().OfType <MethodDeclarationSyntax>();
                            var getKeysMethod = methods.First(o => o.Identifier.Text.Equals("GetKeys"));
                            var methodBody    = getKeysMethod.Body.GetText().ToString();
                            var i1            = methodBody.IndexOf("{", methodBody.IndexOf("{") + 1) + 1;
                            var i2            = methodBody.IndexOf("}", methodBody.IndexOf("}"));
                            var pks           = methodBody.Substring(i1, i2 - i1).Replace(" ", "").Split(',');

                            if (pks.Count() > maxPkSize)
                            {
                                maxPkSize = pks.Count();
                            }

                            var props           = data.SyntaxTree.GetRoot().DescendantNodes().OfType <PropertyDeclarationSyntax>();
                            var primaryKeysList = new List <Tuple <string, string> >();
                            foreach (var prop in props)
                            {
                                var pname = prop.Identifier.Text;
                                var pline = prop.GetText().ToString();
                                var pk    = pks.FirstOrDefault(o => o.Equals(pname));
                                if (pk != null)
                                {
                                    var ptype = pline.Substring(pline.IndexOf("public ") + 7, pline.IndexOf(" " + pk) - pline.IndexOf("public ") - 7);
                                    primaryKeysList.Add(new Tuple <string, string>(pname, ptype));
                                }
                            }

                            // add controller
                            var res = apiProject.AddDocument(className + "Controller", CodeSnippets.GetRepositoryController(className, primaryKeysList, (bool)options["CORS"], (bool)options["Unity"], dbContext), new[] { apiProjectName, "Controllers" });

                            workspace.TryApplyChanges(res.Project.Solution);

                            classesNameList.Add(className);
                            Send(p, 80, " - " + className + "Controller generated", Color.Green);
                        }
                        Send(p, 85, " - All controllers generated successfully", Color.Green);

                        //----------------------------------------------------------------------------------------------------------------
                        // CREATE BOOTSTRAPPER FILE AND REGYSTERTYPES
                        if ((bool)options["Unity"] && bootstrapper)
                        {
                            Send(p, 90, " - Trying to create Bootstrapper file");

                            GetCurrentSolution(out solution);
                            apiProject = solution.Projects.First(o => o.Name == apiProjectName);

                            var newFile = apiProject.AddDocument("Bootstrapper",
                                                                 CodeSnippets.GetBootstrapper(classesNameList, dbContext),
                                                                 new[] { apiProjectName, "App_Start" });
                            workspace.TryApplyChanges(newFile.Project.Solution);

                            GetCurrentSolution(out solution);
                            apiProject = solution.Projects.First(o => o.Name == apiProjectName);
                            Send(p, 90, " - Bootstraper file created", Color.Green);
                            Send(p, 90, " - Added all registerType statements for each entity", Color.Green);

                            // adds "Bootstrapper.InitUnity(container);" line in unity config
                            foreach (ProjectItem pi in dteProject.ProjectItems)
                            {
                                if (pi.Name != "App_Start")
                                {
                                    continue;
                                }
                                foreach (ProjectItem subpi in pi.ProjectItems)
                                {
                                    if (subpi.Name != "UnityConfig.cs")
                                    {
                                        continue;
                                    }
                                    // DELETE FILE
                                    var filename = subpi.FileNames[0];
                                    subpi.Remove();
                                    System.IO.File.Delete(filename);
                                }
                            }
                            GetCurrentSolution(out solution);
                            apiProject = solution.Projects.First(o => o.Name == apiProjectName);
                            var res    = apiProject.AddDocument("UnityConfig", CodeSnippets.GetUnityConfig(true), new[] { apiProjectName, "App_Start" });
                            workspace.TryApplyChanges(res.Project.Solution);

                            /* var unityConfigDoc =
                             *   apiProject.Documents.First(
                             *       o => o.Folders.Contains("App_Start") && o.Name == "UnityConfig.cs");
                             * var tree = await unityConfigDoc.GetSyntaxTreeAsync();
                             *
                             * var targetBlock =
                             *   tree.GetRoot()
                             *       .DescendantNodes()
                             *       .OfType<BlockSyntax>()
                             *       .FirstOrDefault(
                             *           x =>
                             *               x.Statements.Any(
                             *                   y => y.ToString().Contains("var container = new UnityContainer();")));
                             *
                             * StatementSyntax syn1 =
                             *   SyntaxFactory.ParseStatement(@"
                             * Bootstrapper.InitUnity(container);
                             *
                             * ");
                             * List<StatementSyntax> newSynList = new List<StatementSyntax> { syn1 };
                             *
                             * SyntaxList<StatementSyntax> blockWithNewStatements = targetBlock.Statements;
                             *
                             * foreach (var syn in newSynList)
                             * {
                             *   blockWithNewStatements = blockWithNewStatements.Insert(1, syn);
                             * }
                             *
                             * BlockSyntax newBlock = SyntaxFactory.Block(blockWithNewStatements);
                             *
                             * var newRoot = tree.GetRoot().ReplaceNode(targetBlock, newBlock);
                             *
                             * var doc = unityConfigDoc.WithSyntaxRoot(newRoot);
                             * workspace.TryApplyChanges(doc.Project.Solution);
                             */
                            GetCurrentSolution(out solution);
                            apiProject = solution.Projects.First(o => o.Name == apiProjectName);
                            Send(p, 90, " - Added call to Bootstrapper init in UnityConfig.cs file", Color.Green);
                        }

                        //WEBAPI.CONFIG FILE
                        // adds unity init, json formatter and url mapping line in web config
                        Send(p, 95, " - Trying to add configuration statements on WebApiConfig.cs");


                        // dte.Solution.AddFromTemplate("ENVTEST", "", "ENVTEST");
                        foreach (ProjectItem pi in dteProject.ProjectItems)
                        {
                            if (pi.Name != "App_Start")
                            {
                                continue;
                            }
                            foreach (ProjectItem subpi in pi.ProjectItems)
                            {
                                if (subpi.Name != "WebApiConfig.cs")
                                {
                                    continue;
                                }
                                // DELETE FILE
                                var filename = subpi.FileNames[0];
                                subpi.Remove();
                                System.IO.File.Delete(filename);
                            }
                        }
                        GetCurrentSolution(out solution);
                        apiProject = solution.Projects.First(o => o.Name == apiProjectName);

                        var config = "";

                        if ((bool)options["Unity"])
                        {
                            config += @"
            UnityConfig.RegisterComponents();
 ";
                            Send(p, 95, " - Added component register of Unity", Color.Green);
                        }
                        if ((bool)options["JSON"])
                        {
                            config += @"
            var json = config.Formatters.JsonFormatter;
            json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
            config.Formatters.Remove(config.Formatters.XmlFormatter);
 ";
                            Send(p, 95, " - Added JSON formatter", Color.Green);
                        }
                        if ((bool)options["CORS"])
                        {
                            config += @"
            config.EnableCors();
 ";
                        }
                        Send(p, 95, " - Enabled CORS header", Color.Green);
                        var routeTemplate = "";
                        var defaults      = "";
                        for (var i = 1; i <= maxPkSize; i++)
                        {
                            if (i == 1)
                            {
                                routeTemplate += "{id}";
                                defaults      += "id = RouteParameter.Optional";
                                continue;
                            }
                            routeTemplate += "/{id" + i + "}";
                            defaults      += ", id" + i + " = RouteParameter.Optional";
                        }
                        var routing = @"
            config.Routes.MapHttpRoute(
                name: ""DefaultApi"",
                routeTemplate: ""api/{controller}/" + routeTemplate + @""",
                defaults: new { " + defaults + @" }
            );
 ";
                        var resWac  = apiProject.AddDocument("WebApiConfig", CodeSnippets.GetWebApiConfig(config, routing), new[] { apiProjectName, "App_Start" });
                        workspace.TryApplyChanges(resWac.Project.Solution);

                        /*var webApiConfigDoc = apiProject.Documents.First(o => o.Folders.Contains("App_Start") && o.Name == "WebApiConfig.cs");
                         * var webApitree = await webApiConfigDoc.GetSyntaxTreeAsync();
                         *
                         * var targetBlock2 =
                         *  webApitree.GetRoot()
                         *      .DescendantNodes()
                         *      .OfType<BlockSyntax>()
                         *      .FirstOrDefault(x => x.Statements.Any(y => y.ToString().Contains("config.MapHttpAttributeRoutes();")));
                         *
                         *
                         * Send(p, 95, " - Enabled CORS", Color.Green);
                         * }
                         *
                         * StatementSyntax syn2 = SyntaxFactory.ParseStatement(config);
                         *
                         * StatementSyntax syn3 =
                         * SyntaxFactory.ParseStatement(@"
                         * config.Routes.MapHttpRoute(
                         * name: ""DefaultApi"",
                         * routeTemplate: ""api/{controller}/" + routeTemplate + @""",
                         * defaults: new { " + defaults + @" }
                         * );
                         * ");
                         * List<StatementSyntax> newSynList2 = new List<StatementSyntax> { syn2 };
                         *
                         * var r = targetBlock2.Statements.RemoveAt(1);
                         *
                         * SyntaxList<StatementSyntax> blockWithNewStatements2 = r;
                         *
                         * foreach (var syn in newSynList2)
                         * {
                         * blockWithNewStatements2 = blockWithNewStatements2.Insert(0, syn);
                         * }
                         * blockWithNewStatements2 = blockWithNewStatements2.Insert(blockWithNewStatements2.Count, syn3);
                         *
                         * BlockSyntax newBlock2 = SyntaxFactory.Block(blockWithNewStatements2);
                         *
                         * var newRoot2 = webApitree.GetRoot().ReplaceNode(targetBlock2, newBlock2);
                         *
                         * var doc2 = webApiConfigDoc.WithSyntaxRoot(newRoot2);
                         * // workspace.TryApplyChanges(doc2.Project.Solution);
                         */
                    }
                    else
                    {
                        Send(p, 100, " - ViewModels folder not found",
                             Color.Red);
                    }
                }

                Send(p, 100, " ---ACG process ended---");
            });
        }
Beispiel #19
0
 public Option <(IText remaining, CodeSnippets script)> Apply(NonEmptyText current, CodeSnippets script) =>
Beispiel #20
0
 void Awake()
 {
     codeSnippets = JsonUtility.FromJson <CodeSnippets>(File.ReadAllText("Assets/JSON/python-snippets.json"));
 }
    public override void EmitPublicClass(CodeBuilder b)
    {
        b.AppendLine("using Event;");
        b.AppendLine();

        b.AppendSummaryAndRemarks(Comments, false, true);

        b.BeginClass(ClassName + " : CfxBaseClient", GeneratorConfig.ClassModifiers(ClassName));
        b.AppendLine();

        if (NeedsWrapFunction)
        {
            b.BeginFunction("Wrap", ClassName, "IntPtr nativePtr", "internal static");
            b.AppendLine("if(nativePtr == IntPtr.Zero) return null;");
            b.AppendLine("var handlePtr = CfxApi.{0}.{1}_get_gc_handle(nativePtr);", ApiClassName, CfxName);
            b.AppendLine("return ({0})System.Runtime.InteropServices.GCHandle.FromIntPtr(handlePtr).Target;", ClassName);
            b.EndBlock();
            b.AppendLine();
            b.AppendLine();
        }

        b.AppendLine("private static object eventLock = new object();");
        b.AppendLine();

        b.BeginBlock("internal static void SetNativeCallbacks()");

        foreach (var sm in CallbackFunctions)
        {
            b.AppendLine("{0}_native = {0};", sm.Name);
        }
        b.AppendLine();
        foreach (var sm in CallbackFunctions)
        {
            b.AppendLine("{0}_native_ptr = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate({0}_native);", sm.Name);
        }

        b.EndBlock();
        b.AppendLine();

        foreach (var cb in CallbackFunctions)
        {
            var sig = cb.Signature;

            b.AppendComment(cb.ToString());
            CodeSnippets.EmitPInvokeCallbackDelegate(b, cb.Name, cb.Signature);
            b.AppendLine("private static {0}_delegate {0}_native;", cb.Name);
            b.AppendLine("private static IntPtr {0}_native_ptr;", cb.Name);
            b.AppendLine();

            b.BeginFunction(cb.Name, "void", sig.PInvokeParameterList, "internal static");
            //b.AppendLine("var handle = System.Runtime.InteropServices.GCHandle.FromIntPtr(gcHandlePtr);")
            b.AppendLine("var self = ({0})System.Runtime.InteropServices.GCHandle.FromIntPtr(gcHandlePtr).Target;", ClassName);
            b.BeginIf("self == null || self.CallbacksDisabled");
            if (!sig.ReturnType.IsVoid)
            {
                sig.ReturnType.EmitSetCallbackReturnValueToDefaultStatements(b);
            }
            foreach (var arg in sig.Parameters)
            {
                if (!arg.IsThisArgument)
                {
                    arg.ParameterType.EmitSetCallbackArgumentToDefaultStatements(b, arg.VarName);
                }
            }
            b.AppendLine("return;");
            b.EndBlock();
            b.AppendLine("var e = new {0}();", cb.PublicEventArgsClassName);
            for (var i = 1; i <= sig.ManagedParameters.Count() - 1; i++)
            {
                if (sig.ManagedParameters[i].ParameterType.IsIn)
                {
                    sig.ManagedParameters[i].EmitPublicEventFieldInitializers(b);
                }
            }
            b.AppendLine("self.m_{0}?.Invoke(self, e);", cb.PublicName);
            b.AppendLine("e.m_isInvalid = true;");

            for (var i = 1; i <= sig.ManagedParameters.Count() - 1; i++)
            {
                sig.ManagedParameters[i].EmitPostPublicRaiseEventStatements(b);
            }

            sig.EmitPostPublicEventHandlerReturnValueStatements(b);

            b.EndBlock();
            b.AppendLine();
        }

        if (NeedsWrapFunction)
        {
            b.AppendLine("internal {0}(IntPtr nativePtr) : base(nativePtr) {{}}", ClassName);
        }
        b.AppendLine("public {0}() : base(CfxApi.{1}.{2}_ctor) {{}}", ClassName, ApiClassName, CfxName);
        b.AppendLine();

        var cbIndex = 0;

        foreach (var cb in CallbackFunctions)
        {
            EmitPublicEvent(b, cbIndex, cb);
            b.AppendLine();
            cbIndex += 1;
        }

        var onlyBasicEvents = true;

        b.BeginFunction("OnDispose", "void", "IntPtr nativePtr", "internal override");
        cbIndex = 0;
        foreach (var cb in CallbackFunctions)
        {
            onlyBasicEvents &= cb.IsBasicEvent;
            b.BeginIf("m_{0} != null", cb.PublicName);
            b.AppendLine("m_{0} = null;", cb.PublicName);
            b.AppendLine("CfxApi.{0}.{1}_set_callback(NativePtr, {2}, IntPtr.Zero);", ApiClassName, CfxName, cbIndex);
            b.EndBlock();
            cbIndex += 1;
        }
        b.AppendLine("base.OnDispose(nativePtr);");
        b.EndBlock();

        b.EndBlock();

        if (!onlyBasicEvents)
        {
            b.AppendLine();
            b.AppendLine();

            b.BeginBlock("namespace Event");
            b.AppendLine();

            foreach (var cb in CallbackFunctions)
            {
                EmitPublicEventArgsAndHandler(b, cb);
                b.AppendLine();
            }

            b.EndBlock();
        }
    }
Beispiel #22
0
 public Option <(IText remaining, CodeSnippets script)> Apply(NonEmptyText current, CodeSnippets script) =>
 this.ApplyBeforePreamble(current, script);
Beispiel #23
0
 private Option <(IText remaining, CodeSnippets script)> ApplyBeforePreamble(NonEmptyText current, CodeSnippets script) =>
 void Awake()
 {
     codeSnippets = JsonUtility.FromJson <CodeSnippets>(Resources.Load <TextAsset>("JSON/python-snippets").text);
 }
    public void EmitRemoteClient(CodeBuilder b)
    {
        b.BeginClass(ClassName + "RemoteClient", "internal static");
        b.AppendLine();

        b.BeginBlock("static {0}RemoteClient()", ClassName);

        foreach (var sm in RemoteCallbackFunctions)
        {
            b.AppendLine("{0}_native = {0};", sm.Name);
        }
        foreach (var sm in RemoteCallbackFunctions)
        {
            b.AppendLine("{0}_native_ptr = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate({0}_native);", sm.Name);
        }

        b.EndBlock();
        b.AppendLine();

        b.BeginBlock("internal static void SetCallback(IntPtr self, int index, bool active)");
        b.BeginBlock("switch(index)");
        foreach (var cb in RemoteCallbackFunctions)
        {
            b.AppendLine("case {0}:", cb.ClientCallbackIndex);
            b.IncreaseIndent();
            b.AppendLine("CfxApi.{0}.{1}_set_callback(self, index, active ? {2}_native_ptr : IntPtr.Zero);", ApiClassName, CfxName, cb.Name);
            b.AppendLine("break;");
            b.DecreaseIndent();
        }
        b.EndBlock();
        b.EndBlock();
        b.AppendLine();

        foreach (var cb in RemoteCallbackFunctions)
        {
            var sig = cb.Signature;

            b.AppendComment(cb.ToString());
            CodeSnippets.EmitPInvokeCallbackDelegate(b, cb.Name, cb.Signature);
            b.AppendLine("private static {0}_delegate {0}_native;", cb.Name);
            b.AppendLine("private static IntPtr {0}_native_ptr;", cb.Name);
            b.AppendLine();

            var inArgumentList = new List <string>();

            foreach (var arg in sig.Parameters)
            {
                if (!arg.IsThisArgument)
                {
                    foreach (var pm in arg.ParameterType.RemoteCallbackParameterList(arg.VarName))
                    {
                        if (!pm.StartsWith("out "))
                        {
                            inArgumentList.Add(pm.Substring(pm.LastIndexOf(' ') + 1));
                        }
                    }
                }
            }

            b.BeginFunction(cb.Name, "void", sig.PInvokeParameterList, "internal static");
            b.AppendLine("var call = new {0}RemoteEventCall();", cb.RemoteCallName);
            b.AppendLine("call.gcHandlePtr = gcHandlePtr;");
            foreach (var pm in inArgumentList)
            {
                b.AppendLine("call.{0} = {0};", pm);
            }
            b.AppendLine("call.RequestExecution();");
            foreach (var arg in sig.Parameters)
            {
                if (!arg.IsThisArgument)
                {
                    arg.ParameterType.EmitPostRemoteCallbackStatements(b, arg.VarName);
                }
            }
            if (!sig.ReturnType.IsVoid)
            {
                b.AppendLine("__retval = call.__retval;");
            }

            //sig.EmitPostPublicEventHandlerCallStatements(b);

            b.EndBlock();
            b.AppendLine();
        }


        b.EndBlock();
    }
Beispiel #26
0
        public void LoadLegacy(CodeSnippetCollectionOld collection)
        {
            BeginUpdate();

            Cleanup(collection);

            Counter = collection.Counter;

            CodeSnippetCollection _newCollection = new CodeSnippetCollection();

            _newCollection.Items.Clear();

            foreach (CodeSnippetOld _old in collection.Items)
            {
                if (string.IsNullOrWhiteSpace(_old.Path))
                {
                    _old.Path = Constants.UNNAMED;
                }

                CodeSnippet _new = new CodeSnippet()
                {
                    DefaultChildCodeType        = _old.DefaultChildCodeType,
                    DefaultChildCodeTypeEnabled = _old.DefaultChildCodeTypeEnabled,
                    DefaultChildName            = _old.DefaultChildName,
                    Name        = _old.Name,
                    Blob        = _old.Blob,
                    AlarmActive = _old.AlarmActive,
                    AlarmDate   = _old.AlarmDate,
                    CodeLastModificationDate = _old.CodeLastModificationDate,
                    CodeType        = _old.CodeType,
                    CreationDate    = _old.CreationDate,
                    CurrentLine     = _old.CurrentLine,
                    Expanded        = _old.Expanded,
                    Flag            = _old.Flag,
                    HtmlPreview     = _old.HtmlPreview,
                    Id              = _old.Id,
                    Important       = _old.Important,
                    Locked          = _old.Locked,
                    Order           = _old.Order,
                    ReferenceLinkId = _old.ReferenceLinkId,
                    RTFAlwaysWhite  = _old.RTFAlwaysWhite,
                    RTFOwnTheme     = _old.RTFOwnTheme,
                    RTFTheme        = _old.RTFTheme,
                    ShortCutKeys    = _old.ShortCutKeys,
                    Wordwrap        = _old.Wordwrap
                };

                if (_old.Path.Equals(@"Trashcan"))
                {
                }

                if (_old.Path.Equals(@"C#\Classes\VersionNumber"))
                {
                }

                bool _changed = false;
                _new.SetPath(_old.Path, out _changed);
                _new.SetCode(_old.Code, out _changed);
                _new.SetRtf(_old.RTF, out _changed);
                _new.SetDefaultChildCode(_old.DefaultChildCode, out _changed);
                _new.SetDefaultChildRtf(_old.DefaultChildRtf, out _changed);


                _newCollection.Items.Add(_new);
            }

            TreeNodes.Clear();
            CodeSnippets.Clear();
            CodeSnippets.AddRange(_newCollection.Items);

            if (Counter < collection.Items.Count)
            {
                Counter = collection.Items.Count;
            }

            if (ClipboardMonitor != null)
            {
                ClipboardMonitor.Order = -1;
                ClipboardMonitor.SetPath("Clipboard Monitor", out bool _changed);
            }
            if (Trashcan != null)
            {
                Trashcan.Order = -2;
                Trashcan.SetPath("Trashcan", out bool _changed);
            }

            DocumentId = Guid.NewGuid(); // Legacy always new DocumentId

            EndUpdate();
        }