Tuesday, June 25, 2013

Basic Operations

Core Object Example


using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
namespace Lesson4_2
{
    class Program
    {
        static void Main(string[] args)
        {
            SPFarm currentFarm = SPFarm.Local;
            Console.WriteLine("Farm:  " + currentFarm.Name);
            foreach (SPService service in currentFarm.Services)
            {
                if (service is SPWebService)
                {
                    SPWebService currentWebService = service as SPWebService;
                    Console.WriteLine("SPWebService:  " + currentWebService.DisplayName);
                    foreach (SPWebApplication webApp in currentWebService.WebApplications)
                    {
                        Console.WriteLine("--Web Application:  " + webApp.DisplayName + " contains " + webApp.Sites.Count.ToString() + " SPSite objects.");
                        foreach (SPSite siteCollection in webApp.Sites)
                        {
                            Console.WriteLine("----Site Collection:  " + siteCollection.Url + " contains " + siteCollection.AllWebs.Count.ToString() + " SPWeb objects.");
                            foreach (SPWeb web in siteCollection.AllWebs)
                            {
                                Console.WriteLine("------Web Site:  " + web.Title + " contains " + web.Lists.Count.ToString() + " SPList objects.");
                                Console.WriteLine("--------Lists:  ");
                                foreach (SPList list in web.Lists)
                                {
                                    Console.WriteLine("----------" + list.Title);
                                }
                            }
                        }
                    }
                }
            }
            Console.WriteLine("*************  DONE  **************...Press any key to continue");
            Console.ReadLine();
        }
    }
}

Feature Which will create site collection on web application level.

SPWebApplication objWebApplication = properties.Feature.Parent as SPWebApplication;
            if (objWebApplication.Name == "TrainingWebApp")
            {
                SPSiteCollection objSitecollection = objWebApplication.Sites;
                if (objSitecollection["sites/TrainingSite1"] == null)
                {
                    SPSite objSite = objSitecollection.Add("sites/TrainingSite", "RAJ-PC\\raj", "rajsharma@gmail.com");
                }
            }
 
 

Feature Which will modify the site properties on feature activated

 public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWeb objWeb = properties.Feature.Parent as SPWeb;
            objWeb.Title = "Training Site Title has been changed";
            objWeb.Description = "Training Site Description has been changed";
            objWeb.Update();
        }
       
        // Uncomment the method below to handle the event raised before a feature is deactivated.
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWeb objWeb = SPContext.Current.Site.RootWeb;
            objWeb.Title = "Training Site";
            objWeb.Description = "Training Site";
            objWeb.Update();
        }
 

Three Technique to dispose objects

protected void Page_Load(object sender, EventArgs e)
        {
            DisposeTechniqueFirst();
            DisposeTechniqueSecound();
            DisposeTechniqueThird();
           
        }
      
        private void DisposeTechniqueFirst()
        {
            using (SPSite objSite = new SPSite("http://raj-pc:28498/sites/TrainingSite"))
            {
                Response.Write("Current Site URL :- " + objSite.Url.ToString());
            }
            using (SPSite firstSite = new SPSite("http://raj-pc:28498/sites/TrainingSite"))
            {
                Response.Write("First Site URL :- " + firstSite.WebApplication.Sites[0].Url.ToString());
            }
            using (SPSite secondSite = new SPSite("http://raj-pc:28498/sites/TrainingSite"))
            {
                Response.Write("Secound Site URL :- " + secondSite.WebApplication.Sites["/"].Url.ToString());
            }
            using (SPSite thirdSite = new SPSite("http://raj-pc:28498/sites/TrainingSite"))
            {
                Response.Write("third Site URL :- " + thirdSite.WebApplication.Sites["sites/TrainingSite"].Url.ToString());
            }
        }
        private void DisposeTechniqueSecound()
        {
            SPSite objSite = null;
            SPSite firstSite = null;
            SPSite secoundSite = null;
            SPSite thirdSite = null;
            try
            {
                objSite = new SPSite("http://raj-pc:28498/sites/TrainingSite");
                Response.Write("Current Site URL :- " + objSite.Url.ToString());
                firstSite = new SPSite("http://raj-pc:28498/sites/TrainingSite");
                Response.Write("First Site URL :- " + firstSite.WebApplication.Sites[0].Url.ToString());
                secoundSite = new SPSite("http://raj-pc:28498/sites/TrainingSite");
                Response.Write("Secound Site URL :- " + firstSite.WebApplication.Sites["/"].ToString());
                thirdSite = new SPSite("http://raj-pc:28498/sites/TrainingSite");
                Response.Write("third Site URL :- " + thirdSite.WebApplication.Sites["sites/it"].Url.ToString());
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if(objSite!=null)
                    objSite.Dispose();
                if(firstSite!=null)
                    firstSite.Dispose();
                if(secoundSite!=null)
                    secoundSite.Dispose();
                if(thirdSite!=null)
                    thirdSite.Dispose();
            }
        }
        private void DisposeTechniqueThird()
        {
                SPSite objSite = SPContext.Current.Site;
                Response.Write("Current Site URL :- " + objSite.Url.ToString());
                SPSite firstSite = SPContext.Current.Site.WebApplication.Sites[0];
                Response.Write("First Site URL :- " + firstSite.Url.ToString());
                SPSite secondSite = SPContext.Current.Site.WebApplication.Sites["/"];
                Response.Write("Secound Site URL :- " + secondSite.Url.ToString());
                SPSite thirdSite = SPContext.Current.Site.WebApplication.Sites["/sites/it"];
                Response.Write("third Site URL :- " + thirdSite.Url.ToString());
        }
    }
 

ListItemOperation

