Category: SharePoint Development

SharePoint Development

Profiling SharePoint code using DebugView tool

I thought of  writing a post on profiling the SharePoint code using DebugView tool. Because DebugView is bit undermined and it’s not widely used for profiling SharePoint code. You can think of leveraging DebugView tool, when you can’t do a remote debugging and when the Developer Dashboard does not give you much information. DebugView comes handy in such scenarios and it is also less invasive approach of profiling the code.

The whole idea is to place set of Debug statements in your code and run the DebugView tool on the server. Then DebugView tool captures all the output from Debug statements and lists them.

I’ve an event handler by name ‘TestListEventHandler’ attached to a custom list called ‘TestCustomList’

pic1

Now I’ll be adding the Debug statements (System.Diagnostics.Debug.WriteLine) to the event handler methods.

My event handler implementation looks like the following with Debug statements.

public override void ItemAdding(SPItemEventProperties properties)
       {
           System.Diagnostics.Debug.WriteLine("Entering Item Adding Event");
           base.ItemAdding(properties);
           System.Diagnostics.Debug.WriteLine("Exiting Item Adding Event");
           

       }

       /// <summary>
       /// An item is being updated.
       /// </summary>
       public override void ItemUpdating(SPItemEventProperties properties)
       {
           System.Diagnostics.Debug.WriteLine("Entering Item updating Event");
           base.ItemUpdating(properties);
           System.Diagnostics.Debug.WriteLine("Exiting Item updating Event");
       }

       /// <summary>
       /// An item is being deleted.
       /// </summary>
       public override void ItemDeleting(SPItemEventProperties properties)
       {
           System.Diagnostics.Debug.WriteLine("Entering Item deleting Event");
           base.ItemDeleting(properties);
           System.Diagnostics.Debug.WriteLine("Exiting item deleting Event");
       }

       /// <summary>
       /// An item is being checked in.
       /// </summary>
       public override void ItemCheckingIn(SPItemEventProperties properties)
       {
           System.Diagnostics.Debug.WriteLine("Entering Item checingin Event");
           base.ItemCheckingIn(properties);
           System.Diagnostics.Debug.WriteLine("Exiting Item checking-in Event");
       }

       /// <summary>
       /// An item is being checked out.
       /// </summary>
       public override void ItemCheckingOut(SPItemEventProperties properties)
       {
           System.Diagnostics.Debug.WriteLine("Entering Item checking out Event");
           base.ItemCheckingOut(properties);
           System.Diagnostics.Debug.WriteLine("Exiting Item checking out");
       }

       /// <summary>
       /// An item is being unchecked out.
       /// </summary>
       public override void ItemUncheckingOut(SPItemEventProperties properties)
       {
           System.Diagnostics.Debug.WriteLine("Entering Item unchecking out Event");
           base.ItemUncheckingOut(properties);
           System.Diagnostics.Debug.WriteLine("Exiting Item checking out");
       }

       /// <summary>
       /// An attachment is being added to the item.
       /// </summary>
       public override void ItemAttachmentAdding(SPItemEventProperties properties)
       {
           System.Diagnostics.Debug.WriteLine("Entering Item attachment Adding Event");
           base.ItemAttachmentAdding(properties);
           System.Diagnostics.Debug.WriteLine("Exiting Item attachment Adding Event");
       }

       /// <summary>
       /// An attachment is being removed from the item.
       /// </summary>
       public override void ItemAttachmentDeleting(SPItemEventProperties properties)
       {
           System.Diagnostics.Debug.WriteLine("Entering Item attachment deleting");
           base.ItemAttachmentDeleting(properties);
           System.Diagnostics.Debug.WriteLine("Exiting Item attachment deleting Event");
       }

       /// <summary>
       /// A file is being moved.
       /// </summary>
       public override void ItemFileMoving(SPItemEventProperties properties)
       {
           System.Diagnostics.Debug.WriteLine("Entering Item file moving Event");
           base.ItemFileMoving(properties);
           System.Diagnostics.Debug.WriteLine("Exiting Item file moving Event");
       }

       /// <summary>
       /// An item was added.
       /// </summary>
       public override void ItemAdded(SPItemEventProperties properties)
       {
           System.Diagnostics.Debug.WriteLine("Entering Item Added Event");
           base.ItemAdded(properties);
           System.Diagnostics.Debug.WriteLine("Exiting Item Added Event");
       }

