Write Clean Code with this one weird tip?!!?1?

You may have heard of, or heard lots about, the concept of “Clean Code”. At its heart is the concept of choosing your structure and syntax carefully, to ensure it is readable and maintainable by others. How many times have you cursed a predecessor for things like creating methods called “WhoAmI()” which returns a Boolean? Your code shouldn’t trick people into believing it has a purpose, other than what is suggested by your choice of names and object structure.

Pluralsight has a really nice, and short, introduction to Clean Code, which I can thoroughly recommend.

When starting to work to Clean Code principles, it can be tricky to decide where to draw the line between concise and technically correct, and verbose and self-explanatory. Should every little thing be broken down into its own method? Exactly how long and explanatory should you make a variable name? It’s particularly difficult to switch to this new mind-set if you have come from university and you are new to commercial programming. Coding for your degree usually involves lots of one letter variable names.

One place where it can be difficult to decide on where to draw the clean code line, is chaining methods; such as is commonly done in jQuery.

So here’s my one weird tip: Read your code out loud, as a sentence.

Consider this jQuery:


Is this too much chaining? When reading this line out loud, it reads as:

“For the element called TextBox, set the value to nothing and add CSS class of “error”, then add the CSS class of error to its label too.”

I think most developers could understand that, it parses well. So how can we achieve too much chaining for it to be clean code?

