Oct 5, 2009

Function to write the cookies in the browser for infinite time in javascript

in this post our objective is to write the cookies through javascript for infinite time period(here we have given the time period as 100 days)ie.cookies never expires.In this javascript we have also accessed the textbox value and SPContext.Current.Web.CurrentUser.LoginName value .
Write this function inside the "Script" tag of the javascript.
------------------------------------------------------


 function WriteCookies() {
//This is the way to access the value of controls in aspx page through javascript      
 var chk = ddocument.getElementById(<% SPHttpUtility.AddQuote(SPHttpUtility.NoEncode(txtBox.ClientID),Response.Output); %>);


//Way to access the current logged in user name from SPContext in javascript
        var userLoginName =<% SPHttpUtility.AddQuote(SPHttpUtility.NoEncode(SPContext.Current.Web.CurrentUser.LoginName),Response.Output); %>;
        if(chk!=null) {
            if (chk.checked) {
                value = 'TRUE';
            } else {
                value = 'FALSE';
            }
            name = 'KeyName'+'_'+userLoginName;
            //To make the expiry if cookie as infinite
            //Currently we have set the expiry date for 100 days.
            var days = 100;
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                var expires = "; expires=" + date.toGMTString();
            }
            else var expires = "";
            document.cookie = name + "=" + value + expires + "; path=/";
        }
    }
-----------------------------------------------------
So your job is done
Enjoy!!!

Reading the cookies from the browser in javascript

Here objective is to read the cookies value in javascript. Here is the function which needs to placed inside the "script" of the javascript.This function will read the cookie value from the available cookies in the browser based on the key passed for the cookie.

Here the function is called on page load
-------------------------------------------------------------------


function OnLoadFuntion() {
        name = 'KeyName';
        readCookie(name);
        function readCookie(name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) == 0) {
                  
                    if (c.substring(nameEQ.length, c.length) == 'TRUE') {
                        //Write functionality
                    }
                }
            }
            return null;
        }
    }
----------------------------------------------------------


So your job is done
Enjoy!!!

Using SharePoint:SPSecurityTrimmedControl to control the visibility of SiteActions

Here the objective is to control the behavior of SiteActions.We can hide these based on the current logged in user permissions.We can hide  the control from all the users accept the SiteAdmin who is having SiteCollection Administrator rights.
For this we do not require any custom coding , Only thing is we have to modify the Master page. Modifying the default master page is not advisable ,so create your custom master page.For deploying master page as a feature in the site follow this link


Now follow these steps to hide SiteActions :
1)     Open the custom master page in visual studio or notepad
2)     Search for <SharePoint:SiteActions
3)     Wrap this SiteActions control with
SharePoint:SPSecurityTrimmedControl ID="SPSecurityTrimmedControl" runat="server" PermissionsString="ManageSubwebs">

“<SharePoint:SiteActions>”

See the image below 





Here we have to set certain parameters like “PermissionString”.This defines if the current logged in user is having this permissions set is able to view the “SiteAction” control. Since ManageWeb is the highest level of permission set ,so this will be available to SiteAdmin only.



To remove the control from Anonymous user use this
PermissionsString="BrowseDirectories"
We can also give the permission level in concatenated fashion also ..like comma(‘,’) way. These permissions work in ‘OR’ manner.
To view the SPBasePermission Enumeration follow this MSDN Link
Similarly we can control the behavior of other controls like ViewAll Site Content
For this find <SharePoint:SPLinkButton in the master pagee
This control is already wrapped in SharePoint:SPSecurityTrimmedControl and is having Permission string as ViewFormPages”.So We can set the permission string here as well based on our requirement.
See the code below present in the master page.
<SharePoint:SPSecurityTrimmedControl runat="server" permissionsstring="ViewFormPages">
                                                                                    <SharePoint:SPLinkButton id="idNavLinkViewAll" runat="server"
                                                                                          NavigateUrl="~site/_layouts/viewlsts.aspx" Text=""
                                                                                          AccessKey="" />
                                                                              SharePoint:SPSecurityTrimmedControl>

So your Job is done.If you face any problem then do let me know.
Enjoy!!!

Oct 2, 2009

Creating a Custom Toolpart for webpart

Webpart comes with a default tool part which contains the configuration settings for the webpart. But often we have requirement to create the custom toolpart for the webpart having certain .net controls like dropdown list ,treeview etc which fetches data from the list or any other source and performs certain functionality based on the logic.

Webpart will look like this



Here is step by step process for creating webpart with custom toolpart:

1)      Open visual studio
2)      Create a new project with type class library
3)      Inherit the class with  Microsoft.SharePoint.WebPartPages.WebPart class

Below is the code for the webpart class


----------------------------------------------------------------------


using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;


namespace CustomToolPartWP
{
    public class CustomWebPart : Microsoft.SharePoint.WebPartPages.WebPart
    {
        private string ddlvalue = string.Empty;


