Introducing TechHub.sk: Latest Features and Approach
In this blog post, we'll explore how to create a timer-triggered Azure Function using .NET 8 to automate updates to a list of blog posts hosted on a GitHub repository. This function will periodically check for new blog posts, update an HTML file with links to these posts, and handle any necessary file creation or updates on GitHub.
Overview of the Azure Function
The function is designed to run every two hours, checking a specified GitHub repository for new HTML blog files. It then generates a list of these blogs, formatted with their titles and publication dates, and updates an HTML file named list.html in the repository.
Key Components
Let's break down the key components and interesting parts of this Azure Function.
Timer Trigger Configuration
The function is triggered by a timer set to run every two hours. This is configured using the [TimerTrigger("0 */2 * * *")] attribute on the Run method:
[Function("BlogsUpdateTrigger")]
public async Task Run([TimerTrigger("0 0 */2 * * *")] TimerInfo myTimer)
{
// Function logic
}
This ensures that the function is invoked at the specified interval, allowing for regular updates to the blog list.
GitHub Client Setup
We use the Octokit library to interact with the GitHub API. The client is authenticated using a personal access token:
var client = new GitHubClient(new ProductHeaderValue("BlogUpdater"));
var tokenAuth = new Credentials("your_github_token");
client.Credentials = tokenAuth;
This setup allows the function to perform authenticated requests to the GitHub repository, enabling file read and write operations.
Fetching Blog Files
The function retrieves all files from the blogs directory in the specified repository:
var contents = await client.Repository.Content.GetAllContents("owner", "repo", "path");
It then processes each file to generate an HTML list of blog links. Files are filtered and formatted based on their naming convention to ensure proper date and title extraction.
Generating the HTML List
The HTML content is dynamically generated using a StringBuilder:
var htmlBuilder = new StringBuilder();
htmlBuilder.Append("<ul>");
foreach (var file in contents.OrderByDescending(f => f.Name))
{
if (file.Name.EndsWith(".html"))
{
var datePart = file.Name.Substring(0, 8);
var titlePart = file.Name.Substring(9).Replace("-", " ").Replace(".html", "");
var formattedDate = date.ToString("yyyy-MM-dd");
htmlBuilder.AppendFormat("<li><a href='/blogs/{0}'>{1} - {2}</a></li>", file.Name, formattedDate, titlePart);
}
}
htmlBuilder.Append("</ul>");
This ensures that the blog list is always up-to-date with the latest posts.
Updating the Repository
The function checks if the list.html file already exists and whether its content needs updating:
if (existingFile == null || !existingFile.Any())
{
var createChangeSet = new CreateFileRequest("Creating list.html", newContent, "main");
await client.Repository.Content.CreateFile("owner", "repo", "list.html", createChangeSet);
_logger.LogInformation("Created list.html");
}
else
{
var existingContent = existingFile.First().Content;
if (existingContent != newContent)
{
var updateChangeSet = new UpdateFileRequest("Updating list.html", newContent, existingFile.First().Sha, "main");
await client.Repository.Content.UpdateFile("owner", "repo", "list.html", updateChangeSet);
_logger.LogInformation("Updated list.html");
}
else
{
_logger.LogInformation("No changes detected in list.html. Skipping update.");
}
}
This logic ensures that the HTML list is created or updated only when necessary, avoiding redundant operations.
Conclusion
By leveraging Azure Functions and .NET 8, we can automate the process of keeping a blog listing up-to-date. This approach ensures that our blog readers always have access to the latest content without manual intervention. The use of the Octokit library simplifies interactions with the GitHub API, making it easy to manage repository content programmatically.
For more details on creating Azure Functions, check out the official documentation.