Wednesday, December 10, 2014

Invalid IL code in system.xml.linq.xdocument:Parse (string): method body is empty

Working on getting a iPhone application off the ground.  We are using Xamarin/Monotouch and MVVMcross to build a cross platform solution.  The PCL does not support File.IO namespace so using some excellent posts about IoC.

Problem:

An issue cropped up in my attempts to get my example working.  I have the xml file being rendered in the iOS project of the solution.  The Interface is stored in the PCL and it compiles and runs.  But when I hit the line in the iOS project

doc = XDocument.Parse(DefaultData);

I got the runtime error:
Invalid IL code in system.xml.linq.xdocument:Parse (string): method body is empty

Solution:

The iOS project is using the Monotouch namespace which includes its own copies of the common
.Net dlls.  It appears that the namespaces for the non mono projects were included as references for the iOS project.  This meant that the source code would compile without errors.  The dll in question was System.XML.dll.  I dropped the reference to this dll and added in the correct mono dll and that removed the IL error.


Wrong System.XML.dll file

Program Files(x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.1\System.XML.dll

vs.


Correct System.XML.dll

Program Files(x86)\Reference Assemblies\Microsoft\Framework\MonoTouch\v1.0\System.XML.dll

Thursday, December 4, 2014

Xamarin Build server with address 192.168.x.x is too old to be used with this version of Xamarin.iOS extension

Problem:

In Visual Studio, I try to connect to the Xamarin Build Host on my Mac.  VS flags an error when I try to compile.  This event occurs when I try to connect to the Build Host.  The error states that my Mac version of Xamarin is to old. 

Try 1:
My obvious conclusion was to update the Mac system to the latest version of Xamarin and try again.
I did this and it did not work.  I installed the update and rebooted the Mac.  I tried to connect from Visual Studio and still got the error.

Try 2:
My next thought was to update my build box which hosts Visual Studio.  I did the update to the most current version of Xamarin Studio which will include the Build Host.  The error was still present following install and reboot.  This is really getting annoying.

Solution:

I took a step back and looked at my Windows dev system and ignored the error message from Xamarin.  I looked at the log files and noted that there was mention of the machine not being reachable.  This got me wondering and I began looking at Network issues. 

I opened up IE > Internet Options > Connections > LAN Settings

There was the problem!!!  The Proxy server check box was selected.  This meant that all my traffic was going through a static connection and not using DHCP.

Fix was to unselect Use Proxy Server checkbox and Select the Automatically detect settings checkbox.

Notes:
The problem with this error is that error message does not alert you to the fact that it is a networking issue.  I had to look at the logs to determine the issue.

Friday, October 31, 2014

Missing certificate for authenticated push notifications: Certificate for authenticated push notifications

Problem:
Finally we have approval to push this application and I was getting the following warning in Windows Phone Store

"Missing certificate for authenticated push notifications: Certificate for authenticated push notifications"
 
I have no more options than before. I have no push notifications in use.
 
Solution:
 
You should check your WMAppManifest.xml file. Do you have ID_CAP_PUSH_NOTIFICATION defined there?
 

Tuesday, October 28, 2014

HP Probook 6565b won't power on!!!!

Tried to power on my work pc and got nothing but a loud fan and not much else.  I was sure that my laptop was toast. I was thinking that a component had failed.  Then I went over to the HP forums and
found the solution:


Solution:


Following solution solved the problem for me:

- after power on when the HP screen is shown press ESC key within the first 2-3 seconds
   (after approximately 5 seconds the system did not respond anymore)
- at the prompt "Login into F10 as a guest user" select "Yes"
- go to Systemm Configuration tab
- select Boot options
- highlight "Multiboot Express Popup Delay (Sec) and press "Enter" key
- change value by "UP/DOWN" keys (arrows) to minimum "05" and press again "Enter" key
- click on "Exit" (bottom right)
- on the "Save Changes" prompt select "Yes"

Now the notebook will boot again and you should see the Multiboot Express Popup menu (after the initial HP Screen).
Use the UP/DOWN keys to select "Notebook Hard Drive" and then press the "Enter" key.
Now the Notebook did boot from the HDD, and I hope that your's will too :-)

Looks like in my case, something with the Notebook Upgrade Bay got "screwed up" when the Notebook went into hibernation due to low battery, because also boot from CD-ROM was not working.




Source
http://h30434.www3.hp.com/t5/Notebook-Hardware/HP-Probook-6560b-won-t-power-on/td-p/1443819

Friday, October 17, 2014

Randomize boolean method in C#

I just saw this slick little trick in a Xamarin class.  Instructor needed to have a sample class randomly return a true or false. 

This is so simple:

public bool IsTrue()
{
return new Random().Next() % 2 == 0;
}

Wednesday, October 15, 2014

MVVMcross mvxException failed to construct and initialize viewmodel check MvxTrace fo more information

Problem:

We are trying to construct the iOS layer to our MVVMcross project.  We have built the core for the initial ViewModel and wanted to add the iPhone layer.  The project when in just fine and the Mac Host even compiled everything. 

Once I ran the solution, I get this runtime error in the iPhone Simulator.

Solution:

Lots of great information about possible solutions at stackoverflow.  However, my problem was the SQLite plugin.  I neglected to add the plugin to my iPhone Layer and once I added it the app runs fine.


Source:
http://stackoverflow.com/questions/18940820/how-do-you-initialize-themvvmcross-sqlite-plugin

Tuesday, October 7, 2014

Install NuGet Packages Offline - Visual Studio

Problem:
You are offline and trying to create a VS project with NuGet Package dependencies.
The challenge is how to get them.

Solution:

Use the cached copies on your machine stored at, %LOCALAPPDATA%\NuGet\Cache.

1.) Start Visual Studio and Open the package manager
  • Tools > NuGet Package Manager > Package Manager Settings
  • Select Package Sources in left hand menu
2.) Add Cache package to package manager.
  • Above the Available Package Sources window are 4 icons
  • Select the + and this will add a new source
  • Highlight the new entry
  • Edit the Name field, provide a name of your choosing
  • Source field add full path to the NuGet Cache
    • Find it by opening a  windows explorer window and typing the path, %LOCALAPPDATA%\NuGet\Cache
    • This will resolve to the path to your local cache
  • Select Update
3.) Your Done.

WARNING: Realize that this is only valid until you clear your nuget cache.

Source:
http://nuget-offline.blogspot.com/#!

Nuget Manager showing packages which have been deleted.

