/// <summary>
        /// If verification fails, the package will be installed by this method.
        /// </summary>
        /// <param name="packageFileName">The file name of the Sitecore Package located in Sitecore's configured Packages folder.</param>
        protected virtual void InstallPackage(string packageFileName)
        {
            var filePath = $"{Sitecore.Configuration.Settings.DataFolder}/packages/{packageFileName}";

            using (new SecurityDisabler())
            {
                var installMode = Details.InstallMode;

                if (installMode == InstallMode.Undefined)
                {
                    installMode = PackageVerifierConfiguration.Current.DefaultInstallMode;
                }

                var mergeMode = Details.MergeMode;
                if (mergeMode == MergeMode.Undefined)
                {
                    mergeMode = PackageVerifierConfiguration.Current.DefaultMergeMode;
                }

                using (new SyncOperationContext())
                {
                    IProcessingContext   context = new SimpleProcessingContext();
                    IItemInstallerEvents events  =
                        new DefaultItemInstallerEvents(
                            new BehaviourOptions(installMode, mergeMode));

                    context.AddAspect(events);
                    IFileInstallerEvents events1 = new DefaultFileInstallerEvents(true);
                    context.AddAspect(events1);

                    var installer = new Sitecore.Install.Installer();
                    installer.InstallPackage(MainUtil.MapPath(filePath), context);
                }
            }
        }
Example #2
0
        public void RegisterSitemapToRobotsFile()
        {
            string        robotsPath     = MainUtil.MapPath(string.Concat("/", "robots.txt"));
            StringBuilder sitemapContent = new StringBuilder(string.Empty);

            if (File.Exists(robotsPath))
            {
                StreamReader sr = new StreamReader(robotsPath);
                sitemapContent.Append(sr.ReadToEnd());
                sr.Close();
            }

            StreamWriter sw = new StreamWriter(robotsPath, false);

            foreach (string sitemapUrl in m_Sites.Values)
            {
                string sitemapLine = string.Concat("Sitemap: ", sitemapUrl);
                if (!sitemapContent.ToString().Contains(sitemapLine))
                {
                    sitemapContent.AppendLine(sitemapLine);
                }
            }
            sw.Write(sitemapContent.ToString());
            sw.Close();
        }
Example #3
0
        public void RegisterSitemapToRobotsFile()
        {
            if (string.IsNullOrWhiteSpace(_config.FileName))
            {
                return;
            }
            var robotsPath     = MainUtil.MapPath(string.Concat("/", Constants.RobotsFileName));
            var sitemapContent = new StringBuilder(string.Empty);


            if (File.Exists(robotsPath))
            {
                var sr = new StreamReader(robotsPath);
                sitemapContent.Append(sr.ReadToEnd());
                sr.Close();
            }
            else
            {
                sitemapContent.AppendLine("User-agent: *");
                sitemapContent.AppendLine("Disallow:");
            }

            var sw          = new StreamWriter(robotsPath, false);
            var sitemapUrl  = _config.ServerUrl + "/" + _config.FileName;
            var sitemapLine = string.Concat("Sitemap: ", sitemapUrl);

            if (!sitemapContent.ToString().Contains(sitemapLine))
            {
                sitemapContent.AppendLine(sitemapLine);
            }
            sw.Write(sitemapContent.ToString());
            sw.Close();
        }
Example #4
0
 public void AddSitemapToRobots(string xmlFileName)
 {
     try
     {
         string        _RobotsFilePath = MainUtil.MapPath("/" + "robots.txt");
         StringBuilder sbRobots        = new StringBuilder(string.Empty);
         if (File.Exists(_RobotsFilePath))
         {
             StreamReader reader = new StreamReader(_RobotsFilePath);
             sbRobots.Append(reader.ReadToEnd());
             reader.Close();
         }
         StreamWriter writer          = new StreamWriter(_RobotsFilePath, false);
         string       _stringToAppend = "Sitemap: " + xmlFileName;
         if (!sbRobots.ToString().Contains(_stringToAppend))
         {
             sbRobots.AppendLine(_stringToAppend);
         }
         writer.Write(sbRobots.ToString());
         writer.Close();
     }
     catch (Exception ex)
     {
         Log.Error(ex.Message, "SiteMapBuilder - AddSitemapToRobots method");
     }
 }
