Category Archives: Nezaradené

Microsoft Lightswitch grid controls – Modal Window picker, Auto Complete Box and small tweaks

LightSwitch is quite flexible when it comes to displaying data in grid. You can even use your own custom Silverlight controls, that you can build according to some rules, but when you need it, it’s there. Nice to feature, when all out-of-possibilities fail.

In this small post I will try to elaborate on built in controls and how to tweak them.

I will start with small sample project, that you can download if you want to dig deeper on you own pc.

Some good old grid in Lightswitch can look like this :

lightswitch grid in editor

Here you can see some sample data. Every node in Data Grid Row means it will be 1 row in a grid. You see icon and then name of each property like Name, Surname, etc. With small dropdown you can select type of control Lightswitch will use when displayed so for example when you need to display something read only, then you can select to display label.

lightswitch grid types of controls

Types that will Lightswitch display are dependent on type of property. When you have DateTime property, you will have more choices :

lightswitch grid types of controls datetime

When you need some column as read only you can use Date Time Viewer in this case.

OK, now comes the tweaking.

When you reference another table, then your screen can look like this :

lightswitch grid in editor another table reference

This is the default, but you can change it. Choosing type next to Country (in this case of course) will result in what you see when you see just grid. In this default case it will look like this :

lightswitch grid in editor default combo

But maybe you want to display a grid in cell of this main grid. OK, just change default to columns layout and you will have this :

lightswitch grid columns in grid

Your users like rows better? OK, here you go :

lightswitch grid rows in grid

Say you want a quite requested feature : you need combo box, but when you click on it, you need grid. OK, here we go :

Set country type to Auto Complete Box but change also underlying type to grid. The way it works in Lightswitch is that you can control what to see in grid by changing node on Data Grid Row level, but change in underlying level will change what you see once you click on down arrow of Auto Complete box. And this can be also table layout. This is how it looks like in editor :

lightswitch grid in editor combo with grid

This at runtime :

lightswitch grid in editor combo with grid runtime

OK, now to another common task with this grid, that will also affect something else. Say you want to display not Slovakia or Czech republic in the grid for selected item, but something else. How to set it? Well, “use the force Luke” :), but we will use model. Lightswitch is written so, it will mind order of properties when we created model. This order is preserved in auto generated window for adding, editing and removing items but also it will take first property and show it here. So once we change model (I moved Currenty to top) like this :

lightswitch model change

It will change also this :

lightswitch grid another property autocomplete

and this :

lightswitch add new country popup

So please be aware of that.

Last things that I would like to show you are modal windows.

Say you need a picker to choose from some another grid, you you can user a Modal Window Picker and in the picker you can have a grid (table layout) and it will look like this ion grid :

lightswitch picker in grid

and with open popup :

lightswitch picker popup

Or just plain old button that will open window properties of current record we want to edit in different controls. Picture text box with very long text. You can add button behind this column to open popup window that will have only one textbox, but that will be multiline and that will enable users to edit this long text more user friendly.

If you have any questions, feel free to ask, or mail me.

Solution can be downloaded here :!1786&parid=78A5783DE37D2EBE!1779&authkey=!AE2rYVVr0I8FBww and look for file.


Môj osobný pocit po Barcampe 2011 v Brne

Takže v krátkosti a stručne – môj osobný pocit je veľmi dobrý, v podstate ako z každého Barcampu ktorého som sa dosiaľ zúčastnil.

  • V prvom rade som mal dobrý pocit z toho, že škola VUT FIT (a ľudia okolo celej akcie), kde sa celý Barcamp odohral bola schopná a ochotná organizovať a hostovať takúto vec. Je to dobrá vizitka toho, že ľudia na nej sú oddaní veci a chcú robiť čo robia a baví ich to. Dobre vybavené učebne, zaujímavé stoličky (o ktorý sa tweetovalo že sú UX fail:D) a všade zástrčky na booky kde sa len pozriete 😀 , WiFi a kopa jedla.
  • Po druhé – zaujímavé prednášky. Všetky ktorých som sa zúčastnil boli buď zaujímavé, alebo aj zaujímavé a aj zábavné. Každý si vybral. Od Developera, cez startup-istu po kreatívca. Proste každý. Jediná škoda chýbajúcej prednášky o GITe, celkom som sa na ňu tešil. Next time.