Problem:
We have moved a project out of TFS and onto a new machine.  The packages where not being cleare up with the Package Manager Console.  Tried several times to refresh.  The


Solution:

Option 1:

1.)Tools > NuGet Package Manager > Package Manager Console
2.)Update-Package -Reinstall -Project iWatch.Core

If that does not work then try:

Option 2:
1.)Tools > NuGet Package Manager
2.)Remove all nuget packages
3.)Find the packages file in the project this should be at the root of the project.  Open the file and clear out the xml entries.
4.)Manually reinstall packages.


Source
http://stackoverflow.com/questions/13085480/restoring-nuget-references

Monday, October 6, 2014

MvxIoCResolutionException: Failed to resolve parameter for parameter pictureChooserTask of type IMvxPictureChooserTask when creating Collect-A-Bull.Core.ViewModels.AddViewModel

Problem:

Using Stuart Lodge's excellent N+1 series, I stumbled in Session N+1 - 14.  This is where the pictureChooserTask is introduced.

 I was getting this error which absolutely baffled me:

MvxIoCResolutionException: Failed to resolve parameter for parameter pictureChooserTask of type IMvxPictureChooserTask when creating  Collect-A-Bull.Core.ViewModels.AddViewModel


Solution:

I would only get this error at runtime which lead me down a path towards the solution.
Stuart reminded me that what I was missing was the bootstrap:

To make the plugin available, you'll need to reference the plugin core and touch assemblies, and you'll need to include a bootstrap class - like https://github.com/MvvmCross/NPlus1DaysOfMvvmCross/blob/master/N-08-Location/Location.Touch/Bootstrap/LocationPluginBootstrap.cs

What I needed to add in my UI layer was the bootstrap folder with the PictureChooserPluginBootstrap class.

using Cirrious.CrossCore.Plugins;
namespace PictureTaking.Phone.Bootstrap
{
public class PictureChooserPluginBootstrap
: MvxPluginBootstrapAction<Cirrious.MvvmCross.Plugins.PictureChooser.PluginLoader>
{
}
}


Once I had this in place the viewmodel loaded correctly and I was able to proceed.


Source:
http://answer.techwikihow.com/1004999/ioc-resolving-dependencies-mvvmcross.html

https://github.com/MvvmCross/MvvmCross/wiki/MvvmCross-plugins#picturechooser

NuGet Error in Visual Studio - Specified path, file name or both are too long. 260 vs. 248

Trying to update some NuGet packages and had the package refuse to deploy giving this message:

The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.
Solution:
Turns out that Visual Studio 2012 has a fixed limit length on property paths of 248 characters.
My package length was 260 characters.  The fix is to not nest your project so deep, ie. shorter paths!!

Microsoft know about the issue:

Hello everyone and thank you for the feedback and for voting on this issue. We understand that this can be a frustrating issue, however, fixing it requires a large and complicated architectural change across different products and features including Visual Studio, TFS, MSBuild and the .NET Framework. Dedicating resources to this work item would come at the expense of many other features and innovation. Additionally, if we removed this limitation from our first party tools it will still likely exist elsewhere in Visual Studio’s ecosystem of extensions and tools. For these reasons, we are declining this suggestion and returning return everyone’s votes so they can be applied to other items. In the interest of delivering the most value to our customers we sometimes have to make very difficult cuts, and this is one of them.
Thank you,
Will Buik,
Visual Studio – Project and Build Team


Source:
http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2156195-fix-260-character-file-name-length-limitation

Saturday, October 4, 2014

Windows 10 Preview install on VHD


1. Download Windows 10 Preview from Microsoft preview site.  

2. Run disk management tool “diskmgmt.msc” to create blank vhd.

3. Select Action > Create VHD.

3. Once you have VHD file , use run disk management tool “diskmgmt.msc”.
4. Select “Attach VHD” option from the “Action” Menu.
5. “Select/Enter” path to VHD location
6. Windows will mount the VHD and assigns drive letter. Note down the drive lettter. In my case it is mount as “G” drive. Now from the explorer you can see the “G” drive.
7. Launch command prompt in “Administrator” mode

8. Now mount the Win 10 preview iso using disk management tool repeat step 4.

9. Use imagex tool to tranfer wim file onto your blank vhd.
imagex.exe /apply e:\win10\sources\install.wim 1 g:\ /verify

10. In “Administrator” mode, Type following command to make entry in the windows boot loader
c:\Windows\system32\bcdboot G:\Windows
Note: Replace “G” with the drive letter depending on you system where VHD is mounted.
11. Launch “msconfig.exe” from the “Administrator” command prompt to verify that new boot entry is added in the boot loader.
You can change the boot order from here.
Note: Replace “G” with the drive letter depending on you system where VHD is mounted
12. If you reboot the system, now you will have option to boot into new OS.








Wednesday, October 1, 2014

Unauthorized Access Exception - MvxLocationWatcher in Windows Phone 8

I have been working through Stuart Lodge's MvvmCross tutorial.  Session 12 is working with location watchers.  I was able to compile the solution but at run time I received the Unauthorized access error.

Solution:
1.) Solution Explorer
2.) Expand properties of the Windows Phone project
3.) Open WMAppManifest.xml
4.) Capabilities tab
5.) Select ID_CAP_LOCATION check box

The application must grant this permission in order to use the onboard location features.


Monday, September 29, 2014

Xamarin Error:No valid iOS code signing keys found in keychain

Problem:

I got this lovely error when trying to do my hello world program.  I just managed to complete the configuration of our development network and needed to test the iPhone compilation within Visual Studio.

When I went to build I got this error: No valid iOS code signing keys found in keychain

After some research, I found the Xamarin forums quite helpful and located this guide:
http://docs.xamarin.com/guides/ios/getting_started/device_provisioning/

The issue is the compiler on the Mac Host is trying to build out the final package for deployment to an iPhone device.  You need to register with as an Apple developer to do that.  Forunately or Unfortuantely, we are not ready to do that just yet with our App.

My issue was why can't I run the emulator in Visual Studio?

Solution:
  1. Right-click the Standard toolbar (the one which has the current configuration drop-down saying Debug, Release etc) and choose Customize… from the menu:
    [ ]
  2. Switch to the Commands tab.
  3. Select the Toolbar radio button
  4. Select the Standard toolbar in the list to the right of the radio button
  5. Scroll down the Controls widget till you see the Solution Configurations widget and select it
  6. Click the Add command... button:
    [ ]
  7. Choose the Build category
  8. Choose the Solution Platforms command and click OK :
    [ ]
  9. Click Close




