Code Updater

Web page by Kevin Harris of Homer IL

Please contact Kevin Harris of Homer IL concerning this web site

Code Updater

C# program to scan all the code files in a directory and replace string values as defined in an input file. An output file lists the before and after text of each line changed with line numbers and file names.


This program replaces string values within all the code files inside a directory. The program leaves the original code files untouched and creates a new version of the file with a .new extension. The new file contains the original code file with all the modifications. An input file is used to define all old and new values for the string replacements. An output file lists the before and after text of each line changed with line numbers and file names.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace UpdateCode
{
    class UpdateCode
    {
        static void Main(string[] args)
        {
            string[] values;
            string oldValue;
            string newValue;
            int fileCount = 0;
            int inputLineCount = 0;
            int codeLineCount = 0;
            bool validInputFile = true;
            bool codeLineChanged = false;
            var folderPath = @"C:\UpdateCode\";

            Console.WriteLine("Press Any Key to Start VB Code Updates in C:\\UpdateCode\\");
            System.Console.ReadKey();

            Console.WriteLine("UpdateCode Started ...\n");
            if (!Directory.Exists(folderPath))
            {
                Console.WriteLine("Failed: Required Directory Not Found: {0}\n", folderPath);
                Environment.Exit(0);
            }

            Console.WriteLine("Validating 'UpdateCode.Input' Input File");

            if (!File.Exists(folderPath + "UpdateCode.Input"))
            {
                Console.WriteLine("Failed: Required File Not Found: {0}\n", folderPath + "UpdateCode.Input");
                Environment.Exit(0);
            }

            string[] inputLines = System.IO.File.ReadAllLines(folderPath + "UpdateCode.Input");

            // Validate Input File Has Two Comma Separated Values on Each Input Line
            // Expected Input File Format:  oldValue, newValue                        
            foreach (string inputLine in inputLines)
            {
                inputLineCount++;
                values = inputLine.Split(',');

                if (values.Count() != 2)
                {
                    Console.WriteLine("Bad input on line: {0}", inputLineCount);
                    Console.WriteLine("Line {0}: {1}\n", inputLineCount, inputLine);
                    validInputFile = false;
                }
            }

            // Process Input File.  Input File was Validated to Have Two Values on Each Input Line.
            if (validInputFile)
            {
                Console.WriteLine("Validating 'UpdateCode.Input' Input File -- Passed Validation");
                fileCount = 0;

                using (System.IO.StreamWriter logFile = new System.IO.StreamWriter(folderPath + "UpdateCode.Log"))
                {
                    foreach (string file in Directory.EnumerateFiles(folderPath, "*.vb"))
                    {
                        string codeLine;
                        string originalCodeLine;

                        fileCount++;
                        codeLineCount = 0;
                        Console.WriteLine("\nProcessing file {0}: {1}", fileCount, Path.GetFileName(file));
                        logFile.WriteLine("\nProcessing file {0}: {1}", fileCount, Path.GetFileName(file));

                        using (System.IO.StreamReader codeFile = new System.IO.StreamReader(folderPath + Path.GetFileName(file)))
                        {
                            using (System.IO.StreamWriter newFile = new System.IO.StreamWriter(folderPath + Path.GetFileNameWithoutExtension(file) + ".new"))
                            {
                                while ((codeLine = codeFile.ReadLine()) != null)
                                {
                                    codeLineChanged = false;
                                    originalCodeLine = null;
                                    codeLineCount++;
                                    foreach (string inputLine in inputLines)
                                    {
                                        values = inputLine.Split(',');
                                        oldValue = values[0].Trim();
                                        newValue = values[1].Trim();
                                        if (codeLine.Contains(oldValue))
                                        {
                                            if (!codeLineChanged)
                                            {
                                                codeLineChanged = true;
                                                originalCodeLine = codeLine;
                                            }
                                            codeLine = codeLine.Replace(oldValue, newValue);
                                        }
                                    }
                                    newFile.WriteLine(codeLine);
                                    if (codeLineChanged)
                                    {
                                        logFile.WriteLine("Replaced({0}): {1}", codeLineCount, originalCodeLine);
                                        logFile.WriteLine("with         : {0}", codeLine);
                                        logFile.WriteLine();
                                    }
                                }
                            }
                        }
                    }
                    logFile.WriteLine("\nUpdateCode Finished Successfully - Number of Files Processed: {0}", fileCount);
                }
            }

            // Write finished line to console
            if (validInputFile)
            {
                Console.WriteLine("\nUpdateCode Finished Successfully - Number of Files Processed: {0}", fileCount);
            }
            else
            {
                Console.WriteLine("\nFailed: A Validation Error Occured (No Processing Completed)");
            }

            // Keep the console window open in debug mode.
            Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();
        }
    }
}

UpdateCode.cs

The input file contains two comma delimited values on each line. The first value is the search value to be replaced in all the code files. The second value is used to replace the first value in all occurrences in all code files within the directory.

1
oldValue,newValue
1
oldValue1,newValue1
1
oldValue2,newValue2

UpdateCode.Input

An output file lists the before and after text of each line changed with line numbers and file names.

Processing file 1: Program1.vb

Processing file 2: Program2.aspx.vb
Replaced(205):         Dim oldValue As MySqlDataAdapter = New MySqlDataAdapter(strSQL, strConn)
with         :         Dim newValue As MySqlDataAdapter = New MySqlDataAdapter(strSQL, strConn)

Replaced(206):         oldValue.Fill(ds, "dataset1")
with         :         newValue.Fill(ds, "dataset1")

Replaced(283):         curOrderBy = " Order By table.oldValue1"
with         :         curOrderBy = " Order By table.newValue1"

Replaced(296):            & " AND table.oldValue1 = table2.field" _
with         :            & " AND table.newValue1 = table2.field" _

Replaced(300):            & " AND table1.oldValue2 = table.oldValue1" _
with         :            & " AND table1.newValue2 = table.newValue1" _ 

UpdateCode.Log



Error | ASP.NET Developer

Error

Error message

  • Warning: Cannot modify header information - headers already sent by (output started at /srv/disk9/1218369/www/kcshadow.net/aspnet/includes/common.inc:2748) in drupal_send_headers() (line 1232 of /srv/disk9/1218369/www/kcshadow.net/aspnet/includes/bootstrap.inc).
  • PDOException: SQLSTATE[42000]: Syntax error or access violation: 1142 INSERT command denied to user '1218369_b2cf'@'185.176.40.58' for table 'watchdog': INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9); Array ( [:db_insert_placeholder_0] => 0 [:db_insert_placeholder_1] => cron [:db_insert_placeholder_2] => Attempting to re-run cron while it is already running. [:db_insert_placeholder_3] => a:0:{} [:db_insert_placeholder_4] => 4 [:db_insert_placeholder_5] => [:db_insert_placeholder_6] => http://www.kcshadow.net/aspnet/?q=codeupdater [:db_insert_placeholder_7] => [:db_insert_placeholder_8] => 54.80.87.62 [:db_insert_placeholder_9] => 1534852096 ) in dblog_watchdog() (line 160 of /srv/disk9/1218369/www/kcshadow.net/aspnet/modules/dblog/dblog.module).
The website encountered an unexpected error. Please try again later.