Example #5
0
        public ActionResult InstallPackage()
        {
            StringBuilder ret = new StringBuilder();
            Stopwatch     sw  = new Stopwatch();

            sw.Start();
            try
            {
                using (new SecurityDisabler())
                    using (new SyncOperationContext())
                    {
                        IProcessingContext   context = new SimpleProcessingContext();
                        IItemInstallerEvents events  =
                            new DefaultItemInstallerEvents(
                                new BehaviourOptions(InstallMode.Overwrite, MergeMode.Undefined));
                        context.AddAspect(events);
                        IFileInstallerEvents events1 = new DefaultFileInstallerEvents(true);
                        context.AddAspect(events1);

                        Sitecore.Install.Installer installer = new Sitecore.Install.Installer();
                        installer.InstallPackage(MainUtil.MapPath(@"C:\inetpub\wwwroot\demo1.local\App_Data\packages\bigtst.zip"), context);
                    }
            }
            catch (Exception e)
            {
                ret.Append(e.ToString());
            }
            finally
            {
                ret.Append($"\n\n{sw.Elapsed.TotalSeconds}");
            }

            return(Content(ret.ToString()));
        }
Example #6
0
        public void RegisterSitemapToRobotsFile()
        {
            if (string.IsNullOrWhiteSpace(_config.FileName))
            {
                return;
            }
            string        robotsPath     = MainUtil.MapPath(string.Concat("/", Constants.RobotsFileName));
            StringBuilder sitemapContent = new StringBuilder(string.Empty);

            if (File.Exists(robotsPath))
            {
                StreamReader sr = new StreamReader(robotsPath);
                sitemapContent.Append(sr.ReadToEnd());
                sr.Close();
            }

            StreamWriter sw = new StreamWriter(robotsPath, false);
            //string sitemapLine = string.Concat(_config.SiteRobotsTxtContent);
            string robotsContent = string.Concat(_config.SiteRobotsTxtContent);
            string sitemapLine   = string.Concat("Sitemap: " + _config.ServerUrl + "/" + _config.FileName);

            if (!sitemapContent.ToString().Contains(sitemapLine))
            {
                sitemapContent.AppendLine(robotsContent);
                sitemapContent.AppendLine(sitemapLine);
            }
            sw.Write(sitemapContent.ToString());
            sw.Close();
        }
