Monthly Archives: December 2015

Earning revenue through in-app purchases on Windows Store

Introduction and Background

A small overview of in-app purchases in Windows Store platform, in this post I will only cover the short summaries of quickly editing the small modules that you have recently created and to enable users to purchase them to support your development environments. Building applications is a tough task, and programmers need to be given what they deserve. Sometimes, respect is just not enough. Sometimes, the module you created is a tough one and you have full rights to ask for some money in a repay. It is your choice to select a price that users have to pay before they can consume the service.

Windows Store allows you to simply create a block of code, around the service, feature or application itself. That code is capable of managing the payment information, client information and other required stuff to make sure the user pays you before they can access the information and the service you are providing them with. Windows Store holds information for users too, it knows if a user has already made the purchase. If so, Windows Store won’t bother the users again to make the purchase and will hold the information for that license, user has acquired.

App monetization methods

On Windows Store you are offered with many methods and ways to earn money and to get support for your development environments and stuff! A few of them are:

  1. Ads display in your application.
    • The ads are of both types, static images or videos.
  2. Providing paid services in your applications.
  3. Asking for a pre-use purchase of your application. Paid apps.

You can ask for an upfront payment by your users. Many application developers use this method to support their development scenarios. This allows them to have an upfront payment to continue their programming and to support any of the updates to their clients. Not just this, the clients are also able to get free updates to the application later one.

But sometimes you want to allow your users to download and install the applications for free! This allows you to allow your users to try out your application. Users like free stuff, specially the stuff that is not available currently in their device’s marketplace. You can develop an application and start to offer a trial-period to allow users to use your service. If they like it, you can then ask them to purchase the license.

Otherwise, you can add a service separately that needs users to purchase it. You can add the price for it and allow users to purchase it. This method is very simple, helpful and handy! Your users can try out the application that they want to, and you can get the revenue for the features that were difficult to build and deploy. In this post, I will discuss and talk about the monetization methods by “in-app purchases” in Windows Store applications.

In-app purchases in Windows Store apps

In-app purchases requires you to have a Windows Store developer account and that you have published your application! In-app purchases are edited (and published) from the WIndows Store dashboard. You create a new in-app purchase in the dashboard, you edit the details and then update the application’s code to call those in-app purchases and provide the users with a service.

If you do not have a Windows Store developer account, you can still edit the application, you can test the license information but you won’t be able to publish the application, you won’t be able to ask your users (if any!) to purchase the services. So, first step would be to create a new developer account. Register as a developer.

If you are all set up for publishing a new application, continue with the sections and by the end you will be able to include in-app purchases for earning some revenue for your development tasks!

Creating a new app

Although, for development purposes you can test the application for performing the purchases without an online application, or a developer account. For that, you can use CurrentAppSimulator object, instead of CurrentApp object from Windows Store API. CurrentAppSimulator allows you to perform actions without having to call the active Windows Store APIs, and to just test the code in your application. This lets you test many things in your application and how user interacts with your application.

However, if you do not like to waste time, you can just head over to the “hard core” stuff. Where you publish an application, create a new in-app and start consuming it and allowing the users to purchase it. First of all, head over to the dashboard (provided: You have a developer account!) and create a new application. Publish it to the store.

Note: Developing application, uploading the source code and getting it to be published after verification takes time. My application took 16+ hours. Yours should have to go through the same procedure so be patient. I assume that you are having an application ready.

Once your application is created, continue to the next section and start creating and developing for an in-app purchase.

Creating the in-app product

The in-app product first needs to be defined in the Windows Store and the team then needs to approve the service. Once the product service has been approved by the team, you can use the product ID of that service to program your application. The product ID is used to check the license information for the application and if user owns the license to use the service or not.

License Information

LicenseInformation object of the application holds the information about the license. License can be checked for,

  1. ExpirationDate
  2. IsActive
  3. IsTrial
  4. ProductLicenses

These properties can be checked to determine the information about license of the application (if your application is a paid application), otherwise you can check for licenses of the in-app products. The in-app products also have a license and they also have properties set up, like active, trial etc. You can check against them!

An example of this license information is something like this,

var license = CurrentApp.LicenseInformation;

if(license.IsActive) {
    // License is active
    // Allow user to use the service.
} else {
    // Allow the users to purchase the service.
}

The same applies to in-app products! You would use the same method, the code for in-apps is in a later section so continue to read.

Create a product in Windows Store

You will be able to create a new in-app product online, on your application’s dashboard! Head over there and find the following option.

Screenshot (3586)
Figure 1: Windows Store showing IAPs option.

Click on this option and it would take you a new page where you can create a new IAP! Click on, “Create a new IAP” and enter a new product ID.

Screenshot (3587)
Figure 2: Enter a new product ID here and click on “Create IAP”.

You may have read that you need to be sure of the name. You won’t be able to update or delete it once you publish it.

Editing the in-app product

You will then be able to update the properties for that product in Windows Store. This is when your updates and properties would need to be verified. You will get the following three properties, that you can edit to make your product a bit “understandable”!

  1. Properties
    • Type of the purchase:
      • Consumables are those services that can be consumed. Like, 500 gold coins! Users can use them and re-purchase them.
      • Durables are those who have a lifetime. Like a premium service of 30 days.
    • Content type
    • Keywords
    • Tag
  2. Pricing and availability
    • Base price
    • A few other settings like Markets to sell the product in.
  3. Descriptions
    • Language
    • Description and title for the purchase. This is shown in the Windows Store.

You can edit the properties there, and then continue to submit it to the store. The team there would read the information and would approve it if there aren’t any problems with it. Chances are, it gets approved within an hour. Then you would continue to write the code to handle the products.

Remember: It takes at least one day to make the changes on the system. So, even if you upload the package along with the products, it would take one day for Windows Store to be able to start selling your products.

Writing the application to provide services

The Windows Store side is a very short process that you can perform in within less than 30 minutes. The longer part is to write the source code to handle the user’s license and to allow or request the user to purchase the license and service. The code is very short, intuitive and simple! I will explain the entire process here, so that it is very easy for you to get started earning revenues from Windows Store applications that you build.

Create a module

I wonder why this section even exists. Just create a module, a function or a service that performs some actions in your application. Suppose, you want to earn something from it. You can create it as a function, so that you can wrap the function within another code block that checks for a license. License information would be used to either allow the user to consume the service or to reject the request and to ask the user to purchase the service from Windows Store.

Add the license check-up!

I shared a code above, to determine the license for the application, you would do the same in case of in-app product too. You would see if a user has the license or not. The following code would do the thing for you:

// Remember the license object we created above?
if(license.ProductLicenses["productId"].IsActive) {
   // productId that you created while creating the in-app product

   // The user owns the license to use it.
} else {
   // Ask the user to get a licence.
}

You can use the CurrentApp.RequestProductPurchaseAsync(“productId”) function to allow the user to purchase the product from Windows Store. Windows Store would open a new window for the user to make a purchase. You can then (as its result) check if the user made the purchase or not. If he made the purchase, then allow him to use the service otherwise just end the request.

The common example for this would be like this:

// Get the license for the user
var license = CurrentApp.LicenseInformation;

// License for the in-app
var iapLicense = license.ProductLicenses["productId"];

// Apply a condition for the in-app product license
if(iapLicense.IsActive) {
   // User has bought the service; provide service
   provideService();
} else {
   // Allow user to purchase it
   await var resultOfPurchase = CurrentApp.RequestProductPurchaseAsync("productId");
   if(resultOfPurchase.Status == ProductPurchaseStatus.Succeeded) {
      // User has bought the service now
   } else {
      // Show the error message; for try again.
   }
}

This way, user would be able to purchase the item from Windows Store. The process is mostly similar to this one:

Screenshot (3588)
Figure 3: Windows Store purchase window is loading up.

Screenshot (3590)
Figure 4: Windows Store shows the details for the purchase the user is about to make. Also allows them to add a payment method to their account.

Screenshot (3589)
Figure 5: Windows Store shows the following methods (or any other, or less; depending on the country of users) to allow them to make the purchase. 

This would then allow the users to make a payment and then it would update their licenses to be able to consume the service later. It would update the “IsActive” property of their license information.

Points of Interest

This is it for this post, in this post you were taught how to earn revenue from your Windows Store applications. MSDN documentation has a lot of great resources available for developers to learn more about in-app purchases and services provided to developers to ensure that users pay for their services and for the users, to allow developers that they have indeed made the purchase and you should allow them to use the service.

There are many other topics that you should consider reading, such as:

  1. Allowing consuming of services like tokens.
  2. Managing the services from Windows Store.
  3. Adding more in-app products.
  4. Using receipts to verify the purchase status.
  5. Validating the receipts of services.

As a further read, you should consider reading “Enable in-app product purchases” guide on MSDN. I hope I have helped you with this post, and I think this is the last post for 2015, catch you in the next year!

