Remove duplicate event receivers from site. SharePoint 2013

Use this if you want to remove all duplicate Event Receivers from all lists in a URL.

Add-PSSnapin Microsoft.SharePoint.Powershell
$spWeb = Get-SPWeb http://site
$SPListCollection = $spWeb.Lists;
foreach ($list in $SPListCollection)
{
$spList = $spWeb.Lists[$list.Title]
$eventReceivers = $spList.EventReceivers
if ($eventReceivers.Count -gt 1)
{
foreach ($er in $eventReceivers)
{
for ($i=0; $i -lt $eventReceivers.count; $i++)
{
if ($er.Assembly -eq $eventReceivers[$i].Assembly -and $er.Type -eq $eventReceivers[$i].Type -and $er.Name -eq $eventReceivers[$i].Name -and $er.Id -ne $eventReceivers[$i].Id)
{
#add delete code here
$eventReceivers[$i] | Select Name, Assembly, Type, id
}
}
}
}
}
$spWeb.dispose()

SharePoint 2013 – Unable to use JavaScript on page – Scripts do not show up in developer tools

I have been troubleshooting an issue that when you put a script on the page with a content editor or script web part, it does not execute and does not show up in the development tools in Chrome or IE. It was a mystery.

I ran across a blog that was talking about my issue. The problem is the page is redirecting to http://server/_layouts/15/start.aspx#/site/list. This is a minimal download page. If I went to http://server/site/list, the script works fine.

All you have to do is deactivate the site feature called “Minimal Download Strategy”.

Image

If you come across an article outlining how to use Content Editor and Script Web Parts with MDS enabled, please comment. 🙂

Select some text with no ID or Distinct Element

This finds some parent id up the DOM tree, then using contents and filter it finds text nodes (nodeType===3). Then for each text node you can replace the text with other text, or you could use jquery .wrap to wrap it in an element, ie. .wrap(“<div></div>”).

Another senario is when you want to select/change/modify some text but do not want to affect a child node.

$(document).ready(function(){
    $("#group0 a").contents().filter(function(){
        return this.nodeType === 3
    }).each(function(){
        this.textContent = this.textContent.replace('Text To Select', ''); 
           //(**I had to use nodeValue instead of textContent for IE8 compatibility)
    });
});

HTML for above example:

<tr id="group0">
    <td colspan="100" nowrap="" class="ms-gb">
        <a href="javascript:" onclick="javascript:ExpCollGroup('1404-1_', 'img_1404-1_',event, false);return false;">
			<img src="/_layouts/images/plus.gif" border="0" alt="expand" id="img_1404-1_">
		Text to select
		</a> : General&nbsp;<span style="font-weight: lighter;display: inline-block;">(5)</span>
	</td>
</tr>

Get ID of custom site template SharePoint 2013

Open SharePoint 2013 Management Shell as Administrator

Enter this:

$site = Get-SPSite http://blah.site.com > Press Enter

$loc = [System.Int64]::Parse(1033) >Press Enter

$site.GetWebTemplates($loc) | Select-Object -ExpandProperty Name > Press Enter

Your newly saved template should be at the bottom of the list. This ID can be used in custom code to create a new site programmatically.

Here is a JavaScript example…

var siteUrl = '/';

function createWebSite() {
    //alert("Project name: " + form1.projectname.value + " Project Description: " + form1.projectdescription.value);
    $('.project-form').append("<img id='spinner' src='http://projectbook.bluebunny.com/SiteAssets/ajax-loader.gif'/>")
    var projectDescription = form1.projectdescription.value;
    var projectLanguage = 1033;
    var projectTitle = form1.projectname.value;
    var projectUrl = form1.projectname.value;
    var projectPermissions = false;
    var webTemplate = '{DF4D4512-8BE6-43BF-B7FB-99BE4763923C}';

    var clientContext = new SP.ClientContext(siteUrl);
    this.oWebsite = clientContext.get_web();

    var webCreateInfo = new SP.WebCreationInformation();
    webCreateInfo.set_description(projectDescription);
    webCreateInfo.set_language(projectLanguage);
    webCreateInfo.set_title(projectTitle);
    webCreateInfo.set_url(projectUrl);
    webCreateInfo.set_useSamePermissionsAsParentSite(projectPermissions);
    webCreateInfo.set_webTemplate(webTemplate);

    this.oNewWebsite = this.oWebsite.get_webs().add(webCreateInfo);

    clientContext.load(this.oNewWebsite, 'ServerRelativeUrl', 'Created');

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));

}

