Tuesday, April 15, 2014

VSLive Chicago - Unity and WinJS

I’ll be speaking at Visual Studio Live!, May 5-8 in Chicago, IL http://bit.ly/CHSPK27_ Surrounded by your fellow industry professionals, Visual Studio Live! provides you with immediately usable training and education that will keep you relevant in the workforce.

I’ll be presenting the following sessions:

Developing Awesome 3D Applications with Unity and C#/JavaScript
Windows 8 HTML/JS Apps for the ASP.NET Developer

SPECIAL OFFER: As a speaker, I can extend $400 savings on the 4-day package. Register here: http://bit.ly/CHSPK27_

Amplify your knowledge at Visual Studio Live! Chicago — bring the issues that keep you up at night and prepare to leave this event with the answers, guidance and training you need.  Register now: http://bit.ly/CHSPK27_Reg

Hope to see you there!!!
Adam

Saturday, April 5, 2014

Why and how to Port your Unity game to Windows and Windows Phone


This post is part of 3 week series giving current and aspiring game devs the tools, resources, and advice they need to get started building for Windows. Check out the overview of the series to find what you need. For additional resources to build your app check out AppBuilder.

If you are an existing Unity developer, please ensure you check out our current offer here where you can get FREE STUFF and a potential for store promotion .

Porting your game to Windows 

Why would you want to do that?

Let’s start this off asking the most important question. Why?
As an Indie game developer myself I fully believe in today’s economy, developers should look at building for multiple platforms. There comes a point though where you can feasibly only support so many platforms given your own resources.

Windows Phone 8 is the strong third phone platform globally. With that said, Window Phone is currently growing faster than the phone market, and as of the latest figures is beating iPhone sales in 24 countries including India and Mexico, and is #2 in 10+ countries. There are more than 14 million downloads a day of apps on the phone alone. That’s nothing to shake a stick at.  The Lumia 520 512 MB phone has sold more than any other Android phone – EVER. Again, not too shabby!

Windows Store applications run on the Windows 8 platform, not the phone which targets 3000+ different devices from hand held small tablets, larger tablets, laptops of all sizes, and of course desktop systems as well. Some folks new to the platform think this means only tablets, like a Microsoft Surface tablet. That’s not the case. Windows 8 runs on many device types as listed above. Every one of them can run a Windows Store app on it.

There is an ever so slightly different build and submission process for Windows 8 apps (ie Windows Store apps) than Windows Phone even though they share a lot of the same common features. We just announced Universal apps at our //build conference being the first platform to be able to take a single code base and go from phone to tablet to desktop to Xbox. Windows 8 in addition has sold over 200 million licenses. Each of those instances by default have access to the Windows Store on them, the marketplace to download and install applications.

With a fairly easy export between platforms, why not target another large ecosystem that isn’t yet oversaturated with apps? There are over 400K apps between Windows Phone and Windows 8. Not a bad number, but definitely not oversaturated. There’s still plenty of room for you to bring your apps on over and be effective. Don’t take my word for it though:
Pat Toulouse, President and Founder of RatRod Studio
“The process of porting our games to Windows and Windows Phone was very straight forward. Since then, it has helped us extend our reach by generating over 5 million downloads within the past 6 months. And this continues to grow rapidly”.
Magma Mobile’s CEO Nicolas Sorel: first 1,000,000 downloads in 2 ½ months of being in the Windows Phone Store, and had 1,000,000 additional downloads in the last 30 days.”


So.. what’s required?

  • Unity (I recommend the latest version. There are important Windows related changes in every build)
  • Developer account to publish to the stores available here
  • Windows 8 / 8.1 (Free trial http://technet.microsoft.com/en-us/evalcenter/hh699156.aspx)
    • Windows 8 is freely upgradable to Windows 8.1
    • If you are on a mac see these links for getting Windows 8 running on it. You can either use boot camp or install it as a virtual machine running inside of OSX. For some common instructions here see
  • Visual Studio (Retail or the free Express edition)
      • If you have the retail version of Visual Studio 2013, you are potentially all set. You may need the Windows Phone 8 SDK installed however and that is available here
      • If you want to dev for Windows Phone 8, here’s the free version
      • If you want to dev for Windows Store (Windows 8) here’s free the version
We have an awesome program for startups called BizSpark. It gives startups free software including Windows, Office, Visual Studio, and access to the Windows / Windows Phone Store - for free. Check it out at www.microsoft.com/bizspark. Note that you can download 90 day trials of Windows 8 as well to do testing on if you need a quick way to get up and running on Windows.

Coming from other platforms

There’s something to be aware of when you’ve been used to working on other platforms. Typically when you run your game on for ex. ios / android, the Mono framework is used. Your app is compiled against that framework as .NET is not natively supported  on those platforms. Mono in the case of ios uses AOT (ahead of time) compilation because of ios restrictions preventing JIT (just-in-time) compiled code. As such, your game is developed with Mono which is what the Unity Editor runs, and your game is deployed and runs.

Enter in now .NET. Mono was essentially based off of Microsoft’s .NET. As such most of the api is cross compatible but Windows Phone 8 and Windows 8 share a common kernel between them and support a newer API. Some objects were dropped along the way and new ones added. You’ll find things like Hashtable & ArrayList to be deprecated on these system’s apis. This created a bit of a problem in the past as a lot of Unity C# code referenced these collections. When Unity would call .NET to compile the code, exceptions would be thrown over the missing collections.

As of Unity 4.3, UnityScript (Javascript) is now supported as it previously didn’t created compliant .NET code for WP8 and W8, but it does now. As of Unity 4.3.3 however, Unity has now added in a WinRtLegacy.dll into your builds. This includes a lot of the missing classes that caused issues before in your builds and UnityScript is supported as well. In other words, the support is now awesome to easily target Window Phone and Windows Store.

Let's get to porting!

unity to windows
The basics of porting are pretty simple:
  1. Switch platform in Unity
  2. Set player settings (images, icons, etc)
  3. Build from Unity which creates a Visual Studio solution
  4. Open solution in Visual Studio
  5. Test the project and deploy to devices or local system (Note debug builds are slow, master builds are fastest more on this below)
  6. Upload to the Windows Store and Windows Phone Store

Switch Platform in Unity

Expect on any platform to have some issues because of platform differences or potentially calls you make via plugins on one platform that another platform won’t support. The typical way in Unity code to handle this is to include a preprocessor directive to separate out your code.

When you switch your build settings to target another platform, you cause a variable that represents your platform to be true. For example, if in Unity you set Windows Store Apps to be the current platform by clicking on “Switch Platform”, behind the scenes the value of UNITY_METRO will become true. As is typically a safe bet in Unity, this code you generally run outside of the Unity Editor, hence the second part of the statement: && !UNITY_EDITOR although you surely could test this code out in the editor if the scenario fits.

For a listing of the variable names that you can reference see here
Windows Store Build

The three important Windows ones (to me) are
Precompile Constant True when platform is
UNITY_METRO Windows Store (Windows 8)
UNITY_WP8 Windows Phone 8
UNITY_WINRT Either of the above
An example of usage is:

#if UNITY_METRO && !UNITY_EDITOR
     //Any platform specific code here
#endif

If you have platform specific libraries in your /Assets/Plugins folder, then you likely this will be compiled using Mono and must be .NET 3.5 compatible, this is a general Unity rule. If you have any libraries in /Plugins/WP8 or /Plugins/Metro, those will be swapped out at compile time. This is how the Unity plugin system works. For more information on writing a plugin for Unity & Windows Phone see here.

Setting player (platform) settings & building your project

In Unity click on the Player Settings icon from your Build settings.
Player Settings
Under your player settings there are a few important things to note.

On future builds, Unity will only overwrite the /data folder in the project that was generated. Any changes you make _in the player settings_ after you have already clicked Build in Unity and generated your solution/project, will not be overwritten in the visual studio project. For example, if you build your project from Unity, and then decide later to change the project name in Unity for your Windows Store build (in your player settings), Unity will not overwrite your project it created already. If you haven’t made any custom changes to your Visual Studio project (see my video link below from //build 2014 if you are interested in that) then you could simply delete your build project folder and have Unity recreate it. The other option if you don’t want to remove your project is you manually make the changes in both Unity and in your Visual Studio project.

Windows Store (Win8) Typical Player Settings

windows store icon
  • If you need to access the internet OR profile your app (which requires network access), you will need to check off the Internet Client capability as your app cannot communicate with a network without it. If you check this off, you MUST set a privacy policy URL when you are submitting your app to the store or you will get rejected. If your application does not communication with the Internet, I’d recommend ensuring this isn’t checked off (and it is not set by default) so you won’t need a privacy policy url. Note that the store submission process won’t force you to set a url during your submission process, so it’s something you need to know to add if you require access to the internet from your application directly. If you use a third party plugin that uses Internet access for ads or leaderboards, then you will require this capability.
  image
  • Ensure your project name doesn’t start with a number or an underscore, as this is not a valid app name. You can fix this once your Visual Studio project is created though in your package.appxmanifest file if by chance you’ve missed this. You’ll actually see a red X when you open that file to show you where you need to change it.

  • There are quite a few settings you can have for a Windows Store application. Most of the defaults will serve you well but you’ll quickly notice under Publishing Settings there are many images you can set. Why so many images? Well – you can have an image show up as a small icon in your Windows program list (30x30), a larger icon if pinned to the start screen (150x150 for a medium tile, 310x150 for a wide tile) , a splash screen (620x300), an image to show in the Windows Store (50x50). Unity will show you the sizes required. I wrote a basic utility to resize a square image and create several output images by simply dragging and dropping. You can see a demo of that in the //build video linked at the bottom of this post and the url is http://aka.ms/wsip. There are also more icon resources listed at the bottom.
player images windows store

Windows Phone Typical Player Settings

windows phone icon
  • As of now, you cannot set the Windows Phone icon in Unity. You must do this in your Visual Studio solution inside of the /Properties/WMAppManifest.xml file.

  • You can force the orientation in Unity by setting Default Orientation as shown here
Orientation

Creating the build

 
You’ll notice in the build settings there are several build options. Which one to choose?
With Visual Studio 2013, you develop for Windows 8.1. Windows 8 folks cannot run a Windows 8.1 app. To target both you can just compile for Windows 8. not everyone has upgraded yet to it’s not a bad idea to target both.
You can compile but are limited in some modifications of a Windows 8 project in Visual Studio 2013. Only a Windows 8.1 project in VS 2013 has no restrictions. However Visual Studio will prompt you to retarget a Windows 8 project to Windows 8.1 when you first open it or you can right click on your project and select “Retarget to Windows 8.1” in Visual Studio as well. You may ask ‘then what can I manage a Windows 8 (not 8.1) project with?” and the answer is Visual Studio 2012-> Windows 8 and Visual Studio 2013->Windows 8.1, although as I mentioned you can compile and make some changes to a Windows 8 project in Visual Studio 2013.

Once you have set your player settings, simply click the build button in the build settings window. You’ll be prompted for a folder to select. I prefer to typically create a folder called “Builds” that will contain all of my platform build projects and I can then source code control each version relatively easily. Unity will then create a Visual Studio solution and a project file.
A Visual Studio solution file is not much more than a listing of one or more projects your solution will contain. For example, I can have a solution that contains projects for Windows 8, Windows Phone 8, XBox, and other code projects I want to use, it surely isn’t limited to just one project at a time that you can have open in Visual Studio.

Open project in Visual Studio

Now that the project has been created, Unity will open the folder in Explorer that contains your build’s folder. Go into your build folder and look for the solution file and open it up. Visual Studio should open up. If you get prompted for the version, ensure you select which version you are trying to open it in – Visual Studio Express for Windows Phone if you are trying to use that build of course.

image


Compile and Test the project

The first thing to notice when Visual Studio opens if what type of build you are currently going to create. The default for both Windows Store and Windows Phone are “Debug” builds. There are actually three build types, three platform (processor) types, and you may or may not use every one. On top of that there are several different places you can run your build – locally, on a device, on a simulator, on an emulator, even on a remote networked machine. Let’s see what all the options are used for:

Build Types

image
Debug – Contains un-optimized code full of debug symbols and typically has a much slower frame rate, on the flip side it contains potentially crucial debugging information. If your game seems to run slow, the first thing is to always note you may be testing a debug build. I’ve seen this countless times and once you change to a release or master build, the problem disappears.

Release – This build contains optimized code but still supports the Unity Profiler so there is still a performance hit, although significantly different. Contrary to typical .NET applications, this is NOT the build you will use to send to the stores.

Master – This is the completely optimized game. There is no profiler support nor is there debug information. This is the build to send to the store. There can be only one Smile
Platform Types

image
Choosing these will change which files get included into your build and how your build is compiled. If you select ARM, the Unity native code player files for ARM are included in the build. If you select x86, the Unity native code player files for x86 are included.
ARM – Only choose this if you are creating a build to run on a system that is ARM based. Let’s talk about both project types that use this for a moment. It’s very important to understand the use cases.
Windows Store projects – You only choose ARM in two cases. First is if you are your builds to upload to the store for a small subset of Windows 8 devices – those running on ARM. Most Windows 8 devices run x86 processors so you typically want the x86 build. You should actually create both builds to send to the store – ARM & x86. ARM is the default build type when you first open your project. Note that for local testing you will _always_ choose x86 – not x64, not ARM unless you are deploying right then to a tablet for testing that you know is an ARM based tablet (there are only a few models that are ARM based). The first time you load your project, change this setting to x86 so you can test locally.
Windows Phone 8 projects– You want an ARM build ONLY if you are creating a build right now to upload to the store or about to deploy to a phone for testing. If you are wanting to only run it in the emulator instead, you would actually want an x86 build not an ARM build.
x86 – You will choose this when
Windows Store projects – You want to create a build to run on your development system, submit a build to the store that will run on the vast majority of Windows 8 devices (you should create a build for ARM and also x86 for that situation to make sure you can deploy to every single Windows 8 device type)
Windows Phone 8 projects – Only when you are building to run in the emulator. There are no other times you would select x86 for a Windows Phone build.
x64 – As of this point, you will not use this platform type – at all. Unity does not make a 64 bit player for Windows phone or Windows Store.

Check out the //build video at the end for how you can debug Unity code in Visual Studio. You can’t do this in development without a third party plugin (UnityVS – well worth it - available here) but you can do this after you’ve built your solution from Unity out to Visual Studio by adding another project to your solution. The file to add is Assembly-CSharp-vs.csproj and this is a file that Unity creates for you.

 

Upload to the Windows Store and Windows Phone Store

These steps are pretty easy, and it's the last steps to get your game in even more hands. There are specific certification requirements for each store and you can help meet those requirements by reading the following links but also running the test kits on your application.

Windows Store

Submitting your app
App Submission Checklist

The process in short is build your package, test it, submit it.

Some things to be aware of:

  • You should support touch & keyboard/mouse unless you note otherwise as noted in section 6.13.4
    • 6.13.4 If your app doesn’t fully support touch input and fully support keyboard and mouse input, you must disclose that in the description elements of the app
  • If your application communicates with the Internet in any way, even through a third party ad sdk, you will need to specify a privacy policy url when you are submitting your app to the store. This will not be required on submission, so note you must add it. A privacy policy can easily be generated and there are easy ways to set this up for free. See Jim's great post here.

The process

Go to the following menu. In Visual Studio Express use the root "Store" menu instead of the Project menu as shown here for Visual Studio Ultimate Edition. If this menu doesn't have the items active, ensure you have your current project highlighted (and file in it) inside of the Solution Explorer window of Visual Studio. If you have the Solution file itself highlighted (the first item in the tree typically on the right) the menu options won't be active. You will be prompted then to login with your Microsoft account (see requirements section up top for a link to register for your dev center account). This will query the developer center for your existing apps and also allow you to specify a name for an app you can reserve for up to a year before you publish.





Specify a build location for your files. Ensure you check of BOTH x86 and ARM as is shown below. This is because you should support both platform types.


Once done, you can now test your application. Click on Launch Windows App Certification Kit. While passing this doesn't guarantee approval, it does run a lot of the same checks that are run on the store side. Also click on the "Output Location" link shown below to open the folder with the files you will need to upload to the store. You can run the test kit any time by searching for "cert" on your systems (press the windows key and type cert on the start screen).


Note the opened folder below and the two .appxupload files. These are the files that will need to be uploaded to the store.


You will also need screenshots to send to the store. These are accessible in the Project->Store->Capture Screenshots menu item. This will launch the Simulator on your local machine so you can grab the screenshots. Note that this will change your project startup location from "Local Machine" to "Simulator". If you want to continue to test locally, make sure you change this back to Local Machine.



You are all ready to upload your files. Go to Project->Store->Upload App Packages and you can go through each step. For more details on that process see Submitting your app.


Windows Phone Store


This process is a little shorter. You can run the tests for the phone project first via the Project->Open Store Test Kit menu option.  First you'll want to create your app package by ensuring you have the proper build settings. Once that is set simply go to the Build->Build Solution menu.



 Make sure you have specified an icon outside of the default Unity icon. This is in the WMAppManifest.xml file as shown below


Open the folder your project is in (you can right click on your project and select "Open in file explorer"). Once the folder opens simply type .xap in the search window in the upper right hand corner. This will search your folder for the .xap file you need to upload. Note that you only need the ARM version, NOT the x86 as that was just for the emulator.


Go to http://dev.windowsphone.com and click submit to begin the process, this is a shorter process than the Windows Store. When prompted, you'll upload the file noted above.

That's all there is to it! If you have any questions please contact me at microsoft.com with the first part intentionally separated of my email address of adamt :) Enjoy!
Resources:
Unity’s site for Windows
Unity & Windows Porting Guidance
//build 2014 conference video - Building your first Windows game with Unity
Choosing your app images
Guidelines for tlies and badges

Wednesday, February 26, 2014

Continually rotate an object in Unity

In games it’s a very common task to rotate/spin an object continually, such as a coin, treasure box, health pack, weapons, etc. In Unity this is extremely simple. As with anything, there are multiple ways of doing it ex code or a particle system, but if we wan’t a quick script to do it, simply assign this script to your GameObject
    private int _rotationSpeed = 90; //degrees per second = 4 seconds for a revolution
    void Update()
    {
        //Since deltaTime is the elapsed time since the last frame, 
        //let’s assume its one second. 1 * 90 = 90 degrees per second. 
        //Simple, right? Rotate’s parameters is (x,y,z, coordinate system)
        transform.Rotate(0, _rotationSpeed * Time.deltaTime, 0, Space.World);
    }
Voila - A spinning object!

There is however a basic optimization we can do here. Even though it seems that this is pretty simple, we can cache our transform. This prevents having to cross over from the 'managed' type of code that c#/mono/.net provides across boundaries into the native code from the c++ based engine that Unity wrote. This type of transition is slow so we can optimize it a little bit as follows by getting a reference to it upon start which is then stored in our c# code. We can then access it without having to do an extra hop into the native c++ code that the Unity engine runs on.
    private int _rotationSpeed = 90; //degrees per second = 4 seconds for a revolution
    private Transform _transform;
    void Start()
    {
     //cache the transform in our managed code side
      _transform = transform;
    }
    void Update()
    {
        //Since deltaTime is the elapsed time since the last frame, 
        //let’s assume its one second. 1 * 90 = 90 degrees per second. 
        //Simple, right? Rotate’s parameters is (x,y,z, coordinate system)
        _transform.Rotate(0, _rotationSpeed * Time.deltaTime, 0, Space.World);
    }
treasure spin

Thursday, February 6, 2014

AWESOME & FREE Unity Event on Saturday Feb 15th, 2014


Southern California
Free Unity Learning Events and Porting Lab on Saturday, February 15th, 2014

We sure have an awesome day planned out for you!

****** Please Note, there are THREE free events that are going on this day that you can attend, please read about each event and register for each event you want to attend individually. Did I say each event is FREE along with food & beverage? Note that parking is reduced to be a max of $10 for the day with validation. Please bring parking stub into the event for validation ****

Session #1 @ 10:00 AM – 2:30 PM
http://unitynewfeat.eventbrite.com
Join Microsoft & Unity for a technical deep dive that covers the new features in Unity 4.3 with focus on how to create a 2D game and the character animation controls with Mecanim. By the end of the session you will be able to create a 2D infinite runner gamer person starting with importing artwork from the Asset Store, creating a playable game in Unity and exporting it to the Windows Phone 8 and Windows 8 Store.

Session #2 @3:00 PM – 6:00 PM
https://unitydeepdive.eventbrite.com
Taught by Carl from Unity, this session aims to build upon the foundations of Unity to learn how to create a third person character controller with Unity's awesome animation system, Mecanim. After that, we'll learn some tips & tricks for doing particle effects (like explosions) in Unity with Shuriken, Unity's very powerful particle system.

Following that we'll have some special guests from Tic Toc Games showing off some of their cool Unity work and talking about the game development process and making successful games.

Session #3 10:00 – 6:00 PM (running concurrently to the other sessions)
http://portyourapp.eventbrite.com
Unity Porting Lab - Join us to port your existing Unity games to Windows. Why? Windows Phone is outselling the iPhone in 24 markets. Windows 8 has surpassed 150 million licenses. The time is now to push your apps out in a marketplace that is not overly saturated. Microsoft will provide free onsite technical assistance to help  you port your existing Unity app(s) over to run on Windows 8 and Windows Phone 8 platforms. We'll have devices to test on too! If you have any interest in getting your app on the Windows platforms, this is the event to go to! Bring your laptops or desktops that you use for development (Windows or OSX) with your games on them and we’ll help get you setup and start you on the porting process.  This will run concurrently to the other events. If you want to go back and forth between this event and the others, please register for both so we know which time group you’ll be in (you can register for all three if you’d like as well)

**** If you plan on staying for more than one event, please register for each one separately so we can have an accurate count for food & beverage.****

Location
Microsoft - The Reserve, Playa Vista Office
13031 W. Jefferson Blvd., LOS ANGELES, CA
Turn onto Alla (towards Home Depot) from Jefferson at the stoplight of Jefferson & Alla (Home Depot is on the corner)
Go to the end of the street and turn left into the last lot on the left. Take a ticket and be sure to bring it in with you.
Once in the lot, turn left in the first few rows and park as close to the buildings as possible. Enter the walkway in the center of the complex there and Microsoft is on the left hand side a few doors down.
The office entrance is just about exactly where the marker shows up in Bing Maps http://binged.it/LOgoRt

See you soon!
Adam Tuliper
Microsoft Technical Evangelist
(PS if you don’t follow me on twitter, follow me here for future updates, unity info, and more! http://twitter.com/adamtuliper)

Wednesday, January 8, 2014

Facebook & Microsoft Hackathon on January 17th


Join us for a Facebook & Microsoft Hackathon in NoCal on January 17th!!



Why you should attend:
  • Learn how to build apps for Windows and Windows Phone
  • Learn how to integrate Facebook Login into your Windows and Windows Phone apps
  • Learn how to use Parse to make building your apps easier
  • Come ready to hack with Microsoft and Facebook engineers!
  • There will be food, drinks, and prizes!

Who should attend:
  • This is a technical event and best suited for Windows and Windows Phone developers

Agenda:
  • 6:00 - 6:30PM: Check in and registration at Building 15
  • 6:30 - 7:00PM: Welcome and Overview of Facebook Login
  • 7:00 - 7:30PM: Intro to Developing for Windows and Windows Phone
  • 7:30 - 8:00PM: Building Windows / Windows Phone Apps with Parse
  • 8:00pm, Friday 17th - 11:30AM, Sat 18th:  Hack with food and drinks and support from our engineers
  • 11:30am - 12:00PM: Wrap up with prizes

Don't miss this chance to learn how to build Windows and Windows Phone apps and connect them with Facebook's 819 million mobile active users!


Please RSVP as space is limited!

Is there really no difference between a partial view and a regular view in MVC?

The question


I've read several posts on the net about there being no real difference between a partial view and a regular view in ASP.NET MVC, only that the convention of using them was different. Is this really the case?



I decided to find out the details for myself as part of the new "MVC for Web Forms Developers" course I'm working on for pluralsight.com so I could see exactly what all this entailed outside of just being a convention difference. Let it be known, there is indeed several differences you should be aware of. This post isn't meant to state when you should use one vs the other, there are plenty of resources for that. Here we just want to delve into how they are different, which in turn can help you decide when to use a View vs PartialView (and to confuse things more the decision there is really View vs PartialView vs Html.Action vs Html.Partial vs Ajax in any combination)


The differences


The differences that were obvious from the code are
  1. Partial Views don't have a layout processed. Very important to know.
  2. Partial Views don't check for a _ViewStart.cshtml. Note this is typically where layouts are specified but technically you could specify one in your partial and it would be ignored. Very important to know.
  3. Partial Views can throw a slightly different exception, the details included to InvalidOperationException in PartialViewResult vs ViewResult classes. This is pretty minor.

There is a slight difference in how they are processed.
Lets look at the code, shall we?

First, the differences between a PartialViewResult and a ViewResult as contained in the following files from the MVC source code:
  1. c:\source\aspnetwebstack\src\System.Web.Mvc\PartialViewResult.cs (link to source here)
  2. c:\source\aspnetwebstack\src\System.Web.Mvc\ViewResult.cs (link to source here)


Lets dive into FindPartialView and FindView. These are the functions called when you "return View()" and "return Partial()" from inside a controller.

The comparison of PartialViewResult and ViewResult


First check out a comparison side by side, this may give you an easy quick view with one of the best tools of all time,Beyond Compare


The codez


 public virtual ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }
            if (String.IsNullOrEmpty(partialViewName))
            {
                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "partialViewName");
            }

            string[] searched;
            string controllerName = controllerContext.RouteData.GetRequiredString("controller");
            string partialPath = GetPath(controllerContext, PartialViewLocationFormats, AreaPartialViewLocationFormats, "PartialViewLocationFormats", partialViewName, controllerName, CacheKeyPrefixPartial, useCache, out searched);

            if (String.IsNullOrEmpty(partialPath))
            {
                return new ViewEngineResult(searched);
            }

            //********* note the call here to CreatePartialView *****
            return new ViewEngineResult(CreatePartialView(controllerContext, partialPath), this);
        }

        public virtual ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }
            if (String.IsNullOrEmpty(viewName))
            {
                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "viewName");
            }

            string[] viewLocationsSearched;
            string[] masterLocationsSearched;

            string controllerName = controllerContext.RouteData.GetRequiredString("controller");
            string viewPath = GetPath(controllerContext, ViewLocationFormats, AreaViewLocationFormats, "ViewLocationFormats", viewName, controllerName, CacheKeyPrefixView, useCache, out viewLocationsSearched);
            string masterPath = GetPath(controllerContext, MasterLocationFormats, AreaMasterLocationFormats, "MasterLocationFormats", masterName, controllerName, CacheKeyPrefixMaster, useCache, out masterLocationsSearched);

            if (String.IsNullOrEmpty(viewPath) || (String.IsNullOrEmpty(masterPath) && !String.IsNullOrEmpty(masterName)))
            {
                return new ViewEngineResult(viewLocationsSearched.Union(masterLocationsSearched));
            }
            //********* note the call here to CreateView *****
            return new ViewEngineResult(CreateView(controllerContext, viewPath, masterPath), this);
        }