Now I’ll be running the DebugView tooll with the following capture settings

pic2

DebI’ll start adding an item item to the custom list.

pic3

DebugView captures the debug statement emitted from the code like the following.

pic4

We can measure execution test time of a particular method/statement by placing them within a enclosed Debug statements (like mentioned in the above code snippet). The tool would give you exact time (in milliseconds) when the particular debug statement is executed. If we can compute the difference in time reported between two debug statements, that would give us an exact time it takes to complete a task (a statement or a method or an external call).

The other advantage of debug view is that we can figure out the execution path of our code at runtime, like how many times a method is called or has a method been skipped etc. The log produced by DebugView can also be exported into a separate file. 

 Subscribe to my blog

SharePoint 2010 Recommended practices for disposing objects–part3

This post is the continuation of my previous post SharePoint 2010 Recommended practices for disposing objects – part2.

1. Automatic Disposal of SPWeb objects created when accessing SPWeb.ParentWeb property

It is not recommended to explicitly dispose SPWeb objects created by accessing SPWeb.ParentWeb property. The SharePoint 2010 Framework (both the SharePoint Foundation 2010 and SharePoint Server 2010) takes care of automatically disposing this object.

using (SPSite oSPSite = new SPSite("http://yoursitecollection")) 

{

using (SPWeb oSPWeb = oSPSite.OpenWeb())

{

SPList oSPList =oSPWeb.Lists ["Shared Documents"];

SPWeb oSPWebNew = oSPList.ParentWeb; //Do not explicitly dispose this

}

}
2. Explicit Disposal of SPWeb objects created when accessing SPWeb.ParentWeb property

It is recommended to explicitly dispose SPWeb objects created by accessing SPWeb.Webs property. In the following code-snippet explicitly dispose oSPWebNew object by an explicity try-finally clause. Because this is not handled by the framework

Using (SPSite oSPSite = new SPSite ("http://yoursitecollection"))

{

Using (SPWeb oSPWeb = oSPSite.OpenWeb ())

{

foreach (SPWeb oSPWebNew in oSPSite.Webs)

{

try //use a try-finally block to explicitly dispose every instance of oSPWebNew

{

// ...

}

finally

{

if(oSPWebNew != null)

oSPWebNew.Dispose ();

}

}

} // Dispose is automatically called for oSPWeb

}
3. Explicit Disposal of SPWeb objects created by when invoking SPWeb.Webs.Add method

It is recommended to explicitly dispose SPWeb objects created by invoking SPWeb.Webs.Add method. In the following code snippet, the SPWeb object created by invoking SPWeb.Webs.Add method need to be explicitly disposed using ‘Using’ clause.

using (SPSite oSPSite = new SPSite("http://yoursitecollection"))

{

using (SPWeb oSPWeb = oSPSite.OpenWeb())

{

//Explicitly use the Using Clause to dispose SPWeb objects

using (SPWeb oSPWebNew = oSPWeb.Webs.Add(strWebUrl))

{

}

} 

}
4. Explicit Disposal of SPWeb objects when invoking SPWeb.Webs[] index operator

It is recommended to explicitly dispose SPWeb objects created by accessing SP.Webs[] index operator in web collection. In the following snippet, the object oSPWeb2 needs to be explicitly disposed.

int i;

SPWeb oSPWeb, oSPWebNew;

SPSite oSPSite = new SPSite ("//yoursitecollection");

using (oSPWeb = oSPSite.OpenWeb())

