Rakesh Kumar Jayswal's Blogs
SharePoint Developer & Office 365 Consultants
Sunday, 5 May 2019
Saturday, 25 February 2017
Web Part life cycle in SharePoint 2010
OnInit
In this event the configuration values can be set using a property bag and those that are in the web part task pane are loaded into the web part.
protected override void OnInit(EventArgs e)
{
}
LoadViewState
The view state of the web part is populated here.
protected override void LoadViewState(object savedState) //Only at Postback
{
}
OnLoad
This event is for loading the WebPart such as adding controls.
protected override void OnLoad(EventArgs e)
{
}
CreateChildControls
In this routine control properties and methods previously declared are defined. In most cases, we have to initialize the control's default value (such as Text, Checked, Items, and so on) and activity that is possible to call just at first WebPart load, checking PostBack. The controls specified are created and added to the controls collection. When the page is being rendered for the first time the method generally occurs after the OnLoad() event. In the case of postback, it is called before the OnLoad() event. We can make use of EnsureChildControls() - It checks to see if the CreateChildControls method has yet been called, and if it has not, calls it.
protected override void CreateChildControls()
{
}
OnPreRender
Here we can change any of the web part properties before the control output is drawn. This is the routine where the control's value is kept for the View State.
protected override void OnPreRender(EventArgs e)
{
}
Render
HTML Output is generated.
protected override void Render(HtmlTextWriter writer)
{
}
OnUnload
This is executed when the web part is unloaded.
protected override void OnUnload(EventArgs e)
{
}
Dispose
This to free the memory.
public override void Dispose()
{
}
SharePoint 2010 Web part Life Cycle
Following Life cycles are available in SharePoint 2010.
There are four predefined routines that take place in a WebPart Life Cycle,
- OnInit
- CreateChildControls
- OnPrerender
- Render
OnInit: This method handles initialization of the control.
Example
- protected override void OnInit(EventArgs e)
- {
- try
- {
- _divPanel = new Panel();
- _ddlCountry = new DropDownList();
- _ddlTown = new DropDownList();
- }
- }
OnLoad: This event handles the Load event and also used for initialize the control. But it is not intended for loading data or other processing functionality.
CreateChildControls: This creates any child controls.
In most cases, we have to initialize the control's default value (as Text, Checked, Items, and so on) and activity that is possible to call just at first WebPart load, checking PostBack:
Example
- protected override void CreateChildControls()
- {
- try
- {
- base.CreateChildControls();
- _divPanel.ID = "_divPanel";
- _divPanel.BorderStyle = BorderStyle.Ridge;
- _divPanel.Width = 250;
- _divPanel.Height = 300;
- _divPanel.BackColor = System.Drawing.Color.Gainsboro;
- Controls.Add(_divPanel);
- }
- }
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.This is the routine where the control's value kept by ViewState (for example Item value set up by the user to DropDownList nation), is available.
For this reason, it's normal to begin business procedure from here, and in our case we're going to load values for the second dropdown list (Town DropDownList) with the proper data.
Page.PreRenderComplete: The page fires the PreRenderComplete event after all controls have completed their OnPreRender methods.
Render: This method is used to render everything.That's the routine for HTML rendering WebPart.
RenderContents: Renders the contents of the control only, inside of the outer tags and style properties.
OnUnload: Performs the final clean up.
where/When/Why FormDigest Control: SharePoint
FormDigest Control:
Every SharePoint developer should know about the “FormDigest” control. Especially who are developing master pages, site pages and application pages?
I am going to cover in which areas FormDigest control use:
- What is FormDigest Control?
- Why every master page should have “FormDigest” control and what is the need?
- The security validation for this page is invalid?
- When/where/why use "AllowUnsafeUpdates" in SharePoint?
- How to do manipulation to the SharePoint data programmatically?
What is FormDigest control?
A FormDigest control has to be included to create a digest for security validations when performing some modifications to SharePoint data. It adds a security token inside your page based on user, site and time. Once the page is posted back the security token is validated. Once the security token is generated it’s valid for a configurable amount of time.
For reasons of security, by default, Microsoft SharePoint Foundation does not allow you to make posts from a Web application to modify the contents of the database unless you include security validation on the page making the request. You can update data for a single site or for a site collection by adding a page directive and a FormDigest control to the page that makes the request.
Note: Main reason why “FormDigest” control introduced is to prevent sites from cross-site scripting attacks and to do validations.
By default, default.master [v4.master in SharePoint 2010] has a “FormDigest” control. Need of it is to prevent pages from the cross-site scripting attacks.
To get the content from the content DB, we need to set the AllowUnsafeUpdates = true.
To set the content to the content DB, not required to set the AllowUnsafeUpdates = true. why means because of "FormDigest" control placed in every master page.
To get the content from the content DB, we need to set the AllowUnsafeUpdates = true.
To set the content to the content DB, not required to set the AllowUnsafeUpdates = true. why means because of "FormDigest" control placed in every master page.
Why every master page should have “FormDigest” control and what is the need?
I guess everyone already knows about what is master page, why we can use it and what is the need of it right? Fine. I have developed some pages and through all my pages I am doing modifications to the SharePoint data [means content DB]. But it’s not the good practice to do manipulations directly on content DB without validating our content is safe or not? If you still try to do manipulations without validating your data, you may get the “The security validation for this page is invalid” exception.
Let’s come back to our topic; so, what will we do and how we can check our updating data is valid or not? Don’t worry; SharePoint has already given up the solution on it. The solution is “FormDigest” control. The “FormDigest” control will do all these validations. In the above I already explain what “FormDigest” control is. Read it again, now you can get it clearly.
To do manipulations on content DB directly with security validation we have to put the “FormDigest” control in all the pages. Here again we have to think is this appropriate to add “FormDigest” control in each page? So, Instead of placing the “FormDigest” control in each page, it’s better to place that control in master. The SharePoint team thought about it too smart right? That’s why they already added “FormDigest” control in all master pages in SharePoint?
But, some situation we should do manipulations to the SharePoint data even the data is not safe. So, how can we do manipulations and how we can avoid from above exception? Don’t worry here also SharePoint thought about very smart; the solution is “AllowUnsafeUpdate”.
Best technical word to say about "FormDigest" Control is:
To make posts from a Web application that modify the contents of the database, you must include theFormDigest control in the form making the post.
The key piece of information I found in here was the following line: "The security validation is specific to a user, site, and time period and expires after a configurable amount of time."
Best technical word to say about "FormDigest" Control is:
To make posts from a Web application that modify the contents of the database, you must include theFormDigest control in the form making the post.
The key piece of information I found in here was the following line: "The security validation is specific to a user, site, and time period and expires after a configurable amount of time."
As per msdn article “AllowUnsafeUpdates” is set to true when you are trying to update the database as a result of the GET request”. Refer to know more what/why/where on “AllowUnsafeUpdate”.
Friday, 24 February 2017
SharePoint Interview Questions and Answers: WebPart
Webparts:
Web Parts are reusable components that display content on Web pages in SharePoint 2010.
A fantastic new feature in SharePoint 2010 is that you can insert a Web Part in the text of one of the Rich Text Editor zone available in the new Wiki Page. (To add, remove, or rearrange the text zones, use the "Text Layout" menu in edit mode)
When you create a team site, the home page is a wiki page. You should be able to move the web parts by Editing (Page tab > Edit) then drag/dropping the web parts to where you'd like them to go. The wiki page won't really have web part zones, but instead you can choose a "Text Layout" to arrange your page as desired. Again you can drag and drop between the layout zones.
Also, when inserting a web part, the web part is added where your cursor is. To make sure you have it in the correct location, open the web part adder first (Edit Page > Insert Tab > Web Part), then click on the page where you want it to go, and then click Add in the web part adder.
Also, when inserting a web part, the web part is added where your cursor is. To make sure you have it in the correct location, open the web part adder first (Edit Page > Insert Tab > Web Part), then click on the page where you want it to go, and then click Add in the web part adder.
Remember points:
We can dropped webparts into anywhere inside the main content area, without having to put it into a WebPartZone (This is all happening behind-the-scenes through a dynamic zone that pushes Webparts into placeholders).
Difference Between .dwp and .webpart
- Dwp was the file extension used in version 2 of SharePoint and .webpart is a new extension used in version 3
- Version number on the xmlns attribute is different [2->2003, 3-> 2007]
- The main difference is that all properties passed to the web part are specified with a property element and a name attribute in version 3. Version 2 uses different element names for everything.
Reference:
Visual Webparts:
- The new important feature introduced in SharePoint on webparts is Visual webpart. It’s a combination of user control (.ascx) and assembly (.dll)
- Since a Visual Web Part loads a User Control (.ascx) from the SharePoint Root it needs access to run the ASP.NET method LoadControl and file system access to the ControlTemplates folder in the SharePoint Root – and this is not allowed by a Sandboxed Solution.
- Visual webpart cannot be deploying using sandbox solutions.
Visual sandboxed web part:
The Microsoft Visual Studio team has released the Visual Studio 2010 SharePoint Power Tools. These tools extend the existing SharePoint 2010 project templates and provide the Sandboxed Visual Web Part template that enables you to create Web Parts that can be deployed as sandboxed solutions. The use of these templates also enables designer support for designing the Web Parts.
Difference between asp.net webparts and SharePoint webparts?
ASP.NET Web Parts:
These Web Parts are built on top of the ASP.NET Web Part infrastructure. The ASP.NET-style Web Parts have a dependency on System.Web.dll and must inherit from the WebPart base class in the System.Web.UI.WebControls.WebParts namespace.
These Web Parts can be used in ASP.NET applications as well as in SharePoint Foundation, making them highly reusable.
SharePoint-based Web Parts:
These Web Parts have a dependency on Microsoft.SharePoint.dll and must inherit from the WebPart base class in the Microsoft.SharePoint.WebPartPages namespace.
These Web Parts can only be used in SharePoint Web sites.
Webpart life cycle:
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.
When the page is being rendered for the first time the method generally occurs after the OnLoad() event. In case of postback, it is called before the OnLoad() event. We can make use of EnsureChildControls() - It checks to see if the CreateChildControls method has yet been called, and if it has not, calls it.
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.
Webpart maintenance page
- A webpart which is causing a problem in a webpart page can be removed using this page. Basically, a Webpart Maintenance page provides the list of all webparts added in a particular page and options to close or remove these webparts.
- Use of it: Sometimes after adding a webpart to the page, we get an error page with some message. But in this error page we won’t get any SharePoint controls (like the SiteActions, Ribbon Menu etc.,), so we cannot edit the page and remove the webpart. Then we usually go to the edit form of the page (through page library) and then click on the 'Open Web Part Page in maintenance view' link, which opens the WebPart Maintenance page to remove the webpart which is causing the problem.
- Shortcut to open:
- Instead of going to the Edit Properties form of the page, we can easily open the WebPart Maintenance page by just adding the following query string to the page URL : ?contents=1
- So, if your page URL is 'http://rams/pages/default.aspx' then after appending the query string it should look like ' http://rams/pages/default.aspx?contents=1'
- Using this approach, we can open the webpart maintenance page for all the forms pages (like /pages/forms/allitems.aspx?contents=1). But it’s not safe to remove or add any webparts in these pages, as they may affect the normal functionality.
- Note: This approach works on both MOSS 2007 and SPS 2010.
Difference web parts visual web parts and traditional web part?
- The advantage of Web User Control is that you can use Visual Web Developer to design the web user control and in normal web parts all controls are created in the code itself i.e. on “CreateChildControls” method only.
- Adding Web Part properties is cumbersome for Visual Web Parts as compared to traditional Web Parts. As you develop Web Parts, many times you will want to expose their properties so that users and administrators can supply the values for those properties.
- Differences in Web Part Connections: This is easily achieved in a traditional Web Part because the logic code is contained in the Web Part itself.
- Differences when Extending a Web Part: You can extend the traditional Web Part by inheriting from the WebPart class. You can then reuse the base Web Part functionality and extend it as desired. Visual Web Parts cannot be extended. Because this Web Part is a wrapper around a user control, it just contains the code to load the user control; the bulk of the Web Part code resides in the code-behind file of the user control.
- Differences in Performance and Memory Footprint: Visual Web Parts have slightly larger memory footprints than code-only Web Parts. Visual Web Parts contain more parts (Web Part, user control) than traditional Web Parts.
- Refer the below msdn article to get a clear idea:
Main webpart base classes:
There are two base classes that a WebPart which is going to be consumed by SharePoint can inherit from, either the SharePoint WebPart Base class or the ASP.NET 2.0 WebPart base class. When inheriting from the SharePoint WebPart Base class your derived WebPart class will inherit from Microsoft.SharePoint.WebPartPages.WebPart. When inheriting from the ASP.NET 2.0 WebPart base class your derived WebPart class will inherit from System.Web.UI.WebControls.WebParts.WebPart. It is considered good practice to use the ASP.NET WebPart base class since the old base class is meant for backwards compatibility with previous version of SharePoint however there are four exceptions when it is better to leverage functionality from the SharePoint WebPart base class:
- Cross page connections
- Connections between Web Parts that are outside of a Web Part zone
- Client-side connections (Web Part Page Services Component)
- Data caching infrastructure.
Note: If you create a webpart in SharePoint 2010 by default it is inheriting from Asp.Net webpart base class.
A Web Part or Web Form Control on this Page cannot be displayed or imported. The type is not registered as safe.”
The reason for this error is if we modify default namespace into custom namespace, Visual Studio 2010 Package is not generating webpart file properly.
Make sure your webpart is added into Safe Control list in Web.config file.
Open your .webpart file in your visual studio - Make sure type element name has proper namespace & class name.
Open your .webpart file in your visual studio - Make sure type element name has proper namespace & class name.
When you made changes to default name space which is being generated by visual studio, you may not see updated namespace in type element. So make sure your webpart name space name & webpart class name placed correctly in type element's name attribute
Access http://server/_layouts/newdwp.aspx page and make sure webpart exist. If webpart not shown in the list, still your webpart name space/classname not matches to your safe control entry in web.config file.
Access http://server/_catalogs/wp/Forms/AllItems.aspx . By clicking on webpart opens webpart in webpart preview page.
Add Web Part inside a Master Page in SharePoint 2010?
I have added the webparts in masterpage successfully by referring the below post. Thanks, SharePoint King.
Note: we cannot add webpart zones to the master page.
Out of box webparts in SharePoint?
Below are my best references to get knowledge on out of box webparts.
Some of important OOB features are listed below:
CQWP:
CQWP:
- The Content Query Web Part is a very handy tool in SharePoint Standard and SharePoint Enterprise only i.e. not available at SharePoint Foundation.
- The CQWP is used to display the content by querying, filtering and sorting.
- The CQWP can fetch the data based on content types.
- By default, we can group and sort by only one field.
- Minimum designer level permissions required.
- CQWP is part of a bundle of features called “SharePoint Server Publishing Infrastructure”.
- The Content Query Web part cannot fetch data across site collections. If you really need it, you can take a look at the Lightning Conductor Web Part.
- Ref: http://sharepointlogics.com/2012/03/how-to-use-content-query-webpart-in.html
DVWP:
- A Data View Web part is a great way to display data with filtering, grouping, and user desired formatting.
- SharePoint Designer is required for developing DVWP.
- DVWP can fetch data from data sources other than lists like xml files.
- DVWP can fetch data from other site collection.
- DVWP can merge data from more than one list.
CQWP:
- The Content Editor Web Part (CEWP) allows you to add text, html, scripts or styles to a SharePoint page.
XSLT list Web part:
- Introduced in SP2010.
- In SharePoint 2010, all views in lists and libraries are XSLT list view web parts. This means that you can edit views from the browser or from SharePoint Designer 2010.
CSWP:
- Introduced in SP 2013.
- The Content Search Web Part (CSWP) is a Web Part that displays search results based on a search query.
Difference between user control and webpart?
Webparts are like user controls, user controls are added in code but webparts are added at runtime.
The advantage of Web User Control is that you can use Visual Web Developer to design the web user control and in normal web parts all controls are created in the code itself i.e. on “CreateChildControls” method only.
The advantage of Web User Control is that you can use Visual Web Developer to design the web user control and in normal web parts all controls are created in the code itself i.e. on “CreateChildControls” method only.
User Control
|
Web Part
|
User controls are based on Microsoft ASP.NET, and most developers are familiar with developing user controls. This improves productivity.
|
In general, developers are not familiar with creating child controls by writing the code from scratch.
|
User controls can be used with ASP.NET -based solutions. If you decide later to convert a project containing a user control to an ASP.NET -based solution, you should be able to use the control without making any changes.
|
Web Parts can be used in ASP.NET -based solutions only when the solution uses Web Parts pages.
|
The Visual Web Developer designer provides support for designing the UI by using drag-and-drop operations that gives the control a consistent look-and-feel, which results in faster development.
|
The controls in Web Parts must be added by using code.
|
User controls must be compiled before use, which adds to the time it takes to load the control.
|
Web Parts are precompiled and ready for use as soon as you need them.
|
Subscribe to:
Posts (Atom)