The differences in view processing


The function calls below to create a partial view or a regular view do indeed differ. One has a pipeline that uses a layout, the other doesn't. The regular view processing uses viewstart pages as well. For those unfamilar with the viewstart file, this is a file MVC looks for since MVC3.

MVC will look in the /Views/Shared folder and in the current view folder as well for a file named _ViewStart.cshtml. This file contains code that will be executed before the view is processed, typically it's used to store the path to the layout in it and again, can be set for all views or overridden in a particular views folder, ex /Views/Customer/_ViewStart.cshtml to set a different Layout for views in that folder as one example.
@{
    Layout = "~/Views/Shared/_MasterPage.cshtml";
}
protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
        {
            //**NOTE a partial view has a null layout and runViewStartPages is false! **
            return new RazorView(controllerContext, partialPath,
                                 layoutPath: null, runViewStartPages: false, viewStartFileExtensions: FileExtensions, viewPageActivator: ViewPageActivator)
            {
                DisplayModeProvider = DisplayModeProvider
            };
        }

        protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
        {
            //note the usage of a masterPath below.
            var view = new RazorView(controllerContext, viewPath,
                                     layoutPath: masterPath, runViewStartPages: true, viewStartFileExtensions: FileExtensions, viewPageActivator: ViewPageActivator)
            {
                DisplayModeProvider = DisplayModeProvider
            };
            return view;
        }