Example #7
0
        public void RegisterSitemapToRobotsFile()
        {
            string        robotsPath     = MainUtil.MapPath(string.Concat("/", "robots.txt"));
            StringBuilder sitemapContent = new StringBuilder(string.Empty);

            if (File.Exists(robotsPath))
            {
                StreamReader sr = new StreamReader(robotsPath);
                sitemapContent.Append(sr.ReadToEnd());
                sr.Close();
            }

            StreamWriter sw = new StreamWriter(robotsPath, false);

            foreach (DictionaryEntry site in m_Sites)
            {
                string sitemapLine = string.Format("Sitemap: http://{0}/{1}", SitemapManagerConfiguration.GetServerUrlBySite(site.Key.ToString()), site.Value);
                if (!sitemapContent.ToString().Contains(sitemapLine))
                {
                    sitemapContent.AppendLine(sitemapLine);
                }
            }
            sw.Write(sitemapContent.ToString());
            sw.Close();
        }
        public bool LoadFromFile([NotNull] string name)
        {
            lock (this)
            {
                try
                {
                    name = MainUtil.MapPath(name);
                    if (!File.Exists(name))
                    {
                        return(false);
                    }

                    var formatter = new BinaryFormatter();

                    using (var stream = File.OpenRead(name))
                    {
                        var loadedState = (State)formatter.Deserialize(stream);
                        if (CurrentStateVersion == loadedState.version)
                        {
                            _State = loadedState;
                            return(true);
                        }

                        return(false);
                    }
                }
                catch (Exception e)
                {
                    Log.Error("Memory Data Provider - Failed to load from cache: ", e, this);
                    return(false);
                }
            }
        }
        public void RegisterSitemapToRobotsFile()
        {
            if (!SitemapManagerConfiguration.GenerateRobotsFile)
            {
                return;
            }

            var robotsPath     = MainUtil.MapPath(string.Concat("/", "robots.txt"));
            var sitemapContent = new StringBuilder(string.Empty);

            if (File.Exists(robotsPath))
            {
                var sr = new StreamReader(robotsPath);
                sitemapContent.Append(sr.ReadToEnd());
                sr.Close();
            }

            var sw = new StreamWriter(robotsPath, false);

            foreach (var sitemapUrl in _sites.Values)
            {
                var sitemapLine = string.Concat("Sitemap: ", sitemapUrl);
                if (!sitemapContent.ToString().Contains(sitemapLine))
                {
                    sitemapContent.AppendLine(sitemapLine);
                }
            }
            sw.Write(sitemapContent.ToString());
            sw.Close();
        }
        public ProtobufDataProvider([NotNull] string databaseName, [NotNull] string filePath)
        {
            Assert.ArgumentNotNullOrEmpty(databaseName, nameof(databaseName));
            Assert.ArgumentNotNullOrEmpty(filePath, nameof(filePath));

            DataSet = new ItemsDataSet(new FileInfo(MainUtil.MapPath(filePath)));
        }
        public void RegisterSitemapToRobotsFile()
        {
            string        robotsPath     = MainUtil.MapPath(string.Concat("/", "robots.txt"));
            StringBuilder sitemapContent = new StringBuilder(string.Empty);

            if (File.Exists(robotsPath))
            {
                StreamReader sr = new StreamReader(robotsPath);
                sitemapContent.Append(sr.ReadToEnd());
                sr.Close();
            }

            StreamWriter sw = new StreamWriter(robotsPath, false);

            // If production, add sitemap Urls to robots.txt.  Otherwise, disallow all bots.
            if (SitemapManagerConfiguration.IsProductionEnvironment)
            {
                foreach (string sitemapUrl in m_Sites.Values)
                {
                    string sitemapLine = string.Concat("sitemap: ", sitemapUrl);
                    if (!sitemapContent.ToString().Contains(sitemapLine))
                    {
                        sitemapContent.AppendLine(sitemapLine);
                    }
                }
            }
            else
            {
                sitemapContent = new StringBuilder();
                sitemapContent.AppendLine("User-agent: *");
                sitemapContent.AppendLine("Disallow: /");
            }
            sw.Write(sitemapContent.ToString());
            sw.Close();
        }
        /// <summary>
        /// Ensures that sitemaps directory exists
        /// </summary>
        protected static void EnsureSitemapsDirectoryExists()
        {
            String dirPath = MainUtil.MapPath(DynamicSitemapConfiguration.SitemapConfigurationOutputFolder + "/");

            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
        }
        /// <summary>
        /// Generates sitemaps index
        /// </summary>
        protected void GenerateSitemapsIndex()
        {
            if (!DynamicSitemapConfiguration.UseSitemapsIndexFile)
            {
                return;
            }

            var encoding = Encoding.UTF8;
            StringWriterWithEncoding stringWriter = new StringWriterWithEncoding(encoding);

            // - Creating the XML Header -

            var xml = new XmlTextWriter(stringWriter);

            xml.WriteStartDocument();
            xml.WriteStartElement("sitemapindex", DynamicSitemapConfiguration.XmlnsTpl);

            int sitemapsCount = 0;

            try
            {
                foreach (var sitemap in this.SiteConfigurations)
                {
                    xml.WriteStartElement("sitemap");
                    xml.WriteElementString("loc", sitemap.SitemapUrl);

                    var lastModified = DateTime.UtcNow.ToString("yyyy-MM-ddThh:mm:sszzz");

                    xml.WriteElementString("lastmod", lastModified);
                    xml.WriteEndElement();

                    sitemapsCount++;
                }
            }

            catch (Exception exc)
            {
                Diagnostics.Log.Error("DynamicSitemapGenerator: " + exc.Message + "\n\n" + exc.StackTrace, this);
            }

            finally
            {
                xml.WriteEndElement();
                xml.WriteEndDocument();
                xml.Flush();

                String result = stringWriter.ToString();

                string path = MainUtil.MapPath("/" + this.SitemapIndex.FileName);

                StreamWriter streamWriter = new StreamWriter(path, false);
                streamWriter.Write(result);
                streamWriter.Close();

                Diagnostics.Log.Info("DynamicSitemapGenerator: Sitemap index generated - in path " + path + ", " + sitemapsCount + " sitemaps attached", this);
            }
        }
        public void InstallPackage()
        {
            var filepath = "";

            if (System.Text.RegularExpressions.Regex.IsMatch(Settings.DataFolder, @"^(([a-zA-Z]:\\)|(//)).*"))
            {
                //if we have an absolute path, rather than relative to the site root
                filepath = Settings.DataFolder +
                           @"\packages\DemandbasePackage.zip";
            }
            else
            {
                filepath = HttpRuntime.AppDomainAppPath + Settings.DataFolder.Substring(1) +
                           @"\packages\DemandbasePackage.zip";
            }
            try
            {
                GeneratePackage(filepath);
                int count = 0;
                while (true)
                {
                    if (count > 15)
                    {
                        throw new Exception("Demandbase package extracted to data folder packages however appears to be locked, unlock this file and recycle the app pool.");
                    }
                    if (!IsFileLocked(new FileInfo(filepath)))
                    {
                        using (new SecurityDisabler())
                        {
                            using (new SyncOperationContext())
                            {
                                IProcessingContext   context = new SimpleProcessingContext();
                                IItemInstallerEvents events  =
                                    new DefaultItemInstallerEvents(
                                        new BehaviourOptions(InstallMode.Overwrite, MergeMode.Undefined));
                                context.AddAspect(events);
                                IFileInstallerEvents events1 = new DefaultFileInstallerEvents(true);
                                context.AddAspect(events1);

                                Sitecore.Install.Installer installer = new Sitecore.Install.Installer();
                                installer.InstallPackage(MainUtil.MapPath(filepath), context);
                                break;
                            }
                        }
                    }
                    else
                    {
                        Thread.Sleep(1000);
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error("Demandbase was unable to initialize", e, this);
            }
        }
        private void BuildSiteMapIndex()
        {
            string fullPath   = MainUtil.MapPath(string.Concat("/", SitemapManagerConfiguration.SitemapIndexFilename));
            string xmlContent = this.BuildSitemapIndexXML();

            StreamWriter strWriter = new StreamWriter(fullPath, false);

            strWriter.Write(xmlContent);
            strWriter.Close();
        }
Example #16
0
        protected virtual string PackageStoragePath(BuildPackageArgs args)
        {
            var storageSetting = Settings.GetSetting("Pintle.PackageStoragePath", "/packager");

            if (storageSetting.StartsWith("/"))
            {
                return(MainUtil.MapPath(storageSetting));
            }

            return(storageSetting);
        }
Example #17
0
        private void BuildSiteMap(string sitename, string sitemapUrlNew)
        {
            Site        site         = SiteManager.GetSite(sitename);
            string      startPath    = Factory.GetSite(sitename).StartPath;
            List <Item> sitemapItems = this.GetSitemapItems(startPath);
            string      path         = MainUtil.MapPath("/" + sitemapUrlNew);
            XmlDocument doc          = this.BuildSitemapXML(sitemapItems, site);

            XmlTextWriter writer = new XmlTextWriter(path, Encoding.UTF8);

            writer.Formatting = Formatting.Indented;
            doc.Save(writer);
        }
        protected override void OnLoad(EventArgs e)
        {
            Assert.ArgumentNotNull(e, "e");

            if (!Context.ClientPage.IsEvent && !Context.ClientPage.IsPostBack)
            {
                var packageGeneratorFolder = Settings.GetSetting("PackageGeneratorFolder");

                this.Directory = MainUtil.MapPath(string.Format("{0}/{1}", Settings.PackagePath, packageGeneratorFolder));

                this.FileList.Controls.Add(new LiteralControl(this.BuildFileInput()));
            }
            base.OnLoad(e);
        }
        /// <summary>
        /// Registers sitemaps to robots.txt
        /// </summary>
        public virtual void RegisterSitemapToRobotsFile()
        {
            if (DynamicSitemapConfiguration.RefreshRobotsFile)
            {
                String robotsPath = MainUtil.MapPath("/" + "robots.txt");

                StringBuilder stringBuilder = new StringBuilder(String.Empty);

                if (File.Exists(robotsPath))
                {
                    StreamReader streamReader = new StreamReader(robotsPath);
                    stringBuilder.Append(streamReader.ReadToEnd());
                    streamReader.Close();
                }

                StreamWriter streamWriter = new StreamWriter(robotsPath, false);

                List <String> sitemapUrls = new List <String>();

                if (DynamicSitemapConfiguration.UseSitemapsIndexFile)
                {
                    sitemapUrls.Add(SitemapIndex.Url);
                }

                else
                {
                    sitemapUrls.AddRange(SiteConfigurations.Select(x => x.SitemapUrl));
                }

                foreach (var url in sitemapUrls)
                {
                    String value = "Sitemap: " + url;

                    if (!stringBuilder.ToString().Contains(value))
                    {
                        if (!stringBuilder.ToString().EndsWith(Environment.NewLine) && stringBuilder.ToString().Trim() != String.Empty)
                        {
                            stringBuilder.AppendLine();
                        }

                        stringBuilder.AppendLine(value);
                    }
                }

                streamWriter.Write(stringBuilder.ToString());
                streamWriter.Close();
            }
        }
Example #20
0
        protected override void LoadAutoIncludeFiles(XmlNode element)
        {
            Assert.ArgumentNotNull((object)element, "element");
            var configPatcher = this.GetConfigPatcher(element);

            LoadAutoIncludeFiles(configPatcher, Path.Combine(ConfigurationRootDirectory, ConditionalConfigFolderName));
            this.LoadAutoIncludeFiles(configPatcher, MainUtil.MapPath("/App_Config/Sitecore/Components"));
            this.LoadAutoIncludeFiles(configPatcher, MainUtil.MapPath("/App_Config/Include"));
            foreach (var includeDirectory in ConfigurationIncludeDirectories)
            {
                if (Directory.Exists(includeDirectory))
                {
                    LoadAutoIncludeFiles(configPatcher, includeDirectory);
                }
            }
        }
        private void BuildSiteMap(string sitename, string sitemapUrlNew)
        {
            var site        = SiteManager.GetSite(sitename);
            var siteContext = Factory.GetSite(sitename);
            var items       = GetSitemapItems(siteContext.StartPath);
            var fullPath    = MainUtil.MapPath(string.Concat("/", sitemapUrlNew));
            var xmlContent  = BuildSitemapXml(items, site);

            using (var writer = new XmlTextWriter(fullPath, Encoding.UTF8))
            {
                writer.Formatting = Formatting.Indented;

                xmlContent.WriteContentTo(writer);
                writer.Flush();
            }
        }
Example #22
0
        private void BuildSiteMap()
        {
            Site        site        = Sitecore.Sites.SiteManager.GetSite(_config.SiteName);
            SiteContext siteContext = Factory.GetSite(_config.SiteName);
            string      rootPath    = siteContext.StartPath;

            List <SitemapItem> items = GetSitemapItems(rootPath);

            string fullPath   = MainUtil.MapPath(string.Concat("/", _config.FileName));
            string xmlContent = this.BuildSitemapXML(items, site);

            StreamWriter strWriter = new StreamWriter(fullPath, false);

            strWriter.Write(xmlContent);
            strWriter.Close();
        }
Example #23
0
        private void BuildSiteMap()
        {
            var site        = SiteManager.GetSite(_config.SiteName);
            var siteContext = Factory.GetSite(_config.SiteName);
            var rootPath    = siteContext.StartPath;

            var items = GetSitemapItems(rootPath);

            var fullPath   = MainUtil.MapPath(string.Concat("/", _config.FileName));
            var xmlContent = BuildSitemapXML(items, site);

            var strWriter = new StreamWriter(fullPath, false);

            strWriter.Write(xmlContent);
            strWriter.Close();
        }
        /// <summary>
        /// Restarts the web server by making a request to the webroot. The request has a short timeout and is expected to fail.
        /// The purpose is to initiate a request to IIS to restart the AppPool. The Url is determined by the Sitecore API or an optional config parameter.
        /// </summary>
        private void RestartSitecoreServer()
        {
            try
            {
                //Force restart of all apppools pointing the website. This can happen during long installs
                Log.Info("Forcing restart", this);

                string configFile = MainUtil.MapPath("/App_Config/Include/SPD_Restart.config");

                using (FileStream fs = File.Open(configFile, FileMode.Create))
                {
                    using (StreamWriter sw = new StreamWriter(fs))
                    {
                        sw.WriteLine("<!-- Restart -->");
                    }
                }

                Thread.Sleep(250);
                File.Delete(configFile);
            }
            catch (Exception ex)
            {
                Log.Error("Exception when forcing restart", ex, this);
            }

            string url = _restartUrl;

            if (string.IsNullOrEmpty(_restartUrl))
            {
                url = WebUtil.GetServerUrl();
            }

            Log.Info("Sitecore Package Deployer is attempting to restart Sitecore at the url: " + url, this);

            WebRequest req = WebRequest.Create(url);

            req.Timeout = 100;

            try
            {
                using (WebResponse resp = req.GetResponse())
                {
                }
            }
            catch (Exception)
            { }
        }
        internal static string GetPackageSource()
        {
            string packageSource = Settings.GetSetting("SitecorePackageDeployer.PackageSource");

            //See if the package source is a web path instead of a file system path.
            if (packageSource.StartsWith("/"))
            {
                packageSource = MainUtil.MapPath(packageSource);
            }

            if (!Directory.Exists(packageSource))
            {
                Directory.CreateDirectory(packageSource);
            }

            return(packageSource);
        }
        private void BuildSiteMap(string Sitename, string FileName, string IsSeparatelanguagefile)
        {
            List <Item> sitemapItems;
            Site        site        = SiteManager.GetSite(Sitename);
            SiteContext siteContext = Factory.GetSite(Sitename);

            XmlDocument xDoc = null;
            List <(XmlDocument doc, string lang)> sitedetails = new List <(XmlDocument doc, string lang)>();
            List <string> enabledLanguages = BuildListFromString(siteContext.Properties["enabledLanguages"], '|');

            if (enabledLanguages.Count == 0)
            {   //if the config doesn't specify any enabled languages, use the current context to retrieve items
                sitemapItems = this.GetSitemapItems(siteContext.StartPath, null);
                xDoc         = StartSitemapXML();
                xDoc         = this.BuildSitemapXML(xDoc, sitemapItems, site, null);
                sitedetails.Add((xDoc, ""));
            }
            else
            {
                //For each language supported by the site, retrieve the items using the language and build out sitemap links
                foreach (var language in enabledLanguages)
                {
                    sitemapItems = this.GetSitemapItems(siteContext.StartPath, Sitecore.Globalization.Language.Parse(language));
                    xDoc         = StartSitemapXML();
                    xDoc         = this.BuildSitemapXML(xDoc, sitemapItems, site, Sitecore.Globalization.Language.Parse(language));
                    if (IsSeparatelanguagefile.ToLower() == "yes")
                    {
                        sitedetails.Add((xDoc, language));
                    }
                    else
                    {
                        sitedetails.Add((xDoc, ""));
                    }
                }
            }
            foreach (var details in sitedetails)
            {
                string str      = String.Empty;
                string filename = !String.IsNullOrWhiteSpace(details.lang) ? String.Format("{0}-{1}.xml", FileName, details.lang) : FileName;
                str = MainUtil.MapPath(string.Concat("/", filename));
                StreamWriter streamWriter = new StreamWriter(str, false);
                streamWriter.Write(details.doc.OuterXml);
                streamWriter.Close();
            }
        }
        protected void StartGeneration(Message message)
        {
            var packageGeneratorFolder = Settings.GetSetting("PackageGeneratorFolder");

            var filename = FileUtil.MakePath(Settings.PackagePath, string.Format(@"\{0}\{1}", packageGeneratorFolder, this.PackageFile.Value));

            this.ResultFile = MainUtil.MapPath(string.Format("{0}/{1}/{2}.zip", Settings.PackagePath, packageGeneratorFolder, this.PackageName.Value));

            if (FileUtil.IsFile(filename))
            {
                this.StartTask(filename);
            }
            else
            {
                Context.ClientPage.ClientResponse.Alert("Package not found");
                this.Active = "Ready";
                this.BackButton.Disabled = true;
            }
        }
        /// <summary>
        /// Locates changed configs installed by the package installer
        /// </summary>
        private void FindAndUpdateChangedConfigs(string installPackageName)
        {
            string appConfigFolder = MainUtil.MapPath("/");

            foreach (string newConfigFile in Directory.GetFiles(appConfigFolder, "*.config." + installPackageName, SearchOption.AllDirectories))
            {
                Log.Info(string.Format("Found changed config {0}", newConfigFile), this);

                int    configExtensionPos = newConfigFile.LastIndexOf(".config") + 7;
                string oldConfigFile      = Path.Combine(Path.GetDirectoryName(newConfigFile), newConfigFile.Substring(0, configExtensionPos));
                string backupConfigFile   = newConfigFile + string.Format(".backup{0:yyyyMMddhhmmss}", DateTime.Now);

                //Backup the existing config file
                if (File.Exists(oldConfigFile))
                {
                    if (File.Exists(backupConfigFile))
                    {
                        File.Delete(backupConfigFile);
                    }

                    Log.Info(string.Format("Backing up config file {0} as {1}", oldConfigFile, backupConfigFile), this);

                    File.Move(oldConfigFile, backupConfigFile);
                }

                Log.Info(string.Format("Copying new config file from {0} to {1}", newConfigFile, oldConfigFile), this);

                //Move the new file into place
                File.Copy(newConfigFile, oldConfigFile);

                //Someone didn't cleanup their handle to the new config file. This waits for it to be cleaned up
                GC.WaitForPendingFinalizers();

                try
                {
                    File.Delete(newConfigFile);
                }
                catch (Exception)
                {
                    Log.Warn(string.Format("Can't delete file {0}", newConfigFile), this);
                }
            }
        }
        public MemoryDataProvider([NotNull] string filename, [NotNull] string serializationPath)
        {
            Assert.ArgumentNotNullOrEmpty(serializationPath, nameof(serializationPath));
            Assert.ArgumentNotNullOrEmpty(filename, nameof(filename));

            ID = GetId(filename);
            Log.Debug("MemoryDataProvider " + ID + " is starting", this);
            filename          = MainUtil.MapPath(filename);
            serializationPath = Path.GetFullPath(Path.Combine(MainUtil.MapPath("/"), serializationPath));

            var started = new AutoResetEvent(false);

            ManagedThreadPool.QueueUserWorkItem(
                a =>
            {
                lock (this)
                {
                    started.Set();
                    try
                    {
                        using (new SecurityDisabler())
                        {
                            lock (string.Intern(filename))
                            {
                                if (!LoadFromFile(filename))
                                {
                                    LoadTree(serializationPath);
                                    SaveToFile(filename);
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Log.Error(e.ToString(), this);
                    }
                }
            });

            started.WaitOne();
        }
Example #30
0
        public void AddSegment([NotNull] XmlNode componentNode)
        {
            Assert.ArgumentNotNull(componentNode, "componentNode");

            var segmentElement = (XmlElement)componentNode;
            var rootString     = segmentElement.GetAttribute("root");

            Assert.IsNotNull(rootString, "root attribute is not specified or has empty string value: " + segmentElement.OuterXml);

            ID root;

            Assert.IsTrue(ID.TryParse(rootString, out root), "root attribute is not a valid GUID value: " + segmentElement.OuterXml);

            var file = segmentElement.GetAttribute("file");

            Assert.IsNotNullOrEmpty(file, "file attribute is not specified or has empty string value: " + segmentElement.OuterXml);

            var filePath = MainUtil.MapPath(file);
            var segment  = new JsonSegment(root, filePath);

            this.Segments.Add(segment);
        }