Thursday, 13 August 2015

Content Iterator

Introduced in SharePoint 2010, the Content Iterator API allows you to iterate through content in a list rather than executing a query. This could be a way for you to process each item in a list while avoiding any throttling limits. The Content Iterator is a great way for you to crawl your sites and lists to process content in bulk. While performance is not as good as a simple query, it works great when the scenario calls for it.

Using the Content Iterator

SharePoint Server provides a new API, ContentIterator, to help with accessing more than 5,000 items in a large list without hitting a list throttling limit and receiving an SPQueryThrottleException. ContentIterator implements a callback pattern for segmenting the query for processing a single item at a time. Consider using this capability if you need to process a large number of items that may exceed a throttling limit. The following trivial example demonstrates the approach used with ContentIterator tested with a list returning 20,001 items from the query.
static int exceptions = 0;
static int items = 0;

protected void OnTestContentIterator(object sender, EventArgs args)
{
    items = 0;
    exceptions = 0;
    string query1 = @"<View>
        <Query>
            <Where>
                <And>
                    <BeginsWith>
                        <FieldRef Name='SKU' />
                        <Value Type='Text'>S</Value>
                    </BeginsWith>
                </And>
            </Where>
        </Query>
    </View>";

    ContentIterator iterator = new ContentIterator();
    SPQuery listQuery = new SPQuery();
    listQuery.Query = query1;
    SPList list = SPContext.Current.Web.Lists["Parts"];
    iterator.ProcessListItems(list,
        listQuery,
        ProcessItem,
        ProcessError
    );
}

public    bool ProcessError(SPListItem item, Exception e) 
{ 
    // process the error
    exceptions++; 
    return true; 
}
public void ProcessItem(SPListItem item)
{
    items++;
    //process the item.
}

ContentIterator will run through each item in the list, invoking the callback provided for list item processing—in this case, ProcessItem. If an error occurs while iterating the list, then the error function is invoked—in this case,ProcessError. Using this approach the ContentIterator processes the list in pieces and avoids any excessively large queries. This functionality is provided as part of Enterprise Content Management (ECM) in SharePoint Server 2010. ContentIterator has additional functionality not described in this section, such as the ability to order result sets. For more information see the ContentIterator Class.

https://msdn.microsoft.com/en-us/library/microsoft.office.server.utilities.contentiterator.aspx

Monday, 2 March 2015

Sharepoint 2013- app prompting for credentials

I have developed an app in app in office 365 site and every thing went well for app in office 365 site. I have developed same app for share point 2013, using visual studio office development tools. Before deploying app in share point server, we need to check the following list of things in share point server,

  • Create an App Domain-- Done
  • Run Shared Service Instances-- Done
  • Check App Service and SharePoint Subscription services are running in the server-- Done
  • Create Subscription Settings Service Application, Subscription Settings Service Application Proxy through Power shell-- Done
  • Create App Management Service, App Management Service Proxy-- Done
  • Add App prefix-- Done
  • Add App Domain to the List of Intranet Sites in Internet Options-- Done 