In closing


So there are some differences as probably expected. Nothing groundbreaking but it is important to understand the shortcut pipeline the PartialView takes hence making them perform a bit better as well. Ok, now you know the exact differences and have seen it from the source, in other words - heard it from
Enjoy!

Sunday, October 27, 2013

Unity - Failing Store Submission or WACK with Windows 8 Games

I was helping a developer in porting their game to work on Windows 8. They had done the export in Unity (Build Settings - Windows Store Apps, as shown below) and uploaded the package to the Windows Store.

So far, pretty easy and straightforward process. The store review process rejected the application. I asked the to run WACK locally (Windows Application Certification Kit) that is on any system that is doing Windows 8 development. To run it, simply hit the windows key on your keyboard and type cert, it should be in the results. It's also available at http://msdn.microsoft.com/en-us/windows/apps/bg127575.aspx


WACK failed and gave the following issues in the report. I'm including everything for those that find this via a search engine trying to solve their own issues. However the fix was quite simple. In Visual Studio ensure you are doing a RELEASE build. The problem here is when a Debug build is selected in Visual Studio, the debug version of the Unity libraries are referenced instead of the Release version. Debug libraries have optimizations removed and a bunch of diagnostic information included in them (for ex information to link in PDB files for debug information). Simply select "Release" in Visual Studio for build settings, recompile via the build menu or control-shift-b, which is also the same hotkey for build in Unity and voila!




