Wednesday, October 13, 2010
How to use SharePoint Log Files
Purpose: SharePoint has a new logging architecture that gives you a much better way of determining issues with your SharePoint farm.
Result: Know how to find and read the SharePoint log files
Task 1 – Turn on verbose and information logging
Open the Central Administration Console
Click “Operations” tab
Under “Logging and Reporting”, click “Diagnostic Logging”
For “Select a category”, select “All”
Under “Least critical event to report to the event log”, select “Information”
Under “Least critical event to report to trace log”, select “Verbose”
Click “Ok”
Task 2 – Review the log file
Open the 12 hive Logs directory (C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\LOGS)
Find the newest log file and open it
Open Microsoft Excel 2007
Copy and paste the data from the log file into Excel
In the menu, click “Data”
In the ribbon, under the “Sort & Filter” jewel, click “Filter”
A majority of your errors will revolve around the w3wp processes, therefore in the second column (process), click the filter dropdown
Uncheck “Select All”
Check all the w3wp.exe processes
Click “Ok”
Review the entries that are present, when any exception occurs across SharePoint it will show up here!
Exercise #2 – Log to SharePoint Log File
Purpose: Learn to append your own messages to the log file
Result: Log entries in the Log files
Task 1 – Create a console application
Open Visual Studio 2005
Create a new console application
Click File->New->Project
Select Console Application
For location, type “c:\Lab Work”
For name, type “Logger”
Click Ok
Add a reference to Microsoft.Office.Server.dll
Right click the project, select “Add Reference”
Click the Browse tab
Browse to c:\program files\common files\microsoft shared\web server extenstions\12\isapi
Select Microsoft.Office.Server.dll
Click Ok
Update the Main code to the following:
using System;using System.Collections.Generic;using System.Text;using Microsoft.Office.Server;namespace ConsoleApplication2{class Program{static void Main(string[] args){try{throw new Exception(“Something bad happend”);}catch (Exception ex){Microsoft.Office.Server.Diagnostics.PortalLog.LogString(“This was a bad one…”, null);}}}}
Run the application
Open the log files, find your log entry
Drag your Outlook file attachment directly into Sharepoint
Did you know that you can drag your Outlook file attachment directly into Sharepoint?
It is straightforward with a few exceptions. Here are the steps:
Open your SharePoint siteSelect the Document Library to store the fileSelect the “Explorer View” of the Document LibraryNow open OutlookOpen the Email with the attachmentResize Outlook so you can see the explorer view of the document library
Click on the attachment and drag to the folder area of the explorer view
The beauty of this is that the file never gets pulled out of Outlook onto a local drive/directory and is less likely to present a security risk.
Explorer view of the SharePoint Library
You can also use the explorer view of the SharePoint Library
(Library Name–>Actions–>Windows Explorer View) to drag&drop/copy&paste email (or just the attachments) and files from Outlook and your desktop.
You can also sync this library back to Oultook so you can browse it from Outlook.
Or for sending out files, while in Explorer view, mouse right click on one or more files,
select “Sent To..”–>Mail Recipient.
It would be great if SharePoint had that option under it’s Send to, but that is a third party add-on right now.
Use “Save As” any email attachment or Document to SharePoint List
Your best bet is to add the SharePoint library as a Network location in your Windows Explorer. In windows explorer, right click on
Computer –> Add Network Connection –> Add custom location
(use the SharePoint library url).
This allows you to use “save as” from any of your desktop applications
(including Outlook and browser) to select your SharePoint library as well as using “Attach File” in an Outlook email to select files from the SharePoint library.
This would also eliminate the need to have SharePoint open.
Custom .NET Application integration to SharePoint
several integration levels of a custom .NET application to SharePoint
- Integration Level 0 (No Integration)
Advantages
Simplest solution as there is no need to integrate with MOSS 2007 or deploy.
More reliable as there is no reliance on MOSS 2007 services.
Server requirements are reduced as SharePoint services are not running/not required.
Simpler development and deployment model and debugging.
Regular workstations can be used for development and Visual Studio 2008 is good for development and no add-ons or extensions required.
Can take advantage of third party tools such as DevExpress and Log4net with little or no setup changes.
Service account can be used for database access, no need to worry about Single Sign On.
Disadvantages
Limited integration with existing MOSS 2007 portals.
Another hosting environment to maintain.
Cannot take advantage of list data that is available in MOSS 2007.
MasterPages and Login pages with common user controls must be developed.
Cannot take advantage of SharePoint security model
Integrating to MOSS 2010 will be another complete effort.
Integration Level 1 (Using ASP.NET 3.5 hosted inside MOSS 2007 as Application Pages)
Advantages
Simpler development Model compared to higher levels of integration and debugging the Business objects and data objects is possible.
SharePoint is aware of the page – so the link is natively visible to portals (i.e. the link doesn’t need to be added to SharePoint)
Can take advantage of SharePoint master page, so the look and fell will be consistent across the organization. This will fasten the development process as there is no need for login and other user controls.
Application can be developed in regular ASP .NET fashion and integrated into MOSS 2007 as application pages, so regular ASP .NET debugging can be leveraged.
Single hosting environment and other Windows 2003 web servers can be taken off
Can take advantage of SharePoint’s security model such as User Profile.
Can take advantage of some of SharePoint’s features for future development.
Can take advantage of collaboration with some existing list data.
Don’t have to concentrate as much as for regular .NET apps regarding the AppScan vulnerabilities
Can take advantage of .Net 3.5 features such as ADO .NET entity framework and LINQ compared to higher levels of integration
Since each page is independent of other, MOSS 2010 migration will be easier compared to higher levels of integration.
Can take advantage of MOSS features in application enhancements.
Disadvantages
Dependency upon MOSS.
More powerful servers are required as there will be single hosting environment that process both regular SharePoint information and ASP .NET web application.
Initial setup of integrating ASP .NET web app into MOSS 2007 could be a night mare as there are some configuration changes, master file changes and some code changes to integrate the custom.master file.
May find some difficulties working with some third party controls such as Dev Express.
May find some challenges in using open source utilities such as Log4net and Microsoft Data Access Applications blocks as MOSS 2007 requires the signed assembly.
Changes in development and deployment process as there will be integration and that needs to be done on a web server which has SharePoint installed.
Verbose logging should be enabled in order to track down the errors in the integration part.
Double hop issue, must use local db account to access the DB or configure Single Sign On.
Cannot use proper identity impersonate with SharePoint security model.
Integration Level 2 (Using ASP.NET 3.5 and developing inside MOSS 2007)
Advantages
Single hosting environment.
Can take advantage of full SharePoint’s security model.
Can take advantage of SharePoint’s rich controls such as SPGridView, built-in web parts and Workflows.
Can integrate with existing list data if any.
Can take advantages of MOSS 2010 easy development framework such as BCS.
Disadvantages
Dependency upon MOSS 2007.
Site Pages render slower in MOSS 2007.
There is reliance on more components – so reliability of system is lower.
More powerful servers are required as there will be single hosting environment that process both regular SharePoint information and ASP .NET web application.
May find some difficulties working with some third party controls such as Dev Express.
May find some challenges in using open source utilities such as Log4net and Microsoft Data Access Applications blocks as MOSS 2007 requires the signed assembly.
Difficulty in troubleshooting. There are different log files to search for the error and it’s not clear where to look.
Development environment issues could arise as work stations do not have SharePoint libraries installed.
Reduced ability to use new .NET 3.5 features such as ADO .NET entity framework and LINQ.
Oracle client must be installed on the server in order to connect to Oracle db
More effort in migrating to MOSS 2010 compared to Integration Level 1.
Integration Level 3 (Deep Integration with MOSS 2007 using Lists , Business Data Catalog and Data Sources)
Advantages
Single hosting environment.
Can take full advantage of SharePoint’s security model.
Can take advantage of SharePoint’s rich controls such as SPGridView, built-in web parts and Workflows.
Can leverage current look and feel of SharePoint sites if they already exist.
Lists are easily customized by users.
Notifications when data changes.
Can take advantages of MOSS 2010 easy development framework such as BCS.
Disadvantages
Complete revamp of business process flow and this will require significant user education.
Dependency upon MOSS 2007.
Site Pages render slower in MOSS 2007.
There is reliance on more components – so reliability of system is lower.
More powerful web servers and SQL server required.
Difficulty in troubleshooting. There are different log files to search for the error and it’s not clear where to look.
Performance and scalability issues using Business Data Catalog to connect to external data sources.
Insane Development Requirements: You must have a Windows 2003/2008 Server as your Workstation; you really should be local Administrator on it.
More effort in migrating to MOSS 2010 compared to other Integration Levels.
How to hide Left Navigation Menu (Quick Launch) in SP
Quick Launch is rendered using a delegate control by SPContentSiteMap provider.
One way to remove the Quick Launch bar is to modify the Master Page to remove the delegate control
Other way is to hide the Quick Launch in a Content Editor Web Part as follows.
Add Content Editor Web Part to a Web Part Zone
Select Edit – Modify Shared Web Part
Under Layout, check the Hidden option
Click the Source Editor button and add the following CSS
Tuesday, April 6, 2010
STSADM commands
--------------------
to add site templates to your installation, you can use the following command:
Stsadm -o addtemplate -filename
-title <> -description <>
----------------------
add a Web Part Package
Stsadm -o addwppack -filename <>
----------------------
The following command will have SharePoint send out immediate alerts every 10 minutes:
Stsadm -o setproperty -pn job-immediate-alerts -pv "Every 10 minutes"
Note : -pn and -pv instead of -propertyname and -propertyvalue
----------------------
The following to a text file named createpersonalsite.cmd
stsadm -o createsite -url http://localhost/users/%1 -ownerlogin contoso\%1
-owneremail %1@contoso.com -sitetemplate usersite.stp
-title "Personal site for %1" -description "Personal site for %1" -quota "500 MB"
----------------------
create a site for the user jaganinfo, simply execute the following:
createpersonalsite.cmd jaganinfo
-----------------------
To rename a web from "oldname" to "coolnewname," use the following:
Stsadm -o renameweb -url http://localhost/oldname -newname coolnewname
------------------------
Backing Up and Restoring
STSADM which site to back up and where to write the backup file, like this:
Stsadm -o backup -url http://localhost -filename site.bak
------------------------
Working with a Data View Web Part
to view a list of site collections
create a scheduled task that runs:
stsadm –o enumsites –url http://localhost
>c:\inetpub\wwwroot\excludedsite\sites.xml
---------------------------
To export a web, use the following simple command:
Stsadm -o export -url http://localhost/web -filename backup.dat
----------------------------
To import a web back to the server, use the following command:
Stsadm -o import -url http://localhost/web2 -filename backup.dat
-------------------------
Expert Operations
If the account jaganinfo is renamed to mohaninfo, you can use the following command:
Stsadm -o migrateuser -oldlogin domain\jaganinfo -newlogin domain\mohaninfo -ignoresidhistory
----------------------------
The following command will unextend your virtual server:
Stsadm -o unextendvs -url http://localhost
--------------------------------
To change the port to one you specify:
Stsadm -o setadminport -port 1026
-------------------------------
Feature
activatefeature
stsadm.exe -o activatefeature
{-filename
-name
-id
[-url
[-force]
deactivatefeature
stsadm.exe -o deactivatefeature
{-filename
-name
-id
[-url
[-force]
installfeature
stsadm.exe -o installfeature
{-filename
-name
[-force]
uninstallfeature
stsadm.exe -o uninstallfeature
{-filename
-name
-id
[-force]
----------------------------------------------
Sunday, March 28, 2010
SharePoint Programming
To fetch the User name in Console application is as follows
using Microsoft.SharePoint;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
SPSite rootSite = new SPSite("http://jaganinfo-pc:1234/");
SPWeb rootWeb= rootSite.RootWeb;
SPUserCollection userList = rootWeb.AllUsers;
foreach (SPUser objUser in userList)
{
Console.WriteLine(objUser.Name);
}
Console.Read();
}
}
}
********************************************************************
Q) Write a Query SharePoint List by using LINQ
// Get DataContext from page context
DataContext data = new DataContext(SPContext.GetContext(this.Context).Web.Url);
// Get the SharePoint list
EntityList Customers = data.GetList("Customers");
// Query for customers from India
var indiaCustomers = from customer in Customers
where customer.City == "India"
select customer;
foreach (var indiaCust in indiaCustomers)
{
Console.Writeline("id = {0}, City = {1}", indiaCust.CustomerId, londonCust.City);
}
********************************************************************
Q) Write a program to Get All Alerts in the Site Collection
public void GetAlerts(Button btn)
{
SPSite rootSite = SPContext.Current.Site;
SPWeb rootWeb = rootSite.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.
SPList alertList = rootWeb.Lists[LIBName.Trim()];
DeleteAllExistingItems(alertList, btn); // Delete existing items
using (SPSite siteCollection = new SPSite(rootSite.ID))
{
foreach (SPWeb curretWeb in siteCollection.AllWebs)
//Get alerts for each web
{
using (SPWeb web = siteCollection.OpenWeb(curretWeb.ID))
{
web.AllowUnsafeUpdates = true;
try
{
SPAlertCollection allAlerts = web.Alerts;
foreach (SPAlert AlertItem in allAlerts)
{
AddAlertToTable(alertList, AlertItem);
}
}
catch (Exception ex)
{
Console.WriteLine("Delete failed: " + ex.Message);
throw;
}
web.AllowUnsafeUpdates = false;
}
}
}
});
}
********************************************************************
Q) Programmatically Upload Documents in a Document Library
public void DocumnetsUpload(SPWeb site)
{
if (FileUploadControl.HasFile)
{
SPFolder folder = site.GetFolder("Document_Library_Name");
SPFileCollection files = folder.Files;
//path of the file to upload
Stream fStream = FileUpload1.PostedFile.InputStream;
byte[] contents = new byte[fStream.Length];
fstream.position = 0;
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
string Filename = FileUpload1.FileName;
string URL = SPContext.Current.Site.Url + "/Document_Library_Name/" + Filename;
SPFile currentFile = files.Add(URL, contents);
}
}
********************************************************************
Q) Write a program to Delete all Items in a list
Note: Deleting all items in list will send all the items to recycle bin. To avoid fill-up recycle bin, we can just turn the recycle bin off while deleting the items.
public void DeleteAllItems(SPList CurrentList)
{
bool IsRecycleBinEnabled = SPContext.Current.Web.Site.WebApplication.RecycleBinEnabled;
if (IsRecycleBinEnabled)
{
//set the use off the recyclebin to false SPContext.Current.Web.site.Webapplication.RecycleBinEnabled = fasle;
}
StringBuilder sbDelete = new StringBuilder();
sbDelete.Append("");
foreach (SPListItem item in CurrentList.Items)
{
sbDelete.Append("
sbDelete.Append("
sbDelete.Append("
sbDelete.Append("
sbDelete.Append("
}
sbDelete.Append("");
try
{
SPContext.Current.Site.RootWeb.ProcessBatchData(sbDelete.ToString());
}
catch (Exception ex)
{
Console.WriteLine("Delete failed: " + ex.Message);
throw;
}
if (!IsRecycleBinEnabled)
{
//set the use off the recyclebin to false
//SPContext.Current.Web.site.Webapplication.RecycleBinEnabled = true;
}
********************************************************************
Q) SharePoint search using FullTextSqlQuery
//Here SharedServices2 refers to the Shared Service Provider servicing the site in Question
ServerContext context = ServerContext.GetContext("SharedServices2");
FullTextSqlQuery qrySearch = new FullTextSqlQuery(context);
//Specifies the results set containing the main search results from
//the content index matching the search query.
qrySearch.ResultTypes = ResultType.RelevantResults;
//Sremming : expansion of searches to include plural forms and
//other word variations :-)
qrySearch.EnableStemming = true;
qrySearch.TrimDuplicates = false;
qrySearch.QueryText = "SELECT URL, Title, Size, Write, HitHighlightedSummary FROM SCOPE() where \"scope\"='NTFS Archive' And FREETEXT(*,'" + TextBox1.Text.Trim() +
"')";
ResultTableCollection results = qrySearch.Execute();
ResultTable resultTable = results[ResultType.RelevantResults];
// Data Table to Store Search Results
DataTable dtResults = new DataTable();
dtResults.Load(resultTable, LoadOption.OverwriteChanges);
********************************************************************
Points to know in SharePoint Interview
Hi Friends, I thought to share some points in SharePoint, which is very usefull in interviews and to update the sharepoint knowledge.
I will update the points frequently and i'm expecting a comments from you with some more points .. Please Share Points .. :).. Urs ... Jagan
--> SharePoint is all about data and data should properly authenticated / authorized to proper users.
--> when a page is requested it first checks in the document table and then goes to the content table to load the page. If it does not find data of the page it goes to the file directory to load the page. This loading is done by ASP.NET runtime himself. But if there is data present in the content table then it’s loaded by the ‘safe mode’ parser.
--> Ghosting (UnCustomized) and UnGhosting (Customized) in WSS 3.0
--> pages which are loaded from the file system are termed as ghosted pages.
--> If the page data is loaded from the content database then it’s termed as unghosted pages.
--> Template is stored in a cache. This definitely brings in performance and flexibility.
--> Site pages are customized pages and are saved in to content database.
--> Application pages are generic pages which will be used by all the sites in a site collection.
--> two types of databases one is the content database (like: WSS_Content ) and the other is the configuration database (like: SharePoint_Config).
--> WSS works with IIS : Using the HttpHandlers and HttpModules request is first passed through the Share Point runtime and then passed to the ASP.NET runtime (aspnet_isapi.dll).
Accenture Sharepoint Interview Questions
1) Tell me about your sharepoint experiences ?
2) Did you ever worked in Web Services ? How you called Webmethods ?
3) What type of Webparts you are developed in your current project ?
4) How many ways we can deploy the webpart ? Which is the best method to deploy the Webpart ?
5) What are new features in MOSS 2007 ?
6) What are the permission levels in Sharepoint ?
7) What is Sharepoint Object Model ?
8) What are basic building blocks for Sharepoint ?
9) How many types of Event Handlers in Sharepoint ? where did you use these event handlers in your project ?
10) What are the Security levels in Sharepoint ?
11) What is the default authentication level in Sharepoint ?
12) Can we impliment Forms Authentication in Sharepoint or is there any custom Authentication ?
13) What is meant by SignIn ?
14) What is meant by MetaData Cache ?
15) How can you impliment Data Fragment cache ? What is VaryByParam ?
16) When configuring Enterprise Search , what are the instances that you are created ?
Windows SharePoint Services Object Model
Identity : Microsoft.SharePoint
Description : Windows SharePoint Services
Path : To add a reference to a Sharepoint API, Right-click the project(in VS) and select Add Reference. Click the Browse tab and select the following directory:
C:\program files\common files\microsoft shared\web server extensions\12\isapi
Some useful Microsoft.SharePoint Namespaces follows with Description :
Microsoft.SharePoint
Provides types and members for working with a top-level site and its subsites or lists.
Microsoft.SharePoint.Administration
Provides administrative types and members for managing a Windows SharePoint Services deployment.
Microsoft.SharePoint.Administration.Backup
Provides types and members for performing backup and restore operations on SharePoint sites.
Microsoft.SharePoint.Deployment
Provides types and members for importing and exporting content between Windows SharePoint Services Web sites.
Microsoft.SharePoint.Dsp
Provides the base class for the data retrieval service adapters used in Windows SharePoint Services.
Microsoft.SharePoint.Meetings
Provides types and members that can be used to customize Meeting Workspace sites.
Microsoft.SharePoint.MobileControls
Provides server controls for rendering the mobile forms and view pages used in SharePoint lists.
Microsoft.SharePoint.Navigation
Provides types and members for customizing the navigation structures and site maps of SharePoint Web sites.
Microsoft.SharePoint.Search
Microsoft.SharePoint.Search.Internal.Protocols
Microsoft.SharePoint.Search.Internal.Protocols.SiteData
Microsoft.SharePoint.Search.Internal.Protocols.SPSCrawl
Microsoft.SharePoint.Search.Internal.UI
Microsoft.SharePoint.Search.Internal.WebControls
Microsoft.SharePoint.Security
Provides a set of code access permission and attribute classes designed to protect a specific set of resources and operations, such as access to the Windows SharePoint Services object model, the ability to do unsafe saving on HTTP Gets, and enabling point-to-point Web Part connections.
Microsoft.SharePoint.StsAdmin
Provides an interface for creating custom operations to run at the command prompt in STSADM.EXE
Microsoft.SharePoint.Upgrade
Provides types and members for upgrading a Windows SharePoint Services deployment.
Microsoft.SharePoint.Utilities
Provides utilities for encoding strings and processing user information.
Microsoft.SharePoint.WebControls
Provides server controls that are used on site and list pages in a SharePoint site.
Microsoft.SharePoint.WebPartPages
Provides classes, interfaces, and members for creating custom Web Parts and Web Part pages
Microsoft.SharePoint.Workflow
Provides types and members for associating, initiating, and managing workflow templates and instances.
Microsoft.SharePoint.WorkflowActions
Provides types that represent workflow activities. These activities can be assembled into workflow activities.
Some useful Microsoft.SharePoint Classes follows with Description and Example :
SPSite
Represents a collection of sites in a Web application, including a top-level Web site and all its subsites. Each SPSite object, or site collection, is represented within an SPSiteCollection object that consists of the collection of all site collections in the Web application.
E.g : SPSite siteCollection = SPControl.GetContextSite(Context);
SPWeb
Represents a Windows SharePoint Services Web site.
E.g : SPWeb objWebSite = siteCollection.OpenWeb();
SPWebCollection
Represents a collection of SPWeb objects.
E.g : SPWebCollection objWebCollection = siteCollection.AllWebs;
SPSecurity
Provides static security management properties and methods.
E.g : SPSecurity.CodeToRunElevated myCode =
new SPSecurity.CodeToRunElevated(ShowFeatures);
SPSecurity.RunWithElevatedPrivileges(myCode);
SPListCollection
Represents a collection of SPList objects.
E.g : SPListCollection objListCollection = objWebSite.Lists ;
SPList
Represents a list on a SharePoint Web site.
E.g : foreach(SPLists objLists in objListCollection)
SPUser
Represents a user in Microsoft Windows SharePoint Services.
E.g : SPUser objUser = objWebSite.CurrentUser ;
****************************************************************
SharePoint 2010 Object Model
In Sharepoint Object model there are two Important namespaces.
The Microsoft.Office.Server namespace is the root namespace of all Office Server objects and Microsoft.SharePoint is the root namespace for all WSS objects.
The Chart Below illustrates some of the key classes contained in each of these namespaces, as well as to which functional area they belong.
Document Libraries (Microsoft.SharePoint)
SPDocumentLibrary , SPPictureLibrary
Business Data Catalog (Microsoft.Office.Server.ApplicationRegistry.Administration)
EntityCollection , ApplicationRegistry
Features (Microsoft.SharePoint)
SPFeatureDefinition, SPFeatureScope, SPElementDefinition, SPFeature, SPFeatureProperty
Sites (Microsoft.SharePoint)
SPSite, SPSiteAdministration, SPSiteCollection, SPWeb
Meetings (Microsoft.SharePoint.Meetings)
SPMeeting, MtgUtility
User Profiles (Microsoft.Office.Server.UserProfiles)
UserProfile, UserProfileManager
Solutions (Microsoft.SharePoint.Administration)
SPsolution, SPFeatureReceiver, SPSolutionCollection
Lists (Microsoft.SharePoint)
SPList, SPListItem, SPListItemCollection
Notes:
* To use the SharePoint API, your code must reside on one of the machines in a SharePoint
application server farm. Your code can still work with other sites in the farm from any
other site in the farm, but you cannot, for example, work with the SharePoint API from a
machine on which MOSS or WSS is not installed.
* The only practical way to consume SharePoint data and functionality from a remote client is to use the SharePoint web services.
* The object model is not designed to support Remoting.
**********************************************************
Sharepoint Webparts Workflows custom controls Questions
Q) How can we use custom controls in SharePoint?
Step 1:- Create the custom control by inheriting from the ‘WebControl’ class and override the ‘RenderContents’ method with your implementation. In the below code snippet we are just writing the site title and site URL to the browser.
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
namespace NameSpaceCustomControl
{
public class CustomControl1 : WebControl
{
protected override void RenderContents(HtmlTextWriter output)
{
SPWeb rootSite = SPContext.Current.Web;
output.Write("The Site title is " + rootSite.Title);
output.Write("
");
output.Write("The URL of the site is " + rootSite.Url);
}
}
}
Step 2 : Compile the custom control class and generate the DLL from the same. Once the compiled DLL is generated, register the same in GAC.
Step 3: Refer the custom control assembly in your ASPX page using the register
attribute. Please note to specify the public key token of the GAC.
<%@ Register Assembly="CustomControl,Version=1.0.0.0,Culture=neutral,PublicKeyToken=4adae03f3c0d5b8e"
Namespace="NameSpaceCustomControl" TagPrefix="CustomSitePages" %>
Specify the custom control with a proper unique ID.
Below is the complete code of the page.
<%@ Page Language="C#" MasterPageFile="~masterurl/default.master" meta:progid="SharePoint.WebPartPage.Document"%>
<%@ Register Assembly="CustomControl,Version=1.0.0.0,Culture=neutral,PublicKeyToken=4adae03f3c0d5b8e"
Namespace="NameSpaceCustomControl" TagPrefix="CustomSitePages" %>
Hi this is a JaganInfo Site Page
-----------------
Q ) What are WebParts and how does it interact with SharePoint ?
It helps to build reusable components which can customized and personalized according to business user. We can either make our own webpart or we can reuse the existing one's from SharePoint itself.
Web Parts are the fundamental building blocks for Share Point user interface, and with them we can build and integrate many different types of applications.In share point also be create custom web part using .oscx control
Steps create custom web part
1. create web part project copied .oscx control and build application.place .dll file in GAC .reset IIS.
2. go 12 hive _layout folder create folder past your .oscx control
3. go inetpub ->wwwroot->wss->open Your site ->web con fig->create safe control write assembly information of web part application
4. open sharepoint site ->site action-site editing->Galleries ->web part->new Add your web part.
Following few WebParts are available in WSS 3.0
Data View Web Part : Displays data with rich design support through Microsoft SharePoint Designer.
List View Web Part : Helps us to display list content for any list in the SharePoint site.
Image Web Part : Helps us to display image files.
Content Editor Web Part : Use this to display static HTML content using a WYSIWYG editor or to link to a text file.
Members Web Part : Helps us to display members of the site.
Page Viewer Web Part: Displays web page in an Iframe.
WebPart is nothing but a simple class which inherits from System.Web.UI.WebControls.WebParts.
In other words you can say WebPart is kind of a WebControl which can be deployed in a WebPartZoneControl.
------------------
Q ) WebPart life cycle events
OnInit : This is the initialization event and is the first event to occur.
OnLoad : The load event.
CreateChildControls : When any child controls are added to a composite control this event fires.
EnsureChildControls : This event makes sure that ‘CreateChildControls’ fires.
OnPreRender : This fires just before the render event.Page.
PreRenderComplete : When all controls have executed the ‘OnPreRender’ event this event fires.
Render : Render the full control.
RenderContents : Renders the contents of the control only.
Steps to create a WebPart in SharePoint
Step 1 : Create the Webpart
Step 2 : Copy the compile DLL to the virtual directory in the BIN folder.
Step 3 : Make entry of the WebPart in to web.config file.
Step 4 : Add it to the WebPart gallery
Step 5 : Add the WebPart to site pages.
Step 6 : View the WebPart
---------------------------------------------------------
Q) Workflows :
While workflow associations are often created directly on lists and document libraries, a workflow association can also be created on a content type that exists within the Content Type Gallery for the current site or content types defined within a list.
It can be applied
* At the level of a list (or document library)
* At the level of a content type defined at site scope
* At the level of a site ( Sharepoint 2010 )
What are the ways to initiate the workflow ?
* Automatic (on item added or item deleted)
* Manual (standard WSS UI interface)
* Manual (Custom UI Interface)
* Programatically through custom code
Types of input forms in Workflows
Can create four different types of input forms including
an association form,
an initiation form,
a modification form, and
a task edit form.
Note that these forms are optional when you create a workflow template.
Different types of Workflow
There are two basics type of workflow Sequential Workflow and State machines workflow.
A sequential workflow has clear start and finish boundaries. Workflow controls execution in Sequential workflow. In sequential execution, one task is executed after other. Sequential workflow is more rigid in format and execution path has a determistic nature.
A State machine workflow is more dynamic in nature. Workflow has states and the state waits for events to help it move to next state. In State machine execution path is undetermestic nature.
Different stages of SharePoint workflow life cycle
There are four stage in the sharepoint workflow cycle associate, initiate, modify and complete.
Associate : As said workflows in sharepoint are always talked in context with a content type.
So the first step is to associate a workflow with a content type like list or a document.
Initiate : The second step is to initiate the workflow instance. Work flows are nothing but classes finally so a workflow instance needs to be created to start the work flow in action.
Modify : Later the workflow instance is modified as per the workflow stages.
Complete : Finally the workflow object is terminated.
How the workflow will be executed ?
• Administrator creates the initiates the task. The task is assigned to the reviewer.
• The reviewer then reviews the task, makes his comments and makes the task in progress. Once he makes the task in progress it’s automatically assigned to the acceptor.
• Acceptor finally does the complete review and closes the task.
---------------------------------------------------------
Q ) list types in SharePoint
Document library : Used for collaborating on documents with support for versioning, check-in and check-out, and workflow.
Form library : Used to store XML documents and forms for use with Microsoft Office InfoPath
Wiki page library : Used for collaborative Web pages based on wiki pages, which are dynamically generated and collaboratively edited Web pages.
Picture library : A specialized document library enhanced for use with pictures. Includes support for slide shows, thumbnails, and simple editing through Microsoft Office Picture Manager
Announcements : Used for simple sharing of timely news with support for expiration.
Contacts : A list for tracking people and contact information, with support for integration into Microsoft Office Outlook and other WSS-compatible contacts applications.
Discussions : A simple list for threaded discussions with support for approval and managing discussion threads.
Links : A list for managing hyperlinks.
Calendar : A list for tracking upcoming events and deadlines. Includes support for integration and synchronization with Office Outlook.
Tasks : A list of activity-based items that can integrate with workflow.
Project tasks : An enhanced tasks list with support for Gannt chart rendering and integration with Microsoft Office Project.
Issue tracking : A list for tracking issues and resolution, with support for prioritization.
Custom list : An empty list definition for extending with custom columns, or created using Microsoft Office Excel spreadsheets
SharePoint My Practices
Q) To Display All List Of Items
Open C# Windows Form , write the below code in the button click event.
private void btnSPList_Click(object sender, EventArgs e)
{
string strSiteAddress = "http://server"; // E.g: "http://jaganinfo-pc:17303";
//SPSite is returning the site collection.
SPSite rootSite = new SPSite(strSiteAddress);
//SPWeb is returning top level site
SPWeb rootWeb = rootSite.OpenWeb();
// Represents a collection of SPList objects
SPListCollection listCollection = rootWeb.Lists;
//Note : Two ways we can display, you can show list by using for loop or foreach
for (int i = 0; i < listCollection.Count; i++)
MessageBox.Show("List Follows : " + listCollection[i].ToString());
// OR
foreach (SPList list in listCollection)
MessageBox.Show("List follows : " + list.ToString());
Sharepoint template ID for event handlers
The following list template integer IDs that you can use in defining the template ID for event handlers.
List Template Id List Template
100 Generic list
101 Document library
102 Survey
103 Links list
104 Announcements list
105 Contacts list
106 Events list
107 Tasks list
108 Discussion board
109 Picture library
110 Data sources
111 Site template gallery
113 Web Part gallery
114 List template gallery
115 XML Form library
120 Custom grid for a list
200 Meeting Series list
201 Meeting Agenda list
202 Meeting Attendees list
204 Meeting Decisions list
207 Meeting Objectives list
210 Meeting text box
211 Meeting Things To Bring list
212 Meeting Workspace Pages list
300 Portal Sites list
1100 Issue tracking
2002 Personal document library
2003 Private document library
There are three main event classes:
* SPItemEventReceiver
* SPListEventReceiver
* SPWebEventReceiver
Attributes of Feature.XML File
| Attribute | Value | Description |
| ID | GUID | Contains the globally unique identifier (GUID) for the Feature. |
| Title | Text | Returns the title of the Feature. Limited to 255 characters. |
| Scope | Farm/WebApplication/Site/Web | Can contain one of the following values: Farm (farm), WebApplication (Web application), Site (site collection), and Web (Web site). |
| Hidden | True/False | This attribute equals FALSE by default. |
| AlwaysForceInstall | True/False | Optional Boolean. TRUE if the Feature is installed by force during installation even if the Feature is already installed. For example, if set to TRUE, Feature installation callouts will always fire anytime a user tries to install the Feature (even if it is already installed) by using either the scanforfeatures or installfeature command-line operation. This attribute equals FALSE by default. The AlwaysForceInstall attribute affects Features of all scopes. |
SharePoint Interview Question and Answers
Q) Difference between MOSS and WSS
WSS is foundation and MOSS is optional add-on.
You cannot install MOSS of itself. If you try to do this, you will be requested to install WSS first.
Characteristics of WSS
It is a Web Based Application
It stores all information in an MS SQL database.
It displays information using web Parts.
It comes with site templates.
What WSS does not have?
There is no support for indexing and Searching.
It does not have advanced intranet features, such as targeted information and content management.
It has no record management.
It cannot display InfoPath forms in Web Browser.
It cannot display MS Excel spreadsheet as Web Part.
It comes with less than 10 Web parts.
It cannot Read and Write to External Database.
So to achieve all above task which WSS does not have, MOSS came into action.
MOSS 2007
Use global search functionality to find any type of information regardless of type and location.
Target information to one or more User Group.
Use Advanced Content Management.
Import User Data from Active Directory.
Use RSS web part to list information fetched from RSS feeds.
Give each SharePoint user a Personal Web Site.
Search, display content from external Database.
Comparison of Built in Feature of SharePoint
Features WSS MOSS
Alerts Yes Yes
RSS Yes Yes
File and Document Management Yes Yes
Project Management Yes Yes
Managing Meeting Yes NO
Update NO Yes
Finding Information NO Yes
Indexing NO Yes
External Data access NO Yes
SSP is nothing but collection of configured service to work with MOSS.
Q) What are Site Pages? how are they different from application pages?
Site pages are customized pages and are saved in to content database. So when you use the SharePoint designer to make custom changes it saves the changes in to content database. If you want to make generic pages in a site collection which will be used by every one, like for instance the ‘Settings.aspx’ page then you need to use application pages.
In other words Site pages are nothing but customized pages stored in content, while application pages are generic pages which will be used by all the sites in a site collection
Q) What are site columns?
Site columns allows you to create a lookup columns in one location and share the column with any custom lists that would need it.
Q) What is a Site Definition? How can you create a new Site Definition?
A site definition is a collection of files that defines the structure & layout of site templates. Confused? Well, don't be. A site definition comprised of a webtemp.xml file which in turn defined the order of various site templates available in that site definition. Site definition file also include a separate directory structure that includes all the other core files required. The webtemp.xml file is stored in %COMMONPROGRAMFILES%\Microsoft Shared\web server extensions\12\TEMPLATE\1033\XML location and directory that contains all the core files is %COMMONPROGRAMFILES%\Microsoft Shared\web server extensions \12\TEMPLATE\SiteTemplates.
Steps for creating a custom Site Definition
Step 1.Create a copy of existing site Definition structure by navigating to %COMMONPROGRAMFILES%\\Microsoft Shared\web server extensions\12\TEMPLATE\SiteTemplates. Rename the file as NewLOB (short form for New line of business).
Step 2. Navigate to %COMMONPROGRAMFILES%\\Microsoft Shared\web server extensions\12\TEMPLATE\1033 and copy the STS directory and paste it in the same strucutre and rename it as NewLOB.
Step 3. Create webTemp.xml file to register the site definition created in step 1&2.
Step 4. Reset IIS.
Thats it. Now, new site definition is available for use for the new line of business group.
Q) Explain the concept of ghosting/unghosting?
First of all, with the release of WSS 3.0, Microsoft has renamed the concept of ghosting/unghosting as uncustomized/customized pages .
In SharePoint most of the site pages derive from templates. The custom pages only store the difference between them. The template is loaded in memory and applied to the custom pages on fly. In other words the template is stored in a cache. This definitely brings in performance and flexibility. Flexibility is in terms that when we change the template page it’s applied to all custom pages. These pages are loaded from the file system. So pages which are loaded from the file system are termed as ghosted pages.
If the page data is loaded from the content database it’s termed as unghosted pages.
Q) Content types in SharePoint
A content type is a flexible and reusable WSS type definition that defines the columns and behavior for an item in a list or a document in a document library.
E.g : you can create a content type for a customer presentation document with a unique set of columns, an event handler, and its own document template.
Content type can be created by the following
• from the rootweb of a site collection, go to Site Action > Site Settings > Galleries > Site content types
• using a feature
Q)What is the difference between Syncronous & Asyncronous events?
Syncronous calls ending with 'ing' E.g. ItemDeleting Event Handler code execute BEFORE action is committed WSS waits for code to return Option to cancel and return error code
Asyncronous calls ending with 'ed' E.g. ItemDeleted Event Handler code executes AFTER action is committed WSS does not wait for code to return Executed in its own Worker thread.
Q)How to query from multiple lists ?
Use SPSiteDataQuery to fetch data from multiple lists.
Q)What are the various kinds of roles the users can have?
A user can be assigned one of the following roles
* Reader : Has read-only access to the Web site.
* Contributor : Can add content to existing document libraries and lists.
* Web Designer : Can create lists and document libraries and customize pages in the Web site.
* Administrator : Has full control of the Web site.
Q)What is CAML, and why would you use it?
CAML stands for Collaborative Application Markup Language.
CAML is an XML based language which provides data constructs that build up the SharePoint fields, view, and is used for table definition during site provisioning.
CAML is responsible for rending data and the resulting HTML that is output to the user in SharePoint. CAML can be used for a variety of circumstances, overall is used to query, build and customize SharePoint based sites. A general use would be building a CAML query in a SharePoint WebPart in order to retrieve values from a SharePoint list.
Q)What is a SharePoint Feature? What files are used to define a feature?
A SharePoint Feature is a functional component that can be activated and deactivate at various scopes throughout a SharePoint instances, such as at the farm, site collection, web, etc. Features have their own receiver architecture, which allow you to trap events such as when a feature is installing, uninstalling, activated, or deactivated. They are helpful because they allow ease of upgrades and versioning.
The two files that are used to define a feature are the feature.xml and manifest file. The feature XML file defines the actual feature and will make SharePoint aware of the installed feature. The manifest file contains details about the feature such as functionality.
A SharePoint Feature is a functional component that can be activated and deactivate at various scopes throughout a SharePoint instances.
Scopes include
• Farm
• WebApplication
• Site (site collection)
• Web (site)
Features have their own receiver architecture, which allow you to trap events such as when a feature is
• installing
• uninstalling
• activated
• deactivated
The element types that can be defined by a feature include
• menu commands
• link commands
• page templates
• page instances
• list definitions
• list instances
• event handlers
• workflows
The two files that are used to define a feature are
• feature.xml
• manifest file(elements.xml)
The feature XML file defines the actual feature and will make SharePoint aware of the installed feature. The manifest file contains details about the feature such as functionality.
Common stsadm commands associated with feature are
• stsadm -o installfeature
• stsadm -o uninstallfeature
• stsadm -o activatefeature
• stsadm -o deactivatefeature
------------------Q)What types of SharePoint assets can be deployed with a SharePoint feature?
With Features we can do a lot. For example, you could deploy as follows
* Simple site customizations
* Custom site navigation
* WebParts
* pages
* list types
* list instances
* event handlers
* workflows
* custom actions
Q)What are event receivers?
Event receivers are classes that inherit from the SpItemEventReciever or SPListEventReciever base class (both of which derive out of the abstract base class SPEventRecieverBase), and provide the option of responding to events as they occur within SharePoint, such as adding an item or deleting an item .
SPListEventReceiver, SPItemEventReciever, and SPWebEventReceiver inherit from the abstract base class SPEventReceiverBase.
SPWorkflowLibraryEventReceiver inherits from SPItemEventReceiver.
SPEmailEventReceiver inherits directly from System.Object
Q) What are the built in ways to backup a SharePoint install?
Through the central administration and the stsadm command
Q) What are the differences between the two base classes ?
The difference is the Microsoft.SharePoint.WebPartPages.WebPart base class is meant for backward compatibility with previous versions of SharePoint. The benefit of using the SharePoint WebPart base class is it supported:
* 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
Q) how can debugging share point application ?
1. build application place .dll into gac and reset iis
2. On the Debug menu, select Attach to Process
3. select the Show processes from all users check box.
4. select W3Wp.exe can attach
5. refresh sharepoint site point break point
Q) Difference SPSite and SPWeb object
The SPSite object represents a collection of sites (site collection [a top level sites and all its subsites]).
The SPWeb object represents an instance SharePoint Web, and SPWeb object contains things like the actual content.
A SPSite object contains the various subsites and the information regarding them.
SPSite rootSite = new SPSite("http://jaganinfo-pc:1234/");
SPWeb objWeb = rootSite.OpenWeb();
Q) How do you connect to a SharePoint list and insert a new List Item?
using(SPSite rootSite = new SPSite("http://jaganinfo-pc:1234/"))
{
using(SPWeb objWeb = mySite.OpenWeb())
{
SPList interviewList = myWeb.Lists["listtoinsert"];
SPListItem newItem = interviewList.Items.Add();
newItem["interview"] = "interview";
newItem.Update();
}
}
Q) How would you loop using SPList through all SharePont List items, assuming you know the name (in a string value) of the list you want to iterate through, and already have all the site code written?
SPList interviewList = rootWeb.Lists["listtoiterate"];
foreach (SPListItem interview in interviewList)
{
// Append the code as per your requirement
}
Q) How could you append a string to the title of a site when it is provisioned?
In the OnActivated event:
SPWeb objWeb = siteCollection.RootWeb;
objWeb.Title += "JaganInfo.com";
objWeb.Update();
Q) What is the difference between SPListItem.SystemUpdate and SPListItem.Update Method
SPListItem.SystemUpdate:
Updates the database(Sharepoint list) with changes that are made to the list item, without effecting changes in the Modified Time or Modified By fields.
SPListItem.SystemUpdate Overloaded Method:
SPListItem.SystemUpdate():
Updates the database with changes made to the list item, without effecting changes in the Modified or Modified By fields.
SPListItem.SystemUpdate(Boolean):
Updates the database with changes that are made to the list item, without effecting changes in the Modified Time or Modified By fields, or optionally, the item version.
SPListItem.Update():
Updates the database(Sharepoint list) with changes that are made to the list item/new version of item, and changes in the Modified Time or Modified By fields.
//Take the reference of that item
SPListItem listItem = listItemCOll[icount];
listItem["FIRST_NAME"] = “Jagan”;
listItem["LAST_NAME"] = “Mohan”;
listItem["EMAIL_ADDR"] = “jaganinfoway[at]gmail.com”;
//Update the Item
listItem.SystemUpdate(false);
//The argument false informs the SP object Model not increment versions.
listItem.Update();