Search This Blog

Sunday, July 13, 2014

SharePoint Server Object Model Code Snippet(SP Interview)

Below are  sample code snippets using SharePoint Object model, probably use full for some people who wants to learn SharePoint Server Object model
• Creating a subsite
SPWeb mySite = SPContext.Current.Web;
SPWebCollection mySiteCollection = mySite.Webs;
uint lcid = mySite.Language;
string templateName = "WIKI#0";
mySiteCollection.Add("Nani Site", "Nani", "Site Created using object model", lcid, templateName, false, false);
mySite.Dispose();
 Creating a list
SPSite mySiteCollection = SPContext.Current.Site;
SPWeb mySite = mySiteCollection.OpenWeb();
SPListCollection myListCollection = mySite.Lists;
myListCollection.Add("Niru6", "created using object model",SPListTemplateType.Contacts);
 Show all top level sites in farm
SPWebServiceCollection myservices = new SPWebServiceCollection(SPFarm.Local);
foreach (SPWebService myservice in myservices)
{
SPWebApplicationCollection myWebAppCollection = myservice.WebApplications;
foreach (SPWebApplication mywebApp in myWebAppCollection)
{
SPSiteCollection mySiteCollection = mywebApp.Sites;
SPSite mySite = mySiteCollection[0];
Label1.Text += mySite.RootWeb.Url + "";
}
}
• Return the collection of site collections in a SharePoint Web application
SPWebApplication myWebApp = SPContext.Current.Site.WebApplication;
SPSiteCollection mySiteCollection = myWebApp.Sites;
foreach (SPSite mySite in mySiteCollection)
{my
Label1.Text += mySite.RootWeb.Title + "";
mySite.Dispose();
}
 To return the collection of The all the Webs or sites within a site collection, including the top-level site and all subsites
SPWebApplication myWebApp = SPContext.Current.Site.WebApplication;
SPSiteCollection mySiteCollection = myWebApp.Sites;
foreach (SPSite mySite in mySiteCollection)
{
SPWebCollection myWebCollection = mySite.AllWebs;
foreach (SPWeb myWeb in myWebCollection)
{
Label1.Text += mySite.Url + " " + myWeb.Title + "";
myWeb.Dispose();
}
mySite.Dispose();
}
• To return the all the subsites and lists of the current site
SPSite mySite = SPContext.Current.Site;
SPWebCollection myWebCollection = mySite.AllWebs;
foreach (SPWeb myWeb in myWebCollection)
{
SPListCollection myListCollection = myWeb.Lists;
foreach (SPList myList in myListCollection)
{
Label1.Text += myWeb.Title +" " + myList.Title + "";
}
myWeb.Dispose();

}
• Show all roles in a site
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.RootWeb;
SPRoleDefinitionCollection myRoleCollection = myWeb.RoleDefinitions;
foreach (SPRoleDefinition myRole in myRoleCollection)
{
Label1.Text += myRole.Name + "";
}
• Show all alerts in a site
SPWeb mySite = SPContext.Current.Web;
SPAlertCollection myAlertCollection = mySite.Alerts;
foreach (SPAlert myAlert in myAlertCollection)
{
Label1.Text += myAlert.Title + "";
}
• Show all lists in a site
SPWeb mySite = SPContext.Current.Web;
SPListCollection myListCollection = mySite.Lists;
foreach (SPList myList in myListCollection)
{
Label1.Text += myList.Title + "";
}
• Show all list templates in a site
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.RootWeb;
SPListTemplateCollection myTemplateCollection = myWeb.ListTemplates;
foreach (SPListTemplate myTemplate in myTemplateCollection)
{
Label1.Text += myTemplate.Name + " " + myTemplate.Type + "";
}
• Show all fields in a list
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.RootWeb;
SPList myList = myWeb.Lists["Niru3"];
SPFieldCollection myFieldCollection = myList.Fields;
foreach (SPField myField in myFieldCollection)
{
Label1.Text += myField.Title + "";
}
• Show all items in a list column
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.RootWeb;
SPList myList = myWeb.Lists["Niru3"];
SPListItemCollection myItemCollection = myList.Items;

