JG Vimalan's Blog

It is all about coding!

XmlSerialization

The following code snippet will show you how to perform xmlserialization.

The main objective is to read / write data to an xml file using XmlSerialization.

1. Create a Windows application (name as DemoXMLSerialization)
2. Rename the default form as App
3. Add a class MyXmlSerialization and include the code as shown below,
4. Call the MyXmlSerialization APIs from the App class.

Comment is given in the code for easy understanding.
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace DemoXMLSerialization
{
    /// <summary>
    /// This class performs xml serialization and de serialization
    /// </summary>
    [XmlRoot(“Demo”)]
    [Serializable]
    public class MyXmlSerialization
    {       
        public MyEmployee Employee = null;
        private static MyXmlSerialization _MyXmlSerialization = null;       
        private static string _FilePath = @”C:\\EmployeeDetails.xml”;

        /// <summary>
        /// Constructor
        /// </summary>
        protected MyXmlSerialization()
        {
            Employee = new MyEmployee();
            Employee.Name = “Test”;
            Employee.Age = 28;
            _MyXmlSerialization = this;
        }

        /// <summary>
        /// Employee details are de serialized from xml file.
        /// </summary>
        /// <param name=”type”></param>
        /// <returns></returns>
        public static MyXmlSerialization Load(Type type)
        {
            XmlSerializer xmlSerializer = null;
            FileStream fileStream = null;

            try
            {
                FileInfo file = new FileInfo(_FilePath);
                if (file.Exists)
                {
                    xmlSerializer = new XmlSerializer(type);
                    fileStream = file.OpenRead();
                    return xmlSerializer.Deserialize(fileStream) as MyXmlSerialization;
                }
                return null;
            }
            finally
            {
                if (fileStream != null)
                    fileStream.Close();
            }
        }

        /// <summary>
        /// Save the employee details to the xml file
        /// </summary>
        public void Save()
        {
            XmlSerializer xmlSerializer = null;
            StreamWriter streamWriter = null;

            try
            {
                xmlSerializer = new XmlSerializer(GetType());
                streamWriter = new StreamWriter(_FilePath, false);
                xmlSerializer.Serialize(streamWriter, this);
            }
            catch(Exception error)
            {
                throw error;
            }
            finally
            {
                if (streamWriter != null)
                    streamWriter.Close();
            }
        }

        /// <summary>
        /// Gets the instance of this class.
        /// Used to read/write the values.
        /// </summary>
        public static MyXmlSerialization Options
        {
            get
            {
                if (_MyXmlSerialization == null &&
                    (_MyXmlSerialization = Load(typeof(MyXmlSerialization))) == null &&
                    (_MyXmlSerialization = new MyXmlSerialization()) == null)
                return null;

                return _MyXmlSerialization;
            }
        }

        /// <summary>
        /// Employee class
        /// </summary>
        [Serializable]
        public class MyEmployee
        {
            /// <summary>
            /// Name of the employee
            /// </summary>
            public string Name
            {
                get
                {
                    return _Name;
                }
                set
                {
                    _Name = value;
                }
            }
            private string _Name = string.Empty;

            /// <summary>
            /// Age of the employee
            /// </summary>
            public int Age
            {
                get
                {
                    return _Age;
                }
                set
                {
                    _Age = value;
                }               
            }
            private int _Age = 0;
        }       
    }
}

 This form will have two buttons namely, serialize and de serialize.

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DemoXMLSerialization
{   
    public partial class App : Form
    {
        public App()
        {
            InitializeComponent();
        }

        private void _SerializeBtn_Click(object sender, EventArgs e)
        {
            //Write to a xml file
            MyXmlSerialization.Options.Save();
        }

        private void _DeSerializeBtn_Click(object sender, EventArgs e)
        {
            //Read from the xml file
            string employeeName = MyXmlSerialization.Options.Employee.Name;
        }
    }
}

 The output xml file will be as shown below,

 xmlSer

September 30, 2009 Posted by | C#.NET | 1 Comment

Create a custom timer service in MOSS 2007

To create a simple timer service, just few thigs needs to be considered.

Create a class library which contains two class (in general).