Happy New Year! 🙂

Advertisements

2015 in review (Review of my blog)

The WordPress.com stats helper monkeys prepared a 2015 annual report for this blog.

Here’s an excerpt:

A New York City subway train holds 1,200 people. This blog was viewed about 4,400 times in 2015. If it were a NYC subway train, it would take about 4 trips to carry that many people.

Click here to see the complete report.

Tips for programmers (and other readers) before 2016

We are about to enter the next year, 2016, and we haven’t yet learnt anything from our mistakes that we have made last year. We may have learnt new things, new ideas and new technologies but unless we learn from our mistakes we are not going to get anything better done in 2016. And, I would hate to hear the same questions in 2016 that I heard in 2015. So, here goes the 5 tips for programmers that I want them to take under considerations before moving forward to 2016!

No C++, no C#, no Java. But a human-to-human talk is all this post is about. I am not going to talk about computers, but you! Programmers make up the computers, computers are nothing but a bunch of transistors passing on electric current from one IC to another. You, my brother (or sister) are the one who matter. Time to share some memories, I guess?! 🙂

Do not go gentle into that good night

I am a very big fan of Interstellar movie, this poem of Dylan Thomas I remember and I use each time when I am about to lose hope in myself. 2016 is about to come, make up some resolutions, make up plans for the party as it is “about to happen“. Do not lose hope, if 2015 was not a good year or if you did not get success. There are many reasons to moan and grieve, but there are many other reasons to smile at 2015 too.

A new year always doesn’t have to be celebration, sometimes you need to consider new innovations before moving on to the new year. Most of us are still working to make our 2016 better! Think of them and work.

I remember, 2014 was not a very much good year for me. Things were rough, odds were all against me and… I was losing hope in myself. I joined C# Corner in January, 2015. I remember myself posting articles with an intent to just share what I had. I did not want any accolade, just shared them. That made me feel good and I had no wish or dream for anything as a repay.and on the eve of 18th March I received the MVP award from C# Corner! I really feel very thankful to them, for granting me with such a pride. I would like to recommend the same to others.

You can read the poem at Academy of American Poets.

Do not go gentle into that good night,
Old age should burn and rave at close of day;
Rage, rage against the dying of the light.

© Dylan Thomas

tumblr_nfrm5pbdS21sao974o1_500

 

Keep dreaming, keep awake

I am not a writer, nor do I consider myself to be a great author but I have a personal saying, that I usually use for myself:

Wake up, open your eyes and start dreaming…

I believe dreams are not what we see in sleep. Dreams are something that doesn’t let us sleep. You cannot just simply skip your dreams, you can dream of anything and if you do not achieve it. You didn’t simply dream enough for it! This is a very simple rule.

All of these discoveries have been made through imagination. There was no concept of gravity until that Apple fell. There was no concept of relativity until Einstein imagined something while sitting on a chair. All of these, they are imaginations, dreams, that people work so hard to bring to reality. If you do not bring it to reality, work more harder.

Physics, chemistry, computer science and many other fields, including Astronomy, are all based on human conceptions. You cannot just do anything with current ideas. You have to look at the verge of chances and then make a decision.

tumblr_m241bwi5PC1r4z4mto1_500

So, now, can I hope you are going to dream, dream bigger than you did in 2015? 🙂 The bigger you dream the better the results would be! Take it for guaranteed, brother.

Find a hobby

Sometimes, you get bored and fed up by the same routine that you have. Go get yourself a hobby, work on it. I might say, the following may be great ones:

  1. Gardening
  2. Household works (trust me, they are not just meant for girls!)
  3. Sports (football, cricket; spend some time in open air)

Your mind would feel fresh and would get impregnated with impressive ideas. I live in an open area, in Rabwah and I am blessed with an open lawn where I can walk and even sleep at night. The stars outside are also mind freshening. Which most of my friends from Delhi often complain about; I can understand how “not having an open area” feels like. If you could find yourself a hobby along with the job, you can get relax very much as compared to those who just work.

Spend time with your loved ones. They need you!

Digital world has separated us so much, and it our own duty to make sure we are not far away when we sit next to each other. Spend most of your time with your parents, and not your laptops. Spend your time with your siblings and not your hardware! Siblings and parents have feelings and emotions attached to you. Your hardware only has a cable attached to the AC line.

Spend most of your time with your mother, father, who really do care about you! Not just that is a good action, but most of the times your parents would find a better solution to your problems. You should always share your mental problems, regular hurdles and other similar troubles with your parents. Remember: Your parents have more experience with “life” than you! No matter how much lucky, rich and successful you become, they will always be your parents.

Families over hardware

Share the happiness

New Year is about to come, it is a happy event for everyone. Share the happiness with everyone, greet everyone you meet!

So, why shouldn’t I be the first one to do so in advance, “Happy New Year, everyone!” 🙂

latest-happy-new-year-2016-photos

You made mistakes, but did you learn anything?

Everyone makes mistakes, that is not the point. The point is to learn something from your mistakes and to solve your problems that may arise in future. I personally hate to make mistakes, but when I do, I try to dig deeper to learn why it happened and how can I make sure it doesn’t happen again.

I remember I made a lot of mistakes, and most of the times I made mistakes that even made me go mad at myself and to doubt my skills. But, I never gave up. Most of the times beginners who get fed up of making mistakes and causing errors ask me, “How did I become a master?” in any programming language or framework. I reply,

I am a master because I have made mistakes more than you can ever make!

Master is not someone who knows everything by birth. But, we come to know everything by experience. I was also making mistakes, the same errors that you get, I got them too! But I never gave up, instead I learnt how to fix them, how to make sure they don’t come again.

Learn-from-Mistakes-500x290

Never give up!

Do not have a plan B. Your plan B must always be to complete plan A! Because the moment you decide a plan B for yourself, you have accepted that your plan A is not going to work. Always consider plan A to be the best one, but once it has been implemented, stick to it, no matter what!

The statements like, “If plan A doesn’t work don’t worry there are 25 other characters…” are only meant to be ironic. Do not put your life on a chance, you may not get another.

NO PLAN B!

Plan-A-Will-Smith-Red

Remember: You can do anything you set your mind to, man!

In the end, I just want to say, do not waste another year of your life! With the celebration of 2016, remember that our time is also running out of our hand like sand. I would suggest that you make up some plans before this year ends.

de86e-10948772_447078795442699_1718729731_n

Eminem — my love, my motivator, my mentor, my favorite hip hop artist — has been a motivation to me for a very long time. His songs, raps had kept me on the right path for a very long time! All, what I am, I think its just because of his motivating songs.

You should also consider to find yourself a motivation, then just stick to your plans and do what’s necessary! 🙂

Tackling text-to-speech and audio file in Windows Store applications

Introduction and Background

I was adding a few more features to the Windows Store application that I have, “Speak It!“, and while doing so it became much more complex task as I dig deeper into streams. Remember, streams provided by Windows Runtime are not as much simpler as .NET has. So, in this post I will talk about a few of those hazards that you may come across. This post consists of two sections, first one is to talk about the “Text-to-speech” API in Windows Store, sorry, Universal Windows Platform and the second one would talk about the saving the generated speech stream to an audio file.

I have already shared most of the concept in another article of mine, which covers the basic concepts, prerequisites and other basic stuff to be understood to build a Text-to-speech application. Unfortunately, that was .NET oriented whereas this article covers the concepts for text-to-speech API in Windows Runtime API set. The article can be read on C# Corner as I did not post it as a blog here, sorry.

App That Reads Out Text For You in WPF

That article is very much similar, because .NET for Windows Store is pretty much similar to what we have as .NET itself! .NET framework (in my opinion!) is very much simple, easy and intuitive as compared to Windows Runtime API set. You can use the same code provided there to get start with the text-to-speech portion, however there are a few differences that I must warn you about. That article also talks about the audio file generation, in this article post I will discuss the development stages in Windows Runtime too. So, follow up with me and learn how to do that!

1. Building text-to-speech part of the application

First section would be to build the basic foundation of the application. I am not going to talk about the UI or UX guidelines at all, instead I will move on to C# code to share how to actually build the application on the backend, so that it actually does some work instead of just showing up its belly. 🙂

I don’t know why, but Windows development team would like to add speech APIs to media technologies and thus they have provided the objects (classes) under Windows.Media.SpeechSynthesis namespace. Please understand this fact, text-to-speech in Windows API is very simple and intuitive task, you don’t even have to do anything to perform a function to generate speech for text. Windows manages everything itself. So, I am going to show you the C# code, simple C# code, that can generate the audio results for the text that you enter in the application.

Initializing the synthesizer

