Use GetValueOrDefault in early bound plugins and say goodbye to catching nulls

When writing plugin code CRM has a very frustrating feature which allows it’s fields to be null.  Note I said this was a feature not a bug 🙂

I believe this was was one of the main reasons in CRM 4 it had it’s own set of variables CrmDateTime, CrmDecimal, CrmFloat, CrmMoney, CrmNumber.  These could hold a null as well as value (I think, it has been a while since I did any CRM 4 development).

Where this really niggles me is when I can’t pass anearly bound field  into a method because the method takes a bool but the early bound field is a ?bool, which basically means it’s a bool that can be null.

So how do we code around this

Late bound

So in previous blog post I have talked about using Entity.GetAttributeValue instead of Entity.Contains

using GetAttributeValue is great because it means I could take all the entity.contains code below

if (entity.Contains("salutation"))
{
     title = ( string)entity.Attributes["salutation"];
}

The GetAttributeValue returns either a null or a default value.  This is great for boolsints etc because instead of null I now get false or 0;

here is the list of default values
Type Return
Numerical (int, decimal, double) 0
Boolean false
DateTime DateTime.MinValue
Guid Guid.Empty

For other variables it will return a null.

Early bound

What if you are using early bound classes and don’t want to add the potential risk of putting in syntax errors in your plugin code by using late bound code.

What are the benefits of early bound code

  • Readability
  • No Syntax errors at runtime
  • casting errors are found at compile time
  • Easier to read, debug, maintain and extend

The main reason I like early bound classes is because it’s easier to understand and I don’t have to keep looking up and typing the name of the CRM fields.  It also moves most of the errors into compile time (syntax and casting errors), which means it’s less likely these errors will get through to the customers.

GetValueOrDefault to the rescue

If you want to convert the an early bound field into simple attribute then you should use GetValueOrDefault, which

The reason it’s a good idea to use this is because if you casted it to a bool or int you are in danger of creating an error because you cannot set a bool to be null!

The GetValueOrDefault will return a value (the default value for the variable type) even when the HasValue for the field is false (e.g. it’s null). Using the GetValueOrDefault means you don’t catch the error but you do have to be prepared for receiving a default value and code with that in mind.

So here it is in action

if (entity.Contains("salutation"))
bool credit = entity. CreditOnHold.GetValueOrDefault ();
entity. CreditOnHold = true ; credit = entity. CreditOnHold.GetValueOrDefault ();

 

 

The MSDN article if you want more, to be honest there isn’t much more to say about it.

Visual Studio 2012 keeps crashing

Visual studio has kept crashing for 3 developers over the last few weeks.

What makes it worse is there doesn’t seem to be any consistency to the cause of the crashing, it sneaks up suddenly and POW, freezes and crashes before kindly offering to reopen for you.

What made it more confusing/annoying was no could reproduce the crashing constantly, some days you would have a few days without crashing and then one day it could crash 10 times and ruin your day.

 

We found a solution which seems to work

(backup first) – ALWAYS

then delete the ComponentModelCache folder, which you should find here

C:\Users\xxx\AppData\Local\Microsoft\VisualStudio\11.0\ComponentModelCache

 

The solution doesn’t seem to shed much light on what was causing the crashing, particularly the fact it was happening to different developers on different computers.

 

 

Installing and uninstalling DLL’s into the GAC

 

There will probably come a time in every CRM developers life when they have to install a DLL into the GAC.

The reason you might want to do this is so you code can access the dll’s and methods without having to have the DLL included with your code.  A good example of this is if you have some code which is used in all of your CRM plugins, you can load the dll into the GAC and then all the plugins will be able to access it.

This can only be done using CRM on premise because you can’t do it with CRM online because you can’t load dll’s into the GAC and also because the online plugins are in the sandbox they are not allowed to call dll’s and external code.

To install dll’s into the GAC you have to use the gacutil, which is usually packaged in with Visual Studio.