function onQuerySucceeded(sender, args) {
    $('#spinner').hide();
    $(".project-form").empty();
    $(".project-form").append("Your site has been created");

    //alert('Title: ' + this.oWebsite.get_title() + ' Description: ' + this.oWebsite.get_description());
}

function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

Read JSON data with # (pound sign) and @ (at sign)

Example:

{
    "locenter": [
        {
            "loname": {
                "@empid": "1001",
                "#text": "FE1"
            },
            "centers": [
                {
                    "@id": "0000100001",
                    "#text": "dcgiDal"
                }
            ]
        },
        {
            "loname": {
                "@empid": "1002",
                "#text": "FE2"
            },
            "centers": [
                {
                    "@id": "0000300006",
                    "#text": "dcgiDah"
                },
                {
                    "@id": "0000100006",
                    "#text": "dcgiDau"
                }
            ]
        }
    ]
}

Answer:

locenter.centers["@id"] / locenter.centers["#text"]

source: http://stackoverflow.com/questions/4637983/how-to-read-json-array-with-tags-in-data-using-jquery

 

You may get this in chrome: getjson pound sign Uncaught SyntaxError: Unexpected token ILLEGAL

Cache output for ashx

Sometimes we use generic handlers to grab JSON or XML data and then use that data somewhere else. The problem you run in to is everytime you load the page you are making a call to that handler and the handler goes to that external data source and brings your data back to the client.

Here is a way to cache the data in IIS for a determined amount of time before you go back out and get new data.

In the ashx file:

public class WeatherHandler : IHttpHandler
{
     public void ProcessRequest(HttpContext context)
     { //SET CACHE FOR THIS ASHX
       TimeSpan freshness = new TimeSpan(0, 0, 0, 10);
       DateTime now = DateTime.Now;
       context.Response.Cache.SetExpires(now.Add(freshness));
       context.Response.Cache.SetMaxAge(freshness);
       context.Response.Cache.SetCacheability(HttpCacheability.Server);
       context.Response.Cache.SetValidUntilExpires(true);

       using (WebClient webclient = new WebClient { })
       {

OR for all ASHX’s, you can put it in the web.config:

<system.webServer>
      <caching enabled="true">
        <profiles>
          <add extension=".ashx" policy="CacheForTimePeriod" duration="00:00:10"/>
        </profiles>
      </caching>
</system.webServer>


Convert Sharepoint date field in javaScript to JSON then filter or orderby

var date = new Date();

                date.setDate(date.getDate()-20);

                var TodayISO = date.toJSON();

                $.getJSON(“http://SharepointServer/_vti_bin/listdata.svc/Notices?$filter=Expires gt datetime'”

                        + TodayISO + “‘&$orderby=Expires%20desc”,

                        {},

                        function (data) {

                        var link = [];

                            var title = [];                      

                            var level =[];

                                        for (i=0; i<data.d.results.length; i++){

                                            title[i] = data.d.results[i].Title;                                           

                                                $(“#notices”).append(“<table><tr><td>”+title[i]+”</td></tr></table>”);

                                        }

                        }

                );

});

Filter / Sort / and return JSON with listdata.svc and Sharepoint 2010

Include reference to the latest jQuery.

This is my standard template for fetching list items in Sharepoint and returning JSON:

$('#IDInContentEditorWP').empty(); //Remove everything from Content Editor Webpart (this resets the content editor for where you are going to append your list items)

$.getJSON(http://SharepointServer/_vti_bin/listdata.svc/ListName?$filter=ColumnName eq 'FieldValue', //filter by field value
    {},
    function (data) {
        var title = [],
        link = []; //create arrays to store values
            for (i=0; i<data.d.results.length; i++ ){ //go through the entire dataset returned by the JSON query
                title[i] = data.d.results[i].Title; //store title
                link[i] = data.d.results[i].Link; //store link
                $("#IDInContentEditorWP").append("<table><tr><td><a href=" link[i] ">" title[i] "</a></td></tr></table>"); //append the title and link with HTML to the ID specified
            }
    });

$.getJSON(http://SharepointServer/sites/UpgradeTest/_vti_bin/listdata.svc/Banner?$filter=PublishDate%20gt%20datetime'2012-01-01T00%3A00%3A00', //Filter by date field

Example of pulling values from a sharepoint list that are already sorted and then doing some logic and calling a function to work with the data. This actually builds a menu based off a sharepoint list. Then you can use the list to setup permissions to security trim the menu.

$.getJSON("http://SharepointServer/sites/mega/_vti_bin/listdata.svc/MegaMenuCategories?$orderby=OrderingValue%20asc",
    {},
    function (data) {
        for (i=0; i<data.d.results.length; i++ ){
            var results1 = data.d.results[i].MenuTitle;
            var order = data.d.results[i].OrderingValue;
            if (order == "1")
                addMenuTitle(order, results1);
            if (order == "2")
                addMenuTitle(order, results1);
            if (order == "3")
                addMenuTitle(order, results1);
            if (order == "4")
                addMenuTitle(order, results1);
            if (order == "5")
                addMenuTitle(order, results1);
            if (order == "6")
                addMenuTitle(order, results1);
        }
        if (menuLength == "5"){
            $("#megaRtCorner").css("left","490px");
            $("#megaMenu").css("width","475px");
        }
    }
);

});//end document ready

function addMenuTitle(order, results1){
    $("a[data-menu='megaNav" order "']").append(results1);
    $("a[data-menu='megaNav" order "']").parents(".liMain").show();
    $("a[data-menu='megaNav" order "']").parents(".liMain").children(".drop").show();
}

Other good articles:

http://sharepointkunskap.wordpress.com/2011/12/15/update-list-items-with-listdata-svc/

https://www.nothingbutsharepoint.com/sites/devwiki/articles/Pages/Got-REST-Querying-SharePoint-List-data-using-REST-services-client-side-Part-1.aspx

http://www.dotnetmafia.com/blogs/dotnettipoftheday/archive/2010/01/21/introduction-to-querying-lists-with-rest-and-listdata-svc-in-sharepoint-2010.aspx

http://books.google.com/books?id=QdNxpPD3QqAC&pg=PA138&lpg=PA138&dq=filter+by+today+listdata.svc&source=bl&ots=op7z0YTWWO&sig=NQJY95Iz26GfdWGKnGHDj5dd6I8&hl=en&sa=X&ei=yJvcUPblHcrQqgHHzYDABQ&ved=0CIIBEOgBMAk#v=onepage&q=filter%20by%20today%20listdata.svc&f=false

Your User Profile Service Application is not syncing Active Directory Users/Groups/Properties.

You need to re-create the User Profile Service Application Proxy – http://support.microsoft.com/kb/2520394

After you have recreated the proxy you need to re-associate it with a Web Application. CA > Manage Web Applications > Choose the web app > Service Connections > Custom > Select the proxy that you just created.

If you do not re-associate it with a web application, you will not have the “Target Audiences” field in web parts and you will not be able to view audiences in Central Administration. You will also receive Failed to render the result list when you try to view the member ship of an audience.

Run a full sync