Ejemplo n.º 1
0
        private static void ReadConnectionString(MigrationToolSettings settings)
        {
            var vdm  = new VirtualDirectoryMapping(_settings.SourceDirectory, true);
            var wcfm = new WebConfigurationFileMap();

            wcfm.VirtualDirectories.Add("/", vdm);
            var config = WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");

            var connectionString = config.ConnectionStrings.ConnectionStrings["EPiServerDB"].ConnectionString;

            if (string.IsNullOrWhiteSpace(connectionString))
            {
                throw new ConfigurationErrorsException("Cannot find EPiServer database connection");
            }

            settings.ConnectionString = connectionString;
        }
Ejemplo n.º 2
0
 public void GetPathConfigFilename(string siteID, string path, out string directory, out string baseName)
 {
     directory = null;
     baseName  = null;
     if (this.IsSiteMatch(siteID))
     {
         VirtualDirectoryMapping pathMapping = this.GetPathMapping(path, false);
         if (pathMapping != null)
         {
             directory = this.GetPhysicalPathForPath(path, pathMapping);
             if (directory != null)
             {
                 baseName = pathMapping.ConfigFileBaseName;
             }
         }
     }
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Gets the configuration.
        /// </summary>
        /// <returns></returns>
        public static Configuration GetConfiguration()
        {
            Configuration configuration;

            try
            {
                configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            }
            catch (Exception)
            {
                var mapping = new VirtualDirectoryMapping(AppDomain.CurrentDomain.BaseDirectory, true);
                var map     = new WebConfigurationFileMap();
                map.VirtualDirectories.Add("/", mapping);
                configuration = WebConfigurationManager.OpenMappedWebConfiguration(map, "/", System.Web.Hosting.HostingEnvironment.ApplicationHost.GetSiteName());
            }

            return(configuration);
        }
Ejemplo n.º 4
0
        internal ConfigMapPath(string physicalPath, ConfigurationFileMap fileMap, bool pathsAreLocal)
        {
            this._pathsAreLocal = pathsAreLocal;

            var configDir = Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "Config");

            this._machineConfigFilename = Path.Combine(configDir, "machine.config");
            this._rootWebConfigFilename = Path.Combine(configDir, "web.config");

            if (!string.IsNullOrEmpty(fileMap.MachineConfigFilename))
            {
                if (this._pathsAreLocal)
                {
                    this._machineConfigFilename = Path.GetFullPath(fileMap.MachineConfigFilename);
                }
                else
                {
                    this._machineConfigFilename = fileMap.MachineConfigFilename;
                }
            }

            this._webFileMap = fileMap as WebConfigurationFileMap;

            if (this._webFileMap != null)
            {
                this._siteName = "Default Site";
                this._siteID   = "1";

                /*if (this._pathsAreLocal)
                 * {
                 *  foreach (string str in this._webFileMap.VirtualDirectories)
                 *  {
                 *      this._webFileMap.VirtualDirectories[str].va;
                 *  }
                 * }*/
                VirtualDirectoryMapping mapping2 = this._webFileMap.VirtualDirectories[null];

                if (mapping2 != null)
                {
                    this._rootWebConfigFilename = Path.Combine(mapping2.PhysicalDirectory, mapping2.ConfigFileBaseName);
                    this._webFileMap.VirtualDirectories.Remove(null);
                }
            }
        }
        public void ShouldAddModifiedAt()
        {
            CreateSampleConfigFile();

            new WebConfigUpdater("Web.config")
            .OverrideAppSettingsWithEnvironmentVars();

            string directory             = Path.GetDirectoryName(Path.GetFullPath("Web.config"));
            WebConfigurationFileMap wcfm = new WebConfigurationFileMap();
            VirtualDirectoryMapping vdm  = new VirtualDirectoryMapping(directory, true, "Web.config");

            wcfm.VirtualDirectories.Add("/", vdm);

            //WebConfigurationManager seems bugging in Mono 3.2.4
            Configuration webConfig = WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");

            CollectionAssert.Contains(webConfig.AppSettings.Settings.AllKeys, "AppSettingsAutoReconfiguration_ModifiedAt");
            Console.WriteLine(webConfig.AppSettings.Settings ["AppSettingsAutoReconfiguration_ModifiedAt"].Value);
        }
