Monday, November 19, 2012

 SharePoint 2010 Vs. SharePoint 2013 limitations


Limit Name SharePoint 2010 Maximum Value SharePoint 2013 Maximum Value
Web application limits    
Web application Not Published 20 per farm
Content database 300 per Web application 300 per Web application
Zone 5 per Web application 5 per Web application
Managed path 20 per Web application 20 per Web application
Solution cache size 300 MB per Web application 300 MB per Web application
Site collection 250,000 per Web application 250,000 per Web application
     
Web server and application server limits    
Application pools
10 per Web server 10 per Web server
     
Content database limits    
Number of content databases
300 per Web application 500 per farm
Content database size (general usage scenarios) 200 GB per content database 200 GB per content database
Content database size (all usage scenarios) 4 TB per content database 4 TB per content database
Content database size (document archive scenario) No explicit content database limit No explicit content database limit
Content database items 60 million items including documents and list items 60 million items including documents and list items
Site collections per content database 2,000 recommended
5,000 maximum
2,000 recommended
5,000 maximum
MySites per content database Not Published 5,000 per content database
Remote BLOB Storage (RBS) storage subsystem on Network Attached Storage (NAS) Time to first byte of any response from the NAS cannot exceed 20 milliseconds Time to first byte of any response from the NAS cannot exceed 20 milliseconds
     
Site collection limits    
Site collection
Not Published 2,000,000 per farm
Web site 250,000 per site collection 250,000 per site collection
MySites per farm Not Published 500,000 per farm
Site collection size Maximum size of the content database Maximum size of the content database
Number of device channels per publishing site collection Not Available in SharePoint 2010 10
     
List and library limits    
List row size
8,000 bytes per row 8,000 bytes per row
File size 2 GB 2 GB
Documents 30,000,000 per library 30,000,000 per library
Major versions 400,000 400,000
Minor versions Not Published 511
Items 30,000,000 per list 30,000,000 per list
Rows size limit 6 table rows internal to the database used for a list or library item 6 table rows internal to the database used for a list or library item
Bulk operations 100 items per bulk operation 100 items per bulk operation
List view lookup threshold 8 join operations per query 8 join operations per query
List view threshold 5,000 5,000
List view threshold for auditors and administrators 20,000 20,000
Subsite 2,000 per site view 2,000 per site view
Coauthoring in Word and PowerPoint for .docx, .pptx and .ppsx files 10 concurrent editors per document 10 concurrent editors per document
Security scope 1,000 per list 1,000 per list
     
Column limits    
Single line of text
276 276
Multiple Lines of Text 192 192
Choice 276 276
Number 72 72
Currency 72 72
Date and Time 48 48
Lookup 96 96
Yes / No 96 96
Person or group 96 96
Hyperlink or picture 138 138
Calculated 48 48
GUID 6 6
Int 96 96
Managed metadata 94 94
     
Page limits    
Web parts
25 per wiki or Web part page
25 per wiki or Web part page
     
Security limits    
Number of SharePoint groups a user can belong to
5,000 5,000
Users in a site collection 2 million per site collection 2 million per site collection
Active Directory Principles/Users in a SharePoint group 5,000 per SharePoint group 5,000 per SharePoint group
SharePoint groups 10,000 per site collection 10,000 per site collection
Security principal: size of the Security Scope 5,000 per Access Control List (ACL) 5,000 per Access Control List (ACL)
     
