Blog of Sundar Narasiman

Create unsecure application pages for sharepoint

There are times, where we need to create an application page to be accessed anonymously by the user, instead of the user signing-in and accessing the page. Here is the code-snippet to create an unsecure application page for sharepoint.

    public partial class UnsecureApplicationPage : Microsoft.SharePoint.WebControls.UnsecuredLayoutsPageBase
    // inherit the page from Microsoft.SharePoint.WebControls.UnsecuredLayoutsPageBase instead of Microsoft.SharePoint.WebControls.LayoutsPageBase    

    {

        protected void Page_Load(object sender, EventArgs e)
        {                   

        }       

    //override the allow anonymous property to true
        protected override bool AllowAnonymousAccess
        {
            get { return true; }
        }

        protected override bool AllowNullWeb { get { return true; } }

        protected override void OnPreInit(EventArgs e)
        {

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {

                base.OnPreInit(e);
                Microsoft.SharePoint.SPWeb _Web = SPControl.GetContextWeb(Context);
                this.MasterPageFile = _Web.MasterUrl;
            });

        }

    }

 Subscribe to my post

Create secure application page for sharepoint

Creating an application page for sharepoint is fairly simple and straight-forward. To make that application page secure, just do some extra steps in the code. Here is the code-snippet for creating secure application page in sharepoint .

public partial class SampleSecurePage : Microsoft.SharePoint.WebControls.LayoutsPageBase    

    {

        public SampleSecurePage()
        {
           //In the constructor define rights check mode to be done on the pre-init event  
            this.RightsCheckMode = RightsCheckModes.OnPreInit;

        }

        //get the permission set from spbase permission enumeration
        protected override SPBasePermissions RightsRequired
        {
        get
        {
        SPBasePermissions permissions = base.RightsRequired;
        return permissions;
        }
        }

        protected override void OnPreInit(EventArgs e)
        {

                 base.OnPreInit(e);
                 Microsoft.SharePoint.SPWeb _Web = SPControl.GetContextWeb(Context);

        //dynamically assign the master of the current spweb to the application page
                 this.MasterPageFile = _Web.MasterUrl;

             if (!HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    //re-direct the user to log-in page and authenticate

                }                  

        }       

        protected void Page_Load(object sender, EventArgs e)
        {
            //do some logic here             

        }        

    }

 Subscribe to my post

Leverage Javascript inside sharepoint web parts

Many a times, we’d find the need for leveraging the javascript in sharepoint web parts. It could be a simple requirement of opening up a pop-up window or could be  a complex requirement to invoke a web service from javascript. Here is code-snippet and steps to leverage java script inside sharepoint web parts. The crux is to embeed or register the javascript function in the PreRender event of the web part and invoke this registered javascript, from wherever desired.

//In the constructor of the web part, define a delegate of the PreRender method.
    public SampleWebPart()
        {
            this.PreRender += new EventHandler(SampleWebPart_ClientScript_PreRender);

        }

        #region register javascript methods

//In the delegate method of PreRender, call the another method that does the registering of javascript
        // Client script registration event
        private void SampleWebPart_ClientScript_PreRender(object sender, System.EventArgs e)
        {
            RegisterJavaScript();
        }
//Use the RegisterClientScriptBlock method of the Page object, to register the javascript
        //Function will embedded script
        protected void RegisterJavasScript()
        {

            //format the string to hold the javascript
            string embeedscript = "   <script>" +
                                    "function openNewWin(url) {" +
                                        //"var x = window.open(url, 'mynewwin', 'width=1200,height=800');" +
                                        "var x = window.open(url);" +
                                        "x.focus();" +
                                            "} " +
                                   "</script>";

            string OpenScriptKey = "OpenNewWin";
            //check whether the javascript has been already registered to the page
            if (!Page.IsClientScriptBlockRegistered(OpenScriptKey))
            {
                Page.RegisterClientScriptBlock(OpenScriptKey, embeedscript);

            }

        }

