Tuesday, May 31, 2011

Custom List forms - Change Newform.aspx or Editform.aspx with Custom Webpart

 

In this article I will show you how to use custom webpart as a replacement for NewForm.aspx or EditForm.aspx.

Sometimes we have a scenario like we have a dropdown box and the data-items coming for this dropdown has to come from a SQL Server database or some other database.

Or we have some business validations to put on the controls present in NewForm.aspx page or Editform.aspx page i.e. in List Forms.

So to tackle these kind of situations we need to customize our List forms.

We can customize the List-forms in two ways.

· Customize the List form through XSLT

· Change the Listforms with custom webpart which is having all your business requirements and a mechanism to add or edit items in List. This custom webpart we can build in Visual Studio through Sharepoint Object Model.

In this article I will tell you how to change the newform.aspx or editform.aspx with custom webpart.

Here I believe that you all know how to build custom webpart for Sharepoint 2007.

When we are click New button to add a new item

image

We are getting NewForm.aspx page. Now to change the list forms with some other webpart we need to edit the page in the same way which we are doing for a normal web part page but the problem here is we do not have Edit Page option under Site Action tab. Now what to do? How to open edit page mode?

The answer is very simple and little bit tricky also.

image

The URL for newform.aspx page will be like this:

http://spdevserver:1003/Lists/Products/NewForm.aspx

just add ?&Toolpaneview=2 above URL. Now your URL becomes like this.

http://spdevserver:1003/Lists/Products/NewForm.aspx?&Toolpaneview=2

Now click on Go button in Internet Explorer and you will see the NewForm.aspx page like this:

image

Just close this webpart and add your new custom webpart here.

So after that whenever you will click on new button for adding a new item you will see your custom webpart instead of default Newform.aspx page.

In the same way we can change editform.aspx page with our custom webpart by adding the ?&Toolpaneview=2 to the url.

Hope this article would be a help to you.

Thank You!

Ravish

Monday, May 30, 2011

Programmatically change the Welcome / Default page of a Sharepoint Publishing Web


Sometimes we have a requirement like on feature activation or deactivation we have to change the Welcome Page(Default Page) of the publishing site.
Below is the code snippet with the help of which we can change the Welcome Page:
public override void FeatureActivated(SPFeatureReceiverPropertiesproperties)
        {
            using (SPSite objSiteProperty = (SPSite)properties.Feature.Parent)
            {
                using (SPWeb objSPWeb = objSiteProperty.OpenWeb())
                {
                    PublishingWeb objPublishingWeb =PublishingWeb.GetPublishingWeb(objSPWeb);
                    SPFile objHomePageFile = objSPWeb.GetFile("Pages/Test.aspx");
                    objPublishingWeb.DefaultPage = objHomePageFile;
                    objPublishingWeb.Update();
                }
            }
        }

And in the same way on Feature Deactivation we can change the Welcome Page again

Handling Access Denied / Authorization Failures


Many a times we are into a situation that we have to handle Authorization Failures. Let’s see how we can handle it by using SPUtility.

·         SPUtility has a method that handles “Access Denied” exceptions and redirects the user to the “Access Denied” page. This method takes Exception object as a parameter. If any kind of Security Exception occured than this methos will handle it as shown below:
        try {
                 //Code
             }
             catch (SecurityException secExptn)
             {
                 SPUtility.HandleAccessDenied(secExptn);
             }

·         SPUtility.Redirect Method can also be used if you want to redirect the user to Sharepoint AccessDenied Page. We can use this method as shown below:

SPUtility.Redirect(SPUtility.AccessDeniedPage,SPRedirectFlags.RelativeToLayoutsPage,httpContext);

·         SPUtility.EnsureSiteAdminAccess(objSPWeb);

This method can be used to determine whether the current user is a site administrator of the specified web or not. If the current user is not the administrator than it will prompt for the administrator credentials and if the user fails to supply the administrator’s credentials than it will open the error page. It will take SPWeb onject as a parameter.

·         SPUtility.SendAccessDeniedHeader(SecExp);

This method is used to send an HTTP 401 (Access Denied) header to the user.
This method will prompt for the new credentials to the user. If the user fails to supply the correct credentials than this methods takes the user to “Access Denied” page.

Thursday, May 26, 2011

Programmatically Add Custom Action ( Link ) in ECB menu of an List Item specific to a Content Type and open Application Page in Modal Dailog Popup in Sharepoint 2010