Search limits    
Search service applications
20 per farm 20 per farm
Crawl databases 10 crawl databases per search service application
25 million items per crawl database
5 crawl databases per search service application
Crawl components 16 per search service application 2 per search service application
Index components Not Published 60 per Search service application
Index partitions 20 per search service application
128 total
20 per search service application
Index replicas Not Available in SharePoint 2010 3 per index partition
Indexed items 100 million per search service application;
10 million per index partition
100 million per search service application;
10 million per index partition
Crawl log entries 100 million per search application 100 million per search application
Property databases 10 per search service application;128 total 10 per search service application;128 total
Link database Not Available in SharePoint 2010 Two per Search service application
Query processing components 128 per search application
64/(total crawl components) per server
1 per server computer
Content processing components Not Published One per server computer
Scope rules 100 scope rules per scope; 600 total per search service application 100 scope rules per scope; 600 total per search service application
Scopes 200 site scopes and 200 shared scopes per search service application 200 site scopes and 200 shared scopes per search service application
Display groups 25 per site 25 per site
Alerts 1,000,000 per search application (seems like a mistake) 100,000 per search application
Content sources 50 per search service application 50 per search service application
Start addresses 100 per content source 100 per content source
Concurrent crawls 20 per search application 20 per search application
Crawled properties 500,000 per search application 500,000 per search application
Crawl impact rule 100 no limit
Crawl rules 100 per search service application no limit
Managed properties 100,000 per search service application 50,000 per search service application
Values per managed property Not Published 100
Indexed managed property size Not Published 512 KB per searchable/queryable managed property
Managed property mappings 100 per managed property 100 per managed property
Retrievable managed property size Not Published 16 KB per managed property
Sortable and refinable managed property size Not Published 16 KB per managed property
URL removals 100 removals per operation 100 removals per operation
Authoritative pages 1 top level and minimal second and third level pages per search service application 1 top level and minimal second and third level pages per search service application
Keywords 200 per site collection 200 per site collection
Metadata properties recognized 10,000 per item crawled 10,000 per item crawled
Analytics processing components Not Available in SharePoint 2010 6 per Search service application
Analytics reporting database Not Available in SharePoint 2010 Four per Search service application
Maximum eDiscovery KeywordQuery text length Not Available in SharePoint 2010 16 KB
Maximum KeywordQuery text length Not Available in SharePoint 2010 4 KB
Maximum length of eDiscovery KeywordQuery text at Search service application level Not Available in SharePoint 2010 20 KB
Maximum length of KeywordQuery text at Search service application level Not Available in SharePoint 2010 20 KB
Maximum size of documents pulled down by crawler Not Available in SharePoint 2010 64 MB (3 MB for Excel documents)
Navigable results from search Not Available in SharePoint 2010 100,000 per query request per Search service application
Number of entries in a custom entity extraction dictionary Not Available in SharePoint 2010 1 million
Number of entries in a custom search dictionary Not Available in SharePoint 2010 5,000 terms per tenant
Number of entries in a thesaurus Not Available in SharePoint 2010 1 million
Ranking models Not Available in SharePoint 2010 1,000 per tenant
Results removal Not Available in SharePoint 2010 No limit
Term size Not Available in SharePoint 2010 300 characters
Unique terms in the index Not Available in SharePoint 2010 2^31 (>2 billion terms)
Unique contexts used for ranking Not Available in SharePoint 2010 15 unique contexts per rank model
User defined full text indexes Not Available in SharePoint 2010 10
     
User Profile Service limits    
User profiles
2,000,000 per service application 2,000,000 per service application
Social tags, notes and ratings 500,000,000 per social database 500,000,000 per social database
Maximum Number of Users Imported Via FIM Not Published 1000000
     
Content deployment limits    
Content deployment jobs running on different paths
20 20
     
Blog limits    
Blog posts
5,000 per site 5,000 per site
Comments 1,000 per post 1,000 per post
     
Business Connectivity Services limits    
ECT (in-memory)
5,000 per Web server (per tenant) 5,000 per Web server (per tenant)
External system connections 500 per Web server 500 per Web server
Database items returned per request 2,000 per database connector 2,000 per database connector
Response latency Not Published 600 seconds
Service response size Not Published 150,000,000 bytes
Filter Descriptor (in-store) Not Published 200 per ECT method
ECT Identifier (in-store) Not Published 20 per ECT
Database Item Not Published 1,000,000 per request
     
Workflow limits    
Workflow postpone threshold
15 15
Workflow timer batch size 100 100
Workflow associations Not Published 100 per list
List items or documents that can be bulk created or uploaded to start workflow instances Not Published 5,000 items
Published workflow definitions per site Not Published 1,000 per site
Total workflow associations per site Not Published 1,799 per site
Maximum workflow definition (xaml) size Not Published 5,120 KB
Maximum depth of a workflow sub-step in xaml (workflow complexity) Not Published 121 levels
Workflow instance activations per second per web server Not Published 6 per second
Rest calls from SharePoint workflow per second per web server Not Published 60 per second
Workflow variable value size Not Published 256 KB
Maximum list size for workflow lookups to non-indexed fields Not Published 5,000 items per list view
Maximum list size for auto-start workflow associations Not Published 10 million items per list
     
Managed Metadata term store (database) limits    
Maximum number of levels of nested terms in a term store
7 7
Maximum number of term sets in a term store 1,000 1,000
Maximum number of terms in a term set 30,000 30,000
Total number of items in a term store 1,000,000 1,000,000
Number of Variation Labels Not Available in SharePoint 2010 209 per term store
     
Visio Services limits    
File size of Visio Web drawings
50 MB 50 MB
Visio Web drawing recalculation time-out 120 seconds 120 seconds
Visio Services minimum cache age (data connected diagrams) Minimum cache age: 0 to 24hrs Minimum cache age: 0 to 24hrs
Visio Services maximum cache age (non-data connected diagrams) Maximum cache age: 0 to 24hrs Maximum cache age: 0 to 24hrs
     
