Thursday, August 30, 2012

MVC Error: 0x800a1391 - Microsoft JScript runtime error: 'Sys' is undefined

If you get the error:

MVC 0x800a1391 - Microsoft JScript runtime error: 'Sys' is undefined

Then first check to make sure you have included the correct MVC javascript files:

C#:

<script src="<%= Url.Content("~/Scripts/MicrosoftAjax.debug.js") %>" 
    type="text/javascript"></script> 
<script src="<%= Url.Content("~/Scripts/MicrosoftMvcAjax.debug.js") %>"
    type="text/javascript"></script>

VB.Net:

<script src="@Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>

Saturday, August 25, 2012

CRM 4 - Could not load file or assembly ‘Microsoft.Crm.Tools.Admin.DMSnapinLib’

Error message:

Could not load file or assembly 'Microsoft.Crm.Tools.Admin.DMSnapinLib' or one of its dependencies. The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))

We fixed this error by clearing out the Asp.Net temporary folder under the Microsoft.Net\Framework64\v2.xxxxx folder. After that we had to restart IIS before we were able to load up the site.

CRM 2011 upgrade issues and solutions

The following were some issues that we encountered when upgrading a CRM 4.0 installation to CRM 4.0 and I hope it helps others out there:

Issue 1: Connection string doesn’t like FQDN

Error| System.Exception: Action Microsoft.Crm.Setup.Server.AddServerAction failed. ---> Microsoft.Crm.CrmException: Exceeded column length: Column Name
   at Microsoft.Crm.SharedDatabase.DatabaseService.RestrictLength(Column column, PropertyEntry propertyEntry)
   at Microsoft.Crm.SharedDatabase.DatabaseService.BuildBaseInsertSql(PropertyBag columnSet)
   at Microsoft.Crm.SharedDatabase.DatabaseService.Create(String tableName, PropertyBag columnSet)
   at Microsoft.Crm.Admin.AdminService.CrmServerService.Create(String serverName, Guid scaleGroupId, Guid podId, ServerRoles roles, ServerState state)
   at Microsoft.Crm.Setup.Server.Utility.ConfigUtility.AddServerToConfigDB(String serverName, ServerRoles roles, ServerRoles roleExclusionMask)
   at Microsoft.Crm.Setup.Server.AddServerAction.Do(IDictionary parameters)
   at Microsoft.Crm.Setup.Common.CrmAction.ExecuteAction(CrmAction action, IDictionary parameters, Boolean undo)
   --- End of inner exception stack trace ---, Error, RetryCancel, Option1

This turned out to be caused by the fact that we were using the fully qualified domain name in CRM 4.0. Once we went into the Deployment Mananger and edited the organization to use just the simple name for the sql connection (i.e, without the xxxxx.domain.com), We were able to restart the CRM 2011 installer. Important: at this point we had to restore a snapshot of CRM 4.0, as CRM 2011 installer had removed the old installer.

Issue 2: Corrupted performance logs:

"Action Microsoft.crm.setup.common.registerasyncserviceAction failed"

Please see: http://support.microsoft.com/kb/949092 – Although this is for CRM 4.0, the article is applicable to CRM 2011. In our case, it turned out to be corrupted performance logs. The performance logs were rebuilt using the command “lodctr /R” from c:\windows\system32.

Sunday, August 19, 2012

Enumerating a list object when you don’t know the actual type

Here is the scenario I was working with:

I needed to write an extension method that would be able to convert any class to a string representation. The class could have properties that were lists of any type (eg: List<T>), but I wouldn’t know in advance what types might be implemented as lists in the class. Here is the code I came up with. Listed below is the code for metro apps as well as for normal .net apps: (The code to enumerate any object that is a List is highlighted in the code below).

Metro