The synthesizer is defined in the above mentioned namespace, you can use it by calling a constructor and passing a language (or using the default languages provided by the Windows operating system; which are installed by the user). In most cases you don’t have to set up the engines, you can get them already set up. But if you would want to change the engines up and down, you can still manipulate the object that you create.

// Namespace addition
using Windows.Media.SpeechSynthesis;

// Create the object here...
var synthesizer = new SpeechSynthesizer();

// You can update the properties, such as voice engine being used.

The next step is just to execute the “Synthesize…” function! This function would return the stream, based on what you pass. You can pass text and SSML; which I will not cover, then engine would return the stream for audio speech based on the parameter.

Modifying the properties

Before the final stage, I want to discuss the properties that you may want to update in your engine to provide a better experience to your users and target a wide variety of audience.

Voices and other stuff

First of all, you should consider that an engine would always require a voice to be installed on the system. Each and every voice that you want to use, must be there on the system before your application can think about using it in your application! That is why, I would recommend that you first of all, consider which language have been installed. I use English language, my family members also do, but my friends don’t. Some prefer French whereas some have Urdu or Hindi languages installed. So, if you would hard code anything in the application it may cause a runtime exception when application won’t be able to build an engine with specified language. In such cases, you can loop through the available languages (voices!)

// Object created above
var voices = synthesizer.AllVoices;

Now you can loop over each language voice and then provide the users an interface to select a language from each one installed on the machine. Also, allow users to install more languages so that they can render the text in audio streams in many more voices. Voices are also based on genders, geographic location, pitch and age. So you can also find out if a specific language is installed or not.

Then each of the item in this array would target the Voice object. This object is another type, VoiceInformation, which holds the information about the voice that gets used to render the text into. The voice (as already mentioned!) can hold information about language it speaks, age and gender based information. You can also select a language based on these parameters if you want to select a language and don’t know which language is installed or don’t want to hard code the language name in your application.

You can then change the voice of the synthesizer to the one you want to use. For example,

// Assume you collected a voice information from the AllVoices list
synthesizer.Voice = voiceFromList;

Then you can continue to the next stage, where you get the stream!

Getting and loading the stream of speech

In Windows 10, you do not get an audio from this API, instead you get a stream of data, audio data, you then need a player to play that stream. Windows 10 has a control named, MediaElement. You can use that player to render the stream for you. Easy way, I would say! The thing is, MediaElement would handle most of the headache for you and you wouldn’t have to work around with the codecs and other byte-management concepts, you just send it as a resource to the media element and it would then preview it.

Even the code to do that is pretty much simple and straight-forward, you only have to specify the stream and the content-type so that MediaElement can render the media correctly. Have a look at the two-line code below:

// Generate the stream
var stream = await synthesizer.SynthesizeTextToStreamAsync(message);

// Set it as a source
mediaElement.SetSource(stream, stream.ContentType);

MediaElement would then render the controls, seek bar and other stuff that it requires.

Screenshot (3078)
Figure 1: Application showing controls and resources for text-to-speech

In the above image, it is clear that MediaElement displays the controls, renders the stream and allows the users to pause or play the content and even seek it through the audio stream. This makes it better for story-reader applications.

So, this was it for the text-to-stream section. Rest of the stuff is just “extra cheese topping” that I don’t want to talk about, I want to focus on generating the audio content to be saved as a file on the machine. So, head over to the next section.

2. Generating audio files for audio speech streams

This part was tough one and I had to work on it for like 1 and a half hour to get it to work! Actually, there is a bit of confusion between the Stream object in .NET and the .NET for Windows Store. That caused me a lot of trouble, but anyways I want to share the achievement with you so that you don’t have to pull your hairs off your head.

Selecting a file

In Windows Runtime (or, Windows Store applications), you cannot just move from here to there like you could in .NET environment. You are abstracted by permission set and thus it is better to allow the user to select and set up a location for you to work. This way, Windows won’t intervene and would allow your application to have permissions as if user were doing them himself.

The following code does that and the object being used is FileSavePicker, which allows user to select a file where your application would save the data. You can specify the type of file, extension and (optionally) the name of the file.

// Create the object
var picker = new FileSavePicker();

// Set up a few settings
picker.DefaultFileExtension = ".wav";
picker.CommitButtonText = "Save";
picker.FileTypeChoices.Add("Audio", new List<string>() { ".wav" });

// Let the user select a file now; and a location
var file = await picker.PickSaveFileAsync();

Then you can use the file selected and load the data in it. The conceptual point comes after this. If the user has selected the file, you now need to:

  1. Open a stream to that file, with read/write permissions.
  2. Create a byte-array for the stream you have.
    1. For this, you would need to use MemoryStream.
  3. Write those byte-array values to the file.
  4. File type would be .wav file so make sure it is that one.
  5. Commit the changes to the file system and you’re done!

Now, implementing the above logic is also very similar part. Have a look at the following code, FileIO object provided by Windows Runtime is a great object to lets us work around with Input/output across the files. So, using the same object I am going to write a block that does what I want it to…

// If user selected a file
if (file != null)
{
    // Create a memory stream
    using (var mem = new MemoryStream())
    {
        // Get the stream object; Stream of .NET
        var strm = stream.AsStream();
        strm.Position = 0;                  // Change the location index to copy from
        await strm.CopyToAsync(mem);
       
        // Convert to array of bytes
        var array = mem.ToArray();
        // Write the byte-array to the file.
        await FileIO.WriteBytesAsync(file, array);
    }
}

Just the above code is required! We’re done. The code when I refactored it, amazed me and I was very much shocked as to why did I not get it in the first place. The code is simple and it does what it is intended to do, so if I convert the above speech stream to audio file, it would be like this.

Screenshot (3103)
Figure 2: FileSavePicker showing the interface to select a file to save the data to.

Screenshot (3104)
Figure 3: Windows File Manager showing the “MyAudio” file just created using the above mentioned application for Windows 10!

So, this way we can store the data in audio file.

Points of Interest

Windows 10 is new, Windows Runtime is also new… Most of the C# programmers are still fond of .NET environment, although Microsoft did provide them with tools to work around in Windows Runtime, but still Windows Runtime API is not as much simple and beautiful as is .NET framework.

This post talks about and shares the information required to build your own text-to-speech application and not just that, it also shares how to convert that audio stream to audio file that can be played later. Of course on this post, I cannot play the file but in real, it does say what I wrote. 🙂

It’s almost end of the month, I may write a new post someday earlier, but anyways, Happy new year folks! 🙂

Developing apps for Ubuntu using Ubuntu SDK

Introduction and Background

In this article I am more focussed to write about applications for Ubuntu platform. I have always wanted to write about the platform, SDK, features and more stuff ever since I started programming for Ubuntu, back 3 months ago. The platform is so catchy, even for script-kiddies, that even I was caught by its catchy features. I do not prefer writing apps where I have to use shell scripts too often. But, Ubuntu is an exceptional case for me though. I have not yet tried using C# or the open sourced .NET Core on Ubuntu but I am sure going to try it some day sooner, and I will update the article for that or write a new one for that one section.

There have been many questions related to Ubuntu programming, graphical UIs in Ubuntu, SDK for Ubuntu etc and I always wanted to make sure that I do share some of my knowledge as an article for community but I was always found busy in other projects and blog etc. that I was not able to actually write it. So, since I am free from any other job, project, I guess before starting my Masters in CS course I should write the article for Ubuntu starters. I am sure you would enjoy the SDK and the article as you read it.

Some light on Ubuntu itself

Ubuntu, if you are unaware of what it is, is a Linux (kernel and Debian) based operating system. So right under that GUI a Linux kernel is being used for the underground stuff. Linux kernel maintains the processes and the communication channels between the operating system and the machine hardware. Machine is totally abstracted from the operating system, and kernel is used (along with a few other stuff) to make sure that operating system runs on every (selected or supported) architecture of machines. For example, you can run Ubuntu on a 32-bits and 64-bits, x86 and other architectures. The processes seem to be alike and the applications that you make for one of the machine runs on other machine too which is running Ubuntu. Why? Because Ubuntu runs at a very high-level in the hierarchy, so the programs that run the application are abstracted from the machine. The OS in this state only acts as the virtual machine, with a byte-code (for example!) that runs in it. The byte-code is compiled to native machine code just-in-time! Due to this fact, the code that you write once is executed on every machine because the virtual machine decides which code to be compiled as which instruction. The instructions for machines differ from one to another.

Some introduction of Linux

Ubuntu is a distribution of Linux, Linux was just a kernel, it is not an operating system. And that is exactly the difference between Linux and GNU. GNU was the project that lacked a kernel, until Linus Torvalds created Linux and GNU guys took that open-source kernel (which, still offers royalty to Mr. Linus) and completed their operating system project. Thus, Linux is the kernel, GNU is the operating system. So, if someone asks you to do something on a GNU based system, do not confuse it with “Hey, but I only know how to do that on a Linux“.

