How to add an item to the quick launch in SharePoint

Here is a method to add a node to the quick launch.  You need to pass in the name you want displayed for the link, the Site,  and the path to the page you want the link to open.
This method checks if the link already exists and it won’t add the node if it does.  So it’s safe to run multiple time without jacking up your quick launch.

private void AddNodeToQuickLaunch(string linkName, string SiteToOpen, string pathtoPage)
       {
           try
           {
               using (SPWeb web = SPContext.Current.Site.OpenWeb(SiteToOpen))
               {
                   web.AllowUnsafeUpdates = true;

                   SPNavigationNodeCollection nodes = web.Navigation.QuickLaunch;

                   SPNavigationNode createNode = new SPNavigationNode(linkName, pathtoPage, true);

                   foreach (SPNavigationNode node in nodes)
                   {
                       bool nodeExists = false;
                       if (node.Title.Equals("Lists"))
                       {
                           foreach (SPNavigationNode child in node.Children)
                           {
                               if (child.Title == linkName)
                               {
                                   nodeExists = true;
                               }
                           }

                           if (!nodeExists)
                           {
                               node.Children.Add(createNode, node);
                           }
                       }
                   }
                   web.AllowUnsafeUpdates = false;
               }
           }
           catch (Exception ex)
           {
               throw ex;
           }
       }
[tweetmeme only_single=”false”]
Advertisements

How to create a new site based on a custom site template

