Synchronizing attachments between two items in separate lists

When synchronizing the attachments between two items in separate lists by using the asynchronous event handlers ItemAttachmentAdded or ItemAttachmentDeleted, make sure that you use the lock statement. Otherwise, you might get unexpected results (because these events are triggered individually for each attachment, on separate threads).

Here’s an example:

    static object _locker = new object();

    public override void ItemAttachmentAdded(SPItemEventProperties properties)
    {
        lock (_locker)
        {
            base.ItemAttachmentAdded(properties);
            var currentItem = properties.ListItem;
            var otherItemId = Convert.ToInt32(currentItem[Constants.OtherIdFieldName].ToString());
            var oWeb = (SPWeb)properties.Web;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite oSite = new SPSite(oWeb.Url))
                {
                    using (SPWeb oWebContext = oSite.OpenWeb())
                    {
                        var otherList = oWebContext.Lists[Constants.OtherListName];
                        var otherItem = otherList.GetItemById(otherItemId);
                        var source = properties.WebUrl + "/" + properties.AfterUrl;
                        var fileName = System.IO.Path.GetFileName(properties.AfterUrl);
                        var attachments = otherItem.Attachments;
                        var file = currentItem.ParentList.ParentWeb.GetFile(source);
                        byte[] imageData = file.OpenBinary();
                        otherItem.Attachments.Add(fileName, imageData);

                        using (var disabler = new DisabledEventFiringScope())
                        {
                            otherItem.Update();
                        }
                    }
                }
            });
        }
    }

DisabledEventFiringScope is a helper class used for disabling the event firing.

class DisabledEventFiringScope : SPEventReceiverBase, IDisposable
{
    public DisabledEventFiringScope()
    {
        EventFiringEnabled = false;
    }

    public void Dispose()
    {
        EventFiringEnabled = true;
    }
}
Posted in 2013, Programming, SharePoint | Tagged , , , | Leave a comment

Validate the brazilian CPF by using LINQ

For anybody looking for an alternative implementation by using LINQ to validate the brazilian CPF (Cadastro de Pessoas Físicas) ID, here it is:

using System;
using System.Collections.Generic;
using System.Linq;

namespace Validators.Brazil
{
    public static class Cpf
    {
        public static bool Validate(string input)
        {
            if (input.Length != 11)
                return false;
            var cpf = input.Select(c => Int32.Parse(c.ToString())).ToList();
            var m1 = cpf.Take(9)
                .Select((e, i) => e * (11 - (i + 1))).Sum() % 11;
            if (cpf[9] != ((m1 == 0 || m1 == 1) ? 0 : 11 - m1))
                return false;
            var m2 = cpf.Take(10)
                .Select((e, i) => e * (11 - i)).Sum() % 11;
            if (cpf[10] != ((m2 == 0 || m2 == 1) ? 0 : 11 - m2))
                return false;
            return true;
        }
    }
}
Posted in Algorithm, C#, LINQ, Programming, Validation | Tagged , , , | Leave a comment

Making a dynamic JSLink URL from Visual Studio

As a developer, I consider the JSLink property of the SharePoint’s classes as being one of it’s coolest features. In order to make sure that you get what I mean and see some good examples about it’s usage capabilities, take a look at Martin Hatch’s excellent overview over JSLink.

But with all the recent popularity that client-side rendering is gaining, probably there are quite a few developers out there that have already faced the problem of JavaScript and CSS files caching in SharePoint (explained generically, for example, by Chris O’Brien in Avoiding bugs from cached JavaScript and CSS files in SharePoint) when deploying their solutions from Visual Studio.

Basically, as you modify the JavaScript files and deploy your solution, the already cached JS files are being served in the browser until the next IIS recycling. The only way to prevent that is to add some dynamic parameter to URL in the JSLink property with each deployment. Let’s take as an example a List template’s Schema.xml file where you’ll have to change this:

JSLink="~site/siteassets/myScript.js"

into this:

JSLink="~site/siteassets/myScript.js?v=20130925"

So, you have to increase the v=20130925 parameter’s value with each deployment. But that means that you have to actually modify the Schema.xml file on each deployment. And when working with JSLink, probably you’ll have to do that quite often. Not for the faint-hearted.

