Wednesday, June 1, 2011

Start "Sharepoint 2010 Administration" Service using Powershell Script

Many a time we are into a situation that we have to deploy the WSP file by using Powershell script and it is required that if you want to deploy a wsp file in Sharepoint than "Sharepoint 2010 Administration" service has to be in Started status.

So if you want to start the "Sharepoint 2010 Administration" Service also through Powershell script than below is the snippet of Powershell script by using which we can start it before deploying the WSP.

Create a text file in notepad and add the below mentioned Script line and save this file as StartAdminService.ps1.

$AdminServiceName = "SPAdminV4"
$snapin="Microsoft.SharePoint.PowerShell"

if (get-pssnapin $snapin -ea "silentlycontinue")
{
    write-host -f Green "PSsnapin $snapin is loaded"
}
if ($(Get-Service $AdminServiceName).Status -eq "Stopped")
{
    $IsAdminServiceWasRunning = $false;
    Start-Service $AdminServiceName
    write-host -f Green "SPAdminV4 Service has been started Successfully."

}
else
{
    write-host -f Green "SPAdminV4 Service is already started."
}

Now drag and drop the text file in the Sharepoint 2010 Management Shell and Press Enter key. It will start the "Sharepoint 2010 Administration" service if it is not started.

Hope it will be a help to you.

Cheers!
Ravish

Programmatically check a Feature is activated on a SiteCollection or Not

Sometime we have a requirement like while deactivating a feature we need to check programmatically weather that Particular feature is deployed to other site collections of the same Web Application or not.
 Below is the code snippet with the help of which we can check it:
    public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
         {
             base.FeatureDeactivating(properties);            
             String URL;
             URL = ((SPSite)properties.Feature.Parent).Url;
             bool isFeatureActiveInOtherSiteCollection = false;
             
             try
             {
                 SPSecurity.RunWithElevatedPrivileges(delegate()
                         {
                             using (SPSite objSite = new SPSite(URL))
                             {
                                 using (SPWeb objWeb = objSite.OpenWeb())
                                 {
                                     SPWebApplication objSPWebApp = objSite.WebApplication;

                                     foreach (SPSite objOtherSite in objSPWebApp.Sites)
                                     {
                                         if (!objOtherSite.Url.Equals(objSite.Url) && objOtherSite.Features[properties.Feature.DefinitionId] != null)
                                         {
                                             isFeatureActiveInOtherSiteCollection = true;
                                             break;
                                         }
                                     }
                                 }
                             }
                         });
             }                    
             catch (Exception ex)
             {
                 throw ex;
             }
         }

Programmatically check a WSP is deployed on a Web Application or not

Sometimes we have a scenario like we have to check that whether a particular wsp (Solution Package) is deployed on a Web application or not.
Suppose we have a feature and on the feature activation we need to add a webpart on some page of a site but that webpart is not packaged in the Feature Deployment Solution Package rather it’s a part of some other wsp package.
So during the activation process we have to know whether the webpart which we are going to add through feature is deployed on the webapplication or not.
Below is the code snippet with the help of which we can check that whether a particular wsp package is deployed on a webapplication or not.
private static bool CheckWSPDeployedStatus(SPSite objSite)
        {
            System.Collections.ObjectModel.Collection<SPWebApplication> objWebApplications = objSite.WebApplication.Farm.Solutions["Sample.wsp"].DeployedWebApplications;
            if (objWebApplications != null && objWebApplications.Count > 0)
            {
                if (objWebApplications.Contains(objSite.WebApplication))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

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