Tuesday, February 3, 2015

Some of SharePoint Basic operations

           SharePoint Basic operations




1.Adding Data to List from Text File:

            SPWeb web = new SPSite("http://RKU:9870").OpenWeb();
            web.AllowUnsafeUpdates = true;
            SPList CusList = web.Lists["CusList"];
            SPListItem item;
            StreamReader reader = new StreamReader("C:\\Documents and Settings\\Administrator\\Desktop\\CusList.txt");
            while (reader.Peek() != -1)
            {
                item = CusList.Items.Add();
                item["One"] = reader.ReadLine();
                item["FName"] = reader.ReadLine();
                item["LName"] = reader.ReadLine();
                item["No"] = reader.ReadLine();
                item.Update();
            }


2.Displays data from CustListDesinger- 5141 :

            SPWeb Web = new SPSite("http://RKU:9870/").OpenWeb();
            SPList List = Web.Lists["CustListDesinger"];
           
            SPQuery spq=new SPQuery();
            spq.Query="Select * from CustListDesinger";
            SPListItemCollection Items = List.GetItems(spq);
            DataTable dt = new DataTable();
            dt = Items.GetDataTable();
            GridView1.DataSource = dt;
            GridView1.DataBind();

3.Adding data to CustListDesinger-5141 :

            SPWeb Web = new SPSite("http://RKU:9870/").OpenWeb();
            SPList List = Web.Lists["CustListDesinger"];
           
            Web.AllowUnsafeUpdates = true;

            // **** To add Item **** //
            SPListItem LItem = List.Items.Add();
            LItem["FName"] = txtFNmae.Text;
            LItem["LName"] = txtLName.Text;
            LItem["No"] = txtNo.Text;
            LItem.Update();
            List.Update();
            Web.Update();

4.Display data from CandInfo Document Library:

            SPWeb Web = new SPSite("http://RKU:9870/").OpenWeb();
            SPList List = Web.Lists["CandInfo"];

            SPQuery spq = new SPQuery();
            spq.Query = "Select * from CandInfo";
            SPListItemCollection Items = List.GetItems(spq);
            DataTable dt = new DataTable();
            dt = Items.GetDataTable();
            gvCandInfoDisplay.DataSource = dt;
            gvCandInfoDisplay.DataBind();

5.Display data from CandInfo Document Library using CAML Query:

            SPWeb Web = new SPSite("http://RKU:9870/").OpenWeb();
            SPList List = Web.Lists["CustListDesinger"];

            SPQuery spq = new SPQuery();
            spq.Query = "<OrderBy><FieldRef Name='Title' /></OrderBy><Where><Gt><FieldRef Name='No' /><Value Type='Number'>120</Value></Gt></Where>";
            SPListItemCollection Items = List.GetItems(spq);
            DataTable dt = new DataTable();
            dt = Items.GetDataTable();
            gvCaml.DataSource = dt;
            gvCaml.DataBind();

6.Calculate avg of No Column in CusList:

            SPWeb web = new SPSite("http://RKU:9870").OpenWeb();
            SPList CusList = web.Lists["CusList"];
            double total = 0;
            foreach (SPListItem item in CusList.Items)
            {
                //Console.WriteLine("Title : {0}", item["Title"]);
                //Console.WriteLine("Price : {0}", item["Price"]);
                total += (double)item["No"];
            }
            double Avg = total / CusList.Items.Count;
            lblAvg.Text = Avg.ToString();

