Issue: Remove orphan web application features

I found a custom web application feature which I tried to deactivate but got the error message that I couldn’t find the manifest.  This feature folder or the feature manifest file may have been accidently deleted from your Web Front End servers file system, you will get the error “Failed to find the XML file at location ’12\Template\Features\Feature_Name\feature.xml”.  Another reason is if you installed the feature in your farm and accidently deleted the feature manifest file from the file system of the web front end server. Feature folders are located at “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\FEATURES”.

I launched the SharePoint Manager 2013 and then click on the features for a web application I showed a dialog with an error of the culprit feature but without a feature id. This is because your feature is still installed in the farm, and when you view the features, the page will go through all the features installed in your farm, and then read their corresponding manifest files from the file system to determine if the feature has a corresponding manifest associated to it. If the feature is installed and the corresponding manifest file has been deleted, this error will be thrown.

Solution: The reason why they don’t show up in PowerShell is the missing Scope, those feature are orphaned, indeed. We cannot use -Site parameter. What you can is to list it in PowerShell without -Site parameter and filter out those without Scope:

Get-SPFeature | ? { $_.Scope -eq $null }

This will give you a complete list of orphaned features.

Obviously, I had a lot of orphaned features on my Development Environment

Now you have to find the culprit feature and delete it. You cannot use ID for getting your feature, neither use Unistall-SPFeature cmdlet with ID:

Uninstall-SPFeature : Cannot find a Feature object with Path or Id: a4d208a3-b4fa-4bca-bb34-be4d30156b63 in scope Local farm. At line:1 char:1 + Uninstall-SPFeature a4d208a3-b4fa-4bca-bb34-be4d30156b63 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidData: (Microsoft.Share…ninstallFeature:SPCmdletUninstallFeature) [Uninstall-SPF eature], SPCmdletPipeBindException + FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletUninstallFeature

The workaround is to use the DisplayName to get the spfeature (actually SPFeatureDefinition) and then delete it.

I tried stsadm -o uninstallefeature -id <GUID> -force <– but this didn’t work

I also tried Uninstall-SPFeature but it also didn’t work

but what WORKED was the below commands:

$feature = Get-SPfeature | ? { $_.DisplayName eq “My_Orphane_Feature” }

$feature.delete()

Aside: You can even use this code to clean all the orphaned features:

Get-SPFeature | ? { !$_.Scope } | % { $_.Delete() }

This line of code gets all the orphaned features and removes them.

SharePoint Search Query: Include or Exclude empty or null dates

Problem: I wanted to show only announcements where the events have not expired including events with blank expiry dates and where the event is to be published.

Solution: To filter out a datetime managed property you could use definition:

-ExpirationTime:1900-01-01..{Today}

Notice the following important things:

  • the minus sign (-) => is to not include someting that is a certain definition
  • ExpirationTime => will be replaced with your managed property name
  • 1900-01-01..{Today} => is a range, the minimum value is the “empty” or “null” value in a SharePoint datetime field. In other words the lowest possible datetime value which is 1900-01-01.

To include “null” or “empty” date time values just remove the minus (-) sign

Finally Query Syntax: path:{SiteCollection.URL} (contentclass:STS_ListItem_Announcements AND -ExpirationTime:1900-01-01..{Today} AND Publish=1)

 

Error: Workflow 2010 failed to run after in sleep mode.

Problem: We had an issue with our SharePoint 2010 Workflows where once in sleep mode it would show failed to run in the workflow history. When only one item into the custom list ,after pause 5 mins , it will randomly to show the error ‘xxx workfow fail to run’.

To solve this the ‘xxx workfow fail to run’ error

Solution:  We found that we only have Microsoft SharePoint Foundation Workflow Timer Service started on the application server, the reason was we were concern about performance which workflows may have on the WFEs, thus this service was never started on the WFEs.  The solution was to start Microsoft SharePoint Foundation Workflow Timer Service on the WFEs.  Since then all new workflows would sleep and then automatically wake up and continue as usual.

Aside: Microsoft’s documentation explicitly says that the Microsoft SharePoint Foundation Workflow Timer Service should be run only on web servers. But it’s also marked as a ‘Can also be deployed to application servers‘. It’s recommended to be a WFE role but it’s not mandatory as far as we know.  But this started the service on all WFEs solved our problem.

