Access to the path is denied in SPDiag 3.0 connecting remotely to SP 2013

While trying to create a new project in the Microsoft SharePoint Diagnostic Studio 2010 (SPDiag version 3.0) at some point I got the error below:

Access to the path '\\mySharePointServer\C$\Users\SPAccount\AppData\Local\Temp' is denied.

For anyone encountering the same issue, please see the scenario details below and the solution that worked in my case.

The Configuration

- remote connection to a SharePoint 2013 farm
– PowerShell remoting configured on my computer, acting as client
– PowerShell remoting configured on the SharePoint server
– account used for the connection (SPAccount) is a Farm Administrator

The Problem

Created a new project

Create a new project

Provided credentials

Providing credentials

Waiting for the configuration steps

First step

At the step above, got the error:

Access to the path '\\mySharePointServer\C$\Users\SPAccount\AppData\Local\Temp' is denied.

The Solution

In my case, the solution was to add the credentials for the SPAccount to the Windows Vault.

Credential Manager

Adding the credential

Entering credentials

Credentials added

 

Credentials

After the steps above, I retried to create the project and everything went smooth.

 

Posted in 2013, PowerShell, SharePoint | Tagged , , , | Leave a comment

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