Thursday, November 28, 2013

Add a user to a custom group in SharePoint Group - A Function to serve the purpose


How do i add a user to a group using SharePoint Object Model.

The following function will help you to achieve this...

1. Get the loginname of the user and pass it to the following function
2. the following code adds the user to the Sharepoint Group called MYSite_MyGroup1.

public void AddUser(strloginName)
{
if (!string.IsNullOrEmpty(strloginName))
 {                                                                //Gets the Collection of Site Groups
                                SPGroupCollection objSPSiteGroups = objSPWeb.SiteGroups;
                               string  strCustomGroupName = "MYSite_MyGroup1";
                                if (objSPSiteGroups != null && !string.IsNullOrEmpty(strloginName))
                                {                                                                     
                                        // Adds the new user to the MYSite_MyGroup1 group
                                        objSPgpUserGroup = objSPWeb.SiteGroups[strCustomGroupName];

     // Make sure that the user is added to site . the following built in method makes sure it is added to the site
                                        objnewUser = objSPWeb.EnsureUser(strloginName);                                    


              //Add the user to group                         
                                        objSPgpUserGroup.AddUser(objnewUser);
                                        objSPgpUserGroup.Update();                                 
                                   

                                 }
 }
}


And thats it...

Monday, November 25, 2013

How to remove an event Handler from a list ? A method to detach the event handler

In my previous post i explained about a method to add/attach an event handler to a list.

Now what would you do to remove an event handler from a list ?

The following function would help you to achieve the same in sharepoint..

Just like in the adding event handler post , create the following method.



  private void RemoveHandler(SPList objlist, string strrecieverName)
        {
            try
            {
              
                Guid objGuid = new Guid();
                SPEventReceiverDefinition objEvent = objlist.EventReceivers.Cast<SPEventReceiverDefinition>().FirstOrDefault(l=>string.Compare(l.Name,strrecieverName,true)==0);
                if (objEvent != null)
                {
                    objGuid = objEvent.Id;
                }

                if (objGuid.CompareTo(System.Guid.Empty) != 0)
//Deletes the eventHandler object
                    objEvent.Delete();
            }
            catch (Exception ex)
            {
                ExceptionPolicy.HandleException(ex, CommonConstants.ITI_EXCEPTION);
            }
        }
----------------------------------------------------------------------------------------------------------------------------------------------


Now call the RemoveHandler() method from the feature deactivating method of Reciever.cs .

This will remove the adding and deleting event handler from the test list respectively.


   public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWeb objweb = (SPWeb)properties.Feature.Parent;
            List<SPList> objspLists = new List<SPList>();
            try
            {
                SPList objTestList = objweb.Lists.Cast<SPList>().FirstOrDefault(l => string.Compare(l.Title, "TestList", true) == 0);
       
                if (TestList!= null)
                {
                   //Remove the adding and deleting event handler from the test
                    RemoveHandler(objTestList , "AddingEventHandler");
                    RemoveHandler(objTestList , "DeletingEventHandler");
                  
                }
            }
            catch (Exception ex)
            {
                ExceptionPolicy.HandleException(ex, CommonConstants.ITI_EXCEPTION);
            }

        }

-----------------------------------------------------------------------------------------------------------------------------------------------------------------


How to attach an event handler to a SharePoint List using C#? a simple reusable method for attaching an event handler

Creation of event handler requires creation of an event receiver class in SharePoint .  For this we would  need to create a feature receiver from the already built in template of visual studio.  Once the receiver is created we can use the following code to attach the event handler to any list.


The following is the code to attach the event handler to the list

Reciever.cs

 private void AddHandler(SPList objList, string strRecieverName, int iseqno, SPEventReceiverType eventType)
        {
            try
            {
                SPEventReceiverDefinitionCollection objEventDefColl = objList.EventReceivers;
                ////Set the values for the Definition object 
                Assembly objAssembly = Assembly.GetExecutingAssembly();
                string strAssemblyName = objAssembly.FullName;
               
// MyCustomClass.cs" is the Name of the class in which the logic is writen to handle various events like adding,updating,deleting
                 string strClassName = "MyCustomClass.cs";
      
                string strReceiverName = strRecieverName;
                string strDefData = "Data";
                int iSequenceNo = iseqno;
                ////Create the Definition object 
                SPEventReceiverDefinition oEventDef = objEventDefColl.Add();
                ////Set the properties
                oEventDef.Name = strReceiverName;
                oEventDef.Assembly = strAssemblyName;
                oEventDef.Class = strClassName;
                oEventDef.Data = strDefData;
                oEventDef.SequenceNumber = iSequenceNo;
                oEventDef.Type = eventType;
                oEventDef.Update();
            }
            catch (Exception ex)
            {
                ExceptionPolicy.HandleException(ex, CommonConstants.ITI_EXCEPTION);
            }
        }


