Search This Blog

Thursday, February 12, 2015

SharePoint Some Good Concept

Why do we use properties.current.web instead of SPContext.Current.Web in an event receiver class?
The reason we are using the properties.current.web in the event receiver is because it is not directlyaccessible over the browser.Since a normal custom application is accessible over the browser we can use theSPContext.Current.Web.

What is the use of the .ddf?
The .ddf (Data Directive File) is the file which contains the details of the files and where it needs to be deployed.

It is used when the WSP file is being created, it is sent as a parameter to the MAKECAB.EXE file to generate the WSP file.

What is a different between a Site Column and a Content Type?
Content Type is a collection of Site Columns that can be used throughout the site. Where as a site column is a predefined column, for e.g. it can be a single line of text, multiple lines etc.

What are different types of master pages in SharePoint 2010?
There are basically three types of pages in SharePoint for which we have a corresponding master page, which are as follows:
·         Publishing Pages - these are those pages that are there in the Site Pages document library for e.g. default.aspx --- so we have the Site Master for these kinds of pages.
·         Forms and Views Pages - these are the pages used to view the data stored in the lists and document libraries for e.g. AllItems.aspx --- so we have System Master for these kinds of pages.
·         Application Pages - these are the pages that are stored in the _layouts folder in the server, these are the pages that are used for settings etc. --- so we have Application Master for these kinds of pages.
The different types of master pages that are available in SharePoint 2010 are as follows:
  1. v4.master - this is the default master page
  2. default.master - this is a master page that provides backward compatibility with MOSS 2007
  3. minimal.master - 
  4. simple.master - this is used for the accessdenied, sign out, login, error pages etc.
What is a WSP file? Explain the installation process.
Farm solution installation in Microsoft SharePoint is a system that enables developers to package custom farm solutions and administrators to deploy those farm solutions in a straightforward, safe and consistent manner. Specifically, installation refers to the process of uploading and unpacking solution packages (.wsp files) to front-end web servers and deploying the contents. Web Solution Package is a cabinet file that contains assemblies, resource files, features, images, application pages, site definitions etc. into single file.

When the solution is being added it is stored in the Farm Solution Store table in the farm's configuration database.
When adding a farm solution to the store, the contents of the solution file are validated against an .xsd file to verify that the files contained in it comply with the SharePoint Foundation schemas. If the verification fails, an error message is returned. If the verification succeeds, the process of adding the farm solution continues.

There are two methods of adding a solution to the Farm Solution Store, which are as follows:

·         The first one is through using the stsadm command from within the Management Shell, one can also the Central Admin to deploy the solution after it has been added.
·         Using the Object Model, one needs to call the Add method of the SPFarm.Solution class and then call the SPSolution.Deploy method to deploy the solution.

The steps in installing a farm solution are as follows:

·         Adding - in this process the solution is added to the farm solution store in the configuration database, one needs to have the farm administrator's privilege in order complete the process. It cannot be done from the Central admin it can either be done from the Management Shell or using the Object Model.
·         Deploying - in this process the solution is unpacked and the files are copied to the respective locations, this can done either from the Central Admin, Management Shell or using the Object Model. For this process the user needs the farm administrator's privilege. The deployment step for a farm solution creates a timer job. This timer job is used by the timer service on each web server in the server farm. The timer job also uses the SharePoint Foundation Administrative web service to access appropriate privileges to deploy solution files to each computer, so both services must be running on all servers for the deployment to succeed.
Initially, the package manifest (The description the WSP file is stored in the file "manifest.xml") is parsed to find assemblies, application pages, JavaScript, and other files that are not part of a Feature. These are copied to the locations specified in the manifest. All files contained within a Feature are copied to the Feature directory, a subdirectory of %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\FEATURES. After solution files are copied to the target computers, a configuration reset is scheduled for all front-end web servers; the reset then deploys the files and restarts Internet Information Services (IIS).
For e.g. the user control files (.ascx) are copied to the location %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\ControlTemplates subfolder, assemblies are deployed to the global assembly cache or to a web application's \bin folder and if there are Features in the farm solution, they are copied to a subfolder of %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\FEATURES and installed in the Feature Gallery of the farm, web application, site collection, or website, depending on the scope of the Feature.
·         Activating Feature -  Features must be activated before they can be used, so activating becomes a third step of installation for solutions that contain Features. Features can contain content types, controls, custom actions, custom fields, files, workflows, list instances, list templates, event receivers, and document converters; although some of these cannot be included in certain scopes.