1. Manager.cs    – Inherits from SPJobDefinition and overrides the Execute(Guid targetInstanceId) method.

2. ServiceController – To create / delete the service

Create a test app (console is enough) for calling the create / delete a service methods

The code snippets are given below and i hope it is easy to understand.

Manager.cs class

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Collections;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using System.Configuration;
using System.Net;
using System.Net.Mail;
using System.Diagnostics;

namespace SampleTimerService
{
    public class Manager : SPJobDefinition
    {
        #region Constructors

        /// <summary>
        /// Default
        /// </summary>
        public Manager()
            : base()
        { }

        
        public Manager(string mail, SPService service, SPServer server, SPJobLockType targetType)
            : base(mail, service, server, targetType)
        { }

        
        public Manager(string mail, SPWebApplication webApplication)
            : base(mail, webApplication, null, SPJobLockType.ContentDatabase)
        {
            this.Title = “Custom Manager”; //Service Name. Can be viewed in

                                                         //Central Admin Page
        }

        #endregion Constructors 

       /// <summary>
        /// This method will be executed by the SharePoint timer in the specified time

       ///interval.
        /// Also, this method can be invoked from outsite by just referencing this

        ///assembly.
        /// </summary>
        /// <param name=”targetInstanceId”></param>
        public override void Execute(Guid targetInstanceId)
        {

                 //Write your business logic here

         } 

ServiceController.cs

using System;
using System.Text;
using System.Collections;
using Microsoft.SharePoint;
using System.Configuration;
using System.Collections.Generic;
using Microsoft.SharePoint.Administration;

 namespace SampleTimerService
{
    /// <summary>
    ///
    /// </summary>
    public class ServiceController
    {
        /// <summary>
        ///
        /// </summary>
        public static void CreateService()
        {
            SPServer server = SPServer.Local;
            SPSite site = new SPSite(ConfigurationManager.AppSettings[“URL”]);
            SPWebApplication web = site.WebApplication;
            SPJobDefinitionCollection jobs = web.JobDefinitions;

            SPSchedule schedule = SPSchedule.FromString(“daily at 18:05:00”);
           
            Manager manager = new Manager(“email”, web);
            manager.Schedule = schedule;
            jobs.Add(manager);

            web.Update();
            site.Dispose();
        }

