Show Recent Blog Posts In GitHub ReadMe Using An Azure Function

Introduction

 
 Show Recent Blog Posts In GitHub ReadMe Using Azure Function
 
 
GitHub recently introduced an option to customize our profile by giving a separate magical repository. This repository name should be the same as your username, for example, here. This is how you can find this secret repository.
 
Show Recent Blog Posts In GitHub ReadMe Using Azure Function 
 
GitHub secret repository
 
This opens endless opportunities for what you can do to your GitHub home page. For example, I am showing the image of the titles of my recent 5 blog posts on my home page automatically. I did it using the Azure Function which will return the image, and all I had to do in this repository was to use it. Overall it was fun.
 
Show Recent Blog Posts In GitHub ReadMe Using Azure Function 
 
Custom GitHub home page
 
Here in this post, we will see how we can develop an Azure Function solution that returns the above-mentioned image.
 

Develop an Azure function

 
The first thing that you need to do is to create a new Azure Function. Go to your Azure portal, and search for Azure Function. The creation process is the same as we would create any other Azure resource.
 
Once you create the Azure function, you are good to go and develop an Azure function application in Visual Studio. Here, I am using Visual Studio 2019.
 
Show Recent Blog Posts In GitHub ReadMe Using Azure Function
 

Create Azure function using Visual Studio

 
We are going to create an HttpTrigger Azure function, so make sure you select that option on the next screen. If you need a basic introduction about the HttpTrigger Azure function. I named my function as GetLatestPosts, and feel free to give any name you wish. This Azure function has the preceding jobs to do.
  1. Get the latest posts details from the feed of my blog
  2. Create an image with the feed data
  3. Send back the image as a stream
Get the latest posts details from the feed
 
You can usually get the feed data by going to {yoursitelink}/feed. For example, I can get my feed data by going to https://sibeeshpassion.com/feed/. So in our function, we will get this data using an XmlReader and Deserialize it using SyndicationFeed. Please be noted that the Syndication namespace is part of the System.ServiceModel and you should install the Nuget package System.ServiceModel.Syndication. Below is the function used to retrieve the latest 5 blog posts' details.
  1. public static IEnumerable < SyndicationItem > GetLatestFeeds() {  
  2.     var reader = XmlReader.Create(Configuration.BlogLink);  
  3.     var feed = SyndicationFeed.Load(reader);  
  4.     reader.Close();  
  5.     return feed.Items.Take(5);  
  6. }  

Create an image with titles

 
Now we need a function to generate an image and write the blog posts title to that image dynamically. To do this, we are using the Nuget package called SixLabors.ImageSharp. Feel free to use any packages you like, the only thing that matters is that we need an image with the blog posts titles. The SixLabors.ImageSharp is indeed an amazing library, I can recommend you to give it a try. This is how your Nuget package installed window should look now:
 
Show Recent Blog Posts In GitHub ReadMe Using Azure Function 
 
Required Nuget packages
 
Now we can write the function as shown below.
  1. private static string WriteOnImage(IEnumerable < SyndicationItem > feedItems) {  
  2.     var titles = string.Join(", ", feedItems.Select(s => s.Title.Text).ToList());  
  3.     using  
  4.     var img = new Image < Rgba32 > (Configuration.ImageWidth, Configuration.ImageHeight);  
  5.     var font = System Fonts.CreateFont(Configuration.Font, Configuration.FontSize);  
  6.     img.Mutate(ctx => ctx.ApplyScalingWaterMark(font, titles, Color.Black, 5, true));  
  7.     return img.ToBase64String(PngFormat.Instance);  
  8. }  
As you can see that there is a Configuration class, from where we take all the configurations. Let’ write that now. You can also use Environment variables here, I may update my repository in the coming days.
  1. namespace GitHub Funcs {  
  2.     public static class Configuration {  
  3.         public static string BlogLink {  
  4.             get;  
  5.             set;  
  6.         } = "https://sibeeshpassion.com/feed";  
  7.         public static int ImageWidth {  
  8.             get;  
  9.             set;  
  10.         } = 850;  
  11.         public static int ImageHeight {  
  12.             get;  
  13.             set;  
  14.         } = 100;  
  15.         public static string ContentType {  
  16.             get;  
  17.             set;  
  18.         } = "image/png";  
  19.         public static string Font {  
  20.             get;  
  21.             set;  
  22.         } = "Arial";  
  23.         public static int FontSize {  
  24.             get;  
  25.             set;  
  26.         } = 5;  
  27.     }  
  28. }  
