How to create dynamic XML sitemaps in ASP.NET MVC

When developing web applications (especially websites), some rules have to be obeyed. One of those rules are Sitemaps. Sitemap is an essential to tell more about a website to search engines. According to sitemaps.org, sitemaps are an easy way for webmasters to inform search engines about pages on their sites:

Sitemaps are an easy way for webmasters to inform search engines about pages on their sites that are available for crawling. In its simplest form, a Sitemap is an XML file that lists URLs for a site along with additional metadata about each URL (when it was last updated, how often it usually changes, and how important it is, relative to other URLs in the site) so that search engines can more intelligently crawl the site.

Implement sitemaps in ASP.NET MVC is very easy and this post is going to cover it.

There are several ways to implement sitemaps in ASP.NET MVC. Since sitemaps are just XML files, they can be generated using XLINQ (LINQ to XML) technology.

The process of creating a sitemap in a website can be divided into the following steps:

  • Get a list of URLs which has to be included in the sitemap.
  • Create the sitemap XML in code.
  • Return the created XML to the user.

Note: You don’t really need to create an actual XML file. All of the process above can be done inside a controller action.

The first step is to get the list of objects we want to create the sitemap based on. In this post, I have a list of categories which have a unique URL based on its ID. So:

public ActionResult SiteMap() {
    var items = categoryService.SelectAll();
}

After that, it’s time to create the XML document. Sitemaps must have a specific format; so, they can recognized by search engines. The following is a valid XML sitemap:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
   <url>
      <loc>http://www.example.com/</loc>
      <lastmod>2005-01-01</lastmod>
      <changefreq>monthly</changefreq>
      <priority>0.8</priority>
   </url>
</urlset>

As you know, creating such XML file in LINQ to XML is a very simple task to do:

public ActionResult SiteMap() {
    XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";
    const string url = "http://example.com/Category/{0}";
    var items = categoryService.SelectAll();
    var sitemap = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"),
    new XElement(ns + "urlset",
        from i in items
        select
        new XElement(ns + "url",
            new XElement(ns + "loc", string.Format(url, i.CategoryId)),
            new XElement(ns + "lastmod", String.Format("{0:yyyy-MM-dd}", DateTime.Now)),
            new XElement(ns + "changefreq", "always"),
            new XElement(ns + "priority", "0.5")
    )));
}

As you can see in above code, we’ve simply created an XML file in sitemap format. Now we can return it to the user.