{

for(i = 0;i < oSPWeb.Webs.Count;i++)

{

oSPWebNew = oSPWeb.Webs[i];

//do some arbitrary operation

oSPWeb2.Dispose();

}

}
5. Explicit Disposal of SPWeb objects when invoking Microsoft.SharePoint.Portal.SiteData.Area.Web Property

It is recommended to explicitly dispose SPWeb objects created by accessing SharePoint.Portal.SiteData.Area. Though Area and AreaManager is obsolete in SharePoint 2010 and it exists more in legacy code. This should be considered while migrating legacy SharePoint code to SharePoint 2010

int i;

SPWeb oSPWeb, oSPWebNew;

SPSite oSPSite = new SPSite("//yoursitecollection");

using(oSPWeb = oSPSite.OpenWeb())

{

for(i = 0;i < oSPWeb.Webs.Count;i++)

{

oSPWebNew = oSPWeb.Webs[i];

//do some arbitrary operation

oSPWeb2.Dispose();

}

}
6. Explicit Disposal of SPWeb objects when accessing Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager property

It is recommended to explicitly dispose SPLimitedWebPartManager object while accessing Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager property. Because SPLimitedWebPartManager internally creates an instance of SPWeb object .

using (SPSite oSPSite = new SPSite("http://youroSPSite"))

{

using (SPWeb oSPWeb = oSPSite.OpenWeb())

{

SPFile oPage = web.GetFile("Folder_Name/Source_Page");

SPLimitedWebPartManager oSPLimitedWebPartManager =

oPage.GetLimitedWebPartManager(PersonalizationScope.Shared);

//Explicity dispose oSPLimitedWebPartManager object

oSPLimitedWebPartManager.Web.Dispose();

} 

}
7. Handling Microsoft.SharePoint.Publishing.PublishingWeb objects

The PublishingWeb and PublishingWebCollection come into picture when we develop using SharePoint Server 2010. It is recommended to explicitly close the each instance of PublishingWeb object accessed inside PublishingWebCollection.

Using (SPSite oSPSite = new SPSite("http://youroSPSite"))

{

Using (SPWeb oSPWeb = oSPSite.OpenWeb())

{

PublishingWeb oPublishingWeb = PublishingWeb.GetPublishingWeb(oSPWeb);

PublishingWebCollection oPublishingWebCollection = oPublishingWeb.GetPublishingWebs();

foreach (PublishingWeb oPublishingWebNew in oPublishingWebCollection)

{

try

{

// ...

}

finally

{

if(oPublishingWebNew != null)

oPublishingWebNew.Close();

}

}

}

}
This post completes the 3 part series of guidance on disposing SharePoint objects.

 Subscribe to my blog

SharePoint 2010 Recommended Practices for disposing objects–Part1

I thought of collating set of best practices around disposing the SharePoint objects. This three part series of articles primarily focuses around that.

1. Disposal of SharePoint Objects

All the SharePoint Foundation 2010 and SharePoint Server 2010 object models implement IDisposable interface. It is recommended to explicitly dispose SharePoint 2010 objects that implement this interface. Because the large part of SharePoint Foundation 2010 object model has unmanaged objects, only a small set of it is managed objects. Do not rely on Garbage collector to release unused SP Foundation objects. It is recommended to explicitly dispose them.

Using Statement for disposing objects

a)The Using Statement can be leveraged to automate the disposal of SharePoint objects that implements IDisposable interface

string test;

using(SPSite oSPsite = new SPSite("http://yoursitecollection"))

{

using(SPWeb oSPWeb = oSPSite.OpenWeb())

{

test = oSPWeb.Title;

test = oSPWeb.Url;

}

}

b)The common language runtime translate ‘Using’ statement into a finally block and disposes the object. Using statements should be used

with Caution for the objects instantiated through SPContext.

c)Do not leverage ‘Using’ statements for SPSite or SPWeb objects that get instantiated through SPContext like the following.

using( SPWeb web = SPControl.GetContextWeb(HttpContext.Current)) { … }

