WriteAllLines() public static méthode

public static WriteAllLines ( String path, IEnumerable contents ) : void
path String
contents IEnumerable
Résultat void
Exemple #1
0
        private void AddTermsAndConditionsPage()
        {
            var migrationName = MethodBase.GetCurrentMethod().Name;

            try
            {
                var path = HostingEnvironment.MapPath(MigrationMarkersPath + migrationName + ".txt");
                if (File.Exists(path))
                {
                    return;
                }

                var contentService = ApplicationContext.Current.Services.ContentService;
                var rootContent    = contentService.GetRootContent().FirstOrDefault();
                if (rootContent != null)
                {
                    var termsAndConditionsContent = rootContent.Children().FirstOrDefault(x => x.Name == "Terms and conditions");
                    if (termsAndConditionsContent == null)
                    {
                        var content = contentService.CreateContent("Terms and conditions", rootContent.Id, "TextPage");
                        content.SetValue("bodyText", "<p>These are our terms and conditions...:</p>");
                        var status = contentService.SaveAndPublishWithStatus(content);
                    }
                }

                string[] lines = { "" };
                File.WriteAllLines(path, lines);
            }
            catch (Exception ex)
            {
                LogHelper.Error <MigrationsHandler>(string.Format("Migration: '{0}' failed", migrationName), ex);
            }
        }
Exemple #2
0
        private void UseNewForgotPasswordForm()
        {
            var migrationName = MethodBase.GetCurrentMethod().Name;

            try
            {
                var path = HostingEnvironment.MapPath(MigrationMarkersPath + migrationName + ".txt");
                if (File.Exists(path))
                {
                    return;
                }

                var macroService = ApplicationContext.Current.Services.MacroService;
                var macro        = macroService.GetByAlias("MemberPasswordReminder");
                macro.ControlType = "";
                macro.ScriptPath  = "~/Views/MacroPartials/Members/ForgotPassword.cshtml";
                macroService.Save(macro);

                string[] lines = { "" };
                File.WriteAllLines(path, lines);
            }
            catch (Exception ex)
            {
                LogHelper.Error <MigrationsHandler>(string.Format("Migration: '{0}' failed", migrationName), ex);
            }
        }
    /// <summary>
    ///     Asynchronously writes lines of text to a file.
    /// </summary>
    /// <param name="path">The path of the file.</param>
    /// <param name="contents">The contents to write.</param>
    /// <param name="encoding">The encoding to use.</param>
    /// <param name="cancellationToken">The cancellation token to stop this operation.</param>
    /// <returns>A task representing the current operation.</returns>
    /// <exception cref="ArgumentNullException">
    ///     <paramref name="path" /> or <paramref name="contents" /> is <see langword="null" /> (<see langword="Nothing" /> in
    ///     Visual Basic).
    /// </exception>
    /// <remarks>
    ///     This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
    ///     <see langword="null" />, an implementation-specific
    ///     encoding will be used.
    /// </remarks>
    public Task WriteAllLinesAsync(
        string path,
        IEnumerable <string> contents,
        Encoding?encoding = null,
        CancellationToken cancellationToken = default)
    {
        _ = Requires.NotNullOrWhiteSpace(
            path,
            nameof(path));
        _ = Requires.NotNull(
            contents,
            nameof(contents));

        return(encoding == null
            ? Work.OnThreadPoolAsync(
                   state => FSFile.WriteAllLines(
                       state.Path,
                       state.Contents),
                   (Path : path, Contents : contents),
                   cancellationToken)
               : Work.OnThreadPoolAsync(
                   state => FSFile.WriteAllLines(
                       state.Path,
                       state.Contents,
                       state.Encoding),
                   (Path : path, Contents : contents, Encoding : encoding),
                   cancellationToken));
    }
    /// <summary>
    ///     Writes lines of text to a file.
    /// </summary>
    /// <param name="path">The path of the file.</param>
    /// <param name="contents">The contents to write.</param>
    /// <param name="encoding">The encoding to use.</param>
    /// <exception cref="ArgumentNullException">
    ///     <paramref name="path" /> or <paramref name="contents" /> is <see langword="null" /> (<see langword="Nothing" /> in
    ///     Visual Basic).
    /// </exception>
    /// <remarks>
    ///     This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
    ///     <see langword="null" />, an implementation-specific
    ///     encoding will be used.
    /// </remarks>
    public void WriteAllLines(
        string path,
        IEnumerable <string> contents,
        Encoding?encoding = null)
    {
        _ = Requires.NotNullOrWhiteSpace(
            path,
            nameof(path));
        _ = Requires.NotNull(
            contents,
            nameof(contents));

        if (encoding == null)
        {
            FSFile.WriteAllLines(
                path,
                contents);
        }
        else
        {
            FSFile.WriteAllLines(
                path,
                contents,
                encoding);
        }
    }
Exemple #5
0
        public void RemoveLinesInFile(string filePath, IFileLinePredicate predicate, string destinationPath = null)
        {
            if (destinationPath.IsNull())
            {
                destinationPath = filePath;
            }

            string[] lines      = File.ReadAllLines(filePath);
            int      linesCount = lines.Length;

            List <string> destinationLines = new List <string>();

            for (int r = 0; r < linesCount; r++)
            {
                string oldLine = lines[r];

                if (!predicate.IsTrue(oldLine))
                {
                    destinationLines.Add(oldLine);
                }
            }

            if (predicate.IsSimulation)
            {
                return;
            }

            File.WriteAllLines(destinationPath, destinationLines);
        }
        private void AddHomeOnlyBannerTextArea()
        {
            var migrationName = MethodBase.GetCurrentMethod().Name;

            try
            {
                var path = HostingEnvironment.MapPath(MigrationMarkersPath + migrationName + ".txt");
                if (File.Exists(path))
                {
                    return;
                }

                var contentTypeService   = UmbracoContext.Current.Application.Services.ContentTypeService;
                var communityContentType = contentTypeService.GetContentType("Community");
                var propertyTypeAlias    = "homeOnlyBanner";
                if (communityContentType.PropertyTypeExists(propertyTypeAlias) == false)
                {
                    var textarea             = new DataTypeDefinition("Umbraco.TextboxMultiple");
                    var textareaPropertyType = new PropertyType(textarea, propertyTypeAlias)
                    {
                        Name = "Banner (only shown on home)"
                    };
                    communityContentType.AddPropertyType(textareaPropertyType, "Banners");
                    communityContentType.MovePropertyType("mainNotification", "Banners");
                    contentTypeService.Save(communityContentType);
                }

                string[] lines = { "" };
                File.WriteAllLines(path, lines);
            }
            catch (Exception ex)
            {
                LogHelper.Error <MigrationsHandler>(string.Format("Migration: '{0}' failed", migrationName), ex);
            }
        }
        public bool removeLyrics(string title)
        {
            try
            {
                title = title.ToLower().Trim();

                checkLocalResources();
                string[]      lyricsList     = File.ReadAllLines(localResourcesData);
                List <string> lyricsListTemp = new List <string>();
                foreach (string ly in lyricsList)
                {
                    if (ly.Contains("="))
                    {
                        string t = ly.Substring(0, ly.IndexOf("=")).ToLower().Trim();

                        if (t != title)
                        {
                            lyricsListTemp.Add(ly);
                        }
                    }
                    else
                    {
                        break;
                    }
                }

                File.Delete(localResourcesData);
                File.WriteAllLines(localResourcesData, lyricsListTemp);

                return(true);
            }
            catch (Exception ex) { }
            return(false);
        }
Exemple #8
0
        private void ForumArchivedCheckbox()
        {
            var migrationName = MethodBase.GetCurrentMethod().Name;

            try
            {
                var path = HostingEnvironment.MapPath(MigrationMarkersPath + migrationName + ".txt");
                if (File.Exists(path))
                {
                    return;
                }

                var contentTypeService = UmbracoContext.Current.Application.Services.ContentTypeService;
                var projectContentType = contentTypeService.GetContentType("Forum");
                var propertyTypeAlias  = "archived";
                if (projectContentType.PropertyTypeExists(propertyTypeAlias) == false)
                {
                    var checkbox             = new DataTypeDefinition("Umbraco.TrueFalse");
                    var checkboxPropertyType = new PropertyType(checkbox, propertyTypeAlias)
                    {
                        Name = "Archived"
                    };
                    projectContentType.AddPropertyType(checkboxPropertyType, "Forum Information");
                    contentTypeService.Save(projectContentType);
                }

                string[] lines = { "" };
                File.WriteAllLines(path, lines);
            }
            catch (Exception ex)
            {
                LogHelper.Error <MigrationsHandler>(string.Format("Migration: '{0}' failed", migrationName), ex);
            }
        }