Source:
http://developer.xamarin.com/guides/ios/getting_started/installation/windows/



Friday, September 26, 2014

Xamarin Error 429 - clocks not synced

I am building out a disconnected network for our VS/Xamarin iOS build environment. 

Problem:
I have successfully paired the Mac and Windows boxes on our local network.  I noted that there is a discrepancy in the clocks between the two machines.  How to fix this problem.

Solution:
Make your Mac the time server

  1. Unload the current npd daemon.
    • sudo launchctl unload /System/Library/LaunchDaemons/org.ntp.ntpd.plist 
  2. Edit the ntp-restrict.conf
    • /etc/ntp-restrict.conf
    • Remove the “noquery” from the 1st two restrict lines:
  3. Now load the npd file again
    • sudo launchctl load /System/Library/LaunchDaemons/org.ntp.ntpd.plist
  4. Test npd to ensure it is running
    • sudo ntpdate -u localhost
On your Windows PC
  1. Open Date and Time Dialog
  2. Select the Internet time tab
  3. Change Settings
  4. Select Synchronize with and Internet time server.
  5. Place the IP Address of the Mac you are using as the time server (192.168.0.100) in the Server block
  6. Update Now
  7. OK
Now
  1. Open up command window as admin
  2. type in command: w32tm /config /manualpeerlist:192.168.0.100 /syncfromflags:MANUAL
 Now the windows box will sync its time with the Mac box and should not have the 429 errors any longer.


Source
http://macmule.com/2013/12/15/how-to-use-osx-server-as-a-time-server/

The remote server returned an error: 429 (Xamarin Visual Studio iOS error 429)

Problem:
VS not working (The remote server returned an error: 429)

Solution:
My clocks were off by one hour inspite of showing the same time.  The windows box had an incorrect setting for the timezone UTC+1.  It had been manually advanced by one hour.  This meant that the times between the Windows box running VS and the Mac Host had a difference of 1 hour.
Anything over 3 minutes will throw an error in the compiler.






http://forums.xamarin.com/discussion/17062/vs-not-working-the-remote-server-returned-an-error-429

Tuesday, September 23, 2014

Installing Xamarin.iOS on Windows

Xamarin site has great how to guides for installing their product for use with Visual Studio.
We are writing our first iPhone app using C#, Xamarin and Mvvmcross.




How to install:

http://developer.xamarin.com/guides/ios/getting_started/installation/windows/#Connecting_to_the_Mac_Build_Host

Setting up Mac OS 10.9 Mavericks as a DHCP server.

As part of our iPhone Xamarin project, we are setting up a disconnected network.  I had a linksys switch but needed to get DHCP going on our internal network.  Fortunately, this has already been done.

How to
1.)  Enable root user on Mavericks
  • Launch The System Preference Application
  • Open Users & Groups preferences, click Login Options, then click the lock icon to unlock it. If necessary, type your password, then click Unlock.
  • In the Network Account Server section, click Join or Edit.
  • Click Open Directory Utility.
  • Click the lock icon to unlock it, then enter your administrator name and password.
  • Choose Edit > Enable Root User, then enter a root user password in the Password and Verify fields.
  • Close the Directory Utility Application.
2.) Configure bootpd on Mavericks.  The post by Jacques Fortier does a great job explaining each step.
  • To start, you need to create a configuration file for the server. The file should be stored in /etc/bootpd.plist.
Sample:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>bootp_enabled</key>
    <false/>
    <key>detect_other_dhcp_server</key>
    <integer>1</integer>
    <key>dhcp_enabled</key>
    <array>
        <string>en0</string>
    </array>
    <key>reply_threshold_seconds</key>
    <integer>0</integer>
    <key>Subnets</key>
    <array>
        <dict>
            <key>allocate</key>
            <true/>
            <key>lease_max</key>
            <integer>86400</integer>
            <key>lease_min</key>
            <integer>86400</integer>
            <key>name</key>
            <string>192.168.33</string>
            <key>net_address</key>
            <string>192.168.33.0</string>
            <key>net_mask</key>
            <string>255.255.255.0</string>
            <key>net_range</key>
            <array>
                <string>192.168.33.2</string>
                <string>192.168.33.254</string>
            </array>
        </dict>
    </array>
</dict>
</plist>
  • To start the server, run the following command:
    sudo /bin/launchctl load -w /System/Library/LaunchDaemons/bootps.plist
  • Stopping the server is very similar:
    sudo /bin/launchctl unload -w /System/Library/LaunchDaemons/bootps.plist


Source:

How to simulate a low-bandwidth connection or poor signal for Windows Phone 8

Problem:

Testing the Windows Phone with limited bandwidth for cell coverage has been something you need to do with a device attached to a VS debug session.  This obviously is not an optimal solution.  Visual Studio now has the Simulation Dashboard.

Solution:

To open the Simulation Dashboard, in Visual Studio, on the Tools menu, click Simulation Dashboard. After you open the dashboard, it remains open and available even when you open and close projects in Visual Studio.

Source
  1. http://msdn.microsoft.com/en-us/library/windows/apps/jj206952(v=vs.105).aspx

Tuesday, September 16, 2014

MVVM and Windows Phone application bar

Working a cross platform mobile solution.  I have the Commands defined in my mvvm core View Model.  I need to bind my View in the Windows Phone 8 application to the command in the ViewModel. 

Problem:
"Windows Phone AppBar's are naive rather than Silverlight controls - so they are not bindable"

Solution:
Get an addon which will support app bar binding for windows phone 8. 
https://bindableapplicationb.codeplex.com/


Source:
http://stackoverflow.com/questions/25466816/how-to-do-binding-for-a-global-applicationbar-in-windows-phone-with-mvvmcross

Wednesday, September 10, 2014

Xaml Binding EventToCommand to MVVM core

I have worked my way through Stuart Lodge's N+1 tutorials.
I was stumped about how to connect my Icommand control from the core to the UI.
Stuart's demo showed how to connect a button or checkbox to the MvxCommand but did not explain how to use the EventToCommand relationship.

I was trying to have a stackpanel fire the event when the user taps it in the UI.
The stackoverflow article provided me the leg up I needed.

I was struggling on which syntax to use to associate a stackpanel in xaml with my command. Turns out I needed to reference the Cirrious namespace in the xaml


