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.