return Content("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + sitemap.ToString(), "text/xml");

Look at the code above. When creating normal actions, we usually return a View or PartialView objects; but, since we’re going to return a content, we use the Content method. Content method requires two arguments. The first argument is the content we’re going to return to the user as string and the second is the content’s MIME type.

Hope it helps.

The most essential apps I use everyday

Since I purchased my first ever smartphone which was an iPhone 3G, I started using some apps to help me get organized, learn more, stay in touch with my friends and family and have fun on my device.

During these four years I have used and tried a lot of apps and selected some of them to fulfill my needs. Nowadays, I can’t live without some of these apps. In this post I am going to share some of the most effective apps I use everyday. I thought this might be useful for you as well.

1. iPhone’s official Mail App

Mail appOne of the most important applications I use on my iPhone is the Mail app. The built-in iPhone mail app is not as feature-rich as some other third-party applications but I think its features are enough. It covers all of my expectations including the following:

  • It let me setup multiple accounts on it. Currently, I have setup my iCloud account and my main (i [at] ramezanpour [dot] net) account on it.
  • It supports signatures.
  • Its has a feature called VIP; so, you can add the most important people you’re communicating with in it. Email from those people will be shown bolder than others; also, they will be placed in a separate folder called VIP.
  • It supports all major email providers including GMail, Yahoo, AOL, Outlook and also Exchange.

2. Podcasts

Podcasts appOne of the iOS’s most unique features over Android or other mobile operating systems is the podcast. Podcasts app will let you have all of your favorite podcasts in one place. I usually connect my iPhone to my car’s stereo and listen to my favorite podcasts instead of listening to music.

Podcasts are available in a wide range of categories such as music, news, arts, education, science and technology. I have subscribed to some science and technology podcasts and listen to them when on my way to work or returning home. My wife also likes some of them; so we listen to them together.

3. Viber

ViberAlmost all of friends are using Viber nowadays. It’s the most popular messaging app in Iran. According to a report, more than 40 million Iranians are using Viber these days. Viber let me stay in touch with my friends and family at a very low cost. It’s not the best messaging app (I perfer Whatsapp messenger) but since most of my friends are using it’s difficult to find them on other messaging apps.

4. Skype

SkypeAlthough Viber covers all of my text needs; but, when it comes to voice and video messaging, Skype is by far the best option. The voice quality is awesome (Even with Iran’s bad internet service) and the service is almost free. I use Skype to talk to some of my friends who live overseas. Beside its mobile app, Skype is also available for desktop computers as I am currently using it in my Windows and Mac machines.

5. Evernote

Evernote“Getting used to productivity apps is always a very hard thing to do but once you get used to them, your life gets brighter.” - Mohammad M. Ramezanpour

Evernote is one of those apps I use almost everyday. Since I use Evernote I don’t use papers anymore. I use Evernote for taking notes and creating checklists. One of the good features of Evernote is the ability to share a note or notebook with someone else. My wife has created a shopping list in Evernote and shared it to me. Every time she needs something at home, she adds a new item to that list. We go shopping almost every week and purchase things according to that list.

6. DropBox

DropBoxDropBox is the best online cloud storage. I have been using SkyDrive (OneDrive) and Google Drive but in my opinion, non of them were as powerful as DropBox. DropBox is available in all operating systems. I use it in my iPhone, Windows and Mac devices. DropBox is very simple and easy to use. One of the coolest features of DropBox in comparison with other cloud storage apps is its “Lan Sync” feature which let users to share files in-between without using the internet bandwidth. all of the files will be transferred via local network.

I use some other apps but these 6 apps are very essential for me. What apps do use the most? Please share your list by commenting down below.

Hope it helps.

Create an on-demand VPN connection programmatically in iOS 8

A while ago, I published a post about configuring and managing VPN connections programmatically in iOS 8. By default, established VPN connection will be disconnected if user iOS device goes to sleep to save battery life. To avoid this, Apple introduced a feature called on-demand; so, iOS will get connected to VPN whenever it needs to connect to the internet.

Well, it can be implemented programmatically too using the NetworkExtension framework and that’s exactly what this post is all about. In this post, I am going to create an on-demand VPN connection using NetworkExtension; therefore, VPN connection will be established whenever an app opens a network connection.

Note: I am not going to describe how to create a VPN connection in this post. If you’re not familiar with creating a VPN connection programmatically, please take a checkout my post.

Turn on On-Demand

The first thing you need to do is to tell the NetworkExtension framework that you want to create an on-demand connection. To do so, set the onDemandEnabled property to YES:

[[NEVPNManager sharedManager] setOnDemandEnabled:YES];

turning on-demand on is not enough. You will also need to tell the OS when exactly you want on-demand to be enabled. To do so, you will need to assign some rules to your configuration. These rules called “On-demand rules”:

What are On-demand rules?

On-demand rules are set of attributes which must be set to tell the OS when VPN connection should be established on-demand. onDemandRules property accepts an array of rules. Consequently, you can set multiple rules for a VPN configuration.

For example, you can set a rule and tell the OS to establish the VPN connection whenever user wants to open Apple.com; otherwise, the VPN connection won’t be established.

One thing you may want to do it to activate the VPN connection whenever an app open a network connection; so, all iOS network traffic will be transferred through your VPN server. To achieve this, NEOnDemandRuleConnect class must be used.

In Network Extension framework, Apple has provided some useful on-demand rule templates you can make use of. Although you can create your own rule, it’s possible to use templates as well.  NEOnDemandRuleConnect class is one of those templates. It will tell the OS to establish VPN connection whenever iOS needs to connect to the internet; as a result, users will always connect to your VPN servers whenever they want to access the internet. As far as I know, this is what most VPN providers and users want:

[[NEVPNManager sharedManager] setOnDemandEnabled:YES];
NSMutableArray *rules = [[NSMutableArray alloc] init];
NEOnDemandRuleConnect *connectRule = [NEOnDemandRuleConnect new];
[rules addObject:connectRule];
[[NEVPNManager sharedManager] setOnDemandRules:array];

Once you changed the configuration you have to save it using saveToPreferencesWithCompletionHandler: method.

Hope it helps :)

