コード例 #1
0
        public void RegisterBuildProvider()
        {
            AssertExtensions.Throws <ArgumentException> (() =>
            {
                BuildProvider.RegisterBuildProvider(null, typeof(FooBuildProvider));
            }, "#A1-1");

            AssertExtensions.Throws <ArgumentException> (() =>
            {
                BuildProvider.RegisterBuildProvider(String.Empty, typeof(FooBuildProvider));
            }, "#A1-2");

            AssertExtensions.Throws <ArgumentNullException> (() =>
            {
                BuildProvider.RegisterBuildProvider(".foo", null);
            }, "#A1-3");

            AssertExtensions.Throws <ArgumentException> (() =>
            {
                BuildProvider.RegisterBuildProvider(".foo", typeof(string));
            }, "#A1-4");

            // This would have worked if we called the method during the pre-application start stage
            // (we have a test for this in the standalone test suite)
            AssertExtensions.Throws <InvalidOperationException> (() =>
            {
                BuildProvider.RegisterBuildProvider(".foo", typeof(BuildProvider));
            }, "#A1-5");
        }
コード例 #2
0
    private static void DryRun()
    {
        var provider   = new BuildProvider(AssetDatabase.LoadAssetAtPath <BuildProviderSettingAsset>("Assets/Example/Editor/BuildProviderSettingAsset.asset"));
        var returnCode = provider.DryRun();

        UnityEngine.Debug.Log(returnCode);
    }
コード例 #3
0
        private async Task OnConnectAsync()
        {
            IsConnecting = true;

            try
            {
                Application.Current.Dispatcher.Invoke(() => { BuildDefinitions.Clear(); });

                var buildDefinitions = await BuildProvider.GetBuildDefinitionsAsync(MonitorSettings).ConfigureAwait(false);

                if (buildDefinitions.IsSuccessStatusCode)
                {
                    Application.Current.Dispatcher.Invoke(() => { ApplyBuildDefinitions(buildDefinitions.Data); });
                    StatusText = String.Empty;
                    ShowPersonalAccessTokenInput = false;
                }
                else
                {
                    AccessTokenInputWhenUnauthorized(buildDefinitions.StatusCode);
                }
            }
            catch (AdvancedHttpRequestException ex)
            {
                AccessTokenInputWhenUnauthorized(ex.StatusCode);
            }
            catch (Exception ex)
            {
                StatusText = ex.Message;
            }

            IsConnecting = false;
        }
コード例 #4
0
ファイル: FooBuildProvider.cs プロジェクト: pmq20/mono_forked
        public static void RegisterFooBuildProvider()
        {
            Log.Data.Add("RegisterFooBuildProvider called");

            try {
                BuildProvider.RegisterBuildProvider(".foo", typeof(string));
                Log.Data.Add("Registering typeof (string) succeeded.");
            } catch (ArgumentException) {
                Log.Data.Add("Registering typeof (string) failed (ArgumentException)");
            } catch (Exception ex) {
                Log.Data.Add(String.Format("Registering typeof (string) failed ({0})", ex.GetType()));
            }

            try {
                BuildProvider.RegisterBuildProvider(".foo", typeof(BuildProvider));
                Log.Data.Add("Registering typeof (BuildProvider) succeeded.");
            } catch (ArgumentException) {
                Log.Data.Add("Registering typeof (BuildProvider) failed (ArgumentException)");
            } catch (Exception ex) {
                Log.Data.Add(String.Format("Registering typeof (BuildProvider) failed ({0})", ex.GetType()));
            }

            try {
                BuildProvider.RegisterBuildProvider(".foo", typeof(FooBuildProvider));
                Log.Data.Add("Registering typeof (FooBuildProvider) succeeded.");
            } catch (ArgumentException) {
                Log.Data.Add("Registering typeof (FooBuildProvider) failed (ArgumentException)");
            } catch (Exception ex) {
                Log.Data.Add(String.Format("Registering typeof (FooBuildProvider) failed ({0})", ex.GetType()));
            }
        }
コード例 #5
0
 private static void SetupEmbeddedResource(AssemblyBuilder assemblyBuilder,
                                           BuildProvider prov, XmlElement xmlElement, string resourceName)
 {
     using (Stream resStream = assemblyBuilder.CreateEmbeddedResource(prov, resourceName))
     {
         EntityDesignerUtils.OutputXmlElementToStream(xmlElement, resStream);
     }
 }
コード例 #6
0
 private void UpdateSoftware(SoftwareInfo software)
 {
     software.Category = CategoryProvider.GetCategory(software);
     software.Source   = SourceProvider.GetSource(software);
     software.Build    = BuildProvider.GetBuild(software);
     software.Compiler = CompilerProvider.GetCompiler(software);
     software.Encoding = EncodingProvider.GetEncoding(software);
 }
コード例 #7
0
 public static void Start()
 {
     if (_startWasCalled)
     {
         return;
     }
     _startWasCalled = true;
     BuildProvider.RegisterBuildProvider(".cshtml", typeof(SimpleRazorBuildProvider));
 }
