예제 #1
0
        private static void infoParam(List <string> lines, CfgActions action)
        {
            FindParamResult fr = findParam(lines, action.Key);

            if (fr.IsError)
            {
                action.IsResult  = false;
                action.ResultMsg = fr.Comment;
            }
            else
            {
                action.IsResult  = true;
                action.ResultMsg = string.Format("'{0}', комментарий: {1}", fr.Value, fr.Comment);
            }
        }
예제 #2
0
        private static void deleteComment(List <string> lines, FindParamResult fr)
        {
            // удалить пустые строки между комментарием и параметром
            int i1 = fr.LineIndex - 1;

            while (i1 > fr.CommentIndex)
            {
                lines.RemoveAt(i1); i1--;
            }

            // удалить комментарий
            lines.RemoveAt(fr.CommentIndex);

            // удалить пустые строки перед комментарием
            int idx = fr.CommentIndex - 1;

            while ((idx > 0) && (idx < lines.Count) && (lines[idx].TrimStart().Length == 0))
            {
                lines.RemoveAt(idx); idx--;
            }
        }
예제 #3
0
        private static void delParam(List <string> lines, CfgActions action)
        {
            FindParamResult fr = findParam(lines, action.Key);

            if ((fr.IsError) || (fr.Key == null) || (fr.LineIndex == 0))
            {
                action.IsResult  = false;
                action.ResultMsg = fr.Comment;
                return;
            }

            lines.RemoveAt(fr.LineIndex);

            // удалить комментарий
            if (fr.CommentIndex != 0)
            {
                deleteComment(lines, fr);
            }
            action.IsResult  = true;
            action.ResultMsg = "параметр удален успешно";
        }
예제 #4
0
        private static FindParamResult findParam(List <string> lines, string paramName)
        {
            FindParamResult retVal = new FindParamResult();
            string          line   = lines.FirstOrDefault(l => l.Contains("\"" + paramName + "\""));

            if (line == null)
            {
                retVal.IsError = true;
                retVal.Comment = "ошибка поиска: ключ НЕ найден";
                return(retVal);
            }

            retVal.Line      = line;
            retVal.LineIndex = lines.IndexOf(line);

            // атрибут key
            int i1 = line.IndexOf('\"', 0);

            if (i1 <= 0)
            {
                retVal.IsError = true;
                retVal.Comment = "ошибка структуры xml-элемента add: нет ОТКРЫВАЮЩЕЙ кавычки для атрибута KEY";
                return(retVal);
            }
            int i2 = line.IndexOf('\"', i1 + 1);

            if (i2 <= 0)
            {
                retVal.IsError = true;
                retVal.Comment = "ошибка структуры xml-элемента add: нет ЗАКРЫВАЮЩЕЙ кавычки для атрибута KEY";
                return(retVal);
            }
            retVal.Key = line.Substring(i1 + 1, i2 - i1 - 1);

            // атрибут value
            i1 = line.IndexOf('\"', i2 + 1);
            if (i1 <= 0)
            {
                retVal.IsError = true;
                retVal.Comment = "ошибка структуры xml-элемента add: нет ОТКРЫВАЮЩЕЙ кавычки для атрибута VALUE";
                return(retVal);
            }
            i2 = line.IndexOf('\"', i1 + 1);
            if (i2 <= 0)
            {
                retVal.IsError = true;
                retVal.Comment = "ошибка структуры xml-элемента add: нет ЗАКРЫВАЮЩЕЙ кавычки для атрибута VALUE";
                return(retVal);
            }
            retVal.Value = line.Substring(i1 + 1, i2 - i1 - 1);

            // comment
            // признак комментария для строки: перед этой строкой есть xml-комментарий, и после - есть xml-комментарий.
            // если после строки нет комментария, то это
            if ((retVal.LineIndex == 0) || (retVal.LineIndex == lines.Count))
            {
                retVal.IsError = true;
                retVal.Comment = "ошибка структуры config-файла: нет корневого элемента";
                return(retVal);
            }

            int    iLinePre = retVal.LineIndex - 1;
            string linePre  = lines.ElementAt(iLinePre).TrimStart();

            while (((linePre == null) || (linePre.Length == 0)) && (iLinePre > 0))
            {
                iLinePre--;
                linePre = lines.ElementAt(iLinePre).TrimStart();
            }
            string comment = ((linePre.StartsWith("<!--")) ? linePre : null);

            // проверка комментария на принадлежность одному параметру или для группы параметров
            if (comment != null)
            {
                int    iLinePost = retVal.LineIndex + 1;
                string linePost  = lines.ElementAt(iLinePost).TrimStart();

                // пропустить последующие пустые строки
                while (((linePost == null) || (linePost.Length == 0)) && (iLinePost < lines.Count))
                {
                    iLinePost++;
                    linePost = lines.ElementAt(iLinePost).TrimStart();
                }

                if ((string.IsNullOrEmpty(linePost) == false) &&
                    (linePost.StartsWith("<!--") || linePost.StartsWith("</")))
                {
                    if (comment.StartsWith("<!--"))
                    {
                        comment = comment.Substring(4).TrimStart();
                    }
                    if (comment.EndsWith("-->"))
                    {
                        comment = comment.Substring(0, comment.Length - 3).TrimEnd();
                    }
                    retVal.Comment      = comment;
                    retVal.CommentIndex = iLinePre;
                }
            }

            return(retVal);
        }