Failing application details:
Binary analyzer
Error Found: The binary analyzer test detected the following errors:
File \AppX\BridgeInterface.dll has failed the WXCheck check.
File \AppX\BridgeInterface.dll has failed the SafeSEHCheck check.
File \AppX\Catch Falling Stuff.exe has failed the WXCheck check.
File \AppX\Catch Falling Stuff.exe has failed the SafeSEHCheck check.
File \AppX\UnityEngineDelegates.dll has failed the WXCheck check.
File \AppX\UnityEngineDelegates.dll has failed the SafeSEHCheck check.

Impact if not fixed: If the app doesn’t use the available Windows protections, it can increase the vulnerability of customer's computer to malware.

How to fix: Apply the required linker options - SAFESEH, DYNAMICBASE, NXCOMPAT, and APPCONTAINER - when you link the app. See links below for more information:
Fixing Binary Analyzer Errors


Debug configuration
Error Found: The debug configuration test detected the following errors: ?The binary UnityPlayer.dll is built in debug mode.
The binary BridgeInterface.dll is built in debug mode.
The binary UnityEngineProxy.dll is built in debug mode.
The binary UnityEngineDelegates.dll is built in debug mode.
The binary Catch Falling Stuff.exe is built in debug mode.
This package has a dependency on Microsoft.VCLibs.110.00.Debug.
Impact if not fixed:  Windows Store doesn’t allow a debug version of an app.
How to fix:  Please make sure the app isn’t linking to any debug versions of a framework, and it is built with release configuration. If this is a managed app please make sure you have installed the correct version of .NET framework.