xmlns:Commands="clr-namespace:Cirrious.MvvmCross.WindowsPhone.Commands;assembly=Cirriou... xmlns:Commands="clr-namespace:Cirrious.MvvmCross.WindowsPhone.Commands;assembly=Cirrious...

<i:Interaction.Triggers >
   <i:EventTrigger EventName="Tap">
      <Commands:MvxEventToCommand Command="{Binding OnItemTappedCommand}" />
   </i:EventTrigger >
</i:Interaction.Triggers>
Source:
http://stackoverflow.com/questions/16823444/im-getting-build-errors-when-using-mvxeventtocommand-within-a-wp8-project

https://github.com/MvvmCross/MvvmCross/blob/e6d10972b5c28e00e80acc3d9e8910961aa813d6/Cirrious/Cirrious.MvvmCross.WindowsPhone/Commands/MvxEventToCommand.cs


Awesome MvvmCross tutorial from Stuart Lodge

Stuart has posted an amazing series of videos on youtube.  He explains how mvvmcross templates interacts with the Xamarin templates.  This is some great information.
https://www.youtube.com/watch?v=He6QvnLsPUA&list=PLR6WI6W1JdeYSXLbm58jwAKYT7RQR31-W&index=7

iPhone development in C#

Starting a project to develop an iPhone application.  We are going to pursue a cross platform solution using Xamarin software.  This should allow us to write the core processes in C# and deploy UIs specific to the platform we are targeting.  In order to get the most out of the design, we are going to use the MVVM pattern.  MVVMCross is a github project which used in concert with Xamarin software will allow us to write C# for both back end and UI.

This promises to be an exciting project.  We currently have 2 versions of the application written (WP8, Android).  These were done without the benefit of this approach and will at some point be migrated to this pattern. 

Wednesday, September 3, 2014

MVVMCross - Could not install package 'MvvmCross.PortableSupport 3.1.1'.

MVVM Cross nuget package 3.1.1 with VS 2012 SP2 not working

Error:

Could not install package 'MvvmCross.PortableSupport 3.1.1'. You are trying to install this package into a project that targets 'portable-net45+sl40+wp+win', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

Explanation:

The problem is that MvvmCross.PortableSupport 3.1.1 has a portable class library that targets:
portable-win+net45+sl50+wp8+MonoAndroid+MonoTouch
Whilst your portable class library project is targeting:
portable-win+net45+sl40+wp71
The MonoAndroid and MonoTouch frameworks are optional and will not be used in the comparison if you are using NuGet 2.7.2 or above. Your project is targeting Silverlight 4.0 and Windows Phone 7.1 whilst MvvmCross.Portable is targeting Silverlight 5.0 and Windows Phone 8. So it is not compatible. You cannot install a portable class library into a portable class library project that targets older framework versions. You will need to change the profile for your portable class library project so that it targets these frameworks.


Solution:


Option 1:

Target Frameworks
.Net 4.5, Silverlight 5, Windows Phone 8, Windows Store apps (Windows 8)


Option 2:

The workaround mentioned on a comment on Stuart's blog (at http://slodge.blogspot.co.uk/2013/04/n0-first-mvvmcross-application-n1-days.html) worked for me:
Remove Mono for Android, MonoTouch, VS MonoTouch and Windows Phone from the Target Frameworks in the Core project properties. Install MvvmCross NuGet package. Add the Target Frameworks back in.

Tuesday, September 2, 2014

Updating ApplicationBarIconButton Dynamically - Causes NullReference

Problem:

I ran into this error trying to disable a icon on the Application Bar of my Windows Phone Application.  I declared the applicationbar declaratively and not programmatically.  When I went to
access the applicationbar icon I assigned it a name property using x:Name.  The control resolved to
null.


AppBarEmailButton.IsEnabled = true;

Error Message:
System.NullReference: Object Reference not set to an instance of an object.


Solution:

Microsoft.Phone.Shell.ApplicationBarIconButton btn = (ApplicationBarIconButton )ApplicationBar.Buttons[0];

btn.IsEnabled = true;

or declare the applicationbar programmatically.



Source
http://blogs.msdn.com/b/ptorr/archive/2010/06/18/why-are-the-applicationbar-objects-not-frameworkelements.aspx?wa=wsignin1.0

http://stackoverflow.com/questions/5334574/applicationbariconbutton-is-null

http://social.technet.microsoft.com/wiki/contents/articles/975.updating-applicationbariconbutton-dynamically.aspx

Wednesday, August 27, 2014

Setting up windows store account

I was tasked with creating a corporate account today and wanted to capture the steps required to get the account set up.

Basically you will need to do the following

1.) Sign up for an outlook account.
2.) Now sign into the windows dev center using the account you created.
You will  be asked to set the account up as a individual ($19) or corporate ($99).


This article from msdn describes the entire process in detail
http://msdn.microsoft.com/en-us/library/windows/apps/hh868184.aspx

Error 3355 Cannot connect to SQL Server. SQL Server not found.

Problem:
I ran into this issue due to a SQL being configured on a port other than 1433.
The configuration wizard kept failing with this error and this was even after
I had specified the correct path in the wizard to the SQL server.

Solution:
What was missing was the SQL alias on the WFE.
How do you get this?

1.) Open command prompt as administrator
2.) Type cliconfg
3.) Add server alias.


Thursday, August 14, 2014

Sharepoint 2010 Configuration Wizard error address is invalid or loopback address

I ran into this error due to the wizard not correctly creating the SharePoint_Config database.
This was due to the incorrect syntax on the first screen of the wizard.  The path you must use is


Server.FQDN\SQLServerInstance, Port

Example:
A sql instance dumpty running on server humpty running on port 2010 would be

humpty.xyz.com\dumpty, 2010




Source:
http://blogs.msdn.com/b/psssql/archive/2013/10/04/invalid-or-loopback-address-when-configuring-sharepoint-against-a-sql-server.aspx

Wednesday, August 13, 2014

SharePoint 2010/2013 Prequisites

New task today required me to grab the bits for a 2010 install. We are building out 2 Frontends and so I grabbed the MSDN bits. Next I was looking at the the whole update and prereq issue. This can be a real pain until I found this great project on Codeplex. The Autospsourcebuilder project does all this work for you.  You just get the powershell script and the SharePoint iso and go this script will create a slipstream installer for you.

Sample:

.\AutoSpSourceBuilder.pas1 -SourceLocation "d:\SP2010" -Destination "d:\SPSlipstream" -GetPrerequisites $true