static class ObjectExtensions
    {
        public static string Convert(this object obj)
        {
            var typeInfo = obj.GetType().GetTypeInfo();
            var sb = new StringBuilder();

            foreach (var info in typeInfo.DeclaredProperties)
            {
                var val = info.GetValue(obj, null);
                string strVal;
                if (val != null)
                {
                    var valType = val.GetType();
                    var valTypeInfo = valType.GetTypeInfo();
                   
                    if ((val is string)
                        || valTypeInfo.IsValueType)
                    {
                        strVal = val.ToString();
                    }
                    else if (valType.IsArray ||
                        (valTypeInfo.IsGenericType
                            && (valTypeInfo.GetGenericTypeDefinition() == typeof(List<>))))
                    {
                        Type genericArgument = valType.GenericTypeArguments[0];

                        var genericEnumerator =
                            typeof(System.Collections.Generic.IEnumerable<>)
                                .MakeGenericType(genericArgument)
                                .GetTypeInfo()
                                .GetDeclaredMethod("GetEnumerator")
                                .Invoke(val, null);
                        IEnumerator enm = genericEnumerator as IEnumerator;
                        StringBuilder sbEnum = new StringBuilder();
                        sbEnum.AppendLine("List:");
                        while (enm.MoveNext())
                        {
                            var item = enm.Current;
                            sbEnum.AppendLine("Item: " + item.Convert());
                        }
                        strVal = sbEnum.ToString();
                    }
                    else{
                        strVal = val.Convert();
                    }
                }
                else
                {
                    strVal = "null";
                }
                sb.AppendLine(info.Name + ": " + strVal);
            }

            return sb.ToString();
        }
    }

Windows .Net

static class ObjectExtensions
    {
        public static string Convert(this object obj)
        {
            var props = obj.GetType().GetProperties();
            var sb = new StringBuilder();

            foreach (var info in props)
            {
                var val = info.GetValue(obj, null);
                string strVal;
                if (val != null)
                {
                    var valType = val.GetType();
                    if ((val is string)
                        || valType.IsValueType)
                    {
                        strVal = val.ToString();
                    }
                    else if (valType.IsArray ||
                        (valType.IsGenericType
                            && (valType.GetGenericTypeDefinition() == typeof(List<>))))
                    {
                        Type genericArgument = valType.GetGenericArguments()[0];

                        var genericEnumerator =
                            typeof(System.Collections.Generic.IEnumerable<>)
                                .MakeGenericType(genericArgument)
                                .GetMethod("GetEnumerator")
                                .Invoke(val, null);
                        IEnumerator enm = genericEnumerator as IEnumerator;
                        StringBuilder sbEnum = new StringBuilder();
                        sbEnum.AppendLine("List:");
                        while (enm.MoveNext())
                        {
                            var item = enm.Current;
                            sbEnum.AppendLine("Item: " + item.Convert());
                        }
                        strVal = sbEnum.ToString();
                    }
                    else
                    {
                        strVal = val.Convert();
                    }
                }
                else
                {
                    strVal = "null";
                }
                sb.AppendLine(info.Name + ": " + strVal);
            }

            return sb.ToString();
        }
    }

Thursday, August 16, 2012

Using Linq to concatenate strings

string[]words = new string[]{"hello","world"};
string concatenated = words.Aggregate((w,n) => w + " " + n);

Returns "hello world"

Saturday, August 11, 2012

MS Windows 8–Hackathon–My experience

Pre-prep:

  1. Installed Windows 8 Release Preview
  2. Installed VS 2012
  3. Did some exploration of the Bing Maps sdk for metro (blogged about it here: Using Bing Maps in a Metro App)

Idea: Port my OptiRoute Windows Phone 7 app to Windows 8

8:30 am : Check in. Setup my area, pickup coffee!

9:00 am : Quick sketch of how I plan on migrating OptiRoute to Windows 8. Setup a default VS project based on the “Grid App”

9:15 am: uh! oh! – VS 2012 preview does not open my Windows Phone 7 projects:

image

Need to install VS 2010 if I need to open it – screw – I just need the code – NotePad++ to the rescue.

9:30 am: Came up with basic design on paper. Watching Jerry Nixon’s demo.

WP_000301

10:00 am: Jerry Nixon’s demo is still going on. First issue encountered. Added reference to the Bing Maps Geocode Service. Looks like in WinRT there is no “GeocodeCompleted” event to which I can add my own handler. Hmmm, looks like I need to use “Await Async” model.

This Windows Phone 7 code changes:

public class GeoCoder
    {
        public void GeoCode(string query, Action<List<Coordinate>> action)
        {
            GeocodeServiceClient client = new GeocodeServiceClient();
            client.GeocodeCompleted += new EventHandler<GeocodeCompletedEventArgs>(client_GeocodeCompleted);
            GeocodeRequest request = new GeocodeRequest();
            request.Credentials = new Credentials();
            request.Credentials.ApplicationId = "Your Bing Maps Service Key Here";
            request.Query = query;
            client.GeocodeAsync(request, action);
        }

        void client_GeocodeCompleted(object sender, GeocodeCompletedEventArgs e)
        {
            if (!e.Cancelled && e.Error == null)
            {
                Action<List<Coordinate>> action = e.UserState as Action<List<Coordinate>>;
                List<Coordinate> coordinates = new List<Coordinate>();
                foreach (GeocodeResult geocodeResult in e.Result.Results)
                {
                    foreach (GeocodeLocation geocodeLocation in geocodeResult.Locations)
                    {
                        coordinates.Add(new Coordinate(geocodeLocation.Latitude, geocodeLocation.Longitude));
                    }
                }
                action(coordinates);
            }
        }
    }

Here is what the code looks like in WinRT:

async public Task<List<Coordinate>> GeoCode(string query)
        {
            GeocodeServiceClient client = new GeocodeServiceClient(GeocodeServiceClient.EndpointConfiguration.BasicHttpBinding_IGeocodeService);
            GeocodeRequest request = new GeocodeRequest();
            request.Credentials = new Credentials();
            request.Credentials.ApplicationId = "Bing Maps Service Key Here";
            request.Query = query;

            var geoCodeResponse = await client.GeocodeAsync(request);
            List<Coordinate> coordinates = new List<Coordinate>();
            if (geoCodeResponse != null)
            {
                foreach (GeocodeResult geocodeResult in geoCodeResponse.Results)
                {
                    foreach (GeocodeLocation geocodeLocation in geocodeResult.Locations)
                    {
                        coordinates.Add(new Coordinate(geocodeLocation.Latitude, geocodeLocation.Longitude));
                    }
                }
            }
            return coordinates;
        }

Wow! that code is so much more nicer looking! Me like this new Asynchronous programming model.

10:30 am: Jerry is still demoing his rad WinRT dev skills. Using geo-location, Netflix OData feeds to make an app.

10:31 am: For the last 15 minutes was fighting with a unit test project to get an Async test to run. It would not run!!
Took out the async keyword and it ran! weird!
Modified the unit test to not use the “await” keyword, which meant I could take out the “async” qualifier on the method.
Test is passing – woo! hoo! getting geo-coded results for my query!

[TestMethod]
       public void TestGeoCoder()
       {
           var geoCoder = new Bing.GeoCoder.GeoCoder();
           var asyncReturn = geoCoder.GeoCode("1 Microsoft Way");
           List<Coordinate> coordinates = asyncReturn.Result;
           Assert.IsNotNull(coordinates);
           Assert.IsTrue(coordinates.Count > 0);
       }

Also, needed to update the manifest of the test project to allow for internet connectivity for the tests to pass!

10:45 am: Jerry is finally done with his demo! He created a complete app in about 1 hour.

10:47 am: Looks like I cant call “Array.Sort(array,array)” (where the first array are the values and 2nd are the keys) method in a Metro app. Why would they have dropped this method?!!! WTF!
Need to implement my own code for this! (Note to self – see if I can get rid of the need for this sort completely).
For now, using a List of KeyValuePairs, ordering by the key and then using Linq to select the sorted set of keys

11:00 am: Looking good. All tests passing!
image

11:05 am: Migrated most of my base routing algorithm code. Now on to the UI

11:20 am: Working on the UI.
One needs to remember to set the active configuration platform to x86 for Bing Maps to work in the designer (x64 is not supported by the designer)

12:10 pm: Its lunch time. Still working on the UI

1:30 pm: Called in Jerry to help me with setting up a wrap panel. This is why these events are so cool. You get resources to help you through some of your road blocks. Thanks Jerry!