The solution I’ve come up with is very simple and it involves using the Visual Studio’s $SharePoint.Project.AssemblyFullName$ token.

First, modify your AssemblyInfo.cs file so that Visual Studio generates the Build and Revision Numbers for your assembly’s version:

[assembly: AssemblyVersion("1.0.*")]

Second, modify your JSLink attributes in the Schema.xml file like this:

JSLink="~site/siteassets/myScript.js?v=$SharePoint.Project.AssemblyFullName$"

That’s it.

From now on, on each deployment, the JS files’ URLs will contain as a parameter the assembly’s full name, which includes a unique / auto-incremented Version. So you’re good to test and debug your latest JS modifications.

Posted in SharePoint, Tips | Tagged , , , , | Leave a comment

Performance issues with SharePoint 2013 debugging

If you encounter major performance hits (CPU and memory load) when you are developing a SharePoint 2013 solution and you try to debug it, one of the causes could be the SharePoint Search Host Controller service. The issue occurred not only when actually debugging, but also when simply attaching/detaching to the W3WP.exe IIS worker processes.

Recently, I had this sort of problems on a pretty decent developer box with 2 CPUs, 16 GB of RAM and with the SQL server database on a different server. The task manager showed me multiple suspicious process instances for NodeRunner.exe. Firstly, I managed to reduce the memory usage by following the workaround addressed also by Cameron Dwyer:

Fix Memory Leak in SharePoint 2013 Preview (Microsoft Office 2013 Component / NodeRunner.exe)

But still, that was not enough for me, as the CPU was being used almost exclusively by the NodeRunner.exe processes. I chose to completely stop the service and set it’s Startup Type to Manual:

Search Host Controller

So, if you also have this problem and given the fact that you aren’t working on some feature that has a dependency on the search service, my recommendation for you is to simply stop the SharePoint Search Host Controller service.

Posted in Programming, SharePoint, Tips | Tagged , , , , , | 1 Comment

Find duplicate keys in two .resx files

While looking for an answer for a Stack Overflow question, I’ve created a method which finds duplicate keys in two .resx files. In order to use it, you need to add a reference to the System.Windows.Forms assembly, as the ResXResourceReader class resides inside it.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Resources;

class ResxComparer
{
    public static IEnumerable<Tuple<string, string, string>>
        GetConflicts(string path1, string path2)
    {
        try
        {
            using (var r1 = new ResXResourceReader(path1))
            using (var r2 = new ResXResourceReader(path2))
            {
                var r = (from re1 in r1.Cast<DictionaryEntry>()
                         join re2 in r2.Cast<DictionaryEntry>()
                             on re1.Key equals re2.Key
                         select new Tuple<string, string, string>(
                             re1.Key.ToString(),
                             re1.Value.ToString(),
                             re2.Value.ToString())).ToList();

                return r;
            }
        }
        catch (ArgumentException ex)
        {
            throw new Exception("Invalid .resx file", ex);
        }
        catch (Exception)
        {
            throw;
        }
    }
}

It’s sample usage in a console application could be:

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        if (args.Length != 2)
        {
            Console.WriteLine("Wrong number of arguments.");
            return;
        }
        if (!File.Exists(args[0]))
        {
            Console.WriteLine("The first path is not a valid file path.");
            return;
        }
        if (!File.Exists(args[1]))
        {
            Console.WriteLine("The second path is not a valid file path.");
            return;
        }

        var path1 = args[0];
        var path2 = args[1];
        
        try
        {
            var result = ResxComparer.GetConflicts(path1, path2);
            foreach (var item in result)
            {
                Console.Write("Key with name \"{0}\" is present in ",
                    item.Item1);
                Console.WriteLine("both files (\"{0}\" and \"{1}\")",
                    item.Item2, item.Item3);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}
Posted in C#, Programming, Tips | Tagged , , , , , , , , , , , | Leave a comment

Create a new Outlook email message by using a keyboard shortcut

Today I’ve been Googling for a quick way to create a new Outlook email message just by using the keyboard, even if the Outlook window is not active. So I’ve bumped into Aaron Lerch’s post TIP: Create a “new mail” shortcut for Outlook. It seems like a nice way to achieve the goal so I considered that a step by step instruction set would help some keyboard shortcut freaks out there :) Here it is:

1. Create a new shortcut on your desktop
2. Set the target of the shortcut to

"Path_to_your_OUTLOOK.exe" /c "IPM.Note"

For example, on my system:

"C:\Program Files (x86)\Microsoft Office\Office14\OUTLOOK.EXE" /c "IPM.Note"

3. Pin the shortcut to the taskbar (optionally, delete the shortcut from your desktop)
4. Drag the taskbar shortcut in front of all other shortcuts
5. Pressing the Windows key and 1 at the same time, Win + 1, will open a new Outlook email

Note: I’m using Windows 7 and MS Office Professional Plus 2010.

Posted in Tips | Tagged , , , , | 3 Comments

SharePoint 2013 Custom Field Type vs. Aggregation vs. XSLT list view vs. JSLink

Introduction

I created a solution for SharePoint 2013 that contained a custom field type inheriting from SPFieldText. I added the XML definition for it:

XML definition for the custom field type

XML definition for the custom field type

I also added the XSL rendering template:

XSLT list view

XSLT list view

After I deployed the solution, added the field to a list and inserted a few items, the view looked like this:

Successful XSLT rendering

Successful XSLT rendering

The problem

Now, the problem I am facing is that if I would like to modify the view and use the custom field type for grouping or aggregation (Count), the rendering of the list view would look like this:

Rendering problem for custom field type

Rendering problem for custom field type

Actually, the problem with grouping and aggregation exists even if there is no custom XSLT list view template for rendering, but I added it for emphasizing purposes. You can see that the Count row for the Title column looks as expected, but for Test Custom Field Type, i.e. my CustomFieldType column, it shows Count = First Item Value, which is the value from the first row in the list view of items for that column.

I tried to find, firstly, a match for the XSLT template that would allow me to process only the aggregations row. This was unsuccessful. After many hours of googling, I still couldn’t find anything related to this issue. Then, by chance, I observed something in SharePoint Designer, when taking a look at the list view’s definition:

View definition

View definition

I already knew that main.xsl, in conjunction with the fldtypes_xxx.xsl from the %PROGRAMFILES%\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\LAYOUTS\XSL folder were being used to render the list view. But only now it occurred to me that a JavaScript file could be specified to be responsible for the rendering logic.

Of course, this was the list view and I wanted to check if there was a way to specify a custom JS file to be used only for my custom field type. Then, I found out that that actually, there is such a overridable SPField.JSLink property which allows you to specify a string pointing to a custom JavaScript file.

All right! The next step for me was to try to understand what was happening inside the clienttemplates.js file. So, I made a copy of that file, named it clienttemplates_CustomFieldType.js and I added it to my solution, in the Layouts SharePoint mapped folder. I just added a debugger inside the RenderAggregate function, which seemed to be the place where all the magic took place:

RenderAggregate function inside the clienttemplates_CustomFieldType.js

RenderAggregate function inside the clienttemplates_CustomFieldType.js

I jumped in the code again and overridden the JSLink property:

JSLink property override

JSLink property override

I deployed again, I applied grouping and counting on the custom field type and the result was as depicted below:

Successful grouping and aggregation on a custom field type

Successful grouping and aggregation on a custom field type

Conclusion

(at least, a temporary one)

Both grouping and aggregation seem to work just fine! I’m not sure how this happened, but the simple overriding of the JSLink property had the following effects:

  1. The grouping and the aggregation on a custom filed type are working
  2. The XSLT list view template does not apply, since the light green background disappeared from the list view
  3. The Display form for the item is has a faulty rendering:
    Display form rendering error

    Display form rendering error

    I managed to fix this by evaluating the ((CustomFieldTypeFieldControl)this.FieldRenderingControl).ControlMode inside a try{...}catch{...} statement:

    Fixed JSLink property override

    Fixed JSLink property override

I have also successfully tried this solution for a custom field type which inherits from the SPFieldLookup class. I will keep you updated with the overall progress and the unsolved points and, at the same time, I’m waiting for any suggestions from your side on this challenging issue.

Posted in SharePoint | Tagged , , , , , , , | 1 Comment