How to get persistent reference to a keychain item in iOS

Keychain is a very good idea from Apple. It lets app developers to store and retrieve sensitive data securely.

Keychain Services provides secure storage of passwords, keys, certificates, and notes for one or more users. A user can unlock a keychain with a single password, and any Keychain Services–aware application can then use that keychain to store and retrieve passwords. Keychain Services Programming Guide contains an overview of Keychain Services, discusses the functions and data structures that are most commonly used by developers, and provides examples of how to use Keychain Services in your own applications.

The following shows how keychain works:

unlocking_keychain. Photo taken from: developer.apple.com

During the process of creating VPN profiles programmatically in iOS 8, the NEVPNProtocol.passwordReference property requires a persistence reference to a keychain item with the kSecClassGenericPassword class. This post covers saving and getting persistence references to a keychain item in iOS.

Getting started with Keychain

The process of saving data in keychain is very simple once you understand it. To start working with Keychain, Security.framework needs to added to your project. Security framework has 4 major methods which enables you to access iOS keychain. These methods are:

  • SecItemAdd
  • SecItemCopyMatching
  • SecItemDelete
  • SecItemUpdate

As it can be guessed from each method’s name SecItemAdd, SecItemDelete and SecItemUpdate adds, deletes and updates data. SecItemCopyMatching method searches for a specific keychain item and copies item data to a reference variable if available. For more information about these four methods checkout Apple’s Keychain Services Reference page.

Saving data

Note: There’s actually no difference in saving normal and persistent references to the keychain!
The following adds a NSData object to the iOS keychain:

NSData *data = [Your data]; // Data to save. It can be a string too.
NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
[dict setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
NSData *encodedKey = [@"[Your key name]" dataUsingEncoding:NSUTF8StringEncoding];
[dict setObject:encodedKey forKey:(__bridge id)kSecAttrGeneric];
[dict setObject:encodedKey forKey:(__bridge id)kSecAttrAccount];
[dict setObject:service forKey:(__bridge id)kSecAttrService];
[dict setObject:(__bridge id)kSecAttrAccessibleAlwaysThisDeviceOnly forKey:(__bridge id)kSecAttrAccessible];
[dict setObject:data forKey:(__bridge id)kSecValueData];

OSStatus status = SecItemAdd((__bridge CFDictionaryRef)dict, NULL);
if(errSecSuccess != status) {
    NSLog(@"Unable add item with key =%@ error:%ld",key,status);
}

After the data is saved it can be get anytime from keychain.

Getting Data

Data can be get from keychain using the following code:

NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
[dict setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
NSData *encodedKey = [@"[Your key name]" dataUsingEncoding:NSUTF8StringEncoding];
[dict setObject:encodedKey forKey:(__bridge id)kSecAttrGeneric];
[dict setObject:encodedKey forKey:(__bridge id)kSecAttrAccount];
[dict setObject:service forKey:(__bridge id)kSecAttrService];
[dict setObject:(__bridge id)kSecAttrAccessibleAlwaysThisDeviceOnly forKey:(__bridge id)kSecAttrAccessible];
[dict setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];
[dict setObject:(id)kCFBooleanTrue forKey:(__bridge id)kSecReturnPersistentRef]; // The most important part
    
CFTypeRef result = NULL;
OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)dict,&result);
    
if( status != errSecSuccess) {
    NSLog(@"Unable to fetch item for key %@ with error:%ld",key,status);
    return nil;
}
    
NSData *resultData = (__bridge NSData *)result; //Your data is ready

The most important part of the above code is in line 9 where kSecReturnPersistentRef attribute is set. This attribute tells the keychain to return a persistent reference to the keychain item.

Hope it helps :)

Introducing timeago: A jQuery library to update fuzzy timestamps automatically

You may have seen at least one of these timestamps in websites especially social networks:

time1

time3

These timestamps are very important and useful in all websites that time matters. But you may have wondered how to implement such a thing in your own web applications.

