JG Vimalan's Blog

It is all about coding!

People Editor in custom webpart in MOSS 2007

Hi, 

The following code snippet shows how to add PeopleEditor control in custom sharepoint webpart. It also shows how to read values from people editor. 

    public class EmployeeDetails : WebPart
    {
        #region declarations
        PeopleEditor _DisplayName = null;
         . . .
        //In the business logic, use this method to get the user selected in the
        //people editor
        private SPUser GetuserName(PeopleEditor userName, SPWeb web)
        {
            SPUser user = null;

            foreach (PickerEntity pe in userName.Entities)
            {
                user = web.AllUsers[pe.Key];
            }
            return user;
        }
    protected override void CreateChildControls()
     {
         . . .
         
            TableRow EmployeeName = new TableRow();

            TableCell EmployeeNameLabel = new TableCell();
            TableCell EmployeeNameControl = new TableCell();
            EmployeeNameLabel.Text = “Employee Name:”;

            EmployeeNameLabel.HorizontalAlign = HorizontalAlign.Right;
            EmployeeNameLabel.CssClass = “ms-formlabel”;
            _DisplayName = new PeopleEditor();
            _DisplayName.AllowTypeIn = true;
            _DisplayName.AllowEmpty = false;
            _DisplayName.EnableBrowse = true;
            _DisplayName.ID = “peopleID”;
            _DisplayName.MultiSelect = false;
            _DisplayName.ValidatorEnabled = true;

            EmployeeNameControl.CssClass = “ms-formbody”;
            EmployeeNameControl.Controls.Add(_DisplayName);
            ….

     //TO DO: Render the controls 

OutPut: 

Once this webpart is deployed, you will get output as shown below,

PE

Happy Coding!!!

JG Vimalan

Advertisements

August 11, 2009 Posted by | SharePoint | Leave a comment

Deleting the selected items in listview at runtime using C#

Hi, 

Consider a scenario where, you have a listview control in your application. Each record in the listview control holds a xmlnode object in its Tag property.

User selects few items (rcords) in listview at random and you need to save the selected node into a list and then delete the selected records from the listview at runtime. 

To accomplish this scenario, the following code will help you…          

//Generic list to hold the selected nodes 

List<XmlNode> seletedItemsInList = new List<XmlNode>();      

//working from a high index keeps lower indexes at their original value
            for (int i = _ListView.Items.Count – 1; i >= 0; i–)
            {
                if (_ListView.Items[i].Selected)
                {
                    seletedItemsInList.Add(_ListView.Items[i].Tag as XmlNode);
                    _ListView.Items[i].Remove();
                }
            }
           
Note: if you work low to high, indexes change and you do not get the right results 

Regards,

JG Vimalan

August 10, 2009 Posted by | C#.NET | Leave a comment

Ping UNC path

Hi, 

The code Directory.Exists(“uncPath”); is too slow for unavailable/disconnected unc path. So, to solve this issue, we can ping the unc path before checking for the directory. The following code snippet will give you an idea of pinging unc path, 

       public static bool PingUNCPath(string uncPath)
       {
           string hostNameOrAddress = string.Empty;
           string[] uncPathMembers = uncPath.Split(‘\\’);

           //You may have a path some thing like \\\\abcd001\\Documents\\New\\

          //We need only the computer name. So split the path.

           //Get the host name or address.
           foreach (string pathName in uncPathMembers)
           {
               if (!string.IsNullOrEmpty(pathName))
               {
                   //first non empty word is host name
                   hostNameOrAddress = pathName;
                   break;
               }
           }
          
           try
           {
               System.Net.NetworkInformation.Ping ping = new  System.Net.NetworkInformation.Ping();
               System.Net.NetworkInformation.PingReply reply = ping.Send (hostNameOrAddress, 200); //200ms

               if (reply.Status == System.Net.NetworkInformation.IPStatus.Success)
                   return true;
           }
           catch //if host name is not found, you get ping exception!!!
           {
               //Invalid Operation
               //Not supported
               //Ping exception
               //Socket exception
               //object disposed exception
               return false;
           }          

           return false;
       } 

Regards,

JG Vimalan

August 10, 2009 Posted by | C#.NET | Leave a comment

Check if a path is UNC or not using C#

The following code snippet will give you an idea on verifying whether the given path is an UNC or not, 

using System.Runtime.InteropServices; 

public class UNCTest

 . . .

 . . . 

[DllImport(“shlwapi.dll”, CharSet = CharSet.Unicode)]
        [ResourceExposure(ResourceScope.None)]
        [return: MarshalAsAttribute(UnmanagedType.Bool)]
        public static extern bool PathIsUNC(
            [MarshalAsAttribute(UnmanagedType.LPWStr), In] string pszPath); 

You can directly call the PathIsUNC method and verify whether the given path is unc or not as shown below, 

if (UNCTest.PathIsUNC(\\\\abcd001\\Documents\\))
 _UncPath = true; 

Regards,

JG Vimalan

August 10, 2009 Posted by | C#.NET | Leave a comment

Hiding default toolbar in DispForm.aspx page in SharePoint

The following has to be added in the DispForm.aspx for the selected list (I’ve used Calendar).

You can locate this page using SharePoint designer.

<asp:Content ContentPlaceHolderId=”PlaceHolderTitleAreaClass” runat=”server”>
<script id=”onetidPageTitleAreaFrameScript”>
document.getElementById(“onetidPageTitleAreaFrame”).className=”ms-areaseparator”;

<!– Code for removing toolbar menu –>
var objToolBar = document.getElementById(“ctl00_m_g_894df972_bb01_4b6f_8c99_1247cadd83f0_ctl00_ctl01_ctl00_toolBarTbl”);

var objParent = objToolBar.parentNode;
objParent.removeChild(objToolBar);

var  tdEvent =  document.getElementById(“SPFieldAllDayEvent”);
var  tdRecurrence =  document.getElementById(“SPFieldRecurrence”);
var  tdLink =  document.getElementById(“SPFieldCrossProjectLink”);

var  tr = tdEvent.parentNode;
var  table = tr.parentNode;
table.removeChild(tr);
table.removeChild(tdRecurrence.parentNode);
table.removeChild(tdLink.parentNode);

</script>
</asp:Content>

hidingToolBar

Happy Coding!

August 10, 2009 Posted by | SharePoint | Leave a comment

Create a custom toolbar webpart in MOSS 2007

Hi, 

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

Regards,

JG Vimalan

August 10, 2009 Posted by | SharePoint | Leave a comment