Can’t Connect to the SharePoint Store

enter image description here

After setting up the SharePoint Store, I got this message and I was sure everything was setup correctly.  I checked the Event Log and saw this:

image

Solution:

Check the trust between SharePoint and the Auth provider .

OR try below option once

Go to your SharePoint site web.config and add the following line within
system.net tag:

<system.net>
<defaultProxy />
<settings>
<servicePointManager
 checkCertificateName=”false”
 checkCertificateRevocationList=”false”
/>
</settings>
</system.net>

Note: Need to do this for the web.config file on all WFE, no need for Application Server

Aside: Make that your server has access to the Microsoft url: https://store.office.com/en-in/appshome.aspx

Also you maybe need to refresh the App Store several times before any Apps will show up.  Occasionally, I’ve seen adding/removing the above <Settings></Settings> tag also solves the can’t connect to App Store.

Adding javascript file to custom masterpage html page

I wanted to make change to the html masterpage and not the SharePoint converted masterpage because if someone happends to public a major version of the html masterpage it will replace the *.masterpage and ALL of my changes to *.masterpage will be gone.

  1.  Upload your js file to Style Library in SharePoint site collection rather than 15\layouts
  2. Open SharePoint Designer > Go to Master Page > Right click on your custom masterpage HTML file and Check it out.
  3. Right click -> Edit in advanced mode.
  4. In < head > section add your reference of your js file like <script type="text/javascript" src="../../Style Library/JS/jquery7.min.js"> after <!--SPM:<SharePoint:CustomJSUrl runat="server"/>-->

Note: To get the correct URL > write Src=” > then the Pick URL button should be shown, navigate to your js file in Style Library.

  • Save -> Right click Check-in -> Publish As Major version ->

Enter image description here

  • This is similar to going to your master page gallery -> right click and select publish.

Enter image description here

Note: Please also check if same master page is set for both “Site Master Page” as well as “System Master Page”. In publishing sites, “System Master Page” is the primary master page.

Additionally:

To apply custom resources to master page, we modify associated html file which is a recommended practice by Microsoft. And we will only modify html tags. Below is our way to include css and javascript files. enter image description here

 

Custom Messages Using Event Receiver in SharePoint

In SharePoint 2010 and 2013, we can write event receivers that are triggered on the occurrence of a specific event, such as when an item is added or deleted from a list or library and so on. For a complete list of possible event receivers, we can refer to the following link:

Table of SharePoint Events, Event Receivers, and Event Hosts
When we write an “–ing ” type receiver where the handler is triggered before the event actually updates the SharePoint object, after performing the necessary check or actions of the handler, we have two options with the event; one to proceed with the update of the SharePoint object and another is to cancel it.
There are scenarios when we want to update/cancel an event and display a message to the user regarding the outcome. In most cases, a successful update may not warrant a message to be displayed to the user. But if the operation is cancelled, we may want to show a meaningful message to the user.
By default, if we merely cancel an event in the receiver such as the following, SharePoint throws an ugly error page to the user that may leave them confused.

public override void ItemDeleting(SPItemEventProperties properties)

{

base.ItemDeleting(properties);

try

{

StringBuilder strMessage = new StringBuilder();

using (SPSite oSite = new SPSite(properties.SiteId))

{

using (SPWeb oWeb = oSite.OpenWeb(properties.Web.ID))

{

SPList oProducts = oWeb.Lists.TryGetList(“Products”);

if (properties.List.ID == oProducts.ID)

{

if (properties.ListItem != null && properties.ListItem[“Status”] != null && properties.ListItem[“Status”].ToString().Equals(“Sealed”))

{

properties.Cancel = true;

}

}

}

}

}

catch (Exception ex)

{

properties.Status = SPEventReceiverStatus.CancelWithError;

properties.Cancel = true;

}

}

Resulting errorResulting error

Only a SharePoint-aware developer can understand this message that comes out of the box from SharePoint. To a business user, this makes little sense and might induce some panic. A more customized message indicating the root cause for cancelling the operation would make sense here.
This article details a method to show custom error messages when an event receiver cancels an operation.
Let’s assume that we have a SharePoint list named “Products” with the following columns:SharePoint list