foreach (SPListItem myItem in myItemCollection)
{

Label1.Text += myItem["Last Name"].ToString() + "";

}
 Delete all items from a list
When using a for Loop, if you wish to remove an item from the collection you are iterating through it can be done very easily. When using foreach you will get an exception stating that the item cannot be removed
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.RootWeb;
SPList myList = myWeb.Lists["Niru3"];
for (int i = myList.Items.Count - 1; i >= 0; i--)
{
myList.Items.Delete(i);
}
• Show all groups in a site
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.RootWeb;
SPGroupCollection myGroupCollection = myWeb.Groups;
foreach (SPGroup myGroup in myGroupCollection)
{
Label1.Text += myGroup.Name + "";

}
• Delete a item in a list based on condition
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.RootWeb;
SPList myList = myWeb.Lists["Niru3"];
for (int i = myList.Items.Count - 1; i >= 0; i--)
{
if (myList.Items[i]["Last Name"].ToString() == "Nani")
{
myList.Items.Delete(i);
}

}
• Show all users in a group
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.RootWeb;
SPGroupCollection myGroupCollection = myWeb.Groups;
SPGroup myGroup = myGroupCollection["Viewers"];
SPUserCollection myUserCollection = myGroup.Users;
foreach (SPUser myUser in myUserCollection)
{
Label1.Text += myUser.Name + "
";
}
• Show all users from all groups from user collection
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.RootWeb;
SPGroupCollection myGroupCollection = myWeb.Groups;
foreach (SPGroup myGroup in myGroupCollection)
{
SPUserCollection myUserCollection = myGroup.Users;
foreach (SPUser myUser in myUserCollection)
{
Label1.Text += myGroup.Name + "" + myUser.Name + "";
}

}
 Show only blog sites
SPSite mySite = SPContext.Current.Site;
SPWebCollection myWebCollection = mySite.AllWebs;
foreach (SPWeb myWeb in myWebCollection)
{
if (myWeb.WebTemplate == "BLOG")
{
Label1.Text += myWeb.Title + "" ;
}
myWeb.Dispose();

}
• Show services and status in sharepoint server farm
SPFarm myFarm = SPFarm.Local;
SPServiceCollection myServiceCollection = myFarm.Services;
foreach (SPService myService in myServiceCollection)
{
Label1.Text += myService.Name + " " + myService.Status + "
";
}
• To get the timer jobs history for a particular service in the SharePoint 2010 farm
SPFarm myFarm = SPFarm.Local;
SPServiceCollection myServiceCollection = myFarm.Services;
foreach (SPService myService in myServiceCollection)
{
if (myService.DisplayName == "My Sample Service")
{
foreach (SPJobHistory entry in myService.JobHistoryEntries)
{
Label1.Text += "Job Definition Title - " + entry.JobDefinitionTitle + " : Status - " + entry.Status + " : Start Time - " + entry.StartTime + "
";
}

}
}
• Get content database for all site collections
SPWebServiceCollection myWebServiceCollection = new SPWebServiceCollection(SPFarm.Local);
foreach (SPWebService myWebService in myWebServiceCollection)
{
SPWebApplicationCollection myWebApplicationCollection = myWebService.WebApplications;
foreach (SPWebApplication myWebApplication in myWebApplicationCollection)
{
SPContentDatabaseCollection myContentDatabaseCollection = myWebApplication.ContentDatabases;
foreach (SPContentDatabase myContentDatabase in myContentDatabaseCollection)
{
Label1.Text += myContentDatabase.Name + "
";
}
}

}
• Add fields to list and add it to default view
SPWeb mySite = SPContext.Current.Web;
SPList myList = mySite.Lists.TryGetList("Niru2");
SPFieldCollection myFieldCollection = myList.Fields;
string strNewFieldName = myFieldCollection.Add("Native Place", SPFieldType.Text, false);
SPField oField = myFieldCollection.GetField(strNewFieldName);
SPView oView = myList.DefaultView;
SPViewFieldCollection colViewFields = oView.ViewFields;
colViewFields.Add(oField);
oView.Update();
• Creating a new view in a list
SPWeb mySite = SPContext.Current.Web;
SPList myList = mySite.Lists.TryGetList("List_Name");