What is the difference between URI and URL?
URI (Uniform Resource Identifier) identifies a resource with by its location or by its name.
It has two parts which are as follows:
·         URL(UniformResourceLocator)
The URL identifies the location of the resource along with the ways to access the resource.
·         URN(UniformResourceName)
The URN identifies a resource by its name in a given namespace, but it does not provide the actual location of the resource and as to how it can accessed.

How can we debug a SharePoint Application or a SharePoint Timer Job
The steps to be followed to debug are as follows:
  1. Build and deploy the application
  2. Set the breakpoint in application
  3. Open up the Debug menu and view all the processes that are running
  4. For SharePoint Applications attach the process "w3wp.exe" and for SharePoint Timer job attach the process "OWSTIMER.exe"
  5. For SharePoint Application just refresh the application and for the timer jobs just run the job from the list

What are zones in SharePoint 2010?
Zones are separate logical paths mapping of the same application, the different zones that are available are as follows:
·         Default
·         Internet
·         Intranet
·         Extranet
·         Custom

What is a farm in SharePoint?
A farm is a collection of SharePoint Servers sharing the same configuration database. The configuration database holds all the information needed to run the servers within the farm and is configured and controlled from the Central Administration.

Wnat is CAML?
CAML (Collaborative Application Markup Language) is a custom XML language provided by SharePoint which is used to manipulate the data stored within SharePoint.

What is a SiteCollection in SharePoint?
A Site Collection is a collection of web sites under a web application.
Under each site collection there will be a top level site and under that there can be multiple child sites.

It is represented as "SPSite" in the object model and each web site under each of the site collection is represented as "SPWeb" in the object model.

What are the steps to configure the My Site?
In order to setup and configure the My Site in SharePoint 2010, the steps to be followed are as follows:

  1. Logon to the Central Admin with the Admin credentials and create a new Web Application in the desired port
  2. Once the web application has been created, create a Site, while creating the site choose the site template as "Enterprise - My Site Host"
  3. After site has been created go to "Central Admin - Application Management - Service Applications - Manage Service Applications - User Profile Service Application"
  4. In the page that opens up click on the link "My Site Settings - Setup My Site"
  5. Under the section "My Site Host" provide the URL of the site that has been created in the steps above
  6. Go to "Central Admin - Application Management - Web Applications - Manage Web Application" and select the site created for My Site and make sure that the option "Self-Service Site Collection Management" has been set to "On"

What do you understand by event receivers in SharePoint?
Event Receivers are custom methods that are written to handle certain events within a list or document library. There are basically two types of event receivers, which are as follows:
·         Synchronous Events - these events are like "ItemAdding" or "Uploading"
·         Asynchronous Events - these events are like "ItemAdded" or "Uploaded" 
The Event Receivers are either derived from the base class "SPListEventReceiver" or "SPItemEventReceiver". 

What are the steps to configure the Enterprise Search Center in SharePoint 2010?
The steps to configure the Enterprise Search Center are as follows:

  1. Firstly go to Central Admin and create a web application
  2. Once the web application has been created, create a site and from the template section choose the template as "Enterprise - Enterprise Search Center"
  3. Under the section "My Site Settings" click on the option "Setup My Site" set the "Preferred Search Center", here you need to provide the URL of the newly created site
What is a WebApplication in SharePoint?
A Web Application is a site in the IIS of the server, the web application can be created from within the Central Administration and has a content database associated with it.

It can have multiple sites under it and can be accessed by the different zones within SharePoint.

It is represented by the "SPWebApplication" object model.

What is difference between SPContext.Current.Web and SPContext.Current.Site.OpenWeb()


To refer SPWeb object sometimes we use SPContext.Current.Web or SPContext.Current.Site.OpenWeb(). Here we will see What are differences between SPContext.Current.Web and SPContext.Current.Site.OpenWeb()

SPContext.Current.Site.OpenWeb()

  1. Creates a new instance of the SPWeb object, and we are responsible to dispose after using it.
  2. OpenWeb() with out sending parameters opens root web of current site collection. If OpenWeb() with parameters opens specific web site.
  3. Expensive call - It cost more resources than reusing an existing one.

SPContext.Current.Web :

  1. Gives you access to the current instance of SPWeb, and you must not dispose it
  2. Gives current Subsite if you are at web other than root web.

What are the view formats for SharePoint Custom List template


When we create a Custom List in SharePoint site, we need to map the list to View. By default when we create List, it will be mapped to "All Items" standard view. But we can change the view for the list. 