SharePoint Web Analytics service limits    
SharePoint entities 30,000 per farm when Web Analytics is enabled Deprecated
     
PerformancePoint Services limits    
Cells
1,000,000 per query on Excel Services data source 1,000,000 per query on Excel Services data source
Columns and rows 15 columns by 60,000 rows 15 columns by 60,000 rows
Query on a SharePoint list 15 columns by 5,000 rows 15 columns by 5,000 rows
Query on a SQL Server data source 15 columns by 20,000 rows 15 columns by 20,000 rows
     
Word Automation Services limits    
Input file Size
512 MB 512 MB
Frequency with which to start conversions (minutes) 1 minute (recommended) 
15 minutes (default)
59 minutes (boundary)
1 minute (recommended) 
15 minutes (default)
59 minutes (boundary)
Number of conversions to start per conversion process For PDF/XPS output formats: 30 x M For all other output formats: 72 x M Where M is the value of Frequency with which to start conversions (minutes) For PDF/XPS output formats: 30 x M For all other output formats: 72 x M Where M is the value of Frequency with which to start conversions (minutes)
Conversion job size 100,000 conversion items 100,000 conversion items
Total active conversion processes N-1, where N is the number of cores on each application server N-1, where N is the number of cores on each application server
Word Automation Services database size 2 million conversion items 2 million conversion items
     
SharePoint Workspace limits (Renamed to Office Live Workspace)    
Office Live Workspace list items
30,000 items per list 30,000 items per list
Office Live Workspace documents 1,800 documents limit in SharePoint Workspace 1,800 documents in Office Live Workspace
     
OneNote limits    
Number of Sections and Section Groups in a OneNote Notebook (on SharePoint)
See limit for "Documents" in List and library limits See limit for "Documents" in List and library limits
Maximum size of a section See limit for "File size" in List and library limits See limit for "File size" in List and library limits
Maximum size of an image, embedded file, and XPS OneNote printout in a OneNote section. See limit for "File size" in List and library limits See limit for "File size" in List and library limits
Maximum size of all images, embedded files, and XPS printouts in a single OneNote page. Default limit is double the "File size" limit. Default limit is double the "File size" limit.
Merge operations One per CPU core per Web server One per CPU core per Web server
     
Excel Services limits    
Maximum workbook size
Not Published 10 MB
     
Machine Translation Service limits    
Input file size for binary files
Not Available in SharePoint 2010 524,288 KB per file
Input file size for text files Not Available in SharePoint 2010 15,360 KB per file
Maximum character count for Microsoft Word Documents Not Available in SharePoint 2010 10,000,000 per document
Total concurrent translation processes Not Available in SharePoint 2010 5
Delay between translations Not Available in SharePoint 2010 59 minutes
Number of translations per translation process Not Available in SharePoint 2010 1,000 per process
Maximum concurrent translation requests Not Available in SharePoint 2010 300
Files per translation job Not Available in SharePoint 2010 100,000 files
Machine Translation Service database size Not Available in SharePoint 2010 1,000,000 files
     
Office Web Application Service limits    
Cache size
100 GB 100 GB
Renders One per document per second per CPU core per application server (maximum eight cores) One per document per second per CPU core per application server (maximum eight cores)
OneNote concurrent merge operations Not Available in SharePoint 2010 8 per document
     
Project Server limits    
End of project time
Date: 12/31/2049 Date: 12/31/2049
Deliverables per project plan 1,500 deliverables 1,500 deliverables
Number of fields in a view 256 256
Number of clauses in a filter for a view 50 50
     
SharePoint Apps limits    
Maximum Access app size on Office 365/SQL Azure Not Available in SharePoint 2010 100 Mb
Apps displayed in Manage Licenses page Not Available in SharePoint 2010 2,000
Number of app licenses per tenant Not Available in SharePoint 2010 1,000,000
Number of apps displayed in the Add an App page Not Available in SharePoint 2010 240
Number of managers per app license Not Available in SharePoint 2010 30
Number of app licenses assigned to a user viewable by that user Not Available in SharePoint 2010 2,000
Number of apps in the corporate catalog viewable by a single user Not Available in SharePoint 2010 500
     