For more: Well, that is it for now for Linux. If you want to learn more about Linux itself, go and read

  1. Minix 3
    Background and a few books that you can get about Minix 3.
  2. Linux
    Background and history
  3. GNU

After reading these, you will have an idea of what is Minix 3, how Linux started and how did it complete GNU. 🙂 I won’t talk more on these, and will move on to Ubuntu for now.

Ubuntu—a Linux distribution

Linux alone would be a favorite operating system for the shell-lovers, and those with a craze for command-line interface. But, for ones like me, if there is no graphical user-interface and no way to click a button to open “This PC”, the OS is not “my type”. Right? There are many distributions of Linux kernel, many companies and organizations has invested their money and time in creating an operating system over Linux kernel. Linux kernel allows them to worry about the operating system and the programs and services that it will offer while kernel manages the low-level services, CPU interrupts, RAM management and other facilities. Latest versions of Linux include many bug fixes, security patches and other loophole fixes so that operating systems have to worry about the code on their ends.

Ubuntu is one of those distributions, and is mostly used on personal computers. Ubuntu is based on Linux (according to the website, and yes, many geeks, it is a Debian-based Linux distribution) and yes, you can use the same features that Linux has, those same user accounts and the commands. But Ubuntu just adds a graphical user-interface on top of that, plus a framework and design to support third-party applications to be developed and ported to the devices. Ubuntu is not just a desktop OS, but also provides services for:

  1. Web servers
  2. Smartphones
  3. Tablets
  4. Cloud management
  5. Quite other options are also available because it is not a one machine based OS.

In my opinion, the concept of Windows 10 is much like Ubuntu’s infrastructure. One operating system to rule it all. So the applications that you create on one device are able to run on multiple devices, just the way Windows 10 applications work, they just need a few tinkering and they are ready to go.

As captured from this thread, where Ubuntu’s architecture is discussed about, the following representation may suffice your needs of understanding the architecture.


Figure 1: Graphical representation of Ubuntu OS from a Linux point-of-view. Drawing the schema for every service and process is almost impossible in a single diagram.

Now, as already said, explaining and connecting each and every service provided in Ubuntu OS or the kernel is almost impossible. So, I will leave you with an abstracted overview that the levels come in a way, like, first there is Linux kernel (skip the machine), then a few services that continue to run and communicate with Linux kernel, then a few UI services that render the graphics on screen for the opened windows and tabs, after that comes your application. These services communicate with the kernel and kernel executes the commands on CPU.

Well, on other hand I have created a much simpler diagram that you may find easier to understand also.


Figure 2: An easier to understand, abstracted overview of Ubuntu OS.

In the above image you can get the overview of Ubuntu OS itself, now if that is some-what clear we can now continue to the main topic, Ubuntu SDK. In the next sections I will walk you through using Ubuntu SDK and how to create an application in Ubuntu SDK for Ubuntu OS.

Ubuntu SDK—Qt creator and a bunch of services

Ubuntu SDK is a collection of a few services that every SDK has, Ubuntu is a Linux based system so an IDE is not a fully-integrated IDE as Windows has, Visual Studio. Ubuntu didn’t come with a full-featured IDE, but not anymore. Ubuntu OS also has a full-featured IDE (special thanks to Qt project) which includes:

  1. Text-editor with syntax highlighting.
    Of course most of the programmers need it, the syntax highlighting includes JavaScript, C++, C and many other languages, including the QML (markup language for Qt applications). Qt is a most widely used IDE and framework for cross-platform development. Qt is used for Windows, Linux (Ubuntu, Debian and Android etc), Mac and mobile phone development. So it has to include the syntax highlighting for a wide-variety of languages.

    • C/C++
    • JavaScript
    • QML
    • XML
    • JSON
    • etc…
  2. Compilers for languages.
    Along with the compilers, it also comes with the markup language and JavaScript parsers.

    • QML allows you to integrate the client-side scripting using JavaScript. So the events are handled using JavaScript and the same pattern is used. Plus, the QML markup language is also so much easy that creating the GUI is not at all a problem.
    • The integrated compilers for C/C++ make it easy to run and debug your application instead of having to execute separate commands for each of these processes.
      • Compile the code
      • Parse the markup
      • Assemble the binaries
      • Create a package
      • Find the executables
      • Run them to see what happens.
    • In Ubuntu, you just have to run the application; or debug it.
  3. Debuggers
    Should you run into any trouble with your application or whether you want to try out the application before publishing it, SDK contains the stuff required.

    • Debugger
    • Profiler
  4. Emulators and devices
    SDK also contains the stuff that would help you to create the emulators and devices, on which you can run the applications on. In this guide, I will use the device that I am using to run the app on.

    • You can create emulators for mobiles, desktop and other platform or architecture where you want your application to run.
    • I will be using Desktop one only in this guide.
  5. Source control
    If you are a team of developers working together to create a project, then you would need source control, every team needs it. Ubuntu SDK has a wide variety of source control ranging from git to Bazaar. You can chose the one that suffices your needs.

    • git is a most-widely used source control, it also allows you to host your code over GitHub. It is fast and is widely used by command-line programmers. Plus, there are many guides already provided for you to learn git.
    • Bazaar is another source control which is mostly used in Ubuntu, I never stumbled upon it in Windows. But, I didn’t find a way to create an account so look for that yourself. 🙂
  6. Publishing tools
    Ubuntu SDK also provides you with facility to publish the applications to Ubuntu Software Center. Where your application can be downloaded by thousands of users!
    Note: There is a commercial version of applications provided, but since I am in Pakistan and do not have a PayPal account I have no idea how that would be done, but that is also simple. Just add the details for your account and they will pay you for the revenue that your application will make.

That is just an overview of Ubuntu SDK, but using Ubuntu SDK and installing it just really very easy. I do love Visual Studio, everyone does, but installing Ubuntu SDK is a very simple and easy task. The size of SDK is also very compact, so downloading the binaries won’t take too much time. Installation is also very robust and fast that it doesn’t really matter what you do, it would take at maximum of 10 minutes; depends on your network and machine.

Installing the SDK

I will assume that you are having Ubuntu installed. You can get Ubuntu SDK two ways,

  1. From the Software Center; where you get to only click a button, “Install” and it gets installed.
  2. or… From the terminal. Where the stuff is processed step-by-step and you are aware of how long it will take and what process is being executed.

I will share “how-to” of both of these procedures to make it clear for you, I personally prefer the terminal way of installing the SDK, they are just 3 commands and you get most of the stuff already fixed up for you!

1. Installing using graphical user-interface

First of all, a section for graphical user-interface lovers. The process is very easy, all you need to do is go the Software Center and install the Ubuntu SDK. Using the software center you would have to only click a single button. Rest of the stuff is managed by the software center itself.

Go to the developer tools, right under their find IDEs. Ubuntu SDK is categorized under there.


Figure 3: Ubuntu SDK listed in the IDEs category of Developer Tools section.

You should click on More Info to get more details on this. This window should come up,


Figure 4: Ubuntu SDK details and a button to Quick-Install it.

You should click on Install if you have gone through the details of this software product. Once you click on that, Ubuntu would ask you for your password to perform super-user actions. It would take some time, it requires both Internet and some time. It would have the SDK installed for you!

2. Installing from the terminal

This is my favorite method of installing the Ubuntu SDK. It doesn’t take much time, but is very powerful and simple way, since it only requires a few commands to install the SDK for you!

Open the terminal from your machine and proceed with installing the SDK,

1. Add the SDK release PPA
$ sudo add-apt-repository ppa:ubuntu-sdk-team/ppa

It will prompt you for a password, enter the password for your user account. Once that is done, proceed with the installation of the SDK package.

2. Install the SDK

Execute the following command to install the SDK:

$ sudo apt update && sudo apt install ubuntu-sdk

This would now look for the packages and other resources on the network to download and setup for the SDK. It does take some time and this is the step that will take most of the time. It depends on your network speed so make sure you have a good network, slow would also work, but slowly. 🙂

Once that is finished, there is no other stuff required to worry about. The SDK is set up. Start it, the terminal way.

$ ubuntu-sdk

There you will have the SDK running in front of you. Yes, it is the Qt creator ported with a few more plugins to work with Ubuntu programming.


Figure 5: Ubuntu SDK start up screen.

In the next section I will walk you through different options that Qt creator (Ubuntu SDK) provides you with for developing the Ubuntu applications. The IDE has many features and many templates for applications that you can use to create the applications. The applications are of wide variety.

  1. Console applications
    If you want to build a program that doesn’t need any graphics or rendering, then you can create a simple C/C++ console application and write the logic for your application.
  2. Services or templates
  3. Graphical user-interface apps
    If you want to create applications that make use of graphics, then these are your options.
  4. Non-Qt projects
    When you need to use the native power of Ubuntu, you can create Non-Qt projects and write softwares that make use of native power for better performance.