예제 #5
0
        private static void addParam(List <string> lines, CfgActions action)
        {
            if (string.IsNullOrEmpty(action.Key))
            {
                action.IsResult  = false;
                action.ResultMsg = "ошибка добавления параметра: не задан атрибут KEY";
                return;
            }
            if ((action.Options == null) || (action.Options.Length == 0))
            {
                action.IsResult  = false;
                action.ResultMsg = "ошибка добавления параметра: не задано значение атрибута VALUE";
                return;
            }
            string newValue   = action.Options[0];
            string newComment = (action.Options.Length > 1) ? "<!-- " + action.Options[1] + " -->" : null;

            bool            isAdd = false;
            FindParamResult fr    = findParam(lines, action.Key);

            // ключ найден - обновить значение
            if (fr.Key != null)
            {
                string lineUpd = fr.Line;
                int    i1      = lineUpd.IndexOf("\"", lineUpd.IndexOf("value") + 5);
                int    i2      = lineUpd.IndexOf("\"", i1 + 1);
                if ((i1 != -1) && (i2 != -1))
                {
                    string preValue = lineUpd.Substring(i1 + 1, i2 - i1 - 1);
                    if (preValue == newValue)
                    {
                        action.IsResult  = false;
                        action.ResultMsg = "ошибка добавления параметра: параметр с таким значением уже существует, добавление не требуется";
                    }
                    else
                    {
                        lineUpd             = lineUpd.Substring(0, i1 + 1) + newValue + lineUpd.Substring(i2);
                        lines[fr.LineIndex] = lineUpd;
                        action.IsResult     = true;
                        action.ResultMsg    = "параметр существует, атрибут VALUE обновлен новым значением";
                    }
                }
                else
                {
                    action.IsResult  = false;
                    action.ResultMsg = "ошибка получения значения атрибута VALUE";
                    isAdd            = true;
                }
            }
            else
            {
                isAdd = true;
            }

            // ключ не найден или ошибка - добавить
            if (isAdd)
            {
                string newLine    = string.Format("<add key=\"{0}\" value=\"{1}\" />", action.Key, newValue);
                string prefixLine = getLinePrefix(lines);
                if (prefixLine != null)
                {
                    newComment = prefixLine + newComment;
                    newLine    = prefixLine + newLine;
                }

                // вставить перед последней строкой
                if (lines.Last().TrimStart().StartsWith("</"))
                {
                    lines.Insert(lines.Count - 1, "");
                    if (newComment != null)
                    {
                        lines.Insert(lines.Count - 1, newComment);
                    }
                    lines.Insert(lines.Count - 1, newLine);
                }
                // добавить к концу
                else
                {
                    lines.Add("");
                    if (newComment != null)
                    {
                        lines.Add(newComment);
                    }
                    lines.Add(newLine);
                }
                action.IsResult  = true;
                action.ResultMsg = "в файл добавлена строка " + newLine + ((newComment == null) ? "" : ", с комментарием " + newComment);
            }
        }