The Script will prompt you for the name of the update which can be found at the sharepoint updates site.



Source:
  1. http://autospsourcebuilder.codeplex.com/
  2. List of all Cumulatives Updates

Powershell cannot be loaded because execution of scripts is disabled on this system.

Everytime I need to run a powershell script I forget to set the ExecutionPolicy

Set-ExecutionPolicy Unrestricted

This will let you run the script without the error. Be warned you do this at the risk of it not being from a trusted source.

Get-ExecutionPolicy

This will tell you what your current session is running at.

Source:
http://technet.microsoft.com/en-us/library/ee176949.aspx

Move Inetpub off of c drive

The inetpub folder is installed by default on the c drive. We often are asked to move this default folder onto an application drive (i.e. d, f, g drive). It is a convenient practice as it gets the files off of the c drive which can get clogged up with all kinds of system level files. Here is the script which will move an existing c:\inetpub install to the drive of your choice. Save it as inetpub.bat and then execute as c:\inetpub.bat f where f is the name of the target drive you want to run inetpub from. REM PLEASE BE AWARE: SERVICING (I.E. HOTFIXES AND SERVICE PACKS) WILL STILL REPLACE FILES REM IN THE ORIGINAL DIRECTORIES. THE LIKELIHOOD THAT FILES IN THE INETPUB DIRECTORIES HAVE REM TO BE REPLACED BY SERVICING IS LOW BUT FOR THIS REASON DELETING THE ORIGINAL DIRECTORIES REM IS NOT POSSIBLE. @echo off IF "%1" == "" goto err setlocal set MOVETO=%1:\ REM simple error handling if drive does not exist or argument is wrong IF NOT EXIST %MOVETO% goto err REM Backup IIS config before we start changing config to point to the new path %windir%\system32\inetsrv\appcmd add backup beforeRootMove REM Stop all IIS services iisreset /stop REM Copy all content REM /O - copy ACLs REM /E - copy sub directories including empty ones REM /I - assume destination is a directory REM /Q - quiet REM echo on, because user will be prompted if content already exists. echo on xcopy %systemdrive%\inetpub %MOVETO%inetpub /O /E /I /Q @echo off REM Move AppPool isolation directory reg add HKLM\System\CurrentControlSet\Services\WAS\Parameters /v ConfigIsolationPath /t REG_SZ /d %MOVETO%inetpub\temp\appPools /f REM Move logfile directories %windir%\system32\inetsrv\appcmd set config -section:system.applicationHost/sites -siteDefaults.traceFailedRequestsLogging.directory:"%MOVETO%inetpub\logs \FailedReqLogFiles" %windir%\system32\inetsrv\appcmd set config -section:system.applicationHost/sites -siteDefaults.logfile.directory:"%MOVETO%inetpub\logs\logfiles" %windir%\system32\inetsrv\appcmd set config -section:system.applicationHost/log -centralBinaryLogFile.directory:"%MOVETO%inetpub\logs\logfiles" %windir%\system32\inetsrv\appcmd set config -section:system.applicationHost/log -centralW3CLogFile.directory:"%MOVETO%inetpub\logs\logfiles" %windir%\system32\inetsrv\appcmd set config -section:system.applicationHost/sites -siteDefaults.ftpServer.logFile.directory:"%MOVETO%inetpub\logs\logfiles" %windir%\system32\inetsrv\appcmd set config -section:system.ftpServer/log -centralLogFile.directory:"%MOVETO%inetpub\logs\logfiles" REM Move config history location, temporary files, the path for the Default Web Site and the custom error locations %windir%\system32\inetsrv\appcmd set config -section:system.applicationhost/configHistory -path:%MOVETO%inetpub\history %windir%\system32\inetsrv\appcmd set config -section:system.webServer/asp -cache.disktemplateCacheDirectory:"%MOVETO%inetpub\temp\ASP Compiled Templates" %windir%\system32\inetsrv\appcmd set config -section:system.webServer/httpCompression -directory:"%MOVETO%inetpub\temp\IIS Temporary Compressed Files" %windir%\system32\inetsrv\appcmd set vdir "Default Web Site/" -physicalPath:%MOVETO%inetpub\wwwroot %windir%\system32\inetsrv\appcmd set config -section:httpErrors /[statusCode='401'].prefixLanguageFilePath:%MOVETO%inetpub\custerr %windir%\system32\inetsrv\appcmd set config -section:httpErrors /[statusCode='403'].prefixLanguageFilePath:%MOVETO%inetpub\custerr %windir%\system32\inetsrv\appcmd set config -section:httpErrors /[statusCode='404'].prefixLanguageFilePath:%MOVETO%inetpub\custerr %windir%\system32\inetsrv\appcmd set config -section:httpErrors /[statusCode='405'].prefixLanguageFilePath:%MOVETO%inetpub\custerr %windir%\system32\inetsrv\appcmd set config -section:httpErrors /[statusCode='406'].prefixLanguageFilePath:%MOVETO%inetpub\custerr %windir%\system32\inetsrv\appcmd set config -section:httpErrors /[statusCode='412'].prefixLanguageFilePath:%MOVETO%inetpub\custerr %windir%\system32\inetsrv\appcmd set config -section:httpErrors /[statusCode='500'].prefixLanguageFilePath:%MOVETO%inetpub\custerr %windir%\system32\inetsrv\appcmd set config -section:httpErrors /[statusCode='501'].prefixLanguageFilePath:%MOVETO%inetpub\custerr %windir%\system32\inetsrv\appcmd set config -section:httpErrors /[statusCode='502'].prefixLanguageFilePath:%MOVETO%inetpub\custerr REM Make sure Service Pack and Hotfix Installers know where the IIS root directories are reg add HKLM\Software\Microsoft\inetstp /v PathWWWRoot /t REG_SZ /d %MOVETO%inetpub\wwwroot /f reg add HKLM\Software\Microsoft\inetstp /v PathFTPRoot /t REG_SZ /d %MOVETO%inetpub\ftproot /f REM Do the same for x64 directories if not "%ProgramFiles(x86)%" == "" reg add HKLM\Software\Wow6432Node\Microsoft\inetstp /v PathWWWRoot /t REG_EXPAND_SZ /d %MOVETO%inetpub\wwwroot /f if not "%ProgramFiles(x86)%" == "" reg add HKLM\Software\Wow6432Node\Microsoft\inetstp /v PathFTPRoot /t REG_EXPAND_SZ /d %MOVETO%inetpub\ftproot /f REM Restart all IIS services iisreset /start echo. echo. echo =============================================================================== echo Moved IIS7 root directory from %systemdrive%\ to %MOVETO%. echo. echo Please verify if the move worked. echo If something went wrong you can restore the old settings via echo "APPCMD restore backup beforeRootMove" echo and echo "REG delete HKLM\System\CurrentControlSet\Services\WAS\Parameters\ConfigIsolationPath" echo You also have to reset the PathWWWRoot and PathFTPRoot registry values echo in HKEY_LOCAL_MACHINE\Software\Microsoft\InetStp. echo =============================================================================== echo. echo. endlocal goto success REM error message if no argument or drive does not exist :err echo. echo New root drive letter required. echo Here an example how to move the IIS root to the F:\ drive: echo. echo MOVEIISROOT.BAT F echo. echo. :success