Here is a method to create a sub site based on a custom site template.  You need to pass in your new site name and the name of the site template.  It will check the available site templates for the one you specified (so you must deploy the site template first).  If it’s not there an error gets displayed.  I put a label on my web part to display the error _lblErrMsg.  You will need that control (or you can remove it and handle errors whatever way you want.

private bool CreateSubSite(string newSiteName, string ProjectsiteTemplateName)
      {
          try
          {
              SPWeb webSite = SPContext.Current.Web;

              webSite.AllowUnsafeUpdates = true;

              //Get all the site templates
              SPWebTemplateCollection Templates = webSite.GetAvailableWebTemplates(Convert.ToUInt32(LOCALE_ID_ENGLISH));

              //Get the specific project template
              SPWebTemplate siteTemplate = null;

              //Verify the custom site template exists
              if (templateExists(Templates, ProjectsiteTemplateName))
              {
                  siteTemplate = Templates[ProjectsiteTemplateName];
              }
              else
              {
                  _lblErrMsg.Text = "Could not find the custom site template.";
              }

              if (siteTemplate != null)
              {

                  SPWeb newWeb; 
                  newWeb = SPContext.GetContext(HttpContext.Current).Web.Webs.Add(
                      newSiteName.Trim(),
                      newSiteName,
                              "Project Site",
                              LOCALE_ID_ENGLISH, siteTemplate,
                              true, false);

                  //Inherit navigation from parent site
                  newWeb.Navigation.UseShared = true;

                  newWeb.Update();

                  siteCreated = true;

                  webSite.AllowUnsafeUpdates = false;

              }

              webSite.Close();

          }
          catch (Exception ex)
          {
              this._lblErrMsg.Text = ex.Message.ToString();
          }

          return siteCreated;
      }
[tweetmeme only_single=”false”]

How to remove a feature with PowerShell

Here are the PowerShell commands to remove a feature.

Step 1
Uninstall the feature.
Uninstall-SPSolution -identity “<WSP FileName>”
(For ex, Uninstall-SPSolution -identity “Deploy_Service_Requests_Lists.wsp”)

Step 2
Remove the solution.
Remove-SPSolution -identity “<WSP FileName>”
(For ex, Remove-SPSolution -identity “Deploy_Service_Requests_Lists.wsp”)

* Note pay attention to SPSoluion (farm solution) vs SPUserSolution (sandboxed solution). You need what kind of solution you deployed to know which command to use.

Here is the link to install a feature.

[tweetmeme only_single=”false”]

How to check if a project template exists

If you are creating sites based off custom project templates through code you should if the project template exists.  If you don’t and you try then SharePoint will through an error.

Here is a simple method that will return true or false if your project template exists.  You pass in the name of the project template you are looking for.

//Check if a site template already exists
        private static bool templateExists(string title)
        {
            using (SPWeb webSite = SPContext.Current.Web)
            {
                SPWebTemplateCollection collection = webSite.GetAvailableWebTemplates(Convert.ToUInt32(1033));

                foreach (SPWebTemplate list in collection)
                {
                    if (list.Title.ToLower() == title.ToLower())
                    {
                        return true;
                    }
                }
            }
            return false;
        }
[tweetmeme only_single=”false”]

How to deploy a feature through PowerShell

Every time I go to deploy a feature from outside Visual Studio I forget the PowerShell commands.
I found the Corey Roth has a great blog entry about it and I end up going there.

So I decided to finally write up what I do.  After using stsadmin for so long it’s hard to make the adjustment to PowerShell.

Here is the first step to add a Farm Solution.
Add-SPSolution <File Path>\<WSP Filename>
(For ex, Add-SPSolution C:\Users\Administrator\Desktop\Deploy\Deploy_Service_Lists.wsp)

The next step is to install the solution.
Install-SPSolution –Identity <WSP Filename> p  –GACDeployment
(For ex, Install-SPSolution –Identity Deploy_Service_Requests_Lists.wsp  –GACDeployment)

*If you use Add-SPUserSolution it will be sandboxed solution.  Which I’ve done before at a client and I couldn’t find the solution because I used the wrong command.

** Workflows are a little different because they are not scoped at the farm level.  Here is the link to deploy a workflow.

[tweetmeme only_single=”false”]

How to add your own WebPart properties

If you are creating your own part you might want to add a property for the users to set when editing the webpart.

At the top of your web part class add the following code (before any methods).

[FriendlyName("Project Site Template")]
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
public string ProjectsiteTemplateName { get; set; }

This will add a property (in my case called Project Site Template) for the users to set when editing the web part.

This allows the user configure the web part for what you need (instead of hard coding some things).

[tweetmeme only_single=”false”]

How to deploy a workflow through PowerShell

Every time I go to deploy a workflow from outside Visual Studio I forget the PowerShell commands.

So I decided to finally write up what I do.   Here’s what I do.

Step 1 add the solution.
Add-SPSolution –LiteralPath <FILEPATH\WSP FileName> –Site <URL>
(For ex,
Add-SPSolution -LiteralPath C:\Users\Administrator\Desktop\Deploy\Service_Request_Workflow.wsp -Site
http://win-ate30fn6vk5 )

Step 2 install the solution.
Install-SPSolution –Identity <WSP FileName> –Site “<URL>”
(For ex, Install-SPSolution –Identity Service_Request_Workflow.wsp -Site “http://win-ate30fn6vk5&#8221; )

[tweetmeme only_single=”false”]

SharePoint generic handle web part error

If you have web part that has code behind to do something (like add data to a list) and it has an exception during processing you need a way to display that error.
Here is a generic method I use to display the error.
I put this in all my catches.  It will add a new literal control with the error.

        /// <summary>
       /// Clear all child controls and add an error message for display.
       /// </summary>
       /// <param name="ex"></param>
       private void HandleException(Exception ex)
       {
           this._error = true;
           this.Controls.Clear();
           this.Controls.Add(new LiteralControl(ex.Message));
       }
[tweetmeme only_single=”false”]

SharePoint 2013 Forms Based Authentication (FBA)

Here are the instructions for setting up FBA on SharePoint 2013.

Install FBA and Setup SharePoint to use FBA

The site users and roles will be stored in a SQL database, and the web site will use the FBA provider to authenticate the uses through the database.

Create Users/Roles Database

The first step is to create the database using the ASP.net SQL server setup wizard. Install the new database on the database server hosting the other SharePoint databases for this app. The wizard can be accessed from the following command from the run menu.

%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regsql.exe

This wizard will guide you through the creation of the new SQL database.

· A welcome screen will appear. Click Next.
image

· Select “Configure SQL Server for application services” and click Next.
image

· Enter the name of your server and your authentication information.  In this case SQL Server is installed on the same server as SharePoint 2013 and I am logged in as an administrator and have full access to SQL Server, so I choose Windows Authentication. For the database name, I just leave it as <default>, which creates a database called “aspnetdb”. Unless you want a specific name for your FBA database.
image

· A Confirm Your Settings screen will appear. Click Next.

· A “database has been created or modified” screen will appear. Click finish and the wizard will close.

Setup database Permissions

· Now that the database has been created, we’ll have to give SharePoint permissions to read and write to it. We’re going to connect to the database with Windows Authentication, so we’re going to have to give those permissions to the service account that is being used to run SharePoint. First, let’s find out the service account that’s being used to run SharePoint. Open IIS, go to “Application Pools”. Take a look at the “Identity” that is being used to run the SharePoint application pools. On my test VM, it happens to network service that is being used, but it will probably be different on your machine. Make note of the identity used.
image

· Now that we know what account is being used to run SharePoint, we can assign it the appropriate permissions to the membership database we created.  Open up SQL Server Management Studio and log in as an administrator.
image

· Under Security/Logins find the user that SharePoint runs as.  Assuming this is the same database server that SharePoint was installed on, the user should already exist. Right click on the user and click ‘Properties’

.image

· Go to the “User Mapping” Page. Check the “Map” checkbox for the aspnetdb database. With the aspnetdb database selected, check the “db_owner” role membership and click OK. This user should now have full permissions to read and write to the aspnetdb membership database.
image

Setup SharePoint membership provider.

The next thing that has to be done to get forms based authentication working with SharePoint is setting up the membership provider.  A membership provider is an interface from the program to the credential store.  This allows the same program to work against many different methods of storing credentials.

SharePoint is actually divided up into several web applications – Central Administration, the Security Token Service and all of the SharePoint web applications that you create. Each of those web applications needs to know about the membership provider. Most tutorials have you adding the membership provider settings over and over again in each web config (as well as every time you setup a new SharePoint web application).  I prefer to add the membership provider settings directly to the machine.config. By adding it to the machine.config, the configuration is inherited by all of the web.config files on the machine – so you only have to make the changes once, and don’t have to remember to make the changes every time you create a new SharePoint web application.

If you don’t have access to the machine.config, or prefer not to edit it, you will have to make all of these changes to the following web.config files:

· SharePoint Central Administration

· SecurityTokenServiceApplication

· Every SharePoint web application you create that you would like to access via FBA.

· Navigate to “C:\Windows\Microsoft.Net\Framework64\v4.0.30319\Config” and open “machine.config”.

image

  • In the <ConnectionString> section, add the following line:
    <add connectionString=”Server=<SERVER>;Database=aspnetdb;Integrated Security=true” name=”FBADB” />
    !!Be sure to replace the value for Server with the name of your SQL Server.
    image
  • In the <membership><providers> section add the following:
    <add name=”FBAMembershipProvider” type=”System.Web.Security.SqlMembershipProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a” connectionStringName=”FBADB”
    enablePasswordRetrieval=”false” enablePasswordReset=”true”
    requiresQuestionAndAnswer=”false” applicationName=”/”
    requiresUniqueEmail=”true” passwordFormat=”Hashed”
    maxInvalidPasswordAttempts=”5″ minRequiredPasswordLength=”7″
    minRequiredNonalphanumericCharacters=”1″ passwordAttemptWindow=”10″ passwordStrengthRegularExpression=”” />

You can customize the authentication by modifying each of these options.

· In the <roleManager><providers> section add the following:
<add name=”FBARoleProvider” connectionStringName=”FBADB” applicationName=”/” type=”System.Web.Security.SqlRoleProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a” />
image

· Save and close the machine.config file.

  • The SharePoint Web Services configuration overrides the machine.config and clears the entries we created. For that reason, the membership and role providers also need to be added to the SecurityTokenService First we need to find the web.config for the SecurityTokenService.
  • Open up IIS. Under sites, SharePoint Web Services, right click on SecurityTokenServiceApplication and click on Explore. Edit the web.config in the folder that opens.
  • Add the following to the web.config, just before the closing </configuration> tag:

<system.web>
<membership>
<providers>

<add name=”FBAMembershipProvider” type=”System.Web.Security.SqlMembershipProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a” connectionStringName=”FBADB” enablePasswordRetrieval=”false”
enablePasswordReset=”true” requiresQuestionAndAnswer=”false” applicationName=”/” requiresUniqueEmail=”true” passwordFormat=”Hashed” maxInvalidPasswordAttempts=”5″ minRequiredPasswordLength=”7″ minRequiredNonalphanumericCharacters=”1″ passwordAttemptWindow=”10″ passwordStrengthRegularExpression=”” />

</providers>
</membership>
<roleManager>|
<providers>
<add name=”FBARoleProvider” connectionStringName=”FBADB” applicationName=”/” type=”System.Web.Security.SqlRoleProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a” />

</providers>
</roleManager>
</system.web>
image

Now that the membership and role provider have been configured, we can configure SharePoint to use them.

Configure SharePoint to use new membership provider

· Open SharePoint Central Administration -> Application Management -> Manage Web Applications.

· Click the Web Application you want the authentication model.
image

· Click the Authentication Providers button.
image

· Click the Zone you want to change the membership provider.

· Check “Enable Forms Based Authentication (FBA)”. Enter the ASP.Net Membership Provider Name and ASP.NET Role Provider Name that you configured in the web.config. For this example we used “FBAMembershipProvider” and “FBARoleProvider” (Without the quotation marks).Also, for this example we left “Enable Windows Authentication” checked. This allows us to login either via Windows Authentication or Forms Based Authentication (SharePoint will prompt you when you login for which method you’d like to use).  Click OK.
image

Install FBA Pack

Now that an empty membership database has been created, users need to be added. Install the SharePoint 2013 FBA Pack so that all user management can be done in SharePoint.

Deploy FBA Pack
Download and unzip Sharepoint2013FBAPack.X.X.X.zip to the SharePoint server.
Open PowerShell and navigate to the folder the files were unzipped to.
Run the following command:
.\deploy [Site Collection URL]
(e.g. .\deploy http://cbarba-vmsp/)

The FBA Pack will be deployed to SharePoint and activated on the specified site collection. If the site collection url is omitted, you will need to manually activate the ‘Forms Based Authentication Management’ feature in each site collection you wish to use it.

Notes:

Ensure that the SharePoint 2013 Administration service is running prior to running the deployment scripts, or the deployment will fail.

Depending on your PowerShell security settings, it may prevent you from running the deployment scripts because they are not signed. To change the setting to allow unsigned scripts to run, run the following command:

Set-ExecutionPolicy Unrestricted

Adding Users
The configuration and management pages can be opened from the Site Settings page:
image

Select ‘FBA Site Configuration’ to open the configuration page:

Click Enable Roles.
Click Review Membership Requests (so new logins have to be approved).

You can review all the settings here. http://sharepoint2013fba.codeplex.com/documentation?referringTitle=Home

Click the FBA Role Management link.
Add 2 roles
Admin
Users

Click the FBA User Management link to add users.
Add a new user (like fbaadmin) and give them the role of Admin.

Note: If you get an error about the membership provider not setup correctly, verify your connection string in the machine.config.

In Central Admin, click Application Management -> Change Site collection Adminstrators.

In the Secondary site collection administrator enter the admin user you setup earlier (fbaadmin).
This way you can manage the site externally as the admin user (fbaadmin) or internally as a windows user.

Login

· When you go to your website, if you enabled both Windows Authentication and Forms Based Authentication, you’ll be prompted for which method you’d like to use to authenticate.
(If you want to only have forms based authentication, go to the Authentication Providers in Central Admin (Manage Web Applications) and uncheck the Enable Windows Authentication).
image

· You’ll be prompted for a username and password. Enter the username and password that we created earlier.
image

· You’re now logged.
image

Now you’re ready to use Forms Based Authentication on your SharePoint site.

[tweetmeme only_single=”false”]

How to add a content editor web part to a SharePoint page

Here is some code to add a content editor web part to a page. So if you are creating a page in code (like during feature activation), then you put a content editor web part on the page.

Setting the InnerText (contentXMLElement.InnerText = “”;) will set the text in the content editor, incase you want something to be there by default.  User HTML.

using (SPWeb webSite = SPContext.Current.Site.OpenWeb(SiteToOpen))
{
using (SPLimitedWebPartManager mgr = webSite.GetFile(“default.aspx”).GetLimitedWebPartManager(PersonalizationScope.Shared))
{
if (mgr != null)
{
# region AddNewLink

ContentEditorWebPart cewp = new ContentEditorWebPart();
cewp.AllowClose = false;
cewp.AllowEdit = false;
cewp.AllowHide = false;
cewp.AllowMinimize = false;
cewp.ID = “ContentEditorWP”;
cewp.Title = “Content Editor Web Part”;
cewp.ChromeType = PartChromeType.None;

//Add content to the content editor web part
XmlDocument addNewXMLDoc = new XmlDocument();
XmlElement contentXMLElement = addNewXMLDoc.CreateElement(“Root”);
contentXMLElement.InnerText = “”;
cewp.Content = contentXMLElement;
cewp.Content.InnerText = contentXMLElement.InnerText;

// add the web part.
// first argument: web part object
// second argument: zone
// third argument: index (location within the zone)
mgr.AddWebPart(cewp,”left”, 0);

# endregion

}
}
}