Exemple #9
0
        private void UseNewMyProjectsOverview()
        {
            var migrationName = MethodBase.GetCurrentMethod().Name;

            try
            {
                var path = HostingEnvironment.MapPath(MigrationMarkersPath + migrationName + ".txt");
                if (File.Exists(path))
                {
                    return;
                }

                var macroService = ApplicationContext.Current.Services.MacroService;
                var allMacros    = macroService.GetAll();
                //For some reason GetByAlias does not work
                var macro = allMacros.FirstOrDefault(x => x.Alias == "DeliMyProjects");
                macro.ControlType = "";
                macro.ScriptPath  = "~/Views/MacroPartials/Projects/MyProjects.cshtml";
                macroService.Save(macro);

                string[] lines = { "" };
                File.WriteAllLines(path, lines);
            }
            catch (Exception ex)
            {
                LogHelper.Error <MigrationsHandler>(string.Format("Migration: '{0}' failed", migrationName), ex);
            }
        }
        public void ExportShapePathTests(FarmSimulatorVersion version, string shapeFileName)
        {
            var gameMapPath = GamePaths.GetGameMapsPath(version);

            if (!Directory.Exists(gameMapPath))
            {
                var message = $"Game map path not found: \"{version}\".";
                Trace.WriteLine(message);
                Assert.Inconclusive(message);
            }

            var mapPath = Path.Combine(gameMapPath, shapeFileName);

            if (!File.Exists(mapPath))
            {
                var message = $"Map not found \"{version}\": \"{mapPath}\".";
                Trace.WriteLine(message);
                Assert.Inconclusive(message);
            }

            var xmlMapFilePath = mapPath.Replace(GameConstants.SchapesFileExtension, GameConstants.XmlMapFileExtension);
            var mapFile        = MapFile.Load(xmlMapFilePath);
            var shapePaths     = FindShapePath(mapFile)
                                 .OrderBy(v => v.Id)
                                 .ToArray();

            File.WriteAllLines(Path.Combine(Output, version.ToString(), "shapes.path"), shapePaths.Select(v => v.ToString()));
        }
Exemple #11
0
 public void Save()
 {
     if (FilePath.Length <= 0)
     {
         return;
     }
     File.WriteAllLines(FilePath, Lines);
     Boot.Log(string.Format("Saved '{0}'", FilePath));
 }
Exemple #12
0
 public void Save(string path)
 {
     File.WriteAllLines(path, declarations);
     LogFile.Log("Saving to " + path);
     foreach (var line in declarations)
     {
         LogFile.Log("   " + line);
     }
 }
Exemple #13
0
        private void MemberActivationMigration()
        {
            var migrationName = MethodBase.GetCurrentMethod().Name;

            try
            {
                var path = HostingEnvironment.MapPath(MigrationMarkersPath + migrationName + ".txt");
                if (File.Exists(path))
                {
                    return;
                }

                var macroService = UmbracoContext.Current.Application.Services.MacroService;
                var macroAlias   = "MembersActivate";
                if (macroService.GetByAlias(macroAlias) == null)
                {
                    // Run migration

                    var macro = new Macro
                    {
                        Name          = "[Members] Activate",
                        Alias         = macroAlias,
                        ScriptingFile = "~/Views/MacroPartials/Members/Activate.cshtml",
                        UseInEditor   = true
                    };
                    macro.Save();
                }

                var contentService = UmbracoContext.Current.Application.Services.ContentService;
                var rootNode       = contentService.GetRootContent().OrderBy(x => x.SortOrder).First(x => x.ContentType.Alias == "Community");

                var memberNode = rootNode.Children().FirstOrDefault(x => x.Name == "Member");

                var pendingActivationPageName = "Pending activation";
                if (memberNode != null && memberNode.Children().Any(x => x.Name == pendingActivationPageName) == false)
                {
                    var pendingActivationPage = contentService.CreateContent(pendingActivationPageName, memberNode.Id, "Textpage");
                    pendingActivationPage.SetValue("bodyText", "<p>Thanks for signing up! <br />We\'ve sent you an email containing an activation link.</p><p>To be able to continue you need to click the link in that email. If you didn\'t get any mail from us, make sure to check your spam/junkmail folder for mail from [email protected].</p>");
                    contentService.SaveAndPublishWithStatus(pendingActivationPage);
                }

                var activatePageName = "Activate";
                if (memberNode != null && memberNode.Children().Any(x => x.Name == activatePageName) == false)
                {
                    var activatePage = contentService.CreateContent(activatePageName, memberNode.Id, "Textpage");
                    activatePage.SetValue("bodyText", string.Format("<?UMBRACO_MACRO macroAlias=\"{0}\" />", macroAlias));
                    contentService.SaveAndPublishWithStatus(activatePage);
                }

                string[] lines = { "" };
                File.WriteAllLines(path, lines);
            }
            catch (Exception ex)
            {
                LogHelper.Error <MigrationsHandler>(string.Format("Migration: '{0}' failed", migrationName), ex);
            }
        }