protected void Page_Load(object sender, EventArgs e)
        {
           
        }
        private void BindGrid(SPWeb objWeb)
        {
            SPList objList = objWeb.Lists["Market"];
            SPListItemCollection objItems = objList.Items;
            DataTable dttable = objItems.GetDataTable();
            GridView1.DataSource = dttable;
            GridView1.DataBind();
        }
        protected void Button6_Click(object sender, EventArgs e)
        {
            SPWeb objWeb = SPContext.Current.Web;
            BindGrid(objWeb);
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            SPWeb objWeb = SPContext.Current.Web;
            SPList objList = objWeb.Lists["Market"];
            SPListItem objItem = objList.Items.Add();
            objItem["Market"] = "Test Market";
            objItem["Country Key"] = "460";
            objItem["Country Abbreviation"] = "TE";
            objItem.Update();
            BindGrid(objWeb);
        }
        protected void Button2_Click(object sender, EventArgs e)
        {
            SPWeb objWeb = SPContext.Current.Web;
            SPList objList = objWeb.Lists["Market"];
            SPListItem objItem = objList.GetItemById(200);
            objItem["Market"] = "Palestine Changed";
            //objItem["Country Key"] = "460";
            objItem["Country Abbreviation"] = "Palestine Change";
            objItem.Update();
            BindGrid(objWeb);
        }
        protected void Button3_Click(object sender, EventArgs e)
        {
            SPWeb objWeb = SPContext.Current.Web;
            SPList objList = objWeb.Lists["Market"];
            //SPListItem objItem = objList.Items[272];
            objList.Items.DeleteItemById(272);
            //objItem.Delete();
            BindGrid(objWeb);
               
        }
        protected void Button4_Click(object sender, EventArgs e)
        {
            SPWeb objWeb = SPContext.Current.Web;
            SPList objList = objWeb.Lists["Market"];
            SPListItem objItem = objList.GetItemById(264);
            Response.Write(objItem["Market"]);
        }
       
        protected void Button5_Click(object sender, EventArgs e)
        {
            SPWeb objWeb = SPContext.Current.Web;
            SPList objList = objWeb.Lists["Market"];
            SPQuery myQuery = new SPQuery();
            myQuery.Query = "<Where><Gt><FieldRef Name='ID'/><Value Type='Counter'>80</Value></Gt></Where>";
            SPListItemCollection myItems = objList.GetItems(myQuery);
            DataTable dttable = myItems.GetDataTable();
            GridView1.DataSource = dttable;
            GridView1.DataBind();
        }

DocumentLiberaryOperations

