Monday, June 30, 2014

Safe Control enteries in your web.config for the particular web application.(sharepoint 2010)

Web Part Error: A Web Part or Web Form Control on this Page cannot be displayed or imported. The type SunInt.Hrda.SharePoint.MaintainBudget.MaintainBudget, SunInt.Hrda.SharePoint, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b21a70e7493d978f could not be found or it is not registered as safe.


  1. Select your custom webpart
  2. Use right click > Properties
  3. In properties windows under SharePoint find Safe Control Entries
  4. Click ... button
  5. Verify your settings (namespace)

Thursday, June 19, 2014

Debugging SharePoint 2010 Web Parts from Visual Studio 2010


Most of you probably already have figured this out, but for those of you who still have not, here is how you can debug your web part in Visual Studio 2010:
  1. Deploy your Web Part
  2. Add the Web Part to Page
  3. In your code, create a break point.
  4. Go to “Debug” menu, and choose “Attach to Process”.
  5. Under “Attach to:” section, click on “Select …” button.
  6. Uncheck all options, checking ONLY “Managed (v2.0, v1.1, v1.0) code”.
  7. Check the “Show processes in all sessions” checkbox.
  8. Select all “w3wp.exe” Processes, then click on the “Attach” button.
  9. Run your page that contains the Web Part. You should now hit your break point, and will be able to step through your code.

Wednesday, June 18, 2014

force a page to postback using javascript in c#

protected override void Render(HtmlTextWriter output) {
                  output.Write("<a  id=\"" + this.UniqueID + "\" href=\"javascript:"
 + Page.GetPostBackEventReference(this) +"\">");
                  output.Write(" " + this.UniqueID + "</a>");

}

Wednesday, June 11, 2014

install or remove or retract wsp in SP


Follow the steps for STSADM:
  1. Open command prompt and navigate to C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN
  2. Use the stsadm command = stsadm -o retractsolution -name solutionName.wsp -immediate
  3. and then remove the wsp = stsadm -o deletesolution -name solutionName.wsp
Follow the steps for Powershell:
  1. Go to All Programs => Microsoft SharePoint 2010 Products =>SharePoint 2010 Management Shell =>Run as administrator
  2. Uninstall-SPSolution -identity "solutionName.wsp"
  3. Remove-SPSolution -identity "solutionName.wsp"

Thursday, June 5, 2014

How to find the name of your configuration database in SharePoint 2010.

This is a quick tip if you need to find the configuration database name. The alternative to the solution below would be connecting to your SQL server and looking through the names of the databases within.
1. Remote into your server in the farm where central admin is installed.
2. Open regedit [Start > Run > "regedit"]
3. Navigate to [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\14.0\Secure\ConfigDB]
4. Open the [dsn] key.
Done! You now have your config database name.
It should look something like this.

Data Source=sp2010srv;Initial Catalog=SharePoint_Config_StyledPoint;Integrated Security=True;Enlist=False;Connect Timeout=15

Tuesday, June 3, 2014

Programmatically Updating SharePoint Web Part Properties

deploy sharepoint -2010- solution- wsp- package using Management Shell

Add the solution
stsadm -o addsolution -filename {path of wsp file}
Example:
stsadm -o addsolution -filename C:\MyTest.wsp

Deploy the solution
stsadm -o deploysolution -name {path of wsp file} -url {URL}
Example:
stsadm -o deploysolution -name MyTest.wsp -url http://URL

Retract solution:
stsadm.exe -o retractsolution -name {path of wsp file}.wsp –URL
Example:
stsadm.exe -o retractsolution -name MyTest.wsp.wsp –URL http://URL

Delete Solution
stsadm.exe -o deletesolution -name {path of wsp file}.wsp
Example:
stsadm.exe -o deletesolution -name MyTest.wsp.wsp

http://www.enjoysharepoint.com/Articles/Details/deploy-sharepoint-2010-solution-wsp-package-using-59.aspx

http://www.fewlines4biju.com/2011/05/deploy-wsp-file-in-sharepoint-2010.html




Deploy using managment shell


STEP 1
Add-SPSolution "C:\Projects\RFB\Deploys\SunInt.Hrda.Controls.wsp"