protected void Button1_click(object sender, ImageClickEventArgs e)

        {

//invoke the javascript function that opens the application page  in new window
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWin", "<script>openNewWin('" + url + "')</script>");                

}

 Subscribe to my post

SharePoint List Item Read Security and Write Security

Many a times, i’ve seen in MSDN Forums where people asking for the much granular-level of list security like who can read the list items and who can write/update t sayihe list items. There are couple of properties called ReadSecurity and Write Security in the SPListClass, that provides the more granular level of security.

The ReadSecurity property of the SPList gets or sets the Read security setting for the list. It can have the possible values of 1 or 2.

1- indicates all users can read the list items

2 – indicates the users can read the items only that they create

The WriteSecurity property of the SPList gets or sets the Read security setting for the list. It can have the possible values of 1, 2 and 4.

1 – Indicates that all the users can modify the all the items

2- Indicates the users can modify the items that they create

4 – Users cannot modify any list item

 Subscribe to my post

Create Custom Tool Parts for SharePoint Web Parts

What is a custom tool part ?

The Custom tool part is part of the web part infrastructure, that helps us to create a custom user interface for the web part properties that goes beyond the capabilities of the default property pane.

When do we need a custom tool part ?

Let’s say, If we need to create a web part property of type dropdown, we need to create a custom tool part. This is not supported out-of-box in the web part framework. I’ve the similar requirement of creating a custom web part property of type drop-down, So i went ahead and implemented the custom tool parts. Here are the steps to create a custom tool part.  

 public class SampleToolPart : Microsoft.SharePoint.WebPartPages.ToolPart
    {
        //create an instance of the dropdown control to be used in the custom tool part 
        System.Web.UI.WebControls.DropDownList oDropDown = new System.Web.UI.WebControls.DropDownList();

        // Reference to the parent web part
        SampleWebPart oSampleWebPart = null;

On the constructor method of the tool part class, just set the title of the tool part. In this case i'm going to display the 
vendor names to the user
So i naming the title as select a vendor.
        public SampleToolPart()
        {

            // Set the title for the custom tool part
            this.Title = "Select a Vendor";

        }

        protected override void CreateChildControls()
        {
            try
            {

            //Get the instance of the parent web part on which this tool part is to be hosted
            oSampleWebPart = (SampleWebPart)ParentToolPane.SelectedWebPart; 
            //Get the instance of the current site collection
            SPSite oSPSite = SPControl.GetContextSite(HttpContext.Current);
            //Get the instance of the current site (spweb)
            Guid currentsiteid = SPControl.GetContextWeb(HttpContext.Current).ID;

            using (SPWeb oSPWeb = oSPSite.OpenWeb(currentsiteid))   

                {
In the following few lines of code, i'm reading the list of vendors from the sharepoint custom list 'VendorList' and binding it to the sharepoint custom tool part. 
                    SPList oProviderMaster = oSPWeb.Lists["VendorList"];
                    foreach (SPListItem oSPListItem in oProviderMaster.Items)
                    {

                        string sProviderName = oSPListItem["VendorName"].ToString();
                        oDropDown.Items.Add(sProviderName);
                    }

                }

            // Add the dropdown to the actual toolpart controls
            this.Controls.Add(oDropDown);
            base.CreateChildControls();
            }
            catch (Exception ex)
            {

            }

        }

When the user choses the item from the dropdown of the custom tool part and clicks 'Apply Changes', grab the selected item from 
the dropdown list and assign this value to a public property declared in the parent web part, where the tool part is hosted.
        public override void ApplyChanges()
        {
            try
            {
                if (!(oDropDown.SelectedItem == null))
                {
                    oSampleWebPart.SelectVendor = oDropDown.SelectedValue;
                }

            }
            catch (Exception ex)
            {

               //handle exceptions here
            }            

        }   

    }

 Subscribe to my post

Render Iframes dynamically inside SharePoint Application Pages