コード例 #8
0
        public void GenerateCode(AssemblyBuilder assemblyBuilder, Stream xamlStream, BuildProvider buildProvider)
        {
            object serviceObject = WorkflowServiceHostFactory.LoadXaml(xamlStream);

            WorkflowService workflowService = serviceObject as WorkflowService;

            if (workflowService != null && workflowService.Body != null)
            {
                string activityName;
                if (this.TryGenerateSource(assemblyBuilder, buildProvider, workflowService, false, null, out activityName))
                {
                    this.generatedPrimaryTypeName = GeneratedNamespace + "." + activityName + ExpressionRootFactorySuffix;
                }

                // find all supported versions xamlx files, load and compile them
                IList <Tuple <string, Stream> > streams = null;

                string xamlVirtualFile = GetXamlVirtualPath(buildProvider);
                string xamlFileName    = Path.GetFileNameWithoutExtension(VirtualPathUtility.GetFileName(xamlVirtualFile));
                WorkflowServiceHostFactory.GetSupportedVersionStreams(xamlFileName, out streams);
                if (streams != null)
                {
                    try
                    {
                        foreach (Tuple <string, Stream> stream in streams)
                        {
                            try
                            {
                                WorkflowService service = WorkflowServiceHostFactory.CreatetWorkflowService(stream.Item2, workflowService.Name);
                                if (service != null && service.Body != null)
                                {
                                    this.TryGenerateSource(assemblyBuilder, buildProvider, service, true, stream.Item1, out activityName);
                                }
                            }
                            catch (Exception e)
                            {
                                Exception newException;
                                if (Fx.IsFatal(e) || !WorkflowServiceHostFactory.TryWrapSupportedVersionException(stream.Item1, e, out newException))
                                {
                                    throw;
                                }

                                throw FxTrace.Exception.AsError(newException);
                            }
                        }
                    }
                    finally
                    {
                        foreach (Tuple <string, Stream> stream in streams)
                        {
                            stream.Item2.Dispose();
                        }
                    }
                }
            }
        }
コード例 #9
0
        public void EqualsAndHashCode()
        {
            BuildProvider b1, b2;

            b1 = new BuildProvider(".hi", "System.Bye");
            b2 = new BuildProvider(".hi", "System.Bye");

            Assert.IsTrue(b1.Equals(b2), "A1");
            Assert.AreEqual(b1.GetHashCode(), b2.GetHashCode(), "A2");
        }
コード例 #10
0
        ///-------------------------------------------------------------------------------------------------
        /// <summary>
        ///     Initialises this object.
        /// </summary>
        ///-------------------------------------------------------------------------------------------------

        public static void Init()
        {
            BuildProvider.RegisterBuildProvider(".mustactml", typeof(RazorBuildProvider));

            // add the new extensions to the collection of languages supported by Razor
            RazorCodeLanguage.Languages.Add("mustactml", new CSharpRazorCodeLanguage());

            // register the extensions
            WebPageHttpHandler.RegisterExtension("mustactml");
        }
コード例 #11
0
 void WriteCodeFile(AssemblyBuilder assemblyBuilder, BuildProvider buildProvider, string name)
 {
     using (TextWriter codeFile = assemblyBuilder.CreateCodeFile(buildProvider))
     {
         foreach (string line in File.ReadLines(name))
         {
             codeFile.WriteLine(line);
         }
     }
 }
コード例 #12
0
        public static void Start()
        {
            if (!_startWasCalled)
            {
                _startWasCalled = true;

                PageBuildProvider.CompilerFactory
                .RegisterExtensionsForAssembly(typeof(ExtensionLoader).Assembly);

                const string extension = "." + PageBuildProvider.FileExtension;

                BuildProvider.RegisterBuildProvider(extension, typeof(ViewPageBuildProvider));
            }
        }
コード例 #13
0
        public static void Start()
        {
            // Even though ASP.NET will only call each PreAppStart once, we sometimes internally call one PreAppStart from
            // another PreAppStart to ensure that things get initialized in the right order. ASP.NET does not guarantee the
            // order so we have to guard against multiple calls.
            // All Start calls are made on same thread, so no lock needed here.

            if (_startWasCalled)
            {
                return;
            }
            _startWasCalled = true;

            BuildProvider.RegisterBuildProvider(".cshtml", typeof(RazorBuildProvider));
        }
コード例 #14
0
        bool TryGenerateSource(AssemblyBuilder assemblyBuilder, BuildProvider buildProvider, WorkflowService workflowService, bool isSupportedVersion, string filePath, out string activityName)
        {
            bool   generatedSource;
            string codeFileName;

            this.GenerateSource(isSupportedVersion, filePath, assemblyBuilder, workflowService, out codeFileName, out generatedSource, out activityName);

            if (generatedSource)
            {
                this.WriteCodeFile(assemblyBuilder, buildProvider, codeFileName);
                this.GenerateExpressionRootFactory(assemblyBuilder, buildProvider, GeneratedNamespace, activityName);
            }

            return(generatedSource);
        }
コード例 #15
0
        public static void Start()
        {
            if (!startWasCalled)
            {
                startWasCalled = true;

                TypeLoader.Instance = new WebTypeLoader();

                XmlDynamicResolver.RegisterResolver(Uri.UriSchemeFile, typeof(XmlVirtualPathAwareUrlResolver));
                XmlDynamicResolver.RegisterResolver(Uri.UriSchemeHttp, typeof(XmlVirtualPathAwareUrlResolver));

                BuildProvider.RegisterBuildProvider(".xsl", typeof(XsltPageBuildProvider));
                BuildProvider.RegisterBuildProvider(".xqy", typeof(XQueryPageBuildProvider));
            }
        }
コード例 #16
0
        private static void RegisterJS()
        {
            BuildProvider.RegisterBuildProvider(".js", typeof(StaticBuildProvider));
            WebPageLocatorFactory.RegisterLocator(".js", StaticPageLocator.Instance);
            WebPageExtensions.Register(".js");

#if (DEBUG)
            _watchers.Add(PageUtil.WatchFiles(".js", (file, virtaulPath) =>
            {
                if (!StaticBuildProvider.IsIgnore(virtaulPath))
                {
                    StaticBuildProvider.RemoveCache();
                }
            }));
#endif
        }