STEP 2
Install-SPSolution -Identity "SunInt.Hrda.Controls.wsp" -WebApplication http://vr-tl-dev-ap01:99 -GACDeployment -Force

Step1:  Start Power Shell command prompt
Start->All Programs->MicrosoftSharepoint2010Products->open Sharepoint2010Managementshell

Type the command

Step2:  Add Solution Package
Add-SPSolution “C:\SharePoint2010Solution.wsp”

Step3:  Install Solution Package
Install-SPSolution –Identity SharePoint2010Solution.wsp –WebApplication http://myserver –GACDeployment

If you are using Sandbox Solution,

Step4: Install Solution Package
Install-SPUserSolution –Identity SharePoint2010Solution.wsp     –WebApplication http://myserver  –GACDeployment

For Updating the Sharepoint 2010 Solution type the following commands

Step5: Update Solution Package
Update-SPSolution –Identity SharePoint2010Solution.wsp –LiteralPath “C:\SharePoint2010Solution.wsp” –GacDeployment

For retract and remove a solution, type the following commands:

Step 6: Uninstall Solution Package
Uninstall-SPSolution –Identity MySharePointSolution.wsp –WebApplication    http://myserver

Step7: Remove Solution Package
Remove-SPSolution–Identity MySharePointSolution.wsp

Sunday, June 1, 2014

SP webpart Examples

WPEX1 : Display contact Details

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace WPEX1.ContactUs
{
    [ToolboxItemAttribute(false)]
    public class ContactUs : WebPart
    {
        protected override void RenderContents
            (HtmlTextWriter writer)
        {
            writer.WriteLine(
                "<h1 style='color:navy;font-size:12pt;'>Peers</h1>");
            writer.WriteLine(
                "<h2 style='font-size:10pt;'>Ameerpet, Hyd -38</h2>");
        }
    }
}

Ex 2 : Display links to open all lsits and libraries

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace WPEX2.ListsLinks
{
    [ToolboxItemAttribute(false)]
    public class ListsLinks : WebPart
    {
        protected override void RenderContents
            (HtmlTextWriter writer)
        {
            SPWeb web = SPContext.Current.Web;
            foreach (SPList list in web.Lists)
                writer.WriteLine(
                    "<a href= '" +
                    list.DefaultViewUrl +
                    "'>" +
                    list.Title +
                    "</a><br/>");

        }
    }
}

WPEX3 : Calculate Interest to be paid on a loan taken

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace MBWPEX3.InterestCalculator
{
    [ToolboxItemAttribute(false)]
    public class InterestCalculator : WebPart
    {
        TextBox txtAmount, txtRate, txtPeriod, txtInterest;
        Button btnCalculateInterest;
        protected override void CreateChildControls()
        {
            txtAmount = new TextBox();
            Controls.Add(txtAmount);
            txtRate = new TextBox();
            Controls.Add(txtRate);
            txtPeriod= new TextBox();
            Controls.Add(txtPeriod);
            txtInterest= new TextBox();
            txtInterest.ReadOnly = true;
            Controls.Add(txtInterest);
            btnCalculateInterest = new Button();
            btnCalculateInterest.Text = "Calculate Interest";
            Controls.Add(btnCalculateInterest);
            btnCalculateInterest.Click +=
                btnCalculateInterest_Click;

        }

        void btnCalculateInterest_Click
            (object sender, EventArgs e)
        {
            double amount, rate, period, interest;
            amount = Convert.ToDouble(txtAmount.Text);
            rate = Convert.ToDouble(txtRate.Text);
            period = Convert.ToDouble(txtPeriod.Text);
            interest = amount * rate * period / 100;
            txtInterest.Text = interest.ToString();
        }
        protected override void RenderContents
            (HtmlTextWriter writer)
        {
            writer.WriteLine("<table>");

            writer.WriteLine("<tr>");
            writer.WriteLine("<td>Amount</td>");
            writer.WriteLine("<td>");
            txtAmount.RenderControl(writer);
            writer.WriteLine("</td>");
            writer.WriteLine("</tr>");

            writer.WriteLine("<tr>");
            writer.WriteLine("<td>Rate</td>");
            writer.WriteLine("<td>");
            txtRate.RenderControl(writer);
            writer.WriteLine("</td>");
            writer.WriteLine("</tr>");

            writer.WriteLine("<tr>");
            writer.WriteLine("<td>Period</td>");
            writer.WriteLine("<td>");
            txtPeriod.RenderControl(writer);
            writer.WriteLine("</td>");
            writer.WriteLine("</tr>");

            writer.WriteLine("<tr>");
            writer.WriteLine("<td>Interest</td>");
            writer.WriteLine("<td>");
            txtInterest.RenderControl(writer);
            writer.WriteLine("</td>");
            writer.WriteLine("</tr>");

            writer.WriteLine("</table>");
            btnCalculateInterest.RenderControl(writer);

        }
    }
}