---------------------------------------------------------------------------------------------------------------------------------------------

Now in the reciever.cs file just call the method AddHandler inside the FeatureActivated Mehod.

This will enable the event handler to be attached to the TestList as soon as the feature is activated on thesite


  public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                SPWeb objweb = (SPWeb)properties.Feature.Parent;
                SPList objTestList= objweb.Lists.Cast<SPList>().FirstOrDefault(l => string.Compare(l.Title,TestList, true) == 0);
                //Attach the ItemAdded event and the ItemDeletingEvent
                if (objTestList!= null)
                {
                   
                    AddHandler(objTestList, "AddingEventHandler", 10003, SPEventReceiverType.ItemAdding);
                    AddHandler(objTestList, "DeletingEventHandler", 10002, SPEventReceiverType.ItemDeleting);
                                    
                    
                }
            }
            catch (Exception ex)
            {
                ExceptionPolicy.HandleException(ex, CommonConstants.ITI_EXCEPTION);
            }

        }

--------------------------------------------------------------------------------------------------


Happy SharePointing again :)


Sunday, November 24, 2013

what is the maximum file size limit in Sharepoint 2013 ?

what is the maximum file size limit in SharePoint 2013 ?

Its 2GB.

Yes the maximum size of file should not exceed 2 GB.

Tuesday, October 22, 2013

Handling List with Huge Amount of Data/Items ? -- the Concept of ContentIterator

How to Handle Large list data in SharePoint?
SPQuery Fails for Large Lists Items?
Unable to Retrieve list item from large lists? 

ContentIterator to the rescue...


so how to use it? 
 If indexed column condition return more value than List View Threshold, it handles by batch..

      Simply include the  Microsoft.Office.Server.dll which is available in 14/ISAPI/
2    Include namespace Microsoft.Office.Server.Utilities. as reference


So what it gives us??
· Fetches list items as a batch so it reduces the load.
· Batch Procesing can be stopped at anytime.
· Alternative to SPQuery as it fails for large data greater than list threshold


It works as follows
SPQuery.ListItemCollectionPosition in 2007 MOSS  helps to fetch large number of items efficiently in the batches. ContentIterator.ProcessListItems method make use of SPQuery.ListItemCollectionPosition internally in a such way that its value is less than the list threshold value .

ContentIterator will run through each item in the list, invoking the callback provided for list item processing—in this case, ProcessItem. If an error occurs while iterating the list, then the error function is invoked—in this case, ProcessError. Using this approach the ContentIterator processes the list in pieces and avoids any excessively large queries. This functionality is provided as part of Enterprise Content Management (ECM) in SharePoint Server 2010.


static int exceptions = 0;
static int items = 0;

protected void OnTestContentIterator(object sender, EventArgs args)
{
    items = 0;
    exceptions = 0;
    string query1 = @"<View>
        <Query>
            <Where>
                <And>
                    <BeginsWith>
                        <FieldRef Name='Title' />
                        <Value Type='Text'>A</Value>
                    </BeginsWith>
                </And>
            </Where>
        </Query>
    </View>";

    ContentIterator iterator = new ContentIterator();
    SPQuery listQuery = new SPQuery();
    listQuery.Query = query1;
    SPList list = SPContext.Current.Web.Lists["Parts"];
    iterator.ProcessListItems(list,listQuery,ProcessItem,ProcessError)
    );
}

public    bool ProcessError(SPListItem item, Exception e)
{
    // process the error
    exceptions++;
    return true;
}
public void ProcessItem(SPListItem item)
{
    items++;
    Do what you wish with the item


}


How to check if a user belongs to a SharePoint Group or Not ?

How to check if a user belongs to a SharePoint Group or Not ? 


Well.. its not a big deal these days ..We have one liner functions to do the same in server object model.. so.. just use it ..

The method is called as  IsCurrentUserMemberOfGroup(GroupName) - it returns a true if the user is present in the Group  else it returns a false ..  Here is the sample code for the same.... 