SPViewCollection myViewCollection = myList.Views;
string strViewName = "View_Name";
System.Collections.Specialized.StringCollection collViewFields = new System.Collections.Specialized.StringCollection();
collViewFields.Add("Field1_Name");
collViewFields.Add("Field2_Name");
collViewFields.Add("Field3_Name");
string strQuery = "" +
"1000";

myViewCollection.Add(strViewName, collViewFields, strQuery, 100, true, false,
Microsoft.SharePoint.SPViewCollection.SPViewType.Grid, false);
• Creating a new content type and add it to a list, Adding the existing site columns to existing content type
- Check for duplicate content type, field, and list names.
- Create a new site content type.
- Add the content type to the site collection
- Create a site field to link to
- Link the content type to the field
- Commit changes to the database
- Create a list
- Apply the new content type to the list
o Add the new content type
o Remove the default content type
o Commit changes to the list
• Delete recycle bin items
SPSite site = new SPSite(<>);
SPWeb web = site.RootWeb;
SPRecycleBinQuery q = new SPRecycleBinQuery();

q.RowLimit = Int32.Parse(<>);
q.OrderBy = SPRecycleBinOrderBy.Default;
SPRecycleBinItemCollection itemColl = web.GetRecycleBinItems(q);
foreach (SPRecycleBinItem item in itemColl)
{
Guid[] id = new Guid[1];
id[0] = item.ID;
itemColl.Delete(id);
}
Source: MSDN
• creating folder, uploading file to folder, deleting folder searching the folder in a doc lib
Refer to MSDN
Use about AllowUnsafeUpdates  :Refer this link
About Disposing objects :link
My Notes :
* (SPSite -> AllWebs)The AllWebs property of the SPSite class returns all the Web sites within a site collection, including the top-level site and all subsites.
* (SPWeb ->webs) To return a list of all the first-tier subsites beneath a specific Web site, use the Webs property of the SPWeb class.
* (SPWeb) openweb – return the site that is associated with the url that is used in SPSite constructor
* To return the collection of site collections in a SharePoint Web application, use the Sites property of the Microsoft.SharePoint.Administration.SPWebApplication class. Use properties of the Microsoft.SharePoint.SPContext class to return the current Web application.
* (SPWeb ->RootWeb)To return the top-level Web site of the current site collection, use the RootWeb property.
* close method — Closes the website at the end of a request and releases resources.
* Dispose method — Releases all resources used by the current instance of the website.
*  To Get the web site where the feature is activated.
SPWeb parentWeb = properties.Feature.Parent as SPWeb;
* when we use Rootweb and SPContext ie No explicit  dispose required.
Leave a comment
Posted by  on January 26, 2014 in SharepointSP Interview

How to Create User Control in SharePoint 2010 and insert into Pages, Masterpages,and in webparts.

User controls are rapid way to develop custom functionality. There are three steps involved in creating user controls. This article walks through step by step on creating user controls in SharePoint 2010 which displays currently logged in user.
  1. Create and deploy user control
  2. Register user control in the target
  3. Insert the user control wherever required.
Step 1: Create and deploy user control
1. Fire up visual studio 2010, Create a new Empty SharePoint Project.
2. Add an user control to the Project, say “MyUserControl”, Project structure will look like this:
sharepoint 2010 create user control
3. Lets build the control now. Go to the code view, Insert a <DIV> and label. Set some CSS styles as like this:
?
1
2
3
<div id="Main" style="border:1; background-color:#2C84CA; font-size: 25px; color:White;">
    <asp:Label ID="lblUserName" runat="server" Text="0"></asp:Label>
</div>