d)In this case the ‘SPContext’ object is managed by SharePoint 2010 framework. This should not be used in ‘Using’ clause.

e)Leverage ‘Using’ statements for every new instance of SPSite or SPWeb created explicitly by the user (not created through SPContext). The following statement is problematic. Because the ‘Using’ statement takes care of only SPWeb, not the SPSite object. In this case, the SPSite object is created, but never disposed.

using (SPWeb web = new SPSite(SPContext.Current.Web.Url).OpenWeb())

{

} // SPWeb object web.Dispose() automatically called.

f)This problem can be fixed by nesting a ‘Using’ statement for SPSite within another ‘Using’ statement for SPWeb.

void NestingUsingStatements()

{

using (SPSite oSiteCollection = new SPSite(SPContext.Current.Web.Url))

{

using (SPWeb oSPWeb = siteCollection.OpenWeb())

{

// 

} // SPWeb object web.Dispose() automatically called.

} // SPSite object siteCollection.Dispose() automatically called.

}

2. Try-Catch-Finally statement for disposing objects

The alternative approach is to leverage Try-Catch-Finally block for disposing unused objects.

a)Leverage catch block to handle exceptions and finally block to dispose unused objects. Do not leave ‘Catch’ block empty.

try

{

oSPSite = new SPSite("http://yourserver");

oSPWeb = oSPSite.OpenWeb(..);

str = oSPWeb.Title;

}

catch(Exception e)

{

// Handle exception, log exception, etc.

}

finally

{

if (oSPWeb != null)

oSPWeb.Dispose();

if (oSPSite != null)

oSPSite.Dispose();

}

b) Always check for ‘Null’ in the finally block before disposing objects.

c)Try-Catch-Finally block can be leveraged to dispose objects created inside for-each loop.

d)Whenever the SharePoint code performs a Re-direct using Response. Redirect, it is recommended to dispose the objects explicitly before redirect. Usually finally block never gets executed during the re-direct.

try

{

oSPSite = new SPSite("http://server");

oSPWeb = oSPSite.OpenWeb(..);

str = oSPWeb.Title;

if (oSPWeb != null)

oSPWeb.Dispose();

if (oSPSite != null)

oSPSite.Dispose();

Response.Redirect("newpage.aspx");

}

catch(Exception e)

{

}

finally

{

if (oSPWeb != null)

oSPWeb.Dispose();

if (oSPSite != null)

oSPSite.Dispose();

}

e)If an object is created using ‘new’ operator , it is recommended to dispose the object

void ExplicitDisposeMethod()

{

SPSite oSPSiteCollection = null;

try

{

oSPSiteCollection = new SPSite("http://moss");

}

finally

{

if (oSPSiteCollection != null)

oSPSiteCollection.Dispose();

}

}

f)Do not share SPRequest objects across threads

g)Do not store SharePoint objects (SPSite and SPWeb) in static variables

Please refer part2 of this article for continuation …

 Subscribe to my blog

Replace SharePoint 2010 Search Box using Delegate Control

The Delegate Controls comes into picture when want to brand a SharePoint Site. The delegate control acts like a container control which encapsulates default content (set of child controls inside it). The default content (set of child controls associated with delegate) can be substituted by a specific control, by creating a feature. The ability to override or substitute the delegate controls brings the power & flexibility to brand SharePoint Sites.

The out-of-box SharePoint Foundation Master Page defines many controls like Top Navigation Data Source, Left Navigation Data Source, Search Box and Additional Page Head etc as delegate controls. The list is illustrated below :-

<SharePoint:DelegateControl runat="server" ControlId="AdditionalPageHead" 
AllowMultipleControls="true"/>
<SharePoint:DelegateControl runat="server" ControlId="GlobalNavigation" />
<SharePoint:DelegateControl runat="server" ID="GlobalDelegate0" ControlId="GlobalSiteLink0" />

<SharePoint:DelegateControl ControlId="GlobalSiteLink2" ID="GlobalDelegate2" Scope="Farm"
 runat="server" />