The applications created in GUI mode, use QML as the markup language for user-interface and JavaScript as the handler for clients’ interactions. C++ is used as a back-end language for processing complex algorithms and structures. In most cases, JavaScript will suffice for example in case of network requests etc. But in cases where you need CPU to be used, you can make use of C++ language at its best!

Points of Interest—future versions of post

Alright, I think this is enough for this post. Until now you have got the basic idea of Ubuntu SDK, Ubuntu and how to build the applications. You may also have got the understanding of SDK IDE’s environment and other basic tools and packages. That was all this post was meant to provide you with.

In next post about Ubuntu SDK, I will show you how to build different applications on Ubuntu platform. Ubuntu is a very powerful platform to build applications on. From console-based, to services to GUI based applications. The GUI based applications, built using Qt are also very easy in Ubuntu SDK. The QML, C++ configuration and all of that stuff, is very easy and native to understand that even if you have never programmed for Ubuntu, or if you are a web developer you will still get your hands on Ubuntu, pretty quick!

See you in the later posts. 🙂

Creating a “customizable” personal blog using ASP.NET

Introduction and Background

I don’t want to speak too much in this piece of article, instead I just want to demonstrate the presentation that I have to make today. This article is a short piece of “long report” that can be considered as an answer to most common question, “How to create a blog in ASP.NET?”

Well, I find it most compelling that most people are unaware of what a blog itself is, because if they knew they could just play around with ASP.NET to build one for themselves in a night or two. In this article I will discuss a few steps that are needed to be followed while creating your own blog. I am not a good designer, so please forgive the most annoying design that you are going to witness in coming sections. But I promise I will give you an overview of a “blog in ASP.NET”. The facts that I will talk about, or the reason that you should read this article is that this article is not a “specific” how to for my own procedures. Instead, I am writing this article to give you a brief overview of what a blog is, what ASP.NET has in it for you, how you can create it and not just that, but also, how you can create a blog with all that you have. In most cases, you just have a small area for hosting with less HDD space and no database. I will cover what to do in such cases too. Just read the post.

To add some “content” I wrote a Windows 10 client application to consume the blog posts through ASP.NET Web API. I am sure in most cases this Web API thing for ASP.NET blog posts would interest you.

What is a blog, anyways?

Putting the content here simple, a blog is a place where you can share, what you want, anytime you want, with anyone you want! That is a general type of blog being used. Blog is a short form for weblog (logging, makes sense?). More specific types of blogs come depending on your content. Some of blog categories are as below:

  1. Microblogs
    Compact and straight-forward blogs. 140 characters beast, Twitter, is an example of this type.
  2. Personal blogs
    Anyone can create them and they are very much personal, demonstrating only one person. Your website can be your personal blog.
  3. Media blogs
    You can share the images, videos and other multi-media content in media blogs.

So basically a blog is just a website for sharing the content. If you ever created an online website for sharing the content, current work information, regular “diary”, then you have already worked on developing a personal blog. Blog is just a term given to online log system, where you can “log” your regular discussion topics.

So, in this article post I am going to cover a basic application that can act as a blog for someone. As an additional support I will also give you an idea of using ASP.NET’s Web API to promote your blog on native applications, such as a native Windows 10 application that loads the content from your only blog and display the blog posts to users natively.

Getting started with ASP.NET

Since most of the readers are currently not upgrading themselves to ASP.NET MVC 6, I will use ASP.NET MVC 5 (not ASP.NET 5) to show you how to do it. Things are very much similar in ASP.NET MVC 5 and ASP.NET MVC 6. The common things that I have found to change in the coming versions is that ASP.NET is now cross-platform, so if you continue to write the same application by following my article, in ASP.NET MVC 6, you will be able to run it on a server in Ubuntu, or Mac and so on. But that is not a big deal here, is it?

I will be using ASP.NET MVC 5 (not ASP.NET 5!) to demonstrate how to build your own ASP.NET personal blog. But before I get Visual Studio started, I wanted to explain the term “customizable”, which is used in the title of my current article. By the term “customizable” I mean

  1. A blog that is entirely flexible. You can integrate plugins, or update the theme and so on.
  2. A blog that doesn’t rely on a specific third-party framework, even a data source.
  3. A blog that is built just on top of ASP.NET assemblies and doesn’t require you to do anything at all.
  4. A general blogging platform, which can be then altered to create
    1. Social blogging service.
    2. Personal CV house
    3. Your own website to demonstrate your services
    4. So on and so forth.

In simple, the blog can be altered to your own needs and requirements. After all an ASP.NET blog is just an ASP.NET web application that you have modified to suit your own needs.

At this stage I would ask you to create a new ASP.NET project in your own machine, in the next section I will continue with the next things, like create controllers, defining the Views and so on. So, it would be good for you to create a new project at this moment and continue with the article next.

Building the application

First of all, I would like to share how I actually built the ASP.NET web application to be able to host my blog. I am going to use a web interface and an API interface, to be able to consume the blog from multiple native applications. So, I will talk about the ASP.NET programming in this section and then I will talk about the Windows 10 application programming, to actually consume the blog posts and show it to the users in a “native experience”.

Web interface controller

First of all, I will consider building the web interface to be able to showcase the blog on the internet, using a browser. This is what ASP.NET was initially developed for. To build web sites, and web applications. Web applications were introduced a bit later and then was introduced the Web API and so on. So, I am going to use the very basic concepts of ASP.NET MVC to build a simple web application, that can “act” as a blog.

If you are novice to ASP.NET, because most of the times the question (in the title) is asked by a beginner in ASP.NET, so if you have no idea about ASP.NET, please read the previous posts of mine that cover ASP.NET in a great detail and would help you in understanding and learning every bit of ASP.NET programming, as from a beginner’s perspective.

  1. Understanding ASP.NET MVC using real world example, for beginners and intermediate
  2. Novice to MVC? Read this… (ASP.NET MVC is implementation of MVC pattern of software development, this post talks about MVC not ASP.NET MVC)

I will continue to share more of my articles and posts, as the topic proceeds. I would recommend that you read the above posts if you are new to ASP.NET, most of the concepts like Controller, Views and Models may cause a confusion to you, if you are a newbie!

Almost there…

I am very much fan of JSON data, I prefer using JSON over SQL databases and thus I am a fan of Newtonsoft.Json library. So, please consider installing the library before moving further. This library would be the backbone for our data source.

PM> Install-Package Newtonsoft.Json -Version 7.0.1

Once this package gets installed, please continue to the next section.

1. Build the model for application

In my case, I always prefer building the models first. This gives me an idea of building the controllers and then building the views for the application. So, I would also give you a tip, to always build the models, data structures first and then continue to build the rest of the stuff.

The model we need is just a model for the blog post. So, the structure would just be as easy as the following,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using Newtonsoft.Json;

namespace PersonalBlogTemplateWithServices.Models
{
     public class BlogPostModel
     {
         // General properties
         public int ID { get; set; }
         public string Title { get; set; }
         public string Content { get; set; }
         public List<string> Tags { get; set; }

         // Time based properties
         public DateTime CreateTime { get; set; }

         // Other properties and settings may include UserID, RoleID etc.
      }
 
      // The class to manage the data-sources
      public class PostManager
      {
          // Define the members
          private static string PostsFile = HttpContext.Current.Server.MapPath("~/App_Data/Posts.json");
          private static List<BlogPostModel> posts = new List<BlogPostModel>();

          // The CRUD functions
          public static void Create(string postJson)
          {
              var obj = JsonConvert.DeserializeObject<BlogPostModel>(postJson);

              if(posts.Count > 0)
              {
                  posts = (from post in posts
                           orderby post.CreateTime
                           select post).ToList();
                  obj.ID = posts.Last().ID + 1;
              } else
              {
                  obj.ID = 1;
              }
          }

          posts.Add(obj);
          save();
      }

      public static List<BlogPostModel> Read()
      {
          // Check if the file exists.
          if(!File.Exists(PostsFile))
          {
              File.Create(PostsFile).Close();
              File.WriteAllText(PostsFile, "[]"); // Create the file if it doesn't exist.
          }
          posts = JsonConvert.DeserializeObject<List<BlogPostModel>>(File.ReadAllText(PostsFile));
          return posts;
      }

      public static void Update(int id, string postJson)
      {
          Delete(id);
          Create(postJson);
          save();
      }

      public static void Delete(int id)
      {
          posts.Remove(posts.Find(x => x.ID == id));
          save();
      }

      // Output function
      private static void save()
      {
          File.WriteAllText(PostsFile, JsonConvert.SerializeObject(posts));
       }
    }
}