コード例 #17
0
        internal static void AddArtifactReference(AssemblyBuilder assemblyBuilder, BuildProvider prov, string virtualPath)
        {
            // add the artifact as a resource to the DLL
            using (Stream input = VirtualPathProvider.OpenFile(virtualPath))
            {
                // derive the resource name
                string name = BuildProviderUtils.GetResourceNameForVirtualPath(virtualPath);

                using (Stream resStream = assemblyBuilder.CreateEmbeddedResource(prov, name))
                {
                    int byteRead = input.ReadByte();
                    while (byteRead != -1)
                    {
                        resStream.WriteByte((byte)byteRead);
                        byteRead = input.ReadByte();
                    }
                }
            }
        }
コード例 #18
0
        void GenerateExpressionRootFactory(AssemblyBuilder assemblyBuilder, BuildProvider buildProvider, string activityNamespace, string activityName)
        {
            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();

            // namespace <%= activityNamespace %>
            // {
            //     public class <%= activityName %>_ExpressionRootFactory : System.ServiceModel.Activities.WorkflowService
            //     {
            //         public static System.Activities.XamlIntegration.ICompiledExpressionRoot CreateExpressionRoot(System.Activities.Activity activity)
            //         {
            //             return new <%= activityNamespace %>.<%= activityName %>(activity);
            //         }
            //     }
            // }
            CodeNamespace       codeNamespace       = new CodeNamespace(activityNamespace);
            CodeTypeDeclaration codeTypeDeclaration = new CodeTypeDeclaration(activityName + ExpressionRootFactorySuffix);

            codeTypeDeclaration.BaseTypes.Add(new CodeTypeReference(typeof(WorkflowService)));

            CodeMemberMethod codeMemberMethod = new CodeMemberMethod();

            codeMemberMethod.Name       = CreateExpressionRootMethodName;
            codeMemberMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            codeMemberMethod.ReturnType = new CodeTypeReference(typeof(ICompiledExpressionRoot));
            codeMemberMethod.Parameters.Add(new CodeParameterDeclarationExpression(
                                                new CodeTypeReference(typeof(Activity)),
                                                ActivityParameterName));

            CodeTypeReference          typeRef = new CodeTypeReference(activityNamespace + "." + activityName);
            CodeObjectCreateExpression expr    = new CodeObjectCreateExpression(typeRef, new CodeArgumentReferenceExpression(ActivityParameterName));

            codeMemberMethod.Statements.Add(new CodeMethodReturnStatement(expr));

            codeTypeDeclaration.Members.Add(codeMemberMethod);
            codeNamespace.Types.Add(codeTypeDeclaration);
            codeCompileUnit.Namespaces.Add(codeNamespace);

            assemblyBuilder.AddCodeCompileUnit(buildProvider, codeCompileUnit);
        }
コード例 #19
0
        public static void Start()
        {
            if (_startWasCalled)
            {
                return;
            }
            _startWasCalled = true;

            //be sure default buildproviders are registered first
            System.Web.WebPages.PreApplicationStartCode.Start();
            System.Web.WebPages.Razor.PreApplicationStartCode.Start();

            ControllerBuilder.Current.SetControllerFactory(new SignumControllerFactory());
            HostingEnvironment.RegisterVirtualPathProvider(new CompiledVirtualPathProvider(HostingEnvironment.VirtualPathProvider));
            BuildProvider.RegisterBuildProvider(".cshtml", typeof(CompiledRazorBuildProvider));

            ModelBinders.Binders.DefaultBinder = new LiteModelBinder();
            ModelBinders.Binders.Add(typeof(DateTime), new CurrentCultureDateModelBinder());
            ModelBinders.Binders.Add(typeof(DateTime?), new CurrentCultureDateModelBinder());
            ModelBinders.Binders.Add(typeof(FindOptions), new FindOptionsModelBinder());
            ModelBinders.Binders.Add(typeof(QueryRequest), new QueryRequestModelBinder());
        }
コード例 #20
0
        private static void RegisterHTM()
        {
            WebPageLocatorFactory.RegisterLocator(".htm", XamlPageLocator.Instance);
            WebPageExtensions.Register(".htm");

            BuildProvider.RegisterBuildProvider(".htm", typeof(XPCBuildProvider));
            //在VS里执行生成时,App_Code下的cs文件会自动编译,如果某个文件生成失败,那么整个生成操作(包括htm)会终止并且报错
            //这就导致修改后的htm始终无法生成新的cs文件,因此,我们使用XPCBuildIgnoreProvider来让VS不执行cs的生成操作
            BuildProvider.RegisterBuildProvider(".cs", typeof(XPCBuildIgnoreProvider));

#if (DEBUG)
            _watchers.Add(PageUtil.WatchFiles(".htm", (file, virtualPath) =>
            {
                HtmlWatcher.Instance.OnChange(virtualPath);
            }));

            _watchers.Add(PageUtil.WatchFiles(".cs", (file, virtualPath) =>
            {
                CSharpWatcher.Instance.OnChange(virtualPath);
            }));
#endif
        }
コード例 #21
0
        private async Task <SoftwareData> GetSoftwareAsync(SoftwareCameraInfo camera, SoftwareInfo softwareInfo, CancellationToken cancellationToken)
        {
            SetTitle(nameof(Resources.Download_FetchingData_Text));

            var buildName = BuildProvider.GetBuildName(softwareInfo);
            var matches   = await MatchProvider.GetMatchesAsync(camera, buildName, cancellationToken);

            if (matches == null)
            {
                var error = MatchProvider.GetError();
                SetTitle(error, LogLevel.Error);
                return(null);
            }

            var match     = matches.Last();
            var info      = SoftwareProvider.GetSoftware(match);
            var downloads = DownloadProvider.GetDownloads(matches, info).ToArray();

            return(new SoftwareData
            {
                Info = info,
                Downloads = downloads,
            });
        }