There are a couple of ways to do so. The first one is to implement this functionality server side. I’ve implemented a server side C# function to do it; but, there would be a very big issue: As the time goes on, the timestamp won’t update! The whole page needs to be refreshed! You may have use ajax to refresh the time but this method also costs lots of resources. The best place to do such a thing is client and that’s exactly what timeago does!

What is timego?

Timeago is a jQuery plugin that makes it easy to support automatically updating fuzzy timestamps (e.g. “4 minutes ago” or “about 1 day ago”).

Timeago has lots of advantages over server side implementation I’ve mentioned above. Here are some:

  • It is very lightweight (About 8KB when not minified and about 4KB when minified and GZiped)
  • Runs on user’s browser; consequently, it won’t cost any server resources.
  • It can be used alongside caching techniques while it runs on client.
  • The timestamps’ values will update live so there’s no need to refresh the whole page or make ajax requests to update them.
  • It’s free and open-source!

How to use timeago?

Using timeago it very simple. Imagine you have a span element in your web page and you want to update the value of this field using timeago. The very first step is to use jquery.timeago.js file in your page’s head element. You also need jQuery library as well; so, add it too if you haven’t:


After that place your ‘span’ as following:

July 17, 2008

As you may have noticed that we put the real datetime we want to calculate from in the ‘title’ attribute. The final step is to add the following piece of javascript in your page:

$(document).ready(function() {
  $("span.timeago").timeago();
});

You’re done! The javascript code above converts all span elements which has “timeago” class.

How to download timeago

Since timeago is an open-source project, it can be found by its GitHub repository or its official website at: http://timeago.yarp.com/. Don’t forget to check out its website for more examples.

This library was very useful for me. Hope it does the same for you.

Quick post: Testing in-app purchases in iOS 8

I love quick posts, they’re short and handy. Some topics should be explained as short as possible. I name these quick posts. In this (quick) post, I want to talk about significant changes to iOS 8 simulator when testing in-app purchases; so, here you go:

iOS simulator - Photo taken from http://www.ralfebert.de/ios/ueberblick-ios-xcode/icon_simulator.pngTesting in-app purchases is one of the most important tasks to do in your applications; because, it’s the way you can make money from your app. In-app purchases were one of those features which had to be tested on a real device only.

Prior to iOS 8, developers had to have at least one real device (an iPod Touch for example) to test their apps’ in-app purchases. But in iOS 8, Apple has made significant changes to its iOS simulator. Now developers can do much more as it’s possible to test in-app purchase functionality right in the simulator even if no real device is available!

This is a very important improvement especially for me as a developer who is working with iOS 8 new feautres. If this feature was not available, I had to install iOS 8 beta on my iPhone which I prefer not to.

There might be more improvements in iOS simulator which I haven’t faced yet. If you know any of them, let the world know them as well by commenting down below.

Have a nice coding ;-)

 

Essential tools everyone should have at home

In less than two month from now, we’ll celebrate our wedding party. Regarding this, we are preparing our new home. This is one of the hardest things to do because, they’re lots of tasks I haven’t ever thought about and I must get all of them done before the wedding party. Before this, I preferred to give all tasks to their professionals; but, after a while, I realized it’s not possible to give them to someone else because there are lots of small tasks that need to be done immediately.

My father is a handyman. He’s doing all of his house’s tasks by himself. He thinks that everyone knows about his own problems better than anyone else. I didn’t understand the meaning of this until now.

YOU NEED TO BE ABLE TO DO SOME OF CRITICAL TASKS YOURSELF. IF YOU DON’T KNOW HOW TO GET THEM DONE, LEARN THEN!

As a result, I decided to fix our new home’s small tasks myself. accordingly, I started to figure out what tools I need. I asked a few repairmen and handymen including my father about the essential tools I should have to get our home issues done and I decided to share them with you here.

Note that these tools is essential for everyone no matter what are their profession. I’m a programmer and I need these tools as well. Also, if you’re not going to do your home tasks yourself, you may want to skip this post. In addition, this post is all about my own opinion and I’m not advertising any brand here.

1. ToolBox

A large toolboxThe very first thing you need is a toolbox. This will help you gather all of your tools into one package; consequently, you won’t lose any of them. Also, it will be possible to carry them all with ease. toolboxes have different sizes and shapes. To get started, it’s not necessary to buy a large toolbox but a very small one is also enough. Moreover, a small bag can be used if you don’t want to buy one. I preferred to buy a small toolbox while I don’t have a lot of tools by the time.