SP 2013 Example

Example 11:

The following example queries all lists that were created with
the Contacts list template anywhere in the site collection,
retrieves the first and last names of every contact,
and displays that information.

using System;
using Microsoft.SharePoint;
using System.Data;
namespace KNRao.SP2013Examples
{
    class Program
    {
        static void Main(string[] args)
        {
            using (SPSite mySiteCollection =
            new SPSite("http://sp2013dev/sites/peers487"))
            {
                using (SPWeb web = mySiteCollection.OpenWeb())
                {
                    SPSiteDataQuery query = new SPSiteDataQuery();

                    //Ask for all lists created from the contacts template.
                    query.Lists = "<Lists ServerTemplate=\"105\" />";

                    // Get the Title (Last Name) and FirstName fields.
                    query.ViewFields = "<FieldRef Name=\"Title\" />" +
                                       "<FieldRef Name=\"FirstName\" Nullable=\"TRUE\" Type=\"Text\"/>";
                    // Note that setting the Nullable attribute to TRUE
                    // causes an empty value to be returned for lists that
                    // do not include the FirstName column. The default is
                    // to skip a list that does not include the column.

                    // Set the sort order.
                    query.Query = "<OrderBy>" +
                                      "<FieldRef Name=\"Title\" />" +
                                  "</OrderBy>";

                    // Query all Web sites in this site collection.
                    query.Webs = "<Webs Scope=\"SiteCollection\" />";

                    DataTable dtContacts =
                        web.GetSiteData(query);
                    foreach (DataRow dr in dtContacts.Rows)
                    {
                        Console.WriteLine("Last Name : {0}",
                            dr["Title"]);
                        Console.WriteLine("First Name : {0}",
                            dr["FirstName"]);
                    }

                }
            }
        }
    }
}


Example 12:

The following example performs Insert, Update, and Delete operations
on a Products List using Linq to SharePoint.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SharePoint.Linq;
using Peers.SP2013.LinqToSP;
namespace DMLLinqinSP
{
    class Program
    {
        static void Insert()
        {
            PeersDataContext PeersDataContext = new
                                   PeersDataContext("http://sp2013dev/sites/peers487");

            // Get the list from the site
            EntityList<ProductsItem> listItems =
                              PeersDataContext.GetList<ProductsItem>("Products");

            //Create a new item
            ProductsItem newItem = new ProductsItem()
            {
                Title = "Hardware",
                ProductID = "5",
                ProductName = "RAM"
            };

            // Insert the new list item to the list
            listItems.InsertOnSubmit(newItem);

            //Submit the changes
            PeersDataContext.SubmitChanges();
            Console.WriteLine("Item Inserted");
        }
        static void Update()
        {
            PeersDataContext PeersDataContext = new
                                     PeersDataContext("http://sp2013dev/sites/peers487");
            // Querying the list item that has to be updated
            var updateItem = (from item in PeersDataContext.Products
                              where
                                  item.ProductID == "1"
                              select item).First();
            updateItem.ProductID = "6";
            updateItem.ProductName = "MotherBoard";

            // Submit the changes
            PeersDataContext.SubmitChanges();

            Console.WriteLine("Item Updated");
        }
        static void Delete()
        {
            // Create an instance
            PeersDataContext PeersDataContext = new
                                      PeersDataContext("http://sp2013dev/sites/peers487");
            // Get the list from the site
            EntityList<ProductsItem> listItems =
                               PeersDataContext.GetList<ProductsItem>("Products");

            // Querying the list item that has to be deleted
            var updateItem = (from item in PeersDataContext.Products
                              where
                                  item.ProductID == "3"
                              select item).First();

            // Deleting the list item
            listItems.DeleteOnSubmit(updateItem);

            // Submit the changes          
            PeersDataContext.SubmitChanges();

            Console.WriteLine("Item Deleted");
        }
        static void Main(string[] args)
        {
            Insert();
            Update();
            Delete();
        }
    }
}