7.Creating Sub Sites(Pages) and adding to QuickLunchBar:

          Using System.IO;
          Using System.Shareoint.Navigation;

             SPWeb web = new SPSite("http://RKU:9870").OpenWeb();
            web.AllowUnsafeUpdates = true;
            MemoryStream stream;
            StreamWriter writer;
            StreamReader reader;

            stream = new MemoryStream();
            writer = new StreamWriter(stream);
            reader = new StreamReader("C:\\Documents and Settings\\Administrator\\Desktop\\SharePoint Program Examples\\csharp.aspx");
            writer.Write(reader.ReadToEnd());
            writer.Flush();
            web.Files.Add("csharp.aspx", stream, true);
            writer.Close();
            reader.Close();

            stream = new MemoryStream();
            writer = new StreamWriter(stream);
            reader = new StreamReader("C:\\Documents and Settings\\Administrator\\Desktop\\SharePoint Program Examples\\vbnet.aspx");
            writer.Write(reader.ReadToEnd());
            writer.Flush();
            web.Files.Add("vbnet.aspx", stream, true);
            writer.Close();
            reader.Close();

            stream = new MemoryStream();
            writer = new StreamWriter(stream);
            reader = new StreamReader("C:\\Documents and Settings\\Administrator\\Desktop\\SharePoint Program Examples\\aspnet.aspx");
            writer.Write(reader.ReadToEnd());
            writer.Flush();
            web.Files.Add("aspnet.aspx", stream, true);
            writer.Close();
            reader.Close();

            SPNavigationNode dropdownMenu =
            new SPNavigationNode("Course Materials", "");
            SPNavigationNodeCollection quickLaunch =
                web.Navigation.QuickLaunch;
            quickLaunch.AddAsLast(dropdownMenu);
            dropdownMenu.Children.AddAsLast(
             new SPNavigationNode
            ("Csharp", "csharp.aspx"));

            dropdownMenu.Children.AddAsLast(
                new SPNavigationNode
                ("VB.Net", "vbnet.aspx"));

            dropdownMenu.Children.AddAsLast(
                new SPNavigationNode
                ("ASP.Net", "aspnet.aspx"));

8.Creating List=Navigation and add one link=home:

            SPWeb web = new SPSite
                ("http://RKU:9870").OpenWeb();
            System.Guid NewListGuid = new System.Guid();
            SPList list = null;
            // THIS IS REQUIRED WHEN CREATING NEW LISTS!!
            web.AllowUnsafeUpdates = true;
            // Create the list in SharePoint:
            NewListGuid = web.Lists.Add("Navigation Page List",
            "List used to provide Custom Navigation",
            SPListTemplateType.GenericList);
            list = web.Lists[NewListGuid];
            list.OnQuickLaunch = true;
            list.Update();
            // Rename the title field:
            SPField TitleField = list.Fields["Title"];
            TitleField.Description = "Title to appear in Navigation";
            TitleField.Update();
            // Add Link Field:
            list.Fields.Add("Link", SPFieldType.URL, true);
            SPField LinkField = list.Fields["Link"];
            LinkField.Description = "Relative Link and Tool Tip";
            LinkField.ShowInEditForm = true;
            LinkField.ShowInDisplayForm = true;
            LinkField.ShowInListSettings = true;
            LinkField.ShowInViewForms = true;
            LinkField.Update();
            // Add Appearance Order Field:
            list.Fields.Add("Appearance Order", SPFieldType.Number, true);
            SPField AppearanceOrderField = list.Fields["Appearance Order"];
            AppearanceOrderField.Description = "Order to display";
            AppearanceOrderField.ShowInEditForm = true;
            AppearanceOrderField.ShowInDisplayForm = true;
            AppearanceOrderField.ShowInListSettings = true;
            AppearanceOrderField.ShowInViewForms = true;
            AppearanceOrderField.Update();
            // Add Publish Date Field:
            list.Fields.Add("Publish Date", SPFieldType.DateTime, false);
            SPFieldDateTime PublishDateF =
            (SPFieldDateTime)list.Fields["Publish Date"];
            PublishDateF.Description = "Date to publish (show)";
            PublishDateF.DefaultValue = "[today]";
            PublishDateF.DisplayFormat = SPDateTimeFieldFormatType.DateOnly;
            PublishDateF.ShowInEditForm = true;
            PublishDateF.ShowInDisplayForm = true;
            PublishDateF.ShowInListSettings = true;
            PublishDateF.ShowInViewForms = true;
            // NOWCRAWL means don’t search this field!
            PublishDateF.NoCrawl = true;
            PublishDateF.Update();
            // Add Stop Publish Date Field:
            list.Fields.Add("Stop Publish Date", SPFieldType.DateTime, false);
            SPFieldDateTime StopPublishDateF =
            (SPFieldDateTime)list.Fields["Stop Publish Date"];
            StopPublishDateF.Description = "Date to remove";
            StopPublishDateF.DisplayFormat = SPDateTimeFieldFormatType.DateOnly;
            StopPublishDateF.ShowInEditForm = true;
            StopPublishDateF.ShowInDisplayForm = true;
            StopPublishDateF.ShowInListSettings = true;
            StopPublishDateF.ShowInViewForms = true;
            // NOWCRAWL means don’t search this field!
            StopPublishDateF.NoCrawl = true;
            StopPublishDateF.Update();
            //
            // Add the Columns (fields) to the default view:
            SPView DefView = list.DefaultView;
            DefView.ViewFields.Add(LinkField);
            DefView.ViewFields.Add(AppearanceOrderField);
            DefView.ViewFields.Add(PublishDateF);
            DefView.ViewFields.Add(StopPublishDateF);
            DefView.Update();
            //
            // Now add an item:
            SPListItem NewItem = list.Items.Add();
            //
            NewItem["Title"] = "Home";
            NewItem["Link"] =
            web.ServerRelativeUrl.ToString() + ", " + web.Title;
            NewItem["Appearance Order"] = 0;
            NewItem["Publish Date"] = System.DateTime.Today.AddDays(-1);
            NewItem["Stop Publish Date"] = null;
            NewItem.Update();