コード例 #22
0
 internal ApplicationBrowserCapabilitiesCodeGenerator(BuildProvider buildProvider) {
     _browserOverrides = new OrderedDictionary();
     _defaultBrowserOverrides = new OrderedDictionary();
     _buildProvider = buildProvider;
 }
コード例 #23
0
			public BuildProviderItem (BuildProvider bp, int listIndex, int parentIndex)
			{
				this.Provider = bp;
				this.ListIndex = listIndex;
				this.ParentIndex = parentIndex;
			}
コード例 #24
0
		bool IsDependencyCycle (BuildProvider buildProvider)
		{
			var cache = new Dictionary <BuildProvider, bool> ();
			cache.Add (buildProvider, true);
			return IsDependencyCycle (cache, buildProvider.ExtractDependencies ());
		}
コード例 #25
0
 private string GetXamlVirtualPath(BuildProvider buildProvider)
 {
     return(((System.Xaml.Hosting.XamlBuildProvider)buildProvider).VirtualPath);
 }
コード例 #26
0
    // Add a checksum pragma.  This is used for improved debugging experience.
    private void AddChecksumPragma(BuildProvider buildProvider, CodeCompileUnit compileUnit) {

        // If we can't get a virtual path, do nothing
        if (buildProvider == null || buildProvider.VirtualPath == null)
            return;

        // Only do this if we're compiling in debug mode
        if (!_compilerType.CompilerParameters.IncludeDebugInformation)
            return;

        string physicalPath = HostingEnvironment.MapPathInternal(buildProvider.VirtualPath);

        // Only do this is the file physically exists, which it would not in the
        // case of a non-file based VirtualPathProvider.  In such case, there is
        // no point in putting the pragma, since the debugger could not locate
        // the file anyway.
        if (!File.Exists(physicalPath))
            return;

        CodeChecksumPragma pragma = new CodeChecksumPragma() {
            ChecksumAlgorithmId = s_codeChecksumSha1Id
        };

        if (_compConfig.UrlLinePragmas) {
            pragma.FileName = ErrorFormatter.MakeHttpLinePragma(buildProvider.VirtualPathObject.VirtualPathString);
        }
        else {
            pragma.FileName = physicalPath;
        }

        // Generate a SHA1 hash from the contents of the file

        // The VS debugger uses a cryptographic hash of the file being debugged so that it doesn't accidentally
        // display to the user the wrong version of the file. This is merely a convenience feature for debugging
        // purposes and is not security-related in any way. Since VS only supports MD5 and SHA1 hashes, we just
        // use SHA1 and suppress the [Obsolete] warning.
#pragma warning disable 618
        using (Stream stream = new FileStream(physicalPath, FileMode.Open, FileAccess.Read, FileShare.Read)) {
            using (SHA1 hashAlgorithm = CryptoAlgorithms.CreateSHA1()) {
                pragma.ChecksumData = hashAlgorithm.ComputeHash(stream);
            }
        }
#pragma warning restore 618

        // Add the pragma to the CodeCompileUnit
        compileUnit.StartDirectives.Add(pragma);
    }
コード例 #27
0
ファイル: BuildManager.cs プロジェクト: Profit0004/mono
		internal static Type GetCodeDomProviderType (BuildProvider provider)
		{
			CompilerType codeCompilerType;
			Type codeDomProviderType = null;

			codeCompilerType = provider.CodeCompilerType;
			if (codeCompilerType != null)
				codeDomProviderType = codeCompilerType.CodeDomProviderType;
				
			if (codeDomProviderType == null)
				throw new HttpException (String.Concat ("Provider '", provider, " 'fails to specify the compiler type."));

			return codeDomProviderType;
		}
コード例 #28
0
ファイル: AssemblyBuilder.cs プロジェクト: ztzg/mono
		public Stream CreateEmbeddedResource (BuildProvider buildProvider, string name)
		{
			if (buildProvider == null)
				throw new ArgumentNullException ("buildProvider");

			if (name == null || name == "")
				throw new ArgumentNullException ("name");

			string filename = GetTempFilePhysicalPath ("resource");
			Stream stream = File.OpenWrite (filename);
			ResourceFiles [name] = filename;
			return stream;
		}
コード例 #29
0
    private void AddCompileWithBuildProvider(VirtualPath virtualPath, BuildProvider owningBuildProvider) {

        BuildProvider buildProvider = BuildManager.CreateBuildProvider(virtualPath,
            _compConfig, _initialReferencedAssemblies, true /*failIfUnknown*/);

        // Since it's referenced via compileWith, it doesn't need its own build result
        buildProvider.SetNoBuildResult();

        // If it's a CompileWith provider, remember the main provider
        SourceFileBuildProvider sourceBuildProvider = buildProvider as SourceFileBuildProvider;
        if (sourceBuildProvider != null)
            sourceBuildProvider.OwningBuildProvider = owningBuildProvider;

        AddBuildProvider(buildProvider);
    }
コード例 #30
0
 public void AddCodeCompileUnit(BuildProvider buildProvider, CodeCompileUnit compileUnit)
 {
     InnerBuilder.AddCodeCompileUnit(buildProvider, compileUnit);
 }
コード例 #31
0
    private bool IsBuildProviderSkipable(BuildProvider buildProvider) {

        // If another build provider depends on it, we should not skip it
        if (buildProvider.IsDependedOn) return false;

        // No one depends on it (at least in this directory)

        // If it's a source file, skip it.  We need to do this for v1 compatibility,
        // since v1 VS projects contain many source files which have already been
        // precompiled into bin, and that should not be compiled dynamically
        if (buildProvider is SourceFileBuildProvider)
            return true;

        // For the same reason, skip resources
        if (buildProvider is ResXBuildProvider)
            return true;

        return false;
    }