Kedže sa všetko nahrávalo (občas síce blbol nejaký mikrofón, ale to nevadí), dúfam už onedlho si budete môcť všetci pozrieť prednášky z pohodila domova.

Osobne by som chcel pochváliť a odporučiť tieto prednášky (iné pochváliť neviem, no tieto som osobne navštívil) :

Každopádne, pozrite si všetky videá, nemáte o čo prísť. Iný uhol pohľadu vždy len obohacuje. 🙂

Takže sa teším na budúcu akciu a ďakujem organizátorom aj prednášajúcim.

How to get count of entities in Microsoft CRM 2011

Working on a task, I wanted to know exact number of records for particular entity in CRM 2011 but I wasn’t able to access this information via some standard way and LINQ query with .Count was throwing exception that this type of query is no implemented – The method ‘Count’ is not supported. (I’m talking about class that is generated by crmsvcutil.exe tool from CRM 2011 SDK).

How to solve this… hmmm.

So, there are several posibilites :

When accessing entity with small number of records, you can use this approach :

but there is small caveat, default paging in CRM 2011 is set to 5000 records (at least on system that I have my hands on). So returned XML will claim that there is 5000 records, but you have to watch for EntityCollection.MoreRecords bool that is set when this is just page of entities also with PagingCookie that has the value of last record (XML fragment) that CRM knows where to continue (essentialy there is GUID with last record).

Or you can use my snippet :

I created small chunk of code that can retrieve total number of your desired entity and return this as int.

Introducing > the code 🙂 :