Exemple #14
0
 public static Task <Message> SecureSend(this string text, long chatid, string path)
 {
     if (text.Length < 3000)
     {
         return(Api.Send(chatid, text.FormatHTML()));
     }
     else
     {
         File.WriteAllLines(path, text.Split('\n'));
         return(Api.SendFile(chatid, path));
     }
 }
Exemple #15
0
        private void AddTwitterFilters()
        {
            var migrationName = MethodBase.GetCurrentMethod().Name;

            try
            {
                var path = HostingEnvironment.MapPath(MigrationMarkersPath + migrationName + ".txt");
                if (File.Exists(path))
                {
                    return;
                }

                var contentTypeService   = ApplicationContext.Current.Services.ContentTypeService;
                var communityContentType = contentTypeService.GetContentType("Community");
                var propertyTypeAlias    = "twitterFilterAccounts";
                var textboxMultiple      = new DataTypeDefinition("Umbraco.TextboxMultiple");

                var tabName = "Settings";
                if (communityContentType.PropertyGroups.Contains(tabName) == false)
                {
                    communityContentType.AddPropertyGroup(tabName);
                }

                if (communityContentType.PropertyTypeExists(propertyTypeAlias) == false)
                {
                    var textboxAccountsFilter = new PropertyType(textboxMultiple, propertyTypeAlias)
                    {
                        Name = "CSV of Twitter accounts to filter"
                    };
                    communityContentType.AddPropertyType(textboxAccountsFilter, tabName);
                }

                propertyTypeAlias = "twitterFilterWords";
                if (communityContentType.PropertyTypeExists(propertyTypeAlias) == false)
                {
                    var textboxWordFilter = new PropertyType(textboxMultiple, propertyTypeAlias)
                    {
                        Name = "CSV of words filter tweets out"
                    };
                    communityContentType.AddPropertyType(textboxWordFilter, tabName);
                }

                contentTypeService.Save(communityContentType);

                string[] lines = { "" };
                File.WriteAllLines(path, lines);
            }
            catch (Exception ex)
            {
                LogHelper.Error <MigrationsHandler>(string.Format("Migration: '{0}' failed", migrationName), ex);
            }
        }
Exemple #16
0
        public static void HtmlScoring(string text) //Outputs input above "</ul>"
        {
            string location   = @"C:\\Dynamix\\score_report.html";
            string lineToFind = "			<!--correct-->";

            List <string> lines = File.ReadLines(location).ToList();
            int           index = lines.IndexOf(lineToFind);

            lines.Insert(index, "<li>" + text + "</li>");
            File.WriteAllLines(location, lines);

            Console.WriteLine(text); //Just a debug
        }
    public async Task <string> GetAccessToken()
    {
        //First tries to get a token from the cache
        try {
            string previousLogin = "";
            previousLogin = await File.ReadAllTextAsync(
                System.Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile) +
                "\\todo\\prevUser.txt");

            previousLogin = previousLogin.Split("\r")[0]; //Evil formatting
            previousLogin = previousLogin.Split("\n")[0]; //Evil formatting again....
            var result = await _msalClient
                         .AcquireTokenSilent(_scopes, previousLogin)
                         .ExecuteAsync();

            return(result.AccessToken);
        } catch (Exception) {
            // If there is no saved user account, the user must sign-in
            if (_userAccount == null)
            {
                try {
                    // Let user sign in
                    var result = await _msalClient.AcquireTokenInteractive(_scopes).ExecuteAsync();

                    _userAccount = result.Account;
                    string[] lines = { _userAccount.Username };
                    File.WriteAllLines(
                        System.Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile) +
                        "\\todo\\prevUser.txt",
                        lines); //Questionable saving of previous user but its just a username and is local so should be fine
                    return(result.AccessToken);
                } catch (Exception exception) {
                    Console.WriteLine($"Error getting access token: {exception.Message}");
                    return(null);
                }
            }
            else
            {
                // If there is an account, call AcquireTokenSilent
                // By doing this, MSAL will refresh the token automatically if
                // it is expired. Otherwise it returns the cached token.
                var result = await _msalClient
                             .AcquireTokenSilent(_scopes, _userAccount)
                             .ExecuteAsync();

                return(result.AccessToken);
            }
        }
    }