예제 #6
0
        private static void updParam(List <string> lines, CfgActions action)
        {
            action.IsResult = false;

            FindParamResult fr = findParam(lines, action.Key);

            if ((fr.IsError) || (fr.Key == null) || (fr.LineIndex == 0))
            {
                action.ResultMsg = fr.Comment;
                return;
            }
            if ((action.Options == null) || (action.Options.Length == 0))
            {
                action.ResultMsg = "не указан обязательный режим обновления: -k[ey] | -v[alue] | -c[omment]";
                return;
            }

            string mode     = action.Options[0];
            string newValue = ((action.Options.Length > 1) ? action.Options[1] : "");

            // обновить имя параметра
            if ((mode == "-k") || (mode == "-key"))
            {
                if (newValue.Length == 0)
                {
                    action.ResultMsg = "не указано обязательное новое ИМЯ параметра";
                    return;
                }
                int i1 = fr.Line.IndexOf("key"), i2 = -1;
                if (i1 > -1)
                {
                    i1 = fr.Line.IndexOf("\"", i1 + 3);
                }
                if (i1 > -1)
                {
                    i2 = fr.Line.IndexOf("\"", i1 + 1);
                }
                if ((i1 > -1) && (i2 > -1))
                {
                    string newLine = fr.Line.Substring(0, i1 + 1) + newValue + fr.Line.Substring(i2);
                    lines[fr.LineIndex] = newLine;
                    action.ResultMsg    = "ИМЯ параметра изменено на '" + newValue + "'";
                    action.IsResult     = true;
                }
                else
                {
                    action.ResultMsg = "ошибка поиска значения атрибута KEY в исходной строке";
                }
            }
            // обновить значение параметра
            else if ((mode == "-v") || (mode == "-value"))
            {
                if (newValue.Length == 0)
                {
                    action.ResultMsg = "не указано обязательное новое ЗНАЧЕНИЕ параметра";
                    return;
                }
                int i1 = fr.Line.IndexOf("value"), i2 = -1;
                if (i1 > -1)
                {
                    i1 = fr.Line.IndexOf("\"", i1 + 3);
                }
                if (i1 > -1)
                {
                    i2 = fr.Line.IndexOf("\"", i1 + 1);
                }
                if ((i1 > -1) && (i2 > -1))
                {
                    string newLine = fr.Line.Substring(0, i1 + 1) + newValue + fr.Line.Substring(i2);
                    lines[fr.LineIndex] = newLine;
                    action.ResultMsg    = "ЗНАЧЕНИЕ параметра изменено на '" + newValue + "'";
                    action.IsResult     = true;
                }
                else
                {
                    action.ResultMsg = "ошибка поиска значения атрибута VALUE в исходной строке";
                }
            }
            // обновить комментарий
            else if ((mode == "-c") || (mode == "-comment"))
            {
                // есть комментарий в исходном файле
                if (fr.CommentIndex > 0)
                {
                    // удалить комментарий
                    if (string.IsNullOrEmpty(newValue))
                    {
                        deleteComment(lines, fr);
                        action.ResultMsg = "КОММЕНТАРИЙ удален";
                        action.IsResult  = true;
                    }
                    // обновить комментарий
                    else
                    {
                        string prefixLine = getLinePrefix(lines);
                        string newLine    = (prefixLine ?? "") + "<!-- " + newValue + " -->";
                        lines[fr.CommentIndex] = newLine;
                        action.ResultMsg       = "КОММЕНТАРИЙ изменен";
                        action.IsResult        = true;
                    }
                }
                // нет комментария и не задан - ошибка
                else if (string.IsNullOrEmpty(newValue))
                {
                    action.ResultMsg = "КОММЕНТАРИЙ к параметру НЕ найден и НЕ задан";
                }
                // нет комментария и задан - добавить
                else
                {
                    string prefixLine = getLinePrefix(lines);
                    string newLine    = (prefixLine ?? "") + "<!-- " + newValue + " -->";
                    lines.Insert(fr.LineIndex, newLine);
                    lines.Insert(fr.LineIndex, "");
                    action.ResultMsg = "КОММЕНТАРИЙ добавлен";
                    action.IsResult  = true;
                }
            }

            else
            {
                action.ResultMsg = "ошибочный режим обновления: " + mode + " (должен быть -k[ey], -v[alue] или -c[omment])";
            }
        }