9.Creating EmpInfoList and Adding one Item:
           
            SPWeb Web = new SPSite("http://RKU:9870").OpenWeb();
            Web.AllowUnsafeUpdates = true;
            // Creating EmpInfoList, here GenericList means Custom List
            System.Guid NewListGuid = new System.Guid();
            SPList List = null;
            NewListGuid=Web.Lists.Add("EmpInfoList","This is Employee List",SPListTemplateType.GenericList);
            List = Web.Lists[NewListGuid];
            List.OnQuickLaunch = true;
            List.Update();

            // Rename the title field:
            SPField TitleField = List.Fields["Title"];
            TitleField.Description = "Title to appear in Navigation";
            TitleField.Update();

            //Add EmpName Field
            List.Fields.Add("EmpName", SPFieldType.Text, true);
            SPField EmpNameField = List.Fields["EmpName"];
            EmpNameField.Description = "Employee Name";
            EmpNameField.ShowInDisplayForm = true;
            EmpNameField.ShowInEditForm = true;
            EmpNameField.ShowInListSettings = true;
            EmpNameField.ShowInViewForms = true;
            List.Update();

            //Add Number Field
            List.Fields.Add("Number", SPFieldType.Integer, true);
            SPField EmpNumberField = List.Fields["Number"];
            EmpNumberField.Description = "Employee Number";
            EmpNumberField.ShowInDisplayForm = true;
            EmpNumberField.ShowInEditForm = true;
            EmpNumberField.ShowInListSettings = true;
            EmpNumberField.ShowInViewForms = true;
            List.Update();

            //Add BOD Field
            List.Fields.Add("BOD", SPFieldType.DateTime, false);
            SPFieldDateTime EmpBODField = (SPFieldDateTime)List.Fields["BOD"];
            EmpBODField.Description = "Employee BOD";
            EmpBODField.DefaultValue = "[today]";
            EmpBODField.DisplayFormat = SPDateTimeFieldFormatType.DateOnly;
            EmpBODField.ShowInDisplayForm = true;
            EmpBODField.ShowInEditForm = true;
            EmpBODField.ShowInListSettings = true;
            EmpBODField.ShowInViewForms = true;
            EmpBODField.NoCrawl = true;
            List.Update();

            //Add Salary Field
            List.Fields.Add("Salary", SPFieldType.Number, false);
            SPField EmpSalField = List.Fields["Salary"];
            EmpSalField.Description = "Employee Salary";
            EmpSalField.ShowInDisplayForm = true;
            EmpSalField.ShowInEditForm = true;
            EmpSalField.ShowInListSettings = true;
            EmpSalField.ShowInViewForms = true;
            List.Update();

            // Add Columns to Default View
            SPView DefView = List.DefaultView;
            DefView.ViewFields.Add(EmpNameField);
            DefView.ViewFields.Add(EmpNumberField);
            DefView.ViewFields.Add(EmpBODField);
            DefView.Update();

            //Add a Item to List
            SPListItem newItem = List.Items.Add();
            newItem["Title"] = "Nag Title";
            newItem["EmpName"] = "Nag";
            newItem["Number"] = "141";
            newItem["BOD"] = System.DateTime.Today.AddDays(-1);
            newItem["Salary"] = "1000";
            newItem.Update();
            List.Update();