When a SharePoint user tries to delete an item with a specific value in a column, say “Sealed” in a “Status” column, then the deletion should not happen and the user must be shown a proper message indicating that a Sealed record cannot be deleted.
Here, we will first create an event receiver to implement this functionality.
In Visual Studio click on “Create a new project” and add a new event receiver for Custom List type and select the event as “An item is being deleted”.
Visual Studio creates the skeleton receiver for us to work on. Add the following code to the event receiver.

public override void ItemDeleting(SPItemEventProperties properties)

{

base.ItemDeleting(properties);

try

{

StringBuilder strMessage = new StringBuilder();

using (SPSite oSite = new SPSite(properties.SiteId))

{

using (SPWeb oWeb = oSite.OpenWeb(properties.Web.ID))

{

SPList oProducts = oWeb.Lists.TryGetList(“Products”);

if (properties.List.ID == oProducts.ID)

{

if (properties.ListItem != null && properties.ListItem[“Status”] != null && properties.ListItem[“Status”].ToString().Equals(“Sealed”))

{

properties.Cancel = true;

properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;

properties.RedirectUrl = oSite.Url + “/_layouts/Seal/CustomErrorPage.aspx”;

}

}

}

}

}

catch (Exception ex)      {

properties.Status = SPEventReceiverStatus.CancelWithError;

properties.Cancel = true;

}

}   We observe that in the code, we are first checking if the list id is that of the list we are interested in and if the item’s Status matches “Sealed”. If so then we are cancelling the event and redirecting to an application page.
Hence, we should create this application page named “CustomErrorMessage.aspx”, in the folder mapped to the “Layouts” folder and add the following code to the aspx of the application page:

<%@ assembly name=”$SharePoint.Project.AssemblyFullName$” %>

<%@ import namespace=”Microsoft.SharePoint.ApplicationPages” %>

<%@ register tagprefix=”SharePoint” namespace=”Microsoft.SharePoint.WebControls”

assembly=”Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c” %>

<%@ register tagprefix=”Utilities” namespace=”Microsoft.SharePoint.Utilities” assembly=”Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c” %>

<%@ register tagprefix=”asp” namespace=”System.Web.UI” assembly=”System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″ %>

<%@ import namespace=”Microsoft.SharePoint” %>

<%@ assembly name=”Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c” %>

 

<%@ page language=”C#” autoeventwireup=”true” codebehind=”CustomErrorPage.aspx.cs”

inherits=”Seal.Layouts.CustomErrorPage” dynamicmasterpagefile=”~masterurl/default.master” %>

 

<asp:content id=”PageHead” contentplaceholderid=”PlaceHolderAdditionalPageHead” runat=”server”>

</asp:content>

<asp:content id=”Main” contentplaceholderid=”PlaceHolderMain” runat=”server”>

<table border=”1″ cellspacing=”5″ cellpadding=”5″  style=’border-collapse:collapse;border:none;’>

<tr style=’height:1.9in’>

<td width=”499″ style=’width:5.2in;border:solid windowtext 1.0pt; padding:0in 5.4pt 0in 5.4pt;height:1.9in’>

<p  align=”center”   text-align:center;line-height:normal;mso-layout-grid-align:none;text-autospace:

none’><span style=’font-size:9.5pt;font-family:Consolas;mso-bidi-font-family:

Consolas;color:red’>Sealed Records cannot be deleted. Please contact your

administrator.<o:p></o:p></span></p>

</td>

</tr>

</table>

</asp:content>

<asp:content id=”PageTitle” contentplaceholderid=”PlaceHolderPageTitle” runat=”server”>

Sealed Records cannot be deleted

</asp:content>

<asp:content id=”PageTitleInTitleArea” contentplaceholderid=”PlaceHolderPageTitleInTitleArea”

runat=”server”>

Sealed Records cannot be deleted

</asp:content>

Now when we deploy the solution and attempt to delete a record with the Status “Sealed” it redirects us to the following page:

Sealed Status
I have observed that, if the list is in a site other than the root site with variuos permissions, then if we access the error page using the following code:

properties.RedirectUrl = oSite.Url + “/_layouts/Seal/CustomErrorPage.aspx”;   Then, the error page shows the navigation links of the root site. The look and feel can also be different from the current site if the master pages of the root site and the current site are different. To prevent this, we can modify the master page URL of the error page to use the custom master page, by replacing this line in the errorpage aspx:

<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”CustomErrorPage.aspx.cs” Inherits=”Seal.Layouts.CustomErrorPage” DynamicMasterPageFile=”~masterurl/default.master” %>

To this:

<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”CustomErrorPage.aspx.cs” Inherits=”Seal.Layouts.CustomErrorPage” DynamicMasterPageFile=”~masterurl/custom.master” %>

Article from: http://www.c-sharpcorner.com/UploadFile/3a164c/custom-messages-using-event-receiver-in-sharepoint/

How To create Event Receivers and Custom Application Error Pages

Introduction

SharePoint 2007

Many of you are aware that in SharePoint 2007, you can create Event Receivers (aka. Event Handlers) to take care of things for you when specific things happen. For example, you can subscribe to the “ItemAdded” event for a specific list, and have your custom code execute when the event fires.

Also, you are in SP 2007 able to cancel an event if you have the need for it, hence providing the user with an error message in the browser.

With SharePoint 2007 you had no way to customize this error message, and could only display the out-of-the-box message.

I’ve been getting the question about 1 million times – but never had any really good answer. Until now, where this specific functionality is built into SP 2010.

SharePoint 2010

The object model has been extended in various places, and this is one of the most welcome changes for me and a lot of my fellow peers doing daily SharePoint development.

So, in this article I will walk you through the news with Event Receivers in SP 2010 in regards to creating custom Error Pages for your users.

Creating an Event Receiver in SharePoint 2010 with a Custom Error Page

Using Visual Studio 2010, choose the new template called “Event Receiver” like so:
image

Choose if you want this to be a Farm Solution or a Sandboxed Solution. Then click next:
image

Finally, choose the Type of receiver you want to create, what event you would like to hook up and to what type. I chose “List Item Events“, “Announcements” and “An item is being added“:
image

Click next and let Visual Studio 2010 work it’s magic.

You’re presented with the following project structure that is created for us:
image

I will not dig deep on how and why the structure of the project looks the way it does now – it will be covered in another article.

1. Adding some basic logic for your Event Receiver

In the EventReceiver1.cs file that you’re presented with, you can quite easily add any code you want – and some code has already been added so you don’t have to!

The code looks like this out of the box:

image

Now, what I want to do in order to make sure my event receiver works – is to simply add some dummy-code and have it tested!

Add the following code to your ItemAdding-method:
image

All we do here is check our item that is being added makes a condition to see if the DueDate property is set. The breakpoint is simply added because you easily should see that your code executes and works as expected.

2. Press the Holy Button (F5)

By pressing F5, Visual Studio will take care of the build, packaging and deployment of your Event Receiver. For more details on the actual F5-experience, I encourage you to read MSDN, SDK and all the blogs out there.

You are presented with a web page (VS 2010 launches IE for you as well), where you now can easily test your Event Receiver.

In our case, when adding a new Announcement, we should automatically check the DueDate property. Currently we don’t cancel the event or do anything else – let’s leave that to your imagination.

Cancelling an Event in SharePoint 2010

So – now that we’ve got a very basic Event Receiver in SharePoint 2010, we should add that Custom Error Page we talked about.

  • Start by adding a New Item to your project of type Application Page: image
  • Visual Studio 2010 will now automatically add a mapped folder called “Layouts” which is mapping to the _layouts folder in the SharePointRoot (14-folder): image
  • Edit the ErrorDueDate.aspx file to add some rich HTML: image Note that I am referring to an image as well. I just popped that into the same Layouts-folder that was created for my Event Receiver project.
  • Edit your EventReceiver1.cs file and add the current logic: image This will now cancel the event if the DueDate field is empty, and show the user a custom error page that you designed yourself.
  • Hit F5 and let Visual Studio 2010 work it’s magic again
  • Try it out by adding a new Announcement without adding a DueDate: image
  • You should now be presented with the following dialog:  image

As you can see, your custom HTML now appears. Apparently I didn’t do any fancy design on my Application Page, but you can add more images and whatever else you want to make it more easy for the users to understand what actually went wrong – and how to make it on from there.

Summary

As easy as 1-2-3, you’ve created a new event receiver in SharePoint 2010 – and created a Custom Error Page upon which your users will land when they’re presented with the error – something that wasn’t really possible in 2007.

Article from: https://zimmergren.net/sp-2010-how-to-event-receivers-and-custom-error-pages/