Tuesday, August 12, 2014

Adding listener to MessageBox ok button in Windows Phone

I was updating my phone application and needed to provide a response to a user prompt. This is called adding a listener to the message box. This is easily done by adding the following code block into the location where you will be running the messagebox. This SDK supported messagebox control only supports the OK and Cancel buttons. If you want more control then you will need to use the XNAFramework messagebox which supports more customization. Deployment.Current.Dispatcher.BeginInvoke(() => { MessageBoxResult result = MessageBox.Show("Show next message?", "Question", MessageBoxButton.OKCancel); // code after user click if (result == MessageBoxResult.OK) MessageBox.Show("Yeah"); }); Source: http://stackoverflow.com/questions/21773730/adding-listener-to-messagebox-ok-button-in-windows-phone

Tuesday, July 29, 2014

Display Created by fields in Custom SharePoint List

One challenge to getting a custom form to display what you want is understanding the eccentricities of SharePoint Designer and the SharePoint storage.  I had a custom list which needed to display the created by and modifed by data.  These fields needed to be displayed on the main form along with the other data items.  This information is normally parked in the footer of the form.  This can be done by using the SharePoint:CreatedModifiedInfo  control item.  One thing to note is that the fields in Sharepoint are stored internally with different names:

Created By = @Author
Modified By = @Editor

Code to add to your custom form:

<tr>
         <td valign="top" class="ms-formlabel"><nobr>Created by</nobr></td>
         <td valign="top" class="ms-formbody">
             <SharePoint:CreatedModifiedInfo ControlMode="Edit" runat="server">
             <CustomTemplate>
                 <SharePoint:FormField FieldName="Author" runat="server" ControlMode="Display" DisableInputFieldLabel="true" /><br/>
                 <SharePoint:FieldValue FieldName="Modified" runat="server" ControlMode="Display" DisableInputFieldLabel="true"/>
             </CustomTemplate>
             </SharePoint:CreatedModifiedInfo>
         </td>
     </tr>

Custom Edit List Form Modified By field is blank -

Custom Form Does Not Display “Created By” value


I was customizing a sharepoint list today and customer asked for a modification to the New and Edit forms for the list.  I was using Designer to accomplish the task and was able to get most of it working.  The customer had asked for a field on the edit form to show the Modified by field.  This is the standard canned field which is part of every list in SharePoint.  I thought no problem I just get the internal field name and use the <xsl:value-of select="@Editor"/>. 

Challenge:

Each time I would load the edit form the field would resolve to empty.  This made no sense and really drove me crazywhile I tried to understand the problem. 

Sample:
<tr>
      <td valign="top" class="ms-formlabel" width="190px">
       <H3 class="ms-standardheader">
        <nobr>Modified By</nobr>
       </H3>
     <!--Always Blank --/>
       <xsl:value-of select="@Editor" disable-output-escaping="yes"/>
      

      </td>
      <td valign="top" class="ms-formbody" width="400px">
       <SharePoint:FormField runat="server" id="ModifiedByID" ControlMode="New" FieldName="Editor" __designer:bind="{ddwrt:DataBind('u','ModifiedByID','Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Editor')}"/>
       <SharePoint:FieldDescription runat="server" id="ff7description{$Pos}" FieldName="Editor" ControlMode="Edit"/>
      </td>
     </tr>

Solution:

It helped me to look at the entire form and pay close attention to the syntax for the FormField control.
This includes the attribute ControlMode.  This tells the form control what state it is currently in.  (New,Edit,Display)  The key mistake I had made was to set this controlmode attribute to New instead of Edit.Once I set the controlmode attribute to Edit the value began to be passed to the form and displayed.

Corrected:
<tr>
<td valign="top" class="ms-formlabel" width="190px">
<H3 class="ms-standardheader">
<nobr>Modified By</nobr>
</H3>
<!--Always Blank --/>
<xsl:value-of select="@Editor" disable-output-escaping="yes"/>


</td>
<td valign="top" class="ms-formbody" width="400px">
<SharePoint:FormField runat="server" id="ModifiedByID" ControlMode="Edit" FieldName="Editor" __designer:bind="{ddwrt:DataBind('u','ModifiedByID','Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Editor')}"/>
<SharePoint:FieldDescription runat="server" id="ff7description{$Pos}" FieldName="Editor" ControlMode="Edit"/>
</td>
</tr>

Wednesday, July 23, 2014

Xamarin and Sole Source justification

Great post by Tim Anderson and Andy Dent about Xamarin vs. other competitors

- Xamarin (+ MVVMCross) ideal cross product solution. https://github.com/MvvmCross/MvvmCross

- The purpose of PhoneGap is to allow HTML-based web applications to be deployed and installed as native applications

- The goal of Titanium Mobile is to provide a high level, cross-platform JavaScript runtime and API for mobile development (today we support iOS, Android, and the browser, with BlackBerry 10 and Windows Phone coming soon and eventually, respectively).


Source:

http://stackoverflow.com/questions/17249500/xamarin-2-0-vs-appcelerator-titanium-vs-phonegap

Friday, July 18, 2014

JSON deserializing and serializing

Convert XML to JSON

http://www.utilities-online.info/xmltojson/

JSON convert between XMLNode and json

XmlNote myXmlNode = JsonConvert.DeserializeXmlNode(myJsonString);
// or .DeserilizeXmlNode(myJsonString, "root");
// if myJsonString does not have a root
string jsonString = JsonConvert.SerializeXmlNode(myXmlNode);

SDK documentation
http://james.newtonking.com/json/help/index.html

Wednesday, July 16, 2014

Connection string sytnax for IIS to SQL Server connection.

I always forget the syntax for connnection strings in my applications.  The guys at connectionsstrings.com do a great job but stumbled across another way to get at the correct syntax.


The steps below.


1.     Right-click an empty spot on the desktop and choose NEW, TEXT DOCUMENT from the context menu


2.     Save it with a .udl extension, and click yes when it asks are you sure.


3.     Double-click the new udl file you just created. It will open a dialogue. Go to the Provider tab, and choose the appropriate provider.


4.     Go to the Connection tab and fill in the server name and database name, and choose NT authentication (or use a specific username and password, which is SQL authentication). Now click Test Connection. If it works, you're ready to click OK and move on to the final step. If it doesn't you need to resolve permission issues, or you've mis-typed something.

5.     Now right-click the file on the desktop and open it in notepad. It will display the connection string that you can copy and paste to wherever you need it.

Identity Impersonation with Classic ASP

The ideal:

I have written before about using impersonation in IIS.  That was using the tools provided in .Net Framework.  This allows a web application to provide dedicated account access to a database.  Thus the application can prompt a user to login with their Windows credentials and a separate service account can be used to support all data access between that web application and the database.  This makes the application most secure as it restricts database access to a single account.  Auditing also becomes much simpler.

The reality:

Now it is great to think about how easy it is in .Net.  The reality is that there are still classic ASP applications which are simply being ported forward to IIS7/7.5.  I cringe when a customer asks for this.  They can't understand why the software has to be updated.  One issue is impersonation.

I had a customer wanting to port the application forward and just assuming that they could apply all the security "boxes" just like a .Net application.  Sadly this is not the case for classic ASP.  It does not have a native mechanism to support impersonation. 

"As most of you know ASP executes under the guise, typically, of the IUSR_ account in IIS (IIS_IUSRS group for IIS 7) which has a very few permissions to do anything on the system (in most cases anyway). "

So what can you do?  I found some great help from Doug Parsons over at Wrox.com


The fix:

You can write a ActiveX dll which you register on your IIS box.  This dll is then used by your ASP application each time you want to access the database. 

Using Statements
csharp Code:
using System; using System.Runtime.InteropServices;
Class Definition
csharp Code:
namespace Impersonate
{[indent]public class UserLogon
{[indent][DllImport("advapi32.dll", SetLastError=true)]
public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);

[DllImport("advapi32.dll")]
public static extern int ImpersonateLoggedOnUser(IntPtr hToken);

[DllImport("advapi32.dll")]
public static extern bool RevertToSelf();

[DllImport("kernel32.dll")]
public static extern bool CloseHandle(IntPtr hObject);

private const int LOGON32_LOGON_INTERACTIVE = 2;
private const int LOGON32_PROVIDER_DEFAULT = 0;
public void Logon(string strAdminUser, string strAdminPassword, string strAdminDomain)
{
IntPtr hToken;

RevertToSelf();

LogonUser(strAdminUser, strAdminDomain, strAdminPassword, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out hToken);

ImpersonateLoggedOnUser(hToken);

CloseHandle(hToken);
}
public void Logoff()
{
RevertToSelf();
}
[/indent]}
[/indent]}

In the Solution Explorer locate the AssemblyInfo.cs file underneath the Properties folder of your project (you may need to click the 'Show all Files' button at the top of the solution explorer) and open it. Add the following line to the file:


csharp Code:
[assembly: ComVisible(true)]
Hit Ctrl + Shift + B (Build) to create your assembly.

Start* up a Visual Studio Command Prompt which can, typically, be found in Start -- > Programs --> Visual Studio 2008 --> Visual Studio Tools and navigate to the directory where your assembly is (something like: projectDirectory\bin\debug\) and issue the following command: regasm Impersonate.dll /tlb

*if you are running Win7/8 run this prompt with Admin rights

In your ASP editor (I used Notepad) use the following code to test your assembly:

asp Code:
[size=2]<% Option Explicit Dim objLogon, oFs, oTextFile Set objLogon = Server.CreateObject("Impersonate.UserLogon") objLogon.Logon "username", "password", "domainname" Response.Write("Impersonating") set oFs = server.createobject("Scripting.FileSystemObject") set oTextFile = oFs.OpenTextFile("C:\foo.txt", 2, True) oTextFile.Write "This is some data wrote as a domain user" oTextFile.Close set oTextFile = nothing set oFS = nothing objLogon.Logoff Set objLogon = Nothing Response.Write("Done Impersonating") %> [/size]

Most of this is very basic but there are some things to point out here:

  • Make sure that the call to CreateObject for objLogon has the name of your assembly. The format for the name will be Namespace.Class. If you have followed along using my code then the correct name is Impersonate.UserLogon.
  • Provide a valid username, password, and domain. I have not tried to impersonate a Local User but, I assume, you could simply provide the PC name as the domain and have this work.
  • Make sure that you call LogOff so that the thread reverts back to running as the IUSR account.
Provided that you execute this ASP script under the guise of IUSR, under normal circumstances, the call to create a text file in the root of the C drive should fail with an Access Denied error so that is a good case to test out our impersonation assembly. As you can see above, a user is impersonated, a file is wrote, and the user is logged off. If all went according to plan you should now see a text file in the root of your C drive! Obviously I am making the assumption that the domain user you are impersonating has the right to create files in the root of the C drive so adjust this test case accordingly.

Pitfalls and Gotchas
  • If you are running IIS 7 on a x64 platform you may get a cryptic "Active X is unable to Create Object". Before you google the problem first start up inetmgr, and locate the Application Pool that your ASP script is running from, right click on it and select 'Advanced Settings' from the context menu. The second option under the General section is 'Enable 32-Bit Applications'; change the value from False to True. If you still get the error, then Google it ;]
  • For testing purposes, I suggest moving your dll out of your debug directory and into another one and then register the dll from there. The reason for this is if you have to make any changes to the dll you will not be able to rebuild your project since the OS will have a lock on the dll in your bin directory.
  • If you need to make changes to your assembly after you have already registered it issue the following command from a Visual Studio command prompt inside the directory your assembly is registered from: regasm /u Impersonate.dll tlb:Impersonate.tlb Make your changes and then re-register the assembly using the regasm from the main tutorial. If, after you have unregistered the dll you are unable to replace the file (Access is denied because the file is in use by another process) start taskmgr and kill the w3wp.exe process (you will need to tick off the 'Show porcesses from all users' checkbox). You should now be able to replace the file.