<SharePoint:DelegateControl runat="server" ControlId="PublishingConsole" 
Id="PublishingConsoleDelegate">
</SharePoint:DelegateControl><SharePoint:DelegateControl ControlId="GlobalSiteLink3" Scope="Farm" 
runat="server" />
<SharePoint:DelegateControl runat="server" ControlId="SmallSearchInputBox" Version="4" />

<SharePoint:DelegateControl runat="server" ControlId="TopNavigationDataSource" 
Id="topNavigationDelegate"/>
    

The above listed delegate controls can be substituted at runtime to achieve custom branding. Let’s try to replace the Small Search Input box and see how the delegate control helps for this process. The whole idea is to define a feature for the Custom User Control with same control id mentioned in delegate and the lowest possible sequence number.

Here are the steps below :-

File —> New Project —> Empty SharePoint Project

pic1

Right Click Project –> Add New item –> User Control . Name it as ‘ReplaceSearchBox’

image

It automatically creates control templates folder and places the user control underneath that. Create any arbitrary control inside the user control. For the illustration purpose, I’ll add a Calendar Control inside the user control, to visually show a difference how the page looks after the delegate substitution.

<asp:Calendar ID="Calendar1" runat="server"></asp:Calendar>
It automatically creates control templates folder and places the user control underneath that.

Right Click Features –> Add Feature

Set the Feature Scope at Site (site-collection level)

Right Click Solution —> Add New Item –> Empty Element

We’d be leveraging Elements.xml file for the delegate substitution process. Before jumping on to the substitution lets understand how the out-of-box Search Box is defined using Feature.

searchbox

The Search Box is defined in both the Features ‘OSearchBasicFeature’ and ‘OSearchEnhancedFeature’ in the location 
C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions14TEMPLATEFEATURES
The definition looks like the following :-
 
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <Control 
        Id="SmallSearchInputBox" 
        Sequence="50"
        ControlClass="Microsoft.SharePoint.Portal.WebControls.SearchBoxEx" 
ControlAssembly="Microsoft.Office.Server.Search, Version=14.0.0.0, Culture=neutral, 
PublicKeyToken=71e9bce111e9429c">

    <Property Name="GoImageUrl">/_layouts/images/gosearch15.png</Property>
    <Property Name="GoImageUrlRTL">/_layouts/images/gosearchrtl15.png</Property>
    <Property Name="GoImageActiveUrl">/_layouts/images/gosearchhover15.png</Property>
    <Property Name="GoImageActiveUrlRTL">/_layouts/images/gosearchrtlhover15.png</Property>
    <Property Name="DropDownMode">ShowDD</Property>
        <Property Name="SearchResultPageURL">/_layouts/osssearchresults.aspx</Property>
    <Property Name="ScopeDisplayGroupName"></Property>
    <Property Name="FrameType">None</Property>
    </Control>    
</Elements>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
 
Here the Id & Sequence number of the control plays an important role. 
To substitute this out-of-box SmallSearchInput box, Let’s define Elements.xml file for Feature. The id of the control should match with id of control to be replaced. 
The Sequence number should be less than the sequence number of the out-of-box control. In this case we’re assigning sequence number as 10, so that the control with the lowest
 sequence number gets precedence.
 
    <Control Id="SmallSearchInputBox" Sequence="10"
      ControlSrc ="~/_controltemplates/ReplaceSearchBox/ReplaceSearchBox.ascx">        
    </Control>
</Elements>
 
Since we’re using an user control for substitution, we need to make sure that ControlSrc attribute is defined. There is no need to define ControlClass and ControlAssembly attribute here. 
I did define all the 3 attributes, but the substitution was not happening. I’ve learnt that it’s enough to define the ControlSrc attribute itself. Do not define all 3  attributes for user control, 
the substitution will not happen. If you are using Custom Control, it makes sense to use ControlClass and ControlAssembly attribute.
The final Solution Package looks like the following :-
image