The SixLabors.ImageSharp has an inbuilt extension function called ToBase64String, which will return the image as base64 string. Did you notice that we are using another extension method here, “ApplyScalingWaterMark”? Let’s create a class for our Extension methods so that it will be handy in the future.
  1. using SixLabors.Fonts;  
  2. using SixLabors.ImageSharp;  
  3. using SixLabors.ImageSharp.Drawing.Processing;  
  4. using SixLabors.ImageSharp.Processing;  
  5. using System;  
  6. namespace GitHub Funcs.ExtensionMethods {  
  7.     public static class ImageSharpExtensions {  
  8.         public static IImageProcessingContextApplyScalingWaterMark(thisIImageProcessingContextprocessingContext, Font font, string text, Color color, float padding, bool wordwrap) {  
  9.             if (wordwrap) {  
  10.                 return processing Context.ApplyScalingWaterMarkWordWrap(font, text, color, padding);  
  11.             } else {  
  12.                 return processing Context.ApplyScalingWaterMarkSimple(font, text, color, padding);  
  13.             }  
  14.         }  
  15.         private static IImage Processing Context Apply Scaling WaterMarkSimple(thisIImageProcessingContextprocessingContext, Font font, string text, Color color, float padding) {  
  16.             Size imgSize = processingContext.GetCurrentSize();  
  17.             float target Width = img Size.Width - (padding * 2);  
  18.             float target Height = img Size.Height - (padding * 2);  
  19.             // measure the text size  
  20.             Font Rectangle size = Text Measurer.Measure(text, newRendererOptions(font));  
  21.             //find out how much we need to scale the text to fill the space (up or down)  
  22.             float scaling Factor = Math.Min(imgSize.Width / size.Width, imgSize.Height / size.Height);  
  23.             //create a new font  
  24.             Fonts caled Font = new Font(font, scalingFactor * font.Size);  
  25.             var center = new PointF(imgSize.Width / 2, imgSize.Height / 2);  
  26.             var textGraphicOptions = new TextGraphicsOptions() {  
  27.                 Text Options = {  
  28.                     Horizontal Alignment = Horizontal Alignment.Center,  
  29.                     Vertical Alignment = Vertical Alignment.Center  
  30.                 }  
  31.             };  
  32.             return processing Context.DrawText(textGraphicOptions, text, scaledFont, color, center);  
  33.         }  
  34.         private static IImageProcessing ContextApply ScalingWaterMark WordWrap(thisIImageProcessingContextprocessingContext, Font font, string text, Color color, float padding) {  
  35.             Size imgSize = processing Context.GetCurrentSize();  
  36.             floattar get Width = img Size.Width - (padding * 2);  
  37.             floattar get Height = imgSize.Height - (padding * 2);  
  38.             float target Min Height = imgSize.Height - (padding * 3); // must be with in a margin width of the target height  
  39.             // now we are working i 2 dimensions at once and can't just scale because it will cause the text to  
  40.             // reflow we need to just try multiple times  
  41.             var scaled Font = font;  
  42.             Font Rectangles = new FontRectangle(0, 0, float.MaxValue, float.MaxValue);  
  43.             float scale Factor = (scaledFont.Size / 2); // every time we change direction we half this size  
  44.             int trap Count = (int) scaledFont.Size * 2;  
  45.             if (trap Count < 10) {  
  46.                 trap Count = 10;  
  47.             }  
  48.             bool is TooSmall = false;  
  49.             while ((s.Height > targetHeight || s.Height < targetMinHeight) && trapCount > 0) {  
  50.                 if (s.Height > target Height) {  
  51.                     if (isTooSmall) {  
  52.                         scale Factor = scale Factor / 2;  
  53.                     }  
  54.                     scaled Font = new Font(scaledFont, scaledFont.Size - scaleFactor);  
  55.                     isTooSmall = false;  
  56.                 }  
  57.                 if (s.Height < targetMinHeight) {  
  58.                     if (!isTooSmall) {  
  59.                         scale Factor = scale Factor / 2;  
  60.                     }  
  61.                     scaled Font = new Font(scaledFont, scaledFont.Size + scaleFactor);  
  62.                     isTooSmall = true;  
  63.                 }  
  64.                 trapCount--;  
  65.                 s = TextMeasurer.Measure(text, newRendererOptions(scaledFont) {  
  66.                     Wrapping Width = target Width  
  67.                 });  
  68.             }  
  69.             var center = new PointF(padding, imgSize.Height / 2);  
  70.             var textGraphicOptions = new TextGraphicsOptions() {  
  71.                 Text Options = {  
  72.                     Horizontal Alignment = Horizontal Alignment.Left,  
  73.                     Vertical Alignment = Vertical Alignment.Center,  
  74.                     WrapText Width = target Width  
  75.                 }  
  76.             };  
  77.             return processing Context.DrawText(textGraphicOptions, text, scaledFont, color, center);  
  78.         }  
  79.     }  
  80. }  