4. The idea is: Lets display the currently logged in user name in the label. Get in to the code behind file (.cs) add this little code.
?
1
2
3
4
5
6
7
8
9
10
11
namespace MyUserControl.ControlTemplates.MyUserControl
{
    public partial class MyUserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string currentUser = "Current User Name:" + SPContext.Current.Web.CurrentUser.Name;
            lblUserName.Text = currentUser;
        }
    }
}
?
1
SharePoint 2010 user control code behind
sharepoint 2010 user control code behind
5. Deploying user control in SharePoint 2010: Build and deploy the project. This will create new folder in 14 hive’s Controltemplate’s folder (In my case it was: \14\TEMPLATE\CONTROLTEMPLATES\MyUserControl\MyUserControl.ascx)

Step 2: Register user control in the target

We have our user control ready now. Next step is insert the user control wherever needed. Here, Lets add it to a SharePoint page. say, Default.aspx. By the way, You can load the user control wherever you want, like in Pages, Master pages, Page layouts, and even in Web parts (use Page.LoadControl method)

SharePoint 2010 add user control to page

1. Open SharePoint designer, Open the target site, and then Default.aspx in advanced mode.
2. Register the user control at the top of the page.
<%@ Register TagPrefix=”MyUserControl”  TagName=”UserName” Src=”~/_controltemplates/MyUserControl/MyUserControl.ascx” %>
sharepoint 2010 add user control master page 

Step 3: Insert the user control wherever required.

We’ve created user control for SharePoint 2010, Registered it on the page. Now, the final step is to  include the user control in the page, Here I’ve coded like:
<MyUserControl:UserName id=”MyUserControl1″ runat=”server” />
sharepoint 2010 deploy user control
That’s all! See it in action: SharePoint 2010 user control example. Similar method applies to add user control to SharePoint 2010 master page.
sharepoint 2010 user control example
Leave a comment
Posted by  on January 9, 2014 in SharepointSP Interview

Creating Custom Timer Jobs programatically in SharePoint 2010

What is a Timer Job?

A Timer Job is a periodically executed task inside SharePoint Server. It provides us a task execution environment.

Default Timer Jobs inside SharePoint

There are many timer jobs inside SharePoint which do internal tasks like:
  • Send emails
  • Validate sites
  • Delete unused sites
  • Health analysis
  • Product versioning
  • Diagnostics
These tasks will having execution periods like:
  • Minute
  • Hour
  • Day
  • Week
  • Month
The purpose of this timer job is to add an item to a list for every 5 min.

There are some prerequisites before proceeding further.
1. The user should have Administrator privileges to deploy the timer job into Central Admin.
2. Create a list with the name “TimerJobList” in the site in which you are going to deploy the solution.
Please find the steps to create the custom timer job.
Step 1: Open Visual Studio 2010 >File > New >Project >SharePoint 2010>Empty SharePoint Project. >Name it Custom_TimerJob>Ok
Step 2: Specify the site and security level for debugging
Step 3: Create a class with the name “waiinTimer” that inherits from the “Microsoft.SharePoint.Administration.SPJobDefinition” class. To implement this class, we need to create a few constructors and override the Execute() method as following .12-12-2013 12-16-31 PM
Step 4: Now that you have the job built> Right click on the Features >Add Feature
Right click on the Feature1 ” you can rename the Feature1 to any name” > Add Event Receiver
Step 5: the event Receiver class inherits from the “Microsoft.SharePoint.SPFeatureReceiver” and This class handles events raised during feature activation, deactivation as following
using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Administration;
namespace Custom_TimerJob.Features.Feature1
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>
    [Guid("114e3935-3594-42d5-aa34-1c532b30539a")]
    public class Feature1EventReceiver : SPFeatureReceiver
    {
        const string List_JOB_NAME = “List Timer Job”;
        // Uncomment the method below to handle the event raised after a feature has been activated.
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;
            // make sure the job isn’t already registered
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {
                if (job.Name == List_JOB_NAME)
                    job.Delete();
            }
            // install the job
            List_TimerJob listLoggerJob = new List_TimerJob(List_JOB_NAME, site.WebApplication);
            SPMinuteSchedule schedule = new SPMinuteSchedule();
            schedule.BeginSecond = 0;
            schedule.EndSecond = 59;
            schedule.Interval = 5;
            listLoggerJob.Schedule = schedule;
            listLoggerJob.Update();
        }
        // Uncomment the method below to handle the event raised before a feature is deactivated.
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;
            // delete the job
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {
                if (job.Name == List_JOB_NAME)
                    job.Delete();
            }
        }
    }
}
Step 6: Before Deploying you should select the scope of the Feature in other words in which scope you will activate the Feature(Farm,Site,Web,WebApplication). In our case we will activate Feature1 on Site which means Site Collection.
Note:if u r trying to dploy feature with wrong scope they will give u error. Change Scope…
 