private bool IsMember()
{
bool isMember;
SPSite site = new SPSite(SiteURL);
SPWeb web = site.OpenWeb();

//Returns true on successfull membership 

isMember = web.IsCurrentUserMemberOfGroup(web.Groups["GroupName"].ID);

web.Close();
site.Close();
return isMember;
}


Happy SharePointing .... 

Tuesday, August 6, 2013

How to Retrieve the user name from Person or Group Field(People Finder) in SharePoint

How to Retrieve the SPUSer Valuesfrom people finder control .

The following function can be used to retrieve the user name and other properties from people finder controls.

There are two classes used here
1. SPFieldUser -- Gets the field or column onformation
2. SPFieldUserValue- -Gets the values from SPUSERFIELD


and here is the code ... enjoy....


 private SPUser GetSPUserNameFromIDEmailGAP(SPList GAPList, SPListItem ObjGroupAuditInformation)
        {

            try
            {
                SPUser user = null;

                
                if (GAPList != null)
                {
//gets the column name
                    SPFieldUser userField = (SPFieldUser)GAPList.Fields["ColumnName"];
//gets the value of spuser
                    SPFieldUserValue fieldValue = (SPFieldUserValue)userField.GetFieldValue(Convert.ToString(ObjGroupAuditInformation["Column name"];


                    if (fieldValue.User != null)
                    {

                        user = fieldValue.User; // you can have all other properties such as fieldvalue.email etc)


                    }

                }

                return user;
            }
            catch (Exception ex)
            {
               
                return null;
            }


        }

Monday, July 29, 2013

Export a List in SPS2010

Navigate to Central Admin--> backup and Recovery -->  Export a list

and Perform the following : Click on the Image to see a  better View













Then Click the Start Export Button





Resource Throttling in Sharepoint 2010 -- Options to Throttle with Screens



Sharepoint 2010 Search --- Whats New in sharepoint Search?

The major Enhancements in Search of sharepoint 2010 are :



  • Platform – improvements to increase customization, to allow developers to extend the platform and build new applications.
  • Management & reliability – including admin webparts, scriptable admin (Windows PowerShell) and improved monitoring including SCOM support.
  • Federation – via OpenSearch with client side software including IE8, Firefox and Windows 7 plus federated providers including Bing, SharePoint 2010 and any searchable RSS feeds and SQL result sets.
  • User Experience – improved user interfaces, including 'visual' navigation, see the screen shot below:
  • Scalability – both content scalability (size of the corpus) and query performance scalability via multiple crawlers, and the ability to both partition and mirror the index.
  • Social and people search – a big element of the improvements in SP2010, allowing search to surface the tacit knowledge stored inside your people by allowing those people themselves to be found. This is heavily tied into the social side of SharePoint such as My Sites and profiles.
  • Relevance – improved algorithms for better matching and ranking capabilities and improved language support.

Monday, July 22, 2013

SharePoint 2013 --here we come



1. New Minimal UI

2. 
SharePoint and Office Apps model.
3. 
Social and Collaboration Features (Interactive feed,Community Site,Follow People,Follow Sites ..)
4. Improved Search
5. Cross-Site Publishing (Improved ECM)
6. 
Shredded Storage
7. Out-of-Box PDF support
8. Minimal Download Strategy (Improve Performance)
9. 
Dual SharePoint 2013 License

Sunday, July 21, 2013

Its raining Questions again


What does AllowUnsafeUpdates do ?

If your code modifies Windows SharePoint Services data in some way, you may need to allow unsafe updates on the Web site, without requiring a security validation. You can do by setting theAllowUnsafeUpdates property. C#:
using(SPSite mySite = new SPSite("yourserver"))
{ using(SPWeb myWeb = mySite.OpenWeb())
{
myWeb.AllowUnsafeUpdates = true;
SPList interviewList = myWeb.Lists["listtoinsert"];
SPListItem newItem = interviewList.Items.Add();
newItem["interview"] = "interview";
newItem.Update();
}
}

- What does RunWithElevatedPrivileges do?

Assume that you have a Web Part in which you want to display information obtained through the Windows SharePoint Services object model, such as the name of the current site collection owner, usage statistics, or auditing information. These are examples of calls into the object model that require site-administration privileges. Your Web Part experiences an access-denied error if it attempts to obtain this information when the current user is not a site administrator. The request is initiated by a nonprivileged user. you can still successfully make these calls into the object model by calling the RunWithElevatedPrivileges method provided by the SPSecurityclass. C#:
SPSite siteColl = SPContext.Current.Site;
SPWeb site = SPContext.Current.Web;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite ElevatedsiteColl = new SPSite(siteColl.ID))
{
using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb(site.ID))
{
string SiteCollectionOwner = ElevatedsiteColl.Owner.Name;
string Visits = ElevatedsiteColl.Usage.Visits.ToString();
string RootAuditEntries = ElevatedSite.RootFolder.Audit.GetEntries().Count.ToString();
}
}
});