In the model , I have the following attributes that can be used to identify or describe the blog post at the instance.

  1. ID
  2. Title
  3. Content
  4. Tags (is an array; List)
  5. CreateTime (used to sort the items)

Great, we now have a model, and now we can continue to write the rest of the logic for our application. The model implements the CRUD functions, that we can call from external objects, from both, web interface and from Web API interface. This would allow us to manage the data layer in this class.

2. Creating the controller

Alright, first of all, create the controller. The controller would have the actions that we need to perform in our blog. Please pay attention to the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using PersonalBlogTemplateWithServices.Models;
using Newtonsoft.Json;

namespace PersonalBlogTemplateWithServices.Controllers
{
    public class BlogController : Controller
    {
        // GET: Blog
        public ActionResult Index()
        {
            // Read the list
            var blogs = PostManager.Read();
            if (blogs == null)
            {
                 ViewBag.Empty = true;
                 return View();
            }
            else
            {
                 // Just for sorting.
                 blogs = (from blog in blogs
                          orderby blog.CreateTime descending
                          select blog).ToList();

                 ViewBag.Empty = false;
                 return View(blogs);
            }
        }
 
        [Route("blog/read/{id}")] // Set the ID parameter
        public ActionResult Read(int id)
        {
            // Read one single blog
            var blogs = PostManager.Read();
            BlogPostModel post = null;
 
            if(blogs != null && blogs.Count > 0)
            {
                post = blogs.Find(x => x.ID == id);
            }

            if(post == null)
            {
                ViewBag.PostFound = false;
                return View();
            } else
            {
                ViewBag.PostFound = true;
                return View(post);
            }
        }

        public ActionResult Create()
        {
            if (Request.HttpMethod == "POST")
            {
                 // Post request method
                 var title = Request.Form["title"].ToString();
                 var tags = Request.Form["tags"].ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                 var content = Request.Form["content"].ToString();

                 // Save content
                 var post = new BlogPostModel { Title = title, CreateTime = DateTime.Now, Content = content, Tags = tags.ToList() };
                 PostManager.Create(JsonConvert.SerializeObject(post));

                 // Redirect
                 Response.Redirect("~/blog");
            }
            return View();
        }

        [Route("blog/edit/{id}")]
        public ActionResult Edit(int id)
        {
             if(Request.HttpMethod == "POST")
             {
                 // Post request method
                 var title = Request.Form["title"].ToString();
                 var tags = Request.Form["tags"].ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                 var content = Request.Form["content"].ToString();

                 // Save content
                 var post = new BlogPostModel { Title = title, CreateTime = DateTime.Now, Content = content, Tags = tags.ToList() };
                 PostManager.Update(id, JsonConvert.SerializeObject(post));

                 // Redirect
                 Response.Redirect("~/blog");
             } else
             {
                 // Find the required post.
                 var post = PostManager.Read().Find(x => x.ID == id);

                 if (post != null)
                 {
                     // Set the values
                     ViewBag.Found = true;
                     ViewBag.PostTitle = post.Title;
                     ViewBag.Tags = post.Tags;
                     ViewBag.Content = post.Content;
                 }
                 else
                 {
                     ViewBag.Found = false;
                 }
             }

             // Finally return the view.
             return View();
         }
    }
}

The above code, is enough! This code contains the code that you may be needing. Now, I think I need to explain the code a bit.

I have implemented the CRUD functions, in this manner, I created the functions that would allow me to create a new post, read the list of posts, read a single post at the web page or perform other functions, like update the post. You can also see, that most of the codes and functions are being called from the model. That is why, I designed the model before I created the controller. I think now you understand the importance of a model before controller.

The controller would simply capture the request, extract the data from it and then pass the data and request over to the Model. The model would then perform as per our request and return a response, which can then be sent back to the client. The purpose of such a design, is to create a web application being consumed over by Web API too. In the later sections I will consider sharing that too.

Until now, the web application is able to show us messages on the blog. If we have created a post, it will show us the post otherwise it will show us a message that there is no post currently available.

3. Creating the views

Views are simple enough to be understood easily! If you have been developing using HTML, I won’t explain them. If you haven’t, go learn! 🙂

Default page…

The default page for the blog would be simple one, it would either enlist the blog posts otherwise show a message.

For this page, I would instead show the HTML code, and for the rest of the pages I will show the images, because I want to demonstrate how to use the actions.

@model List<PersonalBlogTemplateWithServices.Models.BlogPostModel>
@{
    ViewBag.Title = "My Blog";
}

@if(ViewBag.Message != null)
{
    <h4>@ViewBag.Message</h4>
}

@if(Model == null || Model.Count == 0)
{
    <h4>Blog empty</h4>
    <p>Either under development, or author is busy. Visit back again later! :-)</p>
    <a href="~/blog/create">Create new post</a>
}
else
{
    <h4>My blog</h4>
    <p>Read my blog posts below...</p>
    // Content is available.
    <a href="~/blog/create">Create new post</a>
    foreach (var post in Model)
    {
       int tagIndex = 1;
       <h4><a href="~/blog/read/@post.ID">@post.Title</a></h4>
       <p>
       @foreach (var tag in post.Tags)
       {
           if(tagIndex == post.Tags.Count)
           {
               <span class="tag"><a href="~/blog/tag/@tag">@tag</a></span>
           }
           else
           {
               <span class="tag"><a href="~/blog/tag/@tag">@tag</a></span>
           }

           tagIndex++;
       }
       </p>
   }
}

The page uses the conditional values from the controller. You may have noticed the value from Controller, which is passed as a model (of type of the BlogPostModel). I have checked against that, to see if there are any posts in the data source. That is pretty much simple and straight-forward. The main thing to see, if what happens if there is a new post in the data source. Consider the next section, please!

Creating the post

When you create a new post, you follow the hyperlink, which takes you to a page where you have created a form and so on. I am not much a designer-type, so the UI is very ugly. You can make it better if you want to.

The view for “C” in “CRUD, is something like this.

@{
 ViewBag.Title = "New Post";
}

<h2>Create new blog post</h2>

<form method="post">
    <label>Title</label>
    <input type="text" name="title" style="" class="form-control" placeholder="The headline goes here..." /><br />
    <label>Tags</label>
    <input type="text" name="tags" style="" class="form-control" placeholder="Separate each tag using a comma ','." /><br />
    <label>Content</label>
    <textarea name="content" class="form-control" style="height: 300px;" placeholder="What would you like to write?"></textarea><br />
    <input type="submit" style="width: auto; font-weight: 600;" value="Post" /><br />
</form>

Very simple though, yet powerful! Power is in your hands. Add some, or leave it if you do not want to share the admin panel with anyone. 🙂 Once this page gets loaded, it takes the following web page shape.

Screenshot (219)
Figure 1: Create a new blog post page. Form is filled.

The above HTML takes this shape. The HTML looks clean because of hard work of

  1. ASP.NET team for providing a template.
  2. Bootstrap guys, Twitter bootstrap is being used here (is provided along with ASP.NET template)

You can now submit the post. Alright, until now things are pretty neat and simple. Do you have any questions? Please re-read this section. 🙂

Reviewing the default page now

If you go back to the default page now, you will see that the blog would now enlist the posts (currently only 1). The following is the image, you already have the HTML for this page.

Screenshot (220)
Figure 2: Default page showing one blog in the list. 

Now the page is able to demonstrate that we have a post, it displays the tags and name. Nothing else. After all, why would we show anything else on the default page?

Reading the blog posts, one by one

If you could read the HTML for the default page, you will see that the title of the blog post is actually a URL to the blog post, to be read. I have created the action for that (please read the controller code for Read action). This would let us now read the content,

Screenshot (221).png
Figure 3: Reading the post, shows date time, content and tags. 

This is how I display the content. I agree, a very bad design. But I am very bad at designing the web applications. (I know, my first attempt went wrong because IDs were null and… Ah, you get it the second time, didn’t time? Quit whining!)

I used the following HTML code for this, the thing was that I just wanted to display the blog post, in a very simple way. Indeed in your case, you will write something much more useful. But, at the moment, just read this.

@model PersonalBlogTemplateWithServices.Models.BlogPostModel
@{
    ViewBag.Title = Model.Title;
    var tagIndex = 1;
}

<h4 style="font-weight: bold;">@Model.Title</h4>

<p>@Html.Raw(Model.Content.Replace("\r\n", "<br />"))</p>
<p>Posted by &mdash; Afzaal Ahmad Zeeshan &mdash; on @Model.CreateTime.ToString("MMMM dd, yyyy 'at' hh:mm tt")</p>
<p>
    Tagged under:
    @foreach (var tag in Model.Tags)
    {
        <span class="tag"><a href="~/blog/tag/@tag">@tag</a></span>
        if (tagIndex == Model.Tags.Count)
        {
            // In the end, write the edit hyperlink
            <span><a href="~/blog/edit/@Model.ID">Edit</a></span>
        }

        // Finally increment the index
        tagIndex++;
    }