10. Event Receiver Example 1:

Class Library :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace ERListExample1
{
    public class CusListEventReceiver : SPListEventReceiver
    {
        public override void FieldAdding(SPListEventProperties properties)
        {
            properties.ErrorMessage = "You cannot change this list schema!";
            properties.Cancel = true;
        }
        public override void FieldUpdating(SPListEventProperties properties)
        {
            properties.ErrorMessage = "You cannot change this list schema!";
            properties.Cancel = true;
        }
        public override void FieldDeleting(SPListEventProperties properties)
        {
            properties.ErrorMessage = "You cannot change this list schema!";
            properties.Cancel = true;
        }
    }
}

To Deploy Programatically:
using System;
using Microsoft.SharePoint;
namespace EventHandlerExample2DeployProgrammatically
{
    class Program
    {
        static void Main(string[] args)
        {
            SPWeb webSite = new SPSite("http://RKU:9870").OpenWeb();
            SPList theList = webSite.Lists["CusList"];
            theList.EventReceivers.Add(SPEventReceiverType.FieldAdding,
                "EventHandlerExample2,Version=1.0.0.0,Culture=neutral,PublicKeyToken=8b788521338931a6",
                "EventHandlerExample2.TasksListEventReceiver");
            theList.EventReceivers.Add(SPEventReceiverType.FieldDeleting,
                 "EventHandlerExample2,Version=1.0.0.0,Culture=neutral,PublicKeyToken=8b788521338931a6",
                 "EventHandlerExample2.TasksListEventReceiver");
            theList.EventReceivers.Add(SPEventReceiverType.FieldUpdating,
                 "EventHandlerExample2,Version=1.0.0.0,Culture=neutral,PublicKeyToken=8b788521338931a6",
                 "EventHandlerExample2.TasksListEventReceiver");
           
        }
    }
}

11. Store data from sql to SharePoint List:

using System.Data;
using System.Data.SqlClient;

            SPWeb web = new SPSite("http://RKU:9870").OpenWeb();
            web.AllowUnsafeUpdates = true;
            SPList clientsList = web.Lists["CusList"];
            SPListItem item;
            SqlConnection myCon = new SqlConnection(@"Data Source=MOSS07;Initial Catalog=testDB;Persist Security Info=True;User ID=sa;Password=Welcome141");
            SqlCommand myCom = new SqlCommand("Select Name, NO from test1", myCon);
            myCon.Open();
            SqlDataReader reader = myCom.ExecuteReader();
            while (reader.Read())
            {
                item = clientsList.Items.Add();
                item["One"] = "ONE";
                item["FName"] = reader["Name"];
                item["LName"] = reader["Name"];
                item["No"] = reader["NO"];
                item.Update();
            }
            reader.Close();
            myCon.Close();