Each view is created from View Type and below are the available view types
  1. Standard View  - View data on a Web page. You can choose from a list of display styles.
  2. Calendar View -  View data as a daily, weekly, or monthly calendar.
  3. Datasheet View  - View data in an editable spreadsheet format that is convenient for bulk editing and quick customization. 
  4. Gantt View  - View list items in a Gantt chart to see a graphical representation of how a team's tasks relate over time. 
  5. Custom View in SharePoint Designer  - Start SharePoint Designer to create a new view for this list with capabilities such as conditional formatting. 
In order to see the available view types, Go to Custom List Settings -> Create View -> View Type.

What are the default columns added to SharePoint Custom List template

When we create a Custom List in SharePoint site, By default 5 columns are added to custom list which are
  1. Title (Single line of text) - Mandatory field that defines a title for each list item.
  2. Created (Date and Time) -  When the user has created the current item.
  3. Modified (Date and Time) - When the last user has modified the current item.
  4. Created By (Person or Group) - User who created the current item.
  5. Modified By (Person or Group) - User who last modified the current item.
We can modify the column properties by clicking on Column Name from List Settings.

What is custom list template in sharepoint site

Inbuilt SharePoint provides some predefined list of templates like Announcements,Calendar,Picture Library,Links...etc. If none of templates are meeting you requirement, you can create your own custom list instance and define columns/views for the list. This list is called Custom List.

In-order to create new custom list, Go to Site Contents -> Add an App -> Select Custom List -> Provide Name for Your Custom list.After creating list, add columns and views to it.
Create Column/View for List: Open created Custom List -> List Settings -> Create Column/View

Note: By default every Custom List will have 5 columns (Title, Modified, Created, Created By and Modified By).

What are the various default permission levels in SharePoint site

SharePoint site has different permission levels for the SharePoint Groups. When you create SharePoint site, you can observe the below permissions as default. 

Full Control -   Has full control.
Design -           Can view, add, update, delete, approve, and customize.
Edit -    Can add, edit and delete lists; can view, add, update and delete list items and documents.
Contribute -     Can view, add, update, and delete list items and documents.
Read -  Can view pages and list items and download documents.
Limited Access -          Can view specific lists, document libraries, list items, folders, or documents when given permissions.
Approve -         Can edit and approve pages, list items, and documents.
Manage Hierarchy -    Can create sites and edit pages, list items, and documents.
Restricted Read -         Can view pages and documents, but cannot view historical versions or user permissions.
Restricted Interfaces for Translation - Can open lists and folders, and use remote interfaces.

We can create our own set of permissions also. In order to create new permission, go to site settings -> Users and Permissions -> Site permissions -> Permission Levels(Display list of permissions avalible on site) ->  Add a Permission Level

What is site template in sharepoint

Site Template is a pre-defined set of configuration, layout, and content files that define a site model for an SharePoint application. In built SharePoint has shipped with the set of site templates or we can create our own site templates. 

Each site collection site is associated with a site template. While creating a new site collection for an web application from Central Admin, we need to select a site template from Template Selection section.

Once we crate site collection, share point stores some of the files in the file system of front-end webs servers and some content in back-end databases. When we request for a page from browser, SharePoint engine will decide from where it needs to pick the data either file system or content database.

Sample Site Templates:
Collaboration - Team Site
Collaboration - Blog
Collaboration - Coommunity Site
Enterprise - Document Center
Publishing - Publishing Portal
Publishing - Enterprise Wiki
Service Applications(SA) are software services which run in a SharePoint farm. These are very useful to share information, resources and capabilities across multiple sites/applications/servers in the same share point farm or even across farms.

 

What is Service Applications in SharePoint


Service applications are introduced from SharePoint 2010. Advantage with the Service Applications are salable and extensible.

Sample Service Applications:
Access Services
User Profile Service
User Profile Synchronization Service
SharePoint Server Search      
...

Location of services : Central Administration -> System Settings -> Manage services on server

What is content database in SharePoint

A content database is a database file that stores content for one or more site collections for SharePoint web application. The content can be pages,files,documents,images and much more. So if the Site Collection has more number of SharePoint sites, the content database size grows rapidly.

One SharePoint web application can have more than one content database mapped to it and the max limit is 300 ContentDB's per Web Application. If you want to add more content databases to web application, Go to Central Admin -> Application Management -> Manage Content Databases -> select web application -> Add a content database.