Exemple #18
0
        private void AddMissingUmbracoUsers()
        {
            var migrationName = MethodBase.GetCurrentMethod().Name;

            try
            {
                var path = HostingEnvironment.MapPath(MigrationMarkersPath + migrationName + ".txt");
                if (File.Exists(path))
                {
                    return;
                }

                var userService = ApplicationContext.Current.Services.UserService;
                var rootUser    = userService.GetUserById(0);
                if (rootUser == null)
                {
                    return;
                }

                // Don't run this on Seb's database which has slightly different data in it
                if (rootUser.Email == "*****@*****.**")
                {
                    return;
                }

                var db = ApplicationContext.Current.DatabaseContext.Database;
                db.Execute("DELETE FROM [umbracoUser] WHERE id != 0");
                db.Execute("DELETE FROM [umbracoUser2app] WHERE [user] != 0");
                db.Execute("DBCC CHECKIDENT ('dbo.umbracoUser');");
                db.Execute("DBCC CHECKIDENT ('dbo.umbracoUser', NORESEED);");
                db.Execute("DBCC CHECKIDENT ('dbo.umbracoUser', RESEED, 1);");

                for (var i = 0; i < 17; i++)
                {
                    var user = userService.CreateUserWithIdentity(string.Format("user{0}", i), string.Format("user{0}@test.com", i));

                    var userGroup = ToReadOnlyGroup(userService.GetUserGroupByAlias("admin"));
                    user.AddGroup(userGroup);
                    userService.Save(user);
                }

                string[] lines = { "" };
                File.WriteAllLines(path, lines);
            }
            catch (Exception ex)
            {
                LogHelper.Error <MigrationsHandler>(string.Format("Migration: '{0}' failed", migrationName), ex);
            }
        }
