blog

#CASBAN6: Creating A Serverless Blog on Azure with .NET 6 (new series)

#CASBAN6: Creating A Serverless Blog on Azure with .NET 6 (new series)

Motivation

I was planning to run my blog without WordPress for quite some time. For one, because WordPress is really blown up as a platform. The second reason is more of a practical nature – this project gives me lots of stuff to improve my programming skills. I already started to move my developer website away from WordPress with ASP.NET CORE and Razor Pages. Eventually I arrived at the point where I needed to implement a blog engine for the news section. So, I have two websites (including this one here) that will take advantage of the outcome of this journey.

High Level Architecture

Now that the ‘why’ is clear, let’s have a look at the ‘how’:

There are several layers in my concept. The data layer consists of a serverless MS SQL instance on Azure, on which I will work with the help of Entity Framework Core and Azure Functions for all the CRUD operations of the blog. I will use the powers of Azure API Management, which will allow me to provide a secure layer for the clients – of course, an ASP.NET CORE Website with RazorPages, flanked by a .NET MAUI admin client (no web administration). Once the former two are done, I will also add a mobile client for this blog. It will be the next major update for my existing blog reader that is already in the app stores.

For comments, I will use Disqus. This way, I have a proven comment system where anyone can use his/her favorite account to participate in discussions. They also have an API, so there is a good chance that I will be able to implement Disqus in the Desktop and Mobile clients.

Last but not least, there are (for now) two open points – performance measuring/logging and notifications. I haven’t decided yet how to implement these – but I guess there will be an Azure based implementation as well (until there are good reasons to use another service).

Open Source

Most of the software I will write and blog about in this series will be available publicly on GitHub. You can find the repository already there, including stuff for the next two upcoming blog posts already in there.

Index

I will update this blog post regularly with a link new entries of the series.

Additional note

Please note that I am working on this in my spare time. This may result in delays between the blog posts and the updates committed into the repository on GitHub.

Until the next post – happy coding, everyone!


Title Image by Roman from Pixabay

Posted by msicc in Android, Azure, Dev Stories, iOS, MAUI, Web, 2 comments

How to create a RSS feed web tile with notifications for your Microsoft Band

This is a blog post not only for developers, but also for users (I will try to get not to technical in this post).  I managed to buy a Microsoft Band 2 for me here in Europe two weeks ago, and of course I am still exploring all the functionality that it has. A web tile is one of the cool features it supports – with a web tile, you can add your digital footprint to the Microsoft Band. And the best thing: you don’t need to be a developer to create your own! Microsoft provides a web kit that creates the tile for you!

Let’s have a look at the (not so hard to understand) steps it takes to create your own web tile:

The First step is to choose the layout, which also describes the type of the web tile:

Screenshot (82)

After selecting the feed tile template, you need to find the RSS url of your blog or other source site. Paste it in the desired field and hit the next button.

Screenshot (83)

Microsoft’s site now reads your RSS feed and provides you the single fields that come with your feed. When you hover with your mouse over the fields, they’’ll get highlighted. Just drag and drop them into the Microsoft Band preview image on the left hand side.

Screenshot (77)

Now that you have selected the data that should appear on the Microsoft Band, let’s set up the notification for the web tile. This is where it gets a bit tricky, but most feeds should be covered by the following image:

Screenshot (79)

No worries, I am telling you what is done here. The first and second line is the title and the description of the notification. You can put in there whatever you like. The most important part is the condition expression below the Band preview. Sadly the documentation provided by Microsoft is not as detailed for feed tiles as it should. Luckily, I found a post at StackOverflow that explains a little bit more. If you’re a developer, feel free to read the full text. If you are a user: just drag and drop the guid field of the “item” section into the first and also into the last field and set the condition to not equal. If your feed gets a new item, you will get a notification on your band with that. This condition looks if there is any new guid in the items list of your feed – and if so, sends out the notification and shows the badge.

In the last step, we just need to provide some details about the web tile we have created. If you want to have all features, you must provide both images:

Screenshot (80)

If you want to have control on how the image looks like, you should provide the images already flattened into a transparent and white image already. The result could look very creepy otherwise. After that, you have finally created your web tile – congratulations!

Screenshot (81)

Once you have downloaded the web tile, you just need to mail it to yourself or anyone who wants to use it. The other option is to put it on your OneDrive and just share a link to your web tile. To share the link you need to add the link of your online storage to this: “mshealth-webtile://?action=download-manifest&url=”. The web tile I created for my blog is in this case: mshealth-webtile://?action=download-manifest&url=http://1drv.ms/1TDRGSC . This link only works on phones (also Android and iOS). It opens the Microsoft Health app (that needs to be installed for the usage of web tiles, anyways) and asks you to install the web tile:

wp_ss_20160226_0001

Once you have done that, your web tile is ready to go. Once you have a new entry in your RSS feed, the notification should appear on your band. If you want to force the update, just force the Microsoft Health app to sync with your band. After that, you should see the notification and also the badge count. Here is a shot of the one I did for testing:

WP_20160226_17_48_20_Rich_LI

I only began to play around with web tiles, and already was able to create a pretty good result so far. As I will explore them more and more, I will continue to blog about it. In the meantime, I hope this blog post is helpful for some of you. Have fun, everybody!

Posted by msicc in Archive, 1 comment

Service post–domain chaos finally has an end (msicc.net is back)

 

moving_chaos

 

Some of you might have noticed that a lot of chaos was going on with my domain msicc.net in the last few months.

The reason were some serious issues with my old hoster – that would be a evil long post to describe.

As backup, I used msicc.cloudapp.net, a virtual machine on Azure that I set up to play around and learn more about webservers on Linux. Sadly, I just don’t have enough time to dive deeper into that.

Now that msicc.net is finally working again, this will be the primary address to go to.

I will shut down the server on Azure soon. If you come across links for my blog with msicc.cloudapp.net, just remove the ‘cloudapp.’ part of the link, and you will end on the corresponding blog post on msicc.net.

Also my apps for Windows Phone and Windows 8 are working again (some small updates will come with an update).

Sorry for any inconveniences caused by this.

Posted by msicc in Archive, 0 comments

How to update a live tile in a background agent with web data on Windows Phone

scheduledtaskWP

In one of my recent projects, I needed to update the live tile of the app via a background agent with data from a WordPress based web site. I did what I always do when implementing a feature I never used before: researching.

I found tons of example on how to update the live tile periodically, but non of them told me how I can use the data from the web site or where I need to put it in.

In the end, it was Jay Bennet, developer of the fantatsic WPcentral Windows Phone app, who gave me the last hint I needed – where do I start the request for the data I need. Thanks to him for that!

Ok, but let’s start in the beginning. When it comes to web based services, you first need a class (or ViewModel) that can hold your data you receive from your service. I explained that already pretty well here. No matter if you are running your request within your app project or in a PCL, it pretty much always works like this.

After stripping of our class out of the JSON string, we are now able to create our request as well as our Background Agent.

The first thing you need to do is to add a Windows Phone Scheduled Task Agent. Create a new project within your app and choose the project type mentioned before. Then, in your main project, add it as a reference (right click on References/Add Reference/Solution => select your background agent project there. That’s it.

No go to your ‘ScheduledAgent.cs’ file and open it. You will find this code in there:

protected override void OnInvoke(ScheduledTask task)
{
  //TODO: Add code to perform your task in background

  NotifyComplete();
}

And thanks to Jay, I know that this is where all the action (not only updating the tile like in all samples I found) happens. This may sound very trivial for those of you who have experience with that, but if you’re new to it, it may hold you back a bit. However, there are a few points you’ll need to take care of:

    • you only have 25 seconds to perform all action here
    • your task will run every 30 minutes, no way to change that
    • scheduled tasks need to be restarted within 14 days after the current start
    • Battery saver and the OS/the user can deactivate the agent
    • there is a long list of what you are not able to do in here (check MSDN)
    • there are memory limits (check MSDN)

all action needs to be finished before NotifyComplete() is called

Based on this information, I created my task as following:

        protected async override void OnInvoke(ScheduledTask task)
        {
        //performing an async request to get the JSON data string        
            PostsFetcher postfetcher = new PostsFetcher();
            Constants.latestPostsForLiveTileFromWordPressDotComResultString = await postfetcher.GetLatestPostFromWordPressDotComForLiveTileOnPhone();

        //deserialize all data
            var lifetileBaseData = JsonConvert.DeserializeObject<json_data_class_Posts.Posts>(Constants.latestPostsForLiveTileFromWordPressDotComResultString);

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
        //using Telerik's LiveTileHelper here
                Uri launchUri = new Uri("Mainpage.xaml", UriKind.Relative);
                RadFlipTileData fliptileData = new RadFlipTileData();
                fliptileData.BackContent = lifetileBaseData.posts[0].title;
                fliptileData.WideBackContent = lifetileBaseData.posts[0].title;
                fliptileData.BackTitle = string.Format("{0} {1}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString());
                fliptileData.Title = "LiveTileTitle";               

                if (lifetileBaseData.posts[0].featured_image != string.Empty)
                {
                    fliptileData.BackgroundImage = new Uri(lifetileBaseData.posts[0].featured_image, UriKind.RelativeOrAbsolute);
                    fliptileData.WideBackgroundImage = new Uri(lifetileBaseData.posts[0].featured_image, UriKind.RelativeOrAbsolute);
                    fliptileData.BackBackgroundImage = new Uri("Images/BackBackground.png", UriKind.RelativeOrAbsolute);
                    fliptileData.WideBackBackgroundImage = new Uri("Images/WideBackBackground.png", UriKind.RelativeOrAbsolute);
                }
                else
                {
                    fliptileData.BackgroundImage = new Uri("Images/PlaceholderBackgroundImage.png", UriKind.RelativeOrAbsolute);
                    fliptileData.WideBackgroundImage = new Uri("Images/PlaceholderWideBackgroundImage.png", UriKind.RelativeOrAbsolute);
                    fliptileData.BackBackgroundImage = new Uri("Images/BackBackground.png", UriKind.RelativeOrAbsolute);
                    fliptileData.WideBackBackgroundImage = new Uri("Images/WideBackBackground.png", UriKind.RelativeOrAbsolute);
                }

                foreach (ShellTile tile in ShellTile.ActiveTiles)
                {
                    LiveTileHelper.UpdateTile(tile, fliptileData);
                }
            });

            NotifyComplete();
        }