Maximum Content database size is 200 GB in general usage scenarios.

How to Remove User from SharePoint Group programmatically


The snippet shows, how to remove user from SharePoint group. "RemoveUserFromSPGroup" method accepts  3 parameters as SPSite object, LoginName of the user and Group name.
//Removes user from SPGroup
public static void RemoveUserFromSPGroup(SPSite site, string userLoginName, string groupName)
{
    //Executes this method with Full Control rights even if the user does not have Full Control
     SPSecurity.RunWithElevatedPrivileges(delegate
        {
            using (SPWeb spWeb = site.RootWeb)
            {
                try
                {
                    spWeb.AllowUnsafeUpdates = true;//Allows updating web
                    SPUser spUser = spWeb.EnsureUser(userLoginName);
                    //check user and group exists in web
                    if (spUser != null && CheckGroupExistsInSiteCollection(spWeb, groupName))
                    {
                           SPGroup spGroup = spWeb.Groups[groupName];
                           if (spGroup != null)
                                  spGroup.RemoveUser(spUser);
                        }
                }
                catch (Exception)
                {
                    //exception handling
                }
                finally
                {
                    spWeb.AllowUnsafeUpdates = false; //Even Exception occurs it set back to false
                }
            }
        });
}
//checks group exists in site collection
private static bool CheckGroupExistsInSiteCollection(SPWeb web, string groupName)
{
  return web.SiteGroups.OfType<SPGroup>().Count(g => g.Name.Equals(groupName, StringComparison.InvariantCultureIgnoreCase)) > 0;
}
Method call :
SPSite currentSite = SPContext.Current.Site;
SPUser loginName = "Domain\LoginName";
RemoveUserFromSPGroup(currentSite,loginName,"Group Visitors")
Output: 
Removes "Domain\LoginName" user from "Group Visitors" group
Explanation: 
In the code we are using
  • SPSecurity.RunWithElevatedPrivileges - executes code with full control
  • AllowUnsafeUpdates to true - Because we are removing user from SPGroup so AllowUnsafeUpdates allow updates to the web.

SharePoint Get all userprofiles with GetUserProfile method - Performance issue for bulk users


Introduction

On regular SharePoint sites development, we need to fetch the SharePoint user-profiles to grid or some other operations. Recently, We had faced an performance issue for retrieval of SharePoint user-profiles. I tried to address the issue and resolution what we did.

Issue:

We have 2000+ users in Active Directory group and AD group is mapped to a SharePoint group. We need to fetch all the user-profile information for the SharePoint group and show them to a grid. Initially we had written the code as
List<UserProfile> uspList = new List<UserProfile>();
SPSecurity.RunWithElevatedPrivileges(delegate()
{
var serviceContext = SPServiceContext.GetContext(site);
var upm = new UserProfileManager(serviceContext );

List<string> listUsers = (users account name from SharePoint Group);
foreach (var userAccountName in listUsers)
{
UserProfile profile = null;
try
{
profile = upm.GetUserProfile(userAccountName);
}
catch (UserNotFoundException ex)
{
continue;
}
if (profile != null)
{
uspList.Add(profile);
}
}
});
retutn uspList;
The code was fetching all user profile information for each SharePoint group user using GetUserProfile method. The operation was taking about 4-5 minutes. We tried to optimize the performance and look for solution then we found UserProfileManager context object has already have the all user-profiles in it. Just we need to loop through the context object user-profile list (with a check of whether user belongs to group) instead of calling GetUserProfile for each user.

Solution:

SPSecurity.RunWithElevatedPrivileges(delegate()
{
List<string> lstUsers = (users account name from SharePoint Group);
lstUsers = lstUsers.Select(x => x.ToLower()).ToList();
lstUsers = lstUsers.Where(x => x.Contains("|")).Select(x => x.Split('|')[1]).ToList();
foreach (UserProfile userProfile in upm)
{
UserProfileValueCollection profileValue = userProfile[PropertyConstants.AccountName];
if (profileValue != null && profileValue.Value != null && lstUsers.Contains(profileValue.Value.ToString().ToLower()))
{
uspList.Add(userProfile);
}
}
});
After the optimization, the execution time reduced to  seconds.

Conclusion

Calling GetUserProfile method for bulk users is costly operation so use the above code. If we need only single user profile information, use GetUserProfile method.
Note: Here we have not covered, how to fetch list of account names from SharePoint group. Out intention is to improvise the performance on getting user profiles.




No comments:

Post a Comment