Deployed the app in share point site, while accessing the app through share point site, it is prompting for credentials. I have tried many times with different credentials, Redeployed app to share point site and restarted my machine, No luck.. :(

I have googled for the same issue and in Microsoft forums i got some clue on the issue. The issue here is we need set the value for DisableLoopbackCheck registry key.

What is Loop Back Check
From Server 2003 SP1, There is feature called Loop back check related to security. It will makes server can't call by itself through the host name, that share point does. So that share point will prompts us to enter credentials.

i have followed following steps to fix this error,

Go to Registry Editor (Run-->regedit)




Navigate to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa




Right-click Lsa--> New--> DWORD Value.



Type DisableLoopbackCheck, and then press ENTER.



Right click on DisableLoopbackCheck--> Modify,




Change value form 0 to 1 and click on OK.



Quit Registry editor and restart computer.

That's it. My issue got fixed and i am able to see my custom app. Hope this help you.

Developing a SharePoint-Hosted App in SharePoint 2013 Part -II

Continuation to the post Developing a SharePoint-Hosted App in SharePoint 2013 Part -I .

Once we verified that the above services are running do these next steps..

Step 2 :
Now we need to create domain for apps and register this domain to sharepoint. So that our apps will be hosted separately when we deploy them.
Run this PowerShell command to create the app domain. You should be an administrator with the Managed Account. Here my domain name is nature.com
So for naming conventions (or to follow principles J) , If your domain name is nature.com, give your domain name for apps as like natureapps.com
Set-SPAppDomain  "natureapps.com".
Now we need to create the AppManagement and subscription service applications as mentioned above.
Step 3 :
Creating the App Management and Subscription Setting Service applications
Ensure that the SPSubscriptionSettingsService and AppManagementServiceInstance services are running with these below cmdlets(if they are not running this cmdlet will make them to run)
Get-SPServiceInstance | where{$_.GetType().Name -eq "AppManagementServiceInstance" -or $_.GetType().Name -eq "SPSubscriptionSettingsServiceInstance"} | Start-SPServiceInstance
You will get this message if they are already running


 If you will not get this message, check whether they are started or not by going to
Central AdministrationàManage services on server under System Settings category


These services are running now, so the next step is we need to create the respective service applications with the below cmdlets. To do this you should have a SPManagedAccount.(or u can run with farm admin if it is a managed account).
If you want to create new managed account follow these steps : This **** marked step is optional if you have already a managed account
*****************************************
$account= New-SPManagedAccount
It will ask the credentials for the user to whom you want to make the Managed Account(in my case im giving farm admin  credentials itself, since i want to use my farm admin as a managed account for this )
******************************************
Now create the service apps with below cmdlets using this Managed Account.
$account = Get-SPManagedAccount “nature\administrator”(your domain name\user name)

$appPoolSubSvc = New-SPServiceApplicationPool -Name SettingsServiceAppPool -Account $account
$appPoolAppSvc = New-SPServiceApplicationPool -Name AppServiceAppPool -Account $account

$appSubSvc = New-SPSubscriptionSettingsServiceApplication –ApplicationPool $appPoolSubSvc –Name SettingsServiceApp –DatabaseName SettingsServiceDB
$proxySubSvc = New-SPSubscriptionSettingsServiceApplicationProxy –ServiceApplication $appSubSvc
$appAppSvc = New-SPAppManagementServiceApplication -ApplicationPool $appPoolAppSvc -Name AppServiceApp -DatabaseName AppServiceDB
$proxyAppSvc = New-SPAppManagementServiceApplicationProxy -ServiceApplication $appAppSvc
 If you notice the above cmdlets, here we are creating the AppManagement Service application and SubscriptionSettingsServiceApplication. This will create two databases too.

Check this Msdn url to get all the cmdlets at a place.
So now lets verify whether these service applications are created or not .
Go to Central Administration àApplication Management àManage service applications check these two



And also verify ourAppdomain(natureapps.com) configured or not. Go to Central AdministrationàSelect Apps àThen select Configure App Urls under App Management.



Now you can find the App Domain as “natureapps.com”.And give app prefix for the app. This will be used in the app url. Here I have given as “spapps”.And says OK.(This app prefix can be given through powershell as like appdomain name, but i missed it).
With these, you have completed the settings required to deploy the sharepoint-hosted App. Now try to deploy the app. Once it got deployed successfully you will find this message in the output window


If you notice this message, it is showing that the app is successfully installed at
Here
Spapp  - is the prefix what we have provided just now
cdab466a043db3- is the app id dynamically generated one
natureapps.com- is our app domain name
SharePointDemoApp1- is our app name
Now check the app from the SharePoint site (where we deployed our visual studio app solution ) à Site ContentsàCheck our App .



Now Click on it.It will redirect to our app site.( http://spapp-cdab466a043db3.natureapps.com/SharePointDemoApp1/.)


So FINALLY we achieved it...
Hope this will helpful ...Thanks.

Developing a SharePoint-Hosted App in SharePoint 2013 Part -I

This is the first post from me on SharePoint 2013. As part of R&D on SharePoint 2013 Apps, I got some good information from the msdn site and others. So I wanted to share with you…
Before start reading this post, have a look at this post to know basics about apps and why aapps?
In simple words, apps are of three types based on their hosting model
SharePoint Hosted: If you deploy/install your app with in the sharepoint server it is called sharepoint hosted app. In this, when we deploy the app a sharepoint site will be created and all the app content stored in the sharepoint itself. The app content will be lists/pages/content types etc.   
Auto Hosted (Azure): If we host the app on Windows Azure, it is called auto hosted. The app will sit in the cloud, we will download and install this app in to the sharepoint. When we install, the app will automatically create a site and provides us a windows azure site.
Provider Hosted: If you host your app in any other cloud (other cloud providers) environment, it is called Provider hosted. The logic and code related to app will be resided external to sharepoint. The code/logic might be in C# or JavaScript or php or java or anything. Here sharepoint just work as a place holder for the app.


Apps are isolated identities and they need a separate domain(called app domain) to deploy/install.one app cannot communicate with other apps. Once you deploy/install a sharepoint hosted app, it creates a separate site.
 i.e. http://[Appprefix]-[App Id].[App domain name]/[AppName].
Now let's create a simple sharepoint-hosted app with a static text and an alert message..
Developing a SharePoint Hosted App :
Go to visual studio 2012 à Create -> New -> Project -> select Office/Sharepoint category and then select the Apps under that.
Choose the App for SharePoint 2013 template .And give the required information
Give the name of the app, the url of the sharepoint site, give the hosting option as “SharePoint-hosted”. In this post I am showing only how to develop a sharepoint hosted app. If you want to deploy your app to windows azure, you need to select the “Auto-hosted”. If you want to deploy your app to any other cloud (or your own cloud) select “Provider-hosted” option.


Once you say finish, Your App Solution structure will be like this :

If you notice this, there is one feature, some css, image , javascript files along with a default.aspx page.
This default.aspx page is the landing page of your app site (When you deploy your app a site will be created and this page will be the home page of this site).
If you have look at to the Default.aspx page, you will find a head and main place holder and references to the App.css and App.js files. Along with this it calls the sharePointReady function of App.js file.
In this default page im writing a content with the h1 tags like this
 

In App.js by default CSOM code will be there. Here Sharepoint Ready function calling the  getUserName function. Now I am adding a simple function called ShowAlert(), just to show an alert when we access the app. Check this
Now build the project and then try to deploy it. You will find this below error (if you are trying to deploy the app for the first time without service apps creation and app domain creation).
The reason for this deployment error is you need set some prerequisite settings before deploying the app. These are the below settings/configurations to install and configure the apps in SP2013 successfully. 
·         Create an Isolated domain for the app
·         Create/Configure the App Management Service
·         Create/Configure the Subscription Settings Service
Creating Isolated Domain for the Apps :

Create the app domain using PowerShell cmdlets (There are some other approaches to create the app domain but I am showing here with the PowerShell as i am deploying in a single server work group environment )
Step 1 : 
Open the SharePoint 2013 Management PowerShell with Admin rights
Check the Admin and timer services running or not (if you say start it will start if they are stopped) with these commands
 
net start spadminv4
net start sptimerv4

For continuation ....

Friday, 9 January 2015

How to Show the ID Field in EditForm.aspx and DispForm.aspx

We do not get ID field in DispForm.aspx and EditForm.aspx pages out of the box. However many times business needs this field to show up in this form because of their uniqueness. To accomplish it a javascript is most easy option and it can be applied via content editor webpart. To do this follow these steps
  1. Go to the list.
  2. Click view item with any existing item or if you do not have any item then in the URL after listname add /DispForm.aspx .
  3. In the next page add ?ToolPaneView=2 . This will open the page in editable form and the add a content editor webpart. Edit it to add the HTML content.
  4. Paste the below script:

<script language="javascript" type="text/javascript">
_spBodyOnLoadFunctionNames.push("showID");
function showID()
{
var querystring = location.search.substring(1, location.search.length);
var ids = querystring.split("&")[0];
var id = ids.split("=")[1];
var Td1 = document.createElement("td");
Td1.className = "ms-formlabel";
Td1.innerHTML ="<h3 class ='ms-standardheader'>ID</h3>";
var Td2 = document.createElement("td");
Td2.className =  "ms-formbody";
Td2.innerHTML = id;
var Tr1 = document.createElement("tr");
Tr1.appendChild(Td1);
Tr1.appendChild(Td2);
var Location = GetSelectedElement(document.getElementById("idAttachmentsRow"),"TABLE").getElementsByTagName("TBODY")[0];
Location.insertBefore(Tr1,Location.firstChild);
}
</script>

Monday, 29 September 2014

SharePoint 2010 - Features Overview

Overview
Feature is a server side functional component which can be installed and activated at various scopes throughout a SharePoint instance. Additionally, a feature can be used to replace a standard control or functionality with your own custom functionality.
For example, the search box which appears in the upper-right corner of every standard SharePoint layout can be replaced with a custom search control.


Scope of a feature
Every feature has an activation scope that can assume one of the following values:
1) Farm - The feature will target the entire SharePoint farm.
2) WebApplication - The feature targets a single web application and all the contained Site Collections.
3) Site - The feature will target a single Site Collection and all of its websites.
4) Web - The feature targets a single website.