There is a requirement to render the publically available web site content inside SharePoint application pages, dynamically based on arbitrary condition. This can be done in two ways. The first option is to use the page viewer web part and dynamically set the url of page viewer using a user control tied to the master page. The second option is to design an application page and render the external content using IFrames. The option of application pages + Iframes is better compared to dynamic page viewer web part way, considering many pros and cons.

The best way to achieve this to have an ASP.NETuser control that hosts the IFrame. Then host the entire user control inside the application page. Because user control gives the more control and flexibility to manipulate the properties of Iframes at run-time, than finding the logical event of ASP.NET page life-cycle and accomplish this task.

.  On the page load of user control, add the src property of the user control

 protected void Page_Load(object sender, EventArgs e)
        {
            this.IFrame1.Attributes.Add("src", ThirdPartyUrl);
        }

 Subscribe to my post

SharePoint Conference 2009 Sessions

The initial list of sessions for SharePoint Conference 2009 to be held in October 2006 at LasVegas is announced. Here is the initial list of session and topics :-

  1. SharePoint 2010 Overview and What’s New
  2. Upgrading to SharePoint 2010
  3. SharePoint 2010 Capacity and Performance Planning
  4. SharePoint 2010 Security and Identity Management: What’s New
  5. Visual Studio 2010 Tools for Office Development
  6. SharePoint 2010 Ribbon, ECMAScript and Dialog Framework Development
  7. Developing with REST and LINQ in SharePoint 2010
  8. Upgrading SharePoint Server 2007 Code to SharePoint 2010
  9. Building Composite Applications with the Microsoft Application Platform
  10. What’s New in Business Connectivity Services (The Business Data Catalog Evolves!)
  11. FAST Search for SharePoint – Capabilities Deep Dive
  12. Advanced Dashboard Creation with Performance Point Services for SharePoint 2010
  13. Overview of Visio and Visio Services for SharePoint 2010
  14. SharePoint 2010 Web Content Management Deep-Dive

We may get more updated sessions down the line.

Power of Host-named Site Collections for url scaling

In SharePoint 2007, we can create two types of site-collections namely path-based site-collections and host-named site collections. The path-based site-collections are more the traditional and more common way of deployment. In Path-based site-collections,  the site-collections are mapped to a managed path that is subordinate to the web application.  The limiation of the path-based site-collection is that i can have only the single host name or hosted URL.  This does not provide great benefit in terms of url scaling.

The host-named site-collections  are created by providing a valid host-header name.

 

 

 

 

 

 

 

 

Offers and Discount on Microsoft Exams

Microsoft is providing a 10% discount on Microsoft Certified Technical Specialist (MCTS), Microsoft Certified IT Professional (MCITP) or Microsoft Certified Professional Developer (MCPD) exams.

Register today with your MVP Certification Promotion Code and enjoy 2 chances to pass a Microsoft Certification Examination* plus a 10% discount! If you fail on your first attempt, you will receive a free retake of the same exam (both exams must be taken by May 31, 2009)**!

Your Unique MVP Certification Promotion Code: IN0E9D9F

From now till March 31, 2009, the microsoft community members can  key in the above MVP Promotion Code at www.learnandcertify.com to obtain a Microsoft Certification Exam Voucher Code at a 10% discount and free retake offer.

Note:-

The Exam Voucher Code is valid for exams taken by May 31, 2009 in India. Note that the limited time offer is valid for Microsoft Certified Technology Specialist (MCTS), Microsoft Certified IT Professional (MCITP) and Microsoft Certified Professional Developer (MCPD) exams only. More information on how to obtain the vouchers and the Terms & Conditions of Usage are available to your community at www.learnandcertify.com.

Passing ASP.NET Server control id to Java script function

I’m recently working on a web application, that invovles creating a Date Picker Control. I’ve decided to leverage calendar javascript and develop them as the textox and an image invoking Calendar Javascript.

My datepicker control looks like the following

Here i’m trying to pass the id of textbox control to the javascript. Javascript could not recognize that.

I’ve learnt that the way to do is as follows