Miscellaneous limits    
Number of User agent substrings per device channel
Not Available in SharePoint 2010 150
Number of SharePoint sources per EDiscovery case Not Available in SharePoint 2010 100
Number of Exchange sources (mailboxes) per EDiscovery case Not Available in SharePoint 2010 1500
Maximum size of EDiscovery Query Not Available in SharePoint 2010 16K characters or 500 keywords
Number of nodes in managed navigation term set Not Available in SharePoint 2010 2000

Friday, November 16, 2012

Q. What is Enterprise Metadata Management?

Introduction to Enterprise Metadata Management


Enterprise metadata management (EMM) is a set of features introduced in Microsoft SharePoint Server 2010 that enable taxonomists, librarians, and administrators to create and manage terms and sets of terms across the enterprise.
The managed metadata service: is a service application that enables the use of managed metadata and
allows you to share content types across site collections and across Web applications. The service publishes a term store and content types, and the metadata is consumed via the managed metadata connection. A managed metadata service and connection are created when the metadata service application is created.

Managed Metadata Service Application Creating the service application requires the administrator to specify the database to be used as the term store. When you create new managed terms, or when users add managed keywords, these terms are stored in the database. Like other service applications, the managed metadata service can be published to provide access to other Web applications.
When a service application is published, a URL to the service is created.
 The administrator of another Web application can create a connection to your service by using this URL.
In addition to sharing metadata, you can also use the managed metadata service to share content types. By creating a new managed metadata service and specifying a site collection as the content type hub, you can share all content types in the site collection’s content type gallery.

You can create multiple managed metadata service applications. This provides the capability to share multiple term stores and content types from multiple site collections. Each service must specify a different term store during the creation process, and a new database will be created if it does not exist.

Managed Metadata Service ConnectionThe connection provides access to the service. When you create a managed metadata service, a connection to the service is automatically created in the same Web application as the service. Web applications can have connections to multiple services. Several properties are specified as part of the connection. Values for each of these properties must be specified as part of configuring the service connection.

Default keyword location Specifies that the term store will be used to store new managed keywords. This provides the capability for sharing and managing a common set of keywords across site collections.

Default term set location Specifies where to store term sets when new site columns are created. This provides the capability for sharing and managing a common set of terms across site collections.

Use content types Makes content types associated with this managed metadata service available to users of sites in this Web application.Push-down content type publishing updates from the content type gallery to subsites and lists by using the content type whether to update existing instances of the changed content types in subsites and libraries.

Creating and Deploying Custom aspx Page as Feature and Solution Package


There are two ways to deploy a custom aspx page in SharePoint.

1. Using VseWss extensions project. Here you won't need to create a solution package manually. All the files need to create a solution package are created by the VS extensions itself. See the related Post Deploy Custom Css file in 12 hive. You can use same method to deploy your Custom aspx page.

2. The second way is creating a solution package around your asp.net webapplication so that the pages in the webapplictaion can be deployed in sharepoint. This requires you to manually create all the solution related files (I mean manifest.xml, feature.xml, elements.xml and .ddf file).


In this Post, we will create a solution package manually for a asp.net webapplication project, so that the custom aspx page created in asp.net web application can be deployed in SharePoint's Layouts folder.

Below are the Steps that you can follow :

1. Create a New WebApplication Project.

2. Create a new folder "MyCustomFolder" in the solution explorer and Add your custom aspx page (along with cs file) under it.

3. Add two more xml files in the same folder with names as elements.xml and feature.xml.

The Elements.xml File should look like below -

<elements xmlns="<a href=">http://schemas.microsoft.com/sharepoint/">
<module name="Pages" url="_layouts">
<file url="CustomPage.aspx" name="CustomPage.aspx" type="GhostableInLibrary"> </file>
</module>
</elements>
</div>

Note : Add Module name as “Pages” and url as ” _Layouts “


The Feature.xml File should look like below -

<feature id="79DD53E7-8719-45b0-8E25-C2450B3E3F14" title="Project.CustomPage" description="Custom Page" scope="Web" version="1.0.0.0" hidden="false" xmlns="http://schemas.microsoft/sharepoint/">
<elementmanifests>
<elementmanifest location="elements.xml">
<elementfile location="CustomPage.aspx"> </elementfile> </elementmanifest>
</elementmanifests>
</feature></div>


4. Now, Create another xml file in the Project and name it as manifest.xml

The manifest.xml should look like below -

<solution xmlns="<a href=">http://schemas.microsoft.com/sharepoint/" SolutionId="A5A9C1C2-4EBF-40db-935F-66085A9E0BE8">
<rootfiles>
<rootfile location="TEMPLATE\LAYOUTS\MyCustomFolder\CustomPage.aspx">
</rootfile>
<assemblies>
<assembly deploymenttarget="GlobalAssemblyCache" location="Project.CustomPage.dll">
<safecontrols>
<safecontrol assembly="Project.CustomPage Version=1.0.0.0, Culture=neutral, PublicKeyToken=a28586c97e90b41f" namespace=" Project.CustomPage" typename="*" safe="True"> </safecontrol>
</safecontrols>
</assembly>
</assemblies>
</rootfiles>
</solution>