Exemple #19
0
        private void SpamOverview()
        {
            var migrationName = MethodBase.GetCurrentMethod().Name;

            try
            {
                var path = HostingEnvironment.MapPath(MigrationMarkersPath + migrationName + ".txt");
                if (File.Exists(path))
                {
                    return;
                }

                var macroService = UmbracoContext.Current.Application.Services.MacroService;
                var macroAlias   = "AntiSpam";
                if (macroService.GetByAlias(macroAlias) == null)
                {
                    // Run migration

                    var macro = new Macro
                    {
                        Name          = "[Spam] Overview",
                        Alias         = macroAlias,
                        ScriptingFile = "~/Views/MacroPartials/Spam/Overview.cshtml",
                        UseInEditor   = true
                    };
                    macro.Save();
                }

                var contentService = UmbracoContext.Current.Application.Services.ContentService;
                var rootNode       = contentService.GetRootContent().OrderBy(x => x.SortOrder).First(x => x.ContentType.Alias == "Community");

                var antiSpamPageName = "AntiSpam";
                if (rootNode.Children().Any(x => x.Name == antiSpamPageName) == false)
                {
                    var content = contentService.CreateContent(antiSpamPageName, rootNode.Id, "Textpage");
                    content.SetValue("bodyText", string.Format("<?UMBRACO_MACRO macroAlias=\"{0}\" />", macroAlias));
                    contentService.SaveAndPublishWithStatus(content);
                }

                string[] lines = { "" };
                File.WriteAllLines(path, lines);
            }
            catch (Exception ex)
            {
                LogHelper.Error <MigrationsHandler>(string.Format("Migration: '{0}' failed", migrationName), ex);
            }
        }
        private void Button3_Click(object sender, EventArgs e)
        {
            if (savepatch != "not saved")
            {
                saveFileDialog1.Filter = "Shortcut (.lnk)|*.lnk|Bat file (.bat)|*.bat";
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    if (saveFileDialog1.FileName.Contains(".bat"))
                    {
                        string[] tmp  = new string[100];
                        char     tmp2 = '"';
                        tmp[0] = "cd " + Application.StartupPath;
                        tmp[1] = tmp2 + "BlueScreen Simulator" + tmp2 + " loadfile " + savepatch;
                        File.WriteAllLines(saveFileDialog1.FileName, tmp);
                    }
                    else
                    {
                        string[] tmp  = new string[100];
                        char     tmp2 = '"';
                        tmp[0] = "cd " + Application.StartupPath;
                        tmp[1] = tmp2 + "BlueScreen Simulator" + tmp2 + " loadfile " + savepatch;
                        if (saveFileDialog1.FileName.Contains(".lnk"))
                        {
                        }
                        else
                        {
                            saveFileDialog1.FileName += ".lnk";
                        }

                        object       shDesktop = (object)"Desktop";
                        WshShell     shell     = new WshShell();
                        IWshShortcut shortcut  = (IWshShortcut)shell.CreateShortcut(saveFileDialog1.FileName);
                        shortcut.TargetPath = Application.ExecutablePath;
                        shortcut.Arguments  = " loadfile " + savepatch;
                        shortcut.Save();

                        saveFileDialog1.FileName = "";
                        openFileDialog1.FileName = "";
                    }
                }
            }
            else
            {
                MessageBox.Show("Load or Save first");
            }
        }
Exemple #21
0
        private void OverrideYouTrack()
        {
            var migrationName = MethodBase.GetCurrentMethod().Name;

            try
            {
                var path = HostingEnvironment.MapPath(MigrationMarkersPath + migrationName + ".txt");
                if (File.Exists(path))
                {
                    return;
                }

                var contentTypeService = UmbracoContext.Current.Application.Services.ContentTypeService;
                var releaseContentType = contentTypeService.GetContentType("Release");
                var propertyTypeAlias  = "overrideYouTrackDescription";
                if (releaseContentType.PropertyTypeExists(propertyTypeAlias) == false)
                {
                    var checkbox             = new DataTypeDefinition("Umbraco.TrueFalse");
                    var checkboxPropertyType = new PropertyType(checkbox, propertyTypeAlias)
                    {
                        Name = "Override YouTrack Description?"
                    };
                    releaseContentType.AddPropertyType(checkboxPropertyType, "Content");
                    contentTypeService.Save(releaseContentType);
                }

                propertyTypeAlias = "overrideYouTrackReleaseDate";
                if (releaseContentType.PropertyTypeExists(propertyTypeAlias) == false)
                {
                    var textbox             = new DataTypeDefinition("Umbraco.Textbox");
                    var textboxPropertyType = new PropertyType(textbox, propertyTypeAlias)
                    {
                        Name = "Override YouTrack release date"
                    };
                    releaseContentType.AddPropertyType(textboxPropertyType, "Content");
                    contentTypeService.Save(releaseContentType);
                }

                string[] lines = { "" };
                File.WriteAllLines(path, lines);
            }
            catch (Exception ex)
            {
                LogHelper.Error <MigrationsHandler>(string.Format("Migration: '{0}' failed", migrationName), ex);
            }
        }
Exemple #22
0
        public static void EditHTML()
        {
            string location   = @"C:\Dynamix\score_report.html";
            string lineToFind = "			<!--issues-->";

            List <string> lines = File.ReadLines(location).ToList();
            int           index = lines.IndexOf(lineToFind);

            lines.Insert(index, "<li class=\"issuesTitle\">Security Issues (" + currentVulns + " out of " + TotalVulns() + " resolved)</li>");
            File.WriteAllLines(location, lines);

            string lineToFind2 = "			<!--scored-->";

            int index2 = lines.IndexOf(lineToFind2);

            lines.Insert(index, "<li>" + currentVulns + " out of " + TotalVulns() + " security issues resolved</li>");
            File.WriteAllLines(location, lines);

            currentVulns = 0;
        }