Sharepoint 2013 Examples

Example 1 :

The following example displays title and url of all sites in a
specific site colleciton.

using System;
using Microsoft.SharePoint;

namespace KNRao.SP2013Examples
{
    class Program
    {
        static void Main(string[] args)
        {
            SPSite sc = new SPSite(
                "http://c4968397007/sites/peersfjeslaiflaesaf");
            foreach (SPWeb web in sc.AllWebs)
            {
                Console.WriteLine("Title : {0}",
                    web.Title);
                Console.WriteLine("Url : {0}",
                    web.Url);
                Console.WriteLine("Created on : {0}",
                    web.Created);
            }
        }
    }
}

Example 2:

The following code modifies the Title of the top-level site in a
specific site collection.

using System;
using Microsoft.SharePoint;

namespace KNRao.SP2013Examples
{
    class Program
    {
        static void Main(string[] args)
        {
         
   using (SPSite site = new SPSite("http://sp2013dev/sites/peers487"))
            {
                using (SPWeb web = site.RootWeb)
                {
                    web.Title = web.Title + " - Changed by code!";
                    web.Update();
                }
            }
        }
    }
}

Example 3:

The following code deletes a specific subsite in a site collection.

using System;
using Microsoft.SharePoint;

namespace KNRao.SP2013Examples
{
    class Program
    {
        static void Main(string[] args)
        {
            using (SPSite site = new SPSite("http://sp2013dev/sites/peers487"))
            {
                SPWeb web = site.OpenWeb("Sales");
                web.Delete();
            }
        }
    }
}

Example 4:

Delete all sub sites under a specific site.

using System;
using Microsoft.SharePoint;

namespace KNRao.SP2013Examples
{
    class Program
    {
        static void Main(string[] args)
        {
            string siteUrl;
            Console.WriteLine("Enter the site url: ");
            siteUrl = Console.ReadLine();
            SPWeb web =
                new SPSite(siteUrl).OpenWeb();
            for (int i = web.Webs.Count - 1; i >= 0; i--)
                web.Webs[i].Delete();
        }
    }
}


Example 5:

The following code enumerates through all of the lists contained in a
sample SharePoint site, displaying a few of the properties of
each list. If the list is hidden, an asterisk is displayed before
the list title and the item count.

using System;
using Microsoft.SharePoint;

namespace KNRao.SP2013Examples
{
    class Program
    {
        static void Main(string[] args)
        {
            using (SPSite mySiteCollection = new SPSite("http://sp2013dev/sites/peers487"))
            {
                using (SPWeb web = mySiteCollection.OpenWeb())
                {
                    foreach (SPList list in web.Lists)
                    {
                        Console.WriteLine("{0}{1} - {2} items.",
                        list.Hidden ? "* " : "", list.Title, list.ItemCount);
                        Console.WriteLine("Description : {0}", list.Description);
                        Console.WriteLine("Created by {0}", list.Author.Name);
                        Console.WriteLine
("----------------------------------------------------");
                    }
                    Console.WriteLine("\n{0} lists found.", web.Lists.Count);
                }
            }
        }
    }
}

Example 6:

Update the price of all products by a 10% increase.
Assume that a list called Products with the Price column is existing.

using System;
using Microsoft.SharePoint;

namespace KNRao.SP2013Examples
{
    class Program
    {
        static void Main(string[] args)
        {
            string siteUrl;
            Console.WriteLine("Enter the site url: ");
            siteUrl = Console.ReadLine();
            SPWeb web =
                new SPSite(siteUrl).OpenWeb();
            SPList list = web.Lists["Products"];
            foreach(SPListItem  item in list.Items)
            {
                item["Price"] =
                    ((double) item["Price"] * 1.1).ToString();
                item.Update();

                }
        }
    }
}