        /// <summary>
        ///
        /// </summary>
        public static void DeleteService()
        {
            Guid id = new Guid();
            SPSite site = new SPSite(ConfigurationManager.AppSettings[“URL”]);
            SPWebApplication web = site.WebApplication;
            SPJobDefinitionCollection jobs = web.JobDefinitions;
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {
                if (job.Title == “Custom Manager”)
                {
                    id = job.Id;
                    break;
                }
            }

            if (id != null)
            {
                jobs.Remove(id);
                web.Update();               
            }

            site.Dispose();
        }
    }
}

Other steps to follow before creating the timer service:

1. Provide strong name to the assemble.

2. Add the assemply in the GAC.

3. Put the assembly in the 80/bin folder

Finally the test application (console) to create / delete a service

using System;
using System.Collections.Generic;
using System.Text;

namespace ServiceManager
{
    class Program
    {
        static void Main(string[] args)
        {
            LeaveManager.ServiceController.DeleteService();
            LeaveManager.ServiceController.CreateService();
        }
    }

Once the service is created, it can be activated/deactivate from the central admin page.

September 27, 2009 Posted by | SharePoint | Leave a comment

Excel report using C# in SharePoint Custom Webpart

The following code snippet is focussing on creating an Excel at runtime to display the employees attendance report for the selected month using C# via SharePoint WebPart,

 

So, you will get an idea on creating excel at runtime using C#,

 

#region Required Namespaces

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
using System.IO;
using System.Data;
using Microsoft.SharePoint;
using System.Web;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Drawing;
using System.Reflection;

#endregion  
    

. . .

. . .

. . .
        /// <summary>
        /// Create the excel workbook with monthly report.
        /// </summary>
        public void CreateExcelWorkbook()
        {
            _Message.Text = “Generating report…”;
           
            Excel.Application oXL;
            Excel._Workbook oWB;
            Excel._Worksheet oSheet;
            Excel.Range oRng;
            SPSite mySite= null;
            SPWeb myWeb = null;
            string strCurrentDir = @”C:\Inetpub\wwwroot\wss\VirtualDirectories\80 \MonthlyReportsHolder\”;

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {            
                    GC.Collect();

                    mySite= new SPSite(“http://MySite“);
                    myWeb = mySite.OpenWeb(“/MyWeb”);
                    myWeb.AllowUnsafeUpdates = true;
                    myWeb.ParentWeb.AllowUnsafeUpdates = true;

                    SPList members = myWeb.ParentWeb.Lists[“Company Members”];
                    SPList leaveRecords = myWeb.Lists[“Leave Details”];                  

                    oXL = new Excel.Application();
        oXL.Visible = false;
        //Get a new workbook.
        oWB = (Excel._Workbook)(oXL.Workbooks.Add( Missing.Value ));
        oSheet = (Excel._Worksheet)oWB.ActiveSheet;   
               
                    //Legend
                    oSheet.Cells[1, 1] = “LEGEND”;
                    oSheet.Cells[1, 2] = “FORENOON”;
                    Excel.Range fn = (Excel.Range)oSheet.Cells[1, 2];
                    fn.Font.Color = ColorTranslator.ToWin32(System.Drawing.Color.Green);
                    fn.Font.Bold = true;
                    fn.EntireColumn.AutoFit();
                    oSheet.Cells[1, 3] = “AFTERNOON”;
                    Excel.Range an = (Excel.Range)oSheet.Cells[1, 3];
                    an.Font.Color = ColorTranslator.ToWin32(System.Drawing.Color.Blue);
                    an.Font.Bold = true;
                    an.EntireColumn.AutoFit();
                    oSheet.Cells[1, 4] = “FULLDAY”;
                    Excel.Range fu = (Excel.Range)oSheet.Cells[1, 4];
                    fu.Font.Color = ColorTranslator.ToWin32(System.Drawing.Color.Red);
                    fu.Font.Bold = true;
                    fu.EntireColumn.AutoFit();
                    oSheet.Cells[1, 5] = “PRESENT”;
                    Excel.Range pr = (Excel.Range)oSheet.Cells[1, 5];
                    pr.Font.Color = ColorTranslator.ToWin32(System.Drawing.Color.Gray);
                    pr.Font.Bold = true;
                    pr.EntireColumn.AutoFit();

                    _Message.Text = “Generating report…”;

                    // Build the sheet contents
                    for (int count = 1; count <= members.ItemCount; count++)
                    {
                        _Message.Text = “Generating report…”;

                        string memberName = members.Items[count – 1][“Team_x0020_Member”].ToString();

                        int index = memberName.IndexOf(“#”);
                        if (index > 0)
                            memberName = memberName.Substring(index + 1);

                        oSheet.Cells[count + 3, 1] = memberName;

                        string memberID = members.Items[count – 1][“Title”].ToString();

                        SPQuery filterQuery = new SPQuery();
                        filterQuery.Query = “<Where><And>” +
                        “<Eq><FieldRef Name=’EmployeeID’></FieldRef> <Value Type=’Text’>” + memberID + “</Value></Eq>” +
                        “<Eq><FieldRef Name=’Status’></FieldRef> <Value Type=’Text’>” + “HR Approved” + “</Value></Eq>” +
                        “</And>” +
                        “</Where>”;

                        SPListItemCollection thisMemberLeaveRecords = leaveRecords.GetItems(filterQuery);                       

                        if (thisMemberLeaveRecords.Count > 0)
                        {
                            foreach (SPListItem leaveRecord in thisMemberLeaveRecords)
                            {
                                DateTime From = Convert.ToDateTime(leaveRecord[“EventDate”]);
                                DateTime To = Convert.ToDateTime(leaveRecord[“EndDate”]);

                                TimeSpan duration = To – From;

                                if (From.Month == Month || To.Month == Month)
                                {
                                    if (From.ToShortTimeString() == “2:00 PM”)
                                    {
                                        if (From.Month == Month)
                                        {
                                            oSheet.Cells[count + 3, From.Day + 1] = leaveRecord[“LeaveType”].ToString();

                                            Excel.Range colorSetterA = (Excel.Range)oSheet.Cells[count + 3, From.Day + 1];
                                            colorSetterA.Font.Color = ColorTranslator.ToWin32(System.Drawing.Color.Blue);
                                            colorSetterA.Font.Bold = true;
                                        }
                                    }
                                    else if (To.ToShortTimeString() == “1:00 PM”)
                                    {
                                        if (To.Month == Month)
                                        {
                                            oSheet.Cells[count + 3, From.Day + 1] = leaveRecord[“LeaveType”].ToString();

                                            Excel.Range colorSetterB = (Excel.Range)oSheet.Cells[count + 3, From.Day + 1];
                                            colorSetterB.Font.Color = ColorTranslator.ToWin32(System.Drawing.Color.Green);
                                            colorSetterB.Font.Bold = true;
                                        }
                                    }
                                    else
                                    {
                                        if (From.Month == Month)
                                        {
                                            oSheet.Cells[count + 3, From.Day + 1] = leaveRecord[“LeaveType”].ToString();

                                            Excel.Range colorSetterC = (Excel.Range)oSheet.Cells[count + 3, From.Day + 1];
                                            colorSetterC.Font.Color = ColorTranslator.ToWin32(System.Drawing.Color.Red);
                                            colorSetterC.Font.Bold = true;
                                        }
                                    }
                                }

                                if (duration.Days >= 1)
                                {
                                    int totalDays = duration.Days;

                                    for (int day = 1; day <= totalDays; day++)
                                    {
                                        if (From.AddDays(day).Month == Month)
                                        {                                          
                                            oSheet.Cells[count + 3, From.AddDays(day).Day + 1] = leaveRecord[“LeaveType”].ToString();

                                            Excel.Range colorSetterD = (Excel.Range)oSheet.Cells[count + 3, From.AddDays(day).Day + 1];
                                            colorSetterD.Font.Color = ColorTranslator.ToWin32(System.Drawing.Color.Red);
                                            colorSetterD.Font.Bold = true;                                          
                                        }
                                    }
                                }
                            }
                        }
                    }

                    DateTime dt = Convert.ToDateTime(Month + “/” + “1” + “/” + Year);

                    List<string> companyHolidays = new List<string>();
                    SPList companyHolidayList = myWeb.Lists[“companyHolidays”];

                    if (companyHolidayList.ItemCount > 0)
                    {
                        foreach (SPListItem item in companyHolidayList.Items)
                            companyHolidays.Add(Convert.ToDateTime(item[“Date”]).ToShortDateString());
                    }

                    int holidaysCount = 0;

                    for (int day = 1; day <= DateTime.DaysInMonth(Year, Month); day++)
                    {
                        _Message.Text = “Generating report…”;

                        oSheet.Cells[3, day + 1] = day;
                        bool dayCounted = false;

                        for (int count = 1; count <= members.ItemCount; count++)
                        {
                            Excel.Range prColor = (Excel.Range)oSheet.Cells[count + 3, day + 1];
                            prColor.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;

                            if (dt.AddDays(day-1).DayOfWeek == DayOfWeek.Saturday ||
                                dt.AddDays(day-1).DayOfWeek == DayOfWeek.Sunday ||
                                companyHolidays.Contains(dt.AddDays(day-1).ToShortDateString()))                               
                            {
                                oSheet.Cells[count + 3, day + 1] = string.Empty;
                                if (!dayCounted)
                                {
                                    dayCounted = true;
                                    holidaysCount++;
                                }
                                continue;
                            }
                           
                            if (prColor.Text == null || prColor.Text.ToString() == “”)
                            {
                                oSheet.Cells[count + 3, day + 1] = “P”;
                                prColor.Font.Color = ColorTranslator.ToWin32(System.Drawing.Color.Gray);
                            } 
                        }
                    }

                    oSheet.Cells[3, DateTime.DaysInMonth(Year, Month) + 2] = “No of Working Days”;
                    Excel.Range noOfWrkDys = (Excel.Range)oSheet.Cells[3, DateTime.DaysInMonth(Year, Month) + 2];
                    noOfWrkDys.EntireColumn.AutoFit();
                    noOfWrkDys.Font.Bold = true;
                    oSheet.Cells[3, DateTime.DaysInMonth(Year, Month) + 3] = “No of Days Present”;
                    Excel.Range noOfDysPrsnt = (Excel.Range)oSheet.Cells[3, DateTime.DaysInMonth(Year, Month) + 3];
                    noOfDysPrsnt.EntireColumn.AutoFit();
                    noOfDysPrsnt.Font.Bold = true;
                    oSheet.Cells[3, DateTime.DaysInMonth(Year, Month) + 4] = “Days on PL”;
                    Excel.Range plDays = (Excel.Range)oSheet.Cells[3, DateTime.DaysInMonth(Year, Month) + 4];
                    plDays.EntireColumn.AutoFit();
                    plDays.Font.Bold = true;
                    oSheet.Cells[3, DateTime.DaysInMonth(Year, Month) + 5] = “Days on CL”;
                    Excel.Range clDays = (Excel.Range)oSheet.Cells[3, DateTime.DaysInMonth(Year, Month) + 5];
                    clDays.EntireColumn.AutoFit();
                    clDays.Font.Bold = true;

                    for (int count = 1; count <= members.ItemCount; count++)
                    {
                        oSheet.Cells[count + 3, DateTime.DaysInMonth(Year, Month) + 2] = DateTime.DaysInMonth(Year, Month) – holidaysCount;
                    }                   

                    for (int count = 1; count <= members.ItemCount; count++)
                    {
                        double presentDays = 0;
                        double plTaken = 0;
                        double clTaken = 0;

                        for (int day = 1; day <= DateTime.DaysInMonth(Year, Month); day++)
                        {
                            Excel.Range prColor = (Excel.Range)oSheet.Cells[count + 3, day + 1];
                            if (prColor.Text.ToString() != “”)
                            {
                                if (prColor.Text.ToString() == “P”)
                                    presentDays += 1;

                                if (prColor.Text.ToString() == “PL” && (Convert.ToInt32(prColor.Font.Color) == ColorTranslator.ToWin32(System.Drawing.Color.Blue) ||
                                    Convert.ToInt32(prColor.Font.Color) == ColorTranslator.ToWin32(System.Drawing.Color.Green)))
                                    plTaken += 0.5;
                                else if (prColor.Text.ToString() == “PL” && Convert.ToInt32(prColor.Font.Color) == ColorTranslator.ToWin32(System.Drawing.Color.Red))
                                    plTaken += 1;

                                if (prColor.Text.ToString() == “CL” && (Convert.ToInt32(prColor.Font.Color) == ColorTranslator.ToWin32(System.Drawing.Color.Blue) ||
                                    Convert.ToInt32(prColor.Font.Color) == ColorTranslator.ToWin32(System.Drawing.Color.Green)))
                                    clTaken += 0.5;
                                else if (prColor.Text.ToString() == “CL” && Convert.ToInt32(prColor.Font.Color) == ColorTranslator.ToWin32(System.Drawing.Color.Red))
                                    clTaken += 1;

                                if (Convert.ToInt32(prColor.Font.Color) == ColorTranslator.ToWin32(System.Drawing.Color.Blue) ||
                                    Convert.ToInt32(prColor.Font.Color) == ColorTranslator.ToWin32(System.Drawing.Color.Green))
                                    presentDays += 0.5;
                            }
                        }

                        oSheet.Cells[count + 3, DateTime.DaysInMonth(Year, Month) + 3] = presentDays;
                        oSheet.Cells[count + 3, DateTime.DaysInMonth(Year, Month) + 4] = plTaken;
                        oSheet.Cells[count + 3, DateTime.DaysInMonth(Year, Month) + 5] = clTaken;
                    }

                    //Format A1:AF1 as bold, vertical alignment = center.
        oSheet.get_Range(“A3”, “AF1”).Font.Bold = true;                  
                 oSheet.get_Range(“A3”, “AF1”).VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; 
                    oSheet.get_Range(“A3”, “AF1”).HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                   
        //AutoFit columns
        oRng = oSheet.get_Range(“A3”, “A3”);
                    oSheet.get_Range(“A3”, “A” + members.ItemCount + 3).Font.Bold = true;                  

        oRng.EntireColumn.AutoFit();
        oXL.Visible = false;
        oXL.UserControl = false;

        string strFile =”Report” + System.DateTime.Now.Ticks.ToString() + “.xls”;
                    oWB.SaveAs( strCurrentDir + strFile,Excel.XlFileFormat.xlWorkbookDefault,null,null,false,false,Excel.XlSaveAsAccessMode.xlShared,false,false,null,null,null);

        // Need all following code to clean up and extingush all references!!!
        oWB.Close(null,null,null);
        oXL.Workbooks.Close();
        oXL.Quit();
        System.Runtime.InteropServices.Marshal.ReleaseComObject (oRng);
        System.Runtime.InteropServices.Marshal.ReleaseComObject (oXL);
        System.Runtime.InteropServices.Marshal.ReleaseComObject (oSheet);
        System.Runtime.InteropServices.Marshal.ReleaseComObject (oWB);
        oSheet=null;
        oWB=null;
        oXL = null;
        GC.Collect();  // force final cleanup! 

                    _Message.ForeColor = Color.Red;
                    _Message.Text = “<A href=” + mySite.Url + @”\MonthlyReportsHolder\”+ strFile + “>Download Report</a>”;
                });
            }
            catch(System.Exception error)
            {
                _Message.Text = error.Message;
            }
            finally
            {
                //dispose sharepoint objects!
                myWeb.Dispose();
                mySite.Dispose();
            }
        }

September 27, 2009 Posted by | SharePoint | 2 Comments

Create a custom toolbar webpart in MOSS 2007

The following code snippet will give you an idea on creating a custom toolbar webpart in MOSS 2007. The code snippet also contains enabling support for Ajax.

public class CustomCalendar : System.Web.UI.WebControls.WebParts.WebPart
{