Set date picker value in InfoPath

I had to set the date picker field of an InfoPath form using PowerShell.

Note: Only Date format “yyyy-MM-dd” or dateTime “yyyy-MM-ddTHH:mm:ss” is accepted by InfoPath

If you look at the image above, a small insert of the InfoPath xml file, you will see that if you tried to update the field dtDateRevisionsorUpdateReturned and then you go to look at the InfoPath form.  You will see a red dotted line will get the error message “Only date or date and time allowed” like the below image, even though the powershell script to update the field doesn’t complain.

Reason: If you look at the field dtDateRevisionsorUpdateReturned in the InfoPath xml you will see the xsi:nil=”true” and this is issue.

Solution: If you remove the xsi:nil=”true” if it exists and then update the field dtDateRevisionsorUpdateReturned with whatever value you want then everything is fine.

I have create a function which will delete the xsi:nil=”true” if a DateTime field needs to be set.  Note: if your xml file has xsi:nil=”true” and then you set the DateTime field to an empty string you will also get the Only date or date and time allowed error message.  If you want to set the DateTime field to empty then just don’t set it.

Function SetDateToXNode($xml, $xpath, $value)
{
$ns = new-object System.Xml.XmlNamespaceManager($xml.NameTable)
$ns.AddNamespace(“my”, $xml.DocumentElement.NamespaceURI)
$node = $xml.CreateNavigator().SelectSingleNode($xpath, $ns)

if ($node.MoveToAttribute(“nil”, “http://www.w3.org/2001/XMLSchema-instance”))
{
$node.DeleteSelf()
}
$dt = reformatDate $value

$node.SetValue($dt)
}

If you need to do the above but using C#:
DateTime date = DateTime.Today;
DateTime nextDayDate = (DateTime)date.Value.AddDays(1);
string nextDateString = nextDayDate.ToString(“yyyy-MM-dd”);

XPathNavigator endDateNode = MainDataSource.CreateNavigator().SelectSingleNode(“/my:myFields/my:yourTargetDatePickerField”, NamespaceManager);

if (endDateNode.MoveToAttribute(“nil”, “http://www.w3.org/2001/XMLSchema-instance”))
endDateNode.DeleteSelf();

endDateNode.SetValue(nextDateString );

so, generally

DateTime dateTime = DateTime.Now;
string dateString = dateTime.ToString(“yyyy-MM-dd”);
string dateTimeStrng = dateTime.ToString(“yyyy-MM-ddTHH:mm:ss”);
//this node is Date type
XPathNavigator endDateNode = MainDataSource.CreateNavigator().SelectSingleNode(“/my:myFields/my:DatumNastupu”, NamespaceManager);

//XPathNavigator endDateNode = XNode(“/my:myFields/my:DatumNastupu”);

if (endDateNode.MoveToAttribute(“nil”, “http://www.w3.org/2001/XMLSchema-instance”))
endDateNode.DeleteSelf();
endDateNode.SetValue(dateString);

//this node is DateTime type
XPathNavigator dateTimeNode = MainDataSource.CreateNavigator().SelectSingleNode(“/my:myFields/my:DateTimeField”, NamespaceManager);
if (dateTimeNode.MoveToAttribute(“nil”, “http://www.w3.org/2001/XMLSchema-instance”))
dateTimeNode.DeleteSelf();
dateTimeNode.SetValue(dateTimeStrng);
or functions for use for Date field type or DateTime field type
public void SetDateToXNode(string xpath, DateTime date)
{
XPathNavigator dateNode = MainDataSource.CreateNavigator().SelectSingleNode(xpath, NamespaceManager);

if (dateNode.MoveToAttribute(“nil”, “http://www.w3.org/2001/XMLSchema-instance”))
dateNode.DeleteSelf();
dateNode.SetValue(date.ToString(“yyyy-MM-dd”));
}

public void SetDateTimeToXNode(string xpath, DateTime dateTime)
{
XPathNavigator dateNode = MainDataSource.CreateNavigator().SelectSingleNode(xpath, NamespaceManager);

if (dateNode.MoveToAttribute(“nil”, “http://www.w3.org/2001/XMLSchema-instance”))
dateNode.DeleteSelf();
dateNode.SetValue(dateTime.ToString(“yyyy-MM-ddTHH:mm:ss”));
}