Example 7:

The following code creates a Customers list based on the Contacts list
template.

using System;
using Microsoft.SharePoint;

namespace KNRao.SP2013Examples
{
    class Program
    {
        static void Main(string[] args)
        {
            using (SPSite mySiteCollection =
            new SPSite("http://sp2013dev/sites/peers487"))
            {
                using (SPWeb web = mySiteCollection.OpenWeb())
                {
                    SPList list = web.Lists.TryGetList("Customers");
                    if (list != null) list.Delete();
                   Guid newListId = web.Lists.Add(
                        "Customers", // List Title
                        "Company's Customers", // List Description
                        SPListTemplateType.Contacts // List Template Type
                        );
                    SPList newList = web.Lists[newListId];
                    newList.OnQuickLaunch = true;

                    newList.Update();

                    Console.WriteLine("Created list: {0}", newList.Title);
                }
            }
        }
    }
}

Example 8:

The following code populates the Customers list with items.

using System;
using Microsoft.SharePoint;

namespace KNRao.SP2013Examples
{
    class Program
    {
        static void Main(string[] args)
        {
            using (SPSite mySiteCollection =
            new SPSite("http://sp2013dev/sites/peers487"))
            {
                using (SPWeb web = mySiteCollection.OpenWeb())
                {
                    SPList list = web.Lists["Customers"];
                    SPListItem newItem;

                    newItem = list.Items.Add();
                    newItem["Last Name"] = "Gorantla";
                    newItem["First Name"] = "Ramesh";
                    newItem["Email Address"] = "ramesh@peerstech.com";
                    newItem.Update();

                    newItem = list.Items.Add();
                    newItem["Last Name"] = "Doppalapudi";
                    newItem["First Name"] = "Kiran Kumar";
                    newItem["Email Address"] = "kiran@hotmail.com";
                    newItem.Update();

                    newItem = list.Items.Add();
                    newItem["Last Name"] = "Tenneti";
                    newItem["First Name"] = "Surendra";
                    newItem["Email Address"] = "surendra@hotmail.com";
                    newItem.Update();

                    newItem = list.Items.Add();
                    newItem["Last Name"] = "Gorantla";
                    newItem["First Name"] = "Rajani";
                    newItem["Email Address"] = "rajani@gmail.com";
                    newItem.Update();

                    newItem = list.Items.Add();
                    newItem["Last Name"] = "Boyapati";
                    newItem["First Name"] = "Suneetha";
                    newItem["Email Address"] = "suneetha@yahoo.co.in";
                    newItem.Update();

                    newItem = list.Items.Add();
                    newItem["Last Name"] = "Bandlamudi";
                    newItem["First Name"] = "Ravi";
                    newItem["Email Address"] = "ravi@hotmail.com";
                    newItem.Update();
                }
            }
        }
    }
}

Example 9:

The following code displays First Name, Last Name and E-mail Address
of all customers in the Customers list.

using System;
using Microsoft.SharePoint;

namespace KNRao.SP2013Examples
{
    class Program
    {
        static void Main(string[] args)
        {
            using (SPSite mySiteCollection =
            new SPSite("http://sp2013dev/sites/peers487"))
            {
                using (SPWeb web = mySiteCollection.OpenWeb())
                {
                    SPList list = web.Lists["Customers"];
                    foreach (SPListItem item in list.Items)
                    {
                        Console.WriteLine("{0} {1} - {2}",
                            item["First Name"],
                            item["Last Name"],
                            item["Email Address"]);
                    }
                }
            }
        }
    }
}

Example 10:

The following code displays all products having a price between 5
and 10.

using System;
using Microsoft.SharePoint;