Azure function to return a stream

 
As all the supporting methods are ready, let's write our main function. The ultimate job of this function is to convert the base64 string to a stream and return the stream. It's as simple as that.
  1. [FunctionName("GetLatestPosts")]  
  2. public static FileStreamResultRun([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequestrequest, ILoggerlog) {  
  3.     try {  
  4.         varbase String = WriteOnImage(GetLatestFeeds());  
  5.         // Had to do this, as it was throwing error "The input is not a valid Base-64 string as it contains a non-base 64 character"  
  6.         string convert = baseString.Replace("data:image/png;base64,", String.Empty);  
  7.         var bytes = Convert.FromBase64String(convert);  
  8.         var result = new FileStreamResult(newMemoryStream(bytes), Configuration.ContentType);  
  9.         log.LogInformation("Returning stream now!");  
  10.         request.HttpContext.Response.Headers.Add("Cache-Control""s-maxage=1, stale-while-revalidate");  
  11.         return result;;  
  12.     } catch (System.Exceptionex) {  
  13.         log.LogError($ "Something went wrong: {ex}");  
  14.         throwex;  
  15.     }  
  16. }  
Once your Azure function is ready, please remember to publish the same to Azure. To publish your Azure Function app, just right click on your project and click Publish and then set up your publish target by choosing the existing Azure Function App, remember we have created one earlier?
 
Develop secret GitHub readme repository
 
Here, I am assuming that you already created your secret repository. And if yes, you can update the “readme” content as follows. Please remember that this is just a sample, you can update it as you wish.
 
Hi there 👋, feel free to check out my blog and youtube channel!
 
Show Recent Blog Posts In GitHub ReadMe Using Azure Function  Show Recent Blog Posts In GitHub ReadMe Using Azure Function Show Recent Blog Posts In GitHub ReadMe Using Azure Function Show Recent Blog Posts In GitHub ReadMe Using Azure Function
 
Below are the titles of the latest 5 posts from my blog (This is an automated message using Azure Function. Azure is Love!)
  • 🔭 I’m currently working on Azure IoT Hub, IoT Central, Raspberry Pi
  • 🌱 I’m currently learning a lot of new IoT topics
  • 👯 I’m looking to collaborate on any MVP product in IoT
  • ⚡ Fun fact: Well, this readme file will not be enough!
Boom!. We did it. Now go to your GitHub home page, and I am sure that you will love your new beautiful, detailed home page.
 
Update
 
As GitHub has a very low timeout, sometimes the image created was not showing in my profile. Thus, I had to change the mechanism. I changed my Azure function to a time trigger function that runs every hour and the main functionality of this function now is to generate the image and upload to the Azure blob storage. Now I can directly get the blob image URL in the Readme file. No more timeout issues. Following are the codes of the new Azure function. You can also see this in the Dev branch of the repository.
  1. using GitHubFuncs.ExtensionMethods;  
  2. using Microsoft.AspNetCore.Mvc;  
  3. using Microsoft.Azure.WebJobs;  
  4. using Microsoft.Extensions.Logging;  
  5. using Microsoft.WindowsAzure.Storage;  
  6. using SixLabors.Fonts;  
  7. using SixLabors.ImageSharp;  
  8. using SixLabors.ImageSharp.Formats.Png;  
  9. using SixLabors.ImageSharp.PixelFormats;  
  10. using SixLabors.ImageSharp.Processing;  
  11. using System;  
  12. using System.Collections.Generic;  
  13. using System.IO;  
  14. using System.Linq;  
  15. using System.Net.Mime;  
  16. using System.ServiceModel.Syndication;  
  17. using System.Threading.Tasks;  
  18. using System.Xml;  
  19. namespace GitHubFuncs {  
  20.     public class GetLatestPosts {  
  21.         private static ILogger_logger;  
  22.         private  
  23.         const string_fileName = "latestpost.png";  
  24.         private  
  25.         const string_blobContainerName = "github";  
  26.         [FunctionName("GetLatestPosts")]  
  27.         public async TaskRun([TimerTrigger("0 0 */1 * * *")] TimerInfomyTimer, ILoggerlog) {  
  28.             try {  
  29.                 _logger = log;  
  30.                 await UplaodImageToStorage();  
  31.             } catch (System.Exceptionex) {  
  32.                 log.LogError($ "Something went wrong: {ex}");  
  33.                 throwex;  
  34.             }  
  35.         }  
  36.         private static async Task < bool > UplaodImageToStorage() {  
  37.             try {  
  38.                 var base String = WriteOnImage(GetLatestFeeds());  
  39.                 string convert = baseString.Replace("data:image/png;base64,", String.Empty);  
  40.                 var bytes = Convert.FromBase64String(convert);  
  41.                 var stream = newMemoryStream(bytes);  
  42.                 if (CloudStorageAccount.TryParse(Environment.GetEnvironmentVariable("AzureWebJobsStorage"), outCloudStorageAccountcloudStorageAccount)) {  
  43.                     var cloud BlobClient = cloud StorageAccount.CreateCloudBlobClient();  
  44.                     var cloud BlobContainer = cloud BlobClient.GetContainerReference(_blobContainerName);  
  45.                     var cloud BlockBlob = cloud BlobContainer.GetBlockBlobReference(_fileName);  
  46.                     cloud BlockBlob.Properties.ContentType = "image/png";  
  47.                     await cloud BlockBlob.UploadFromStreamAsync(stream);  
  48.                     _logger.LogInformation("Uploaded new image");  
  49.                 } else {  
  50.                     _logger.LogError("Error in connection");  
  51.                 }  
  52.             } catch (Exceptionex) {  
  53.                 _logger.LogError(ex.Message);  
  54.             }  
  55.             return false;  
  56.         }  
  57.         private static string WriteOnImage(IEnumerable < SyndicationItem > feedItems) {  
  58.             var titles = string.Join(", ", feedItems.Select(s => s.Title.Text).ToList());  
  59.             using  
  60.             var img = new Image < Rgba32 > (Configuration.ImageWidth, Configuration.ImageHeight);  
  61.             var font = SystemFonts.CreateFont(Configuration.Font, Configuration.FontSize);  
  62.             img.Mutate(ctx => ctx.ApplyScalingWaterMark(font, titles, Color.Black, 5, true));  
  63.             return img.ToBase64String(PngFormat.Instance);  
  64.         }  
  65.         public static IEnumerable < SyndicationItem > GetLatestFeeds() {  
  66.             var reader = XmlReader.Create(Configuration.BlogLink);  
  67.             var feed = SyndicationFeed.Load(reader);  
  68.             reader.Close();  
  69.             return feed.Items.Take(5);  
  70.         }  
  71.     }  
  72. }  
Source Code
 
Please feel free to check out the repositories here:
  • https://github.com/SibeeshVenu/GitHubFuncs
  • https://github.com/SibeeshVenu/sibeeshvenu
Your turn. What do you think?
 
Thanks a lot for reading. Did I miss anything that you may think is needed in this article? Did you find this post useful? Please do not forget to share your feedback!