Open now your SharePoint site and select ListTimerJob List and you should see something similar to the following image
Our custom timer job is working fine now you can go and check it and modify the schedule as following
Go to SharePoint 2010 central administration >Monitoring >in the Timer Jobs Section Select Review Job Definitions
and you should See our Custom Timer Job
 
Click on it and you should see Edit Timer Job Page ,Modify Timer Job schedule based on your requirement
In this article we have explored the Timer Job feature of SharePoint and creating a custom timer job.  Following are the key points to be remembered:
  • Timer Jobs can be scheduled for automating jobs inside SharePoint 2010
  • SPJobDefinition is the base class for Timer Job
  • Create Event Receiver Feature to create or delete the timer job
  • SPFeatureReceiver is the base class for the event receiver
  • The feature gets deployed in the 14hive folder
  • OWSTIMER.EXE is the process executing Timer Jobs
Note : you can also modify schedule of your custom Timer Job from the code but you need to add one of the following class in FeatureActviated Event Handler as following
After Specific Minutes use SPMinuteSchedule class
Hourly use SPHourlySchedule class
Daily use SPDailySchedule class
Weekly use SPWeeklySchedule class
Monthly use SPMonthlySchedule class

What is the difference between stsadm and powershell?

In SharePoint 2007 administration commands were executed by command utility called STSADM. In 2007 version of MOSS PowerShell was not integrated into the SharePoint platform.
In SharePoint 2010 PowerShell is largely integrated. STSADM is still supported but mainly for backward compatibility.
PowerShell:
The Windows PowerShell Integrated Scripting Environment offers a lot of debugging possibilities like setting breakpoints, step by step debugging, etc. If you’re working with Visual Studio, these debugging possibilities are very useful.PowerShell is Microsoft’s next-generation scripting language offering direct access to .NET objects, complex flow and structure capabilities.
SharePoint 2010 Management Shell is just a PowerShell instance that loads the sharepoint.ps1 script file.
STSADM is still present in SharePoint 2010, but its prominence has been greatly reduced as it is extremely limited. Using STSADM, Conditional logic was difficult to achieve using batch files. If no command was available to manipulate a setting, a custom command would have to be created. And performance was poor because of the inability to re-use objects across command calls.
STSADM Commands
1) To add solution to the Farm:
stsadm –o addsolution –filename “C:\Deployment\MySharePointSolutionPackage.wsp
2) To deploy the solution
stsadm –o deploysolution –name MySharePointSolutionPackage.wsp –url http://webapplication/ –allowgacdeployment –immediate
3) To upgrade a solution
stsadm –o upgradesolution –name MySharePointSolutionPackage.wsp –filename “C:\Deployment\MySharePointSolutionPackage.wsp” –immediate
4) To retract and remove a solution:
stsadm –o retractsolution –name MySharePointSolutionPackage.wsp –url http://webapplication/ –immediate
stsadm –o deletesolution –name MySharePointSolutionPackage.wsp
Powershell Solution Cmdlets
1) To add solution to the Farm:
Add-SPSolution –LiteralPath “C:\Deployment\MySharePointSolutionPackage.wsp
To add a Sandboxed solution(adding to the site collection)
Add-SPUserSolution –LiteralPath “C:\Deployment\MySharePointSolutionPackage.wsp” –Sitehttp://webapplication/sitecollection
2) To install ( deploy in stsadm) a Farm Solution:
Install-SPSolution –Identity MySharePointSolutionPackage.wsp –WebApplication http://webapplication/ –GACDeployment
To install ( deploy in stsadm) a Sandboxed Solution (installing to the site collection):
Install-SPUserSolution –Identity MySharePointSolutionPackage.wsp –Site http://webapplication/sitecollection
3) To update (upgrade in stsadm) a Farm solution :
Update-SPSolution –Identity MySharePointSolution.wsp –LiteralPath “C:\Deployment\MySharePointSolutionPackage.wsp” –GacDeployment
To update (upgrade in stsadm) a Sandbox solution (updating to the site collection) :
Update-SPUserSolution –Identity MySharePointSolution.wsp –Site http://webapplication/site –ToSolutionMySharePointSolutionPackage.wsp
4) To uninstall and remove FARM level solutions :
Uninstall-SPSolution –Identity MySharePointSolution.wsp –WebApplication http://webapplication/
Remove-SPSolution –Identity MySharePointSolution.wsp
To uninstall and remove Sandbox solutions (uninstall and remove from the site collection):
Uninstall-SPUserSolution –Identity MySharePointSolution.wsp –Site http://webapplication/sitecollection
Remove-SPUserSolution –Identity MySharePointSolution.wsp –Site http://webapplication/sitecollection
Tags: 