Many a times we are having a requirement like we have to add a Link in ECB menu of an Item and open an application Page in a modal dialog pop up box of Sharepoint 2010.
In this article we will see how
·         Programmatically we can add a link in ECB and associate it with  a Content Type on Feature Activation.
·         Open an Application Page on the click of the ECB link in Modal Dailog Box of SharePoint.
·         Remove the link on Feature Deactivation.
Below are the One by One Steps:
1.        Open Visual Studio 2010 and create an Empty Sharepoint 2010 Project and add a Feature Reciever on it.
2.       On FeatureActivated method write the below given code.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPContentType objContentType;
            //SPSite objSPSite;
            //SPWeb objSPWeb;
            string sUrl;

            sUrl = ((SPSite)properties.Feature.Parent).Url;

            using (SPSite objSPSite = new SPSite(sUrl))
            {
                using (SPWeb objSPWeb = objSPSite.OpenWeb())
                {
                    objContentType = objSPWeb.ContentTypes["TestContentLink"];

                    SPUserCustomAction action = objSPWeb.UserCustomActions.Add();
                    action.RegistrationType = SPUserCustomActionRegistrationType.ContentType;
                    action.RegistrationId = objContentType.Id.ToString();
                    action.Location = "EditControlBlock";
                    action.Sequence = 450;
                    action.Title = "New Configuration Link";
                    action.Rights = SPBasePermissions.EditListItems;
                    //action.Url = "/_Layouts/TestContentTypeLinkSettings/NewConfigurationWizard.aspx";
                    action.Url = "javascript:OpenPopUpPageWithTitle('{SiteUrl}/_Layouts/TestContentTypeLinkSettings/NewConfigurationWizard.aspx', RefreshOnDialogClose, 600, 400,'My Custom PopUp')";
                    action.Update();

                }
            }

           
        }

This code snippet will register the “New Configuration Link” in the ECB menu of the List Item created with the content type “TestContentLink


1.       Add one application Page in your Project.
action.Url = "javascript:OpenPopUpPageWithTitle('{SiteUrl}/_Layouts/TestContentTypeLinkSettings/NewConfigurationWizard.aspx', RefreshOnDialogClose, 600, 400,'My Custom PopUp')";

This Url will be the URL of the application page which you have created. This JavaScript will open the newly added custom page in the Modal Dailog popup.
2.       On feature deactivation we have to remove this link also. To remove the link add the below mentioned Code in FeatureDeactivating method:
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            string sUrl;

            sUrl = ((SPSite)properties.Feature.Parent).Url;

            using (SPSite objSPSite = new SPSite(sUrl))
            {
                using (SPWeb objSPWeb = objSPSite.OpenWeb())
                {
                    foreach (SPUserCustomAction action in objSPWeb.UserCustomActions)
                    {
                        SPContentType objContentType = objSPWeb.ContentTypes["TestContentLink"];
                        if (action.RegistrationId == objContentType.Id.ToString())
                        //if (action.Name != null && action.Name.Equals("Test"))
                        {
                            action.Delete();
                            objSPWeb.Update();
                            break;
                        }
                    }
                }
            }
        }
We have the Registration ID of the ECB link which we specified on Feature Activated method. Based upon that Registration ID we are removing that custom action.

In this way we can add an Custom Action/Link in ECB menu of the Sharepoint ListItem specific to a Content Type.

 
And on clicking this link it will open the application page created in Modal Dialog Popup of Sharepoint 2010.

Thursday, May 19, 2011

Create Browsable webpart property


Sometimes there are requirements like we need to create a webpart which can be configured from the UI itself.
The solution is to create a webpart property which can be browse through UI so that user of the webpart can change the value accordingly and configure the webpart.
To add the Browsable Properties in the Toolpane of the webpart add the below code snippet  into your webpart code and deploy it.