コード例 #32
0
 public void AddCodeCompileUnit(BuildProvider buildProvider, CodeCompileUnit compileUnit)
 {
     BuildProvider = buildProvider;
     CompileUnit   = compileUnit;
 }
コード例 #33
0
 public void Add(BuildProvider buildProvider) {
     BaseAdd(buildProvider);
 }
コード例 #34
0
ファイル: BuildManager.cs プロジェクト: Profit0004/mono
		internal static ICollection GetVirtualPathDependencies (string virtualPath, BuildProvider bprovider)
		{
			BuildProvider provider = bprovider;
			if (provider == null) {
				CompilationSection cs = CompilationConfig;
				if (cs == null)
					return null;
				provider = BuildManagerDirectoryBuilder.GetBuildProvider (virtualPath, cs.BuildProviders);
			}
			
			if (provider == null)
				return null;
			
			IDictionary <string, bool> deps =  provider.ExtractDependencies ();
			if (deps == null)
				return null;

			return (ICollection)deps.Keys;
		}
コード例 #35
0
ファイル: BuildManager.cs プロジェクト: Profit0004/mono
		static void StoreInCache (BuildProvider bp, Assembly compiledAssembly, CompilerResults results)
		{
			string virtualPath = bp.VirtualPath;
			var item = new BuildManagerCacheItem (compiledAssembly, bp, results);
			
			if (buildCache.ContainsKey (virtualPath))
				buildCache [virtualPath] = item;
			else
				buildCache.Add (virtualPath, item);
			
			HttpContext ctx = HttpContext.Current;
			HttpRequest req = ctx != null ? ctx.Request : null;
			CacheDependency dep;
			
			if (req != null) {
				IDictionary <string, bool> deps = bp.ExtractDependencies ();
				var files = new List <string> ();
				string physicalPath;

				physicalPath = req.MapPath (virtualPath);
				if (File.Exists (physicalPath))
					files.Add (physicalPath);
				
				if (deps != null && deps.Count > 0) {
					foreach (var d in deps) {
						physicalPath = req.MapPath (d.Key);
						if (!File.Exists (physicalPath))
							continue;
						if (!files.Contains (physicalPath))
							files.Add (physicalPath);
					}
				}

				dep = new CacheDependency (files.ToArray ());
			} else
				dep = null;

			HttpRuntime.InternalCache.Add (BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX + virtualPath,
						       true,
						       dep,
						       Cache.NoAbsoluteExpiration,
						       Cache.NoSlidingExpiration,
						       CacheItemPriority.High,
						       new CacheItemRemovedCallback (OnVirtualPathChanged));
		}
コード例 #36
0
    /// <devdoc>
    ///     Adds a CodeCompileUnit to the compilation.  This is typically used as an
    ///     alternative to CreateSourceFile, by providers who are CodeDOM aware.
    ///     The build provider should pass itself as a parameter to this method.
    /// </devdoc>
    public void AddCodeCompileUnit(BuildProvider buildProvider, CodeCompileUnit compileUnit) {

        // Add a checksum pragma to the compile unit if appropriate
        AddChecksumPragma(buildProvider, compileUnit);

        // Add all the referenced assemblies to the CodeCompileUnit in case the CodeDom
        // provider needs them for code generation
        Util.AddAssembliesToStringCollection(_initialReferencedAssemblies, compileUnit.ReferencedAssemblies);

        // Merge the _additionalReferencedAssemblies from individul build providers
        Util.AddAssembliesToStringCollection(_additionalReferencedAssemblies, compileUnit.ReferencedAssemblies);

        String filename;

        // Revert impersonation when generating source code in the codegen dir (VSWhidbey 176576)
        using (new ProcessImpersonationContext()) {
            TextWriter writer = CreateCodeFile(buildProvider, out filename);

            try {
                _codeProvider.GenerateCodeFromCompileUnit(compileUnit, writer, null /*CodeGeneratorOptions*/);
            }
            finally {
                writer.Flush();
                writer.Close();
            }
        }

        if (filename != null) {
            _totalFileLength += GetFileLengthWithAssert(filename);
        }
    }
コード例 #37
0
    /// <devdoc>
    ///     Creates a new resource that will be added to the compilation.  The build provider
    ///     can write to it using the returned Stream.
    ///     The build provider should close the Stream when it is done writing to it.
    ///     The build provider should pass itself as a parameter to this method.
    /// </devdoc>
    public Stream CreateEmbeddedResource(BuildProvider buildProvider, string name) {

        // Make sure it's just a valid simple file name
        if (!Util.IsValidFileName(name)) {
            throw new ArgumentException(null, name);
        }

        string resourceDir = BuildManager.CodegenResourceDir;
        string resourceFile = Path.Combine(resourceDir, name);
        CreateTempResourceDirectoryIfNecessary();

        _tempFiles.AddFile(resourceFile, _tempFiles.KeepFiles);

        if (_embeddedResourceFiles == null)
            _embeddedResourceFiles = new StringSet();

        _embeddedResourceFiles.Add(resourceFile);

        // Assert to be able to create the file in the temp dir
        InternalSecurityPermissions.FileWriteAccess(resourceDir).Assert();

        return File.OpenWrite(resourceFile);
    }
	// Methods
	public void Add(BuildProvider buildProvider) {}
コード例 #39
0
 public ConfigurationBuildProviderInfo(BuildProvider buildProvider) {
     Debug.Assert(buildProvider != null);
     _buildProvider = buildProvider;
 }