There is one odd and tricky thing to watch out for, the code for installing/uploading a dll is different from the instruction to uninstall.  It’s not very different which makes it all the more tricky.

You have to use the command line and call the gacutil.exe from the command line, the line below installs a dll into the GAC.

gacutil /i Common.PluginCode.dll

notice you put /i and then the name of the dll with the dll affix.

to uninstall he same dll

gacutil /u Common.PluginCode

its backslash /u and the name of the dll (without the dll affix)

Recently I got this muddled and kept the .dll on the uninstall instruction.  So I then ended up installing a duplicate DLL into the GAC which caused problems, so beware.

 

if would like a more professional explanation about installing into the GAC click the link below

http://msdn.microsoft.com/en-gb/library/ex0ss12c(v=vs.80).aspx

 

Windows 8 and Yammer

Software updates can be sometimes be easy and sometimes cause howling of frustration

People have started to updated to windows 8, which seems a lot a faster than the previously version of windows but does take a little bit of time to get used to (there’s no start button!).  The first impressions of Windows 8 is it looks fantastic and new interface is easy to use.  The one puzzling aspect is it does act like a tablet screen which means you can only have one application on screen at one time, this is great for tablets but not always ideal for desktops.

The developer who upgraded his windows 7 desktop had a very simple job taking under 2 hours to upgrade but the person who had to update their MAC had quite a task on their hand, which even involved visiting an Apple shop to get some help from someone known as Obi-Wan.  Obi-Wan used the force and we now have Windows 8 successfully running on a Mac.

I haven’t taken the plunge myself yet because I (in my wisdom) setup my laptop to use windows server 2008 so I could have hyper v on my laptop.  The downside is I would have to have a totally new install to have Windows 8.  I am at the moment working up the ethusiams for the task, it might be a new year thing.

One gotcha with Windows 8 and installing .NET 3.5, the full details are below in the Microsoft kb article

Error codes when you try to install the .NET Framework 3.5 in Windows 8 or in Windows Server 2012

http://support.microsoft.com/kb/2734782

Yammer

The company I work for (Metaphorix) have decided to use Yammer.  I think this is a good idea because hopefully in a future release of CRM yammer will be fully integrated.

My first impression is Yammer seems to be a bit like an internal company twitter feed where you can create groups (twitter lists maybe or hashtag) which enables users to subscribe to groups (sales, developers, CRM, NAV, Support, etc etc) and share/receive information for certain groups.

The main driver for wanting to use Yammer is reduce the amount of internal emails being sent because  this is not an efficient method of sharing information.  Also users who receive a lot of emails can basically lose information because their inbox is receive too many emails for them to read and respond to all of them.

Like most new pieces of software the trick is understanding how to use it to fit in your companies working ecosystem and processes, not to mention it can be difficult to change peoples working habits.

Why change the Web Service Namespace from tempuri.org