2. Screwdriver

screwdriverAlmost anything including devices, gadgets, electronics, etc. have some screws today. So, it’s obvious you need some screwdrivers to fix them in the case of emergency.

There are plenty of screwdriver types out there but I believe you’ll need just two of them: Slot and Phillips

You’ll need at least two types of screwdrivers to get most of your tasks done. But, if you want you can purchase a power screwdrivers!  Most power screwdrivers have at least two built-in heads and you can extend it whenever you want. Using a power screw driver makes your work much easier and faster. The following is a photo of automatic screwdriver with more 10 heads:

3209014159_25d91e567c_b

3. Pliers

plierPilers are very important when want to hold objects firmly. Actually, it’s very handy tool because can be used in variety of cases but it’s main functionality is holding objects. I use pliers to bend small objects, pull objects out of the wall, hold wires when working with electricity and many many more.

Pliers are not limited to just one type. There plenty of types out there are I’m using some of those as well.

4. Locking pliers

locking plierLocking pliers, Mole grips (Mole wrench) or Vise-Grips are pliers that can be locked into position, using an over-center action. One side of the handle includes a bolt that is used to adjust the spacing of the jaws, the other side of the handle (especially in larger models) often includes a lever to push the two sides of the handles apart to unlock the pliers.

5. Needle-nose pliers

Needle-nose pliersNeedle-nose pliers (also known as long-nose pliers, pinch-nose pliers or snipe-nose pliers) are both cutting and holding pliers used by artisans, jewelry designers, electricians and other tradesmen to bend, reposition and cut wire. Their namesake long nose gives excellent control while the cutting edge near the pliers’ joint provides “one-tool” convenience. Because of their long shape they are useful for reaching into small areas where cables or other materials have become stuck or unreachable with fingers or other means.

6. Pipe wrench

PipeThe pipe wrench (US), Stillson wrench or Stillsons (UK) is an adjustable wrench used for turning soft iron pipes and fittings with a rounded surface. The design of the adjustable jaw allows it to lock in the frame, such that any forward pressure on the handle tends to pull the jaws tighter together. Teeth angled in the direction of turn dig into the soft pipe. They are not intended for use on hardened steel hex nuts or other fittings because they would ruin the head; however, if a hex nut is soft enough that it becomes rounded beyond use with standard wrenches, a pipe wrench is sometimes used to break the bolt or nut free.

7. Utility knife

utility knifeWhen we were bringing furnitures everything was packed so we needed something to unpack them. The utility knife is exactly what we wanted. It’s one of the most handy tools all the time especially while moving to a new place. It has a very sharp blade which helped us unpack all or our packages. In some cases that scissors are not usable, utility knife is the best choice.

8. Self Retractable Metric Ruler

meterFitting everything in its right place is a very important especially for women. Before we start moving to this house, we needed to measure every single part of the house in order to buy right furnitures such as curtains. A metric ruler was essential for us. Without it, we weren’t be able to fit stuff to their places.

9. Hammer

Hammer is a critical tool everyone should have. It comes very handy when want to install something. For example, we used hammer to install our photos and mirrors on the wall. Hammer has a lot of usage and I think it’s one of the first things you should buy.

hammerI believe everyone should have these essential tools to get small tasks done. Someday you will need at least one of them. I think I won’t be able to set things up without these. If you know any other essential tool I forgot to mention, please tell me by commenting down below.

Hope it helps :-)

 

Configure and manage VPN connections programmatically in iOS 8

Update 3: If you’re going to create an on-demand VPN connection, checkout my article about creating on-demand VPN connection programmatically in iOS 8 after reading this.

Update 2: The beta 5 issue has been fixed in the GM release. Everything is currently working just fine.

Update: This solution does not work on iOS 8 beta 5 due to a weird “Missing name” issue; however, it works find on iOS 8 beta 1 to 4. If you know anything new about managing the VPN connections in iOS 8, let me know by commenting down below.

Connecting to VPN servers programmatically had been always an impossible task to do for developers because of Apple’s limitations.

In my previous post I’ve described that Apple introduced a brand-new Network Extension framework which gives developers the opportunity to configure VPN preferences programmatically but I didn’t describe how!