3:20 pm: Encountered a bunch of road blocks that I had to work through:
The biggest of which was that the map control has completely been changed in how things are done with it in the Metro SDK. I am still trying to figure out a lot of the stuff that I need to make the app ready for prime time (eg: Pushpin’s cant have color, line widths arent working correctly, unable to get the view rectangle, etc).

But here is where I am:

image

6:30pm: Things are coming along real nice and I am feeling nice about my app. Lots of unfinished features, but here is what I have gotten done now:

1. Loading a sample route.
2. Optimizing the sample route
3. Fly out menu to change map type (road, aerial, birds eye)
4. Sharing via email – share the route.
5. Searching for locations

7:15 pm: And we are done. Now the presentations start – Best of luck to me!

7:30 pm: Crap my application package is not working on the demo computer. Its only my package that’s having an error during installation. Jerry thinks its because I am using Bing maps and some dependency is not resolving. Thought I could demo it using my laptop. Nope cant do that – my laptop doesn’t have a VGA port (note to self, buy a HDMI to VGA convertor and keep in bag)

8:00 pm: I have been reschedule to come on at the end. Jerry forgot! He is asking everyone to vote! WAIT…. Jerry has an idea, use his laptop. It works. App is installed and I am going to demo it now!

8:03 pm: 3 minutes fly by during a presentation. Hit upon all the major features. Crossing my fingers.

8:30 pm: 17 apps were presented. 3 apps won the grand prize (Slate + Gift Card). My app (Get Around!) was one of them. I am stoked!

Parting thoughts:

The dev intro event to Win8 on Friday and the hackathon on saturday were well organized. Microsoft had every needed resource on hand. Xaml experts, Javascript experts, sys-admins to help installing Win8, great food and awesome give-aways and prizes. All we had to do was come with our laptops. Jerry Nixon did a great job running the whole show.

Here is what my completed app looked like:

02 03 04  
Initial un-optimized route Optimized route Sharing route via email  

Links:

Jerry Nixon: http://blog.jerrynixon.com/ 
Win 8 resources used during the dev event: http://blog.jerrynixon.com/2012/08/windows-8-resources-links-to-get.html
Joe Shirey: http://www.joeshirey.com/
Michael Palermo: http://palermo4.com/
Harold Wong: http://blogs.technet.com/b/haroldwong/ (has great post on installing Win8 using VHD. Also has posted VHDs that you can use to setup Win8 on your machine)

Friday, August 10, 2012

Metro Apps–Testing lifecycle events

How do you test how your app will behave when it is suspended?

When you run your app within the debugger, life-cycle events are suspended. But you can use the “debug location” toolbar to force events to occur. Find the debug location toolbar under: image

Now you can test life cycle events such as “Suspend”, “Resume” and “Suspend” and “Shutdown”

image

Windows Metro App–ListView reordering

A quick note on enabling reordering of list view items in Metro Apps.

1. In previous version of Windows 8, there was a bug and you could not bind the ListView to an ObservableCollection and have reording work. This has been fixed since the “Windows 8 Release Preview” and you can now use ObservableCollection.

2. For reording to work, it not enough to set “CanReorderItems” to true. You ALSO need to set “AllowDrop” to true.

Thursday, August 09, 2012

Wednesday, August 08, 2012

Migrate Reporting Services to another machine–Reporting Services Scripter

Came across this nifty little tool called “Reporting Services Scripter” which can be used to migrate RDLs to a different machine. In addition, it can also move other settings like schedules, etc. Another cool feature is that you can use it to migrate RDLs from a 2005 machine to a 2008 machine.

Download it from: http://www.sqldbatips.com/showarticle.asp?ID=62

Saturday, August 04, 2012

Using Bing Maps in a Metro App

Step 1: Download the Bing Maps SDK.

This is easier now as its been made into a Visual Studio Extension.

image

Step 2: Create a blank Metro App

Step 3: Reference the SDK dlls:

You need to reference Bing Maps as well as the Visual C++ runtime (don’t worry, this is only a dependency and you will not have to write an C++ code)

image

Step 4: Get your access key