Source:
C# rework:
http://p2p.wrox.com/classic-asp-basics/77007-solution-impersonation-classic-asp.html

MSDN Original (VB6)
http://support.microsoft.com/kb/248187/en-us

Tuesday, July 15, 2014

Cool tool for JSON to C# classes

This is a great site which reads your Json stream and recommends a C# class to contain the resulting query in your solution.

http://json2csharp.com/

Code Sample: Return Office element from Json query in Windows Phone

I wanted to capture this deprecated piece of code which I no longer need in my phone app.
We are supplying a list of office specific information to the phone client via a JSON query.

Calling Method:


using System.Net.WebClient;
using Newtonsoft.Json.JsonConvert;

private static Dictionary<int, Office> _officeLookup;
private static List<Office> theOffices = new List<Office>();

WebClient webClient = new WebClient();
webClient.Headers["Accept"] = "application/json";
webClient.DownloadStringCompleted +=
              new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(new Uri(apiUrl));



private void webClient_DownloadStringCompleted(object sender,             DownloadStringCompletedEventArgs e);
{
      try
      {
           if(e.Result != null)
          {
           var offices = JsonConvert.DeserializeObject<Office[]>(e.Result);
           theOffices = offices.ToList();
           int id = 0;
           foreach(Office office in offices)
           {
                _officeLookup.Add(id,office);
               id++;
             }
          }
         }
         catch (Exception ex)
         {
               //Error handling here
         }


}