コード例 #40
0
    /// <devdoc>
    ///     Creates a new source file that will be added to the compilation.  The build provider
    ///     can write source code to this file using the returned TextWriter.
    ///     The build provider should close the TextWriter when it is done writing to it.
    ///     The build provider should pass itself as a parameter to this method.
    /// </devdoc>
    public TextWriter CreateCodeFile(BuildProvider buildProvider) {
        // Ignore the unused filename param.
        string filename;

        return CreateCodeFile(buildProvider, out filename);
    }
コード例 #41
0
        public void Extension_validationFailure()
        {
            BuildProvider b = new BuildProvider("hi", "bye");

            b.Extension = "";
        }
コード例 #42
0
    internal virtual void AddBuildProvider(BuildProvider buildProvider) {

        // By default, use the build provider itself as the key
        object hashtableKey = buildProvider;

        bool isFolderLevel = false;

        // If the buildProvider is a folderLevel build provider, use the build provider itself
        // so that multiple build providers can work on the same path.
        if (_compConfig.FolderLevelBuildProviders != null) {
            Type t = buildProvider.GetType();
            isFolderLevel = _compConfig.FolderLevelBuildProviders.IsFolderLevelBuildProvider(t);
        }

        // Keep track of the build provider's virtual path, if any
        if (buildProvider.VirtualPath != null && !isFolderLevel) {

            // It has a virtual path, so use that as the key
            hashtableKey = buildProvider.VirtualPath;

            // If we already had it, ignore it.  This can happen when there is a user control
            // with a code beside in App_Code (VSWhidbey 481426)
            if (_buildProviders.ContainsKey(hashtableKey))
                return;
        }

        _buildProviders[hashtableKey] = buildProvider;

        // Ask the provider to generate the code
        // If it throws an Xml exception, extra the relevant info and turn it
        // into our own ParseException
        try {
            buildProvider.GenerateCode(this);
        }
        catch (XmlException e) {
            throw new HttpParseException(e.Message, null /*innerException*/,
                buildProvider.VirtualPath, null /*sourceCode*/, e.LineNumber);
        }
        catch (XmlSchemaException e) {
            throw new HttpParseException(e.Message, null /*innerException*/,
                buildProvider.VirtualPath, null /*sourceCode*/, e.LineNumber);
        }
        catch (Exception e) {
            throw new HttpParseException(e.Message, e,
                buildProvider.VirtualPath, null /*sourceCode*/, 1);
        }

        // Handle any 'compileWith' dependencies, i.e. files that must be compiled
        // within the same assembly as the current file
        InternalBuildProvider internalBuildProvider = buildProvider as InternalBuildProvider;
        if (internalBuildProvider != null) {
            ICollection compileWith = internalBuildProvider.GetCompileWithDependencies();
            if (compileWith != null) {
                foreach (VirtualPath virtualPath in compileWith) {

                    // If we already have it, ignore it
                    if (_buildProviders.ContainsKey(virtualPath.VirtualPathString))
                        continue;

                    // Add the compileWith dependency to our compilation
                    AddCompileWithBuildProvider(virtualPath, internalBuildProvider);
                }
            }
        }

    }
コード例 #43
0
        static void Main(string[] args)
        {
            try
            {
                // Set the path of the config file.
                string configPath = "";

                // Get the Web application configuration object.
                Configuration config =
                    WebConfigurationManager.OpenWebConfiguration(configPath);

                // Get the section related object.
                CompilationSection configSection =
                    (CompilationSection)config.GetSection
                        ("system.web/compilation");

                // Display title and info.
                Console.WriteLine("ASP.NET Configuration Info");
                Console.WriteLine();

                // Display Config details.
                Console.WriteLine("File Path: {0}",
                                  config.FilePath);
                Console.WriteLine("Section Path: {0}",
                                  configSection.SectionInformation.Name);

                // Display BuildProviderCollection count.
                Console.WriteLine("BuildProviderCollection count: {0}",
                                  configSection.BuildProviders.Count);

                // <Snippet4>
                // <Snippet2>
                // Create a new BuildProvider.
                BuildProvider myBuildProvider =
                    new BuildProvider(".myres",
                                      "System.Web.Compilation.ResourcesBuildProvider");
                // </Snippet2>

                // <Snippet3>
                // Add an BuildProvider to the collection.
                configSection.BuildProviders.Add(myBuildProvider);
                // </Snippet3>
                // </Snippet4>

                // Create a second BuildProvider.
                BuildProvider myBuildProvider2 =
                    new BuildProvider(".myres2",
                                      "System.Web.Compilation.ResourcesBuildProvider");

                // Add an BuildProvider to the collection.
                configSection.BuildProviders.Add(myBuildProvider2);

                // BuildProvider Collection
                int i = 1;
                int j = 1;
                foreach (BuildProvider BuildProviderItem in
                         configSection.BuildProviders)
                {
                    Console.WriteLine();
                    Console.WriteLine("BuildProviders {0} Details:", i);
                    Console.WriteLine("Type: {0}",
                                      BuildProviderItem.ElementInformation.Type);
                    Console.WriteLine("Source: {0}",
                                      BuildProviderItem.ElementInformation.Source);
                    Console.WriteLine("LineNumber: {0}",
                                      BuildProviderItem.ElementInformation.LineNumber);
                    Console.WriteLine("Properties Count: {0}",
                                      BuildProviderItem.ElementInformation.Properties.Count);
                    j = 1;
                    foreach (PropertyInformation propertyItem in
                             BuildProviderItem.ElementInformation.Properties)
                    {
                        Console.WriteLine("Property {0} Name: {1}", j,
                                          propertyItem.Name);
                        Console.WriteLine("Property {0} Value: {1}", j,
                                          propertyItem.Value);
                        j++;
                    }
                    i++;
                }

                // <Snippet5>
                // Remove a BuildProvider.
                configSection.BuildProviders.Remove(".myres2");
                // </Snippet5>

                // <Snippet6>
                // Remove an BuildProvider.
                configSection.BuildProviders.RemoveAt(
                    configSection.BuildProviders.Count - 1);
                // </Snippet6>

                // Update if not locked.
                if (!configSection.SectionInformation.IsLocked)
                {
                    config.Save();
                    Console.WriteLine("** Configuration updated.");
                }
                else
                {
                    Console.WriteLine("** Could not update, section is locked.");
                }
            }

            catch (Exception e)
            {
                // Unknown error.
                Console.WriteLine(e.ToString());
            }

            // Display and wait.
            Console.ReadLine();
        }