        #region Global Variables

         private SPCalendarView _TeamCalendarUI = null;
        private UpdatePanel _ControlsHolder = null;
        private ToolBar _TeamCalendarToolBar = null;
        private LinkButton _NewMeetingButton = null;
        private LinkButton _NewAppointmentButton = null;

         #endregion 

        /// <summary>
        /// Register the ScriptManager during page init.
        /// </summary>
        /// <param name=”e”></param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            ScriptManager ajaxManager = ScriptManager.GetCurrent(this.Page);
            if (ajaxManager == null)
            {
                ajaxManager = new ScriptManager();
                ajaxManager.EnablePartialRendering = true;

                Page.ClientScript.RegisterStartupScript(this.GetType(), this.ID, “_spOriginalFormAction = document.forms[0].action;”, true);

                if ((this.Page.Form != null))
                {
                    string formOnSubmitAtt = this.Page.Form.Attributes[“onsubmit”];
                    if (!string.IsNullOrEmpty(formOnSubmitAtt) & formOnSubmitAtt == “return _spFormOnSubmitWrapper();”)
                    {
                        this.Page.Form.Attributes[“onsubmit”] = “_spFormOnSubmitWrapper();”;
                    }
                    //add the ScriptManager as the first control in the Page.Form
                    this.Page.Form.Controls.AddAt(0, ajaxManager);
                }
            }
        }