Exemple #23
0
        public void ReplaceTextInFile(string filePath, IStringReplace stringConverter)
        {
            string[] lines      = File.ReadAllLines(filePath);
            int      linesCount = lines.Length;

            string[] newLines = new string[linesCount];
            for (int r = 0; r < linesCount; r++)
            {
                string oldLine = lines[r];
                string newLine = stringConverter.GetNewString(oldLine);
                newLines[r] = newLine;
            }

            if (stringConverter.IsSimulation)
            {
                return;
            }

            File.WriteAllLines(filePath, newLines);
        }
Exemple #24
0
        private void AddNuGetUrlForPackages()
        {
            var migrationName = MethodBase.GetCurrentMethod().Name;

            try
            {
                var path = HostingEnvironment.MapPath(MigrationMarkersPath + migrationName + ".txt");
                if (File.Exists(path))
                {
                    return;
                }

                var contentTypeService = ApplicationContext.Current.Services.ContentTypeService;
                var projectContentType = contentTypeService.GetContentType("Project");
                var propertyTypeAlias  = "nuGetPackageUrl";
                var textbox            = new DataTypeDefinition("Umbraco.Textbox");

                var tabName = "Project";
                if (projectContentType.PropertyGroups.Contains(tabName) == false)
                {
                    projectContentType.AddPropertyGroup(tabName);
                }

                if (projectContentType.PropertyTypeExists(propertyTypeAlias) == false)
                {
                    var textboxNuGetPackage = new PropertyType(textbox, propertyTypeAlias);
                    projectContentType.AddPropertyType(textboxNuGetPackage, tabName);
                }

                contentTypeService.Save(projectContentType);

                string[] lines = { "" };
                File.WriteAllLines(path, lines);
            }
            catch (Exception ex)
            {
                LogHelper.Error <MigrationsHandler>(string.Format("Migration: '{0}' failed", migrationName), ex);
            }
        }
Exemple #25
0
        private void AddPeopleKarmaPage()
        {
            var migrationName = MethodBase.GetCurrentMethod().Name;

            try
            {
                var path = HostingEnvironment.MapPath(MigrationMarkersPath + migrationName + ".txt");
                if (File.Exists(path))
                {
                    return;
                }


                var templatePathRelative   = "~/Views/PeopleKarma.cshtml";
                var templatePath           = HostingEnvironment.MapPath(templatePathRelative);
                var templateContent        = File.ReadAllText(templatePath);
                var releaseCompareTemplate = new Template("PeopleKarma", "PeopleKarma")
                {
                    MasterTemplateAlias = "Master",
                    Content             = templateContent
                };

                var fileService = ApplicationContext.Current.Services.FileService;

                var masterTemplate = fileService.GetTemplate("Master");
                releaseCompareTemplate.SetMasterTemplate(masterTemplate);

                fileService.SaveTemplate(releaseCompareTemplate);


                string[] lines = { "" };
                File.WriteAllLines(path, lines);
            }
            catch (Exception ex)
            {
                LogHelper.Error <MigrationsHandler>(string.Format("Migration: '{0}' failed", migrationName), ex);
            }
        }
Exemple #26
0
        private void RenameUaaStoUCloud()
        {
            var migrationName = MethodBase.GetCurrentMethod().Name;

            try
            {
                var path = HostingEnvironment.MapPath(MigrationMarkersPath + migrationName + ".txt");
                if (File.Exists(path))
                {
                    return;
                }

                var contentService = ApplicationContext.Current.Services.ContentService;
                var rootContent    = contentService.GetRootContent().FirstOrDefault();
                if (rootContent != null)
                {
                    var forumContent = rootContent.Children().FirstOrDefault(x => x.Name == "Forum");
                    if (forumContent != null)
                    {
                        var uaasForumContent = forumContent.Children().FirstOrDefault(x => x.Name.ToLowerInvariant() == "Umbraco as a Service".ToLowerInvariant());
                        if (uaasForumContent != null)
                        {
                            uaasForumContent.Name = "Umbraco Cloud";
                            uaasForumContent.SetValue("forumDescription", "Discussions about Umbraco Cloud.");
                            var status = contentService.SaveAndPublishWithStatus(uaasForumContent);
                            status = contentService.SaveAndPublishWithStatus(uaasForumContent);
                        }
                    }
                }

                string[] lines = { "" };
                File.WriteAllLines(path, lines);
            }
            catch (Exception ex)
            {
                LogHelper.Error <MigrationsHandler>(string.Format("Migration: '{0}' failed", migrationName), ex);
            }
        }