- 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.
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

- What are content types ?

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. 
For example, 
-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. 
-You can create a second content type for a customer proposal document with a different set of columns, a workflow, and a different document template.
Then you can attach both the contenttypes to a document library, which allows you to capture metadata based on the contenttype selected during creation of the document.

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


5. Workflow can be applied to what all elements of SharePoint ?

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. 
In short, 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

7. What are the types of input forms that can be created for a workflow ?

You 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.

8. What are ways to create input forms for workflow ?

Two different approaches can be used to develop custom input forms for a WSS workflow template.
You can create your forms by using custom application pages, which are standard .aspx pages deployed to run out of the _layouts directory. ( disadv: lot of code required when compared to Infopath approach)
using Microsoft Office InfoPath 2007 (disadv: picks up a dependenct on MOSS, i.e. it cannot run in a standalone WSS environment)

9. What is the difference between method activity and event activity in WF ?

A method activity is one that performs an action, such as creating or updating a task. An event activity is one that runs in response to an action occurring.

10. What does SPWeb.EnsureUser method do?

Checks whether the specified login name belongs to a valid user of the Web site, and if the login name does not already exist, adds it to the Web site. e.g SPUser usr = myWeb.EnsureUser("mmangaldas");

11. While creating a Webpart, which is the ideal location to Initialize my new controls ?

Override the CreateChildControls method to include your new controls. To make sure that the new controls are initialized.. call 'EnsureChildControls' in the webparts Render method. You can control the exact Rendering of your controls by calling the .Render method in the webparts Render method.

12. How to query from multiple lists ?

Use SPSiteDataQuery to fetch data from multiple lists. more details..

13.How Does SharePoint work?

The browser sends a DAV packet to IIS asking to perform a document check in. PKMDASL.DLL, an ISAPI DLL, parses the packet and sees that it has the proprietary INVOKE command. Because of the existence of this command, the packet is passed off to msdmserv.exe, who in turn processes the packet and uses EXOLEDB to access the WSS, perform the operation and send the results back to the user in the form of XML.

14. 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.

15. What is ServerUpdate() ?

Any changes in the list, i.e. new addition or modification of an item.. the operation is complete by calling the Update method.But if a List is set to maintain versions .. and you are editing an item, but don't want to save it as a new version, then use the SystemUpdate method instead and pass in 'false' as the parameter.

16. What is query.ViewAttributes OR How can you force SPQuery to return results from all the folders of the list?

If you use SPQuery on any SPlist .. it will bring back results from the current folder only. If you want to get results from all the folders in the list.. then you need to specify the scope of the query by the use of ViewAttributes..
e.g. query.ViewAttributes = "Scope=\"Recursive\"";





Work Flow
What is a workflow?

What are the types of workflow that you can design in SharePoint 2010.
List Workflows, Reusable List Workflows and Site workflows

Reusable List Workflows –
Workflow can be associated to any list, library, or content type in the site collection.

Site workflows -is associated to a site

Can you modify the Out-of-Box workflows in SharePoint 2010 ?
In SharePoint 2010, you have an option to customize the Out-of-Box workflows.

Events
Actions
Conditions
What are the Types of forms associated with the workflow ?

1.       Initiation form – An initiation form gathers information from the workflow participant when they start the workflow.

2.       Task form – A custom task form allows workflow participants to interact with tasks in the Tasks list specified for the workflow. With the Custom Task Wizard, you can easily create custom form fields and add them to a custom task form. When you finish designing the workflow, SharePoint Designer 2010 automatically generates the InfoPath or ASP.NET forms for your custom tasks.

3.       Reusable workflow – association form – A reusable workflow, by default, only provides the fields common to all items, such as Created and Modified by. This is because a reusable workflow isn’t by default associated with a list, library, or content type. An association form enables you to associate fields with a reusable workflow so that the fields will be available when you design and run the workflow.