Components of feature
1) Feature Manifest (Feature.xml) - Each time you develop a feature, SharePoint at minimum creates an XML file, named Feature.xml and called the feature manifest, and stores it on every front-end web server of the farm in a sub-folder of the SharePoint 14_Root\TEMPLATE\FEATURES directory.
2) Feature Elements (Elements.xml) - These elements correspond to zero or more ElementManifest tags, which are still defined through XML files, and zero or more ElementFile tags, which declare files supporting the feature.

The feature manifest file structure
Following is the structure of a Feature manifest file.
<Feature xmlns="http://schemas.microsoft.com/sharepoint/"
ActivateOnDefault = "TRUE" | "FALSE"
AlwaysForceInstall = "TRUE" | "FALSE"
AutoActivateInCentralAdmin = "TRUE" | "FALSE"
Creator = "Text"
DefaultResourceFile = "Text"
Description = "Text"
Hidden = "TRUE" | "FALSE"
Id = "Text"
ImageUrl = "Text"
ImageUrlAltText = "Text"
ReceiverAssembly = "Text"
ReceiverClass = "Text"
RequireResources = "TRUE" | "FALSE"
Scope = "Text"
SolutionId = "Text"
Title = "Text"
UIVersion = "Text"
Version = "Text" >
</Feature>