namespace KNRao.SP2013Examples
{
    class Program
    {
        static void Main(string[] args)
        {
            using (SPSite mySiteCollection =
            new SPSite("http://sp2013dev/sites/peers487"))
            {
                using (SPWeb web = mySiteCollection.OpenWeb())
                {
                    SPList list = web.Lists["Products"];
                    SPQuery myQuery = new SPQuery();
                    // Define columns to retrieve
                    myQuery.ViewFields = @"<FieldRef Name='Title' /><FieldRef Name='Price' />";
                    // Force retrieving only the selected columns
                    myQuery.ViewFieldsOnly = true;
                    // Define the query
                    myQuery.Query = @"
                           <Where>
                              <And>
                                 <Geq>
                                    <FieldRef Name='Price' />
                                    <Value Type='Currency'>5</Value>
                                 </Geq>
                                 <Leq>
                                    <FieldRef Name='Price' />
                                    <Value Type='Currency'>10</Value>
                                 </Leq>
                              </And>
                           </Where>
                           <OrderBy>
                              <FieldRef Name='Title' Ascending='True' />
                           </OrderBy>";
                    // Define the maximum number of results for each (like a SELECT TOP)
                    myQuery.RowLimit = 10;
                    // Query for items
                    SPListItemCollection items = list.GetItems(myQuery);
                    foreach (SPListItem item in items)
                    {
                        Console.WriteLine("{0} - {1:C2}",
                            item["Title"], (double)item["Price"]);
                    }
                }
            }
        }
    }
}

Event Reciever Example in sharepoint 2013

Feature Receiver Example

using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;

namespace FeatureExample1.Features.Feature1
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("7d0f6067-7e35-4160-b741-fb2470190e7c")]
    public class Feature1EventReceiver :
        SPFeatureReceiver
    {
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated
            (SPFeatureReceiverProperties properties)
        {
            SPWeb web = properties.Feature.Parent as SPWeb;
            web.Lists.Add("Students", "", SPListTemplateType.Contacts);
            SPList list = web.Lists["Students"];
            list.OnQuickLaunch = true;
            list.Update();
        }


        // Uncomment the method below to handle the event raised before a feature is deactivated.

        public override void FeatureDeactivating
            (SPFeatureReceiverProperties properties)
        {
            SPWeb web = properties.Feature.Parent as SPWeb;
            web.Lists["Students"].Delete();
        }


        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}

Web Event Receiver Example:

using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

namespace WebEventReceiverExample1.PreventWebDeletion
{
    /// <summary>
    /// Web Events
    /// </summary>
    public class PreventWebDeletion :
        SPWebEventReceiver
    {
       /// <summary>
       /// A site is being deleted.
       /// </summary>
       public override void WebDeleting
           (SPWebEventProperties properties)
       {
properties.Status =
                SPEventReceiverStatus.CancelWithError;
          properties.ErrorMessage = "Dear " +
               properties.Web.CurrentUser.Name +
               " Can't delete the site " +
               properties.Web.Title;
          }


    }
}


<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Receivers >
      <Receiver>
        <Name>PreventWebDeletionWebDeleting</Name>
        <Type>WebDeleting</Type>
        <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
        <Class>WebEventReceiverExample1.PreventWebDeletion.PreventWebDeletion</Class>
        <SequenceNumber>10000</SequenceNumber>
      </Receiver>
  </Receivers>
</Elements>

List Event Receiver Example:

using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

namespace SharePointProject1.EnableVersioningAndFolderCreation
{
    /// <summary>
    /// List Events
    /// </summary>
    public class EnableVersioningAndFolderCreation :
        SPListEventReceiver
    {
       /// <summary>
       /// A list was added.
       /// </summary>
       public override void ListAdded
           (SPListEventProperties properties)
       {
            SPList list = properties.List;
            if (list.BaseTemplate ==
                SPListTemplateType.GenericList)
            {
                list.EnableAttachments = false;
                list.EnableFolderCreation = true;
                list.EnableVersioning = true;
                list.Update();
            }

       }


    }
}

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Receivers >
      <Receiver>
        <Name>EnableVersioningAndFolderCreationListAdded</Name>
        <Type>ListAdded</Type>
        <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
        <Class>SharePointProject1.EnableVersioningAndFolderCreation.EnableVersioningAndFolderCreation</Class>
        <SequenceNumber>10000</SequenceNumber>
      </Receiver>

  </Receivers>
</Elements>

Item Event Receiver Example :

using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