When are these forms get created ? And how do you customize it ?
Ans. SharePoint Designer 2010 automatically generates the forms, but you can customize them by going to the settings page for the workflow, in the Forms section, click the form you want to customize. Workflow forms are either InfoPath or ASP.NET pages. They are stored on the SharePoint site with the workflow source files.
Administrator

What are the Hardware and Software requirements for SharePoint 2010.

What Has Changed with SSP in SharePoint 2010.
In SharePoint 2010 Shared Service Providers (SSP's) are replaced by Service Applications

Q. What are the Methods of Backup and Recovery in SharePoint 2010?

Ans. Microsoft SharePoint Server 2010 provides a broad range of levels for performing backups, including the entire farm, farm configuration information, site collections, subsites, or lists.

SharePoint Server 2010 uses two different tools to configure backup and recovery.

1. Central Administration : Central Administration provides a user interface where SharePoint Administrators will be prompted via menu structures to select the information that needs to be backed up. (see the Image below)


2. Windows PowerShell : Windows PowerShell is a command line tool that provides SharePoint administrators a way to perform backup and recovery with additional options such as file compression or working with SQL snapshots.

Q. How to Export a Site or List in SharePoint 2010?

Ans. SharePoint Server 2010 provides several new features that provide a granular level of backup for various components of site content. This includes content at the site, subsite, and list level.

Through Central Administration(Granular level Back-up) a SharePoint Administrator can configure a backup of a subsite or list. An Administrator can choose a site and a specific list to be exported.The administrators can also choose to export security and select the different versions that will be exported with the list.



Q. What is Enterprise Metadata Management?
Enterprise metadata management (EMM) is a set of features introduced in Microsoft SharePoint Server 2010 that enable taxonomists, librarians, and administrators to create and manage terms and sets of terms across the enterprise.

What is Business Connectivity Services in SharePoint ?

Ans.SharePoint 2010 provides a new set of technologies known as Business Connectivity Services for retrieving, editing, updating, and deleting data from external systems(for e.g. data from ERP or CRM database). BCS enhances the SharePoint platform’s capabilities with out-of-box features, services and tools that streamline development of solutions with deep integration of external data and services.

General

What are the security improvements in SharePoint 2010 ?

Ans. In SharePoint 2010 a variety of security methods have been introduced.

Claims-Based Authentication - Claims based authentication is based on identity. and trust.

Code Access Security - in which you can specify your own code access
security (CAS) policy for your web parts.

Sandbox Solutions - Sandbox Solutions which when deployed to the server, SharePoint runs in a special process that has limited permissions.

Cross-Site Scripting - Introduced to prevent Cross - Site Scripting (XSS) attacks

Q. Whats New with SharePoint WebParts?

A developer can create two types of webparts using Visual Studio 2010.

1. Visual Webparts - Allows you to Drag and Drop the controls from the Toolbox to WebPart Design surface. You can of course write your custom code in the code file. You can also package and deploy your webparts directly to Sharepoint from VS by pressing Clt+F5. Visual studio 2010 also provides you with three different views for developing webparts. The views are split view, design view and Source view(as we have in designer 2007).

Note : The Visual Webpart project Item basically loads a User Control as a WebPart.


2. ASP.Net WebParts - Where a developer can build up User Interface and logic in a class file. You do not have designer for drag and drop of controls. This webpart inherits from standard ASP.Net webpart. For Deployment we can again use ctrl+f5 to deploy this webpart.


Q. What are the Visual Studio 2010 Tools for SharePoint.

Ans. Visual Studio 2010 includes SharePoint-specific project types and project item types, and includes powerful packaging, deployment, and debugging features that help increase your efficiency as a SharePoint 2010 developer.

Some of the Templates avaiable are :
1.Visual Web Part project template.
2. List defination template.
3. Content Type template.
4. Empty Project template.
5. Event Receiver template.
6. some workflow template.
7. the Site Definition template
and many more....

What are SharePoint Sandboxed soultions ?

Ans. SharePoint 2010 provides a new sandboxed environment that enables you to run user solutions without affecting the rest of the SharePoint farm. This environment means that users can upload their own custom solutions without requiring intervention from administrators, and without putting the rest of the farm at risk. This means that the existing sites\pages or components will not be effected by the newly added soultion.

Users can deploy the below four things as sandboxed soultions :
1. WebParts.
2. Event Receivers.
3. List Definations.
4. Workflows.


Q. What are Requirenments for SharePoint 2010.

Ans. SharePoint Server 2010 will support only 64 - bit. It will require 64 bit Windows Server 2008 or 64 bit Windows Server 2008 R2. In addition to this, it will require 64 bit version of SQL Server 2008 or 64-bit version of SQL Server 2005.


Q. What is LINQ. How is it used in Sharepoint ?

Ans. LINQ is a feature of the programming languages C# 3.0 and Visual Basic .NET. LINQ allows you to query in an object-oriented way, supports compile-time check, gives you intellisense support in Visual Studio and defines a unified, SQL like syntax to query any data source. But unlike other languages and query syntaxes which vary from one type of data source to another, LINQ can be used to query, in principle, any data source whatsoever. It is commonly used to query objects collections, XML and SQL server data sources.

The LINQ to SharePoint Provider is defined in the Microsoft.SharePoint.Linq namespace. It translates LINQ queries into Collaborative Application Markup Language (CAML) queries.

Q. What Changes are made in SharePoint 2010 to enforce Referential Integrity?

Ans. In SharePoint 2010, Referential Integrity is enforced using two options, available with Look-up columns.

While creating a Look-up column, you can either choose a) Restrict Delete or b) Cascade Delete to define a relationship between the Look-up list and the list containing the look-up Column. Read Details at SharePoint 2010 Referential integrity - Using LookUp Column