public class TestWebPartProperty : WebPart
    {
        //WebBrowsable true - The property can be browse in tool pane
        //Category - It will create the property section in the property tool pane
        //personilation - will share the personalized dat to all users.
        //WebDisplay Name - It is the caption or lable of the property to be shown in propert tool pane

        [WebBrowsable(true), Category("Custom Properties"), Personalizable(PersonalizationScope.Shared), WebDisplayName("CheckBox")]
        public bool Prop_CheckBox { get; set; }

        [WebBrowsable(true), Category("Custom Properties"), Personalizable(PersonalizationScope.Shared), WebDisplayName("TextBox")]
        public string Prop_TextBox { get; set; }


        protected override void CreateChildControls()
        {
            Label lblTextBoxValue = new Label ();
            Label lblCheckBoxValue = new Label ();

            lblCheckBoxValue.Text = Prop_CheckBox.ToString();
            lblTextBoxValue.Text = Prop_TextBox.ToString();

            this.Controls.Add(lblCheckBoxValue);
            this.Controls.Add(lblTextBoxValue);           
        }

After installing the webpart click on webpart click on Edit web part.


image

You will see your Custom Properties section in the Tool Pnae of the webpart. Now change the property to configure your webpart.

image

Now click on Ok button and it will show the cudtom properties value in the lables created. 


image

Wednesday, May 18, 2011

Dynamic Tabs using AJAX tab container and add controls and read them dynamically?


In this article we will see that how to create dynamic tabs.
For making dynamic tabs I will use Ajax Tab Container controls. I will create tabs dynamically, will add controls to each of the tabs dynamically and after that we will read the value of each control on some button click.
Step 1: Open visual studio and create a web site.
image
Step 2: Add the refrence to AjaxToolkit.

image
Step 3: Declare Globally TabContainer.
image
Step 4: Next is we need to create tabs dynamically. We can write code for making Dynamic Tabs in Page_load event also but the problem of writing this code in Pageload event is: If we are creating dynamic tabs for a Sharepoint custom Webpart than it will throw error on postback events. But it will work for normal ASPX pages. For this reason I will write it in Page_Init function.
image
image
Step 5: After creating dynamic tabs we will add dynamic controls to it. Here I will create one asp table and then add the controls to it and after adding controls I will add this dynamically generated table to the tabs of the Tab Container control.
The reason why I am adding a table is just for formatting. You can directly add controls to the panel.
image
Step 6: Here I have added one button and created one click event on it. This button click event I will use for reading the dynamically generated controls

image
Here I used one placeholder PC1 also. If we are creating Dynamic tabs for ASP application than no problem but if we are building it for Sharepoint than it is very helpful. If we are not using it than sometimes postback triggers are showing some ajax javascript error.
Now press F5 and see the result.
image
image
Hope this article will be a help to you!
Cheers,
Ravish

Dynamic Type (New Feature in C# 4.0)

Dynamic Type is a part of DLR (Dynamic Language Runtime). This DLR is nothing but some added feature to common language runtime.
For using DLR features we need to add System.Dynamic namespace.

Dynamic type is the feature of C# 4.0. It is a powerful feature of 4.0 framework which allows us to write code in such a way that we can bypass compile time checking. Here bypass doesn’t mean that we can remove the compile time errors, it means if the operation is not valid than we cannot detect the error at compile time. This error will appear only in run time.
Difference between var keyword and dynamic keyword:
The objects defined with dynamic keyword can change its type at runtime. But it is not possible with the var keyword. When we use var keyword it means the determination of the type is delayed but it will happen only in compile time. It means once the type has been specified than we cannot change the type of the object declared using var keyword.
And in the case of dynamic we can change its type in run time and as many times as required.
In the following example we will see how we can use dynamic objects:
static void Main(string[] args)
        {
            dynamic dynamicVariable;
            var oMyClass = new MyClass();
            dynamicVariable = oMyClass.DisplayGreeting();
            Console.WriteLine(dynamicVariable+ "\n\nand the type of dynamic variable is: "+ dynamicVariable.GetType());

            dynamicVariable = oMyClass.DisplayInteger();
            Console.WriteLine("\n" + dynamicVariable + "\n\nand the type of dynamic variable is: " + dynamicVariable.GetType());
            Console.Read();
        }

        class MyClass
        {
            private string sName = "Jack";
            private string sGreeting = "Good Morning";
            public string DisplayGreeting()
            {
                return (sGreeting + sName);
            }
            public int DisplayInteger()
            {
                return 5;
            }
        }

Here in this example we have MyClass containing two functions ‘DisplayGreeting’ and ‘DisplayInteger’.  Both functions are returing different values.
In our main function we have declared a dynamic variable ‘dynamicVariable’.
dynamicVariable = oMyClass.DisplayGreeting();
            Console.WriteLine(dynamicVariable+ "\n\nand the type of dynamic variable is: "+ dynamicVariable.GetType());

Here in the above line we are assigning string value to it and printing it in console, value as well as its type.
In the below mentioned line line we are assigning string value to it and printing it in console, value as well as its type.
            dynamicVariable = oMyClass.DisplayInteger();
            Console.WriteLine("\n" + dynamicVariable + "\n\nand the type of dynamic variable is: " + dynamicVariable.GetType());


When we are compiling it than we are getting the output as:
clip_image002
This is all about Dynamic type.

Thank You.
Ravish

Tuesday, May 17, 2011

Introduction to SharePoint Object Model

 
There are several namespaces(around 50) that house the SharePoint object model. Out of these 50 namespaces we are using only 16 namespaces, rest of the namespaces are reserved for Microsoft internal use.
1.     Document Library
clip_image002
Document libraries are a special type of list designed to store documents.To access a document library through object model we need to use Microsoft.Sharepoint namespace. To use this namespace in ASP.net we need to add a reference of Microsoft.Sharepoint.dll. This dll we can find from the below mentioned path:
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI
Let’s take each and every class in this namespace:
·         SPDocumentLibrary Class:-
This class represents a document library in Windows Sharepoint Services.
In C# code: SPDocumentLibrary obj = (DocumentLibrary)oList
oList is an object for list. The above code will cast the list object into Document Library.
·         SPPictureLibrary Class:-
This class represents a picture library in Windows Sharepoint Services.  Both classes are used in the sane manner. The only difference is: As the name indicates SPDocumentLibrary is used for Document Library and SPPictureLibrary is used for Picture Library.
2.     Features:-
clip_image004
For using the features through Sharepoint object model we need Microsoft.Sharepoint dll and you can get the dll from the above mentioned path.
·         SPFeatureDefinition Class:- Contains the base definition of an SPFeature, including its name, identifier, scope, and version
·         SPFeatureScope Class :- Specifies the scope to which the feature applies.
·         SPElementDefinition Class:-  Serves as the base class for implementing element types within Windows SharePoint Services
·         SPFeature Class:- Represents the state of a feature at its corresponding scope
·         SPFeatureProperty Class:- Represents a single Feature property.
Code Example:
SPSite oSpSite = new SPSite("http://YourServer");
SPFeatureCollection oSPfeatureCollection = oSpSite.Features;

foreach (SPFeature oSPFeature in oSPfeatureCollection)
{
    SPFeatureDefinition featureDefinition = oSPFeature.Definition;
    SPElementDefinitionCollection elementDefinitionCollection =
featureDefinition.GetElementDefinitions(System.Globalization.CultureInfo.InvariantCulture);

    foreach (SPElementDefinition elementDefinition in elementDefinitionCollection)
    {
        Console.WriteLine(elementDefinition.Id);
    }
}


3.
clip_image006
For using meetings through object model we need to add Microsoft.Sharepoint dll as mentioned above.  The classes under this category are explained as below:
SPMeeting Class:- Provides methods and properties that can be used to work with a Meeting Workspace. Suppose if you want to create a meeting workspace through object model then we need to use this class. There are different kind of meeting template that can be handled like Basic meeting, Decision Meeting, Multiple meeting etc.
MtgUtility:- Initialize a new instance of the MtgUtility class. To access the MtgUtility service and its methods, set a Web reference to http://Server_Name/[sites/][Site_Name/]_vti_bin/xxx.asmx.
Microsoft.SharePoint.Meetings.MtgUtility – System.Object
4.
clip_image008
Sites objects are used to access the sharepoint site, The classes under this category of Sharepoint Object model are explained as below:
SPSite:- . Represents a collection of sites in a Web application, including a top-level Web site and all its subsites. Each SPSite object, or site collection, is represented within an SPSiteCollection object that consists of the collection of all site collections in the Web application.
SPWeb:-  Represents a Windows SharePoint Services Web site.
CODE Example:
using(SPSite oSite = new SPSite("http://Server_Name"))
{
    using(SPWeb oWebsite = oSite.OpenWeb("Website_URL"))
    {
        using(SPWeb oWebsiteRoot = oSite.RootWeb)
        {
           ...//Your Code
        }
    }
}


5.   
clip_image010


Provides administrative types and members for managing a Windows SharePoint Services deployment. There are so many classes, delegates, interface under this namespace but only few classes I am going to explain.
SPSolution :- Represents a solution on a farm.
Namespace: Microsoft.SharePoint.Administration
Assembly: Microsoft.SharePoint (in microsoft.sharepoint.dll)

SPFeatureReceiver:-
Base abstract class that can be overridden to trap the activation, deactivation, installation, or uninstallation of a Feature.
Namespace: Microsoft.SharePoint
Assembly: Microsoft.SharePoint
Use the SPFeatureReceiver class to trap events that are raised after the Feature installation, uninstallation, activation, or deactivation action has been performed.
It is not possible to cancel an installation or uninstallation through Feature events.
SPSolutionCollector:-
Represents a collection of SPSolution objects.
Namespace: Microsoft.SharePoint.Administration
Assembly: Microsoft.SharePoint

6.
clip_image012
SPList object represent a List, SPListItem represent a List Item in the List and SPListItemCollection object represent a full item collection in the SPLIST.
Code Example:-
SPList mylist_Name = myweb.Lists["Category"];
            SPListItemCollection itmcln = mylist_Name.Items;
            foreach (SPListItem itm in itmcln)
            {
                if (itm["ItemCategory"] != null)
                {                   
                   ddlCategory.Items.Add(itm["ItemCategory"].ToString());
                }
            }
7.
clip_image014
8.
clip_image016
This is all about Sharepoint Object Model.
Hope it will be a help to you!