This post is a guide to manage VPN configurations in iOS 8 and OS X (10.10) Yosemite while there’s no official documentation published yet. I Also have to thank quellish who helped me a lot in this.

Requirements

  1. The very first and the most critical things you need is an actual device with iOS 8 beta 1 or above to test the app on! This tutorial cannot be tested on iPhone simulator. If you’re going to write a Mac application, OS X Yosemite Preview 3 or above has to be installed.
  2. Since this test doesn’t work on simulator, you have to be a member of iOS/Mac developer program. Also, you need to make some changes to your provisioning profile. You cannot use your iOS 7 provisioning profiles to develop iOS 8 VPN applications.
  3. Xcode 6 beta. By the time of this post (August 2nd, 2014), Xcode 6 is in beta 4 and just like I’ve mentioned in my previous post, you need to to a member of iOS/Mac program to have access to beta tools.
  4. Last but absolutely not least, you need a Mac since Xcode cannot be run on Windows or Linux machines.

Getting Started

The first thing you need to do before actually start writing any codes is to update your provisioning profiles. If you haven’t created any profiles yet, you need to create one now! To do this, login to your developer account, then click on “Certificate, Identifiers & Profiles”:

Provisioning profile update

Select Identifiers, then select the application you want to update its provisioning profile. If you don’t have any, you can create one using the plus sign. By selecting an app, a list will be appeared. This is a list of features the app is going to use, for example if you want to have iCloud functionality in your application, you have to turn iCloud feature on; otherwise, you won’t be able to test and deploy your iCloud based apps. The following is showing that list:

Identifiers list

By the introduction of iOS 8, a new item has been added to this list which is “VPN Configuration & Control”. This is exactly what we’re looking for! So enable this feature by clicking on it and then ticking its checkbox. When you turn this feature on a modal window will be displayed which describes its functionality:

Enable VPN Config

Enable VPN Configuration & Control feature and click “Done”. Then, download the provisioning profile again and replace it with the old one. We’re done here, now lets get back to Xcode.

Note: In this post I assume that you’re familiar with iOS development and Objective-C. If you’ve never developed any app in for iOS or Mac, you may need to learn some basic concepts and then return to this post.

Open Xcode and create a new iOS 8 single view application project. Then, place a button in the middle of screen and then connect it to your ViewController.

What we’re going to do is to setup VPN preferences on viewDidLoad: method and then connect to our specified VPN server when the button is tapped.

Before getting started, you have to know how all this work! If you understand the structure of Network Extension framework, then it will be much easier to develop apps based on it.

NetworkExtension.framework

Apple has done a brilliant job developing this framework. Every app can access system preferences but in its own sandbox; which means you cannot access other apps’ sandboxes.

First of all, saved preferences have to be loaded from OS to be able to be accessed. Once they’re loaded, it’s possible to make your changes. After changes have been made, they need to be saved. Unsaved preferences won’t be applied. Your app’s preferences can also be removed if you no longer need them. As a result, to create a VPN configuration we need to do the following:

  • Load our app’s preferences
  • Make our changes
  • Save preferences

Note that you need to load your app’s preferences even if you haven’t set any configuration yet.

After VPN connection is created we can connect to or disconnect from it.

Network extension contains three major classes:

  • NEVPNManager
  • NEVPNProtocol
  • NEVPNConnection

NEVPNManager is the most important class in this framework. It’s responsible for load, save and remove preferences. In fact, all VPN tasks have to be done through this class.

Create a new VPN connection

To get started a new instance of this class has to be created:

NEVPNManager *manager = [NEVPNManager sharedManager];

After NEVPNManager is initialized, system preferences can be loaded using loadFromPreferencesWithCompletionHandler: method:

[manager loadFromPreferencesWithCompletionHandler:^(NSError *error) {
    // Put your codes here...
}];

As I’ve mentioned in above code, the load method accepts a compilation handler block. This block is fired whenever the load process is completed. This block also has a parameter which is an NSError. the NSError parameter will be nil if the loading operation completed; otherwise, it will be non-nil. Accordingly:

[manager loadFromPreferencesWithCompletionHandler:^(NSError *error) {
    if(error) {
        NSLog(@"Load error: %@", error);
    } else {
        // No errors! The rest of your codes goes here...
    }
}];