Exemple #27
0
        private void AddMarkAsSolutionReminderSent()
        {
            var migrationName = MethodBase.GetCurrentMethod().Name;

            try
            {
                var path = HostingEnvironment.MapPath(MigrationMarkersPath + migrationName + ".txt");
                if (File.Exists(path))
                {
                    return;
                }

                var db = ApplicationContext.Current.DatabaseContext.Database;
                db.Execute("ALTER TABLE [forumTopics] ADD [markAsSolutionReminderSent] [BIT] NULL DEFAULT ((0))");

                string[] lines = { "" };
                File.WriteAllLines(path, lines);
            }
            catch (Exception ex)
            {
                LogHelper.Error <MigrationsHandler>(string.Format("Migration: '{0}' failed", migrationName), ex);
            }
        }
Exemple #28
0
        private void AddStrictMinimumVersionForPackages()
        {
            var migrationName = MethodBase.GetCurrentMethod().Name;

            try
            {
                var path = HostingEnvironment.MapPath(MigrationMarkersPath + migrationName + ".txt");
                if (File.Exists(path))
                {
                    return;
                }

                var db = ApplicationContext.Current.DatabaseContext.Database;
                db.Execute("ALTER TABLE [wikiFiles] ADD [minimumVersionStrict] VARCHAR(50)");

                string[] lines = { "" };
                File.WriteAllLines(path, lines);
            }
            catch (Exception ex)
            {
                LogHelper.Error <MigrationsHandler>(string.Format("Migration: '{0}' failed", migrationName), ex);
            }
        }
        private void AddBannerPurposeToggleToPackages()
        {
            var migrationName = MethodBase.GetCurrentMethod().Name;

            try
            {
                var path = HostingEnvironment.MapPath(MigrationMarkersPath + migrationName + ".txt");
                if (File.Exists(path))
                {
                    return;
                }

                var contentTypeService = ApplicationContext.Current.Services.ContentTypeService;
                var projectContentType = contentTypeService.GetContentType("banner");
                var propertyTypeAlias  = "supportsCommunityProject";

                if (projectContentType != null && projectContentType.PropertyTypeExists(propertyTypeAlias) == false)
                {
                    var checkbox             = new DataTypeDefinition("Umbraco.TrueFalse");
                    var checkboxPropertyType = new PropertyType(checkbox, propertyTypeAlias)
                    {
                        Name        = "Supports a community project",
                        Description = "Banners are meant to support a community project (contact Ilham/Seb for questions)",
                        Mandatory   = true
                    };
                    projectContentType.AddPropertyType(checkboxPropertyType, "Banner");
                    contentTypeService.Save(projectContentType);
                }

                string[] lines = { "" };
                File.WriteAllLines(path, lines);
            }
            catch (Exception ex)
            {
                LogHelper.Error <MigrationsHandler>(string.Format("Migration: '{0}' failed", migrationName), ex);
            }
        }
Exemple #30
0
        private void CommunityHome()
        {
            var migrationName = MethodBase.GetCurrentMethod().Name;

            try
            {
                var path = HostingEnvironment.MapPath(MigrationMarkersPath + migrationName + ".txt");
                if (File.Exists(path))
                {
                    return;
                }

                var macroService = UmbracoContext.Current.Application.Services.MacroService;
                var macroAlias   = "CommunityHome";
                if (macroService.GetByAlias(macroAlias) == null)
                {
                    // Run migration

                    var macro = new Macro
                    {
                        Name          = "[Community] Home",
                        Alias         = macroAlias,
                        ScriptingFile = "~/Views/MacroPartials/Community/Home.cshtml",
                        UseInEditor   = true
                    };
                    macro.Save();
                }

                string[] lines = { "" };
                File.WriteAllLines(path, lines);
            }
            catch (Exception ex)
            {
                LogHelper.Error <MigrationsHandler>(string.Format("Migration: '{0}' failed", migrationName), ex);
            }
        }