Note : If you are using some code behind with your aspx page, then change the Inherit tag in the aspx page to inherit from the assembly of the project.

For e.g. change the tag to

Inherits="NameSpace.Class, NameSpace, Version=1.0.0.0, Culture=neutral, PublicKeyToken=2ef8d0c4bab8980b" Debug="true"

You dont need to deploy .cs file with the Project. The code is accessed via its .dll .

5. Finally Create the .ddf file ( its simply a text file with name as .ddf)

.ddf file would be something like below -

.OPTION Explicit ; Generate errors.Set CompressionType=MSZIP

.Set UniqueFiles=Off.Set

DiskDirectory1=Package

.Set CabinetNameTemplate=Project.CustomPage.wsp

manifest.xml

bin\ Project.CustomPage.dll

.Set DestinationDir=TEMPLATE\LAYOUTS\CustomPage.aspx

;sets the feature directory.

Set DestinationDir=CustomPageFolder

;adds the feature to the feature directory

MyCustomFolder\feature.xml

;adds the element to the feature

MyCustomFolder\elements.xml

I have created an empty folder in the Project with a name as “Package” to save the .wsp file in it.


6. Sign the project with a key (Project Properties -> "signing tab" and browse your .snk key) and Build the Project.

7. Now, Add and deploy the .wsp solution which is under Package Folder in SharePoint using stsadm commands.
What is the main difference between using SPListItem.Update() and SPListItem.SystemUpdate()?

Ans. Using SystemUpdate() will not create a new version and will also retain timestamps.

Impersonation in Sharepoint (RunWithElevatedPrivileges)

Although not recommended, there may be times when you need your code to perform certain functions that the current user does not have the necessary permissions to perform.

The SPSecurity class provides a method (RunWithElevatedPrivileges) that allows you to run a subset of code in the context of an account with higher privileges than the current user.
The premise is that you wrap the RunWithElevatedPrivileges method around your code. And also In certain circumstances, such as when working with Web forms, you may also need to set the AllowSafeUpdates method to true to temporarily turn off security validation within your code. If you use this technique, it is imperative that you set the AllowSafeUpdates method back to false to avoid any potential security risks.

Code example