protected void Page_Load(object sender, EventArgs e)
        {
            DisplayFileInfoFromDocumentLib();
            DisplayFoldersInfoFromDocumentLib();
            MoveFiles();
        }
        private void MoveFiles()
        {
            SPSite oSiteCollection = SPContext.Current.Site;
            SPWeb oWebsiteSrc = oSiteCollection.AllWebs["Source_Site_Name"];
            SPWebCollection collWebsites =
                oSiteCollection.AllWebs["Destination_Site_Name"].Webs;
            SPFile oFile = oWebsiteSrc.GetFile("Source_Folder_Name/Source_File");
            string strFilename = oFile.Name;
            byte[] binFile = oFile.OpenBinary();
            foreach (SPWeb oWebsite in collWebsites)
            {
                if (oWebsite.GetFolder("Shared Documents").Exists)
                {
                    SPFolder oFolder = oWebsite.GetFolder("Shared Documents");
                    oFolder.Files.Add(strFilename, binFile, true);
                }
                oWebsite.Dispose();
            }
            oWebsiteSrc.Dispose();
        }
        private void DisplayFoldersInfoFromDocumentLib()
        {
            SPSite objSiteCollection = null;
            SPWebCollection objwebCollection =null;
            SPDocumentLibrary objDocumentLib = null;
            try
            {
                objSiteCollection = SPContext.Current.Site;
                objwebCollection = objSiteCollection.AllWebs;
                foreach (SPWeb objweb in objwebCollection)
                {
                    SPFolderCollection objFolderColl = objweb.Folders;
                    foreach(SPFolder objFolder in objFolderColl)
                    {
                        foreach (SPFile objFile in objFolder.Files)
                        {
                            SPFileCollection collFiles = objFolder.Files;
                            long lngTotalFileSize = 0;
                            for (int intIndex = 0; intIndex < collFiles.Count; intIndex++)
                            {
                                lngTotalFileSize += collFiles[intIndex].Length;
                            }
                            lblFilesInformation.Text += " Web: " +
                                SPEncode.HtmlEncode(objweb.Name)
                                + " Folder: " +
                                SPEncode.HtmlEncode(objFolder.Name) + " Number: "
                                + objFolder.Files.Count +
                                " Size: " + lngTotalFileSize + "<BR>";
                        }
                    }
                   
                }
            }
            catch (Exception en)
            {
                string ex = en.Message.ToString();
            }
            finally
            {
                if (objSiteCollection != null)
                    objSiteCollection.Dispose();
            }
        }
       
        private void DisplayFileInfoFromDocumentLib()
        {
            SPSite objSiteCollection = null;
            SPWebCollection objwebCollection =null;
            SPDocumentLibrary objDocumentLib = null;
            try
            {
                objSiteCollection = SPContext.Current.Site;
                objwebCollection = objSiteCollection.AllWebs;
                foreach (SPWeb objweb in objwebCollection)
                {
                    foreach (SPList objList in objweb.Lists)
                    {
                        if (objList.BaseType == SPBaseType.DocumentLibrary)
                        {
                            objDocumentLib = (SPDocumentLibrary)objList;
                            if (!objDocumentLib.IsCatalog && objDocumentLib.BaseTemplate != SPListTemplateType.XMLForm)
                            {
                                SPListItemCollection objDocumentLibCollection = objDocumentLib.Items;
                                foreach (SPListItem objItem in objDocumentLibCollection)
                                {
                                    lblDocumentInfo.Text += SPEncode.HtmlEncode(objList.Title);
                                    if (objItem["Title"] != null && objItem["Title"] != string.Empty)
                                    {
                                        lblDocumentInfo.Text += "<br>" + "----" + SPEncode.HtmlEncode(objItem["Title"].ToString());
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception en)
            {
                string ex = en.Message.ToString();
            }
            finally
            {
                if (objSiteCollection != null)
                    objSiteCollection.Dispose();
            }
        }
       
    }
 

Course Content Type

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Field ID="{26DDE95B-311E-45C0-BBA6-5094773A272B}" Type="Lookup" List="Lists/Courses" ShowField="Title" Name="CourseTitle" DisplayName="Course Title" Required="FALSE" Group="Training Site Columns"/>
  <Field ID="{25A98C28-CF1D-4F55-AA77-B283C0575422}" Type="Lookup" List="Lists/Trainers" ShowField="FullName" Name="Trainer" DisplayName="Trainer" Required="FALSE" Group="Training Site Columns"/>
  <Field ID="{2B13861E-E2E1-4BB0-B82B-F4AEB754449E}" Type="Choice" Name="Venue" DisplayName="Venue" Required="FALSE" Group="Training Site Columns">
    <CHOICES>
      <CHOICE>Chicago</CHOICE>
      <CHOICE>Denver</CHOICE>
      <CHOICE>Los Angeles</CHOICE>
      <CHOICE>New York</CHOICE>
      <CHOICE>Orlando</CHOICE>
    </CHOICES>
  </Field>
  <Field ID="{5941C6CA-6954-4837-8E1F-8E0EC83A3EA0}" Type="Number" Decimals="0" Min="0" Name="Registrations" DisplayName="Registrations" Required="FALSE" Group="Training Site Columns"/>
  <Field ID="{AE0603BD-A18D-4354-9233-5A5DDAD7EE4B}" Type="Number" Decimals="0" Min="0" Name="TotalSeats" DisplayName="Total Seats" Required="FALSE" Group="Training Site Columns"/>
  <Field ID="{F09920A5-4651-4ACA-8D84-A89C968A484E}" Type="Calculated" ResultType="Number" ReadOnly="TRUE" Name="OpenSeats" DisplayName="OpenSeats" Required="FALSE" Group="Training Site Columns">
    <Formula>=TotalSeats-Registrations</Formula>
    <FieldRefs>
      <FieldRef Name="TotalSeats" ID="{AE0603BD-A18D-4354-9233-5A5DDAD7EE4B}"/>
      <FieldRef Name="Registrations" ID="{5941C6CA-6954-4837-8E1F-8E0EC83A3EA0}"/>
    </FieldRefs>
  </Field>
  <!-- Parent ContentType: Item (0x01) -->
 
  <ContentType ID="0x01002d8405cfe2ef4efc8d2038cc63aeaa9a"
               Name="Class"
               Group="Training Content Types"
               Description="Defines a Class"
               Inherits="TRUE"
               Version="0">
    <FieldRefs>
      <FieldRef ID="{26DDE95B-311E-45C0-BBA6-5094773A272B}" Name="CourseTitle" DisplayName="Course Title" Required="TRUE"/>
      <FieldRef ID="{25A98C28-CF1D-4F55-AA77-B283C0575422}" Name="Trainer" DisplayName="Trainer" Required="FALSE"/>
      <FieldRef ID="{2B13861E-E2E1-4BB0-B82B-F4AEB754449E}" Name="Venue" DisplayName="Venue" Required="FALSE"/>
      <FieldRef ID="{5941C6CA-6954-4837-8E1F-8E0EC83A3EA0}" Name="Registrations" DisplayName="Registrations" Required="FALSE"/>
      <FieldRef ID="{AE0603BD-A18D-4354-9233-5A5DDAD7EE4B}" Name="TotalSeats" DisplayName="Total Seats" Required="FALSE"/>     
      <FieldRef ID="{F09920A5-4651-4ACA-8D84-A89C968A484E}" Name="OpenSeats" DisplayName="Open Seats" Required="FALSE"/>
    </FieldRefs>
  </ContentType>
</Elements>
 

Class Content Type

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Field ID="{26DDE95B-311E-45C0-BBA6-5094773A272B}" Type="Lookup" List="Lists/Courses" ShowField="Title" Name="CourseTitle" DisplayName="Course Title" Required="FALSE" Group="Training Site Columns"/>
  <Field ID="{25A98C28-CF1D-4F55-AA77-B283C0575422}" Type="Lookup" List="Lists/Trainers" ShowField="FullName" Name="Trainer" DisplayName="Trainer" Required="FALSE" Group="Training Site Columns"/>
  <Field ID="{2B13861E-E2E1-4BB0-B82B-F4AEB754449E}" Type="Choice" Name="Venue" DisplayName="Venue" Required="FALSE" Group="Training Site Columns">
    <CHOICES>
      <CHOICE>Chicago</CHOICE>
      <CHOICE>Denver</CHOICE>
      <CHOICE>Los Angeles</CHOICE>
      <CHOICE>New York</CHOICE>
      <CHOICE>Orlando</CHOICE>
    </CHOICES>
  </Field>
  <Field ID="{5941C6CA-6954-4837-8E1F-8E0EC83A3EA0}" Type="Number" Decimals="0" Min="0" Name="Registrations" DisplayName="Registrations" Required="FALSE" Group="Training Site Columns"/>
  <Field ID="{AE0603BD-A18D-4354-9233-5A5DDAD7EE4B}" Type="Number" Decimals="0" Min="0" Name="TotalSeats" DisplayName="Total Seats" Required="FALSE" Group="Training Site Columns"/>
  <Field ID="{F09920A5-4651-4ACA-8D84-A89C968A484E}" Type="Calculated" ResultType="Number" ReadOnly="TRUE" Name="OpenSeats" DisplayName="OpenSeats" Required="FALSE" Group="Training Site Columns">
    <Formula>=TotalSeats-Registrations</Formula>
    <FieldRefs>
      <FieldRef Name="TotalSeats" ID="{AE0603BD-A18D-4354-9233-5A5DDAD7EE4B}"/>
      <FieldRef Name="Registrations" ID="{5941C6CA-6954-4837-8E1F-8E0EC83A3EA0}"/>
    </FieldRefs>
  </Field>
  <!-- Parent ContentType: Item (0x01) -->
 
  <ContentType ID="0x01002d8405cfe2ef4efc8d2038cc63aeaa9a"
               Name="Class"
               Group="Training Content Types"
               Description="Defines a Class"
               Inherits="TRUE"
               Version="0">
    <FieldRefs>
      <FieldRef ID="{26DDE95B-311E-45C0-BBA6-5094773A272B}" Name="CourseTitle" DisplayName="Course Title" Required="TRUE"/>
      <FieldRef ID="{25A98C28-CF1D-4F55-AA77-B283C0575422}" Name="Trainer" DisplayName="Trainer" Required="FALSE"/>
      <FieldRef ID="{2B13861E-E2E1-4BB0-B82B-F4AEB754449E}" Name="Venue" DisplayName="Venue" Required="FALSE"/>
      <FieldRef ID="{5941C6CA-6954-4837-8E1F-8E0EC83A3EA0}" Name="Registrations" DisplayName="Registrations" Required="FALSE"/>
      <FieldRef ID="{AE0603BD-A18D-4354-9233-5A5DDAD7EE4B}" Name="TotalSeats" DisplayName="Total Seats" Required="FALSE"/>     
      <FieldRef ID="{F09920A5-4651-4ACA-8D84-A89C968A484E}" Name="OpenSeats" DisplayName="Open Seats" Required="FALSE"/>
    </FieldRefs>
  </ContentType>
</Elements>

CustomeInterface

//alert('hi');
var statusId = '';
var notifyId = '';
function AddNotification() {
    notifyId = SP.UI.Notify.addNotification("Hello World!", true);
}
function RemoveNotification() {
    SP.UI.Notify.removeNotification(notifyId);
    notifyId = '';
}
function AddStatus() {
    statusId = SP.UI.Status.addStatus("Status good!");
    SP.UI.Status.setStatusPriColor(statusId, 'red');
}
function RemoveLastStatus() {
    SP.UI.Status.removeStatus(statusId);
    statusId = '';
}
function RemoveAllStatus() {
    SP.UI.Status.removeAllStatus(true);
}
function ShowDialog() {
    var options = SP.UI.$create_DialogOptions(); options.url =
"CustomDialogAndStatusbar.aspx"; options.height = 300;
    SP.UI.ModalDialog.showModalDialog(options);
}
 
<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CustomDialogAndStatusbar.aspx.cs" Inherits="CustomInterface.Layouts.CustomInterface.CustomDialogAndStatusbar" DynamicMasterPageFile="~masterurl/default.master" %>
<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
<script type="text/javascript" src="../LearningScript.js"></script>
</asp:Content>
 <asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
  <input id="Button1" type="button" value="Add Notification" onclick="AddNotification()" />
    <input id="Button2" type="button" value="Remove Notification" onclick="RemoveNotification()" />
    <p></p>
    <input id="Button3" type="button" value="Add Status" onclick="AddStatus()" />
    <input id="Button4" type="button" value="Remove Last Status" onclick="RemoveLastStatus()" />
    <input id="Button5" type="button" value="Remove All Status" onclick="RemoveAllStatus()" />
    <input id="Button6" type="button" value="ShowDialogBox" onclick="ShowDialog()" />
 </asp:Content>
 
<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
Application Page
</asp:Content>
<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server" >
My Application Page
</asp:Content>
 
Add a custom Ribbon Tab
Creating a SharePoint Project
--------------------------------------------------------------------------------
To add a new tab, you start by creating an empty SharePoint project.
To create a SharePoint Project
1.Start Visual Studio 2010.
2.On the File menu, point to New, and then click Project.
3.In Project Types, under Visual Basic or C#, select Empty SharePoint Project.
4.Type AddARibbonTab as the project name, and then click OK.
5.In the SharePoint Customization Wizard, select Deploy as a sandboxed solution, and then click Finish.
Adding a new Feature
--------------------------------------------------------------------------------
You customize the ribbon by using a Feature. The following steps add a new Feature to your solution.
To add a new Feature
1.In Solution Explorer, right-click Features, and then select Add Feature.
2.Change the Title of the Feature to Custom Ribbon Tab.
3.In Solution Explorer, right-click Feature1, and then select Rename. Type CustomRibbonTab as the new name.
4.In Solution Explorer, right-click the AddARibbonTab project, point to Add, and then click New Item.
5.In the Add New Item dialog box, select the Empty Element template. Enter CustomRibbonTab as the name.
Defining the Custom Action
--------------------------------------------------------------------------------
The ribbon customization is defined by using ribbon XML in a custom action. For an in-depth explanation of the ribbon XML, see Server Ribbon XML.
To define the custom action
1.Open the Elements.xml file.
2.Paste the following ribbon XML into the Elements.xml file. This adds a new My Custom Tab tab with a group and three buttons on a document library.
1.      <?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<CustomAction
Id="MyCustomRibbonTab"
Location="CommandUI.Ribbon.ListView"
RegistrationId="101"
RegistrationType="List">
<CommandUIExtension>
<CommandUIDefinitions>
<CommandUIDefinition
Location="Ribbon.Tabs._children">
<Tab
Id="Ribbon.CustomTabExample"
Title="My Custom Tab"
Description="This holds my custom commands!"
Sequence="501">
<Scaling
Id="Ribbon.CustomTabExample.Scaling">
<MaxSize
Id="Ribbon.CustomTabExample.MaxSize"
GroupId="Ribbon.CustomTabExample.CustomGroupExample"
Size="OneLargeTwoMedium"/>
<Scale
Id="Ribbon.CustomTabExample.Scaling.CustomTabScaling"
GroupId="Ribbon.CustomTabExample.CustomGroupExample"
Size="OneLargeTwoMedium" />
</Scaling>
<Groups Id="Ribbon.CustomTabExample.Groups">
<Group
Id="Ribbon.CustomTabExample.CustomGroupExample"
Description="This is a custom group!"
Title="Custom Group"
Sequence="52"
Template="Ribbon.Templates.CustomTemplateExample">
<Controls Id="Ribbon.CustomTabExample.CustomGroupExample.Controls">
<Button
Id="Ribbon.CustomTabExample.CustomGroupExample.HelloWorld"
Command="CustomTabExample.HelloWorldCommand"
Sequence="15"
Description="Says hello to the World!"
LabelText="Hello, World!"
TemplateAlias="cust1"/>
<Button
Id="Ribbon.CustomTabExample.CustomGroupExample.GoodbyeWorld"
Command="CustomTabExample.GoodbyeWorldCommand"
Sequence="17"
Description="Says good-bye to the World!"
LabelText="Good-bye, World!"
TemplateAlias="cust2"/>
<Button
Id="Ribbon.CustomTabExample.CustomGroupExample.LoveWorld"
Command="CustomTabExample.LoveWorldCommand"
Sequence="19"
Description="Says I love the World!"
LabelText="I love you, World!"
TemplateAlias="cust3"/>
</Controls>
</Group>
</Groups>
</Tab>
</CommandUIDefinition>
<CommandUIDefinition Location="Ribbon.Templates._children">
<GroupTemplate Id="Ribbon.Templates.CustomTemplateExample">
<Layout
Title="OneLargeTwoMedium"
LayoutTitle="OneLargeTwoMedium">
<Section Alignment="Top" Type="OneRow">
<Row>
<ControlRef DisplayMode="Large" TemplateAlias="cust1" />
</Row>
</Section>
<Section Alignment="Top" Type="TwoRow">
<Row>
<ControlRef DisplayMode="Medium" TemplateAlias="cust2" />
</Row>
<Row>
<ControlRef DisplayMode="Medium" TemplateAlias="cust3" />
</Row>
</Section>
</Layout>
</GroupTemplate>
</CommandUIDefinition>
</CommandUIDefinitions>
<CommandUIHandlers>
<CommandUIHandler
Command="CustomTabExample.HelloWorldCommand"
CommandAction="javascript:alert('Hello, world!');" />
<CommandUIHandler
Command="CustomTabExample.GoodbyeWorldCommand"
CommandAction="javascript:alert('Good-bye, world!');" />
<CommandUIHandler
Command="CustomTabExample.LoveWorldCommand"
CommandAction="javascript:alert('I love you, world!');" />
</CommandUIHandlers>
</CommandUIExtension>
</CustomAction>
</Elements>
Deploying the Customization
--------------------------------------------------------------------------------
1.      Because the project was set up as a sandboxed solution, it is deployed to the Solution Gallery.
2.      To deploy the customization
1.Press F5. The SharePoint development tools in Visual Studio 2010 automatically build and deploy the Feature.
3.      2.Navigate to a document library in your site or subsite.
4.      3.Click the My Custom Tab tab, observe the Custom Group, and then click the Hello, World, Good-bye, World, or I Love You, World buttons.
Walkthrough: Adding a Group to the Server Ribbon
SharePoint 2010 0 out of 5 rated this helpful - Rate this topic Published: May 2010
This topic describes how to add a new group to the Server ribbon in Microsoft SharePoint Foundation. To add a group, you identify the tab on the ribbon where the group will appear. You also define the controls inside the group and decide how the group will render those controls. The following procedure adds a new group to the Page tab for a website.
Prerequisites
--------------------------------------------------------------------------------
Microsoft SharePoint Foundation 2010
SharePoint development tools in Microsoft Visual Studio 2010
Creating a SharePoint Project
--------------------------------------------------------------------------------
To add a new group, you start by creating an empty SharePoint project.
To create a SharePoint project
1.Start Visual Studio 2010.
2.On the File menu, point to New, and then click Project.
3.In Project Types, under Visual Basic or C#, select Empty SharePoint Project.
4.Type AddARibbonGroup as the project name, and then click OK.
5.In the SharePoint Customization Wizard, select Deploy as a sandboxed solution, and then click Finish.
Adding a New Feature
--------------------------------------------------------------------------------
You customize the ribbon by using a Feature. The following steps add a new Feature to your solution.
To add a new Feature
1.In Solution Explorer, right-click Features and then select Add Feature.
2.Change the Title of the Feature to Custom Ribbon Group.
3.In Solution Explorer, right-click Feature1, and then select Rename. Type CustomRibbonGroup as the new name.
4.In Solution Explorer, right-click the AddARibbonGroup project, point to Add, and then click New Item.
5.In the Add New Item dialog box, select the Empty Element template. Type CustomRibbonGroup as the Name.
Defining the Custom Action
--------------------------------------------------------------------------------
The ribbon group is defined by using ribbon XML in a custom action. This identifies where the group will appear on the ribbon. For an in-depth explanation of the ribbon XML, see Server Ribbon XML.
To define the custom action
1.Open the Elements.xml file.
2.Paste the following XML into the Elements.xml file. This XML adds a new Custom group with two buttons on the Page tab for a website.
Important
You must replace the Image32by32 and Image16by16 attributes with valid image URLs.
XMLCopy
<?xml version="1.0" encoding="utf-8"?>
<CustomAction
Id="Ribbon.WikiPageTab.CustomGroup"
Location="CommandUI.Ribbon">
<CommandUIExtension>
<CommandUIDefinitions>
<CommandUIDefinition
Location="Ribbon.WikiPageTab.Groups._children">
<Group
Id="Ribbon.WikiPageTab.CustomGroup"
Sequence="55"
Description="Custom Group"
Title="Custom"
Command="EnableCustomGroup"
Template="Ribbon.Templates.Flexible2">
<Controls Id="Ribbon.WikiPageTab.CustomGroup.Controls">
<Button
Id="Ribbon.WikiPageTab.CustomGroup.CustomGroupHello"
Command="CustomGroupHelloWorld"
Image16by16="Insert an image URL here."
Image32by32="Insert an image URL here."
LabelText="Hello, World"
TemplateAlias="o2"
Sequence="15" />
<Button
Id="Ribbon.WikiPageTab.CustomGroup.CustomGroupGoodbye"
Command="CustomGroupGoodbyeWorld"
Image16by16="Insert an image URL here."
Image32by32="Insert an image URL here."
LabelText="Good-bye, World"
TemplateAlias="o2"
Sequence="18" />
</Controls>
</Group>
</CommandUIDefinition>
<CommandUIDefinition
Location="Ribbon.WikiPageTab.Scaling._children">
<MaxSize
Id="Ribbon.WikiPageTab.Scaling.CustomGroup.MaxSize"
Sequence="15"
GroupId="Ribbon.WikiPageTab.CustomGroup"
Size="LargeLarge" />
</CommandUIDefinition>
</CommandUIDefinitions>
<CommandUIHandlers>
<CommandUIHandler
Command="EnableCustomGroup"
CommandAction=”javascript:return true;” />
<CommandUIHandler
Command="CustomGroupHelloWorld"
CommandAction="javascript:alert('Hello, world!');" />
<CommandUIHandler
Command="CustomGroupGoodbyeWorld"
CommandAction="javascript:alert('Good-bye, world!');" />
</CommandUIHandlers>
</CommandUIExtension>
</CustomAction>
</Elements>
Deploying the Customization
--------------------------------------------------------------------------------
Because the project was set up as a sandboxed solution, it is deployed to the Solution Gallery.
To deploy the customization
1.Press F5. The SharePoint development tools in Visual Studio 2010 automatically build and deploy the Feature.
2.Navigate to the home page of your site or subsite.
3.Click the Page tab, look for the Custom group, and click the Hello, World or Good-bye, World buttons.
Walkthrough: Adding a Button to the Server Ribbon

SharePoint 2010 This topic has not yet been rated - Rate this topic Published: May 2010
This topic describes how to add a new button to the Server ribbon in Microsoft SharePoint Foundation.
Prerequisites
--------------------------------------------------------------------------------
Microsoft SharePoint Foundation 2010
SharePoint development tools in Microsoft Visual Studio 2010
Creating a SharePoint Project
--------------------------------------------------------------------------------
To add a new button, you start by creating an empty SharePoint project.
To create a SharePoint project
1.Start Microsoft Visual Studio 2010.
2.On the File menu, point to New, and then click Project.
3.In Project Types, under Visual Basic or C#, select Empty SharePoint Project.
4.Type AddARibbonButton as the project name. Click OK.
5.In the SharePoint Customization Wizard, select Deploy as a sandboxed solution, and then click Finish.
Adding a new Feature
--------------------------------------------------------------------------------
You customize the ribbon by using a Feature. The following steps add a new Feature to your solution.
To add a new Feature
1.In Solution Explorer, right-click Features, and then click Add Feature.
2.Change the Title of the Feature to Custom Ribbon Button.
3.In Solution Explorer, right-click Feature1, and then click Rename. Type CustomRibbonButton as the new name.
4.In Solution Explorer, right-click the AddARibbonButton project, point to Add, and then select New Item.
5.In the Add New Item dialog box, select the Empty Element template. Type CustomRibbonButton as the name.
Defining the Custom Action
--------------------------------------------------------------------------------
You define the ribbon button by using ribbon XML in a custom action. For an in-depth explanation of the ribbon XML, see Server Ribbon XML.
To define the custom action
1.Open the Elements.xml file.
2.Paste the following XML into the Elements.xml file. This XML adds a new button on the Library tab in the Share & Track group for a document library.
Important
You must replace the Image32by32 and Image16by16 attributes with valid image URLs.
XMLCopy
<?xml version="1.0" encoding="utf-8"?>
<CustomAction
Id="Ribbon.Library.Actions.AddAButton"
Location="CommandUI.Ribbon"
RegistrationId="101"
RegistrationType="List"
Title="Add a Ribbon Button">
<CommandUIExtension>
<CommandUIDefinitions>
<CommandUIDefinition
Location="Ribbon.Library.Share.Controls._children">
<Button Id="Ribbon.Library.Share.NewRibbonButton"
Command="NewRibbonButtonCommand"
Image16by16="Insert an image URL here."
Image32by32="Insert an image URL here."
LabelText="Hello World"
TemplateAlias="o2" />
</CommandUIDefinition>
</CommandUIDefinitions>
<CommandUIHandlers>
<CommandUIHandler
Command="NewRibbonButtonCommand"
CommandAction="javascript:alert('Hello, world');" />
</CommandUIHandlers>
</CommandUIExtension>
</CustomAction>
</Elements>
Deploying the Customization
--------------------------------------------------------------------------------
Because the project was set up as a sandboxed solution, it is deployed to the Solution Gallery.
To deploy the customization
1.Press F5. The SharePoint development tools in Visual Studio 2010 automatically build and deploy the Feature.
2.Navigate to a document library in your site or subsite.
3.Click the Library tab, look in the Share & Track group, and click the Hello World button.
Walkthrough: Removing a Button from the Server Ribbon
SharePoint 2010
1 out of 3 rated this helpful - Rate this topic
Published: May 2010
This topic describes how to remove a button from the Server ribbon in Microsoft SharePoint Foundation.
Prerequisites




SharePoint Foundation 2010
SharePoint development tools in Microsoft Visual Studio 2010
Creating a SharePoint Project




To remove a button, you start by creating an empty SharePoint project.
To create a SharePoint project
1.      Start Visual Studio 2010.
2.      On the File menu, point to New, and then click Project.
3.      In Project Types, under Visual Basic or C#, select Empty SharePoint Project.
4.      Type RemoveARibbonButton as the project name, and then click OK.
5.      In the SharePoint Customization Wizard, select Deploy as a sandboxed solution, and then click Finish.
Adding a New Feature




You customize the ribbon by using a Feature. The following steps add a new Feature to your solution.
To add a new Feature
1.      In Solution Explorer, right-click Features, and then select Add Feature.
2.      Change the Title of the Feature to Remove a Ribbon Button.
3.      In Solution Explorer, right-click Feature1, and then click Rename. Type RemoveARibbonButton as the new name.
4.      In Solution Explorer, right-click the RemoveARibbonButton project, point to Add, and then click New Item.
5.      In the Add New Item dialog box, select the Empty Element template. Type RemoveARibbonButton as the name.
Defining the Custom Action




You remove the ribbon button by using the Location attribute of the CommandUIDefinition element. The default values for ribbon buttons are listed in Default Server Ribbon Customization Locations. For an in-depth explanation of the ribbon XML, see Server Ribbon XML.
To define the custom action
1.      Open the Elements.xml file.
2.      Paste the following XML into the Elements.xml file. This XML removes the Connect to Outlook button on the Library tab in the Connect & Export group for a document library.
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction
    Id="RemoveRibbonButton"
    Location="CommandUI.Ribbon">
      <CommandUIExtension>
        <CommandUIDefinitions>
          <CommandUIDefinition
            Location="Ribbon.Library.Actions.ConnectToClient" />
        </CommandUIDefinitions>
      </CommandUIExtension>
  </CustomAction>
</Elements>
Deploying the Customization




Because the project was set up as a sandboxed solution, it is deployed to the Solution Gallery.
To deploy the customization
1.      Press F5. The SharePoint development tools in Visual Studio 2010 automatically build and deploy the Feature.
2.      Navigate to a document library in your site or subsite.
3.      Click the Library tab, look in the Connect & Export group, and observe the absence of the Connect to Outlook button.
Walkthrough: Replacing a Button on the Server Ribbon
SharePoint 2010
This topic has not yet been rated - Rate this topic
Published: May 2010
This topic describes how to replace a button on the Server ribbon in Microsoft SharePoint Foundation.
Prerequisites




Microsoft SharePoint Foundation 2010
SharePoint development tools in Microsoft Visual Studio 2010
Creating a SharePoint Project




To customize the ribbon, you start by creating an empty SharePoint project.
To create a SharePoint project
1.      Start Microsoft Visual Studio 2010.
2.      On the File menu, point to New, and then click Project.
3.      In Project Types, under Visual Basic or C#, select Empty SharePoint Project.
4.      Type ReplaceARibbonButton as the project name, and then click OK.
5.      In the SharePoint Customization Wizard, select Deploy as a sandboxed solution, and then click Finish.
Adding a new Feature




You customize the ribbon by using a Feature. The following steps add a new Feature to your solution.
To add a new Feature
1.      In Solution Explorer, right-click Features and then click Add Feature.
2.      Change the Title of the Feature to Replace a Ribbon Button.
3.      In Solution Explorer, right-click Feature1, and then select Rename. Type ReplaceARibbonButton as the new name.
4.      In Solution Explorer, right-click the ReplaceARibbonButton project, and point to Add, and then select New Item.
5.      In the Add New Item dialog box, select the Empty Element template. Type ReplaceARibbonButton as the name.
Defining the Custom Action




You replace the ribbon button by using the Location attribute of the CommandUIDefinition element. The default values for ribbon buttons are listed in Default Server Ribbon Customization Locations. For an in-depth explanation of the ribbon XML, see Server Ribbon XML.
To define the custom action
1.      Open the Elements.xml file.
2.      Paste the following XML into the Elements.xml file. This XML replaces the Connect to Outlook button on the Library tab in the Connect & Export group for a document library.
Important
You must replace the Image32by32 and Image16by16 attributes with valid image URLs.
3.      XML
4.      Copy
5. <?xml version="1.0" encoding="utf-8"?>
6. <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
7.   <CustomAction Id="Ribbon.Library.Actions.ReplacementButton"
8.     Location="CommandUI.Ribbon"
9.     RegistrationId="101"
10.    RegistrationType="List"
11.    Title="Replace a Ribbon Button">
12.    <CommandUIExtension>
13.      <CommandUIDefinitions>
14.        <CommandUIDefinition
15.          Location="Ribbon.Library.Actions.ConnectToClient">
16.             <Button Id="Ribbon.Library.Actions.ConnectToClient.ReplacementButton"
17.               Command="ReplacementButtonCommand"
18.               Image16by16="Insert an image URL here."
19.               Image32by32="Insert an image URL here."
20.               LabelText="Replaced Button"
21.               TemplateAlias="o2" />
22.        </CommandUIDefinition>
23.      </CommandUIDefinitions>
24.      <CommandUIHandlers>
25.        <CommandUIHandler
26.          Command="ReplacementButtonCommand"
27.          CommandAction="javascript:alert('This button has been replaced.');" />
28.      </CommandUIHandlers>
29.    </CommandUIExtension>
30.  </CustomAction>
31.</Elements>
32. 
Deploying the Customization




Because the project was set up as a sandboxed solution, it is deployed to the Solution Gallery.
To deploy the customization
1.      Press F5. The SharePoint development tools in Visual Studio 2010 automatically build and deploy the Feature.
2.      Navigate to a document library in your site or subsite.
3.      Click the Library tab, look in the Connect & Export group, and observe the absence of the Connect to Outlook button.

 

WebPart Life Cycle

using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
namespace WebPartLifeCycle
{
    [Guid("7fec4103-43c1-4edf-adcc-cc94db3cdc28")]
    public class Reporter : System.Web.UI.WebControls.WebParts.WebPart
    {
        //variable for reporting events
        private string m_report = "";
        //variable for button and text
        private Button m_button;
        private TextBox m_text;
        protected override void OnInit(EventArgs e)
        {
            m_report += "OnInit<br/>";
            base.OnInit(e);
        }
        protected override void LoadViewState(object savedState)
        {
            m_report += "LoadViewState<br/>";
            object[] viewState = null;
            if (savedState != null)
            {
                viewState = (object[])savedState;
                base.LoadViewState(viewState[0]);
                m_report += (string)viewState[1] + "<br/>";
            }
        }
        protected override void CreateChildControls()
        {
            m_report += "CreateChildControls<br/>";
            m_button = new Button();
            m_button.Text = "Push Me!";
            m_button.Click += new EventHandler(m_button_Click);
            Controls.Add(m_button);
            m_text = new TextBox();
            Controls.Add(m_text);
        }
        protected override void OnLoad(EventArgs e)
        {
            m_report += "OnLoad<br/>";
            base.OnLoad(e);
        }
        void m_button_Click(object sender, EventArgs e)
        {
            m_report += "Button Click<br/>";
        }
        protected override void OnPreRender(EventArgs e)
        {
            m_report += "OnPreRender<br/>";
            base.OnPreRender(e);
        }
        protected override object SaveViewState()
        {
            m_report += "SaveViewState<br/>";
            object[] viewState = new object[2];
            viewState[0] = base.SaveViewState();
            viewState[1] = "myData";
            return viewState;
        }
        protected override void RenderContents(HtmlTextWriter writer)
        {
            m_report += "RenderContents<br/>";
            writer.Write(m_report);
            m_text.RenderControl(writer);
            m_button.RenderControl(writer);
        }
        public override void Dispose()
        {
            base.Dispose();
        }
        protected override void OnUnload(EventArgs e)
        {
            base.OnUnload(e);
        }



    }
 

Create Property WebPart
public class CreatePropertyWebPart : WebPart
    {
        string CustomPath = "";
        [Personalizable(PersonalizationScope.Shared),WebBrowsable(true),WebDescription("CustomPropertyPath"),WebDisplayName("DisplayName")]
        public string CustomPath1
        {
          get { return CustomPath; }
          set { CustomPath = value; }
        }
       
        protected override void CreateChildControls()
        {
        }
        protected override void Render(HtmlTextWriter writer)
        {
            writer.Write(CustomPath.ToString());
            base.Render(writer);
        }
    }

Event Reciever

 public override void ItemAdded(SPItemEventProperties properties)
       {
           if (properties.ListTitle == "Courses")
           {
               //Ensure the RegistrationID is unique
               string classId = properties.ListItem["RegistrationID"].ToString();
               string id = properties.ListItem["ID"].ToString();
               properties.ListItem["RegistrationID"] = classId + "-" + id;
               properties.ListItem.Update();
               //Find the class for which the student has registered and increase the "Registrations" column by 1.
               SPWeb currentWeb = properties.Web;
               SPList classesList = currentWeb.Lists["Classes"];
               SPListItem currentClass = classesList.GetItemById(Convert.ToInt32(classId));
               currentClass["Registrations"] = Convert.ToInt32(currentClass["Registrations"].ToString()) + 1;
               currentClass.Update();
           }
           base.ItemAdded(properties);
       }
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Receivers ListUrl ="Lists/Courses">
      <Receiver>
        <Name>ER_Registrations_ItemAddedItemAdded</Name>
        <Type>ItemAdded</Type>
        <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
        <Class>TrainingEventReceivers.ER_Registrations_ItemAdded.ER_Registrations_ItemAdded</Class>
        <SequenceNumber>10000</SequenceNumber>
      </Receiver>
  </Receivers>
</Elements>

 

ItemAdding

 public class ER_Registrations_ItemAdding : SPItemEventReceiver
    {
        HttpContext httpContext = null;
        public ER_Registrations_ItemAdding()
        {
            httpContext = HttpContext.Current;
        }
       /// <summary>
       /// An item is being added.
       /// </summary>
       public override void ItemAdding(SPItemEventProperties properties)
       {
           if (properties.ListTitle == "Courses")
           {
               //Set the Title (RegistrationID column)
               Uri currentUri = httpContext.Request.Url;
               string queryString = currentUri.Query;  //?classid=111
               string classId = queryString.Remove(0, 9);
               properties.AfterProperties["Title"] = classId;
           }
           base.ItemAdding(properties);
       }
 

ItemDeleting

 public class ER_Registrations_ItemDeleting : SPItemEventReceiver
    {
       /// <summary>
       /// An item is being deleted.
       /// </summary>
       public override void ItemDeleting(SPItemEventProperties properties)
       {
           if (properties.ListTitle == "Courses")
           {
               //Before the registration is completely deleted, find the class and decrease the number of registrations for it
               string registrationID = properties.ListItem["RegistrationID"].ToString();  //80-43
               int hyphenIndex = registrationID.IndexOf("-");  //2
               string classId = registrationID.Substring(0, hyphenIndex);  //80
               SPWeb currentWeb = properties.Web;
               SPList classesList = currentWeb.Lists["Classes"];
               SPListItem currentClass = classesList.GetItemById(Convert.ToInt32(classId));
               currentClass["Registrations"] = Convert.ToInt32(currentClass["Registrations"].ToString()) - 1;
               currentClass.Update();
           }
           base.ItemDeleting(properties);
       }