When you create a Web Service the default Namespace is

  [WebService(Namespace = http://tempuri.org/”)]

I was wondering firstly should I change it and secondly what should I change it to.  The default Namespace doesn’t really give you much of an indication or example.

The short answer is all Web Services need a unique namespace to distinguish it from other Web Services on the web and the best way to do this is put the company you work for in it e.g. for me

http://metaphorix.com

Whilst you are developing the Web Service is fine to leave as tempuri.org but don’t forget to change this before you make it public.

I can’t be the only person to wonder about this because Microsoft has a support page dedicated to the question

No recommendation is made to change the http://tempuri.org/ namespace in Visual C++ .NET Managed C++ Web Service applications

Although it’s not really the question I am asking it does provide the answer, there are two useful parts in the article

 

You can change the default namespace by using the Namespace property of the WebService attribute. TheWebService attribute is an attribute that is applied to the class that contains the XML Web service methods. The following example sets the namespace to “http://microsoft.com/webservices/”:

  [WebService(Namespace="http://microsoft.com/webservices/")]
	public __gc 
        class MyWebServiceClass : public System::Web::Services::WebService
    {
        // Implementation     
    };

Identify your XML Web service with a namespace that you control. For example, you can use the Internet domain name of your company as part of the namespace. Many XML Web service namespaces look similar to URLs, however, namespaces do not have to point to actual resources on the Web. (XML Web service namespaces are URIs.)

 

Each XML Web service must have a unique namespace for client applications to distinguish the Web service from other services on the Web. For XML Web services that are under development, “http://tempuri.org/” is available. However, use a more permanent namespace for published XML Web services. For additional information about XML namespaces, see the following World Wide Web Consortium (W3C) Web site:

 

There are also some good forum discussion on the topic.

The two forums discussion I found useful can be read here and here

The first one probably provides the best answer, written by Vipul Modi – MSFT

This web service is using http://tempuri.org/ as its default namespace.

Recommendation: Change the default namespace before the XML Web service is made public.

Each XML Web service needs a unique namespace in order for client applications to distinguish it from other services on the Web. http://tempuri.org/ is available for XML Web services that are under development, but published XML Web services should use a more permanent namespace.

Your XML Web service should be identified by a namespace that you control. For example, you can use your company’s Internet domain name as part of the namespace. Although many XML Web service namespaces look like URLs, they need not point to actual resources on the Web. (XML Web service namespaces are URIs.)

For XML Web services creating using ASP.NET, the default namespace can be changed using the WebService attribute’s Namespace property. The WebService attribute is an attribute applied to the class that contains the XML Web service methods. Below is a code example that sets the namespace to “http://microsoft.com/webservices/”:

C#

[WebService(Namespace="http://microsoft.com/webservices/")]
public class MyWebService {
    // implementation
}
- Vipul Modi - MSFT

removing newline and other special characters from a string

If you are a regular follower of my blog you will have no doubt worked out I am doing some development over the last week and have been wrestling with various problems.

Today I found one of my columns had special characters such as Newline, carrage return etc and I wanted to remove them.  In the end I had to make this function and it did the job just fine.  I’m sure I have come across this problem before and I thought I had a better solution but searching on google and I couldn’t find anything.

 

   public static string ReplaceNewlines(string blockOfText, string replaceWith)
        {
            return blockOfText.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith).Replace("\t", replaceWith);
        }

How to convert an SQL statement into a XML file

Today I found some functionality which I thought was amazing and will save me loads of time creating some sample XML files to test my webservice with.

I had some sample data in database which I wanted to convert into an XML file.

My original idea was to use excel to concatenate bits of it but this turned out to be to slow and difficult.  I then found out that SQL Server has in built functionality to convert sql statements into XML files.

This article goes through some of the functionality and I would also read this article if you want more detail than my example below

below is my select statement, the important part is at the end
FOR XML AUTO,ELEMENTS
this converts the sql statement into XML elements
  
SELECT
      [Code]"Code"
      ,[Name]"Name"
      ,[Commission %]"Commission"
      ,[E-Mail]"Email"
      ,[Phone No_]"Phone"
      ,[Job Title]"JobTitle"
  FROM [database].[dbo].[Salesperson_Purchaser]salesperson
  FOR XML AUTO,ELEMENTS

this is the result, amazing.  I can't believe I have never heard of this fantastic 
feature before

<salesperson>
  <Code>MT</Code>
  <Name>Metaphorix</Name>
  <Commission>0.00000000000000000000</Commission>
  <Email>metaphorix@metaphorix.co.uk</Email>
  <Phone></Phone>
  <JobTitle></JobTitle>
</salesperson>
<salesperson>
  <Code>TS</Code>
  <Name>tom scott</Name>
  <Commission>0.00000000000000000000</Commission>
  <Email>tom.email.co.uk</Email>
  <Phone></Phone>
  <JobTitle></JobTitle>
</salesperson>
<salesperson>
  <Code>DR</Code>
  <Name>Jerry time</Name>
  <Commission>0.00000000000000000000</Commission>
  <Email></Email>
  <Phone></Phone>
  <JobTitle></JobTitle>
</salesperson>