As I fetch different data from the site, I create a class that holds all request methods. In those methods, I just created an HttpClient that downloads the desired Json string into my app. I take only the first post in the case above, to make the live tile updating also on slow internet connections within the 25 seconds and to not reach any memory limit. In the end, I use Telerik’s LiveTileHelper to create a FlipTile with image and text from the site (the image will be downloaded automatically).

That’s all we need to to in the Scheduled Task Agent. Now we need to implement the agent into our app project.

First thing we should implement is a switch where the user can turn our agent on and off. I used a ToggleSwitch for that, saving the isChecked state as a Boolean to the IsolatedStorage of my app.

Knowing I need to restart the background agent after some time, I implemented the agent handling in App.xaml.cs. This way, I need to write less code as I tend to use separate settings pages. The only thing you need to think of is to set up all objects as static and public.

First, we need to declare a PeriodicTask as well as a name for it:

public static PeriodicTask LiveTileUpdaterPeriodicTask; 
public static string LiveTileUpdaterPeriodicTaskNameString = "LiveTileUpdaterPeriodicTaskAgent";

Now we need to generate a method that handles everything for our background task:

       public static void StartLiveTileUpdaterPeriodicTaskAgent()
        {
        //declare the task and find the already running agent
            LiveTileUpdaterPeriodicTask = ScheduledActionService.Find(LiveTileUpdaterPeriodicTaskNameString) as PeriodicTask;

            if (LiveTileUpdaterPeriodicTask != null)
            {
        //separate method, because we need to stop the agent when the user switches the Toggle to 'Off'
                StopLiveTileUpdaterPeriodicTaskAgent();
        //contains:
        //try
                //{
                //  ScheduledActionService.Remove(App.LiveTileUpdaterPeriodicTaskNameString);
                //}
                //catch { }
            }

        //generate a new background task 
            LiveTileUpdaterPeriodicTask = new PeriodicTask(LiveTileUpdaterPeriodicTaskNameString);

        //provide a description. if not, your agent and your app may crash without even noticing you while debugging
            LiveTileUpdaterPeriodicTask.Description = "This background agent checks every 30 minutes if there is a new blog post.";

        //start the agent and error handling
            try
            {
                ScheduledActionService.Add(LiveTileUpdaterPeriodicTask);
            }
        catch (InvalidOperationException exception)
            {
        //user deactivated or blocked the agent in phone settings/background tasks. Ask him to re-activate or unblock it
                if (exception.Message.Contains("BNS Error: The action is disabled"))
                {
                    RadMessageBox.ShowAsync("it seems you deactivated our Background Agent for the Live Tiles. Please go to settings/background tasks to activate our app again.", "Whoops!", MessageBoxButtons.OK);
                }

        //the maximum of running background agents is reached. No further notification to the user required, as this is handled by the OS
                if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
                {
                    //changing the Boolean to false, because the OS does not allow any new taks
                    isLiveTileActivated = false;
                }
            }
            catch (SchedulerServiceException)
            {
                //if there is a problem with the service, changing the Boolean to false. 
        //feel free to inform the user about the exception and provide additional info
                isLiveTileActivated = false;
            }
        }

In Application.Launching() and in ToggleSwitch_Checked event, call this method. In ToggleSwitch_UnChecked event, call ‘StopLiveTileUpdaterPeriodicTaskAgent()’ instead to stop the agent.

Before we are now able to debug our agent, there are two things left. The first thing is to declare

#define DEBUG_AGENT

in the very first line of ‘App.xaml.cs’ as well as in ‘ScheduledAgent.cs’ before all using statements.

The second thing is adding an if-Debug command to our ‘StartLiveTileUpdaterPeriodicTaskAgent()’ and also to our ‘OnInvoke(ScheduledTask task)’ methods:

#if(DEBUG_AGENT)
 ScheduledActionService.LaunchForTest(LiveTileUpdaterPeriodicTaskNameString, TimeSpan.FromSeconds(60));
 #endif

Add this after adding the task to the SchedulerService in our agent starter and before ‘NotifyComplete()’ in ‘ScheduledAgent.cs’.

If you run the project now in Debug mode, your agent will be debugged and forced to run after 60 seconds. If you run the project in Release mode, Visual Studio will throw an ‘Access Denied’ error, so make sure you set it up correctly.

If you follow all steps above, you will be able to add a Live Tile updated via background agent very easily to your app.

As always, I hope this real world scenario will help some of you.

Until then, happy coding!

Posted by msicc in Archive, 7 comments