12. Creating Document Library with Name=CandDocLib:

            SPWeb Web = new SPSite("http://RKU:9870").OpenWeb();
            Web.AllowUnsafeUpdates = true;
            // Creating EmpInfoList, here GenericList means Custom List
            System.Guid NewListGuid = new System.Guid();
            SPList List = null;
            NewListGuid = Web.Lists.Add("CandDocLib", "This is Candidate Document Library", SPListTemplateType.DocumentLibrary);
            List = Web.Lists[NewListGuid];
            List.OnQuickLaunch = true;
            List.Update();

            // Rename the title field:
            SPField TitleField = List.Fields["Title"];
            TitleField.Description = "Title to appear in Navigation";
            TitleField.Update();

            //Add CandNameField
            List.Fields.Add("CandName", SPFieldType.Text, true);
            SPField EmpNameField = List.Fields["CandName"];
            EmpNameField.Description = "Candidate Name";
            EmpNameField.ShowInDisplayForm = true;
            EmpNameField.ShowInEditForm = true;
            EmpNameField.ShowInListSettings = true;
            EmpNameField.ShowInViewForms = true;
            List.Update();

            //Add CandNumberField
            List.Fields.Add("CandNumber", SPFieldType.Integer, true);
            SPField EmpNumberField = List.Fields["CandNumber"];
            EmpNumberField.Description = "Candidate Number";
            EmpNumberField.ShowInDisplayForm = true;
            EmpNumberField.ShowInEditForm = true;
            EmpNumberField.ShowInListSettings = true;
            EmpNumberField.ShowInViewForms = true;
            List.Update();

            //Add BOD Field
            List.Fields.Add("BOD", SPFieldType.DateTime, false);
            SPFieldDateTime EmpBODField = (SPFieldDateTime)List.Fields["BOD"];
            EmpBODField.Description = "Candidate BOD";
            EmpBODField.DefaultValue = "[today]";
            EmpBODField.DisplayFormat = SPDateTimeFieldFormatType.DateOnly;
            EmpBODField.ShowInDisplayForm = true;
            EmpBODField.ShowInEditForm = true;
            EmpBODField.ShowInListSettings = true;
            EmpBODField.ShowInViewForms = true;
            EmpBODField.NoCrawl = true;
            List.Update();


            // Add Columns to Default View
            SPView DefView = List.DefaultView;
            DefView.ViewFields.Add(EmpNameField);
            DefView.ViewFields.Add(EmpNumberField);
            DefView.ViewFields.Add(EmpBODField);
            DefView.Update();

            ////Add a Item to List
            //SPListItem newItem = List.Items.Add();
            //newItem["Title"] = "Nag Title";
            //newItem["EmpName"] = "Nag";
            //newItem["Number"] = "141";
            //newItem["BOD"] = System.DateTime.Today.AddDays(-1);
            //newItem["Salary"] = "1000";
            //newItem.Update();
            List.Update();

13. Event Receiver for Validating Phone Number and Convert Title Field to UpperCase and Restrict to Delete data if he is not Admin:

using Microsoft.SharePoint;
namespace EventHandlerExample3
{
    class CustomersItemEventReceiver:SPItemEventReceiver
    {
        // provide method with validation logic
        private bool PhoneIsValid(string Phone)
        {
            if ((Phone == null) || (Phone.Length < 10))
                return false;
            else
                return true;
        }
        // provide error message
        const string PhoneInvalidErrorMessage =
              "VALIDATION ERROR: Phone must be at least 10 digits.";
        public override void ItemAdding(SPItemEventProperties properties)
        {
            // validate Phone column for new customer item
            string Phone = properties.AfterProperties["Phone"].ToString();
            if (!PhoneIsValid(Phone))
            {
                properties.Status = SPEventReceiverStatus.CancelWithError;
                properties.ErrorMessage = PhoneInvalidErrorMessage;
                properties.Cancel = true;
            }
        }
        public override void ItemUpdating(SPItemEventProperties properties)
        {
            // validate Phone column for update to customer item
            string Phone = properties.AfterProperties["Phone"].ToString();
            if (!PhoneIsValid(Phone))
            {
                properties.Status = SPEventReceiverStatus.CancelWithError;
                properties.ErrorMessage = PhoneInvalidErrorMessage;
                properties.Cancel = true;
            }
        }
        public override void ItemAdded(SPItemEventProperties properties)
        {
            DisableEventFiring();
            string Title = properties.ListItem["Title"].ToString();
            properties.ListItem["Title"] = Title.ToUpper();
            properties.ListItem.Update();
            EnableEventFiring();
        }
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            DisableEventFiring();
            string Title = properties.ListItem["Title"].ToString();
            properties.ListItem["Title"] = Title.ToUpper();
            properties.ListItem.Update();
            EnableEventFiring();
        }
        public override void ItemDeleting(SPItemEventProperties properties)
        {
            if (!properties.OpenWeb().CurrentUser.IsSiteAdmin)
            {
                properties.Status = SPEventReceiverStatus.CancelWithError;
                properties.ErrorMessage = "Customer can only be deleted by site administrator";
                properties.Cancel = true;
            }
        }
    }
}