コード例 #44
0
    /// <devdoc>
    ///     Creates a new source file that will be added to the compilation. See the public overload
    ///     method for detail.
    /// </devdoc>
    internal virtual TextWriter CreateCodeFile(BuildProvider buildProvider, out string filename) {

        string generatedFilePath = GetTempFilePhysicalPathWithAssert(_codeProvider.FileExtension);
        filename = generatedFilePath;

        if (buildProvider != null) {
            if (_buildProviderToSourceFileMap == null)
                _buildProviderToSourceFileMap = new Hashtable();
            _buildProviderToSourceFileMap[buildProvider] = generatedFilePath;
            buildProvider.SetContributedCode();
        }

        _sourceFiles.Add(generatedFilePath);

        return CreateCodeFileWithAssert(generatedFilePath);
    }
コード例 #45
0
ファイル: AppCodeCompiler.cs プロジェクト: stabbylambda/mono
		bool IsCorrectBuilderType (BuildProvider bp)
		{
			if (bp == null)
				return false;
			Type type;
			object[] attrs;

			type = bp.GetType ();
			attrs = type.GetCustomAttributes (true);
			if (attrs == null)
				return false;
			
			BuildProviderAppliesToAttribute bpAppliesTo;
			bool attributeFound = false;
			foreach (object attr in attrs) {
				bpAppliesTo = attr as BuildProviderAppliesToAttribute;
				if (bpAppliesTo == null)
					continue;
				attributeFound = true;
				if ((bpAppliesTo.AppliesTo & BuildProviderAppliesTo.All) == BuildProviderAppliesTo.All ||
				    (bpAppliesTo.AppliesTo & BuildProviderAppliesTo.Code) == BuildProviderAppliesTo.Code)
					return true;
			}

			if (attributeFound)
				return false;
			return true;
		}
コード例 #46
0
ファイル: AssemblyBuilder.cs プロジェクト: ztzg/mono
		void AddPathToBuilderMap (string path, BuildProvider bp)
		{
			if (path_to_buildprovider == null)
				path_to_buildprovider = new Dictionary <string, BuildProvider> ();

			if (path_to_buildprovider.ContainsKey (path))
				return;

			path_to_buildprovider.Add (path, bp);
		}
コード例 #47
0
ファイル: AssemblyBuilder.cs プロジェクト: ztzg/mono
		public void AddCodeCompileUnit (BuildProvider buildProvider, CodeCompileUnit compileUnit)
		{
			if (buildProvider == null)
				throw new ArgumentNullException ("buildProvider");

			if (compileUnit == null)
				throw new ArgumentNullException ("compileUnit");

			units.Add (CheckForPartialTypes (new CodeUnit (buildProvider, compileUnit)));
		}
コード例 #48
0
ファイル: AssemblyBuilder.cs プロジェクト: ztzg/mono
		internal void AddCodeFile (string path, BuildProvider bp)
		{
			AddCodeFile (path, bp, false);
		}
コード例 #49
0
ファイル: AssemblyBuilder.cs プロジェクト: ztzg/mono
		public TextWriter CreateCodeFile (BuildProvider buildProvider)
		{
			if (buildProvider == null)
				throw new ArgumentNullException ("buildProvider");

			// Generate a file name with the correct source language extension
			string filename = GetTempFilePhysicalPath (provider.FileExtension);
			SourceFiles.Add (filename);
			AddPathToBuilderMap (filename, buildProvider);
			return new StreamWriter (File.OpenWrite (filename));
		}
コード例 #50
0
 public AspNetAssemblyBuilder(AssemblyBuilder assemblyBuilder, BuildProvider buildProvider)
 {
     _assemblyBuilder = assemblyBuilder;
     _buildProvider   = buildProvider;
 }
コード例 #51
0
ファイル: AssemblyBuilder.cs プロジェクト: ztzg/mono
		// The kludge of using ICodePragmaGenerator for C# and VB code files is bad, but
		// it's better than allowing for potential DoS while reading a file with arbitrary
		// size in memory for use with the CodeSnippetCompileUnit class.
		// Files with extensions other than .cs and .vb use CodeSnippetCompileUnit.
		internal void AddCodeFile (string path, BuildProvider bp, bool isVirtual)
		{
			if (String.IsNullOrEmpty (path))
				return;

			Dictionary <string, bool> codeFiles = CodeFiles;
			if (codeFiles.ContainsKey (path))
				return;
			
			codeFiles.Add (path, true);
			
			string extension = Path.GetExtension (path);
			if (extension == null || extension.Length == 0)
				return; // maybe better to throw an exception here?
			extension = extension.Substring (1);
			string filename = GetTempFilePhysicalPath (extension);
			ICodePragmaGenerator pragmaGenerator;
			
			switch (extension.ToLowerInvariant ()) {
				case "cs":
					pragmaGenerator = new CSharpCodePragmaGenerator ();
					break;

				case "vb":
					pragmaGenerator = new VBCodePragmaGenerator ();
					break;

				default:
					pragmaGenerator = null;
					break;
			}
			
			if (isVirtual) {
				VirtualFile vf = HostingEnvironment.VirtualPathProvider.GetFile (path);
				if (vf == null)
					throw new HttpException (404, "Virtual file '" + path + "' does not exist.");

				if (vf is DefaultVirtualFile)
					path = HostingEnvironment.MapPath (path);
				CopyFileWithChecksum (vf.Open (), filename, path, pragmaGenerator);
			} else
				CopyFileWithChecksum (path, filename, path, pragmaGenerator);

			if (pragmaGenerator != null) {
				if (bp != null)
					AddPathToBuilderMap (filename, bp);
			
				SourceFiles.Add (filename);
			}
		}
