Exemplo n.º 1
0
        /// <inheritdoc />
        public async ValueTask <bool> ExecuteCodeAsync(IContext e, string body)
        {
            var provider = new CodeProvider(body);

            try
            {
                var block = BlockGenerator.Compile(body);
                return(await ExecuteAsync(e, block, provider));
            }
            catch (MiScriptException ex)
            {
                await SendErrorAsync(
                    e,
                    "error_miscript_parse",
                    ex.Message,
                    new CodeProvider(body),
                    ex.Position);

                return(false);
            }
            catch (Exception ex)
            {
                await SendErrorAsync(
                    e,
                    "error_miscript_parse",
                    "Internal error in MiScript: " + ex.Message,
                    provider);

                return(false);
            }
        }
Exemplo n.º 2
0
        void ExportClassCode(XmlTypeMapping map, bool isTopLevel)
        {
            CodeTypeDeclaration codeClass;

            if (IsMapExported(map))
            {
                codeClass = GetMapDeclaration(map);
                if (codeClass != null)
                {
                    // Regenerate attributes, since things may have changed
                    codeClass.CustomAttributes.Clear();
                    AddClassAttributes(codeClass);
                    GenerateClass(map, codeClass, isTopLevel);
                    ExportDerivedTypeAttributes(map, codeClass);
                }
                return;
            }

            if (map.TypeData.Type == typeof(object))
            {
                exportedAnyType = map;
                SetMapExported(map, null);
                foreach (XmlTypeMapping dmap in exportedAnyType.DerivedTypes)
                {
                    if (IsMapExported(dmap) || !dmap.IncludeInSchema)
                    {
                        continue;
                    }
                    ExportTypeMapping(dmap, false);
                    AddInclude(dmap);
                }
                return;
            }

            codeClass = new CodeTypeDeclaration(map.TypeData.TypeName);
            SetMapExported(map, codeClass);

            AddCodeType(codeClass, map.Documentation);
            codeClass.Attributes = MemberAttributes.Public;

            codeClass.IsPartial = CodeProvider.Supports(GeneratorSupport.PartialTypes);
            AddClassAttributes(codeClass);

            GenerateClass(map, codeClass, isTopLevel);
            ExportDerivedTypeAttributes(map, codeClass);

            ExportMembersMapCode(codeClass, (ClassMap)map.ObjectMap, map.XmlTypeNamespace, map.BaseMap);

            if (map.BaseMap != null && map.BaseMap.TypeData.SchemaType != SchemaTypes.XmlNode)
            {
                CodeTypeReference ctr = GetDomType(map.BaseMap.TypeData, false);
                codeClass.BaseTypes.Add(ctr);
                if (map.BaseMap.IncludeInSchema)
                {
                    ExportMapCode(map.BaseMap, false);
                    AddInclude(map.BaseMap);
                }
            }
            ExportDerivedTypes(map, codeClass);
        }
Exemplo n.º 3
0
        private CodeProvider GetCodeProvider(Type type)
        {
            if (_codeProviders.TryGetValue(type, out var codeProvider) == false)
            {
                codeProvider         = new CodeProvider(type);
                _codeProviders[type] = codeProvider;
            }

            return(codeProvider);
        }
Exemplo n.º 4
0
 private FieldDefinition PrepareStateHoldingField(CodeProvider <ParameterValueHandlingCodeProviderArgument> codeProvider, ModuleDefinition module)
 {
     if (codeProvider.HasState)
     {
         var stateInstanceId = new StateInstanceId(Configuration.StateInstanceName);
         return(StateInstancesCodeGenerator.PrepareInstanceHoldingField(module, codeProvider.GetStateType(), Configuration.StateInstanceName, stateInstanceId));
     }
     else
     {
         return(null);
     }
 }
