Tumblelog by Soup.io
Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

September 19 2014

17:30

A Dual Review of What’s New, Starring Malcolm Gladwell and Sarah Silverman

Malcolm Gladwell and Sarah Silverman size up a smelly fork, a SmartRing and cookies made of bugs.
17:24

Duke Porn Star Belle Knox Once Carved The Word 'Fat' Into Her Body

The content of this post may be sensitive to some readers.

You wouldn't know it by looking at her now, but porn star Belle Knox used to feel very insecure about her body.

Knox, a Duke University student who made national headlines in February when she was outed as an adult performer, describes her "nerdy" high school self as having faced some serious hardship in a new documentary web series, "Becoming Belle Knox."

The series follows Knox, whose real name is Miriam Weeks, as she goes about her dual life as both a porn star and a college student. In the third episode, while on set for a photo shoot, a makeup artist is shown carefully covering up the scars that stripe Knox's inner thigh.

"When I was like in eighth grade, I cut myself," Knox explains in the documentary. "I had like a hand mirror and I punched it, and I took one of the shards and I wrote the word 'fat' into my thigh, so it would always remind me when I looked in the mirror, that I was fat."

Knox wrote in XOJane last March that "Like many young women grappling with depression, I used to take it out on myself."

She's been "clean" from such self-harm for five years now, she said. The revelation of her previous self-harm is juxtaposed with the photo shoot, where she puts on display the body she's since become proud of.

"I like the assertive, passionate person that I'm becoming because of porn," Knox explains in episode two. "It's such a contrast from being that helpless little girl who had no control over her body to being Belle, this sexually in control, empowered porn star."

Watch the full series at Thescene.com.

Need help? In the U.S., call 1-800-DONTCUT for the S.A.F.E. Alternatives hotline.
17:15

Rap Duo Rich White Ladies Wanna Kidnap Dolly Parton's Boobs In Their New Video, "Ransom"


Our favorite Bronx-bred rap duo Rich White Ladies have a star-studded hit list in their bloodthirsty, money hungry video, "Ransom," directed by Frederic Esnault. No A-lister's safe from their "lipstick stick up" -- not Oprah Winfrey, not Kate Moss, not even "Dolly's titties." The irresistibly menacing pair Scotty Rebel and Tokyo Diiva threaten to pluck Marc Zuckerburg "just like a bird," and "tie Donald Trump to a stump" to take a bump and a drag with him. We like your style, ladies -- mind if we join?
17:13

Kendall Jenner Shares Racy Photo On Instagram

Kendall Jenner shares a sexy photo on Instagram.
17:12

SchoolDir 1.6 (Demo)

Easy directory management for elementary or secondary schools
17:05

TTclock 1.10 (Freeware)

Constantly be aware of time, set alarms to remind you of important events or time your activities with the help of this application
17:00

How to Build Rate Limiting into Your Web App Login

Final product image What You'll Be Creating

While reports vary, The Washington Post reported that the recent iCloud celebrity photo hacking centered around Find My iPhone's unprotected login point:

"...security researchers were said to have found a flaw in iCloud's Find My iPhone feature that didn't cut off brute-force attacks. Apple's statement ... suggests the company doesn't regard that revelation as a problem. And that's a problem, according to security researcher and Washington Post contributor Ashkan Soltani.

I agree. I wish Apple had been more forthcoming; its carefully worded response left room for different interpretations and seemed to blame the victims.

Hackers may have used this iBrute script on GitHub to target celebrity accounts via Find My iPhone; the vulnerability has since been closed.

Since one of the wealthiest corporations in the world didn't allocate the resources to rate limit all of their authentication points, it's likely that some of your web apps don't include rate limiting. In this tutorial, I'll walk through some of the basic concepts of rate limiting and a simple implementation for your PHP-based web application.

How Login Attacks Work

Research from prior hacks has exposed passwords that people tend to use most frequently. Xeno.net publishes a list of the top ten thousand passwords. Their chart below shows that the frequency of common passwords in their top 100 list is 40%, and the top 500 make up 71%. In other words, people commonly use and re-use a small number of passwords; in part, because they are easy to remember and easy to type.

Frequency of Common Passwords - From Xenonet

That means that even a tiny dictionary attack using just the twenty-five most common passwords could be quite successful when targeting services.

Once a hacker identifies an entry point that allows unlimited login attempts, they can automate high speed, high volume dictionary attacks. If there's no rate limiting, then it becomes easy for hackers to attack with larger and larger dictionaries - or automated algorithms with infinite numbers of permutations.

Furthermore, if personal information about the victim is known e.g. their current partner or pet's name, a hacker can automate attacks of permutations of likely passwords. This is a common vulnerability for celebrities.

Approaches to Rate Limiting

To protect logins, there are a couple of approaches that I recommend as a baseline:

  1. Limit the number of failed attempts for a specific user name
  2. Limit the number of failed attempts by IP address

