Wikipedia:Projekt DotNetWikiBot Framework/Lsjbot/RemoveTemplateParameter

Från Wikipedia

RemoveTemplateParameter[redigera | redigera wikitext]

Kod att läggas till i DotNetWikiBot.cs för att enkelt kunna ta bort parametrar ur en mall. Funkar i princip likadant som Page.SetTemplateParameter, och är modifierad från den koden.


       /// <summary>
       /// LSJ Addition 2012-07-17!  
       /// </summary>
       /// Remove parameter from template.
       /// <param name="templateTitle">Title of template.</param>
       /// <param name="templateParameter">Title of template's parameter to be removed.</param>
       /// <param name="firstTemplateOnly">When set to true, only first found template instance
       /// is modified. When set to false, all found template instances are modified.</param>
       /// <returns>Returns the number of modified values.</returns>
       /// <returns></returns>
       public int RemoveTemplateParameter(string templateTitle, string templateParameter,
           bool firstTemplateOnly)
       {
           if (string.IsNullOrEmpty(templateTitle))
               throw new ArgumentNullException("templateTitle");
           if (string.IsNullOrEmpty(templateParameter))
               throw new ArgumentNullException("templateParameter");
           if (string.IsNullOrEmpty(text))
               throw new ArgumentNullException("text");
           int i = 0;
           Dictionary<string, string> parameters;
           templateTitle = templateTitle.Trim();
           templateParameter = templateParameter.Trim();
           Regex templateTitleRegex = new Regex("^\\s*(" +
               Bot.Capitalize(Regex.Escape(templateTitle)) + "|" +
               Bot.Uncapitalize(Regex.Escape(templateTitle)) +
               ")\\s*\\|");
           foreach (string template in GetTemplatesWithParams())
           {
               if (templateTitleRegex.IsMatch(template))
               {
                   parameters = site.ParseTemplate(template);
                   parameters.Remove(templateParameter);
                   Regex oldTemplate = new Regex(Regex.Escape(template));
                   string newTemplate = site.FormatTemplate(templateTitle, parameters, false, false, 0);
                   newTemplate = newTemplate.Substring(2, newTemplate.Length - 4);
                   text = oldTemplate.Replace(text, newTemplate, 1);
                   i++;
                   if (firstTemplateOnly == true)
                       break;
               }
           }
           return i;
       }