        /// <summary>
        /// Create the controls to be rendered.
        /// </summary>
        protected override void CreateChildControls()
        {
            //Clear the existing controls
            this.Controls.Clear();
           
            _ControlsHolder = new UpdatePanel();
            {
                _ControlsHolder.ID = “updatePanel”;
                _ControlsHolder.ChildrenAsTriggers = true;
                _ControlsHolder.UpdateMode = UpdatePanelUpdateMode.Conditional;
            }

            this.Controls.Add(_ControlsHolder); 

            #region New Meeting Button

            _NewMeetingButton = new LinkButton();
            _NewMeetingButton.ToolTip = “Schedule a new meeting.”;
            _NewMeetingButton.Text = “New Meeting”;
            _NewMeetingButton.ID = “newMeetingBtn”; 

            #endregion 

            #region New Appointment Button

            _NewAppointmentButton = new LinkButton();
            _NewAppointmentButton.ToolTip = “Schedule a new appointment.”;           
            _NewAppointmentButton.Text = “New Appointment”;
            _NewAppointmentButton.ID = “newAppointmentBtn”;
            _NewAppointmentButton.Attributes.Add(“onclick”, “window.alert(‘Not yet implemented.’)”);

            #endregion 

            #region Custom ToolBar

            _TeamCalendarToolBar = (ToolBar)Page.LoadControl(“~/_controltemplates/ToolBar.ascx”);
            _TeamCalendarToolBar.RightButtonSeparator = “|”;  
            _TeamCalendarToolBar.RightButtons.Controls.Add(_NewMeetingButton);
            _TeamCalendarToolBar.RightButtons.Controls.Add(_NewAppointmentButton);           
            #endregion         

            _ControlsHolder.ContentTemplateContainer.Controls.Add(_TeamCalendarToolBar);

            _TeamCalendarUI = new SPCalendarView();
            _TeamCalendarUI.EnableViewState = true;
            _TeamCalendarUI.Width = System.Web.UI.WebControls.Unit.Percentage(100);

            . . .
            . . .

        }

        protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
        {
            _ControlsHolder.RenderControl(writer);
        }

OutPut:

CustomToolBar

September 27, 2009 Posted by | SharePoint | 1 Comment

SPGridView Paging

The following code will give you an idea of using SPGridView and performe paging in it.

 using System;

using System.Collections.Generic;

using System.Text;

using System.Data;

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;

using Microsoft.SharePoint.Utilities;

namespace MySPGridViewPagingSample {

public class MySPGridView : WebPart {

 SPGridView _MyDetails= null;

protected override void CreateChildControls() {

 SPSite site = new SPSite(“http://wss-MySite/&#8221;); //Open a site

 SPWeb web = site.OpenWeb();

SPList list = web.Lists[“MyList”]; //Get the items from a list.

 _MyDetails = new SPGridView();

MyDetails.AutoGenerateColumns = false;

_MyDetails.AllowPaging = true;

_MyDetails.PageSize = 5;

_MyDetails.PageIndexChanging += new GridViewPageEventHandler(_MyDetails_PageIndexChanging);

BoundField field = new BoundField();

field.HeaderText = “Title”;

field.DataField = “Title”;

field.ShowHeader = true;

_MyDetails.Columns.Add(field);

BoundField field2 = new BoundField();

field2.DataField = “Status”;

field2.HeaderText = “Status”;

_MyDetails.Columns.Add(field2);

_MyDetails.DataSource = list.Items.GetDataTable(); this.Controls.Add(_MyDetails);

_MyDetails.PagerTemplate = null;

_MyDetails.DataBind();

}

void _MyDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)

{

_MyDetails.PageIndex = e.NewPageIndex;

_MyDetails.DataBind();

}

public override void RenderControl(HtmlTextWriter writer)

 {

this.EnsureChildControls();

_MyDetails.RenderControl(writer); } } }

The output will be,

SPGridViewPaging

September 27, 2009 Posted by | SharePoint | 13 Comments

Reading values from a column of type Person or Group in MOSS 2007

Suppose you have a custom list or document library with a column named
‘Members’ of type Person or Group with multiple selections then, the
SPFieldUserValueCollection can be used to hold the multiple values.

The following code snippet will give you an idea on accessing
values from a column of type Person or Group.

SPFieldUserValueCollection selectedMembers = (SPFieldUserValueCollection)                                                                             _SpListItemRecord[“Members”];

if (selectedMembers != null)
   {
      string selected= string.Empty;

      foreach (SPFieldUserValue fuv in selectedMembers)
      {
         SPUser userA = web.AllUsers[fuv.LookupValue];
         selected += userA.Name + “,”;
      }     
    }

Regards,

JG Vimalan

September 27, 2009 Posted by | SharePoint | Leave a comment