Skip to content

Instantly share code, notes, and snippets.

@guardrex
Last active May 23, 2017 06:12
Show Gist options
  • Save guardrex/a5b960397678b5ddea1a21164d3c8c1b to your computer and use it in GitHub Desktop.
Save guardrex/a5b960397678b5ddea1a21164d3c8c1b to your computer and use it in GitHub Desktop.
Replace MSDN links
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
namespace UpdateMSDNLinks
{
class Program
{
static void Main()
{
//string path = @"C:\Users\XXXXXXX\Documents\GitHub\docs-1\docs\framework\migration-guide\net-framework-4-migration-issues.md";
string path = @"net-framework-4-migration-issues.md";
var inputLines = File.ReadAllLines(path);
var outputLines = new List<string>();
var dict = new Dictionary<string, string>();
var replacements = 0;
foreach (var line in inputLines)
{
if (line.Contains("msdn.microsoft.com/library"))
{
var r = new Regex(@"\[(.*?)\]\(https://msdn.microsoft.com/library/(.*?)\((.*?)\).aspx\)", RegexOptions.IgnoreCase);
var outputLine = line;
foreach (var match in r.Matches(line))
{
var linkText = match.ToString();
int startPos = linkText.IndexOf("library/") + 8;
int len = linkText.LastIndexOf("(") - startPos;
var parsedLinkText = linkText.Substring(startPos, len);
if (dict.ContainsKey(parsedLinkText))
{
outputLine = outputLine.Replace(linkText, dict[parsedLinkText]);
replacements++;
Console.WriteLine($"Dict: {linkText}");
}
else
{
var xrefLink = linkText;
WebRequest request = WebRequest.Create($"https://docs.microsoft.com/dotnet/api/{parsedLinkText}");
WebResponse response = null;
try
{
response = request.GetResponse();
string content = string.Empty;
string apiName = string.Empty;
using (var reader = new StreamReader(response.GetResponseStream()))
{
content = reader.ReadToEnd();
}
var web = new HtmlAgilityPack.HtmlDocument();
web.LoadHtml(content);
apiName = web.DocumentNode.SelectNodes("//meta[@name='ms.assetid']")[0].GetAttributeValue("content", String.Empty);
xrefLink = $"<xref:{apiName}>";
dict.Add(parsedLinkText, xrefLink);
outputLine = outputLine.Replace(linkText, xrefLink);
replacements++;
Console.WriteLine($"Web: {linkText} -> {xrefLink}");
}
catch (Exception ex)
{
Console.WriteLine($"{linkText} ({parsedLinkText}) -> {ex.ToString()}");
}
}
}
outputLines.Add(outputLine);
}
else
{
outputLines.Add(line);
}
}
File.WriteAllLines(path, outputLines);
Console.WriteLine($"Total Replacements: {replacements}");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment