Incorporating Ads into Your Windows Phone XNA 4.0 Game

August 16 | Posted by ExpansionFlow | Tutorials Tags: , , , , ,

UPDATE 02/17/2013:

This tutorial for embedding ads in your Windows Phone XNA Game is outdated.  Check back in the near future for an updated Tutorial.

 

The object of this tutorial is to help you integrate the Windows Phone Microsoft Ad SDK, version 5.2.622, into Microsoft’s GameStateManagementSample code found at:

GameStateManagementSample Code

If you are looking for a simpler solution, refer to the sample advertising code at microsoft.com.  After completing this tutorial, you will have a working solution for integrating ads into your latest free Windows Phone app.  The outcome is to provide ad-free game play while the game is running, yet to maximize advertising while the main menu or options menus are being displayed.

First off, if you have not done so already, you will need to download the GameStateManagementSample Code in order to complete the tutorial.  You will want to dowload GSMSample_4_0_PHONE.zip.  Unzip and then open the Solution in Microsoft Visual Studio 2010 Express for Windows Phone.

If you prefer to simply download the finished tutorial, it can be downloaded at:

GameStateManagementSample Code with Ads.

I. Add References to Appropriate DLL Files

Before doing any programming, you must add a reference to the correct advertising dll file, Microsoft.Advertising.Mobile.XNA.dll.  This will allow you to put ads into your application.  I have duplicated Microsoft’s directions here:

1.   In Visual Studio Solution Explorer, right-click References under your project and click Add Reference….

2.   In the Add Reference dialog box, click the .NET tab. Click Microsoft.Advertising.Mobile.Xna.dll to select it, and click OK

Advertising Reference

3.   In the Solution Explorer panel, you will see Microsoft.Advertising.Mobile.Xna.dll listed in the References folder of your project.

4.  Add a reference to the System.Device.dll file using the same steps as in 1 through 3.  This dll file will allow your ads to use content based on the geographical location of the Windows Phone user.

 

II.  Modifying the Game.cs file

5.   Open the Game.cs source code file, and add the following code in the using section of Game class code.

     using Microsoft.Advertising.Mobile.Xna;

6.   In the class variable definitions of the Game class (#region Fields) , add the variable that will store the game’s Application ID.

    private static readonly string ApplicationId = "test_client";

Later, when you are ready to submit your application,  or ready to test real ads, you will replace “test_client” with the applicationId as created on Microsoft Advertising pubCenter.

7.   Next, in the Constructor of the Game class (#region Initialization), you must initialize the AdGameComponent and add it to the game.  Insert the following code after the screenManager component has been added.

    AdGameComponent.Initialize(this, ApplicationId);

    Components.Add(AdGameComponent.Current);

8.   Later in the tutorial, we will designate a variable in the ScreenManager class to represent this component. We will set the ScreenManager’s AdgameComponent equal to this component here just below the code inserted above.

    screenManager.AdGameComponent = AdGameComponent.Current;

 

III.  Modifying the ScreenManager.cs file

9.   Open the ScreenManager.cs source code file, and add the following code in the using section of ScreenManager class code.

     using Microsoft.Advertising.Mobile.Xna;

     using System.Device.Location;

10.   In the class variable definitions of the ScreenManager class (#region Fields) , add the following variables.

     private DrawableAd bannerAd;
     public DrawableAd BannerAd
     {
         get { return bannerAd; }
         set { bannerAd = value; }
     }

     private AdGameComponent adGameComponent; 
     public AdGameComponent AdGameComponent
     {
         get { return adGameComponent; }
         set { adGameComponent = value; }
     }

     private static readonly string AdUnitId = "Image480_80";

     private GeoCoordinateWatcher gcw = null;

The DrawableAd will be the actual bannerAd that is displayed. This will be created later in the ScreenManager class. The AdGameComponent is set to be the AdGameComponent.Current as was instantiated in the Game class. The AdUnitId string, for testing purposes, is set to Image480_80. Other test variables for the AdUnitId are Image300_50 and TextAd. Later, when you wish to test real ads, or when you are ready to submit your application, this will be changed to the IDs that you created in Microsoft Advertising pubCenter. The GeoCoordinateWatcher is initially set to null, but later in the ScreenManager class will be set to the user’s current location.

11.   Next we will add a method to the ScreenManager class for creating ads.  This can be called by whichever file you desire.  In this tutorial, we will create and remove ads in the BackgroundScreen.cs file.  This file is chosen because it resides behind all menus and text in every file except the GameplayScreen.cs file.  Place the following code in the Public Methods region after the DeleteState() method.

      public void CreateAd()
      { 
         int width = 480; 
         int height = 80; 
         int x = (GraphicsDevice.Viewport.Bounds.Width - width) / 2; 
         int y = 720; 

         bannerAd = adGameComponent.CreateAd(AdUnitId, new Rectangle(x, y, width, height),
           true); 

         // Set some visual properties (optional).
         //bannerAd.BorderEnabled = true; // default is true
         //bannerAd.BorderColor = Color.White; // default is White
         //bannerAd.DropShadowEnabled = true; // default is true

         // Provide the location to the ad for better targeting (optional).
         // This is done by starting a GeoCoordinateWatcher and waiting for the location to
         // available.

         // The callback will set the location into the ad.

         // Note: The location may not be available in time for the first ad request.

         adGameComponent.Enabled = false;
         this.gcw = new GeoCoordinateWatcher();
         this.gcw.PositionChanged += new 
           EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>
           (gcw_PositionChanged);
         this.gcw.Start();
     }

12.   Now a method must be created to remove ads when you do not wish them to be displayed. Place the following code immediately below the CreateAds() method.

      public void removeAd()
      {
          adGameComponent.RemoveAd(bannerAd);
          // adGameComponent.RemoveAll();
      }

If only one is being run at a time, simply use the RemoveAd() code for removing one ad, otherwise, use the RemoveAll() to remove all the presently running ads.

13.   The last method to be added to the ScreenManager class is for updating the geographical location of the user. This will not be readily apparent when using the test ads, but once you have either submitted or inserted the actual banner ads as set up from Microsoft’s Advertising pubCenter will display and often include local ads. Below the RemoveAd() method, add this method.

      private void gcw_PositionChanged(object sender, GeoPositionChangedEventArgs e)
      {
           // Stop the GeoCoordinateWatcher now that we have the device location.
           this.gcw.Stop();

           bannerAd.LocationLatitude = e.Position.Location.Latitude;
           bannerAd.LocationLongitude = e.Position.Location.Longitude;

           AdGameComponent.Current.Enabled = true;
      }

IV. Modifying BackgroundScreen.cs file

At this point in the tutorial, we have everything we need to create and remove ads.  Now we simply must find where in the code to create and remove an ad for purposes of game flow.  In this demo, we want the ads to display anytime that the GameplayScreen is not running.   Since the BackgroundScreen.cs file is always running when the game is not in play, this seems like a perfect place.

14.   Insert the following code into the LoadContent() method of the BackgroundScreen.cs file at the very end of the method.

      ScreenManager.CreateAd();

Anytime the application begins or a game pauses or ends, the BackgroundScreen.cs file will load, and an ad will be generated.

15.  Insert the following code into the UnloadContent() method.

      ScreenManager.RemoveAd();

Now, whenever the BackgroundScreen unloads, such as entering into game play, the ad will be removed and the actual game portion of your application will be ad free.

V.   Conclusion

That’s it! You can now successfully run ads in your application that uses the GameStateManagementSample code.  You now have the ability to control when and where you want to display ads in your application.  Simply press the play button and watch the test ad be displayed on your development device.

If you had any difficulty following the tutorial, you can get the entire project code here.

Feel free to leave a comment below or email me anytime at scottlaforge@expansionflow.com.  Also, if you liked this tutorial, please click the Facebook Like button at the top right of the page.  Your support is greatly appreciated.

Tags: , , , , ,

28 Responses to “Incorporating Ads into Your Windows Phone XNA 4.0 Game”

  1. Minime says:

    I still get the WebException:
    A first chance exception of type ‘System.Net.WebException’ occurred in System.Windows.dll
    A first chance exception of type ‘System.Net.WebException’ occurred in System.Windows.dll
    A first chance exception of type ‘System.Net.WebException’ occurred in Microsoft.Advertising.Mobile.dll
    Ad error: HTTP error status code: NotFound (404)

    I have tried updating the location (in the emulator) and moving around the US/World but always WebException…

    I have tried emulator and device, I have tried with test values (test_client/Image480_80/Image300_50) and with real values. I have tried my own app, your example, the June example from MSFT.
    I have tried disabling auto refresh and calling “Refresh()” everytime an error occurs. I have received “NotFound (404)” for really long periods – never a successful call.

    I tried adding all capabilities but to no avail. I can’t get it to work.

    I live in Sweden but faking US coordinates in the emulator.

    • Scott says:

      I am going to be honest. I tried tons of times to get the ads to work in the emulator. They never did. I was told they should but was unable. They did sucessfully display on the Windows Phone.

      Are you connected to the Internet wirelessly? I did not get ads working until I connected directly and bypassed the wireless router. I was able to use Microsoft’s sample code and the code from the tutorial above. This might help.

      Keep me posted. I will try to help you figure this out.

  2. Hi I am trying to put advertisments in a phone game I am developing. When I add your code to a project I am getting . Error 1 Using the generic type ‘System.Device.Location.GeoPositionChangedEventArgs’ requires 1 type arguments C:\Users\Johnathan\Desktop\H1N1 window phone test\H1N1PhoneTest\H1N1PhoneTest\ManagerClasses\ScreenManager.cs 297

    the error seems to be in this code snipet

    private void gcw_PositionChanged(object sender, GeoPositionChangedEventArgs e)
    {
    // Stop the GeoCoordinateWatcher now that we have the device location.
    this.gcw.Stop();

    bannerAd.LocationLatitude = e.Position.Location.Latitude;
    bannerAd.LocationLongitude = e.Position.Location.Longitude;

    AdGameComponent.Current.Enabled = true;
    }

    it the GeoPositionChangedEventArgs e the is giving me the trouble. I am using System.Collection.Generic and need to for my generic lists in my Screenmanager class. any thoughts on why this is happening.

    • Several things. Which version of the SDK are you using? This was posted prior to 7.1. Also, where are you located? I had terrible troubles until I got some support from Microsoft and this seemed related to their servers. Even they never figured out why it wasn’t working, and then suddenly it did. Also, try removing all the references to the geolocations. Are you getting Microsoft’s test ad to run?

      • Johnathan Witvoet says:

        Sorry for late response I am using 7.1 I just had too, like you said take all the references of the geolocations out and it works fine now. I also put in a way that I can change position for every screen if I wanted too. Thank for your help.

      • jonathan says:

        I;m also facing the same problem? Which reference to remove?

        • ojas says:

          This is a type problem, in this you have to change private void gcw_PositionChanged(object sender, GeoPositionChangedEventArgs e) and you are done.
          Enjoy

  3. Jordi van der meer says:

    Ok i got a error when i try this with the script4fun towerdefence

    Error 1 An object reference is required for the non-static field, method, or property

    ScreenManager.CreateAd();
    How can i fix this?

  4. Jordi van der meer says:

    Ok i fixed the problem but now i got a new problem, The game starts but when i get to the help page with the ad , it got a nullreferenceException

  5. Jordi van der meer says:

    Ok maybe it is todo with the portret mode? and the game uses landscape? could this throw a Exception

  6. Jordi van der meer says:

    Ok it isnt that, I think it has to do with the content manager, because i fixxed the object reference with screenmanager screenmanager but you code sample says someting about contentmanager how can i fix this ? iam trying this with the coding4fun tower defence.

  7. Jordi van der meer says:

    In the Aliengame example it doesnt work either, No errors but nothing appears:(

  8. Jordi van der meer says:

    Ok maybe you could also explain how to add a trail mode in a multi screen game?

  9. Jordi van der meer says:

    OK LOL, The test ad in you sample wont show either.

  10. Jordi,

    Where are you located? What version of the SDK are you using? Are you connected wirelessly?

  11. Jordi van der meer says:

    Based in netherlands,but the test ad first worked in the sample, but now a few days later it wont work ?? nothings shows and iam using the latest ad sdk

  12. I can try to take a look at it sometime today. Swamped with work for a December 1st deadline. Send me a link where I can download the code.

  13. Jeff Vaccaro via Facebook says:

    Thanks for your help with incorporating ads into my very first game! Your help has allowed me to understand more about XNA. Thanks again!

  14. Thanks a lot, Jeff! Let me know if I can be of any more assistance.

  15. JD says:

    Hiya.

    All seems to work, except from the Geo locations.
    What would be the simplest way to rotate (or turn) an advert from portrait to landscape whilst in portrait mode?

    Thanks

  16. ojas sinha says:

    Hi,
    When i am trying to implement Screenmanager.AdgameComponent = AdGameComponent.current;
    It is giving me the null reference exception .

  17. Umair says:

    rename the function as

    private void gcw_PositionChanged(object sender, GeoPositionChangedEventArgs e)

    it removed the error and made my game run, but the ad is still not showing.

    The ad banner however shows on the test_client so since I am in Japan, I am guessing that there are no location based ads for japan supported by in app advertising

  18. [...] using Microsoft.Advertising.Mobile.Xna; 4. then follow the instructions on expansionflow – Incorporating Ads into Your Windows Phone XNA 4.0 Game Share [...]

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>