namespace EREXample4.CustomerEventReceiver
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class CustomerEventReceiver :
        SPItemEventReceiver
    {
        /// <summary>
        /// An item is being added.
        /// </summary>
        public override void ItemAdding
            (SPItemEventProperties properties)
        {
            string phone;
            phone = properties.AfterProperties["Phone"].ToString();
            if (phone.Length < 10)
            {
                properties.Status = SPEventReceiverStatus.CancelWithError;
                properties.ErrorMessage = "Phone NO must contain 10 digits";
            }
        }

        /// <summary>
        /// An item is being updated.
        /// </summary>
        public override void ItemUpdating
            (SPItemEventProperties properties)
        {
            string phone;
            phone = properties.AfterProperties["Phone"].ToString();
            if (phone.Length < 10)
            {
                properties.Status = SPEventReceiverStatus.CancelWithError;
                properties.ErrorMessage = "Phone NO must contain 10 digits";
            }
        }

        /// <summary>
        /// An item was added.
        /// </summary>
        public override void ItemAdded
            (SPItemEventProperties properties)
        {
            EventFiringEnabled = false;
            string title;
            title = properties.ListItem["Title"].ToString();
            properties.ListItem["Title"] =
                title.ToUpper();
            properties.ListItem.Update();
            EventFiringEnabled = true;
        }

        /// <summary>
        /// An item was updated.
        /// </summary>
        public override void ItemUpdated
            (SPItemEventProperties properties)
        {
            EventFiringEnabled = false;
            string title;
            title = properties.ListItem["Title"].ToString();
            properties.ListItem["Title"] =
                title.ToUpper();
            properties.ListItem.Update();
            EventFiringEnabled = true;
        }


    }
}
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Receivers  ListUrl="Lists/Customers">
      <Receiver>
        <Name>CustomerEventReceiverItemAdding</Name>
        <Type>ItemAdding</Type>
        <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
        <Class>EREXample4.CustomerEventReceiver.CustomerEventReceiver</Class>
        <SequenceNumber>10000</SequenceNumber>
      </Receiver>
      <Receiver>
        <Name>CustomerEventReceiverItemUpdating</Name>
        <Type>ItemUpdating</Type>
        <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
        <Class>EREXample4.CustomerEventReceiver.CustomerEventReceiver</Class>
        <SequenceNumber>10000</SequenceNumber>
      </Receiver>
      <Receiver>
        <Name>CustomerEventReceiverItemAdded</Name>
        <Type>ItemAdded</Type>
        <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
        <Class>EREXample4.CustomerEventReceiver.CustomerEventReceiver</Class>
        <SequenceNumber>10000</SequenceNumber>
<Synchronization>Synchronous</Synchronization>
      </Receiver>
      <Receiver>
        <Name>CustomerEventReceiverItemUpdated</Name>
        <Type>ItemUpdated</Type>
        <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
        <Class>EREXample4.CustomerEventReceiver.CustomerEventReceiver</Class>
        <SequenceNumber>10000</SequenceNumber>
<Synchronization>Synchronous</Synchronization>
      </Receiver>
  </Receivers>
</Elements>

Application Pages Example in sharepoint 2013

Application Page Ex 1 : (Interest Calculator)

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="InterestCalculator.aspx.cs" Inherits="SharePointProject20.Layouts.SharePointProject20.InterestCalculator" DynamicMasterPageFile="~masterurl/default.master" %>

<asp:Content ID="PageHead"
    ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <style type="text/css">
        .auto-style1 {
            width: 210px;
            height: 100px;
            background-color:navy;
            color:white;
        }
    </style>
</asp:Content>

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <table class="auto-style1">
            <tr>
                <td>AMOUNT</td>
                <td>
                    <asp:TextBox ID="txtAmount" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>RATE</td>
                <td>
                    <asp:TextBox ID="txtRate" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>PERIOD</td>
                <td>
                    <asp:TextBox ID="txtPeriod" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>INTEREST</td>
                <td>
                    <asp:TextBox ID="txtInterest" runat="server" ReadOnly="True"></asp:TextBox>
                </td>
            </tr>
        </table>
    <div>
 
        <asp:Button ID="btnCalculate" runat="server" OnClick="btnCalculate_Click" Text="Calculate Interest" />
 
    </div>
 
</asp:Content>

