WordPress

How to use WordPress to display remote notifications in your Windows Phone app

Sometimes, we need to display information to our users on demand. The easiest way is to do this in our app via a remote notification service.

If you have a WordPress blog, my solution may also be helpful for you.

I am using a page that is not linked anywhere in my blog to display the message. To add a new page, go to your WordPress Dashboard and hover over “Pages” and click on “Add New”.

image

Fill in the title and your notification and publish the page. Before closing your browser, save/remember the id of the page, we will need it later.

image

The next step is to download my WordPress Universal library, which can be downloaded right here from my Github. You can add the project directly to your solution or build it and then reference the library you will find in the bin folder of the WordPress Universal project folder. If you want to learn more about the library, visit http://bit.ly/WordPressUniversal.

Now that we have everything in place, let’s add the code that does the magic for us:

        public async void ShowNotification()
        {
            //initialize the client and load the list of pages from your blog
            wpClient = new WordPressClient();
            var pages = await wpClient.GetPostList("msicc.net", WordPressUniversal.Models.PostType.page, WordPressUniversal.Models.PostStatus.publish, 20, 0);

            //select the notification page
            var notificationContentPage = from p in pages.posts_list where p.id == 4248 select p;

            //check if has content
            if (!String.IsNullOrEmpty(notificationContentPage.FirstOrDefault().content))
            {
                //convert parapgraphs into NewLines
                //you might have more HTML content in there which needs to be converted
                string content = notificationContentPage.FirstOrDefault().content.Replace("

", string.Empty).Replace("

", "\n\n"); //App.SettingsStore = ApplicationData.Current.LocalSettings //change this to your appropriate storage like IsolatedStorage etc. //this displays the message only once to our users, but keeps the door open for an easy update mechanism if (App.SettingsStore.LastNotificationContent != content) { MessageBoxResult result = MessageBox.Show(content, notificationContentPage.FirstOrDefault().title, MessageBoxButton.OK); switch (result) { //the button click saves the actual message case MessageBoxResult.OK: App.SettingsStore.LastNotificationContent = content; break; //BackButtonPress does this as well case MessageBoxResult.None: App.SettingsStore.LastNotificationContent = content; break; } } } }

What does this code do? First, it fetches all pages from our WordPress blog. Then, we are selecting the page we created via its id. If your WordPress blog does not show you the id in the url of the page, set a BreakPoint at the “var notificationContentPage = …” line. you will then easily be able to get the id:

image

Naturally, the returned content is HTML formatted. To remove the paragraph tags and but respect their function, we are using a simple String.Replace pattern. You may have more HTML tags in your message that needs to be removed or converted.

To generate an easy way to display the message only once but keep it open for updates, we are saving the converted message locally. In this case, I used the LocalSettings of my Windows Phone 8.1 app. I am using the MessageBoxResult to make the method saving the message either at the point of the OK click as well as on BackButtonPress.

This is how the above generated WordPress Page looks as a Notification:

wp_ss_20141127_0001

As my WordPress Universal library works cross platform for C# apps, you should be able to adapt this for your Windows 8.1 or  Xamarin apps as well.

As always, I hope this is helpful for some of you.

Happy coding!

Posted by msicc in Dev Stories, wpdev, 1 comment

WordPressUniversal – a PCL library for WordPress based C# mobile apps

WP_CSharp_Lib

As I have already developed a news reader app for my blog, I got asked quite a few times if I want to share my code to help others creating their apps. As I need to redesign my blog reader to match the latest OS features of Windows and Windows Phone, I decided to create my WordPressUniversal library.

Automattic, the company behind WordPress, integrated a powerful JSON API into their JetPack plugin. My library is based on this API. Please make sure the JSON API is active on the blog you are developing your app for.

The library currently provides the following features:

  • getting a list posts or pages
  • getting a list of all categories
  • getting a list of comments for the site and single posts
  • supports Windows Phone 8 & 8.1 Silverlight, Windows Phone 8.1 RT, Windows 8, Xamarin.iOS and Xamarin.Android

The library deserializes all data into C# objects you can immediately work with.

It is still a work in progress, but as it provides already a bunch of options to get you started, I am making this public already.

I am constantly working on the library, so be sure to follow the project along.

Note: JetPack’s JSON API does not support guest commenting at the moment. I already reached out to Automattic to (hopefully) find a solution for this. If you cannot wait, Disqus has a portable solution for Windows Phone apps.

Please make sure to see the documentation on my GitHub page.

If you have any questions, idea, wishes for me, just post a comment here or ping on Twitter.

Happy coding everyone!

Posted by msicc in Dev Stories, win8dev, wpdev, Xamarin, 17 comments

Dev Story Series (Part 5 of many): Styling a WebView or WebBrowser element

This post is about styling our WebView or WebBrowser in our app. Until now, we only got the HTML string that we are displaying in our WebView or WebBrowser. It looks like this:

image.png

The content we receive from our WordPress post content includes already all kind of HTML tags like paragraphs, lists, links, images. That is the advantage for this solution: no parsing is needed, the string can be displayed as is. Both the WebView and the WebBrowser framework element (no, they are not controls) are able to read and render CSS code. And this is how we can match the whole element for our app.

HTML Pages can be styled by using a so called cascading style sheet (CSS), which is similar to XAML code. With a little bit of searching on the web you will be able to style “translate” your XAML properties into CSS.

Here is a sample CSS String:

<STYLE type="text/css">
body{background:#034786; width:450px; }
p{font-family:'Segoe UI';color: white;font-size:medium;}
h1{font-family:'Segoe UI';color: white;}
h2{font-family:'Segoe UI';color: white;}
h3{font-family:'Segoe UI';color: white;}
h4{font-family:'Segoe UI';color: white;}
pre{background-color: #C0C0C0; width:100%;}
blockquote{font-family:'Segoe UI';font-style:italic;}
a:link{font-family: 'Segoe UI';color: #C0C0C0; font-size: medium; text-decoration:underline}
li{font-family: 'Segoe UI';color: white;font-size: medium;list-style-type: square;}
img {text-align:center; width:100%: height:100%;}
</STYLE>";

Every CSS string has to be surrounded with “<STYLE type=”text/css”> </STYLE> “. Between those two Style tags, you can set different properties for each kind of HMTL tag:

  • body = the whole page is embedded in the body. this is where we set the background of our content as well as the width and the height
  • p = paragraphs. paragraphs can contain text as well as images or other multimedia content. Mainly used for text like in our blog post, we style how the user is able to read our blog post.
  • h1 – h4 = different kinds of headers. you can define four styles of headers
  • pre = is for lines of code
  • blockquote = if we quote people or other sites, we use quotes to clarify this aren’t our words. should be styled a bit differently than the rest of our blog (e.g. Italic)
  • a:link = how hyperlinks will be styled
  • li = this is how our list will be styled in this view
  • img = how we want to see our pictures in our post

Hint for using CSS in code behind:

If you just C&P the CSS string from above, it will result in some errors from Visual Studio. Visual Studio does not like the new lines in strings, so you have to add it as one line. Also is it not possible to use ‘”‘ within a string declaration. It has to be “escaped”, which we are doing with a simple before it: ‘”‘. I mentioned it because I learned it the very hard way by trying to solve it for 2 hours.

Only thing we now need to do is pass the CSS String together with our HTML string from our JSON to our WebView or WebBrowser element:

WebBrowser.NavigateToString(CSSString + ContentString);

After navigating to this both strings, our content is now displayed like native:

  styledNativeWebView

One last tip:

I recommend to set the Visibility of your WebBrowser or WebView to “Collapsed” until the whole rendering has done. Once the “navigation” has finished, set it via code to visible. This way the user does not recognize that we are rendering the post content for him. Just display a loading animation until that is done. Both elements have a “LoadCompleted” event. Once the rendering (= the navigation to our string) is done, the content of our blog post is shown as it would be natively in our app.

As always, I hope this is helpful for some of you and feel free to leave a comment below.

Posted by msicc in Dev Stories, win8dev, wpdev, 0 comments

Dev Story Series (Part 4 of many): How to open links from a WebBrowser/WebView in Internet Explorer

XAMLWebView

Today I will share my solution of how to open links from a WebBrowser or WebView on Windows Phone and Windows 8 (as I did in my app for msicc.net).

Generally links are opened within the same WebBrowser or WebView element. On Windows Phone you can solve this problem pretty easy with only one simple method:

public void WebBrowser_Navigating(object sender, NavigatingEventArgs e)
        {
            e.Cancel = true;
            WebBrowserTask wbt = new WebBrowserTask();
            wbt.Uri = e.Uri;
            wbt.Show();
        }

In Windows 8 this gets a bit more complex. There is no Navigating method, and this is why we have to combine different languages together. We will use the ScriptNotify event to pass the link via a small java script and launch IE with the new link.

First, you need to add the function to your HTML string.  I used a RegEx method to add all the pattern that is needed to all links. As I know that a lot of us (especially junior devs like me) have their problems with RegEx, here is my method to add them:

public static string AddScriptToLink(string text)
        {
            const string hrefScript = " onclick="return OnLinkClick('{0}')" ";
            const string pattern = @"href=""(.*?)""";

            var result = text;

            var matches = Regex.Matches(text, pattern);
            var sortedMatches = matches.Cast<Match>().OrderByDescending(x => x.Index);
            foreach (var match in sortedMatches)
            {
                var replacement = string.Format(hrefScript, match.Groups[1].Value);
                result = result.Insert(match.Index, replacement);
            }

            return result;
        }

After you did that, you will be able to use the following script:

<script type='text/javascript'>
	function OnLinkClick(a) 
		{       
         	 window.external.notify(a);       
		 return false;    
		}
</script>

I pass this script together with the HTML string (HTML methods need to be first!) to the WebView. I recommend to save the script as a static string, so you have do insert only the name of the string.

If you add the ScriptNotify Event to your WebView, you will be able to use LaunchUriAsync with the value of e, which is the link.

private async void WebView_ScriptNotify(object sender, NotifyEventArgs e)
        {
            await Windows.System.Launcher.LaunchUriAsync(new Uri(e.Value));
        }

I am not sure if there is a better way to do this, but that is my way. It works like it should and does not hurt the experience of my app.

As always I hope this is helpful for someone out there. If you have any way to improve that, feel free to leave a comment below.

Posted by msicc in Dev Stories, win8dev, wpdev, 0 comments

Dev Story Series (Part 3 of many): Why I use a WebBrowser/WebView to display WordPress post content

When it comes to display the post content on a blog reader app, it starts to become a bit challenging. The post content is formatted to look great on your website. But when we pull our posts into an app, there is only the naked, HTML formatted string.

As developer, you have to think about several things now:

  • What part of the content do I want to be displayed?
  • How do I get the images there?
  • What if there is a video in the post?
  • Where do I put the Links in?
  • How can I handle enumerations?
  • and so on…

There is the HTMLAgilityPack out there, but I never got a satisfying result out of it. The next method would be to write a custom parser. This is what I have done before, in the old version of the app for my WordPress blog. It did work, but I had to invest a real big amount of time in it before I got a result that I was able to live with. I was also not too experienced with RegEx (and I am still not) that I could set up a perfect parser.

When I was creating the Windows 8 version of my app, I wanted to achieve a good reading experience. On the other side I  wanted the code to be as reliable as possible, because there are often changes on WordPress that can have impact on my app.

As I mentioned above, the post content is already formatted. It is formatted in HTML.  I decided to render the content string instead of parsing it.

It is pretty easy to do that. Just pass the content string to your desired details page, and use a WebBrowser on Windows Phone or a WebView on Windows 8. Without any parsing, just by “navigating” to the passed string, we will get a result like this:

image

So we have already a readable result, and if my app has only white background, I could leave it like it is and go on.  Without any additional line of code.

Using the WebBrowser/WebView brings also additional advantages:

  • Pinch-to-Zoom support
  • Orientation support
  • automatic image downloading without any additional control
  • WebView on Windows 8 embeds videos automatically

I don’t want to hide that there are a few points that we need to handle, which will be subject of additional posts:

  • styling of content to match our app colors
  • Navigation to links (including a solution for video links on Windows Phone)
  • Scroll direction in Windows 8 WebView

I know it might be not the best practice for displaying web content, but I am really satisfied what I achieved by using the WebBrowser and WebView element in my apps.

I hope the upcoming blog posts will be helpful for some of you to create also a good user experience by using these elements. Of course these posts will contain some code. Before starting the posts about it I just wanted to share why I used these elements.

 

Posted by msicc in Dev Stories, win8dev, wpdev, 0 comments

Dev Story Series (Part 2 of many): Getting recent posts from WordPress into your Windows Phone and Windows 8 app

Now that we have a full WordPress JSON class, we are able to download our recent posts from WordPress into our apps for Windows Phone and Windows 8. I am still not using MVVM to keep it simple (and because I have to dive into it more deeply).

The first thing we need to do is to download the JSON string for the recent posts. The Uri scheme is pretty simple: {yourblogadresshere}?json=get_recent_posts

I declared a public string in my MainPage for that, so it is very easy to use it in our app.

The second thing we are going to do is to download the JSON string into the app.

For Windows Phone I used a WebClient, as I want to keep it compatible with the Windows Phone 7 OS. I will update the App with an dedicated WP8 version later, for the moment it is working on both OS versions. Add this code to you Page_Loaded event:

                WebClient GetPostsClient = new WebClient();
                GetPostsClient.Headers[HttpRequestHeader.IfModifiedSince] = DateTime.Now.ToString();
                GetPostsClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(GetPostsClient_DownloadStringCompleted);
                GetPostsClient.DownloadStringAsync(new Uri(RecentPostJsonUri));

We will also have to add the Handler for GetPostsClient_DownloadStringCompleted:

 void GetPostsClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            App.jsonString_result = e.Result;
        }

In Windows 8 there is no WebClient, so I used an HttpClient:

                        HttpClient getJsonStringClient = new HttpClient();
                        getJsonStringClient.DefaultRequestHeaders.IfModifiedSince = DateTime.UtcNow;
                        App.jsonString_result = await getJsonStringClient.GetStringAsync(RecentPostJsonUri);

Both the Windows Phone and the Windows 8 apps are downloading the string asynchronously, the UI is reliable all the time. You may have noticed the additional Header that I request. This way, we are able to integrate a refresh function into our app. If we leave this out, our app uses the cached string, and users will have to exit the app to refresh the list of our posts.

You will have to declare a public static string variable for the downloaded string in App.xaml.cs, that keeps the downloaded string accessible through the whole app.

Until now we have only downloaded our JSON String, which looks like this:

image

Side note: The WordPress JSON API has a dev mode. Just add “&dev=1” to your above created Uri, and you will be able to see the whole JSON string in a readable form in your browser.

Back to our topic. Off course this is not a good format for users. They want to see only the content, without all the formatting and structuring code around.

What we need to do, is to deserialize our JSON String. This is possible with Windows Phone and Windows 8 own API, but I highly recommend to use the JSON.net library. You can download and learn more about it here. To install the library, just go to Tools>Library Package Manager>Manage NuGet Packages for Solution, search for JSON.net, and install it.

After installing the package, we are able to use only one line of code to deserialize our JSON String to our data members:

var postList = JsonConvert.DeserializeObject<Posts>(App.jsonString_result);

Now we need the deserialized data to be displayed to the user. The desired control for Windows Phone is a ListBox, for Windows 8 you it is called  ListView. We need to create an ItemTemplate in XAML and bind the data we want to show to the user (Just change ListBox to ListView for Windows 8 in XAML):

<ListBox x:Name="PostListBox">
                <ListBox.ItemTemplate>
                    <DataTemplate>
				<StackPanel>
 				<Image x:Name="PostImage" 
				       Source="{Binding thumbnail}" />
                           	<TextBlock x:Name="TitleTextBlock" 
				           Text="{Binding title}" 
					   TextWrapping="Wrap" 
					   FontSize="20" />
                                <TextBlock x:Name="PublishedTextBlock" 
					   Text="{Binding date}" 
					   FontSize="12"/>
				</StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
          </ListBox>

As you can see, we have set some Bindings in the code above. This Bindings rely on the DataContract Post, as every ListBox/ListView-Item represents one Post of our postList.

[DataContract]
public class Post
    {
        [DataMember]
        public int id { get; set; }
        [DataMember]
        public string type { get; set; }
        [DataMember]
        public string slug { get; set; }
        [DataMember]
        public string url { get; set; }
        [DataMember]
        public string status { get; set; }
        [DataMember]
        public string title { get; set; }
        [DataMember]
        public string title_plain { get; set; }
        [DataMember]
        public string content { get; set; }
        [DataMember]
        public string excerpt { get; set; }
        [DataMember]
        public string date { get; set; }
        [DataMember]
        public string modified { get; set; }
        [DataMember]
        public List<Category> categories { get; set; }
        [DataMember]
        public List<object> tags { get; set; }
        [DataMember]
        public Author author { get; set; }
        [DataMember]
        public List<comment> comments { get; set; }
        [DataMember]
        public List<Attachment> attachments { get; set; }
        [DataMember]
        public int comment_count { get; set; }
        [DataMember]
        public string comment_status { get; set; }
        [DataMember]
        public string thumbnail { get; set; }
    }

Choose the fields you want to display to create your own DataTemplate to show only the data you want. Last but not least we have to tell our app that the ItemSource of our ListBox is the deserialized list, which is also done easily:

PostListBox.ItemsSource = postList.posts;

If you now hit F5 on your keyboard, the app should be built and the device/emulator should show your recent posts in a list. You don’t need to add additional code to download the images, as the image source points already to an image and will be downloaded automatically.

Pro-Tip:

The thumbnails from the our DataContract Post are looking really ugly sometimes. To get a better looking result in your ListBox/ListView, I recommend to use the attached images. To do this, you will need the following code:

          foreach (var item in postList.posts)
            {
                var postImagefromAttachement = item.attachments.FirstOrDefault();
                if (postImagefromAttachement == null)
                {
                    item.thumbnail = placeholderImage; //add your own placeholderimage here
                }
                else
                {
                    item.thumbnail = postImagefromAttachement.images.medium.url;
                }

            }

This code checks your list of attachments in your post, takes the first image, and downloads a higher quality (medium/full).  I am using medium to get best results on quality and download speed.

I hope this is helpful for some of you to get forward for to create a WordPress blog app on Windows Phone and Windows 8.

Happy coding!

Posted by msicc in Dev Stories, win8dev, wpdev, 1 comment