In both cases, we want to measure failed attempts during a specific window or windows of time e.g. 15 minutes and 24 hours.

One risk to blocking attempts by user name is that the actual user could get locked out of their account. So, we want to make sure we make it possible for the valid user to re-open their account and/or reset their password.

A risk to blocking attempts by IP address is that they are often shared by many people. For example, a university might host both the actual account holder and someone attempting to maliciously hack their account. Blocking an IP address may block the hacker as well as the actual user.

However, one cost to increased security is often a bit of increased inconvenience. You have to decide how strictly to rate limit your services and how easy you want to make it for users to re-open their accounts.

It can be useful to code a secret question into your app which can be used to re-authenticate a user whose account was blocked. Alternately, you can send a password reset to their email (hoping that it's not been compromised).

How to Code Rate Limiting

I've written a bit of code to show you how to rate limit your web applications; my examples are based in the Yii Framework for PHP. Most of the code is applicable to any PHP/MySQL application or framework.

The Failed Login Table

First, we need to create a MySQL table to store information from failed login attempts. The table should store the ip_address of the requesting user, the attempted username or email address used and a timestamp:

 $this->createTable($this->tableName, array(
    'id' => 'pk',
    'ip_address' => 'string NOT NULL',
    'username' => 'string NOT NULL',
    'created_at' => 'TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
    ), $this->MySqlOptions);

Then, we create a model for the LoginFail table with several methods: add, check and purge.

Recording Failed Login Attempts

Whenever there is a failed login, we'll add a row to the LoginFail table:

  public function add($username) {
    // add a row to the failed login table with username and IP address
    $failure = new LoginFail;
    $failure->username = $username;
    $failure->ip_address = $this->getUserIP();
    $failure->created_at =new CDbExpression('NOW()'); 
    $failure->save();
    // whenever there is a failed login, purge older failure log
    $this->purge();
  }

For getUserIP(), I used this code from Stack Overflow.

We can also use the opportunity of a failed login, to purge the table of older records. I do this to prevent the verification checks from slowing down over time. Or, you can implement a purge operation in a background cron task every hour or every day:

public function purge($mins=120) {
    // purge failed login entries older than $mins
    $minutes_ago = (time() - (60*$mins));  // e.g. 120 minutes ago
    $criteria=new CDbCriteria();
    LoginFail::model()->older_than($minutes_ago)->applyScopes($criteria);
    LoginFail::model()->deleteAll($criteria);    
}

Checking for Failed Login Attempts

The Yii authentication module I'm using looks like this:

public function authenticate($attribute,$params)
{
	if(!$this->hasErrors())  // we only want to authenticate when no input errors
	{      
		$identity=new UserIdentity($this->username,$this->password);
		$identity->authenticate();
		if (LoginFail::model()->check($this->username)) {
		    $this->addError("username",UserModule::t("Account access is blocked, please contact support."));  		      
	    } else {
  		switch($identity->errorCode)
  			{
  				case UserIdentity::ERROR_NONE:
    					$duration=$this->rememberMe ? Yii::app()->controller->module->rememberMeTime : 0;
    					Yii::app()->user->login($identity,$duration);  		      
  					break;
  				case UserIdentity::ERROR_EMAIL_INVALID:
  					$this->addError("username",UserModule::t("Email is incorrect."));
  					LoginFail::model()->add($this->username);
  					break;
  				case UserIdentity::ERROR_USERNAME_INVALID:
  					$this->addError("username",UserModule::t("Username is incorrect."));
  					LoginFail::model()->add($this->username);
  					break;
    				case UserIdentity::ERROR_PASSWORD_INVALID:
    					$this->addError("password",UserModule::t("Password is incorrect."));
    					LoginFail::model()->add($this->username);
    					break;
  				case UserIdentity::ERROR_STATUS_NOTACTIV:
  					$this->addError("status",UserModule::t("You account is not activated."));
  					break;
  				case UserIdentity::ERROR_STATUS_BAN:
  					$this->addError("status",UserModule::t("You account is blocked."));
  					break;
  			} 
	    }
	}
}

Whenever my login code detects an error, I call the method to add details about it to the LoginFail table:

LoginFail::model()->add($this->username);

The verification section is here. This runs with every login attempt:

$identity->authenticate();
if (LoginFail::model()->check($this->username)) {
	$this->addError("username",UserModule::t("Account access is blocked, please contact support."));

You can graft these functions on to your own code's login authentication section.

My verification check looks for a high volume of failed login attempts for the username in question and separately for the IP address being used:

  public function check($username) {
    // check if failed login threshold has been violated
    // for username in last 15 minutes and last hour
    // and for IP address in last 15 minutes and last hour
    $has_error = false;
    $minutes_ago = (time() - (60*15));  // 15 minutes ago
    $hours_ago = (time() - (60*60));  // 1 hour ago
    $user_ip = $this->getUserIP();
    if (LoginFail::model()->since($minutes_ago)->username($username)->count()>=self::FAILS_USERNAME_QUARTER_HOUR) {
      $has_error = true;
    } else if (LoginFail::model()->since($minutes_ago)->ip_address($user_ip)->count()>=self::FAILS_IP_QUARTER_HOUR) {
        $has_error = true;
      } else if (LoginFail::model()->since($hours_ago)->username($username)->count()>=self::FAILS_USERNAME_HOUR) {
      $has_error = true;
    } else if (LoginFail::model()->since($hours_ago)->ip_address($user_ip)->count()>=self::FAILS_IP_HOUR) {
        $has_error = true;
      }
      if ($has_error)
          $this->add($username);			
      return $has_error;
  }

I check rate limits for the last fifteen minutes as well as the last hour. In my example, I allow 3 failed login attempts per fifteen minutes and six per hour for any given username:

  const FAILS_USERNAME_HOUR = 6;
  const FAILS_USERNAME_QUARTER_HOUR = 3;
  const FAILS_IP_HOUR = 24;
  const FAILS_IP_QUARTER_HOUR = 12;

Note that my verification checks use Yii's ActiveRecord named scopes to simplify the database query code:

// scope of rows since timestamp
  public function since($tstamp=0)
  {
    $this->getDbCriteria()->mergeWith( array(
      'condition'=>'(UNIX_TIMESTAMP(created_at)>'.$tstamp.')',
    ));
      return $this;
  }

  // scope of rows before timestamp
  public function older_than($tstamp=0)
  {
    $this->getDbCriteria()->mergeWith( array(
      'condition'=>'(UNIX_TIMESTAMP(created_at)<'.$tstamp.')',
    ));
      return $this;
  }

  public function username($username='')
  {
    $this->getDbCriteria()->mergeWith( array(
      'condition'=>'(username="'.$username.'")',
    ));
      return $this;
  }

  public function ip_address($ip_address='')
  {
    $this->getDbCriteria()->mergeWith( array(
      'condition'=>'(ip_address="'.$ip_address.'")',
    ));
      return $this;
  }

I've tried to write these examples so that you can easily customize them. For example, you could leave out the checks for the last hour and rely on the last 15 minute interval. Alternatively, you could change the constants to set higher or lower thresholds for the number of logins per interval. You could also write much more sophisticated algorithms. It's up to you.

With this example, to improve performance, you may want to index the LoginFail table by username and separately by IP address.

My sample code doesn't actually change the status of accounts to blocked or provide functionality for unblocking specific accounts, I'll leave that up to you. If you do implement a blocking and resetting mechanism, you may want to offer functionality to separately block by IP address or by username.

I hope you've found this interesting and useful. Please feel free to post corrections, questions or comments below. I'd be especially interested in alternate approaches. You can also reach me on Twitter @reifman or email me directly.

Credits: iBrute preview photo via Heise Security

16:59

5 Celebrity Uses for New iOS8 Features

This piece originally appeared on Celebrity Watchdog.

In the last almost 24 hours, masses of people are deleting everything on their phone to make room for iOS 8 even though they don't realize you can just download it from your computer and not have to free up almost 6 gigabytes of space, but your loss man.

While there's plenty of great updates and new features for us common folk, we've let the creative juices flow to figure out the real importance of this update: How can it make a celebrity's life easier? Well, it's time to take a peek.

1. Safely Send Nudes with New Quick-Videos

During Celebgate at the end of August, a variety of stars had their privacy disrespected when nude photos of them ended up online, after possibly having their iCloud accounts brute-hacked. iOS 8 is stealing a feature from popular self-destructive messaging system Snapchat, by giving users the option of sending temporary videos.

In the new messages screen, if someone holds the camera button, two options will come up: Above your thumb there will be a camera button which takes-and-sends a selfie (without any confirmation, so caution there), and to the right of your thumb is a video button that will allow you to record and send a video in the current message. Default settings will delete these messages after two minutes, and the sender can easily see if friends decide to "keep" the video.

In the interest of fair disclosure, 5 Seconds of Summer boy-bander Calum Hood did recently have his Snapchat video nudes leaked to the world, so self-destructing is not always foolproof either.

2. Send Voice Messages, Not Screenshot-bait

Note to celebrities: Rather than going on phone tirades to vocally voice your frustrations, drunk thoughts, or racism, you can now raise your iPhone to your ear and speak your mind. The best part? Like the above videos, it will be deleted two minutes later.

In the past, Alex Rodriguez, Jesse James, and Tony Parker have been caught cheating through text messages, but if there's virtually no conversation to be had... There's nothing to trace. Cheating scandals aside, there are other celebrities who have their texts hacked for other reasons as well.

It eliminates the incriminating 48 minute phone call, while also leaving no screenshot-worthy evidence for prying eyes.

3. Emergency ID...Well, Helps Them in Emergencies

Let's try to avoid jokes about this one, because Emergency ID is one of the most important features Apple has ever added to their iOS. Considering the number of sudden celebrity deaths, the benefits of having an emergency contact, as well as a quickly-acessible list of necessary information for a bystander or paramedic, are boundless. This feature can certainly save lives with the option to include information such as current medications, allergies, prior medical conditions, organ donor status, and blood type.

While we always assume paramedics are doing everything they can for sudden celebrity injuries and deaths, you never know if having all the information there could have changed things.

4. Health

Branching out from just Emergency ID, to the new health features as a whole, we definitely see a lot of celebrity usage in this one. Between tracking calories burned and steps taken, it can begin working to replace sometimes-bulky fitness trackers, or make room for an Apple Watch on the user's wrist (which may or may not cost $5000 for the premium version). Whether bulking up to appear in The Hunger Games: Catching Fire, or simply slimming down for a role, the app can act as a vast database for all health-info.

The app includes a storage area including: Sleep analysis, flights of stairs climbed, resting calories, the ability to track nutrient intake such as calories and caffeine, oxygen saturation, inhaler usage, and number of times fallen.

There's also a Blood Alcohol Content piece to it. We aren't quite sure what app or iOS enabled hardware would be collecting it, but it'll be definitely good to know, for certain celebs out there. If only Lindsay and Paris had this ten years ago.

5. Apple Pay

Gone are the days of celebrity belittlement. How dare someone propose that a C-list star pull her payment information out of her overpriced clutch to hand to a cashier making $9 per hour, that's embarrassing and definitely not safe. Well, good news is at supported NFC Payment Terminals, all the celeb will need to do is hold their phone against the terminal, avoid eye-contact, and continue on with their day. Since McDonald's drive-thru windows are supported we expect to see a few nights of drunkenly rude Justin Bieber waving his phone (or wrist) through the window.

Apple Pay is also supported for some online retailers, meaning that there's no need for the online merchant to ever receive your billing information. Apple Pay won't make it's grand debut until October and an iPhone 6 (plus or not) or Apple Watch is required for use.
16:58

Do You Remember? A Micro History Of 'The Happiest-Sounding Song In The World'

"Do you remember?" is a lyric from the classic Earth, Wind & Fire hit, "September," that is practically impossible to forget. But just in case fans wanted to know more about the wedding staple as it enters its 36th year this fall, the song's co-writer, Allee Willis, spoke to NPR's "Morning Edition" on Friday, and gave something of a mini history of what she called "the happiest-sounding song in the world."

"As a white Jewish girl getting a break, you could not get better than Earth, Wind & Fire," Willis recalled to Dan Charnas for NPR.

As Willis noted, singer-songwriter Pharrell Williams revealed during his tearful interview with Oprah Winfrey in April that Earth, Wind & Fire was among his biggest influences. The "Happy" creator played his inspiration track for Winfrey's audience on his iPad: It was "September."

Willis, who also co-wrote the theme song for "Friends" -- "I'll Be There for You," performed by The Rembrandts -- recalled the one part of "September" that didn't fill her with joy: bandleader Maurice White's nonsense lyric, "Ba-dee-ya."

White's response to the word being gibberish: "Who the fuck cares?"

"September" (which, despite its name, was actually released in November of 1978), went on to sell more than a million copies for the Chicago-based band, peaking at No. 8 on the Billboard chart.

As for the specific date mentioned in the song, Willis said the 21st day of September has no special significance.

Still, it's something we all remember.

Listen to full interview at NPR:

16:51

Fla. shooter had an extremely troubled past

Fla. shooter had an extremely troubled past

Reuters

Disturbing information has emerged about Don Spirit, the man who gunned down his adult daughter and her six children on Thursday.Relative he killed years ago
16:51

Secession vote a real possibility for one US state

Secession vote a real possibility for one US state

Getty

A recent poll found that 1 in 4 Americans are open to seceding -- and current events have led many to believe it could actually occur.Where the idea is supported most
16:50

Accessing Native Features with Xamarin.Forms

1. Setting the Stage

When it comes to writing mobile applications, it's important to integrate with the platform specific features that are available to you when it makes sense. For instance, if you were writing a navigation app, it would make sense for you to use the geolocation features of the device and platform. If you were creating an app to help people with a vision impairment, you would want to integrate with any text-to-speech features that were available as well.

It's the developers that take advantage of these features that set themselves and their apps apart from the rest. These simple things take just an ordinary app and make it great. But what happens when you want to take advantage of these features, but you have decided to adopt Xamarin.Forms as your cross-platform mechanism of choice? Do you have to give up hope on these features just because you decided that your app needs to be cross-platform and you want to be able to share as much logic and user interface code as possible? Absolutely not.

These types of questions inevitably cause some issues for developers that adopt newer technologies such as Xamarin.Forms. Prior to the release of Xamarin.Forms, when you were working directly with Xamarin.iOS, Xamarin.Android, and Windows Phone project templates, accessing these types of features was fairly straightforward. From the Xamarin perspective, if you could find sample C#—or even native language and SDK documentation—for a particular feature, you could simply map your code to the native concepts, because Xamarin did such a spectacular job of translating the same native concepts on those platforms into C# language constructs. Windows Phone features were even easier because there was no translation necessary. All you had to do was read the documentation.

Luckily for us as developers, Xamarin has put a lot of time and effort into designing a mechanism for us to access these same features even if we choose to use their Xamarin.Forms abstraction layer. This mechanism is know as the DependencyService.

2. DependencyService Overview

At first glance, a name like DependencyService may seem a little intimidating. It sounds like some fancy programming terminology that only the elite few understand. If you have ever worked with Dependency Injection (DI) or Inversion of Controller (IoC) containers, you should feel right at home with the DependencyService. If you haven't, I assure you that it is a very simple concept to understand once you break it down into its components.

What Is the DependencyService?

At it's most basic, DependencyService is a class. It's a class whose sole purpose of existence is to allow you to register any number of classes throughout your application. By register, I mean take any class you have and make it known to the service. Once the DependencyService knows about a class, it can go and retrieve an instance of that class whenever necessary. That is the other purpose of the DependencyService. If at any point in your application, you decide that you need an instance of a class that has been registered in the DependencyService, you can request or get an instance of it.

When you really get down into the nuts and bolts of the DependencyService, this is a very broad generalization. But from a developer's point of view, that's almost all you need to know. However, there is one other concept you need to be aware of when working with the DependencyService, interfaces. When it comes to the DependencyService and all of this registering and retrieving, you are typically doing that with respect to interfaces. This means that when you register a class, you are registering it as an implementation of a particular interface. And when you are retrieving a class, you are actually asking the DependencyService for an implementation of that interface. At this point, you don't really care what the implementation is, you just want a class that implements this interface.

How Does the DependencyService Work?

Now that you have a basic understanding at a conceptual level of what the DependencyService is, let's dig a little deeper and see how it actually works.

To use the DependencyService, you need three things:

  1. Interfaces: An interface is simply a construct that defines what members must be present within any class that chooses to implement, or agree, to this contract.
  2. Registration: Registration is merely the mechanism of letting the DependencyService know that a particular class wishes to be registered and be able to be retrieved later on.
  3. Location: This concept is often associated with a pattern in software development know as the Service Locator pattern. This simply means that you can go to a single place, the DependencyService, and request some functionality, a class, without having to directly instantiate a new instance.

Let's dig into each one of these concepts in a little more detail.

3. Interfaces

Interfaces are very common occurrences in most Object Oriented Programming (OOP) languages these days. Using an interface allows you to define a contract that contains a series of properties, methods, events, etc., that must be implemented by any class that agrees to that contract.

Here's a very simple example of an interface and a class that implements that interface.

public interface IFileGrabber
{
     string GetFileContents(string fileUri);
}

public SimpleGrabber : IFileGrabber
{
     public string GetFileContents(string fileUri)
     {
          return GetFileFromFileSystem(fileUri);
     }
}

This seems like a very simple example, but it serves the purpose quite well. The IFileGrabber interface defines a single method, GetFileContents. The SimpleGrabber class agrees to or implements the IFileGrabber interface, which means that it must contain an implementation for the one method.

Now, instead of having to implement other code in your application directly against a concrete class, SimpleGrabber, you can start to reference the IFileGrabber interface instead. Imagine you have another class in your application that looks like this:

public class DataRetriever
{
    private IFileGrabber _fileGrabber;
    
    public DataRetriever(IFileGrabber fileGrabber)
    {
        _fileGrabber = fileGrabber
    }

     public string GetFileContents(string fileUri)
     {
          return _fileGrabber.GetFileContents(fileUri);
     }
}

By using the IFileGrabber interface instead of a concrete class, you have the ability to create other mechanisms to retrieve files from different places and the DataRetriever class wouldn't care. Let's assume we have another class that looks like this:

public class NetworkGrabber : IFileGrabber
{
     public string GetFileContents(string fileUri)
     {
          return GetFileFromNetwork(fileUri);
     }
}

You now care less about how the class or the GetFileContents method is implemented, you just know that at least the members that are defined in the interface are present and that means you can continue to code away using just that interface as a reference. This is an incredibly important concept when it comes to the DependencyService.

4. Registration

In the context of the DependencyService, Xamarin has made the process of registering a class quite simple. Since you already have defined your interface and at least one class that implements it, you can register it in the DependencyService using a very simple assembly attribute.

Let's continue using the above example and register the SimpleGrabber class. The class definition would now looking something like this:

[assembly: Xamarin.Forms.Dependency(typeof(SimpleFileGrabber))]

// Any namespace declaration that may exist

public SimpleGrabber : IFileGrabber
{
     public string GetFileContents(string fileUri)
     {
          return GetFileFromFileSystem(fileUri);
     }
}

All you need to do is add the assembly reference above your class definition and outside of any namespace definition that may be contained within that file as well. By doing this simple task, you will have successfully registered the SimpleGrabber class as an implementation of the IFileGrabber interface.

When registering a class, that class must contain a parameterless constructor in order for the DependencyService to instantiate it. In my example above, I haven't defined a constructor so the compiler will, by default, create a parameterless constructor for me.

5. Location

The final piece of the puzzle is getting an instance of a registered class. This is actually the easiest part of the entire process. To retrieve an instance of a registered class, you simply use the DependencyService class and it's generic Get<>() method. Here's a simple example:

public class FileHelper
{
    public string GetFileContents(string fileUri)
    {
        return DependencyService.Get<IFileGrabber>().GetFileContents(fileUri);
    }
}

In this case, at runtime, you don't care where the DependencyService is getting the concrete class that implements the IFileGrabber interface. All you care about is that the class implements the IFileGrabber interface.

6. Using the DependencyService

Now that you have a conceptual understanding of what the DependencyService is and how to use it, let's create a simple application to put it to use.

For this example, I will be using Xamarin Studio 5, but feel free to use Visual Studio 2013 if you wish. Start by creating a new solution. In the New Solution dialog box, under the C# category on the left, select the Mobile Apps project family. On the right hand side, select either the Blank App (Xamarin.Forms Portable) or the Blank App (Xamarin.Forms Shared) project template. The code and the resulting application will be the same regardless of the template you choose.

In this example, I will be using the Portable Class Library (PCL) version of the template. Give a name to the project. I will be naming the solution and first project DependencyServiceSample. Then click the OK button.

This process will create three separate projects:

  • DependencyServiceSample - Shared library (PCL)
  • DependencyServiceSample.Android - Android project
  • DependencyServiceSample.iOS - iOS project

Xamarin Studio doesn't support creating Windows Phone projects. If you are using Visual Studio, this process will create four projects. It will create the above three projects as well as a Windows Phone project named DependencyServiceSample.WinPhone.

In the shared library (DependencyServiceSample), create a new interface file and name it ISampleInterface and give it the following implementation:

namespace DependencyServiceSample
{
    public interface ISampleInterface
	{
		string GetData();
	}
}

The is a standard looking interface file that defines a simple method named GetData that will return a string. Once again, the important point to understand is that from the perspective of the shared code file, it doesn't care what the implementation of this interface looks like. The only thing that matters is that whatever implementation is provided for this interface, it has a method named GetData that will return a string.

Next, we modify the App.cs file to use the DependencyService to get an instance of the ISampleInterface to use in your Xamarin.Forms app. Modify the  GetMainPage method to look like the following:

public static Page GetMainPage ()
    	{	
			return new ContentPage { 
				Content = new Label {
					Text = DependencyService.Get<ISampleInterface>().GetData(),
					VerticalOptions = LayoutOptions.CenterAndExpand,
					HorizontalOptions = LayoutOptions.CenterAndExpand,
				},
			};
		}

Notice that the only difference is that the Text property of the Label has been changed to the following line:

DependencyService.Get<ISampleInterface>().GetData()

This way, you are using the DependencyService class and the generic Get<>() method to retrieve whatever implementation of the ISampleInterface is implemented in the platform specific project that is currently running. Once that instance has been retrieved, you are calling the GetData method to get back a string and set the Text property of the Label.

The last step has two parts (three if you are using Visual Studio). At this point, you will need to implement the ISampleInterface interface in all of the platform specific projects in your solution.

Let's start in the DependencyServiceSample.Android application. All you need to do is create a new class file in the project and give it any name you like. I have named mine Sample_Android. Replace the default implementation with the following:

using System;
using DependencyServiceSample.Android;

[assembly: Xamarin.Forms.Dependency(typeof(Sample_Android))]

namespace DependencyServiceSample.Android
{
    public class Sample_Android : ISampleInterface
	{
		#region ISampleInterface implementation

		public string GetData ()
		{
			return "I came from the Android project!";
		}

		#endregion
	}
}

This is a simple class that implements the ISampleInterface interface and its implementation is to simply return a string stating that it's coming from the Android project. The only difference is the use of the assembly attribute at the top of the file that registers this class with the DependencyService so that it can be retrieved later.

Now, let's create another implementation of this interface in the iOS project. Create a new class in the iOS project, name it Sample_iOS, and replace the default implementation with the following:

using System;
using DependencyServiceSample.iOS;

[assembly: Xamarin.Forms.Dependency(typeof(Sample_iOS))]

namespace DependencyServiceSample.iOS
{
    public class Sample_iOS : ISampleInterface
	{
		#region ISampleInterface implementation

		public string GetData ()
		{
			return "I came from the iOS project!";
		}

		#endregion
	}
}

The implementation is exactly the same as the Android version, except that it returns a different string stating that it's coming from the iOS project this time. The final step is to run the application and see if you are getting the result you are expecting.

Here is the result of the iOS application running.

  

Here is the result of the Android application running.

As you can see, both applications run successfully. Not only do they run, but they are successfully running from a shared Xamarin.Forms project that is controlling the user interface. From that user interface code within Xamarin.Forms, you are now able to dip directly into the platform specific projects to access native code.

7. Where to Go From Here

Now that you have the skills to use the DependencyService to get access to native functionality from Xamarin.Forms, the sky's the limit. You can continue to write simple implementations as you have done in this tutorial or you can start to tap into more interesting features of the platforms.

One of the most interesting resources to take a look at for integrating into your DependencyService is the Recipes section of the Xamarin website. Here you'll find platform specific implementations of getting access to a number of features including:

  • Networking
  • Audio
  • Video
  • Geolocation
  • Accelerometers

All of these features are at your disposal when it comes to Xamarin.Forms applications. With the DependencyService, these features can be summoned at a moment's notice.

Conclusion

Now that you know and understand the DependencyService, you no longer have to feel intimidated when you need to access platform specific features from a Xamarin.Forms application. You now possess the tools that allow you to tap into those amazing native features of the devices that will ultimately allow you to differentiate your apps from the rest in the app stores.

Next Step: Watch the Course

If you'd like to learn more about Xamarin, then check out our course Building Multi-Platform Apps With C# in Xamarin

In the course, you will learn how to create a cross-platform application from a single code base that will run on three distinctly different platforms: iOS, Android, and Windows Phone 8. Think it can’t be done? In just a little while you will be doing it yourself. Let’s get to work.

You can take the straight away with a completely free 14 day trial of a Tuts+ subscription. Take a look at our subscription options to get started or, if you're just interested in this course, you can buy it individually for $15! Here's a preview to get you started:

16:49

Serial Port Monitor 1.2.0.35 (Freeware)

A simple, yet effective utility that monitors serial ports, displays their status and logs events in order to track the activity on the selected port
16:42

X!Tandem Viewer (formerly XTandem Parser) 1.7.14 (Apache License 2.0)

A handy and reliable Java-based application designed for extracting mass spectra and peptide sequence data out of X!Tandem XML files
16:34

Clever Brightness Controller 3.0 (Freeware)

An application that is capable of automatically controlling your screen brightness level and the desktop contrast in order to protect your eyes and save resources
16:33

Lauren Conrad And William Tell's Wedding Picture Is As Pinterest-Perfect As You Imagined

We never doubted it for a second: Lauren Conrad's wedding photo is definitely Instagram-worthy, and it's just as Pinterest-perfect as you imagined.




Conrad wore a custom-designed Badgley Mischka Couture gown to wed William Tell on Sept. 13, and she later changed into a Monique Lhuillier gown for the reception.

The former "The Hills" star said "I do" in front of friends, family and 10 bridesmaids, because as she explained on her blog, "The more the merrier!"
16:30

Milan Fashion Week: Etro Spring/Summer 2015

Scenes from the Milan Fashion Week photo diary of Alfredo Piola.
16:28

Bill Murray and the Roles That Got Away

2014-09-19-murray2.2.jpg

Bill Murray has been doing things his own way since the beginning of his career. Not only does he operate without an agent or manager, but he seems to make it virtually impossible to contact him. He has a PO box somewhere in America, and if you're lucky enough to figure out where it is, you can mail your scripts to him. If you're extra lucky, and we mean lottery-winning lucky, he may actually check his mail that year. It's a small miracle that he learns about any offers at all.

It's not that Murray doesn't want to work. It's just that his way of playing the Hollywood game is distinctly different from the way everyone else plays it. This isn't necessarily a star trip, either, for he liked to keep people guessing long before he was scoring at the box office with hits like Ghostbusters (1984).

2014-09-19-ghostbusters2.jpg

For instance, Murray was so uncommunicative with the production crew of Caddyshack (1980) that they had no idea if he was going to show for his first day of shooting. Finally, just moments before his first scene was to begin, he arrived ready to bring the memorable Carl Spackler to life.

It may be an indifference to success that keeps Murray from being too readily available. Fame baffled Murray when it first struck, and he's admitted that the enthusiasm of his fans back in the 1980s was scary. "There's definitely a lot of trash that comes with the prize of being famous," Murray said. "It's a nice gift, but there's a lot of wrapping and paper and junk to cut through."

2014-09-19-billmurrayfans.jpg

Murray's casual attitude towards the movie business has occasionally cost him roles. Some of the top directors and producers in the industry have sought him out for major parts in their films, only to be turned down or totally ignored. A commonly heard phrase in Hollywood is "We wanted Bill Murray, but couldn't find him."

As we celebrate the rascally Murray's 64th birthday, let's take a quick look at some roles he missed or passed on, and wonder what might have been.



BILL MURRAY: FISH LOVER
2014-09-19-splash.jpg
Along with such stars as John Travolta and Michael Keaton, Murray turned down the lead role in Ron Howard's Splash (1984), the so-called "Cinderella story about a man and a fish." The producers then chose relative newcomer Tom Hanks. Murray, busy enough that year with his ghost busting activities, might have made the movie funnier (strike that -- definitely would have), but I can't quite imagine him as a lovelorn fellow pining over a mermaid, even one played by the striking Daryl Hannah. Still, it would have been fun to see Murray do scenes with the late, great John Candy!



BILL MURRAY: ACTION MAN
2014-09-19-starwars.jpg
Maybe I shouldn't count the time Murray auditioned for George Lucas, who had yet to cast the Han Solo role in a little sci-fi project called Star Wars (1977). Smirking Bill Murray in control of the Millennium Falcon? Even I think that one's a stretch. Besides, Bill was virtually unknown at the time -- but of course so was Harrison Ford. Then there was the time Tim Burton considered Murray for the role of the caped crusader in the 1989 version of Batman. This isn't as strange as it sounds, since the initial idea for the production was to echo the cheeky vibe of the old TV show. Murray as a sarcastic Batman? It might've worked like ghostbusters -- I mean gangbusters.



BILL MURRAY: FAMILY ENTERTAINER
2014-09-19-toystory.jpg
Director Robert Zemeckis and producer Steven Spielberg wanted Murray for the role of Eddie Valiant in Who Framed Roger Rabbit? (1988) But as has often happened in Murray's career, they couldn't reach him. Bob Hoskins, who wasn't known for playing comedic roles, took the part. Tim Allen also stepped up happily when Murray passed on playing Buzz Lightyear in Toy Story (1995), as did John Goodman when Bill rejected the role of Sully in 2001's Monsters, Inc. It's actually open to debate whether Murray really turned Sully down. He'd tested for the role and seemed interested, but then, (surprise, surprise) director Pete Docter couldn't find him to offer him the part. Oh well, at least Murray committed to the role of Garfield the cat. Twice.



BILL MURRAY: SENSITIVE INDIE STAR
2014-09-19-xunxhind.jpg
It's hard to imagine anyone but Steve Carell playing suicidal Frank Ginsberg in 2006's Little Miss Sunshine -- or is it? Truth is, the part was actually written for Murray. He would've done a great job, and maybe injected some extra nuance and poignancy into the character, but he didn't accept the role. It's a shame, really; Bill's presence would have brought a little extra "Sunshine" into all our lives. A year earlier he missed out on another intelligent drama, The Squid and The Whale . Director Noah Baumbach wanted Murray for the part of Bernard Berkman, eventually played by Jeff Daniels. We'll give you three guesses why didn't Murray get the part. That's right! Because Baumbach was unable to contact him. Bill: Pick up the phone, or better yet, get a phone!



BILL MURRAY: BROTHER IN NEED
2014-09-19-rainman.jpg
This is an occasion where it wasn't Murray's fault that he didn't score a role. Dustin Hoffman had worked with Murray in Tootsie (1982) and for Barry Levinson's Rain Man (1988), campaigned hard for him to play his brother, Charlie Babbitt. The producers, however, opted for one of the hot young stars of the moment, Tom Cruise. While Cruise turned in a respectable performance, one wonders what wise guy Murray might have done with the part. I say plenty. Of all the film roles Murray missed, this is truly the one that got away.



BILL MURRAY: JUST A LITTLE SIMPLE
2014-09-19-forrest.jpg
Bob Zemeckis was still trying to hire Murray to star in a movie, and actually got in touch with him for 1994's Forrest Gump. Unfortunately, Murray didn't care for the script (so I'm not the only one), and turned the title role down flat. So, Tom Hanks nabbed it and scored his second Oscar. Hanks should send Murray a thank-you letter every year for turning down Splash and Gump. On second thought, sending Bill a note might not be a good idea -- he'll never receive it!


Bill Murray may be less than accessible to the big Hollywood players, but he's always been accessible to us, his public.

______________
Best Movies By Farr gives you the best movies to stream, rent, or buy with just one click! We go beyond the expected, spotlighting outstanding titles you may have missed, overlooked or forgotten about. Start watching wiser today -- find your next favorite movie with Best Movies by Farr.
16:26
Science Has a Sexual Assault Problem
16:23

K-Lite Codec Pack Full 10.7.1 / Update 10.7.3 Build 2014.09.19 (Ad-supported)

A codec pack that will give you the ability to play 99% of all the movies that you download from the internet or that you already store on your system
Older posts are this way If this message doesn't go away, click anywhere on the page to continue loading posts.
Could not load more posts
Maybe Soup is currently being updated? I'll try again automatically in a few seconds...
Just a second, loading more posts...
You've reached the end.