<asp:Content ID="PageTitle"
    ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
Interest Calculator
</asp:Content>

<asp:Content ID="PageTitleInTitleArea"
     ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server" >
    Calculates interest to be paid on loan taken
</asp:Content>


using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace SharePointProject20.Layouts.SharePointProject20
{
    public partial class InterestCalculator : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void btnCalculate_Click(object sender, EventArgs e)
        {
            double amount, rate, period, interest;
            amount = Convert.ToDouble(txtAmount.Text);
            rate = Convert.ToDouble(txtRate.Text);
            period = Convert.ToDouble(txtPeriod.Text);
            interest = amount * rate * period / 100;
            txtInterest.Text = interest.ToString();
        }

    }
}

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomActionGroup Id="ApplicationsLinks"
   Title="Applications"
   Location="Microsoft.SharePoint.SiteSettings"
    Sequence="5">
  </CustomActionGroup>
  <CustomAction Id="InterestCalculatorLink"
                 Title="Interest Calculator"
                 Location="Microsoft.SharePoint.SiteSettings"
                 GroupId="ApplicationsLinks"
                 >
    <UrlAction Url="_layouts/SharePointProject20/InterestCalculator.aspx"/>
  </CustomAction>
</Elements>


Application Page Example 2 : (View all Lists and Libraries)

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ViewLists.aspx.cs" Inherits="SharePointProject21.Layouts.SharePointProject21.ViewLists" DynamicMasterPageFile="~masterurl/default.master" %>

<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">

</asp:Content>

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
      <div>
 
        <asp:Label ID="lblListsLinks" runat="server"></asp:Label>
 
    </div>
</asp:Content>

<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
View Lists
</asp:Content>

<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server" >
Links to all lists and libraries in this site
</asp:Content>


using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace SharePointProject21.Layouts.SharePointProject21
{
    public partial class ViewLists : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SPWeb web = SPContext.Current.Web;
            foreach (SPList list in web.Lists)
                lblListsLinks.Text +=
                     "<a href='" +
                     list.DefaultViewUrl +
                     "'>" +
                     list.Title +
                     "</a><br />";
        }
    }
}

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction Id="ViewListsLink"
                Title="View Lists"
                 Location="Microsoft.SharePoint.StandardMenu"
                 GroupId="SiteActions"
                 >
    <UrlAction Url="_layouts/SharePointProject21/ViewLists.aspx"/>
  </CustomAction>
</Elements>

Features in Sharepoint 2013

Using Features

A feature provides some additional functionality in a sharepoint site when it is activated and can remove that functionality when it is deactivated at the following levels of scope:

1. Farm
2. WebApplication
3. Site
4. Web

Creating custom features

All SharePoint features are stored under sharepoint root template\features folder.

Each feature related files are stored here in a subfolder with feature name.

A feature consists of :

1. A feature manifest file called feature.xml
2. One or more element manifest files.

A solution consists of one or more features and other related files such as assemblies, images, .css files, .js files, etc. that are packaged into a .wsp file.  (windows sharepoint services solution package file)

Solutions are of two types:

1. Sandboxed solutions
2. Farm Solutions

Sandboxed solutions can be deployed by a site collection administrator directly. They are run in a secured, monitored process. They have the following limitations:

1. They can only use a subset of the Server Object Model.
2. They cannot access any content outside the current site collection.
3. They cannot deploy any files to the server's file system.
4. They cannot contain code to be executed with elevated priveleges.

Farm solutions do not have any limitations. They can only be deployed by a server farm administrator.

To create a feature for adding a menu option in the Settings menu

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction
        Id="CentralAdminLink"
         Title="Central Admin Site"
         Location="Microsoft.SharePoint.StandardMenu"
         GroupId="SiteActions"
          >
    <UrlAction Url="http://c4968397007:3695/default.aspx"/>
  </CustomAction>

  <CustomAction
        Id="BackupLink"
         Title="Site Collection Backup"
         Location="Microsoft.SharePoint.StandardMenu"
         GroupId="PersonalActions"
          >
    <UrlAction Url="http://c4968397007:3695/_admin/SiteCollectionBackup.aspx"/>
  </CustomAction>

</Elements>