After loading process is completed, It’s time to set up our VPN connection.

iOS 8 supports two major protocols. IPSec and IKEv2. It’s the first time that Apple offers IKEv2 protocol in its operating systems. This protocol is supported by all major operating systems including Android, Windows Phone, Windows Desktop, Linux and now iOS and Mac. In this post I’m going to talk about IPSec and in my next posts I’ll talk about IKEv2 as well. In addition to these protocols, Apple gives you the ability to create your own protocol if needed! This feature is a very important features for those who have implemented their own protocol; because now it’s possible to implement that protocol on iOS and Mac as well. OK, lets set up our IPSec protocol:

NEVPNProtocolIPSec *p = [[NEVPNProtocolIPSec alloc] init];
p.username = @"[Your username]";
p.passwordReference = [VPN user password from keychain];
p.serverAddress = @"[Your server address]";
p.authenticationMethod = NEVPNIKEAuthenticationMethodSharedSecret;
p.sharedSecretReference = [VPN server shared secret from keychain];
p.localIdentifier = @"[VPN local identifier]";
p.remoteIdentifier = @"[VPN remote identifier]";
p.useExtendedAuthentication = YES;
p.disconnectOnSleep = NO;

In the first line, I’ve created a new instance of NEVPNProtocolIPSec. This class is inherited from NEVPNProtocol class. NEVPNProtocol class is an abstract class you can use to create your own protocols.

Then, we specified our username and password in the second and third line. Notice that the password is a reference from Keychain; so, you need to store your password in Keychain first and then retrieve it.

The fourth line is our server address. Server address can be an IP, a host name or a URL.

Next is authentication method. iOS 8 supports three authentication methods

  • NEVPNIKEAuthenticationMethodNone: Do not authenticate with IPSec server.
  • NEVPNIKEAuthenticationMethodCertificate: Use a certificate and private key as the authentication credential.
  • NEVPNIKEAuthenticationMethodSharedSecret: Use a shared secret as the authentication credential.

As you can see, I’ve used Shared Secret method; but, you can use whatever method you want.

The next line is Shared Secret reference. Again it’s reference from Keychain; so, you need to get Shared secret from there. If you’re going to use certificate rather than shared secret. There’s no need to fill sharedSecretReference property; instead, you have to fill identityData property. Identity data is the PKCS12 data for the VPN authentication identity. The value for this property must be a NSData in PKCS12 format:

p.identityData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"clientCert" ofType:@"p12"]];

The next two lines are local and remote identifiers. These two are strings identifying the local and remote IPSec endpoints for authentication purposes.

The next property we need to set is useExtendedAuthetication. This is a flag indicating if extended authentication will be negotiated. This authentication is in addition to the IKE authentication used to authenticate the endpoints of the IKE session. For IKE version 1, when this flag is set X-Auth authentication will be negotiated as part of the IKE session, using the username and password properties as the credential. For IKE version 2, when this flag is set EAP authentication will be negotiated as part of the IKE session, using the username, password, and/or identity properties as the credential depending on which EAP method the server requires.

The last property to set is disconnectOnSleep. This boolean indicates whether the VPN connection must be disconnected when the device goes to sleep or not.

OK that’s enough for protocol. The next thing we have to do is to assign the protocol we’ve just created to the VPN manager. To do so, the setProtocol: method can be used.

[manager setProtocol:p];

IPSec and IKEv2 protocols have a very cool feature called On-demand. This feature enable connect to connect automatically whenever user attempted to connect to the internet. In iOS 8, it’s possible to enable on-demand on the connection. But, I’m going to cover this feature in another post; therefore, lets leave it for now and set the onDemandEnabled property to NO for now.

[manager setOnDemandEnabled:p];

The last thing we must set is the description of VPN preference we’re going to create. To do so, just set its localized description property by using setLocalizedDescription: method

[manager setLocalizedDescription:@"[You VPN configuration name]"];

We’re almost done. We’ve set up the configuration but haven’t saved it yet. To save the configuration simply call the saveToPreferencesWithCompletionHandler: method:

[manager saveToPreferencesWithCompletionHandler:^(NSError *error) {
    if(error) {
        NSLog(@"Save error: %@", error);
    }
    else {
        NSLog(@"Saved!");
    }
}];