Properties of Feature Manifest
1) ActivateOnDefault - An optional Boolean attribute with a default value of True. It applies only to Farm-scoped or WebApplication-scoped features anddetermines whether the feature will be activated by default during installation. For WebApplication-scoped features, if this attribute is set to True, the feature will also be activated when a new web application is created.
2) AlwaysForceInstall - This is an optional Boolean attribute with a default value of False. When set to True, it forces the feature to be installed—even if it is already installed.
3) AutoActivateInCentralAdmin - This is an optional Boolean attribute with a default value of False. It defines whether the feature will be activated by default in the Administrative website hosting the SharePoint Central Administration. It does not apply to Farm-scoped features.
4) Creator - This is an optional description of the feature’s creator.
5) DefaultResourceFile - This is optional text that defines the name of a common resource file, usually shared with other features released by the same creator. By default, SharePoint will look for resources in a file in the path SharePoint14_Root\TEMPLATE\FEATURES\FeatureName\Resources, with a file name such as Resources.Culture.resx (the Culture value can be any of the standard culture names defined by the Internet Engineering Task Force (IETF), such as en-US, it-IT, fr-FR, and so on.
6) Description - This is optional text that describes the feature in the features’ management UI. You can define it using a resource string in the form $Resources:ResourceName. For example, if the feature description is a resource item with a key value of “FeatureDescription,” the corresponding value should be $Resources: FeatureDescription.
7) Hidden - This is an optional Boolean attribute with a default value of False. When set to True, the feature will be hidden from the UI and can be activated or deactivated only through the command line tools or by using the Object Model.
8) Id - This is a required attribute of type text, which must contain an ID (GUID) that uniquely identifies the feature.
9) ImageUrl - This is optional text that defines the site-relative URL of an image used to render the feature in the UI.
10) ImageUrlAltText - This is optional text that defines alternate text for the image representing the feature in the UI (see ImageUrl). You can define this using a resource string, just like the Description property.
11) ReceiverAssembly - This is optional text that defines the strong name of an assembly that SharePoint will search for in the Global Assembly Cache (GAC) and that provides a receiver class to handle the feature’s events.
12) ReceiverClass - This is optional text that defines the full class name of a receiver class to handle the feature’s events. SharePoint will search for the receiver class name in the ReceiverAssembly.
13) RequireResources - This is an optional Boolean attribute with a default value of False. It determines whether SharePoint requires that resources exist for the language of the current website or Site Collection to make the feature visible in the UI. This attribute does not affect the capability to activate and manage the feature from the command line or from the object model.
14) Scope - This is a required text attribute. It defines the scope within which the feature can be activated. The possible values are: Farm, WebApplication, Site, and Web. SolutionId This is optional text that defines the ID of the solution to which the features belongs.
15) Title - This is optional text that defines the title of the feature and that is visible in the features’ management UI. It is limited to a maximum length of 255 characters. You can define it using a resource string, as described in the Description property.
16) UIVersion - This is optional text that declares the UI version supported by the feature. The accepted values are 3 (for Windows SharePoint Services 3.0) and 4 (for Microsoft SharePoint Foundation 2010).
17) Version - This is optional text that defines the version of the feature. It can be made of up to four numbers, delimited by periods. For example, it might be 1.0.0.0, 1.0.0.1, and so on.
The feature elements file structure
<Feature xmlns="http://schemas.microsoft.com/sharepoint/" Title="My Sample Web Part" Description="Deploys a custom Web Part." Id="c46c270e-e722-4aa0-82ba-b66c8dd61f4e" Scope="Site" Version="1.0.0.0">
<ElementManifests>
<ElementManifest Location="SampleWebPart\Elements.xml" />
<ElementFile Location="SampleWebPart\SampleWebPart.webpart" />
</ElementManifests>
</Feature>