To Deploy :

using Microsoft.SharePoint;
namespace EventHandlerExample3DeployProgrammatically
{
    class Program
    {
        static void Main(string[] args)
        {
            SPWeb webSite = new SPSite("http://intanet.com").OpenWeb();
            SPList theList = webSite.Lists["Customers"];
            theList.EventReceivers.Add(SPEventReceiverType.ItemAdded,
                "EventHandlerExample3,Version=1.0.0.0,Culture=neutral,PublicKeyToken=be792ae89c60d497",
                "EventHandlerExample3.CustomersItemEventReceiver");
            theList.EventReceivers.Add(SPEventReceiverType.ItemAdding,
                "EventHandlerExample3,Version=1.0.0.0,Culture=neutral,PublicKeyToken=be792ae89c60d497",
                "EventHandlerExample3.CustomersItemEventReceiver");
            theList.EventReceivers.Add(SPEventReceiverType.ItemUpdated,
                "EventHandlerExample3,Version=1.0.0.0,Culture=neutral,PublicKeyToken=be792ae89c60d497",
                "EventHandlerExample3.CustomersItemEventReceiver");
            theList.EventReceivers.Add(SPEventReceiverType.ItemUpdating,
                "EventHandlerExample3,Version=1.0.0.0,Culture=neutral,PublicKeyToken=be792ae89c60d497",
                "EventHandlerExample3.CustomersItemEventReceiver");
            theList.EventReceivers.Add(SPEventReceiverType.ItemDeleting,
                "EventHandlerExample3,Version=1.0.0.0,Culture=neutral,PublicKeyToken=be792ae89c60d497",
                "EventHandlerExample3.CustomersItemEventReceiver");
        }
    }
}

14.Event Receiver for calculating discount based on Price

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
namespace EventHandlerExample4
{
    public class ProductsItemEventReceiver:SPItemEventReceiver
    {
        public override void ItemAdded(SPItemEventProperties properties)
        {
            DisableEventFiring();
            double price = (double)properties.ListItem["Price"];
            if (price <= 1000)
                properties.ListItem["Discount"] = 0.1;
            else
                properties.ListItem["Discount"] = 0.15;
            properties.ListItem.Update();
            EnableEventFiring();

        }
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            DisableEventFiring();
            double price = (double)properties.ListItem["Price"];
            if (price <= 1000)
                properties.ListItem["Discount"] = 0.1;
            else
                properties.ListItem["Discount"] = 0.15;
            properties.ListItem.Update();
            EnableEventFiring();
        }
    }
}

To Deploy :

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
namespace EventHandlerExample4DeployProgrammatically
{
    class Program
    {
        static void Main(string[] args)
        {
            SPWeb webSite = new SPSite("http://intanet.com").OpenWeb();
            SPList theList = webSite.Lists["Products"];
            theList.EventReceivers.Add(SPEventReceiverType.ItemAdded,
                "EventHandlerExample4,Version=1.0.0.0,Culture=neutral,PublicKeyToken=81eb34befd3bc9b4",
                "EventHandlerExample4.ProductsItemEventReceiver");
            theList.EventReceivers.Add(SPEventReceiverType.ItemUpdated,
                "EventHandlerExample4,Version=1.0.0.0,Culture=neutral,PublicKeyToken=81eb34befd3bc9b4",
                "EventHandlerExample4.ProductsItemEventReceiver");
      
        }
    }
}

