I needed to remove the content editor dropdown you sometimes see in the form.
The most efficient way to do this is to add een Content Editor WebPart to the form of your list.
This way you could also add any javascript to your edit form, or other things to your page.

Here is the code:

SPList list = web.Lists[LIST_NAME];
string EditFormURL = list.DefaultEditFormUrl;

web.AllowUnsafeUpdates = true;

SPFile file = web.GetFile(EditFormURL);

if (null != file)
{
      using (SPLimitedWebPartManager mgr = file.GetLimitedWebPartManagerPersonalizationScope.Shared))
{
if (null != mgr)
{
//create new webpart object
ContentEditorWebPart contentEditor = new ContentEditorWebPart();
//Add content to CEWP
XmlDocument xmlDoc = new XmlDocument();
XmlElement xmlElement = xmlDoc.CreateElement(“Root”);
xmlElement.InnerText = GetValidationScript().ToString();
contentEditor.Content = xmlElement;contentEditor.Content.InnerText = xmlElement.InnerText;

//Add it to the zone
mgr.AddWebPart(contentEditor, “0”, 0);
web.Update();

}
}
}
}

private StringBuilder GetValidationScript()
{

StringBuilder sbScript = new StringBuilder();
string sJQueryURL = “_layouts/JQuery.js”;//exact path of your js file
sbScript.Append(“<script src='” + sJQueryURL + “‘type=’text/javascript’></script>”);
sbScript.Append(“<script type=’text/javascript’>”);
sbScript.Append(“$(document).ready(function() { “);
sbScript.Append(@” $(‘select[id*=””ContentTypeChoice””]’).parent().parent().hide();”);
sbScript.Append(“}); “);
sbScript.Append(“</script>”);
return sbScript;

}

 

 

 

For one of my customers I needed a top navigation which was the the same acccross their different
sitecollections, and offcourse security trimmed.
The top navigation will look like this:

Afbeelding

So in this post I’m explaining the following :

  • create a custom security trimmed sitemap provider
  • deploying a masterpage accross all sitecollections
  • modifying the web.config
  • activating the masterpage acccross the whole site collection

The solution will look like this:

Afbeelding

To create a custom sitemapprovider a created a sitemap file.
Just add an xml file and rename it:

<siteMap>
<siteMapNodetitle=Containerurl=“”>
<siteMapNodetitle=Global Portaldescription=“”url=//>
<siteMapNodetitle=Test 002description=“”url=~/Test 002>
<siteMapNodetitle=test 001url=~/sites/test 002/001description=“”/>
<siteMapNodetitle=test 002url=~/sites/test 002/002description=“”/>
<siteMapNodetitle=test 003url=~/sites/test 002/003description=“”/>
</siteMapNode>
<siteMapNodetitle=Teamdescription=“”url=~/team/>
<siteMapNodetitle=Information Technologydescription=“”url=~/it/>
<siteMapNodetitle=Legaldescription=“”url=~/legal/>
<siteMapNodetitle=Regionsdescription=“”url=“”>
<siteMapNodetitle=North Americaurl=~/regions/NAdescription=“”/>
<siteMapNodetitle=Middle Easturl=~/regions/medescription=“”/>
</siteMapNode>
</siteMapNode>
</siteMap>

The next step is to tell SharePoint that this provider exists, therefore we need to change the web.config file.
We could do this manually but if you have a large farm mmmm….
I created a feature with a receiver that does the work form:

using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Administration;namespace MUAC.SiteMapProvider.Features.MUAC.SiteMapProvider
{
[Guid(“0b9032da-7c51-48da-8c4b-9635d307a31a”)]
public class MUACEventReceiver : SPFeatureReceiver
{
// Uncomment the method below to handle the event raised after a feature has been activated.

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
try
{
SPWebApplication webApp = (SPWebApplication)properties.Feature.Parent;
webConfigMod(true, webApp);
}
catch (Exception exception)
{

}
}

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
SPWebApplication webApp = (SPWebApplication)properties.Feature.Parent;
UnInstallMasterPage(webApp);
webConfigMod(false, webApp);
}

private void webConfigMod(bool setting, SPWebApplication webApp)
{
try
{

#region Muac Custom Navigator

SPWebConfigModification setting_CustomNavigator = new SPWebConfigModification();
setting_CustomNavigator.Path = “configuration/system.web/siteMap/providers”;
setting_CustomNavigator.Name = “add[@name=’MUAC_CustomNavigator’]”;
setting_CustomNavigator.Sequence = 0;
setting_CustomNavigator.Owner = “MUAC_CustomNavigator”;
setting_CustomNavigator.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
setting_CustomNavigator.Value = @”<add name=””MUAC_CustomNavigator”” siteMapFile=””_layouts/MUAC.sitemap”” type=””MUAC.SiteMapProvider.CustomNavigator, MUAC.SiteMapProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=02fc9494e4423234″” securityTrimmingEnabled=””true”” />”;

#endregion

if (setting)
webApp.WebConfigModifications.Add(setting_CustomNavigator);
else
RemoveProperty(webApp, setting_CustomNavigator, “MUAC_CustomNavigator”);

webApp.WebService.ApplyWebConfigModifications();
webApp.Update();
}
catch (Exception exception)
{

throw;
}
}

In the code I created a method to add or delete a setting from the web.config.
When you activate your feature your web.config will look like this:

<siteMapdefaultProvider=CurrentNavigationenabled=true>
<providers>

<addname=MUAC_CustomNavigatorsiteMapFile=_layouts/MUAC.sitemaptype=MUAC.SiteMapProvider.CustomNavigator, MUAC.SiteMapProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=02fc9494e4423234securityTrimmingEnabled=true />
</providers>
</siteMap>

Dont mind the type property yet, we will get back on this later.
The last thing to do is to modify your masterpage.
I downloaded a version of the v4.master, renamed it and then did the changes on the copy, which is in my case ‘MUAC.master’

You need to search in the masterpage for the ‘SharePoint:AspMenu’.
Right before this control you need to place the following line:

<asp:SiteMapDataSource ShowStartingNode=”False” SiteMapProvider=”MUACNavigationProvider” id=”MUACNavigationProvider” runat=”server”/>

and then you need to modify the ‘SharePoint:AspMenu’ control itself so it looks like this:

<asp:SiteMapDataSource ShowStartingNode=”False” SiteMapProvider=”MUACNavigationProvider” id=”MUACNavigationProvider” runat=”server”/>
<SharePoint:AspMenu
ID=”TopNavigationMenuV4″
Runat=”server”
EnableViewState=”false”
DataSourceID=”MUACNavigationProvider”
AccessKey=”<%$Resources:wss,navigation_accesskey%>
UseSimpleRendering=”true”
UseSeparateCss=”false”
Orientation=”Horizontal”
StaticDisplayLevels=”1″
MaximumDynamicDisplayLevels=”3″
SkipLinkText=””
CssClass=”s4-tn”/>

You need to change the DataSourceId to the one you just added to your masterpage.
Also change the ‘MaximumDynamicDisplayLevels’ else you will not have submenu’s.
I you now save , publish… this master page in to your SharePoint and deploy this feature you will have your menu.

But you need to manually change your masterpage on all sites … , activate the publishing features on all sites…, deploy your masterpage…
This should be done automaticilly!
So we add a new feature site scoped, this feature will only deploy the masterpage.
To do so we need to add a new module to our solution I called it ‘MasterPage’.

Afbeelding

Remove the sample file and add your masterpage (MUAC.master) to your module.
(Right Click add existing file and then search for your altered masterpage)
Open the the ‘Element.xml’ file and modify it so it looks like this:

<Elementsxmlns=http://schemas.microsoft.com/sharepoint/>
<ModuleName=MasterPagesPath=MasterPageRootWebOnly=TRUEUrl=_catalogs/masterpage>
<FileUrl=MUAC.masterType=GhostableInLibraryIgnoreIfAlreadyExists=TRUE >
</File>
</Module>
</Elements>

This module is just deploying the masterpage.
To do so we add a new feature because this cannot be combined with our first feature because that one is not site scoped but webapplication scoped.
The feature looks like this:
Afbeelding

We have now 2 features:

  • To deploy our custom sitemap
  • To deploy the masterpage

Next we want that the masterpage is automaticilly set so we do not have to change every sitecollection manually.
In ourr first feature I added 2 extra methods:

private void InstallMasterPage(SPWebApplication webApp)
{
foreach (SPSite site in webApp.Sites)
{
SPWeb topLevelSite = site.RootWeb;           // Calculate relative path to site from Web Application root.
string webAppRelativePath = topLevelSite.ServerRelativeUrl;
if (!webAppRelativePath.EndsWith(“/”))
webAppRelativePath += “/”;

// Activate publishing infrastructure
site.Features.Add(new Guid(“f6924d36-2fa8-4f0b-b16d-06b7250180fa”), true);

try
{
site.Features.Add(new Guid(“9e9d8436-3a78-4abd-a9d1-d49707ea2116”), true);
}
catch (Exception ex)
{
throw;
}

// Enumerate through each site and apply branding.
foreach (SPWeb web in site.AllWebs)
{
// Activate the publishing feature for all webs.
web.Features.Add(new Guid(“94c94ca6-b32f-4da9-a9e3-1f3d343d7ecb”), true);
web.MasterUrl = webAppRelativePath + “_catalogs/masterpage/MUAC.master”;
web.CustomMasterUrl = webAppRelativePath + “_catalogs/masterpage/MUAC.master”;

web.Update();
}
}
}

private void UnInstallMasterPage(SPWebApplication webApp)
{
try
{
foreach (SPSite site in webApp.Sites)
{
SPWeb topLevelSite = site.RootWeb;

// Calculate relative path to site from Web Application root.
string webAppRelativePath = topLevelSite.ServerRelativeUrl;
if (!webAppRelativePath.EndsWith(“/”))
webAppRelativePath += “/”;

site.Features.Add(new Guid(“9e9d8436-3a78-4abd-a9d1-d49707ea2116”), true);

// Enumerate through each site and apply branding.
foreach (SPWeb subSite in site.AllWebs)
{
subSite.MasterUrl = webAppRelativePath + “_catalogs/masterpage/v4.master”;
subSite.CustomMasterUrl = webAppRelativePath + “_catalogs/masterpage/v4.master”;
subSite.SiteLogoUrl = string.Empty;
subSite.Update();
}
}
}
catch (Exception ex)
{

throw;
}
}

Add ‘InstallMasterPage ‘ in the feature activated and the ‘UnInstallMasterPage’ in the deactivation method.
So this will activate the feature that contains the masterpage if it is their, also activate the publishing features on every site and subsite.
And next it will set the masterpage, when you deactivate it will reverse the settings again.
It just loops through all sitecollections and changes the propery of the masterpage.

try
{
site.Features.Add(new Guid(“9e9d8436-3a78-4abd-a9d1-d49707ea2116”), true);
}
catch (Exception ex)
{
throw;
}

This piece will acctivate our other feature that holds the masterpage, your guid will properbly be different.
You can find it in the properties of the feature, the one that contains the masterpage.
So everything is almost finished, but to make sure our topnavigation bar is security trimmed we need to create our custom Navigator class,
which has a propery called ‘IsAccessibleToUser’ which we can override:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Navigation;
using System.Web;
using System.Xml;namespace MUAC.SiteMapProvider
{
public class CustomNavigator :XmlSiteMapProvider// SPXmlContentMapProvider
{
public override bool IsAccessibleToUser(HttpContext context, SiteMapNode node)
{
try
{
if (node == null)
{
throw new ArgumentNullException(“node”);
}
if (context == null)
{
throw new ArgumentNullException(“context”);
}
if (!base.SecurityTrimmingEnabled)
{
return true;
}
if (string.IsNullOrEmpty(node.Url))
{
return this.IsGranted(context, node.ChildNodes);
}
return this.IsGranted(context, node);
}
catch
{
return false;
}
}

private bool IsGranted(HttpContext context, SiteMapNode node)
{
bool isGranted = false;
SPSecurity.RunWithElevatedPrivileges(delegate
{
using (SPWeb web = new SPSite(SPContext.Current.Site.MakeFullUrl(node.Url)).OpenWeb())
{
SPUser user = web.AllUsers[context.User.Identity.Name];
if (user != null)
{
try
{
if ((node.Roles != null) && (node.Roles.Count > 0))
{
foreach (string str in node.Roles)
{
isGranted = (str == “*”) || (user.Groups[str] != null);
if (isGranted)
{
break;
}
}
}

isGranted = web.DoesUserHavePermissions(user.LoginName, SPBasePermissions.EmptyMask | SPBasePermissions.ViewPages);
}
catch
{
}
}
}
});

return isGranted;
}

private bool IsGranted(HttpContext context, SiteMapNodeCollection childNodes)
{
bool flag = false;
foreach (SiteMapNode node in childNodes)
{
flag = this.IsGranted(context, node);
if (flag)
{
return flag;
}
this.IsGranted(context, node.ChildNodes);
}
return false;
}
}
}

The code is not hard to understand so I’m not going to explain eveything.
But let’s look add the code of our first feature again where we added a provider into the web.config.
This provider needs to referr to this class and asssembly because we created our own Navigator.
The type property needs to referr to our class !!!

  <add name="MUAC_CustomNavigator" siteMapFile="_layouts/MUAC.sitemap"
 type="MUAC.SiteMapProvider.CustomNavigator, MUAC.SiteMapProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=02fc9494e4423234" securityTrimmingEnabled="true" />

When you now debug it should your class and checking if the user has access or not.

So that actually it, if you have questions or remarks let me know…

If you have a webpart or a custom form where you use the SharePoint peoplepicker you have to fetch the values of the control to place them into SharePoint.
This is how you do this.

1

 

2

When I press the save button on my form this code I need to use:

string[] userarray = ppTechnicalManager.CommaSeparatedAccounts.ToString().Split(‘,’);
SPFieldUserValueCollection usercollection = new SPFieldUserValueCollection();
for (int i = 0; i < userarray.Length; i++)
usercollection.Add(ConvertLoginAccount(userarray[i]));
item [“Technical Manager”]= usercollection;      
public SPFieldUserValue ConvertLoginAccount(string userid)
{
SPFieldUserValue uservalue;
SPSite site = new SPSite(SPContext.Current.Site.Url);
SPWeb web = site.OpenWeb();
SPUser requireduser = web.EnsureUser(userid);
uservalue = new SPFieldUserValue(web, requireduser.ID, requireduser.LoginName);
return uservalue;
}

And now the values will be saved into your list.

If you wwant to retrieve those values from your listitem again and display this into you control:

SPFieldUser userField = (SPFieldUser)list.Fields.GetField(Fields.TechnicalManager);
SPFieldUserValue fieldValue = (SPFieldUserValue)userField.GetFieldValue(item[Fields.TechnicalManager].CheckForNull());
ArrayList entityArrayList = new ArrayList();
PickerEntity entity = new PickerEntity();
if (fieldValue.User != null)
{
SPUser user = fieldValue.User;
entity.Key = user.LoginName.ToString();
}
else
{
SPGroup group = SPContext.Current.Web.Groups[fieldValue.LookupValue];
entity.Key = group.LoginName.ToString();
}
entityArrayList.Add(entity);
ppTechnicalManager.UpdateEntities(entityArrayList);

This checks for groups and users.

Hope this helps

Most often you want your customsolution to be deployed to only a specific webapplication but SharePoint won’t allow it.

It’s actually very easy to fix this by tricking SharePoint.

2014-03-03_8-08-06.2png

In your package manifest you add a safe control:

<Solution xmlns=”http://schemas.microsoft.com/sharepoint/”&gt;
<Assemblies>
<Assembly Location=”dll_name_of_your_solution.dll” DeploymentTarget=”GlobalAssemblyCache”>
<SafeControls>
             <SafeControl Assembly=”dll_name_of_your_solution,Version=1.0.0.0,Culture=neutral, PublicKeyToken=****************” Namespace=”namespace_of_your_solution” TypeName=”*” />
</SafeControls>
</Assembly>
</Assemblies></Solution>

2014-03-03_8-07-02

Most of you have already worked with jQuery, if you have not shame on you.
I have worked with jQuery a lot the past years, client site scripting gives you more flexibility towards your customers.
The way you can manipulate the DOM is just great.

Many people find it hard to start with jQuery, the first step of the process is to get your jQuery into SharePoint.
There are several ways of doing this which I’ll be explaining to you in this post.

First we have to download jQuery  here. Just save it somewhere so that you know were it is.

The ways that I know to import jQuery into SharePoint are the following:

  • Put a reference into your MasterPage
  • Put a reference in your webpart or your layouts page
  • Load it programmatic
  • Through the content editor webpart
  • With a feature

1. Put a reference to Jquery

You can tell your webpart, layouts page and master page to load the script directly.
Keep in mind if you do this in the MasterPage then everywhere in your SharePoint the jQuery is loaded.

This technique is the most simple of loading the jQuery.
You have to open SharePoint designer for this, and open the site where you want to place the jQuery.

Next thing you have to select ‘all files’ and then catalog.

Jquery SPS 001

Next you have to select your MasterPage en select ‘Edit file in advanced Mode’

Jquery SPS 002

Next you will see the HTML and stuff of your MasterPage , there we can place a link to the jQuery file.
We can link directly to the jQuery site

Jquery SPS 004

or to our local JQuery file , stored somewhere in the layouts folder of SharePoint in this case

Jsurty local file system  master page linked to layouts folder

Next you just save and publish the masterpage and your are done.

And how do I know that it worked ????
If you open your IE explorer en type F12 which will open the development tools of IE, you’ll see a tab called scripts.

Jquery SPS script loaded from LAyouts folder

Jquery SPS script loaded with direct link

Told you it was simple.
This technique can be repeated for a VisualWebPart or a Layouts page.
I’m not gonna show because it is just copying the same script tags
2. Load the script programmatic

Personally I prefer this way.
Why?
It’s easy, it’s faster, no SharePoint designer, Visual Studio and so on

When you’re using jQuery you are going to develop something, so you’ll be using VS anyway.
So you can deploy the jQuery along with your solution.
I’m just gonna create a very simple webpart to demonstrate.
My Visual Studio project looks like this:

vs 001

I added a link to the SharePoint Layouts/1033 folder in my Visual Studio, then I added the jQuery file which I downloaded earlier in this folder in Visual Studio.
The reason I placed it there is because SharePoint also put it’s JavaScript files there.
Now let’s add this thing into our WebPart, but lets test this.
Lets create a simple “HelloWorld.js” that throws an alert when the page is loaded, and put this also in the 1033 folder.

vs 003

Then you deploy the webpart and add it to your page, now every time the page is loaded it will throw an alert.

vs 004

Using this techniques you do not have to open SharePoint designer every time you have to add a jQuery file.
To my point of view this techniques gives you way more flexibility.

3. Content Editor WebPart

This is the most simple technique there is.
Just edit the page add add a CEW.

Edit the webpart and just add this in the text:

// <![CDATA[
javascript” src=”http://code.jquery.com/jquery-1.11.0.min.js”&gt;
// ]]>

CEW

Click ‘ok’ and you are done.
I find this more unprofessional but it would do the trick, but there are risks to it.

4. Using a feature

This is also a very simple technique to load the general jQuery files into SharePoint.

Add to your solution a new Module.
Delete the txt file that comes with the Module, and change the content of the Element.xml file to look like this:

feature Jquery 001

In the screenshot you’ll see I have put the Module into a feature and that is it.
Go to your feature in SharePoint and activate

feature Jquery 002

You can test with the development tools to check if the feature is deactivated and deactivated.

Hope it helps.

Leave a comment

Cheers

Serveral times I had opened a project developed for SharePoint 2010 and I needed to make some changes for instance to make it work in Sharepoint 2013.

When you open it you will receive some problems regarding your dll references, what the hell ???

The solution for this is to make some changes in the xxx.proj file.

I was able to get my solution upgraded from a 2010 project to 2013 using the following.

Note that this will update your solution to use the new 2013 API.
First edit your .csproj file (for c#).

Modify the target framework to this:

<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>

Add this a node for the office version, I put mine directly below the TargetFrameworkVersion tag

<TargetOfficeVersion>15.0</TargetOfficeVersion>

Update references
Reload the project and update your referenced assemblies.
If you haven’t specified a specific version they should already be referencing the v15 (SharePoint 2013) assemblies.

Do a find replace for 14.0.0.0 to 15.0.0.0. This updates any references on your pages, layouts, and master pages to the v15 assemblies.

Hope it helps !