</p>

So, this code would give us the post. I have many things hardcoded, like, “Posted by &mdash; Afzaal Ahmad Zeeshan &mdash; on {Date Time}”. You can change it, to see who is the author and so on. There are many other things to be taken care of.

One thing to understand is that your HTML is not the same that gets saved in the data source. So, you might need to re-consider the HTML, then render it using Html.Raw function. Have a look at the following code, for example,

<p>@Html.Raw(Model.Content.Replace("\r\n", "<br />"))</p>

Now, each of the occurrence of “\r\n” would be replaced with the breakline object in HTML. This way, you can re-build the HTML and show it as plain text on the HTML web page.

Updating the posts

The final concept that I will be talking about here would be of updating the posts. Updating is similar to creating the new post, but just that you also provide the previous data that you are having. Title, content and other stuff can be provided and then user is allowed to update them as required and then you save it back to the data source.

I have used the same HTML form in this case,

@{
 ViewBag.Title = "Edit the post";

 var tags = string.Join(", ", ViewBag.Tags as List<string>);
}

<h2>Edit the post</h2>

<form method="post">
    <label>Title</label>
    <input type="text" name="title" style="" class="form-control" value="@ViewBag.PostTitle" placeholder="The headline goes here..." /><br />
    <label>Tags</label>
    <input type="text" name="tags" style="" class="form-control" value="@tags" placeholder="Separate each tag using a comma ','." /><br />
    <label>Content</label>
    <textarea name="content" class="form-control" style="height: 300px;" placeholder="What would you like to write?">@ViewBag.Content</textarea><br />
    <input type="submit" style="width: auto; font-weight: 600;" value="Post" /><br />
</form>

This is similar to what we had previously. But it renders along with the previous data we had.

Screenshot (222)
Figure 4: HTML page showing the form to edit the previously updated post.

As you can see, the post contains the previous data, but also allows me to update the post. This is useful, in cases when you want to update the post. I am adding a new paragraph line, which would then be rendered as it is being written.

Tip: This is not WYSIWYG editor, just a plain-textarea. You should get a WYSIWYG editor if you want to be able to use the full power of HTML in your post.

Now, once I will submit this, it would get published as this version. Please revise the controller action,

if(Request.HttpMethod == "POST")
{
    // Post request method
    var title = Request.Form["title"].ToString();
    var tags = Request.Form["tags"].ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
    var content = Request.Form["content"].ToString();

    // Save content
    var post = new BlogPostModel { Title = title, CreateTime = DateTime.Now, Content = content, Tags = tags.ToList() };
    PostManager.Update(id, JsonConvert.SerializeObject(post));

    // Redirect
    Response.Redirect("~/blog");
 }

This demonstrates, how you will update the post. Once again, we are using PostManager, the object we created in our model to be able to perform the actions. The post is now updated, have a look at the revisit to the post preview. Screenshot (223).png
Figure 5: Updated post preview.

This now shows the updates being made. It is also clear as to how the new line is added to the post. Pretty simple it was, but I wanted to demonstrate the concept of this too.

Adding new posts

One more thing is, to add new posts. This is same, requires just a view. I am about to give you an overview of adding new posts, multiple posts and how does this preview them on the default page.

Screenshot (224).png
Figure 6: Creating a new blog post, second one.

This is similar, the only thing to understand is how is it rendered on the blog.

Screenshot (225).png
Figure 7: Two posts being previewed.

The thing that I wanted to share here, is that ASP.NET won’t automatically sort the posts, you would have to do that yourself. If you pay attention to the LINQ code, you will understand it.

// Just for sorting.
blogs = (from blog in blogs
         orderby blog.CreateTime descending
         select blog).ToList();

This would now sort the blogs, a descending order. That is why, “Two posts” shows above, whereas in the JSON data it would come after the “First blog post!” But we have now sorted the list as per our requirements.

Heading over to Windows 10 application and Web API

Before I actually head over, I want to make a final post, that would be read in the application! Please see the following image, then we continue to the next section.

Screenshot (226).png
Figure 8: Final post online.

Web interface has been discussed enough, the next sections will talk about the Web API and Windows 10 application programming.

Further reading:

If you want to get more in-depth information, please read the following documents and articles.

  1. A tip for ajax developers in ASP.NET MVC framework
  2. Getting Started with LINQ in C#

Web API and Windows 10 client application

In this section, I will first talk about the ASP.NET Web API and then I will build the application to consume the API and show the blogs. In the client application, we do not need any functions, like create, update etc. We just consume and display the data, so the client application won’t have enough functions but it would display the content.

Building the API

Actually, the API is simple and does not need anything to be done! The application has already been completed, so our API would only redirect to the application and load the data from the model and return it. API does not need to have any HTML data or CSS stylesheets, instead API just returns the data in JSON or XML format. I personally recommend and always will recommend using JSON. XML is a very heavy format and is also not efficient. JSON is much simple, lightweight and portable format!

The API is just a controller, with the same actions that we need and a return-type. Since we do not need any functions but C (from CRUD), I defined the API to be as simple as,

using Newtonsoft.Json;
using PersonalBlogTemplateWithServices.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace PersonalBlogTemplateWithServices.Controllers
{
    public class BlogApiController : ApiController
    {
        // In this controller, we just need the Read functions. Nothing else!
        // We do not need the clients to be able to write or update the blogs... Just read them

        [HttpGet]
        [Route("blog/api")]
        public List<BlogPostModel> Get()
        {
            return PostManager.Read();
        }
    }
}

Small, but enough.This would let us consume the API from our client application. There is also no need to edit the API configuration, because I have provided the Routing scheme to the function.

[Route("blog/api")]

This would automatically get routed to this URL. The rest of the functionality is to be provided by the application.

One thing to note, is that this function again, reads the data from the model and returns is, as a collection. This would then be translated as JSON data later. So our application will be able to use the JSON converters to get the data from the API and render it on the application.

I hope things for API are clear upto this stage! If not, please re-read. I think the post is pretty much simple. 🙂

Building the client application; Windows 10 application

Great, until now you have learnt how to build the online blog, that has a web interface and an API interface. I will continue with the next post, to teach you how to consume the API, the post has gone way more than I was expecting (it overwent 4k words).

Read the above article and leave your feedback, I would love to hear it!

Points of interest

Thank you for reading the post, I have shared a common, yet easy and simple way to build your own blog. The post contains the information that you may need to have to create your own online personal blog. I have not shared any third-party library because I want you to be able to add your own. The blog is built on top of native ASP.NET frameworks.

In a later post, I will also share the common concepts for building the data sources, so that the only dependency of “Newtonsoft.Json” would also be removed from this project. Until then, please bear with me.

One more thing, the text editor used is plain-textarea, you can replace it with your favorite WYSIWYG editor to be able to use the power of HTML, then render the HTML on the screen.

In coming days, I will write two more posts:

  1. Consuming the Web API from Windows 10 application.
  2. Building your own custom data sources.

Stay tuned for more of such content! 🙂

Using C# for cross-platform development

Introduction and Background

I wrote a bunch of articles about C# programming, but all of them were Windows or .NET oriented. I want to write an article about C# programming on multiple platforms. C# is a very powerful and strong programming language with a very solid foundation over programming concepts. The language is indeed designed to work on high-level applications and initially it was designed to run for .NET applications only, but as time passed it got introduced to other platforms and applications too.

In this article, I will share a few things that you can do on Windows and Linux. I don’t own a Macintosh so I won’t be able to share that concept but I guarantee the procedure to program a Mac application in C# is also similar to this one! Cross-platform itself means to be able to do everything that you can do one platform, on another one too. C# is able to do the same, on every platform. The concept only requires to modify your compilers to be able to accept new environments, same thing applies to C++ and Java and other similar high-level programming languages. C# also works in a similar manner. The concept of C# compilation is that the code doesn’t compile down to machine code. Instead C# code is compiled down to a bytecode, which is later assembled and translated to machine code by the virtual machine; .NET’s virtual machine! That is what makes C# programming language very powerful and at the same time flexible and portable programming language.

If you are a “diagram” lover, please view the following image:

IC15013
Image from MSDN article: Introduction to the C# Language and the .NET Framework

The assemblies are sent to virtual machine, who then translates the code using their metadata and other stuff all the way down to the metal. That is exactly, why it is possible to execute the same C# code on every machine, every platform and every architecture (x86 and x64). Although the instructions are different, but bytecode helps C# to be executed on any machine! In this article, I am going to use the same concept (and a tool) to help you write native applications on other platforms, too.

References:

If you want to learn more about C# or cross-platform, you may read the following contents,

  1. Cross-platform programming: An open-source overview
  2. Introduction to the C# Language and the .NET Framework