15. Code for Web Part:

using System;
using System.Runtime.InteropServices;
using System.Web.UI;
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 KNRaoWPExample4
{
    [Guid("e2002c61-a873-4409-ad84-96c88f43f721")]
    public class LoanCalculator : System.Web.UI.WebControls.WebParts.WebPart
    {
        protected override void OnPreRender(EventArgs e)
        {
            this.Title = "Loan Calculator";
            this.Description = "Calculates monthly loan payment amount";
        }
        TextBox txtAmount, txtPeriod, txtInterestRate, txtMonthlyPayment;
        Button btnCalculateMonthlyPayment;
        public LoanCalculator(){}
        protected override void CreateChildControls()
        {
            txtAmount = new TextBox();
            this.Controls.Add(txtAmount);
            txtPeriod = new TextBox();
            this.Controls.Add(txtPeriod);
            txtInterestRate = new TextBox();
            this.Controls.Add(txtInterestRate);
            txtMonthlyPayment = new TextBox();
            txtMonthlyPayment.ReadOnly = true;
            this.Controls.Add(txtMonthlyPayment);
            btnCalculateMonthlyPayment = new Button();
            btnCalculateMonthlyPayment.Text = "Calculate Monthly Payment";
            btnCalculateMonthlyPayment.Click += new EventHandler(btnCalculateMonthlyPayment_Click);
            this.Controls.Add(btnCalculateMonthlyPayment);
        }
        void btnCalculateMonthlyPayment_Click(object sender, EventArgs e)
        {
            double amount, interestRate, monthlyPayment;
            int period;
            amount = Convert.ToDouble(txtAmount.Text);
            period = Convert.ToInt32(txtPeriod.Text);
            interestRate = Convert.ToDouble(txtInterestRate.Text);
            monthlyPayment = amount * (interestRate / 100) / (1 - (1 / Math.Pow((1 + interestRate / 100), period)));
            txtMonthlyPayment.Text = monthlyPayment.ToString("f2");
        }
        protected override void RenderContents(HtmlTextWriter writer)
        {
            this.EnsureChildControls();
            writer.Write("<table width = 100%>");
            writer.Write("<tr>");
            writer.Write("<td>Principal amount</td>");
            writer.Write("<td>");
            txtAmount.RenderControl(writer);
            writer.Write("</td>");
            writer.Write("</tr>");
            writer.Write("<tr>");
            writer.Write("<td>Period in months</td>");
            writer.Write("<td>");
            txtPeriod.RenderControl(writer);
            writer.Write("</td>");
            writer.Write("</tr>");
            writer.Write("<tr>");
            writer.Write("<td>Monthly interest rate (%)</td>");
            writer.Write("<td>");
            txtInterestRate.RenderControl(writer);
            writer.Write("</td>");
            writer.Write("</tr>");
            writer.Write("</tr>");
            writer.Write("<tr>");
            writer.Write("<td>Monthly payment</td>");
            writer.Write("<td>");
            txtMonthlyPayment.RenderControl(writer);
            writer.Write("</td>");
            writer.Write("</tr>");
            writer.Write("</table>");
            btnCalculateMonthlyPayment.RenderControl(writer);
        }
    }
}

16. Connected Web Parts:
Provider Web Part:
using System;
using System.Runtime.InteropServices;
using System.Web.UI;
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;
using KNRaoWPExample8;

namespace KNRaoWPExample8
{
    [Guid("323f9612-522a-4af7-b12e-f0b1412ba5ed")]
    public class CustomerProvider : System.Web.UI.WebControls.WebParts.WebPart, ICustomer
    {
        protected override void OnPreRender(EventArgs e)
        {
            this.Title = "Customer Provider";
        }
        TextBox txtName, txtCity;
        Button btnSend;
        protected override void CreateChildControls()
        {
            txtName = new TextBox();
            Controls.Add(txtName);
            txtCity = new TextBox();
            Controls.Add(txtCity);
            btnSend = new Button();
            btnSend.Text = "Send Customer";
            Controls.Add(btnSend);
        }
        protected override void RenderContents(HtmlTextWriter writer)
        {
            writer.Write("Name : ");
            txtName.RenderControl(writer);
            writer.Write("<br/>");
            writer.Write("City : ");
            txtCity.RenderControl(writer);
            writer.Write("<br/>");
            btnSend.RenderControl(writer);
        }