Exemplo n.º 5
0
        private bool CompileCodeSync(string[] sources)
        {
            StatusManager.Add("PluginCompiler", 2, new Status("", "Compiling...", StandardColors.Orange));

            Profiler.Start("PluginCompiler_CompileCode");

            CompilerParams.ReferencedAssemblies.Clear();
            CompilerParams.ReferencedAssemblies.AddRange(m_DefaultReferencedAssemblies.ToArray());

            var settings = SettingsManager.GetSettings <CompilerSettings>();

            if (settings != null && settings.CompilerReferences != null && settings.CompilerReferences.Length > 0)
            {
                CompilerParams.ReferencedAssemblies.AddRange(settings.CompilerReferences);
            }

            var results = CodeProvider.CompileAssemblyFromSource(CompilerParams, sources);

            Profiler.Stop("PluginCompiler_CompileCode");

            m_IsCompiling = false;

            // This might happen if scripts are modified before compilation is finished
            if (m_ShouldRecompile)
            {
                m_ShouldRecompile = false;
                CompileCode(m_TempSources);
                return(false);
            }

            if (results.Errors.HasErrors)
            {
                foreach (CompilerError error in results.Errors)
                {
                    Logger.Log(LogType.Error,
                               string.Format("({0}): {1}", error.ErrorNumber, error.ErrorText),
                               string.Format("at {0} {1} : {2}", error.FileName, error.Line, error.Column));
                }

                ScriptsRecompiled?.Invoke();
                Logger.Log(LogType.Error, "Scripts have compilation errors.");
                StatusManager.Add("PluginCompiler", 8, new Status("", "Compilation Failed", StandardColors.Red));
                return(false);
            }
            else
            {
                ScriptsRecompiled?.Invoke();
                Logger.Log(LogType.Log, "Scripts successfully compiled.");
                StatusManager.Add("PluginCompiler", 10, new Status("", "Compilation Complete", default(Color)));
                return(true);
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// 使用一组源程序文件来生成一个程序集。
        /// </summary>
        /// <param name="fileNames">外部的一组源程序文件。</param>
        /// <returns>由代码编译成的程序集。</returns>
        public Assembly CompileAssembly(string[] fileNames)
        {
            var compileOption = GetCompilerParameters();

            var compileResult = CodeProvider.CompileAssemblyFromFile(compileOption, fileNames);

            if (compileResult.Errors.HasErrors)
            {
                ThrowCompileException(compileResult);
            }

            return(compileResult.CompiledAssembly);
        }
Exemplo n.º 7
0
 protected override void LoadFromPropertiesInternal(ComponentProcessorProperties properties, TypeAliasResolver typeAliasResolver, string procesorName)
 {
     if (properties.ContainsProperty(nameof(CodeProvider)))
     {
         var odeProviderAlias = properties.GetProperty(nameof(CodeProvider));
         var codeProviderType = typeAliasResolver.ResolveType(odeProviderAlias);
         CodeProvider = (CodeProvider <MethodCodeInjectingCodeProviderArgument>)Activator.CreateInstance(codeProviderType);
     }
     else
     {
         CodeProvider = GetDefaultCodeProvider();
     }
 }
Exemplo n.º 8
0
        /// <summary>
        /// 使用一组源程序文件来生成一个程序集。
        /// </summary>
        /// <param name="unit">代码模型容器。</param>
        /// <returns>由代码编译成的程序集。</returns>
        public Assembly CompileAssembly(CodeCompileUnit unit)
        {
            var compileOption = GetCompilerParameters();

            var compileResult = CodeProvider.CompileAssemblyFromDom(compileOption, unit);

            if (compileResult.Errors.HasErrors)
            {
                ThrowCompileException(compileResult);
            }

            return(compileResult.CompiledAssembly);
        }
Exemplo n.º 9
0
        private void LoadLibs( CodeProvider code )
        {
            treeView1.Nodes.Clear();

            foreach ( Library lib in code.Libraries )
            {
                TreeNode tn = new TreeNode();
                tn.ImageKey = "library";
                tn.SelectedImageKey = "library";
                tn.Text = lib.Name;
                tn.Tag = lib;
                treeView1.Nodes.Add( tn );
            }
        }
Exemplo n.º 10
0
        public ObjectBrowser( CodeProvider cp, ImageList images, Workspace workspace)
        {
            this.Text = "Object Browser";
            InitializeComponent();

            myWorkspace = workspace;

            treeView1.ImageList = images;
            treeView2.ImageList = images;

            code = cp;

            LoadLibs( code );
        }
Exemplo n.º 11
0
        protected override byte[] GenerateContent(string inputFilePath, string inputFileContents)
        {
            var codeNamespace = new CodeNamespace(DefaultNamespace);
            var codeUnit      = Emitter.Emit(_ctx, codeNamespace, inputFilePath);

            using (var w = new StringWriter())
            {
                CodeProvider.GenerateCodeFromCompileUnit(codeUnit, w, new CodeGeneratorOptions
                {
                    BlankLinesBetweenMembers = false,
                });
                return(Encoding.ASCII.GetBytes(w.ToString()));
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Generates and returns the generated output
        /// </summary>
        /// <param name="inputFileName">The name of the file the custom tool is being run against</param>
        /// <param name="inputFileContent">The contents of the file the custom tool is being run against</param>
        protected override byte[] GenerateCode(string inputFileName, string inputFileContent)
        {
            GadgeteerModel model = LoadGadgeteerModel(inputFileName);

            if (model == null)
            {
                OnError("Unable to load model: {0}", inputFileName);
                return(null);
            }

            string userCodeFileName = Path.ChangeExtension(inputFileName, CodeProvider.FileExtension);

            model.GenerateUsingsInUserCode(GlobalServiceProvider, userCodeFileName);

            CodeCompileUnit         code = new CodeCompileUnit();
            CodeTypeDeclaration     programClass;
            CodeStatementCollection mainStatements;
            CodeStatementCollection initializeModuleStatements;
            CodeMemberProperty      mainboard;

            GenerateFileHeader(inputFileName, code, out programClass, out mainStatements, out initializeModuleStatements, out mainboard);

            GenerateMainMethod(mainStatements, model);
            GenerateModulesDeclaration(programClass, model);
            GenerateModulesInitialization(initializeModuleStatements, model);
            GenerateMainboardProperty(mainboard, model);

            if (model.Store != null)
            {
                model.Store.Dispose();
            }

            using (MemoryStream codeStream = new MemoryStream())
            {
                IndentedTextWriter codeWriter = new IndentedTextWriter(new StreamWriter(codeStream));

                try
                {
                    CodeProvider.GenerateCodeFromCompileUnit(code, codeWriter, null);
                }
                catch (Exception compileException)
                {
                    OnError("Code generation failed: {0}", compileException.Message);
                    return(new byte[0]);
                }

                codeWriter.Flush();
                return(codeStream.ToArray());
            }
        }
Exemplo n.º 13
0
        private void AddTryStart(Handler handler)
        {
            Label           tryStart = CodeProvider.TryStart(handler);
            Stack <Handler> stack;

            this.try_start_list.TryGetValue(tryStart, out stack);
            if (stack == null)
            {
                stack = new Stack <Handler> ();
                this.try_start_list [tryStart] = stack;
            }
            stack.Push(handler);
            AddTargetLabel(tryStart);
        }
Exemplo n.º 14
0
        private void AddTryEnd(Handler handler)
        {
            Label           tryEnd = CodeProvider.TryEnd(handler);
            Queue <Handler> queue;

            this.try_end_list.TryGetValue(tryEnd, out queue);
            if (queue == null)
            {
                queue = new Queue <Handler> ();
                this.try_end_list [tryEnd] = queue;
            }
            queue.Enqueue(handler);
            AddTargetLabel(tryEnd);
        }
Exemplo n.º 15
0
        /// <summary>
        /// 编译代码生成一个程序集。
        /// </summary>
        /// <param name="source">程序源代码。</param>
        /// <returns>由代码编译成的程序集。</returns>
        public Assembly CompileAssembly(string source)
        {
#if !NETSTANDARD2_0
            var compileOption = GetCompilerParameters();

            var compileResult = CodeProvider.CompileAssemblyFromSource(compileOption, source);
            if (compileResult.Errors.HasErrors)
            {
                ThrowCompileException(compileResult);
            }

            return(compileResult.CompiledAssembly);
#else
            var compilation = CSharpCompilation.Create(Guid.NewGuid().ToString())
                              .AddSyntaxTrees(CSharpSyntaxTree.ParseText(source))
                              .AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
                              .AddReferences(Assemblies.Select(s => MetadataReference.CreateFromFile(s)))
                              .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            if (!string.IsNullOrEmpty(OutputAssembly))
            {
                var result = compilation.Emit(OutputAssembly);
                if (result.Success)
                {
                    return(Assembly.Load(OutputAssembly));
                }
                else
                {
                    ThrowCompileException(result);
                    return(null);
                }
            }
            else
            {
                using (var ms = new MemoryStream())
                {
                    var result = compilation.Emit(ms);
                    if (result.Success)
                    {
                        return(Assembly.Load(ms.ToArray()));
                    }
                    else
                    {
                        ThrowCompileException(result);
                        return(null);
                    }
                }
            }
#endif
        }
Exemplo n.º 16
0
        /// <summary>
        /// Generates a strongly typed assembly from the resources
        ///
        /// UNDER CONSTRUCTION.
        /// Doesn't work correctly for Web forms due to hard coded resource managers.
        /// </summary>
        /// <param name="ResourceSetName"></param>
        /// <param name="Namespace"></param>
        /// <param name="Classname"></param>
        /// <param name="FileName"></param>
        /// <returns></returns>
        public bool CreateStronglyTypedResource(string ResourceSetName, string Namespace, string Classname, string FileName)
        {
            try
            {
                //wwDbResourceDataManager Data = new wwDbResourceDataManager();
                //IDictionary ResourceSet = Data.GetResourceSet("", ResourceSetName);

                // *** Use the custom ResourceManage to retrieve a ResourceSet
                wwDbResourceManager   Man        = new wwDbResourceManager(ResourceSetName);
                ResourceSet           rs         = Man.GetResourceSet(CultureInfo.InvariantCulture, false, false);
                IDictionaryEnumerator Enumerator = rs.GetEnumerator();

                // *** We have to turn into a concret Dictionary
                Dictionary <string, object> Resources = new Dictionary <string, object>();
                while (Enumerator.MoveNext())
                {
                    DictionaryEntry Item = (DictionaryEntry)Enumerator.Current;
                    Resources.Add(Item.Key as string, Item.Value);
                }

                string[]        UnmatchedElements;
                CodeDomProvider CodeProvider = null;

                string FileExtension = Path.GetExtension(FileName).TrimStart('.').ToLower();
                if (FileExtension == "cs")
                {
                    CodeProvider = new Microsoft.CSharp.CSharpCodeProvider();
                }
                else if (FileExtension == "vb")
                {
                    CodeProvider = new Microsoft.VisualBasic.VBCodeProvider();
                }

                CodeCompileUnit Code = StronglyTypedResourceBuilder.Create(Resources,
                                                                           ResourceSetName, Namespace, CodeProvider, false, out UnmatchedElements);

                StreamWriter writer = new StreamWriter(FileName);
                CodeProvider.GenerateCodeFromCompileUnit(Code, writer, new CodeGeneratorOptions());
                writer.Close();
            }
            catch (Exception ex)
            {
                this.ErrorMessage = ex.Message;
                return(false);
            }

            return(true);
        }
Exemplo n.º 17
0
 private void ComputeTryBlockStartAndEndInfo(Method method)
 {
     foreach (Handler handler in CodeProvider.GetTryBlocks(method))
     {
         if (CodeProvider.IsFilterHandler(handler))
         {
             AddTargetLabel(CodeProvider.FilterExpressionStart(handler));
         }
         AddTargetLabel(CodeProvider.HandlerStart(handler));
         AddTargetLabel(CodeProvider.HandlerEnd(handler));
         AddTryStart(handler);
         AddTryEnd(handler);
         AddHandlerEnd(handler);
         this.handler_starting_at.Add(CodeProvider.HandlerStart(handler), handler);
     }
 }
Exemplo n.º 18
0
        private FieldDefinition PrepareStateHoldingField(string stateInstanceName, CodeProvider <MethodCodeInjectingCodeProviderArgument> codeProvider, ModuleDefinition module)
        {
            if (codeProvider.HasState)
            {
                if (string.IsNullOrWhiteSpace(stateInstanceName))
                {
                    throw new InvalidOperationException($"Code provider '{codeProvider.GetType().FullName}' has state but '{nameof(stateInstanceName)}' is not defined in configuration of processor.");
                }

                var stateInstanceId = new StateInstanceId(stateInstanceName);
                return(StateInstancesCodeGenerator.PrepareInstanceHoldingField(module, codeProvider.GetStateType(), stateInstanceName, stateInstanceId));
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Gets the type of the specified property.
        /// </summary>
        /// <param name="property">The property.</param>
        /// <returns>The type.</returns>
        public string Type(EdmProperty property)
        {
            if (property == null)
            {
                throw new ArgumentNullException("property");
            }

            var clrType = property.PrimitiveType.ClrEquivalentType;
            var type    = StripQualifiers(CodeProvider.GetTypeOutput(new CodeTypeReference(clrType)));

            if (clrType.IsValueType && property.Nullable)
            {
                return(type + "?");
            }

            return(type);
        }
Exemplo n.º 20
0
        static async Task Main(string[] args)
        {
            var codeProvider = new CodeProvider();
            int score        = 0;

            while (true)
            {
                try
                {
                    Console.Clear();
                    Console.WriteLine("----------------------------------------------------------");
                    Console.WriteLine($"Score: {score}");
                    Console.WriteLine("----------------------------------------------------------");

                    var languages = codeProvider.RandomLanguages.Take(4).ToList();
                    var language  = languages.GetRandomElement();
                    var code      = await codeProvider.GetRandomCodeSample(language);

                    Console.WriteLine(code);
                    Console.WriteLine("----------------------------------------------------------");
                    for (int i = 0; i < 4; i++)
                    {
                        Console.WriteLine($"{i + 1}. {languages[i]}");
                    }
                    Console.Write("What is that language? ");
                    var ans = int.Parse(Console.ReadLine());

                    if (languages[ans - 1] == language)
                    {
                        Console.Write("YASS!");
                        score++;
                    }
                    else
                    {
                        Console.WriteLine($"NAAh, it's {language}. Game over!");
                        return;
                    }

                    Console.ReadLine();
                }
                catch
                {
                    Console.WriteLine("Sorry, some error happened. Press Enter to restart.");
                }
            }
        }
Exemplo n.º 21
0
        private void AddHandlerEnd(Handler handler)
        {
            if (!IsFaultOrFinally(handler))
            {
                return;
            }

            Label           handlerEnd = CodeProvider.HandlerEnd(handler);
            Queue <Handler> queue;

            this.subroutine_handler_end_list.TryGetValue(handlerEnd, out queue);
            if (queue == null)
            {
                queue = new Queue <Handler> ();
                this.subroutine_handler_end_list [handlerEnd] = queue;
            }
            queue.Enqueue(handler);
            AddTargetLabel(handlerEnd);
        }
Exemplo n.º 22
0
        public void Run()
        {
            int templateCount = Templates.Count;

            if (templateCount > 0)
            {
                ClearErrMsgs();

                string[] templateArray = new string[templateCount];
                for (int i = 0; i < templateCount; i++)
                {
                    templateArray[i] = Templates[i].TemplateText;
                    //System.IO.File.WriteAllText("c:\\ttt\\f" + i + ".cs", Templates[i].TemplateText);
                }
                Utility.WriteTrace("Compiling assembly...");
                CompilerResults results = CodeProvider.CompileAssemblyFromSource(CodeCompilerParameters, templateArray);
                Utility.WriteTrace("Done!");

                if (results.Errors.Count > 0 || results.CompiledAssembly == null)
                {
                    if (results.Errors.Count > 0)
                    {
                        foreach (CompilerError error in results.Errors)
                        {
                            LogErrMsgs("Compile Error: " + error.ErrorText);
                        }
                    }
                    if (results.CompiledAssembly == null)
                    {
                        string errorMessage = "Error generating template code: This usually indicates an error in template itself, such as use of reserved words. Detail: ";
                        Utility.WriteTrace(errorMessage + errMsg);
                        string sMessage = errorMessage + Environment.NewLine + errMsg;
                        throw new Exception(sMessage);
                    }
                    return;
                }

                Utility.WriteTrace("Extracting code from assembly and scrubbing output...");
                CallEntry(results.CompiledAssembly);
                Utility.WriteTrace("Done!");
            }
        }
Exemplo n.º 23
0
        static SmartPlayerOld()
        {
            var client = new HttpClient();

            var codeFiles = new List <string>();

            foreach (var url in UrlsForSourceCode)
            {
                var code = client.GetStringAsync(url).Result;
                codeFiles.Add(code);
            }

            CompilerParameters parameters = new CompilerParameters();

            // Reference to System.Drawing library
            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.ReferencedAssemblies.Add("System.Core.dll");
            parameters.ReferencedAssemblies.Add("Santase.Logic.dll");

            // True - memory generation, false - external file generation
            parameters.GenerateInMemory = true;

            // True - exe file generation, false - dll file generation
            parameters.GenerateExecutable = false;

            CompilerResults results = CodeProvider.CompileAssemblyFromSource(parameters, codeFiles.ToArray());

            if (results.Errors.HasErrors)
            {
                foreach (CompilerError error in results.Errors)
                {
                    Console.WriteLine("Error compiling old player ({0}): {1} (line: {2}, col: {3})", error.ErrorNumber, error.ErrorText, error.Line, error.Column);
                    return;
                }
            }

            var assembly = results.CompiledAssembly;

            CompiledPlayerType = assembly.GetType("Santase.AI.SmartPlayer.SmartPlayer");
        }
Exemplo n.º 24
0
        public override bool Execute()
        {
            if (String.IsNullOrEmpty(Source))
            {
                return(true);
            }

            try {
                var provider = CodeProvider.ToUpperInvariant() == "VB"
                                        ? (CodeDomProvider) new VBCodeProvider()
                                        : (CodeDomProvider) new CSharpCodeProvider();

                //Validate config keys and generate code
                using (provider) {
                    IList <KeyValuePair <string, string> > settings;
                    if (File.Exists(Source))
                    {
                        settings = XDocument
                                   .Load(Source)
                                   .XPathSelectElements("/configuration/appSettings/add")
                                   .Select(x => new KeyValuePair <string, string>(x.Attribute("key")?.Value, x.Attribute("value")?.Value))
                                   .ToList();

                        ThrowWhenDuplicateKeys(settings);
                        ThrowWhenDuplicateProperties(settings, provider);
                    }
                    else
                    {
                        Log.LogWarning($"Could not find source config file: \"{Source}\"");
                        settings = new List <KeyValuePair <string, string> >();
                    }

                    using (var writer = new StringWriter()) {
                        var ccu = StronglyTypedConfigBuilder.Create(settings, Class, Namespace, provider, InternalClass);
                        provider.GenerateCodeFromCompileUnit(ccu, writer, new CodeGeneratorOptions {
                            BlankLinesBetweenMembers = false
                        });
                        GeneratedCode = writer.ToString();
                    }
                }

                //Prepare temporary file location for generated code
                string tempFilePath = OutputPath == null
                                        ? Path.Combine(Path.GetTempPath(), $"{Namespace.Replace(".", "_")}_{Class}_{Path.GetRandomFileName().Replace(".", "")}.g.cs")
                                        : Path.Combine(OutputPath, $"{Namespace.Replace(".", "_")}_{Class}.g.cs");

                string tempFileDir = Path.GetDirectoryName(tempFilePath);
                if (tempFileDir != null)
                {
                    Directory.CreateDirectory(tempFileDir);
                }

                //Write and output generated code
                File.WriteAllText(tempFilePath, GeneratedCode, Encoding.UTF8);
                GeneratedConfigPath = tempFilePath;
                return(true);
            } catch (Exception ex) {
                Log.LogErrorFromException(ex, false, false, Source);
                return(false);
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Generates an AssemblyInfo file.
        /// </summary>
        protected override void ExecuteTask() {
            try {
                StringCollection imports = new StringCollection();

                foreach (NamespaceImport import in Imports) {
                    if (import.IfDefined && !import.UnlessDefined) {
                        imports.Add(import.Namespace);
                    }
                }

                // ensure base directory is set, even if fileset was not initialized
                // from XML
                if (References.BaseDirectory == null) {
                    References.BaseDirectory = new DirectoryInfo(Project.BaseDirectory);
                }

                // write out code to memory stream, so we can compare it later 
                // to what is already present (if necessary)
                MemoryStream generatedAsmInfoStream = new MemoryStream();

                using (StreamWriter writer = new StreamWriter(generatedAsmInfoStream, Encoding.Default)) {
                    // create new instance of CodeProviderInfo for specified CodeLanguage
                    CodeProvider codeProvider = new CodeProvider(this, Language);

                    // only generate imports here for C#, for VB we create the 
                    // imports as part of the assembly attributes compile unit
                    if (Language == CodeLanguage.CSharp) {
                        // generate imports code
                        codeProvider.GenerateImportCode(imports, writer);
                    }

                    // generate code for assembly attributes
                    codeProvider.GenerateAssemblyAttributesCode(AssemblyAttributes, 
                        imports, References.FileNames, writer);

                    // flush 
                    writer.Flush();

                    // check whether generated source should be persisted
                    if (NeedsPersisting(generatedAsmInfoStream)) {
                        using (FileStream fs = new FileStream(Output.FullName, FileMode.Create, FileAccess.Write)) {
                            byte[] buffer = generatedAsmInfoStream.ToArray();
                            fs.Write(buffer, 0, buffer.Length);
                            fs.Flush();
                            fs.Close();
                            generatedAsmInfoStream.Close();
                        }

                        Log(Level.Info, ResourceUtils.GetString("String_GeneratedFile"),
                            Output.FullName);
                    } else {
                        Log(Level.Verbose, ResourceUtils.GetString("String_FileUpToDate"),
                            Output.FullName);
                    }
                }
            } catch (Exception ex) {
                throw new BuildException(string.Format(
                    CultureInfo.InvariantCulture,
                    ResourceUtils.GetString("NA2004"), Output.FullName), Location, ex);
            }
        }
Exemplo n.º 26
0
        private string Identifier(string value)
        {
            Debug.Assert(!string.IsNullOrEmpty(value), "value is null or empty.");

            return(CodeProvider.CreateValidIdentifier(value));
        }
Exemplo n.º 27
0
        public async Task <HttpResponseMessage> Post(string containerName, [FromBody] ExecutionRequest request)
        {
            var stopwatch = Stopwatch.StartNew();
            var logs      = new List <ExecutionLog>();

            var reservationExists = await MemoryProvider
                                    .ReservationExists(containerName : containerName)
                                    .ConfigureAwait(continueOnCapturedContext: false);

            if (!reservationExists)
            {
                return(this.Request.CreateResponse(statusCode: HttpStatusCode.NotFound));
            }

            var downloaded = await CodeProvider
                             .DownloadIfNotExists(
                functionId : request.Function.Id,
                blobUri : request.Function.BlobUri)
                             .ConfigureAwait(continueOnCapturedContext: false);

            if (downloaded)
            {
                logs.Add(new ExecutionLog
                {
                    Name     = "DownloadCodeIfNotExists",
                    Duration = stopwatch.ElapsedMilliseconds - (logs.Count > 0 ? logs.Last().Duration : 0)
                });
            }

            var created = await ContainerProvider
                          .CreateContainerIfNotExists(
                containerName : containerName,
                functionId : request.Function.Id,
                memorySize : request.Function.MemorySize)
                          .ConfigureAwait(continueOnCapturedContext: false);

            if (created)
            {
                logs.Add(new ExecutionLog
                {
                    Name     = "CreateContainerIfNotExists",
                    Duration = stopwatch.ElapsedMilliseconds - (logs.Count > 0 ? logs.Last().Duration : 0)
                });
            }

            var container = await ContainerProvider
                            .TryReserve(containerName : containerName)
                            .ConfigureAwait(continueOnCapturedContext: false);

            if (container == null)
            {
                return(this.Request.CreateResponse(statusCode: HttpStatusCode.NotFound));
            }

            var response = await container
                           .Execute(request : request)
                           .ConfigureAwait(continueOnCapturedContext: false);

            logs.Add(new ExecutionLog
            {
                Name     = "Execute",
                Duration = stopwatch.ElapsedMilliseconds - (logs.Count > 0 ? logs.Last().Duration : 0)
            });

            await ContainerProvider
            .ReleaseContainer(containerName : containerName)
            .ConfigureAwait(continueOnCapturedContext: false);

            MemoryProvider.SendWarmReservation(
                queueName: request.Function.Id,
                containerName: containerName);

            response.Logs = new ExecutionLog
            {
                Name     = "ExecuteController",
                Duration = stopwatch.ElapsedMilliseconds,
                SubLogs  = logs.ToArray()
            };

            return(this.Request.CreateResponse(
                       statusCode: HttpStatusCode.OK,
                       value: response));
        }
Exemplo n.º 28
0
        /// <summary>
        /// Creates a new Environment class
        /// </summary>
        /// <param name="sdm">The docking manager used by GLua</param>
        /// <param name="tStrip">Tab context menu</param>
        /// <param name="eStrip">Edit control context menu</param>
        /// <param name="pStrip">Project node context menu</param>
        /// <param name="cStrip">Code node context menu</param>
        /// <param name="fStrip">Folder node context menu</param>
        /// <param name="code">Code provider for code completion</param>
        public Workspace(DockContainer sdm, ContextMenuStrip tStrip, ContextMenuStrip eStrip, ContextMenuStrip pStrip,
                         ContextMenuStrip cStrip, ContextMenuStrip fStrip, ImageList images)
        {
            // set all the values
            Manager = sdm;
            ImageList = images;

            _explorer = new ProjectExplorer(this);
            TreeView = _explorer.tvFiles;
            ImageList = _explorer.imgList;
            _explorer.Show(sdm, DockState.DockLeft); //, DockState.DockLeft);

            _bug = new WebWindow("http://code.google.com/p/gluar/issues/list") {TabText = "Bug Reporter"};

            TabStrip = tStrip;
            EditStrip = eStrip;
            ProjectStrip = _explorer.projectMenu;
            CodeStrip = _explorer.fileMenu;
            FolderStrip = _explorer.folderMenu;

            // used to set the right clicked node as the current node
            //treeView.NodeMouseClick += new TreeNodeMouseClickEventHandler(treeView_NodeMouseClick);

            // Taken out by Marine
            // !  Put back in by VoiDeD
            // load the code database and settings
            _code = CodeProvider.Load(Application.StartupPath + "\\code.db");

            _obj = new ObjectBrowser(_code, images, this);

            // Taken out by Marine
            // Get working in next version
            //settings = Settings.Load( Application.StartupPath + "\\data\\settings.xml" );
        }
Exemplo n.º 29
0
 public int GetILOffset(Label label)
 {
     return(CodeProvider.GetILOffset(label));
 }
Exemplo n.º 30
0
 private void btnPlayGroud_Click(object sender, EventArgs e)
 {
     richTextBox2.Text = CodeProvider.codeRun(richTextBox1.Text);
 }
Exemplo n.º 31
0
 private bool IsFaultOrFinally(Handler handler)
 {
     return(CodeProvider.IsFaultHandler(handler) || CodeProvider.IsFinallyHandler(handler));
 }
Exemplo n.º 32
0
        public override BlockWithLabels <Label> RecordInformationForNewBlock(Label currentLabel, BlockWithLabels <Label> previousBlock)
        {
            BlockWithLabels <Label> result     = null;
            Queue <Handler>         handlerEnd = GetHandlerEnd(currentLabel);

            if (handlerEnd != null)
            {
                foreach (Handler handler in handlerEnd)
                {
                    this.subroutine_stack.Head.Commit();
                    this.subroutine_stack = this.subroutine_stack.Tail;
                    previousBlock         = null;
                }
            }
            Queue <Handler> tryEnd = GetTryEnd(currentLabel);

            if (tryEnd != null)
            {
                foreach (Handler handler in tryEnd)
                {
                    if (!Equals(handler, CurrentProtectingHanlders.Head))
                    {
                        throw new InvalidOperationException("wrong handler");
                    }
                    CurrentProtectingHanlders = CurrentProtectingHanlders.Tail;
                }
            }
            Handler handler1;

            if (IsHandlerStart(currentLabel, out handler1))
            {
                if (IsFaultOrFinally(handler1))
                {
                    SubroutineWithHandlers <Label, Handler> sub = !CodeProvider.IsFaultHandler(handler1)
                                                                                        ? new FinallySubroutine <Label, Handler> (this.SubroutineFacade, currentLabel, this)
                                                                                        : (FaultFinallySubroutineBase <Label, Handler>) new FaultSubroutine <Label, Handler> (this.SubroutineFacade, currentLabel, this);
                    CurrentSubroutineWithHandlers.FaultFinallySubroutines.Add(handler1, sub);
                    this.subroutine_stack = this.subroutine_stack.Cons(sub);
                    previousBlock         = null;
                }
                else
                {
                    result = CurrentSubroutineWithHandlers.CreateCatchFilterHeader(handler1, currentLabel);
                }
            }
            if (result == null)
            {
                result = base.RecordInformationForNewBlock(currentLabel, previousBlock);
            }
            Stack <Handler> tryStart = GetTryStart(currentLabel);

            if (tryStart != null)
            {
                foreach (Handler handler in tryStart)
                {
                    CurrentProtectingHanlders = CurrentProtectingHanlders.Cons(handler);
                }
            }

            CurrentSubroutineWithHandlers.ProtectingHandlers.Add(result, CurrentProtectingHanlders);
            return(result);
        }
Exemplo n.º 33
0
        /// <summary>
        /// Generates an AssemblyInfo file.
        /// </summary>
        protected override void ExecuteTask()
        {
            try {
                StringCollection imports = new StringCollection();

                foreach (NamespaceImport import in Imports)
                {
                    if (import.IfDefined && !import.UnlessDefined)
                    {
                        imports.Add(import.Namespace);
                    }
                }

                // ensure base directory is set, even if fileset was not initialized
                // from XML
                if (References.BaseDirectory == null)
                {
                    References.BaseDirectory = new DirectoryInfo(Project.BaseDirectory);
                }

                // write out code to memory stream, so we can compare it later
                // to what is already present (if necessary)
                MemoryStream generatedAsmInfoStream = new MemoryStream();

                using (StreamWriter writer = new StreamWriter(generatedAsmInfoStream, Encoding.Default)) {
                    // create new instance of CodeProviderInfo for specified CodeLanguage
                    CodeProvider codeProvider = new CodeProvider(this, Language);

                    // only generate imports here for C#, for VB we create the
                    // imports as part of the assembly attributes compile unit
                    if (Language == CodeLanguage.CSharp)
                    {
                        // generate imports code
                        codeProvider.GenerateImportCode(imports, writer);
                    }

                    // generate code for assembly attributes
                    codeProvider.GenerateAssemblyAttributesCode(AssemblyAttributes,
                                                                imports, References.FileNames, writer);

                    // flush
                    writer.Flush();

                    // check whether generated source should be persisted
                    if (NeedsPersisting(generatedAsmInfoStream))
                    {
                        using (FileStream fs = new FileStream(Output.FullName, FileMode.Create, FileAccess.Write)) {
                            byte[] buffer = generatedAsmInfoStream.ToArray();
                            fs.Write(buffer, 0, buffer.Length);
                            fs.Flush();
                            fs.Close();
                            generatedAsmInfoStream.Close();
                        }

                        Log(Level.Info, ResourceUtils.GetString("String_GeneratedFile"),
                            Output.FullName);
                    }
                    else
                    {
                        Log(Level.Verbose, ResourceUtils.GetString("String_FileUpToDate"),
                            Output.FullName);
                    }
                }
            } catch (Exception ex) {
                throw new BuildException(string.Format(
                                             CultureInfo.InvariantCulture,
                                             ResourceUtils.GetString("NA2004"), Output.FullName), Location, ex);
            }
        }
        CodeTypeDeclaration ExportStruct(StructMapping mapping)
        {
            if (mapping.TypeDesc.IsRoot)
            {
                ExportRoot(mapping, typeof(SoapIncludeAttribute));
                return(null);
            }
            if (!mapping.IncludeInSchema)
            {
                return(null);
            }

            string className = mapping.TypeDesc.Name;
            string baseName  = mapping.TypeDesc.BaseTypeDesc == null ? string.Empty : mapping.TypeDesc.BaseTypeDesc.Name;

            CodeTypeDeclaration codeClass = new CodeTypeDeclaration(className);

            codeClass.IsPartial = CodeProvider.Supports(GeneratorSupport.PartialTypes);
            codeClass.Comments.Add(new CodeCommentStatement(Res.GetString(Res.XmlRemarks), true));

            CodeNamespace.Types.Add(codeClass);

            if (baseName != null && baseName.Length > 0)
            {
                codeClass.BaseTypes.Add(baseName);
            }
            else
            {
                AddPropertyChangedNotifier(codeClass);
            }

            codeClass.TypeAttributes |= TypeAttributes.Public;
            if (mapping.TypeDesc.IsAbstract)
            {
                codeClass.TypeAttributes |= TypeAttributes.Abstract;
            }

            CodeExporter.AddIncludeMetadata(codeClass.CustomAttributes, mapping, typeof(SoapIncludeAttribute));

            if (GenerateProperties)
            {
                for (int i = 0; i < mapping.Members.Length; i++)
                {
                    ExportProperty(codeClass, mapping.Members[i], mapping.Scope);
                }
            }
            else
            {
                for (int i = 0; i < mapping.Members.Length; i++)
                {
                    ExportMember(codeClass, mapping.Members[i]);
                }
            }
            for (int i = 0; i < mapping.Members.Length; i++)
            {
                EnsureTypesExported(mapping.Members[i].Elements, null);
            }

            if (mapping.BaseMapping != null)
            {
                ExportType(mapping.BaseMapping);
            }

            ExportDerivedStructs(mapping);
            CodeGenerator.ValidateIdentifiers(codeClass);
            return(codeClass);
        }