Cross-platform tools for C#: Mono Project

If you started programming on Windows, you might have used Visual Studio as your first IDE and specifically, chances are that you started programming using C# programming language. C# is widely used, that it managed to get attention of developers from other platforms and systems too. Mono Project is one of such products which came up not in a near future, but had been known since a while. Mono Project was started to provide C# developers a cross-platform experience. Mono Project can be installed on the following platforms:

  1. Windows
  2. Linux
    This counts any of the distro of Linux kernel, Ubuntu, Red Hat and so on.
  3. OS X

Mono Project can then be used to compile the C# projects as a native application on that platform. In my opinion, that is pretty much self-explanatory, each platform has the resources and architecture information and the related binaries used to target the platform, Mono Project uses those resources and compiles the project down to bare metal components.

In this post I am going to use Mono IDE, not Visual Studio, because Mono is a cross-platform C# development environment, whereas Visual Studio is a Windows-only tool. But C# can be used on other platforms, all thank you to Mono Project! Using Mono Project you can build,

  1. Console applications in C#
  2. Graphical applications using C#
  3. ASP.NET web applications

Mono Project also allows you to use VB.NET, but I won’t be talking about that, instead I am going to cover C# only.

Getting starting…

First of all, you may want to install the Mono on your environment. If you are using Windows, then (in my opinion), you should consider using Visual Studio. You can get Visual Studio Community for free if you are a student, learner, open-source developer or a small team. That’s the beauty of Visual Studio. But, if you are going to develop applications using C# where Visual Studio is not supported, you should consider downloading and installing Mono Project, which includes everything starting from the Mono documentation, Mono IDE and the compilers for the languages.

I did say, that you should try Visual Studio on Windows but if you want to learn other environment on Windows, you can for sure install Mono on your Windows environment too. It would give you a much better experience to program C# applications on non-Windows environment and all by just using terminal or command-line commands to compile and use the application. I have learnt a lot of things by using the terminal in Linux environment, so I would also recommend you guys to give it a try!

Installing Mono

Installing the Mono is different on different environments, on Windows and Mac it is pretty much same. All you have to do is to download the installer and run it. It installs everything for you. But on the environments, like Linux you have to create repositories and then start installing the packages. That takes a bit of time. I will show you how to do that on all of the environments!

1. Installing on Windows/OS X (Mac)

The procedure to install on Windows and Mac is similar. Just download the package and then go install it, by executing the installer. It would install the Mono project including all of the dependencies, files and executables. You can then use your Mono project to build C# applications on platforms, other than .NET themselves.

Install Mono on Windows
Install Mono on Mac OS X

2. Installing on Linux (or Linux distros)

Now the things here get complicated. In Linux, you are going to use the terminal and then execute the commands to build the repository systems and then install the packages, for every Linux distro, it is different process so that may also cause a trouble and that is why I won’t be sharing a single script “to rule it all”, instead I will be providing you with a link that contains all of the scripts that you should execute to get your job done! In the Linux environments, you can execute commands differently to have your job done! Head over to this page to find out which command set would work on your environment. That page would give you the commands that you can execute to set up the environment. Rest assured, now you can execute the following command in your own environment to install the Mono assemblies.

sudo apt-get install mono-complete

This command may also differ based on the environment, some may use yum, some may use rpm or others. Please refer to your own installer commands.

Wait, I cannot find the IDE. Where is it?

Correct, until now, you have only installed the binaries and assemblies required to make Mono workable. You have not yet installed the IDE. Until now you just installed the compilers and binaries. To install the IDE, execute the following command:

sudo apt-get install monodevelop

Now, head over to your IDE that was recently installed and start it! You are going to love it, and well, the folks have seriously put some great efforts in it.

Screenshot (1547)
Ubuntu Studio showing the list of IDEs.

Screenshot (1549)
Hello world project opened in Mono Project.

In the next step, I will share a few example of using C# to build cross-platform applications. Head over to the next step!

References:

I am attaching a few good links in this section too,

  1. Visual Studio Community
  2. Mono Project — Official Website
  3. Install Mono

Building the applications

In this section, I will show you three sample codes for C#, which you already do know in .NET environment. The samples are not to give a new task in C#, but rather just a simple code, to help you understand how C# can be used to execute commands on different environments, different platforms and so on.

Hello world from Linux

First of all, I want to make my application greet me, from a Linux environment, using the same code that you would use on .NET environment. You all are already aware of the following code,

using System;
using System.Net.Http;

namespace HelloWorld
{
   class MainClass
   {
        public static void Main (string[] args)
        {
            Console.WriteLine ("Hello, who's there?");
            string name = "";
            name = Console.ReadLine ();
            Console.WriteLine (string.Format("Hello {0} from Linux using C#.", name));
        }
    }
}

Aren’t you? Yes, it’s the same “elementary” C# code to greet someone! This time, running on a non-.NET environment. This would just prompt me for some input and then continue to do what it was intended to do.

Screenshot (1550)

Pretty simple, right? But notice that this code now runs on native Linux environment. There is no underground .NET frameworks supporting it. In real, it is the Mono Runtime that actually does the processing underground. Please read the reference to Mono Runtime in the references below.

C# programming using collections

Collections are a great resource in any application, you can accept a long record of user data in a single object, that is of type: Collection. C# has been providing generic programming objects, for collections. Collections are much better than arrays, because collections are mutable, unlike arrays. In this section, I will show you how to write an application that consumes the collections.

I created a class object, to hold the values of the people. Then I created a list to hold “some” people and then printed their values. It is also a similar code.

using System;
using System.Net.Http;
using System.Collections.Generic;

namespace HelloWorld
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            // Create the list of the people.
            var people = new List<Person> ();
            people.Add (new Person { Name = "Afzaal Ahmad Zeeshan", Age = 20 });
            people.Add (new Person { Name = "Sofiya Zeeshan", Age = 19 });
            people.Add (new Person { Name = "Daniyal Ahmad Rizwan", Age = 15 });
            people.Add (new Person { Name = "Eminem", Age = 43 });

            // Printing the details for people.
            foreach (var person in people) {
                Console.WriteLine (person);
            }
        }
    }

    class Person {
        // Provide the attributes.
        public string Name { get; set; }
        public int Age { get; set; }

        // Override the default ToString
        public override string ToString ()
        {
            return string.Format ("[Person: Name={0}, Age={1}]", Name, Age);
        }
    }
}

How this code actually ran, please see below.

Screenshot (1551)

It just prints everything and then terminates. These were a few things that were basic. Let’s try out if C# still has the same power or not, why not try out Internet access in C#?

Using C# to access online resources

Now in this section, I will be referring an online API of my own to access the data. This may make things a bit tough, if you have never worked with System.Net namespaces in .NET framework. I will be using an object from these namespace and then I will call the functions to actually download the data from an online API and then I will print it.

Linux also provides the similar manner to use the TCP/IP protocol that is why C# code written for Windows would work in a similar manner with Linux and other Mac’s OS X system.

In the following code, I have also used another concept in C#, asynchronous programming. Mono supports async models of C#, and you can avail the services right in the IDE, just like Visual Studio. The code I have used is like the one below,

using System;
using System.Net.Http;
using System.Collections.Generic;

namespace HelloWorld
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            downloadAndPrint ();
        }

        private static void downloadAndPrint() {
            System.Threading.Tasks.Task.Run (async () => {
                using (var client = new HttpClient()) {
                     Console.WriteLine ("Downloading the data...");
                     var message = await client.GetStringAsync("http://afzaalahmadzeeshan.gear.host/api/sample");
                     Console.WriteLine();
                     Console.WriteLine(message);
                }
            }).Wait();
            Console.WriteLine ("Exiting the function..");
        }
    }
}

The above code simply downloads the response as string and prints it. This shows, that C# not only just works in the console, but it also works perfectly with the protocols on different systems. All of this is managed by the Mono Runtime.

Screenshot (1552)

So, I guess this is enough to demonstrate how C# can be used.

References:

A few topics that you should consider reading:

  1. The Mono Runtime
  2. HttpClient Class
  3. List<T> Class
  4. Asynchronous Programming with Async and Await

Points of Interest

In this article, I have demonstrated how you can use C# to develop cross-platform applications. There is no need to learn multiple languages to target multiple frameworks and application systems. You can use one single programming language, even C#, and write native applications on multiple platforms.

Although C# doesn’t execute natively, even on those platforms. Mono Runtime is responsible for executing the applications on those platforms. Just like .NET’s virtual machine or Windows Runtime executes C# code on Windows environments. On other platforms (and including Windows if compiling and using Mono), you can use Mono Runtime to target the platforms and make use of .NET libraries and lightweight programming model of C# programming language.

I hope you like this article, wait up for the next articles, or write back to me to get more. 🙂