        public string Name
        {
            get { return txtName.Text; }
        }

        public string City
        {
            get { return txtCity.Text; }
        }
        [ConnectionProvider("Customer", AllowsMultipleConnections=true)]
        public ICustomer ProvideCustomer()
        {
            return this;
        }
    }
}
Consumer Web Part:
using System;
using System.Runtime.InteropServices;
using System.Web.UI;
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;

using KNRaoWPExample8;

namespace KNRaoWPExample8
{
    [Guid("6fb56784-970e-4b53-b9bc-0e0880a5e963")]
    public class CustomerConsumer : System.Web.UI.WebControls.WebParts.WebPart
    {
        ICustomer customer;
        [ConnectionConsumer("Customer")]
        public void ConsumeCustomer(ICustomer customer)
        {
            this.customer = customer;
        }
        protected override void RenderContents(HtmlTextWriter writer)
        {
            if (customer == null)
                writer.Write("No connection");
            else if (customer.Name == "" || customer.City == "")
                writer.Write("Provide customer name and city");
            else
                writer.Write("Welcome " + customer.Name + " from " + customer.City);
        }
    }
}

17. To display List Event Receivers in Site(It's a Console Application):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace ShowEvents
{
    class Program
    {
        static void Main(string[] args)
        {
            SPWeb Web = new SPSite("http://RKU:9870").OpenWeb();
            SPEventReceiverDefinitionCollection receivers = Web.EventReceivers;
            if (receivers.Count == 0)
            {
                Console.WriteLine("No");
            }
            foreach (SPEventReceiverDefinition def in receivers)
            {
                Console.WriteLine("Event Receiver :"+def.Name);
                Console.WriteLine("Event Receiver Type :"+def.Type);
            }
        }
    }
}

18. By activating Feature add link to Top Navigation Bar , By deactivating Feature remove link

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Navigation;

namespace SitePagesEx1
{
    public class FeatureReceiver:SPFeatureReceiver
    {

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWeb web = (SPWeb)properties.Feature.Parent;
            SPNavigationNodeCollection topNavBar =
                web.Navigation.TopNavigationBar;
            topNavBar[0].Children.AddAsLast(
                new SPNavigationNode("About Us",
                "sitepages/aboutus.aspx"));
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWeb web = (SPWeb)properties.Feature.Parent;
            web.GetFile("sitepages/aboutus.aspx").Delete();
            SPNavigationNodeCollection topNav = web.Navigation.TopNavigationBar;
            for (int i = topNav[0].Children.Count - 1; i >= 0; i--)
                if (topNav[0].Children[i].Title == "About Us")
                    topNav[0].Children[i].Delete();
           
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
        }

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

19. To Create Custom Web Part(Web Part for Using User Controls):

using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.ComponentModel;


namespace Contentpages
{
   [Guid("3e65b857-9c8e-4021-aee0-fbc13814f90c")]
   public class ContentPage : System.Web.UI.WebControls.WebParts.WebPart
   {
       private string _cPath;

       [Personalizable(PersonalizationScope.Shared),
       WebBrowsable(true),
       WebDisplayName("Contentpage Webpart"),
       WebDescription("Enter the control path"),
      Category("ContentPage Properties")]
       public string CPATH
       {
           get { return _cPath; }
           set { _cPath = value; }
       }


       protected override void CreateChildControls()
       {

          //this.Controls.Add(Page.LoadControl(@"/_CONTROLTEMPLATES/cotentpages/ContentPages.ascx"));
           if (!string.IsNullOrEmpty(CPATH))
           {
               this.Controls.Add(Page.LoadControl(CPATH));
           }


       }
   }
}

No comments:

Post a Comment