How to Find Logical Name of column in SharePoint?

1.123
Leave a comment
Posted by  on November 18, 2013 in SharepointSP Interview

how to lookup “person or Group” field from other list

  1. Create custom list called list1
  2. Create custom list called list2
  3. In list1 create text column called text
  4. In list1 create person column called person
  5. In list1 create text column called 4th
  6. In list1 create a workflow using sharepoint designer
  7. In workflow which i called WF1, there are no conditions and only one action. The workflow is set to run when a new item is created
  8. Workflow action is: Set [field value] to be [field value]
    Set 4th (Text column) to be Person (Display Name of Person Column)
  9. Add an item into list1
  10. In list2 create a lookup column called lookup, point it to list1 and the 4th column
  11. In list2 create a new item, the lookup is working.

Refer Scripts and CSS Style Sheet in SharePoint 2013 Visual Web Part and Master Page

1.Referring Java Script in Master Page
<SharePoint:ScriptLink ID=”ScriptLink1″ Name=”~SiteCollection/Style Library/Scripts/sitecol-master.js” runat=”server” />
<SharePoint:ScriptLink ID=”ScriptLink2″ Name=”~Site/Style Library/Scripts/site-master.js” runat=”server” />
2.Referring CSS Style via CssRegistration Control ( Applicable only for Form Solutions)
<SharePoint:CssRegistration ID=”CssRegistration1″ Name=”/_layouts/15/SFS.Ashok.Refer/Styles/site-visualwp.css” runat=”server” After=”corev15.css” />

Difference between event receivers and workflows?

  1. Unlike Workflows, Event Receivers cannot be triggered manually. SharePoint event handlers run for a short period of time (generally seconds), while SharePoint workflows may run for a much longer time period (days, months, or even years).
  2. Workflows run asynchronously means we can trigger the workflows only when an item is created and when an item is modified but event receivers can work either synchronously and asynchronously.
  3. Workflows can start manually but Event Receivers cannot.
  4. Can cancel the operation in Workflows but in SharePoint 2010 we can cancel the event receivers also.
  5. We can create workflows either by using SharePoint designer or visual studio but we should create an event receivers using visual studio only.
  6. SharePoint event handlers are automatically initiated, while SharePoint workflows can be initiated either automatically or manually.
  7. There is no User Interface(UI) for the event receivers.

How to Use Content Query Webpart in sharepoint.

Refer:
Leave a comment
Posted by  on October 14, 2013 in SP Interview

WebPart Life Cycle

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()
{

No comments:

Post a Comment