Ejemplo n.º 6
0
        // Utility to map virtual directories to physical ones.
        // In the current physical directory maps
        // a physical sub-directory with its virtual directory.
        // A web.config file is created for the
        // default and the virtual directory at the appropriate level.
        // You must create a physical directory called config at the
        // level where your app is running.
        static WebConfigurationFileMap CreateFileMap(string rootPath)
        {
            WebConfigurationFileMap fileMap = new WebConfigurationFileMap();

            // Get he physical directory where this app runs.
            // We'll use it to map the virtual directories
            // defined next.
            string physDir = rootPath;

            // Create a VirtualDirectoryMapping object to use
            // as the root directory for the virtual directory
            // named config.
            // Note: you must assure that you have a physical subdirectory
            // named config in the curremt physical directory where this
            // application runs.
            VirtualDirectoryMapping vDirMap = new VirtualDirectoryMapping(physDir, true);

            // Add vDirMap to the VirtualDirectories collection
            // assigning to it the virtual directory name.
            //fileMap.VirtualDirectories.Add("/config", vDirMap);

            // Create a VirtualDirectoryMapping object to use
            // as the default directory for all the virtual
            // directories.
            VirtualDirectoryMapping vDirMapBase = new VirtualDirectoryMapping(physDir, true, "web.config");

            // Add it to the virtual directory mapping collection.
            fileMap.VirtualDirectories.Add("/", vDirMapBase);

            //# if DEBUG
            //            // Test at debug time.
            //            foreach (string key in fileMap.VirtualDirectories.AllKeys)
            //            {
            //                Console.WriteLine("Virtual directory: {0} Physical path: {1}",
            //                fileMap.VirtualDirectories[key].VirtualDirectory,
            //                fileMap.VirtualDirectories[key].PhysicalDirectory);
            //            }
            //# endif

            // Return the mapping.
            return(fileMap);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Get web configuration
        /// </summary>
        /// <param name="physicalPath"></param>
        /// <returns>configuration object</returns>
        public static Configuration GetConfig(string physicalPath)
        {
            Configuration configuration;

            if (string.IsNullOrWhiteSpace(physicalPath))
            {
                configuration = WebConfigurationManager.OpenWebConfiguration("~");
            }
            else
            {
                var configFile = new FileInfo(physicalPath);
                var vdm        = new VirtualDirectoryMapping(configFile.DirectoryName, true, configFile.Name);
                var wcfm       = new WebConfigurationFileMap();
                wcfm.VirtualDirectories.Add("/", vdm);
                var websiteName = HostingEnvironment.SiteName;
                configuration = WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/", websiteName);
            }

            return(configuration);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// 获取标准Web应用程序的配置信息,合并Web.config和global配置文件
        /// </summary>
        /// <param name="machineConfigPath">global配置文件地址</param>
        /// <param name="ignoreFileNotExist">是否忽略不存在的文件</param>
        /// <param name="fileDependencies">缓存依赖文件</param>
        /// <returns>Web.config和global配置文件合并后的Configuration对象</returns>
        private static System.Configuration.Configuration GetStandardWebConfiguration(string machineConfigPath, bool ignoreFileNotExist, params string[] fileDependencies)
        {
            string cacheKey = ConfigurationBroker.CreateConfigurationCacheKey(machineConfigPath);

            System.Configuration.Configuration config;

            if (ConfigurationCache.Instance.TryGetValue(cacheKey, out config) == false)
            {
                WebConfigurationFileMap fileMap = new WebConfigurationFileMap();

                fileMap.MachineConfigFilename = machineConfigPath;
                VirtualDirectoryMapping vDirMap = new VirtualDirectoryMapping(
                    HttpContext.Current.Request.PhysicalApplicationPath,
                    true);

                fileMap.VirtualDirectories.Add("/", vDirMap);

                config = WebConfigurationManager.OpenMappedWebConfiguration(fileMap, "/",
                                                                            HttpContext.Current.Request.ServerVariables["INSTANCE_ID"]);

                Array.Resize <string>(ref fileDependencies, fileDependencies.Length + 1);
                fileDependencies[fileDependencies.Length - 1] = machineConfigPath;

                ConfigurationBroker.AddConfigurationToCache(cacheKey, config, ignoreFileNotExist, fileDependencies);
#if DELUXEWORKSTEST
                // 测试使用
                ConfigurationBroker.configurationReadFrom = ReadFrom.ReadFromFile;
#endif
            }
            else
            {
#if DELUXEWORKSTEST
                // 测试使用
                ConfigurationBroker.configurationReadFrom = ReadFrom.ReadFromCache;
#endif
            }

            return(config);
        }
Ejemplo n.º 9
0
 public static Configuration GetConfiguration(string filePath)
 {
     if (File.Exists(filePath))
     {
         FileInfo file = new FileInfo(filePath);
         if (file.Name.ToLower() != "web.config")
         {
             try
             {
                 ExeConfigurationFileMap map = new ExeConfigurationFileMap() { ExeConfigFilename = filePath };
                 return ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
             }
             catch (ConfigurationErrorsException ex)
             {
                 return null;
                 //throw;
             }
         }
         else
         {
             try
             {
                 var virtualDirectoryMapping = new VirtualDirectoryMapping(file.DirectoryName, true, file.Name);
                 var webConfigFileMap = new     WebConfigurationFileMap();
                 webConfigFileMap.VirtualDirectories.Add("/",     virtualDirectoryMapping);
                 return WebConfigurationManager.OpenMappedWebConfiguration(webConfigFileMap, "/");
             }
             catch(ConfigurationErrorsException ex)
             {
                 return null;
                 //throw;
             }
         }
     }
     else
         throw new FileNotFoundException("File not found", filePath);
 }
Ejemplo n.º 10
0
        private static WebConfigurationFileMap CreateFileMap(string applicationVirtualPath)
        {
            WebConfigurationFileMap fileMap =
                new WebConfigurationFileMap();
            //WebConfigurationFileMap fileMap = CreateFileMap(HostingEnvironment.ApplicationVirtualPath);

            // Get he physical directory where this app runs.
            // We'll use it to map the virtual directories
            // defined next.
            string physDir = HostingEnvironment.ApplicationPhysicalPath;

            // Create a VirtualDirectoryMapping object to use
            // as the root directory for the virtual directory
            // named config.
            // Note: you must assure that you have a physical subdirectory
            // named config in the curremt physical directory where this
            // application runs.
            VirtualDirectoryMapping vDirMap =
                new VirtualDirectoryMapping(physDir, true);

            // Add vDirMap to the VirtualDirectories collection
            // assigning to it the virtual directory name.
            fileMap.VirtualDirectories.Add(applicationVirtualPath, vDirMap);

            // Create a VirtualDirectoryMapping object to use
            // as the default directory for all the virtual
            // directories.
            VirtualDirectoryMapping vDirMapBase =
                new VirtualDirectoryMapping(physDir, true, "web.config");

            // Add it to the virtual directory mapping collection.
            fileMap.VirtualDirectories.Add("/", vDirMapBase);

            // Return the mapping.
            return(fileMap);
        }
        private static WebPageRazorHost GetRazorWebPageRazorHost(string virtualPath, string physicalPath)
        {
            WebPageRazorHost webPageRazorHost = null;

            try
            {
                string physicalDirectory = physicalPath.Substring(0, physicalPath.Length - virtualPath.Length);
                string text = virtualPath.Replace('\\', '/');
                if (!text.StartsWith("/", StringComparison.Ordinal))
                {
                    text = "/" + text;
                }
                int num = text.LastIndexOf('/');
                text = text.Substring(0, (num == 0) ? 1 : num);
                WebConfigurationFileMap arg_62_0 = new WebConfigurationFileMap();
                VirtualDirectoryMapping mapping  = new VirtualDirectoryMapping(physicalDirectory, true);
                arg_62_0.VirtualDirectories.Add("/", mapping);
                Configuration configuration = WebConfigurationManager.OpenMappedWebConfiguration(arg_62_0, text);
                if (configuration != null)
                {
                    RazorWebSectionGroup razorWebSectionGroup = (RazorWebSectionGroup)configuration.GetSectionGroup(RazorWebSectionGroup.GroupName);
                    if (razorWebSectionGroup != null)
                    {
                        webPageRazorHost = WebRazorHostFactory.CreateHostFromConfig(razorWebSectionGroup, virtualPath, physicalPath);
                    }
                }
            }
            catch (Exception)
            {
            }
            if (webPageRazorHost == null)
            {
                webPageRazorHost = WebRazorHostFactory.CreateDefaultHost(virtualPath, physicalPath);
            }
            return(webPageRazorHost);
        }
Ejemplo n.º 12
0
        RazorEngineHost CreateRazorHost(string fileName)
        {
            if (project != null)
            {
                var projectFile = project.GetProjectFile(fileName);
                if (projectFile != null && projectFile.Generator == "RazorTemplatePreprocessor")
                {
                    var h = MonoDevelop.RazorGenerator.PreprocessedRazorHost.Create(fileName);
                    h.DesignTimeMode    = true;
                    h.EnableLinePragmas = false;
                    return(h);
                }
            }

            string virtualPath = "~/Views/Default.cshtml";

            if (aspProject != null)
            {
                virtualPath = aspProject.LocalToVirtualPath(fileName);
            }

            WebPageRazorHost host = null;

            // Try to create host using web.config file
            var webConfigMap = new WebConfigurationFileMap();

            if (aspProject != null)
            {
                var vdm = new VirtualDirectoryMapping(aspProject.BaseDirectory.Combine("Views"), true, "web.config");
                webConfigMap.VirtualDirectories.Add("/", vdm);
            }
            Configuration configuration;

            try {
                configuration = WebConfigurationManager.OpenMappedWebConfiguration(webConfigMap, "/");
            } catch {
                configuration = null;
            }
            if (configuration != null)
            {
                var rws = configuration.GetSectionGroup(RazorWebSectionGroup.GroupName) as RazorWebSectionGroup;
                if (rws != null)
                {
                    host = WebRazorHostFactory.CreateHostFromConfig(rws, virtualPath, fileName);
                    host.DesignTimeMode = true;
                }
            }

            if (host == null)
            {
                host = new MvcWebPageRazorHost(virtualPath, fileName)
                {
                    DesignTimeMode = true
                };
                // Add default namespaces from Razor section
                host.NamespaceImports.Add("System.Web.Mvc");
                host.NamespaceImports.Add("System.Web.Mvc.Ajax");
                host.NamespaceImports.Add("System.Web.Mvc.Html");
                host.NamespaceImports.Add("System.Web.Routing");
            }

            return(host);
        }
 // Methods
 public void Add(string virtualDirectory, VirtualDirectoryMapping mapping)
 {
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Function that builds the contents of the generated file based on the contents of the input file
        /// </summary>
        /// <param name="inputFileContent">Content of the input file</param>
        /// <returns>Generated file as a byte array</returns>
        protected override byte[] GenerateCode(string inputFileContent)
        {
            var references = GetVSProject().References;
            //add reference to our buildprovider and virtualpathprovider
            var buildprovAssembly = typeof(CompiledVirtualPathProvider).Assembly;

            if (references.Find(buildprovAssembly.GetName().Name) == null)
            {
                references.Add(buildprovAssembly.Location);
            }

            // Get the root folder of the project
            var appRoot = Path.GetDirectoryName(GetProject().FullName);

            // Determine the project-relative path
            string projectRelativePath = InputFilePath.Substring(appRoot.Length);

            // Turn it into a virtual path by prepending ~ and fixing it up
            string virtualPath = VirtualPathUtility.ToAppRelative("~" + projectRelativePath);

            var vdm  = new VirtualDirectoryMapping(appRoot, true);
            var wcfm = new WebConfigurationFileMap();

            wcfm.VirtualDirectories.Add("/", vdm);

            var config = WebConfigurationManager.OpenMappedWebConfiguration(wcfm, projectRelativePath);
            //System.Configuration.ConfigurationManager.OpenExeConfiguration(configFile);

            var sectGroup = new RazorWebSectionGroup
            {
                Host = (HostSection)config.GetSection(HostSection.SectionName) ??
                       new HostSection {
                    FactoryType = typeof(MvcWebRazorHostFactory).AssemblyQualifiedName
                },
                Pages = (RazorPagesSection)config.GetSection(RazorPagesSection.SectionName)
            };

            // Create the same type of Razor host that's used to process Razor files in App_Code
            var host = IsHelper ?
                       new WebCodeRazorHost(virtualPath, InputFilePath) :
                       WebRazorHostFactory.CreateHostFromConfig(sectGroup, virtualPath, InputFilePath);

            // Set the namespace to be the same as what's used by default for regular .cs files
            host.DefaultNamespace = FileNameSpace;

            host.NamespaceImports.Remove("WebMatrix.Data");
            host.NamespaceImports.Remove("WebMatrix.WebData");

            var systemWebPages = config.GetSection("system.web/pages") as PagesSection;

            if (systemWebPages != null)
            {
                foreach (NamespaceInfo ns in systemWebPages.Namespaces)
                {
                    if (!host.NamespaceImports.Contains(ns.Namespace))
                    {
                        host.NamespaceImports.Add(ns.Namespace);
                    }
                }
            }

            var compilationSection = config.GetSection("system.web/compilation") as CompilationSection;

            if (compilationSection != null)
            {
                foreach (AssemblyInfo assembly in compilationSection.Assemblies)
                {
                    if (assembly.Assembly != "*" && references.Find(assembly.Assembly) == null)
                    {
                        references.Add(assembly.Assembly);
                    }
                }
            }

            // Create a Razor engine and pass it our host
            var engine = new RazorTemplateEngine(host);

            // Generate code
            GeneratorResults results = null;

            try {
                using (TextReader reader = new StringReader(inputFileContent)) {
                    results = engine.GenerateCode(reader, null, null, InputFilePath);
                }
            }
            catch (Exception e) {
                this.GeneratorError(4, e.ToString(), 1, 1);
                //Returning null signifies that generation has failed
                return(null);
            }

            // Output errors
            foreach (RazorError error in results.ParserErrors)
            {
                GeneratorError(4, error.Message, (uint)error.Location.LineIndex + 1, (uint)error.Location.CharacterIndex + 1);
            }

            CodeDomProvider provider = GetCodeProvider();

            try {
                if (this.CodeGeneratorProgress != null)
                {
                    //Report that we are 1/2 done
                    this.CodeGeneratorProgress.Progress(50, 100);
                }

                using (StringWriter writer = new StringWriter(new StringBuilder())) {
                    CodeGeneratorOptions options = new CodeGeneratorOptions();
                    options.BlankLinesBetweenMembers = false;
                    options.BracingStyle             = "C";

                    // Add a GeneratedCode attribute to the generated class
                    CodeCompileUnit     generatedCode = results.GeneratedCode;
                    var                 ns            = generatedCode.Namespaces[0];
                    CodeTypeDeclaration generatedType = ns.Types[0];
                    generatedType.CustomAttributes.Add(
                        new CodeAttributeDeclaration(
                            new CodeTypeReference(typeof(GeneratedCodeAttribute)),
                            new CodeAttributeArgument(new CodePrimitiveExpression("MvcRazorClassGenerator")),
                            new CodeAttributeArgument(new CodePrimitiveExpression("1.0"))));

                    if (!IsHelper)
                    {
                        generatedType.CustomAttributes.Add(
                            new CodeAttributeDeclaration(
                                new CodeTypeReference(typeof(PageVirtualPathAttribute)),
                                new CodeAttributeArgument(new CodePrimitiveExpression(virtualPath))));
                    }

                    //Generate the code
                    provider.GenerateCodeFromCompileUnit(generatedCode, writer, options);

                    if (this.CodeGeneratorProgress != null)
                    {
                        //Report that we are done
                        this.CodeGeneratorProgress.Progress(100, 100);
                    }
                    writer.Flush();

                    // Save as UTF8
                    Encoding enc = Encoding.UTF8;

                    //Get the preamble (byte-order mark) for our encoding
                    byte[] preamble       = enc.GetPreamble();
                    int    preambleLength = preamble.Length;

                    //Convert the writer contents to a byte array
                    byte[] body = enc.GetBytes(writer.ToString());

                    //Prepend the preamble to body (store result in resized preamble array)
                    Array.Resize <byte>(ref preamble, preambleLength + body.Length);
                    Array.Copy(body, 0, preamble, preambleLength, body.Length);

                    //Return the combined byte array
                    return(preamble);
                }
            }
            catch (Exception e) {
                this.GeneratorError(4, e.ToString(), 1, 1);
                //Returning null signifies that generation has failed
                return(null);
            }
        }
Ejemplo n.º 15
0
 // Methods
 public void Add(string virtualDirectory, VirtualDirectoryMapping mapping)
 {
 }
 public void CopyTo(VirtualDirectoryMapping[] array, int index)
 {
 }
        /// <summary>
        /// Gets the current applications &lt;NSIClient&gt; section.
        /// </summary>
        /// <param name="configLevel">
        /// The &lt;ConfigurationUserLevel&gt; that the config file
        /// is retrieved from.
        /// </param>
        /// <returns>
        /// The configuration file's &lt;NSIClient&gt; section.
        /// </returns>
        public static NSIClientSettings GetSection(ConfigurationUserLevel configLevel)
        {
            /*
             * This class is setup using a factory pattern that forces you to
             * name the section &lt;NSIClient&gt; in the config file.
             * If you would prefer to be able to specify the name of the section,
             * then remove this method and mark the constructor public.
             */
            Configuration     config         = null;
            HttpContext       ctx            = HttpContext.Current;
            NSIClientSettings clientSettings = null;

            if (ctx != null)
            {
                string virtualPath = ctx.Request.ApplicationPath;

                try
                {
                    config = WebConfigurationManager.OpenWebConfiguration(virtualPath);
                }
                catch (ConfigurationErrorsException ex)
                {
                    string message = Resources.ExceptionReadingConfiguration + ex.Message;
                    if (virtualPath != null)
                    {
                        message = string.Format(
                            CultureInfo.InvariantCulture,
                            Resources.InfoWebConfigLocation,
                            message,
                            ctx.Server.MapPath(virtualPath));
                    }

                    Console.WriteLine(ex.ToString());
                    Console.WriteLine(message);
                    try
                    {
                        var map = new WebConfigurationFileMap();
                        var vd  = new VirtualDirectoryMapping(ctx.Server.MapPath(virtualPath), true);

                        map.VirtualDirectories.Add(virtualPath, vd);
                        config = WebConfigurationManager.OpenMappedWebConfiguration(map, virtualPath);
                    }
                    catch (ConfigurationException e)
                    {
                        Console.WriteLine(e.ToString());

                        // read-only..
                        clientSettings =
                            (NSIClientSettings)
                            WebConfigurationManager.GetWebApplicationSection(typeof(NSIClientSettings).Name);
                    }

                    // throw new NSIClientException(message, ex);
                }
            }
            else
            {
                config = ConfigurationManager.OpenExeConfiguration(configLevel);
            }

            if (config != null)
            {
                clientSettings = (NSIClientSettings)config.GetSection("NSIClientSettings");
                if (clientSettings == null)
                {
                    clientSettings = new NSIClientSettings();
                    config.Sections.Add("NSIClientSettings", clientSettings);
                }

                clientSettings._config = config;
            }
            else
            {
                if (clientSettings == null)
                {
                    throw new NsiClientException("Missing NSIClientSettings. Cannot add NSIClientSettings settings");
                }
            }

            return(clientSettings);
        }
Ejemplo n.º 18
0
        private void InvestigateDotNet(ServerManager localServer)
        {
            //todo find any commercial deployments???
            //todo detect windows services???
            //todo get app type: Webforms, MVC, WebAPI
            //todo detect sizes of files and directories: app DLLs, all DLLs, all HTML/JS/CSS, whole app, logs)

            foreach (var site in _server.Sites)
            {
                foreach (var dir in site.VirtualDirectories)
                {
                    //load up web.config
                    var virtualDirectoryMapping = new VirtualDirectoryMapping(Environment.ExpandEnvironmentVariables(dir.PhysicalPath), true, "web.config");
                    var fileMap = new WebConfigurationFileMap();
                    fileMap.VirtualDirectories.Add(dir.Path, virtualDirectoryMapping);
                    var webConfig = WebConfigurationManager.OpenMappedWebConfiguration(fileMap, dir.Path, site.Name);

                    //how to work with this webConfig: https://msdn.microsoft.com/en-us/library/system.web.configuration(v=vs.110).aspx

                    var connectionStrings = webConfig.ConnectionStrings.ConnectionStrings;
                    dir.Databases = connectionStrings.Cast <ConnectionStringSettings>().Select(connectionString => new Database
                    {
                        ConnectionName   = connectionString.Name,
                        ConnectionString = connectionString.ConnectionString,
                        Provider         = connectionString.ProviderName
                    }).ToList();

                    var authSection = (AuthenticationSection)webConfig.GetSection("system.web/authentication");
                    dir.AuthenticationMode = authSection.Mode.ToString();
                    //if more auth info is needed for forms auth, start grabbing things off of the authSection.Forms...
                    //dir.Auth = authSection.Forms.

                    //digging up security issues. refer to OWASP guidelines
                    //http://www.developerfusion.com/article/6678/top-10-application-security-vulnerabilities-in-webconfig-files-part-one/
                    //https://www.troyhunt.com/owasp-top-10-for-net-developers-part-2/ <-- look at the whole series

                    var compilationSection = (CompilationSection)webConfig.GetSection("system.web/compilation");
                    dir.TargetDotNetFramework = compilationSection.TargetFramework;
                    dir.DebugEnabled          = compilationSection.Debug;

                    var customErrorsSection = (CustomErrorsSection)webConfig.GetSection("system.web/customErrors");
                    dir.RevealsStockErrorPages = customErrorsSection.Mode == CustomErrorsMode.Off;
                    dir.RevealsErrorUrls       = customErrorsSection.RedirectMode == CustomErrorsRedirectMode.ResponseRedirect;

                    var traceSection = (TraceSection)webConfig.GetSection("system.web/trace");
                    dir.TracePubliclyEnabled = traceSection.Enabled && !traceSection.LocalOnly;

                    var httpRuntimeSection = (HttpRuntimeSection)webConfig.GetSection("system.web/httpRuntime");
                    dir.RevealsAspNetVersionHeader = httpRuntimeSection.EnableVersionHeader;

                    var pagesSection = (PagesSection)webConfig.GetSection("system.web/pages");
                    dir.RequestValidationDisabled = !pagesSection.ValidateRequest;

                    var cookiesSection = (HttpCookiesSection)webConfig.GetSection("system.web/httpCookies");
                    dir.JavaScriptCanAccessCookies = !cookiesSection.HttpOnlyCookies;
                    dir.InsecureCookiesAllowed     = !cookiesSection.RequireSSL;

                    var sessionStateSection = (SessionStateSection)webConfig.GetSection("system.web/sessionState");
                    dir.CookielessSessionsAllowed = sessionStateSection.Cookieless != HttpCookieMode.UseCookies;
                }
            }
        }
Ejemplo n.º 19
0
        public override void ProjectFinishedGenerating(Project project)
        {
            if (project != null)
            {
                VSProject vsProj = project.Object as VSProject;
                var       tables = new List <string>();

                Settings.Default.MVCWizardConnection = WizardForm.ServerExplorerConnectionSelected;
                Settings.Default.Save();

                if (_generalPane != null)
                {
                    _generalPane.Activate();
                }

                SendToGeneralOutputWindow("Starting project generation...");

                //Updating project references
                try
                {
                    vsProj.References.Add("MySql.Data");
                }
                catch
                {
                    var infoResult = InfoDialog.ShowDialog(
                        InfoDialogProperties.GetOkCancelDialogProperties(
                            InfoDialog.InfoType.Warning,
                            Resources.MySqlDataProviderPackage_ConnectorNetNotFoundError,
                            @"To use it you must download and install the MySQL Connector/Net package from http://dev.mysql.com/downloads/connector/net/",
                            Resources.MySqlDataProviderPackage_ClickOkOrCancel));
                    if (infoResult.DialogResult == DialogResult.OK)
                    {
                        ProcessStartInfo browserInfo = new ProcessStartInfo("http://dev.mysql.com/downloads/connector/net/");
                        System.Diagnostics.Process.Start(browserInfo);
                    }
                }

                double version = double.Parse(WizardForm.Wizard.GetVisualStudioVersion());
                if (version >= 12.0)
                {
                    References refs = vsProj.References;
                    foreach (Reference item in refs)
                    {
                        switch (item.Name)
                        {
                        case "System.Web.Razor":
                            if (item.Version.Equals("1.0.0.0"))
                            {
                                vsProj.References.Find("System.Web.Razor").Remove();
                            }
                            break;

                        case "System.Web.WebPages":
                            vsProj.References.Find("System.Web.WebPages").Remove();
                            break;

                        case "System.Web.Mvc":
                            vsProj.References.Find("System.Web.Mvc").Remove();
                            break;

                        case "System.Web.Helpers":
                            vsProj.References.Find("System.Web.Helpers").Remove();
                            break;
                        }
                    }

                    vsProj.References.Add("System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL");
                    vsProj.References.Add("System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL");
                    vsProj.References.Add("System.Web.Helpers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL");
                    vsProj.References.Add("System.Web.Razor");

#if NET_40_OR_GREATER
                    vsProj.Project.Save();
#endif
                }
                AddNugetPackage(vsProj, JQUERY_PKG_NAME, JQUERY_VERSION, false);
                var packagesPath = Path.Combine(Path.GetDirectoryName(ProjectPath), @"Packages\jQuery." + JQUERY_VERSION + @"\Content\Scripts");
                CopyPackageToProject(vsProj, ProjectPath, packagesPath, "Scripts");

                if (WizardForm.SelectedTables != null && WizardForm.DEVersion != DataEntityVersion.None)
                {
                    WizardForm.SelectedTables.ForEach(t => tables.Add(t.Name));

                    SendToGeneralOutputWindow("Generating Entity Framework model...");
                    if (tables.Count > 0)
                    {
                        if (WizardForm.DEVersion == DataEntityVersion.EntityFramework5)
                        {
                            CurrentEntityFrameworkVersion = ENTITY_FRAMEWORK_VERSION_5;
                        }
                        else if (WizardForm.DEVersion == DataEntityVersion.EntityFramework6)
                        {
                            CurrentEntityFrameworkVersion = ENTITY_FRAMEWORK_VERSION_6;
                        }

                        AddNugetPackage(vsProj, ENTITY_FRAMEWORK_PCK_NAME, CurrentEntityFrameworkVersion, true);
                        string modelPath = Path.Combine(ProjectPath, "Models");
                        GenerateEntityFrameworkModel(project, vsProj, new MySqlConnection(WizardForm.ConnectionStringForModel), WizardForm.ModelName, tables, modelPath);
                        GenerateMVCItems(vsProj);

                        if (WizardForm.DEVersion == DataEntityVersion.EntityFramework6)
                        {
                            project.DTE.SuppressUI = true;
                            project.Properties.Item("TargetFrameworkMoniker").Value = ".NETFramework,Version=v4.5";
                        }
                    }
                }

                else
                {
                    string indexPath = Language == LanguageGenerator.CSharp ? (string)(FindProjectItem(FindProjectItem(FindProjectItem(vsProj.Project.ProjectItems, "Views").ProjectItems,
                                                                                                                       "Home").ProjectItems, "Index.cshtml").Properties.Item("FullPath").Value) :
                                       (string)(FindProjectItem(FindProjectItem(FindProjectItem(vsProj.Project.ProjectItems, "Views").ProjectItems,
                                                                                "Home").ProjectItems, "Index.vbhtml").Properties.Item("FullPath").Value);

                    string contents = File.ReadAllText(indexPath);
                    contents = contents.Replace("$catalogList$", String.Empty);
                    File.WriteAllText(indexPath, contents);
                }

                var webConfig = new MySql.Data.VisualStudio.WebConfig.WebConfig(ProjectPath + @"\web.config");
                SendToGeneralOutputWindow("Starting provider configuration...");
                try
                {
                    try
                    {
                        string configPath = ProjectPath + @"\web.config";

                        if (WizardForm.CreateAdministratorUser)
                        {
                            SendToGeneralOutputWindow("Creating administrator user...");
                            using (AppConfig.Load(configPath))
                            {
                                var configFile = new FileInfo(configPath);
                                var vdm        = new VirtualDirectoryMapping(configFile.DirectoryName, true, configFile.Name);
                                var wcfm       = new WebConfigurationFileMap();
                                wcfm.VirtualDirectories.Add("/", vdm);
                                System.Configuration.Configuration config = WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");
                                try
                                {
                                    if (!WizardForm.IncludeSensitiveInformation)
                                    {
                                        ConnectionStringsSection connectionStringsection = config.GetSection("connectionStrings") as ConnectionStringsSection;
                                        if (connectionStringsection != null)
                                        {
                                            connectionStringsection.ConnectionStrings[WizardForm.ConnectionStringNameForAspNetTables].ConnectionString = _fullconnectionstring;
                                            config.Save();
                                        }
                                    }
                                }
                                catch
                                { }

                                MembershipSection          section          = (MembershipSection)config.GetSection("system.web/membership");
                                ProviderSettingsCollection settings         = section.Providers;
                                NameValueCollection        membershipParams = settings[section.DefaultProvider].Parameters;
                                var provider = new MySQLMembershipProvider();

                                provider.Initialize(section.DefaultProvider, membershipParams);

                                //create the user
                                MembershipCreateStatus status;
                                if (!WizardForm.RequireQuestionAndAnswer)
                                {
                                    provider.CreateUser(WizardForm.AdminName, WizardForm.AdminPassword, "*****@*****.**", null, null, true, null, out status);
                                }
                                else
                                {
                                    provider.CreateUser(WizardForm.AdminName, WizardForm.AdminPassword, "*****@*****.**", WizardForm.UserQuestion, WizardForm.UserAnswer, true, null, out status);
                                }
                            }
                        }

                        // add creation of providers tables
                        if (WizardForm.IncludeProfilesProvider)
                        {
                            var profileConfig = new ProfileConfig();
                            profileConfig.Initialize(webConfig);
                            profileConfig.Enabled         = true;
                            profileConfig.DefaultProvider = "MySQLProfileProvider";

                            var options = new Options();
                            options.AppName               = @"\";
                            options.AutoGenSchema         = true;
                            options.ConnectionStringName  = WizardForm.ConnectionStringNameForAspNetTables;
                            options.ConnectionString      = WizardForm.ConnectionStringForAspNetTables;
                            options.EnableExpireCallback  = false;
                            options.ProviderName          = "MySQLProfileProvider";
                            options.WriteExceptionToLog   = WizardForm.WriteExceptionsToLog;
                            profileConfig.GenericOptions  = options;
                            profileConfig.DefaultProvider = "MySQLProfileProvider";
                            profileConfig.Save(webConfig);
                        }

                        if (WizardForm.IncludeRoleProvider)
                        {
                            var roleConfig = new RoleConfig();
                            roleConfig.Initialize(webConfig);
                            roleConfig.Enabled         = true;
                            roleConfig.DefaultProvider = "MySQLRoleProvider";

                            var options = new Options();
                            options.AppName              = @"\";
                            options.AutoGenSchema        = true;
                            options.ConnectionStringName = WizardForm.ConnectionStringNameForAspNetTables;
                            options.ConnectionString     = WizardForm.ConnectionStringForAspNetTables;
                            options.EnableExpireCallback = false;
                            options.ProviderName         = "MySQLRoleProvider";
                            options.WriteExceptionToLog  = WizardForm.WriteExceptionsToLog;
                            roleConfig.GenericOptions    = options;
                            roleConfig.DefaultProvider   = "MySQLRoleProvider";
                            roleConfig.Save(webConfig);
                        }
                        webConfig.Save();
                    }
                    catch (Exception ex)
                    {
                        MySqlSourceTrace.WriteAppErrorToLog(ex, null, Resources.WebWizard_UserCreationError, true);
                    }
                }
                catch (Exception ex)
                {
                    MySqlSourceTrace.WriteAppErrorToLog(ex, true);
                }
            }

            SendToGeneralOutputWindow("Finished project generation.");
            WizardForm.Dispose();
        }