Q. Whats Ribbon in SharePoint 2010?

Ans. See the Post Ribbon in SharePoint 2010


Q . Whats New in SPALerts ?

Ans. In SharePoint 2007, alerts were send only through e-mails, but in SP2010 users can also send an alert to mobile devices as SMS Message. A New property DeliveryChannels is introduced to indicate, whether the alert is delivered as E-mail or as an SMS Message.


What are the two base classes a WebPart you are going to use within SharePoint 2007 can inherit from?

There are two base classes that a WebPart which is going to be consumed by SharePoint can inherit from, either the SharePoint WebPart Base class or the ASP.NET 2.0 WebPart base class. When inheriting from the SharePoint WebPart Base class your derived WebPart class will inherit from Microsoft.SharePoint.WebPartPages.WebPart. When inheriting from the ASP.NET 2.0 WebPart base class your derived WebPart class will inherit from System.Web.UI.WebControls.WebParts.WebPart. It is considered good practice to use the ASP.NET WebPart base class since the old base class is meant for backwards compatibility with previous version of SharePoint, however there are four exception when it is better to leverage functionality from the SharePoint WebPart base class:
Cross page connections
Connections between Web Parts that are outside of a Web Part zone
Client-side connections (Web Part Page Services Component)
Data caching infrastructure

- What are the differences between the two base classes and what are the inherit benefits of using one over another?

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
ASP.NET 2.0 WebParts are generally considered better to use because SharePoint is built upon the ASP.NET 2.0 web architecture. Inheriting from the ASP.NET 2.0 base class offers you features that inherit to ASP.NET 2.0, such as embedding resources as opposed to use ClassResources for deployment of said types.

- What is the GAC?

The GAC stands for the global assembly cache. It is the machine wide code cache which will give custom binaries place into the full trust code group for SharePoint. Certain SharePoint assets, such as Feature Receivers need full trust to run correctly, and therefore are put into the GAC. You should always try to avoid deployment to the GAC as much as possible since it will possibly allow development code to do more than it was intended to do.

- What is strong naming (signing) a WebPart assembly file mean?

Signing an assembly with a strong name (a.k.a strong naming) uses a cryptographic key pair that gives a unique identity to a component that is being built. This identity can then be referred throughout the rest of the environment. In order to install assemblies into the GAC, they must be strongly named. After signing, the binary will have a public key token identifier which can be use to register the component in various other places on the server.

- What are safe controls, and what type of information, is placed in that element in a SharePoint web.config file?

When you deploy a WebPart to SharePoint, you must first make it as a safe control to use within SharePoint in the web.config file. Entries made in the safe controls element of SharePoint are encountered by the SharePointHandler object and will be loaded in the SharePoint environment properly, those not will not be loaded and will throw an error.
In the generic safe control entry (this is general, there could be more), there is generally the Assembly name, the namespace, the public key token numeric, the typename, and the safe declaration (whether it is safe or not). There are other optional elements.