This method simply saves your specified configuration to the system settings.

Connect to the VPN connection we’ve just created

Now that you’ve saved your settings to system’s preferences, it’s time to connect to it. NEVPNManager has a property called connection. This property is an object of NEVPNConnection class. It hold information which is responsible for VPN connection. To connect to VPN server you’ve just created, simply call startVPNTunnelAndReturnError: method of NEVPNConnection class just like below:
Run the application on your device and you’ll see and new connection will be create and you can connect to it by tapping the button. Also, you can disconnect from VPN server programmatically as well by calling stopVPNTunnel method of NEVPNConnection:

- (IBAction)buttonPressed:(id)sender {
    NSError *startError;
    [[NEVPNManager sharedManager].connection startVPNTunnelAndReturnError:&startError];
    
    if(startError) {
        NSLog(@"Start error: %@", startError.localizedDescription);
    } else {
        NSLog(@"Connection established!");
    }
    
}

If you have any idea, suggestion or anything else regarding this post, please leave your comments down below. I’ll blog about IKEv2 and On-demand features in the near future. Stay tuned.

Storyboards are now available on OS X Cocoa development

One of the coolest things I love to work with when develop iOS applications is using storyboards. They’re definitely one of the best ways to develop application in my opinion because, they’re very simple and simplify a lot of development tasks, cover most application scenarios and easy to understand as most iOS developers tend to use them.

In recent Apple WWDC (2014), a new version of Xcode (6) has been introduced. This version has a lot of cool features not only for iOS 8 but OS X as well! One of the most surprising features in this version is the support of storyboards for OS X Cocoa development! Using Xcode 6, Mac developers can take advantage of storyboards! Let’s take a look:

Download Xcode 6 from Apple’s developer website. (By the time, Xcode 6 is in beta; consequently, you must be a member of Mac/iOS developer program to be able to download it)

Create a new OS X Cocoa Application. The following window will be appeared:

osx-app-create

As you can see in the above screenshot, you now have the ability to create an OS X Cocoa application and use storyboards.

But, you may ask this question: Why this option is disabled here?

Well, the answer is clear! This feature is only available in the latest version of OS X which is by the time OS X 10.10 Yosemite; as a result, you must install it to use storyboards in your applications.

I believe this improvement to Cocoa development, will courage more developers to release the Mac version of their apps. Most iOS developers today have not worked with older technologies such as nib files because when they started iOS development, storyboards were existed and they didn’t need anything else. But now they can do the same thing in Mac applications as they do in iOS.

Hope it helps

Introducing Network Extension in iOS 8 and OS X 10.10

It’s about a year I’m working on an iOS VPN project which enables users to access the web and its contents without any kind of restrictions. By the time, all VPN applications need to install a configuration profile on clients’ devices to apply their VPN configuration on them; because, Apple forbids applications to access iOS system configurations. After the installation of configuration profile, users have to open iOS settings application to enable that VPN service manually; consequently, client applications are act as a profile installer or statistics viewer only!iOS-8-App-Extensions-icon-200x200

The story is completely different on Android devices since restrictions are much fewer than iOS. Android developers can implement a connect/disconnect button to let their users connect and disconnect from VPN servers right from the app.

By introduction of iOS 8, Apple revealed lots of new developer tools and APIs including App Extensions, Handoff, HealthKit, HomeKit, Swift programming language and many many more. But, one of the most useful stuff specially for VPN providers is NetworkExtension which is first introduced in iOS 8 and OS X 10.10!

Network Extension enables developers to manage VPN preferences on their users’ devices. By using this framework, you will have access to almost all iOS VPN preferences. In addition to letting developers access VPN settings, Apple also introduced a new IKEv2 protocol which wasn’t available on iOS or OS X before. This is a standard protocol which is supported by all major mobile and desktop operating systems such as Windows Phone 8.1, Android and now iOS!

I plan to publish more posts about new stuff in both iOS 8 and OS X 10.10. Unfortunately, by now, Apple hasn’t released any documentations regarding Network Extension; but, I’ve done some researches and I’ll share them with you in near future. Until then, please share your idea and information about network extension with me so I can provide a better post to publish :)