{
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.OpenWeb();

//Using RunWithElevatedPrivileges

SPSecurity.RunWithElevatedPrivileges(delegate()
{
// Get references to the site collection and site for the current context.
// The using statement makes sures these references are disposed properly.

using (SPSite siteCollection = new SPSite(mySite.ID))
{

using (SPWeb web = siteCollection.OpenWeb(myWeb.ID))
{

web.AllowUnsafeUpdates = true;

try
{
//Your code
}


web.AllowUnsafeUpdates = false;

//siteCollection = null;
//web = null;

}

Thursday, November 15, 2012

What is a Field Control?

Ans.
Field controls are server controls that provide the basic field functionality of SharePoint. For example a Inputbox (single line text) to enter the title of the item. You can create your own FieldControl by inheriting classes from BaseFieldControl namespace.
Difference between Application Pages, Site Pages and Content Pages?

Application Pages - An application page is deployed once per Web server and cannot be customized on a site-by-site basis. They stay in 12 hive folder structure, mostly under layouts folder.

Site Pages - These are pages that make up the site interface and are specific to one site or site collection.They mostly get stored in the content database of the site collection.

Content Pages - Site Page which contains webpart or other custom components. This Page is stored in database. They mostly get stored in the content database of the site collection.

What are event receivers or event Handlers in SharePoint?


Ans.
Event Receivers or Event handlers are created to handle the basic actions or events against an item,list\library, a web or a site. There are two kinds of events in sharepoint.

Synchronous Events: Like Itemadding (not added yet), Uploading (document not uploaded yet) etc.

Asynchronous Events: ItemAdded (after item is added), Uploaded(after a document is uploaded)

Events receivers can be written to override an event for e.g. ItemAdded event to change the name of an Item once it is added.

You will normally, find it under C:\Program Files\Common Files\ shared\web server extensions\12\bin.

Run with elevated privileges in SharePoint,MOSS

(Gud one that I found in other blog)
In case you didn't know, there is a construct built into SharePoint that allows developers to create code that runs as the System Account instead of the logged in user, essentially giving that user Administrator Level Permissions in a confined space. I will go over the code required to do this below, but essentially you have a block of code within your larger project that needs the logged in user to have certain permissions that they may not have, and this small block of code will then be run as the System Account, giving it the permissions needed for the task at hand.
Well, at first thought everyone I have explained this to has the same questions and concerns, “Why would you ever want to do that?” or “That is a huge security risk!”.
I could never come up with a very good example to explain it and my attempts to reassure customers that the security risk is very minimal as the user will only have permission to do exactly what the developer lets them sometimes was not well understood.
Well I finally had a project that required me to do this, so I figured I would share it to give a fairly simple real world example.
Project Objective: Create an extranet to serve as a customer support site where users can log Service Requests, manage their account, order new products, etc. via the web or by phone.
This is fairly simple and something I have done several times for different customers, but this project had one difference. Service / Support Requests could be made by phone, where all of my other projects were strictly web oriented. Does anyone see the problem this raises yet? Well I eventually incorporated the Cisco phone system into the site to generate Service Requests, but that is not what I am talking about. With any system like this, it is vital that customers only have access to their own Service Requests (as in they cant view other user’s requests).
Typically, when using a SharePoint list one can turn on the settings in the Advanced Settings section of a List (seen below) so that users can only view and edit their own List Items. This is very handy and works very well when users are always the creator of their own items, but in this case when someone calls in, someone else will be creating the service request for them… see the problem? Well, I thought about trying to change the Created By field to the user that called in, but decided it would be a neat place to use the elevated permissions approach.

The Solution: So, this is the summary of what I did. I didn’t give any customers permissions to the Service Request List at all from within SharePoint. All access that customers had to that List was done through custom forms and web parts that made use of the elevated permission construct. This ended up being 3 forms and 3 web parts that used Elevated Permissions. Customers would use one form to create a Service Request, another to view it, another to edit it and then three web parts to display the contents of the list on various pages.
I added a custom text field to the list called Customer ID which would store each customer’s unique ID, detailing who each Service Request belonged to. The custom forms that users would use would populate this field upon creation by looking to see who the current user was, and looking up their ID in another List. Likewise when a member of the support staff was creating a service request received over the phone, they would fill in the Customer’s ID before creating it (The phone system was later used to automate this). This way, we are not relying on the Created Field to limit what each user is allowed to see.
Below I will go through the basics of how Elevated Permissions work and then show in more detail how I used it in my solution. Then in the next few days I hope to stick out a web part that incorporates it as well.
This is the basic code snippet you need to run with elevated permissions:
private void yourFunction()
{
      // Non-Elevated Permission Code Goes Here

      SPSecurity.RunWithElevatedPrivileges(delegate()
      {
            // Elevated Permission Code Goes Here
      });    

      // Non-Elevated Permission Code Goes Here
}
Pretty much everything you find online about this has code that is poorly explained, so hopefully I can do a decent job and make it easy. The code above is simple enough right? Well here is one place people routinely run into problems. If you are using an instance of SPWeb or SPSite before your Elevated Permission Code block, you won’t be able to use it. You need to get a new instance of the SPWeb or SPSite object to use once you enter the elevated block. Below is the code that I use to do this.
private void yourFunction()
{
      SPSite site = SPContext.Current.Site;
      SPWeb web = SPContext.Current.Web;

      SPSecurity.RunWithElevatedPrivileges(delegate()
      {
            using (SPSite ElevatedSite = new SPSite(site.ID))
            {
                  using (SPWeb ElevatedWeb = ElevatedSite.OpenWeb(web.ID))
                  {
                        // Code Using the SPWeb Object Goes Here
                  }
            }
       });
}
I am pretty sure that little tidbit cost me about a day the first time I tried to play with Elevated Permissions, so hopefully that will help some of you out. After that, it is really simple as you just put your code in the middle of it just like you would if you weren’t using the elevated permissions.
As further example, in my NewSR.aspx form that users go to when creating a new Service Request, I use a runWithElevatedPrivileges block in two functions. The first is a private function I call within the OnPreLoad() function called LoadData(). Inside this function I am populating drop down menus from data in a SharePoint list for the Priority of the service request and the products that are affected.
The second function with a runWithElevatedPrivileges block is my onSubmit() function that is called when a user clicks the submit button.

So it is actually pretty simple. The only other thing I am going to demonstrate is how I made the view and Edit Forms Secure. As you probably know, every List Item has an integer ID (.ID) and a unique guid ID (.UniqueID). Well, the custom forms I made for view and edit look in the querystring for a guid which it then uses to look up the Service Request. (If you can guess the guid of another service request, well you broke my security but it seems quite unlikely) There isn’t anything fancy about accessing the querystring to get the guid and look up the Service Request, but I thought it would be handy to store a link to the item within the item itself as an additional field. This makes it easy to email the user a link to view their service request among other things.
So I created a text field called Link and populated it as shown below.
private void yourFunction()
{
      SPSite site = SPContext.Current.Site;
      SPWeb web = SPContext.Current.Web;

      SPSecurity.RunWithElevatedPrivileges(delegate()
      {
            using (SPSite ElevatedSite = new SPSite(site.ID))
            {
                  using (SPWeb ElevatedWeb = ElevatedSite.OpenWeb(web.ID))
                  {
                        srList = ElevatedWeb.Lists["Service Requests"];
                        SPListItem newItem = srList.Items.Add();
                     
                        // Do stuff to create the list item

                        ElevatedWeb.AllowUnsafeUpdates = true;
                        newItem.Update();
                        Guid temp = newItem.UniqueId;
                        newItem["Link"] = "<DIV><a href=\"https://YourSite.com/_layouts/custom/ViewSR.aspx?ID=" + temp.ToString("d") + "\">View SR</a></DIV>";
                        newItem.Update();
                        ElevatedWeb.AllowUnsafeUpdates = false;
                  }
            }
       });
}
The tricky part here is having to call item.update() twice. You have to call it twice because the first time you call it is when the list item is actually created. Before then, it does not have a Unique ID to reference. So once it is created, you can grab the Unique ID, and populate the Link field with a HTML formatted URL that references the item and can be easily inserted into a HTML based email or a page that has a content editor web part CEWP with the JavaScript in it found here. You then call update the second time to save your link field.

The use of the link field and the JavaScript found above allows me to render links in a web part as shown above.
Well, hopefully this will be useful to someone – I think it would have saved me a day or so once upon a time when I first tried to do this.

Adding your Web Part to the Safe Controls List

why we want to add webpart as safe control in SharePoint?


A fundamental assumption of the Windows SharePoint Services technology is that "untrusted users" can upload and create ASPX pages within the system on which Windows SharePoint Services is running. These users should be prevented from adding server-side code within ASPX pages, but there should be a list of approved controls that those untrusted users can use. One way to provide these controls is to create a Safe Controls list.
The Safe Controls list is a list of controls and Web Parts specific to your SharePoint site that you have designated as safe for invocation on any ASPX page within your site. You store this list in the web.config file in your Web application root.

How to add as safe control

  1. Open the web.config file in the application root.
  2. Add a safe control entry for your custom assembly to the web.config file as follows:


    <SafeControl Assembly="MyWebPartLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" Namespace="MyWebPartLibrary" TypeName="*" Safe="True" AllowRemoteDesigner="True"/>

Web part page life cycle

Main Points are:

    protected override void OnInit(EventArgs e)
    protected override void OnLoad(EventArgs e)
    protected override void CreateChildControls()
    protected override void LoadViewState(object savedState) //Only at Postback
    protected override void OnPreRender(EventArgs e)
    protected override void Render(System.Web.UI.HtmlTextWriter writer)
    protected override void OnUnload(EventArgs e)
    public override void Dispose()



      Description:

      OnInit: This method handles initialization of the control.
      OnLoad: This event handles the Load event. This is also used for initialize the control but is not intended for loading data or other processing functionality.
      CreateChildControls: This is the most popular event in web part life cycle. This creates any child controls. So if you are adding any control to display then you have to write in this method.
      EnsureChildControls: This method ensures that CreateChildControls has executed. EnsureChildControls method must be called to prevent null reference exceptions.
      SaveViewState: View state of the web part saved.
      OnPreRender: This method handles or initiates tasks such as data loading that must complete before the control can render.
      Page.PreRenderComplete: The page fires the PreRenderComplete event after all controls have completed their OnPreRender methods.
      Render: This method is used to render everything.
      RenderContents: Renders the contents of the control only, inside of the outer tags and style properties.
      OnUnload: Performs the final cleanup.

      Friday, November 9, 2012

      Cascading dropdown lists in SharePoint 2010


      Today I am going to explain you how to create a list with filtered lookup columns, based on information in previous columns. Check out SharePoint Cascaded Lookup from SharePointBoost.
      Image from SharePointBoost
      The software looks great. I haven’t tried it, but it does offer some great extra functionality.
      Unfortunately, this piece of software is very expensive for small companies that only need this for a single form on SharePoint.
      So I am going to show you how to create such a list without the need of buying this piece of software. I covered it into a lot of steps, but no programming is needed. The only things you need, are a SharePoint 2010 environment, InfoPath 2010 and this tutorial :D !
      For this small tutorial, I will create a simple room-reservation list for a company existing out of multiple physical buildings. I will not explain about how to create a reservation system, I only use it as a example to show you how to filter data based on a previous selected item.
      The result of this tutorial will be a form where you can select a physical location. After you made your selection, only those rooms for that building will be shown.
      Again, i covered this into a lot of steps. But after you have done this a couple of times, you do not need expensive software and you can create filtered lookup forms yourself!

      1. Create a Custom list called ‘buildings’.
        A Custom list is created with no extra columns except for ‘title’. We leave it like that.
      2. Add buildings to the list: ‘Building A’, ‘Building B’ and ‘Building C’.
      3. Create another Custom list called ‘rooms’.
      4. Go to the list settings of ‘rooms’ and click on ‘create column’. Create a Lookup column called ‘Building’.
        Require that the column contains information.
        Get information from: ‘Buildings’,  in this column: ‘Title’
      5. Add some rooms to this list. I created multiple rooms at each location.
      You have now created the needed lists and filled it with data, but we still need to create the room reservation form.
      1. Again, create a new Custom list called ‘reservations’.
      2. Click on ‘Create column’ and create a Lookup column called ‘Building’. Get information from: ‘buildings’,  in this column: ‘Title’
      3. Repeat step 2, but this time create a Lookup column called ‘Room’. Get information from: ‘rooms’,  in this column: ‘Title’
      4. Use Internet Explorer: Open the list settings for ‘reservations’ and click on ‘Form settings’.
        You will see a label with the text ‘Customize the current form using Microsoft InfoPath’. Click OK.
      5. The Reservations form will now be opened in InfoPath 2010.
      6. Right click on the Building field, and select properties.
        Select ‘Get choices from an external data source’ and click ‘Add…’.
        Create a connection with the following settings:
        - New connection, receive data
        - Receive data from: SharePoint library or list
        - select ‘buildings’ library
        - select the ‘id’ and ‘title’ column
        - do not check the box for making a copy of the data
        - check the box that asks for automatically retrieving data when the form is opened. Save the external data source as ‘buildings1′.
      7. At value, choose ‘ID’ and at display name, choose ‘Title’
      8. Right click on the Room field, and select properties.
        Select ‘Get choices from an external data source’ and click ‘Add…’.
        Create a connection with the following settings:
        - New connection, receive data
        - Receive data from: SharePoint library or list
        - select ‘rooms’ library
        - select the ‘id’, ‘title’ and ‘building’ column
        - do not check the box for making a copy of the data
        - do not check the box that asks for automatically retrieving data when the form is opened. Save the external data source as ‘rooms1′.
      9. At value choose ‘id’, choose ‘Title’ for  the display name.
      You are not done yet, but almost there! A little break here, to tell you what you have done in the last few steps. You created 2 data connections, retrieving data from the SharePoint lists ‘buildings’ and ‘rooms’. The data connection for buildings will load its data into the buildings form when the form is being opened. The other one won’t. Check it out, press ctrl+shift+Q for a fast publish and add a new item to the registration list. If all went well you will see something like this:

      The Room listbox should not yet contain any data.
      Now we are going to execute the final steps. In these steps you will create a filter. This filter will show only rooms for the building you selected in the field above.
      1. Click on the xPath button at the properties dialog of Room next to ‘Entries’.
        Click on the ‘Filter data’ button.
      2. Click on ‘Add’.
        In the first column, choose ‘select a field or group’. A window pops up, choose advanced view.
        - Select the ‘main’ datasource, click on ‘dataFields’ and select ‘Building’.In the second column, choose ‘equals’.In the third column, choose ‘select a field or group’. Agan a window pops up, choose advanced view.
        - Select the ‘rooms’ datasource, click on ‘dataFields’ and select ‘Building’.
        Click OK
      3. The filter will now look like ‘Building equals Building’. Now close all property dialogs.
      4. Select the building column and click on ‘Add Rule’. Select the query action when the field is changed.

        Now choose the data connection ‘rooms1′ and click OK.
      5. Again, click Building and make a new rule: When the field is being changed, set a value for a field.

        Choose field ‘Room’ and leave value empty.
      Finally! We are done. Fast publish the form to SharePoint again by pressing ctrl+shift+Q.
      Now if you carefully executed all steps above, you will see a form like this:

      Notice that only rooms will be shown that are located in that specific building.

      SharePoint - Cannot convert a primitive value to the expected type 'Edm.Double'. See the inner exception for more details If y...

      Ad