$(‘#TextBox’).val(‘’).addClass(‘error’).(“label[for=’#TextBox’]”).addClass(‘error’).next().addClass(‘normal’).attr(‘checked’, true).show();

“For the element called TextBox, set the value to nothing and add CSS class of “error”, then add the CSS class of error to its label too, then get the next element and add a CSS class of “normal”, then make it checked, then show it.”

As a verbal or written instruction, this would probably be too much for a human to parse without them manually breaking it up anyway.

In C#, as with jQuery, you can also chain ordinary methods that return values and objects. Again, as with jQuery, only do so if it is easy for a human to parse.

But in C#, you also have the power of LINQ to chain queries. Here you will probably find that you are creating longer queries than you can comfortably speak as a sentence. It’s probably best to think of them as a set of bullet point instructions:

return words

    .Select(word => word.Trim())

    .Select(word => word.ToUpper())

    .Where(word => word.StartsWith(“A”))

    .OrderBy(word => word);

Get a list of words:

  • Remove trailing and proceeding spaces
  • Make them lower case
  • Get only the words that start with “k”
  • Order the words alphabetically
  • Return the result.

We are able to chain a little longer with LINQ, as all of the actions will be done on one collection, and subsequent actions on the result of the preceding action. It really helps here to put each new method on the new line, so it can be read as a list of actions. Carriage returns and white space can be your friend, just as paragraphs will make reading prose easier.

Application connecting to SP2007 – Unauthorised or “System.IO.FileNotFoundException”

This has caught me out at least twice, embarrassingly.

Running a little C# console application to transfer some files from SP2013 to SP2007 (as mentioned here previously). For some reason, I’m getting a file not found exception, which usually actually means unauthorised.

It runs perfectly on Dev. It runs on Live when connecting to Dev. It runs under my manager’s user account, but not our admin SharePoint 2013 account. The admin account has site collection admin permissions, etc. What gives?

The error is occurring when trying to access the items in a SP2007 list. Some Googling turned up the answer:

The user account that the application is running under must have specific permission to read/write to the content database!

I’m bolding that to never forget it. If that catches me out one more time, I’m getting it tattooed somewhere very visible.

Related article: https://support.microsoft.com/en-us/kb/935751


More useful SharePoint tips

More bits to stop me having to Google the same thing over and over again.

It’s very sweet that SharePoint Designer 2013 still suffers from the caching problem; making changes to a workflow and publishing them doesn’t actually mean they get published!

The two places to delete the files are:

  1. %USERPROFILE%\AppData\Local\Microsoft\WebsiteCache
  2. %APPDATA%\Microsoft\Web Server Extensions\Cache

Perhaps they’ll finally fix this in 2016? Maybe not. Don’t go changing SharePoint!

If you’re missing the All People link from SharePoint 2007 in a newer version, add this after the root site address:


I still come across the problem of people’s name changes causing issues with their profile in SharePoint if they are imported from AD.

Running a Powershell script as a scheduled task

It should have been simple. I have a Powershell script that works as it should, I just need it to run on the hour, every hour. So create a scheduled task, and attach the script. Do a run now, just to make sure it works.

And technically, it works. That’s what the result of the scheduled task says: Task Completed 0x0. But the actual Powershell script hasn’t been actioned.

Once again I confirmed that running the script by itself works. I wrap the code in the script in a Try/Catch with a log file. But nothing writes to the log file.

I googled and googled, and checked all the following things:

  • I globally set Set-ExecutionPolicy to Unrestricted.
  • I tried running the task under a local account with admin permissions, as someone mentioned that domain accounts can’t run scheduled tasks. That doesn’t appear to be the case.
  • I checked that my account has Log on as batch.
  • I added the run script command to a batch file, and called the batch file from scheduled tasks. Still didn’t work!

It turns out that even when setting the Set-ExecutionPolicy to Unrestricted, you still need to add the parameter -ExecutionPolicy ByPass. Just that one little thing. If you are asking an application to run a script for you, it needs to bypass execution policy.

So the correct config was:

Program/script: “Powershell” (should resolve correctly to powershell.exe)

Arguments: -ExecutionPolicy ByPass -File {script file with path}

Start in: {Path of folder that script sits in}

SharePoint and CSOM – Get an application running on SP2007 to access content and managed metadata on SP2013 using CSOM

Please don’t ask why, only know that it had to be done. The requirement was to copy documents in a library in SP2013 to another library in SP2007. This is made easier by using CSOM, but getting the right libraries can be a little tricky. I also needed to access managed metadata values, which SP2007 is like “meta-whata-now?” about.

I found that I needed to use the Microsoft.SharePoint.Client libraries from SP2010, as I was developing on the SP2007 dev box. This is because the 2013 DLLs require .NET 4.0, and 2007 uses 3.5.

So I had to:

  1. Create a new folder on your 2007 server/dev environment in C:Program FilesCommon Filesmicrosoft sharedWeb Server Extensions. You should already see a folder in there called “12”. Create a new one called “14”.
  2. In “14”, create another folder called “ISAPI”. This mirrors the folder structure of 2010. It’s not strictly necessary but it keeps things organised and clear.
  3. On your 2010 server (you have one, right? If not, you’ll need to find these from somewhere,) copy the client DLLs you’ll need. To do my task, I needed the following:
    1. Microsoft.SharePoint.Client
    2. Microsoft.SharePoint.Client.Runtime
    3. Microsoft.Office.Server
    4. Microsoft.SharePoint.Taxonomy
  4. If you find you need to use other libraries from 2010, add them to this same folder.
  5. In Visual Studio, add references in your project to the DLLs  in the new “14” folder.
  6. For the core Microsoft.SharePoint DLL, reference the DLL in the “12” folder.
  7. Keep to the DLLs in the 12 folder wherever possible.

That was the start of my fun crossing-the-streams adventure. I used the above to create a console app that scans given libraries by name, for tagged documents to “publish”, copying some of their managed metadata. I used a couple of good resources, which I’ll link to in the next post regarding this subject.

2008 SSRS Report from CRM 2011: Font with space in its name not rendering correctly

Google was truly not my friend for this one, so now I’ve hacked fixed it, I’m giving back in case anyone has the same issue.

I’ve been tasked with creating some pretty reports in SSRS 2008, which will run from CRM 2011. The company font I’ve been asked to use is Century Gothic.

I created the reports, which rendering perfectly in preview mode and when creating PDFs in SSRS. I then uploaded the reports to CRM, and ran it from its entity.

All instances of Century Gothic came out as Times New Roman. The same happened when exporting it to PDF. Century Gothic didn’t appear to be installed on the CRM report server, so I installed it on there and scheduled the server reboot overnight.

The next day, it was still Times New Roman, except for one textbox which had Century Gothic displayed correctly.

Looking under the hood with developer tools, I saw this:


I cracked open the code, but I couldn’t see any difference between the working correctly textbox, and the others, which had the split font name. I tried putting quotes, singe and double, round the font name in the code, but Visual Studio then couldn’t resolve the font name correctly itself.

I tried other fonts with two names, and got the same problem.

Looking at the working textbox, I saw that the textbox itself didn’t have a font set, only the selected text inside:

ssrs-crm-font-2 ssrs-crm-font-3

The broken textboxes had the font applied directly to it. Creating a new blank textbox automatically assigns a font to the box, which can’t be cleared.

So how to fix it? The working textbox had a bit of Arial text in it as well. So that gave me the idea to add a couple of spaces to the end of each Century Gothic textbox, and make one of those spaces Arial.

That cleared the Font property on the textbox, and then the Century Gothic font started displaying.

What a horrible, hacky fix 🙁

SharePoint and CSOM – Useful links

It’s been a busy couple of weeks, with my head down working on some SharePoint madness which will form at least a couple of articles to come. It involved getting SP2007 to talk to SP2013, by way of the SP2010 client dlls. It’s been as fun as it sounds

I’ve had to some serious Googling, which has generally been my friend . SO here is another list of links that I’ve found invaluable and will be returning to again and again.

Complete basic operations using SharePoint 2013 client library code

SharePoint 2010 – Using the Client Object Model (good CAML resources)

SharePoint 2010 – How to retrieve list items using the COM

CAML queries and the Client Object Model (this is a really excellent resource!)

Server 2003 needs hotfixes for SHA2 256 or higher encryption, or X.509 certificates

Are you still running Windows Server 2003? For shame!

Have you been keeping up with the hotfixes? Hmmm…

Well, you’re in good company. Forgetting for a moment that Microsoft ends support for Server 2003 on 16 July 2015, sometimes it’s easier to just let it keep running.

Beware what happened to us though. Our website stopped serving up a page in an iFrame from a secure site. We spoke to the company, who said the certificate had been updated and to just grab the new one. I had no problem on my local machine going directly to the page, but couldn’t do it via the website.

The company had updated their certificate to a version which our Server 2003 could no longer communicate with:

Windows Server 2003 and Windows XP clients cannot obtain certificates from a Windows Server 2008-based certification authority (CA) if the CA is configured to use SHA2 256 or higher encryption

Applications that use the Cryptography API cannot validate an X.509 certificate in Windows Server 2003

Not to mention that the server had IE6 on there. But thanks to Hotfixes and a swift restart, our 2003 Server machine lives to fight another day, until we finally put it out of its misery. Soon I hope.

Filtering by SharePoint repeating data in your InfoPath 2013 list item form

That was a tortuous post title! Another post to help me remember.

I created an InfoPath 2013 form to add a new list item. One of the fields was a lookup field using a column from another list.

The lookup field was a Person field, which in InfoPath looks like repeating data.

I needed the dropdown list to show values where there was nothing in this Person field. It took me a bit of messing about to get it right.

Filtering with repeating data

Filtering with repeating data

The trick is to filter on the group. In my instance, I needed to show all entries where there was nothing in the User field for that list item.

The logic required was “All occurrences of Person are blank”, on the List Item row.

Hope this helps someone…