コード例 #52
0
		bool AddBuildProvider (BuildProvider buildProvider)
		{
			if (buildProviders == null)
				buildProviders = new Dictionary <string, BuildProvider> (dictionaryComparer);
			
			string bpPath = buildProvider.VirtualPath;
			if (buildProviders.ContainsKey (bpPath))
				return false;

			buildProviders.Add (bpPath, buildProvider);
			return true;
		}
コード例 #53
0
ファイル: AssemblyBuilder.cs プロジェクト: ztzg/mono
			public CodeUnit (BuildProvider bp, CodeCompileUnit unit)
			{
				this.BuildProvider = bp;
				this.Unit = unit;
			}
コード例 #54
0
		List <BuildProviderGroup> GetSingleBuildProviderGroup (BuildProvider bp)
		{
			var ret = new List <BuildProviderGroup> ();
			var group = new BuildProviderGroup ();
			group.AddProvider (bp);
			ret.Add (group);

			return ret;
		}
コード例 #55
0
 public void ctor_validationFailure2()
 {
     BuildProvider b = new BuildProvider("hi", "");
 }
コード例 #56
0
		Type GetBuildProviderCodeDomType (BuildProvider bp)
		{
			CompilerType ct = bp.CodeCompilerType;
			if (ct == null) {
				string language = bp.LanguageName;

				if (String.IsNullOrEmpty (language))
					language = CompilationSection.DefaultLanguage;

				ct = BuildManager.GetDefaultCompilerTypeForLanguage (language, CompilationSection, false);
			}

			Type ret = ct != null ? ct.CodeDomProviderType : null;
			if (ret == null)
				throw new HttpException ("Unable to determine code compilation language provider for virtual path '" + bp.VirtualPath + "'.");

			return ret;
		}
コード例 #57
0
        public void Type_validationFailure()
        {
            BuildProvider b = new BuildProvider("hi", "bye");

            b.Type = "";
        }
コード例 #58
0
		void AssignToGroup (BuildProvider buildProvider, List <BuildProviderGroup> groups)
		{
			if (IsDependencyCycle (buildProvider))
				throw new HttpException ("Dependency cycles are not suppported: " + buildProvider.VirtualPath);

			BuildProviderGroup myGroup = null;
			string bpVirtualPath = buildProvider.VirtualPath;
			string bpPath = VirtualPathUtility.GetDirectory (bpVirtualPath);
			bool canAdd;

			if (BuildManager.HasCachedItemNoLock (buildProvider.VirtualPath))
				return;			

			if (buildProvider is ApplicationFileBuildProvider || buildProvider is ThemeDirectoryBuildProvider) {
				// global.asax and theme directory go into their own assemblies
				myGroup = new BuildProviderGroup ();
				myGroup.Standalone = true;
				InsertGroup (myGroup, groups);
			} else {
				Type bpCodeDomType = GetBuildProviderCodeDomType (buildProvider);
				foreach (BuildProviderGroup group in groups) {
					if (group.Standalone)
						continue;
					
					if (group.Count == 0) {
						myGroup = group;
						break;
					}

					canAdd = true;
					foreach (BuildProvider bp in group) {
						if (IsDependency (buildProvider, bp)) {
							canAdd = false;
							break;
						}
					
						// There should be one assembly per virtual dir
						if (String.Compare (bpPath, VirtualPathUtility.GetDirectory (bp.VirtualPath), stringComparer) != 0) {
							canAdd = false;
							break;
						}

						// Different languages go to different assemblies
						if (bpCodeDomType != null) {
							Type type = GetBuildProviderCodeDomType (bp);
							if (type != null) {
								if (type != bpCodeDomType) {
									canAdd = false;
									break;
								}
							}
						}
					}

					if (!canAdd)
						continue;

					myGroup = group;
					break;
				}
				
				if (myGroup == null) {
					myGroup = new BuildProviderGroup ();
					InsertGroup (myGroup, groups);
				}
			}
			
			myGroup.AddProvider (buildProvider);
			if (String.Compare (bpPath, virtualPathDirectory, stringComparer) == 0)
				myGroup.Master = true;
		}
コード例 #59
0
		bool IsDependency (BuildProvider bp1, BuildProvider bp2)
		{
			IDictionary <string, bool> deps = bp1.ExtractDependencies ();
			if (deps == null)
				return false;

			if (deps.ContainsKey (bp2.VirtualPath))
				return true;

			BuildProvider bp;
			// It won't loop forever as by the time this method is called, we are sure there are no cycles
			foreach (var dep in deps) {
				if (!buildProviders.TryGetValue (dep.Key, out bp))
					continue;

				if (IsDependency (bp, bp2))
					return true;
			}
			
			return false;
		}
コード例 #60
0
 // Methods
 public void Add(BuildProvider buildProvider)
 {
 }