/// <summary>
/// Gets the supplied entity count from CRM 2011.
/// </summary>
/// <param name="Service">The CRM 2010 service.</param>
/// <param name="EntityName">Name of the entity we need get count of.</param>
/// <param name="ServicePageSize">Size of the page (optional).</param>
/// <returns></returns>
private int GetEntityCount(IOrganizationService Service, string EntityName, int ServicePageSize = 5000)
	RetrieveMultipleResponse retrieved;
	int PageNumber = 1;
	string PagingCookie = string.Empty;
	int PageSize = ServicePageSize;

	do {
		QueryExpression query = new QueryExpression() {
			EntityName = EntityName,
			//ColumnSet = new ColumnSet(Columns),
			PageInfo = new PagingInfo() {
				PageNumber = 1,
				Count = PageSize

		if (PageNumber != 1) {
			query.PageInfo.PageNumber = PageNumber;
			query.PageInfo.PagingCookie = PagingCookie;

		RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
		retrieve.Query = query;
		retrieved = (RetrieveMultipleResponse)Service.Execute(retrieve);

		if (retrieved.EntityCollection.MoreRecords) {
			PagingCookie = retrieved.EntityCollection.PagingCookie;
	} while (retrieved.EntityCollection.MoreRecords);

	return ((PageNumber - 1) * PageSize) + retrieved.EntityCollection.Entities.Count;

IOrganizationService is class that is in Microsoft.Xrm.Sdk namespace and is used to connect to CRM. I’m using late binding here, so I created via tool (crmsvcutil.exe mentioned earlier) one class per every entity and thus I can call the method like this :

int acc = GetEntityCount(_serviceProxy, Account.EntityLogicalName);

Alternatively you could use string for the second parameter like this :

int acc = GetEntityCount(_serviceProxy, "account");

_serviceProxy is instance properly initialized with credentials and URL to running CRM 2011.

RetrieveMultipleRequest is class located in Microsoft.Crm.Sdk.Messages.

Optionally you could add filtering to the QueryExpression to apply some logic. There are several examples on other blogs.

The traffic from CRM 2011 server is as small as possible, because as you can see (I have commented out ColumnSet collection) there are no columns specified so only column that will be sent is ID (of type GUID).

If you have any additional questions or perhaps there is some easyer way, pls mail me or write them down in the comments. – complete class, just include it in your project with referenced assemblies and you are good to go. Feel free to modify.

Hope this helps, enjoy 🙂

How to correctly change and set property of type Money in Microsoft CRM 2011

Yesterday I found out that setting property of type Money on entity can make really difference.

I’m altering Account records via WCF service one at a time and saving the changes in CRM 2011. I was changing some money property like this :

entity.SomeMoneyProperty = new Money() { Value = decimalValue };

Everything compiled and worked fine until I realized, that the value I was setting really isn’t stored in the CRM. But there was no runtime error, nothing.

So I searched the CRM 2011 SDK and found out, that they use only this type of creating the Money property :

entity.SomeMoneyProperty = new Money(decimalValue);

And with this aproach, everything worked fine 🙂 THX SDK, I

Microsoft Silverlight RIA Services app splash screen problem – request to WCF service appears to be cached on Internet Explorer 9 and timeouted

The problem :

Our Silverlight RIA Services application isn’t working under “special” circumstances. These special circumstances are : if user launches another instance of Internet Explorer 9 and tries to load page with Silverlight component, app isn’t loaded and after some time IE displaying just white screen (about 1 minute. BTW you could right click on the white surface and see that there si Silverlight loaded) suddenly displays error about RIA service call timeout.

This is the behaviour when deployed to Windows 2008 R2 with IIS 7.5. When launched from development webserver or local IIS 7.5 on my Windows 7 dev box, things worked fine.

First thoughts :

As first thing, I always launch Fiddler as my tool of choice, when it comes to debugging HTTP traffic. What I saw was normal traffic when IE was instantiated once on my localhost.

Under normal traffic you should understand :

  1. Request to root of the app and IIS returned 401 (please authenticate – see HTTP status codes for reference) (you need to have only windows authentication turned on when using RIA Services),
  2. Browser repeates the request and but this time with authorization cookie and IIS responded with html, that causes browser to download xap and other files,
  3. Downloading Silverlight.js file (cached sometimes),
  4. Downloading our custom SplashScreen.xaml file that is loaded before the whole xap and serves as the name reveales as splash screen of the app,
  5. Downloading .xap file (the whole app, big zipped file),
  6. Downloading some resources (images and so on),
  7. First request to WCF service created by RIA Services and these requests continue as user clicks in the apps and loades requests data (BlablaMainService.svc path requests)

On my machine, traffic looked like this :

ria services traffic

Then I browsed to our test server and traffic looked like this :

ria services problem

(please don’t look at the localhost string, I simulated the problem on my machine after we fixed it)

Let me stop here for a moment. At first, I thought that the browser is caching the service requests somehow. They obviously never left the browser. While looking at the Fiddler I realised that there is also other problem.

The difference is obvious – we are missing the SplashScreen.xaml file and we have some additional requests. Browser requested some .png file, to be specific, this is the image you see when there is no Silverlight installed on your machine, but this is not our case. My colleague had javascript errors in IE9 turned off, so he unfortunatelly didn’t saw this message :

error loading silverlight splashscreen

The solution :

So my first assumption that requests are cached because they never hit the server was wrong. For the first time when the app was fired, IE ignored the SplashScreen.xaml file was missing. Silverlight just displayed normal loading screen and user could continue. Of course, JS error telling that specified .xaml file is missing was there, but you could overlook it. The reason of different behaviour on my Windows 7 dev box and on production Windows 2008 R2 was that the SplashScreen.xaml file’s Build Action in VS 2010 was set to Page and not to Content and thus was not copied to destination dir when deployed. But my local IIS was working on my local copy where this file was present. As always, look at the traffic underneath shiny browser experience, it really matters.

How to read, create, update and detele objects in Microsoft CRM 2011 on premise via WCF service.

Please note that this code works for ON PREMISE installation of Microsoft CRM 2011.

In this short article I will show you how to access items in CRM 2011 via new built in WCF webservice. You should use WCF when accessing CRM from code and REST when accessing from client browser of Silverlight application.

Of course you can use old style CRM 4.0 like aproach with QueryExpression class and then RetreiveMultiple on IOrganizationService instance, but there is also easier approach.

You will need to download and extract CRM 2011 SDK. Current version is 5.0.3 and you can find it on this link :

Here are the steps you need to follow :

  1. Create console application (with full .NET fw 4.0, not client profile) (you can ofcourse create WPF, WinForms or ASP.NET app, but for our example we will use console app)
  2. Locate crmsvcutil.exe in sdk\bin folder along with microsoft.crm.sdk.proxy.dll and microsoft.xrm.sdk.dll.
  3. Both assemblies add as reference to the console project and add also .NET FWs System.ServiceModel and System.Runtime.Serialization.
  4. Use crmsvcutil.exe to use early bound aproach, that will generate classes for all entities within CRM 2011 and also your custom ones. (this is essential something like adding webservice reference to webservice in CRM 4.0 times). I used commandline arguments like this :crmsvcutil /url:http://server/organization-name/XRMServices/2011/Organization.svc /o:filename.cs /n:namespace /serviceContextName:context-name. /url – url of services, /o – output file, /n – namespace of generated classes, /serviceContextName is name of service, but when you ommit this switch, no context will be generated at all. Context is used for accessing the entities via WCF.
  5. Add generated .cs file to the project (copy to folder, button Show all files, include in project).
  6. Every generated entity will get it’s dedicated IQueryable collection, so for Account you should query AccountSet, for Annotation you should query AnnotationSet and so on. IQueryable means you can query the store with LINQ expressions.

For access you need only this code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk;
using System.ServiceModel.Description;
using service-namespace;

namespace CrmConsoleApplication2 {
    class Program {
        private static IOrganizationService _service;
        private static OrganizationServiceProxy _serviceProxy;

        static void Main(string[] args) {

            IServiceConfiguration<IOrganizationService> orgConfigInfo =
                ServiceConfigurationFactory.CreateConfiguration<IOrganizationService>(new Uri("http://server/company-name/XRMServices/2011/Organization.svc"));
            var creds = new ClientCredentials();

            using (_serviceProxy = new OrganizationServiceProxy(orgConfigInfo, creds)) {

                // This statement is required to enable early-bound type support.
                _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

                _service = (IOrganizationService)_serviceProxy;

                List<Account> acc;
                using (context srv = new context(_service)) {
                    acc = srv.AccountSet.Where(a => a.AccountId != null).ToList();

Account a1 = acc[0]; a1.Name = a1.Name + ” mod mod”; Account a2 = acc[1]; a2.Name = a2.Name + ” mod mod”; srv.UpdateObject(a1);
srv.UpdateObject(a2); srv.SaveChanges();
} } } }

And this is what you get @ runtime :

crm2011 accessing accounts wcf service

This indeed is a stupid examle with not checking if there is something at position 0 and 1 but I just wanted to modify something on my account. After modification of account you should call UpdateChanges each object you modified and then to save changes to CRM you should call SaveChanges. All changes will be processed at once.

You should also wrap OrganizationServiceProxy and also contex with using, because they both use IDisposable interface. Calling .ToList() after where on AccountSet will trigger downloading of all entities.

Please be aware, that downloading many objects will create big response from server (just for example 6000+ of our customized account objects created aproximately 180MB response (tracked by fiddler) and my console app expanded to 700MB in RAM when parsing and 500MB after loading all objects).

To create and delete record, you can use snippet like this :

                    Account newaaa = new Account();
                    newaaa.Name = "test acc";


                    Account newAcc = srv.AccountSet.Where(a => a.Name == "test acc").FirstOrDefault();

This will create new account, when invoking SaveChanges after AddObject, object newaaa will be filled with guid of freshly created Account. To delete object you have to “download” new object from service, you can’t use newaaa object, because context isn’t tracking the changes, so it can’t delete the object also.

In case of any questions, just mail me or add comment under the article.

Getting : The handshake failed due to an unexpected packet format exception while accessing Microsoft SharePoint 2010 from ASP.NET 4.0 application

Yesterday I encountered strange thing when accessing SharePoint 2010.

What I had :

I created some time ago ASP.NET application for uploading file to SharePoint 2007. Our company upgraded the SharePoint to latest 2010, so I had to update my tool also. It used ASP.NET 3.5. Internally we are using Forefront and I have Forefront client installed on my dev box. Everything worked fine. (I’m not sure, if the Forefront client is installed also the server, but I suppose so).

What was the problem :

After migration to ASP.NET 4.0, my code wasn’t working. When calling Lists.UpdateListItems on web service generated proxy class, I got nice System.Net.WebException The underlying connection was closed: An unexpected error occurred on a send exception with underling The handshake failed due to an unexpected packet format exception. So I created small console app and the code was working again (I used same library in the ASP.NET app and also in console app). But the ASP.NET app wasn’t.

Exception looked like this :

Also as I saw, it had to do something with SSL certificates.

Desperate, I fired up Fiddler, my tool of choice for HTTP traffic debugging and ASP.NET page started to work without any code change. Then it hit me : proxy problem.

The solution :

The Forefront client is set so, it will direct any app to either use our proxy server, or go directly to the server inside of our organization. In my case the ASP.NET app tried to use proxy settings and called the Sharepoint server via proxy and I would say, something messed up the SSL certificates. Anyway, you just have to say to your app, that it shouldn’t use proxy and this can be done in code, or in web.config (respectively app.config). I used this approach. How to set proxy in web.cofign file can be found here :

Enjoy. 🙂

How to turn on developer errors in Microsoft CRM 2011 (aka Titan or 5.0)

Developing for Microsoft CRM can be a big pain sometimes. Often, there is an error on the server, but there is only generic note for normal (understand user) customer. We as devs need stack trace and other fancy things and bells and whistles. I remember, that Microsoft CRM 4.0 had this possibility and it could be done via some 3rd party tool that another developer created and for me it was just checking a checkbox.

Moving to CRM 2011 I had feeling, that there must be a way to turn this thing on again (and turn off in production indeed).

So, if you want to turn developer erros on your dev CRM 2011 , you should go to the web.config and search for this text :

Show Developer Errors
If a server-side error occurs, this setting determines whether or not Debug error
messages are rendered to the user.  Debug error message are not recommended for
production environments, but may be useful in attempting to debug a problem you are
having with MSCRM.
Recommended Setting: “Off”
Values: “On” or “Off”
<add key=”DevErrors” value=”On” />

Setting On and Off will change your web.config file and thus restarting the whole app, but you have a sweet reward. Anytime there will be crash, you will see something like this :
detailed error information crm 2011

On the left you can see big icons with some additional information :

  • Detailed information on error that occured,
  • Original ASP.NET error information (famous ASP.NET yellow screen of the death),
  • Debug information for this server,
  • Generic error that the user would see,
  • Button that will copy some error information to the clipboard.

So, hope this helps. 🙂


How to enable and disable entities in Microsoft CRM 2011

The problem :

In my current project I need to enable and disable some entities, and because there is no direct method on generated proxy class (via crmsvcutil.exe), I created small helper with help from CRM SDK. Particular chunk of code that i’ve used, can be found here : or here

The code :

Following is the snippet (method is static as you see, I placed it in static class CRMHelpers and call it as neccessary) :

         /// <summary>
        /// Sets the state of the entity.
        /// </summary>
        /// <param name="serviceProxy">The service proxy.</param>
        /// <param name="EntityId">The entity id.</param>
        /// <param name="EntityLogicalName">Name of the entity logical.</param>
        /// <param name="StateValue">The state value.</param>
        /// <param name="StatusValue">The status value.</param>
        static public void SetEntityState(IOrganizationService serviceProxy, Guid EntityId, string EntityLogicalName, int StateValue, int StatusValue) {
            SetStateRequest setStateRequest = new SetStateRequest() {
                EntityMoniker = new EntityReference {
                    Id = EntityId,
                    LogicalName = EntityLogicalName
                State = new OptionSetValue(StateValue),
                Status = new OptionSetValue(StatusValue)

You can download the source code here :

How to use the code :

Following is the snippet in one of my classes where I use the helper code.

	/// <summary>
	/// Opens the opportunity.
	/// </summary>
	/// <param name="entity">The entity.</param>
	protected void OpenOpportunity(Opportunity entity) {
		CRMHelpers.SetEntityState(crmService, entity.Id, Opportunity.EntityLogicalName, (int)OpportunityState.Open, -1);

There are two values, that you supply to the SetEntityState : StateValue and StatusValue. These make a pair and if you supply unavailable pair, you will get an exception. You can obtain valid pair from existing entity, or you can use this sample : Retrieving State and Status Options via the MetadataService that worked with CRM 4.0. I haven’t tried it on CRM 2011 (aka 5.0). As you can see I’m using cast from Enum that is generated via crmsvcutil.exe utility from SDK for StateValue and hard coded value for StatusValue.

Additional stuff :

In addition there are some other related tasks, that I found on the internet and you may be interested in :

How to enable and disable whole organization in CRM 2011

General discussion about enabling/disabling entities in CRM2011

Sample code to activate / deactivate record in CRM 2011


In case of any questions, ask them in the comments.