        [Browsable(false), Category("Miscellaneous"),
        WebPartStorage(Storage.Personal),
        FriendlyName("ListValue"), Description("Text Property")]
        public string DropDownListValue
        {
            get
            {
                return ddlvalue;
            }


            set
            {
                ddlvalue = value;
            }
        }


        //  Gets the custom tool parts for this Web Part by
        /// overriding the GetToolParts method of the WebPart
        /// base class. You must implement custom tool parts in
        /// a separate class that derives from
        /// Microsoft.SharePoint.WebPartPages.ToolPart.
        ///
        ///
        /// An array of references to ToolPart objects.
        ///
        public override ToolPart[] GetToolParts()
        {
            ToolPart[] toolparts = new ToolPart[3];
            WebPartToolPart wptp = new WebPartToolPart();
            CustomPropertyToolPart custom = new CustomPropertyToolPart();
            toolparts[0] = custom;
            toolparts[1] = wptp;


            // This is the custom ToolPart.
            toolparts[2] = new CustomToolPartWP.CustomToolPart();


            return toolparts;
        }


        /// Render this Web Part to the output parameter specified.
        /// The HTML writer to write out to
            protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);
            writer.Write("Value Selected from dropdown is " + this.ddlvalue +
");
       
    }
}
------------------------------------------------------------------
Lets discuss some important features of the webpart .Here we have declared one “DropDownListValue” ,it has some attributes like
a)      Browsable : To appear this property in the wepart
b)      Category: It shows the label name under which our custom control should render
c)      WebPartStorage : There are two types of storage .One is personal ,this means that the value stored are specific to the logged in user ,other is shared ,in this saved value will be visible to all the users.


Once the webpart is done we need to add the class for toolpart which contains the code for custom toolpart. Follow these steps:
1)      Add class to the solution
2)      Inherit this class with Microsoft.SharePoint.WebPartPages.ToolPart

This is the sample code for the Toolpart which renders once dropdown list and selecting some value and clicking on Apply or Ok  sets the value in the webpart.
------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;


namespace CustomToolPartWP
{
    ///
    /// Description of the toolpart. Override the GetToolParts method
    /// in your Web Part class to invoke this toolpart. To establish
    /// a reference to the Web Part the user has selected, use the
    /// ParentToolPane.SelectedWebPart property.
        class CustomToolPart : Microsoft.SharePoint.WebPartPages.ToolPart
    {
        private string inputname;
        DropDownList dropdownList;


            // an event handler for the Init event
        private void CustomToolPart_Init(object sender,
                  System.EventArgs e )
            {
                  inputname = this.UniqueID + "message";
            }


            ///
            /// Constructor for the class. A great place to set Set
            /// default values for additional base class properties
            /// here.
            ///


        public CustomToolPart()
            {
                  // Set default properties
                  this.Title="Select Value";
            this.Init += new EventHandler(CustomToolPart_Init);
            }
            ///   Called by the tool pane to apply property changes to
            /// the selected Web Part.
           public override void ApplyChanges()
            {
                  CustomWebPart customWP = (CustomWebPart)
                  this.ParentToolPane.SelectedWebPart;
                 
                  // Send the custom text to the Web Part.
            customWP.DropDownListValue = dropdownList.SelectedItem.Value;
            }


        protected override void CreateChildControls()
        {
            //base.CreateChildControls();
            dropdownList = new DropDownList();
            dropdownList.Items.Add("item1");
            dropdownList.Items.Add("item2");
            dropdownList.Items.Add("item3");
            dropdownList.Items.Add("item4");
            CustomWebPart customWP = (CustomWebPart)
            this.ParentToolPane.SelectedWebPart;
           
            dropdownList.Items.FindByText(customWP.DropDownListValue).Selected = true;


            this.Controls.Add(dropdownList);
        }
            ///   If the ApplyChanges method succeeds, this method is
            /// called by the tool pane to refresh the specified
            /// property values in the toolpart user interface.
            public override void SyncChanges()
            {
                  // sync with the new property changes here
            CustomWebPart customWP = (CustomWebPart)
                  this.ParentToolPane.SelectedWebPart;
            customWP.DropDownListValue = dropdownList.SelectedItem.Value;
            }
           
            ///   Called by the tool pane if the user discards changes
            /// to the selected Web Part.
            public override void CancelChanges()
            {
            }
            /// Render this Tool part to the output parameter
            /// specified.
            /// The HTML writer to write out to
            protected override void RenderToolPart(HtmlTextWriter output)
            {
                  // Establish a reference to the Web Part.
                  CustomWebPart customWebPart = (CustomWebPart)
                  this.ParentToolPane.SelectedWebPart;
                  output.Write("Select value from drop down: ");
            dropdownList.RenderControl(output);
            }
    }
}
 ------------------------------------------------------------------------------------

After this compile the solution and deploy the webpart and put the dll in GAC or the bin folder of the webapplication

And your webpart is ready to use with custom toolpart.
 There is a very good artilce on MSDN to create custom toolpart.
If you have queries than do post.

Your job is done J
Enjoy!!!