Build the Project, Package it and Deploy.

Now you can see the the custom user control with Calendar replaces the Delegate control.

Delegate Substitution

 

 Subscribe to my blog

Create secure sharepoint application page for site administrator

I’ve seen a question in msdn forum few days back, asking whether the sharepoint application page can be accessed only by the administrator. There is a simple way to achieve this. Whenever we create the secure application page in sharepoint, we need to override the property called RequireSiteAdministrator and return the value true. This would secure the application page in such a way that, it can be accessed only the site-administrator. Here is the code-snippet for the same. 

public class YourSampleApplicationPage : LayoutsPageBase {

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

  protected override void OnLoad(EventArgs e) {
    // any arbitrary logic goes here
  }
}

 Subscribe to my post

Create a custom web part to render silverlight application

In my previous post, I’ve discussed about how to leverage the content editor web part to render the silverlight application. In this post, I’d be discussing the steps to create a custom web part to render the silverlight application. The custom web part that renders the silverlight application has more advantages. Because things like attributes of silverlight application can be externalized as web part properties. Moreover security can be applied while rendering silverlight application, because the custom web part has power of code-behind support, rather than content editor web part. The whole idea is to render the silverlight control programmatically inside the web parts(using createchildcontrols method) . Here are the steps mentioned below :-

a)Import required namespace

Add a reference to System.Web.Silverlight.

using System.Web.UI.SilverlightControls; 

b)Programmatically add the script manager control to the page

To render the silverlight control, the ScriptManager object needs to added to the Page. Override the OnLoad method of web part, add the ScriptManager control using the following code-snippet. There needs to be only one instance of ScriptManager object registered with the Page object.

    protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            //get the script manager associated with the current page
            ScriptManager oscriptManager =
                  ScriptManager.GetCurrent(this.Page);

            //check whether the script manager is already registered to the page
            if (oscriptManager == null)
            {
                oscriptManager = new ScriptManager();
                Controls.AddAt(0, scriptManager);
            }

        }

 

c)CreateChildControls method to render silverlight application

Override the CreateChildControls method and render the Silverlight control.

 protected override void CreateChildControls()
        {
            base.CreateChildControls();

            Silverlight oSilverlight = new Silverlight();
            oSilverlight.ID = “SLWPID”;
            oSilverlight.Source = “∼/ClientBin/YourSilverlightApp.xap”;
            oSilverlight.Width = Unit.Percentage(100);
            Controls.Add(oSilverlight);
        }

 Subscribe to my post

Leverage content editor web part to render silverlight application

Silvelight can be integrated with SharePoint sites to provide richness and improve the user experience of the SharePoint sites. There are many ways to integrate the silverlight application (xap) with SharePoint sites. The first option is to leverage the content editor web part and render the silverlight application (xap) through html and JavaScript. This is the simplest way to integrate silverlight applications with SharePoint sites. The other option is to to create a custom web part that does the rendering of the silverlight application.

In this blog post, I’d be sharing the steps to render silverlight applications by leveraging the  content editor web part.

Step1

Go the virtual directory in IIS, corresponding to the SharePoint web application. In my case it is C:inetpubwwwrootwssVirtualDirectories1111

Create a sub-folder by name silverlight_bin under the C:inetpubwwwrootwssVirtualDirectories1111

Copy the silverlight application (xap) from the bindebug directory of silverlight project  to the sub-folder silverlight_bin

Step2

Add the content editor web part to the page

Step3

Click ‘Modify shared web part’ and enter the following html snippet to the web part to the source editor of the content editor web part

<object
  data=”data:application/xsilverlight,”
  type=”application/xsilverlight2b2width=”400height=”300>

<param
  name=”sourcevalue=”/Silverlight_Bin/yoursilverlightapp.xap/>

</object>
Sometimes specifying the object tag in content editor web part may not work properly. If it does not work properly, we need create the object tags and other attributes using javascript.

 Subscribe to my post

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