Feature Element Types
Following are the available features elements in SharePoint 2010:
1) ContentTypeBinding - Used to provision a content type on a list defined in a site template. Can be scoped to Site.
2) ContentType - Defines a content type, ready to be used in lists or libraries. Can be scoped to Site.
3) Control - Used to customize the configuration of an existing delegate control, or to declare a new delegate control to override SharePoint’s standard controls. Can be scoped to Farm, WebApplication, Site, and Web.
4) CustomAction - Defines an extension to the standard user interface. For example, you can use CustomAction to define a new button on a ribbon bar, a new menu item on a standard menu, or a new link on a site settings page. Can be scoped to Farm, WebApplication, Site, and Web.
5) CustomActionGroup - Groups custom actions. Can be scoped to Farm, WebApplication, Site, and Web.
6) DocumentConverter - Declares a document converter that can convert a document from a type X to a type Y. Requires some custom development, to implement the converter. Can be scoped to WebApplication.
7) FeatureSiteTemplateAssociation - Allows associating a feature to a specific site template definition for the purpose of provisioning the feature together with the site definition, when you create a new site with that definition. Can be scoped to Farm, WebApplication, and Site.
8) Field - Declares a Site Column definition. Can be scoped to Site.
9) HideCustomAction - Hides an existing custom action defined by another custom action or implemented by default in SharePoint. Can be scoped to Farm, WebApplication, Site, and Web.
10) ListInstance - Provisions an instance of a list definition, together with a specific configuration. Can be scoped to Site and Web.
11) ListTemplate - Defines a list template for the purpose of provisioning a custom lists’ definitions. Can be scoped to Web.
12) Module - Allows provisioning custom pages or files to a site. Module can also be used to deploy configured Web Parts, ListView Web Parts over existing or provisioned lists, NavBar links, custom Master Pages, and to configure properties of the target feature. Can be scoped to Site and Web.
13) PropertyBag - Assigns properties and metadata to items (File, Folder, ListItem, Web) through features. Can be scoped to Web.
14) Receivers - Defines a custom event receiver. Can be scoped to Web.
15) WebTemplate - Allows deploying a website template, even through a sandboxed solution so that it can create site instances based on that template. Can be scoped to Site.
16) Workflow - Deploys a workflow definition on a target site. Can be scoped to Site.
17) WorkflowActions - Defines custom workflow actions for SharePoint Designer 2010. Can be scoped to Farm.
18) WorkflowAssociation - Associates a workflow with its target. Can be scoped to Site, Web.
Features and Solutions Deployment
To deploy a feature, you need to copy the feature’s folder to the SharePoint14_Root\TEMPLATE\FEATURES path of every target server for the feature. When this is complete, you can use the STSADM.EXE command line tool to install and later activate the feature.
Hope this article gave you an overview of the components of a feature. In the upcoming posts we will figure out the steps involved in the development and deployment of a SharePoint 2010 feature.

References
1) Microsoft SharePoint 2010 Developer Reference, by Paolo Pialorsi - Book