To get your access key you need to sign up for a developer account at the Bing Maps developer portal (https://www.bingmapsportal.com/). Once you have created your account, you need to create a key for your metro app. Remember to set up your app as a Metro app when creating your key.

Step 5: Drop your key into your app.

A good practice is to make your key an application resource. This will make it easy to use it on any page that uses the Maps control.

To do this, open your App.xaml page and add the following line right after the “</ResourceDictionary.MergedDictionaries>” line:

<x:String x:Key="BingMapsApiKey">Insert Your Api Key</x:String>

image

Step 6: Reference the Bing.Maps namespace in the page where you intend to use the map control. To do this add the following line to the page declaration:

xmlns:bing="using:Bing.Maps"

image

Step 7: Add the map control. To do this, just add the following line in your page (I added it to the default grid that gets created when you create a blank page).

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <bing:Map x:Name="MyFirstBingMap" Credentials="{StaticResource BingMapsApiKey}" />
</Grid>

Step 8: Run your app and admire your creation Smile

image

Doing more:

Step 9: Centering the map to your location:

First, you need to enable your app to use location data. To do that, double click the “Package.appmanifest” file and on the capabilities tab, select “location”.

image

In the designer for you page, add a MapLayer to your page:

<bing:Map x:Name="MyFirstBingMap" Credentials="{StaticResource BingMapsApiKey}">
            <bing:MapLayer x:Name="MyMapLayer">
            </bing:MapLayer>
</bing:Map>

Add the following code to the “OnNavigatedTo” event in the page containing your map:

async protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            Geolocator geo = new Geolocator();
            geo.DesiredAccuracy = PositionAccuracy.Default;
            var currentPosition = await geo.GetGeopositionAsync();

            Location loc = new Location()
            {
                Latitude = currentPosition.Coordinate.Latitude,
                Longitude = currentPosition.Coordinate.Longitude
            };

            MyFirstBingMap.SetView(loc, 13, 0);

            Canvas pushPin = new Canvas();
            pushPin.Children.Add(new Ellipse() { Fill = new SolidColorBrush(Windows.UI.Colors.Red), Width = 22, Height = 22, Stroke = new SolidColorBrush(Windows.UI.Colors.Black), StrokeThickness = 2 });

            MapLayer.SetPosition(pushPin, loc);
            MyMapLayer.Children.Add(pushPin);

        }

Running the application will result in the following map:

image

Things to notice:

1. The method is labeled as “async” this is because we are using the “await” keyword on the GetGeopositionAsync method of the GeoLocator.

2. Instead of using “Pushpin” control, I am using a canvas and drawing a circle. The reason is the Pushpin control does not seem to allow changing of colors or size. (Don’t know if this is a bug in the release preview or by design). Which is why I am using a custom control as my pushpin.

Thursday, August 02, 2012

The non-generic method 'Microsoft.Practices.Unity.IUnityContainer.Resolve(System.Type, string, params Microsoft.Practices.Unity.ResolverOverride[])' cannot be used with type arguments

If you get the “The non-generic method 'Microsoft.Practices.Unity.IUnityContainer.Resolve(System.Type, string, params Microsoft.Practices.Unity.ResolverOverride[])' cannot be used with type arguments” compiler error while building a Prism application, remember to add a using statement for “Unity” (using Microsoft.Practices.Unity;)

CRM–Setting the default page for all users

Unfortunately there is no supported way to do this. The only way I have found to do this is by updating the “homepagearea” and “homepagesubarea” values in the usersettingbase table in the organization database of CRM.

update UserSettingsBase
    set Homepagearea='default pane’
    ,Homepagesubarea='default tab'

After running the above script, you need to reset IIS, otherwise for users already logged into the system, will now see the change.

And below are the values for some of the panes and tabs that you can use for the script above.

Pane (Homepagearea) Value
Tab (Homepagesubarea) Value

Workplace

Workplace

 
 

Activities

nav_activities

 

Dashboards

nav_dashboards

 

Queues

nav_queues

 

Calendar

nav_calendar

 

Reports

nav_reports

 

Imports

nav_import

 

Duplicate Detection

nav_duplicatedetectionjobs

Sales       

SFA

 
 

Accounts

nav_accts

 

Contacts

nav_conts

 

Opportunities

nav_oppts

 

Leads

nav_leads

 

Goals

nav_goals

 

Goal Metrics

nav_metric

 

Rollup Queries

nav_goalrollupqueries