- What is the CreateChildControls() method? How can you use it to do something simple like displaying a Label control?

The CreateChildControls method in WebParts is used to notify the WebPart that there are children controls that should be output for rendering. Basically, it will add any child ASP.NET controls that are called instantiating each control with its relevant properties set, wire any relevant event handlers to the control, etc. Then the add method of the control class will add the control to the controls collection. In the relevant WebPart render method, the EnsureChildControls method can be called (or set to false if no child controls should be called) to ensure that the CreateChildControls method is run. When using CreateChildControls it implies that your WebPart contains a composition of child controls.
In order to create something like a label control in Create, you would create a new label control using the new keyword, set the various properties of the control like Visible=True and ForeColor = Color.Red, and then use Controls.Add(myLabelControl) to add the control to the controls collection. Then you can declare EnsureChildControls in the Render method of the WebPart.

- What does the RenderContents method do in an ASP.NET 2.0 WebPart?

The render contents method will render the WebPart content to the writer, usually an HtmlTextWriter since WebParts will output to an HTML stream. RenderContents is used to tell how the controls that are going to be displayed in the WebPart should be rendered on the page.
*** Side Question: I got asked what the difference between CreateChildControls and the RenderContents method. The CreateChildControls method is used to add controls to the WebPart, and the RenderContents method is used to tell the page framework how to render the control into HTML to display on a page.

- What is the WebPartManager sealed class? What is its purpose?

The WebPartManager sealed class is responsible for managing everything occurring on a WebPart page, such as the WebParts (controls), events, and misc. functionality that will occur in WebPartZones. For example, the WebPartManager is responsible for the functionality that is provided when you are working with moving a WebPart from WebPartZone to WebPartZone. It is known as the “the central class of the Web Part Control Set.”
*** Side Question: I got asked how many WebPartManager controls should be on a page. In order to have WebParts on a page there has to be just one WebPartManager control to manage all the WebParts on the page.

- What is a SPSite and SPWeb object, and what is the difference between each of the objects?

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.

- How would you go about getting a reference to a site?

C#: 
oSPSite = new  SPSite("http:/server");

oSPWeb = oSPSite.OpenWeb(); 

- What does a SPWebApplication object represent?

The SPWebApplication objects represents a SharePoint Web Application, which essentially is an IIS virtual server. Using the class you can instigate high level operations, such as getting all the features of an entire Web Application instance, or doing high level creation operations like creating new Web Applications through code.

- Would you use SPWebApplication to get information like the SMTP address of the SharePoint site?

Yes, since this is a Web Application level setting. You would iterate through each SPWebApplication in the SPWebApplication collection, and then use the appropriate property calls (OutboundMailServiceInstance) in order to return settings regarding the mail service such as the SMTP address.
Side Question: I got asked if there are other ways to send emails from SharePoint. The answer is yes, there is. You can use the SendMail method from the SPutility class to send simple emails, however it is not as robust as using the System.Net.Mail functionality since it doesn’t allow things like setting priorities on the email.

- How do you connect (reference) to a SharePoint list, and how do you insert a new List Item?

C#: 
using(SPSite mySite = new SPSite("yourserver"))
{
using(SPWeb myWeb = mySite.OpenWeb())
{
SPList interviewList = myWeb.Lists["listtoinsert"];
SPListItem newItem = interviewList.Items.Add();

newItem["interview"] = "interview";
newItem.Update();
}


- 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?

C#: 
SPList interviewList = myWeb.Lists["listtoiterate"];
foreach (SPListItem interview  in interviewList)
{
// Do Something


- How do you return SharePoint List items using SharePoint web services?

In order to retrieve list items from a SharePoint list through Web Services, you should use the lists.asmx web service by establishing a web reference in Visual Studio. The lists.asmx exposes the GetListItems method, which will allow the return of the full content of the list in an XML node. It will take parameters like the GUID of the name of the list you are querying against, the GUID of the view you are going to query, etc.

Side Question: I got asked how I built queries with the lists.asmx web service. In order to build queries with this service, one of the parameters that the GetListItems method exposes is the option to build a CAML query. There are other ways to do this as well, but that was how I answered it.

Rename a Web Application in Sharepoint : A solution using powershell

Here is a small script that will enable you all to change a SharePoint Web Application name . We can use the following SharePoint Pow...