Thursday, July 10, 2014

Using progress indicator in windows phone systemtray

I am going to add a progress bar to my existing phone app and found a good explanation at Microsoft's site.  It includes an example for implementing the progress bar programmatically or
declaratively.


Code Behind
using Microsoft.Phone.Shell;

namespace SystemTrayTest
{
    public partial class MainPage : PhoneApplicationPage
    {
        ProgressIndicator prog;

        public MainPage()
        {
            InitializeComponent();

            SystemTray.SetIsVisible(this, true);
            SystemTray.SetOpacity(this, 0.5);
            SystemTray.SetBackgroundColor(this, Colors.Purple);
            SystemTray.SetForegroundColor(this, Colors.Yellow);

            prog = new ProgressIndicator();
            prog.IsVisible = true;
            prog.IsIndeterminate = true;
            prog.Text = "Click me...";

            SystemTray.SetProgressIndicator(this, prog);
        }
    }
}


XAML
<shell:SystemTray.ProgressIndicator>
    <shell:ProgressIndicator IsIndeterminate="True" IsVisible="True" Text="Click me..." />
</shell:SystemTray.ProgressIndicator>

Source:
http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff626537(v=vs.105).aspx

Wednesday, July 2, 2014

How to load XML file located inside the folder of the application in window phone 8

Problem:

I have some onboard xml files which I needed to load into memory.  I was puzzling over how to load them into memory for use in my app.  I tried using XDocument library but I kept getting the error:
"Cannot find file '/XML Files/A.xml' in the application xap package.

XDocument doc = XDocument.Load( "XML Files/MyXmlFile.xml" );

This was not working.  I tried several variations but still was getting the error every time I ran to code.

Solution:
It turns out that my syntax was not the problem.  I needed to set the properties on the xml file correctly. 

1.) Build Action=Content
2.)Copy to output=Copy if newer (or Copy always).


Source:

http://stackoverflow.com/questions/4538874/how-to-load-xml-file-located-inside-the-folder-of-the-application-in-window-phon

Friday, June 27, 2014

Are you a programmer? ...Repost of a great article on software developers

- Software solves business problems

Windows Phone Application Bar

Had a great code review from the local MSFT Dev Rep here.  Thanks Gus!

The review brought out the issue of where is best to build the application bar.  I had chosen to implement it in the code behind.  Based on conversations with Gus and some other considerations
it was decided to implement it in the XAML.

It has been a bit since I last visited the theme.  I spent some time digging around the
windows phone website.  If you have not been there yet it is well worth the time and really critical
if you are writing mobile apps for Windows.

Basic syntax for the app bar in the xaml is:

<phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True" Mode="Default" Opacity="1.0" >
            <shell:ApplicationBarIconButton IconUri="/Images/save.png" Text="save" Click="Button1_Click" />
            <shell:ApplicationBarIconButton IconUri="/Images/delete.png" Text="delete" Click="Button2_Click" />
            <shell:ApplicationBarIconButton IconUri="/Images/help.png" Text="help" Click="Button3_Click" />
            <shell:ApplicationBarIconButton IconUri="/Images/settings.png" Text="settings" Click="Button4_Click" />
            <shell:ApplicationBar.MenuItems>
                <shell:ApplicationBarMenuItem Text="get default size value" Click="MenuItem1_Click" />
                <shell:ApplicationBarMenuItem Text="get mini size value" Click="MenuItem2_Click" />
            </shell:ApplicationBar.MenuItems>
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>

This block created a series of icons across the bottom of the screen and a submenu as well.
Just remember to embed the reference inside the phone page tags!

<phone:PhoneApplicationPage>
.....
</phone:PhoneApplicationPage>

Source:
Adding AppBars XAML
AppBar Class
AppBar Sample code
AppBar Icons - C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v8.0\Icons

Tuesday, June 24, 2014

Single controller with multiple GET methods in ASP.NET Web API

Problem:
Using a WebAPI pattern on a web services website, I ran into an issue.  The default WebAPI Pattern provides routing to the standard HTTP routes, GET, POST, PUSH, DELETE.  This is fine if you have no need to "overload" the routes.  My issue revolves around the need to have GET do mulitple actions besides just getting me all records or individual records.  I needed to return some attributes of the object being served up. 

Mike Wasson form MSFT has a great post on ASP.Net routing.  He describes how WebAPI has been designed.  The key was tweaking the routing table!


Solution:
I opened the WebApiConfig.cs file which is located in the App_Start directory of my WebAPI site.
The updated routing looks like

//Existing route
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//New route
routes.MapHttpRoute(    
name: "ActionApi",    
routeTemplate: "apiaction/{controller}/{action}/{id}",    
defaults: new { id = RouteParameter.Optional }
);

I have noted from some initial testing, that the routeTemplate must be unique.  I had tried using api as the common root for both routing entries.  The issue was that at runtime the routing always defaulted to the initial path.



Source:
http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
http://stackoverflow.com/questions/9499794/single-controller-with-multiple-get-methods-in-asp-net-web-api