Pages

Search This Blog

Tuesday, January 17, 2012

Open PDF files directly in browser SharePoint 2010

Here is how you can tell SharePoint 2010 site to open the PDF files in the browser instead of prompting the user to save or open the PDF. This will be a great option to the most of end users. This needs simple Powershell scripting run on the server. Below is the code we should use:



# <# 
# .DESCRIPTION 
#  This script adds new MIME type to "AllowedInlineDownloadedMimeTypes" property list of defined SharePoint 2010 Web Application.
#
#  Script prompts you for MIME type and Web Application URL.
#
#  Code shall run in context of Farm Administrators group member.
# 

If ( (Get-PSSnapin -Name "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null ) {
    Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}
Get-SPWebApplication
$WebApp = Get-SPWebApplication $(Read-Host "Enter Web Application URL")
Write-Host "Mime Type Examples:""application/pdf, text/html, text/xml"


If ($WebApp.AllowedInlineDownloadedMimeTypes -notcontains ($MimeType = Read-Host "Enter a required mime type"))
{
  Write-Host -ForegroundColor White "Adding" $MimeType "MIME Type to defined Web Application"$WebApp.url
  $WebApp.AllowedInlineDownloadedMimeTypes.Add($MimeType)
  $WebApp.Update()
  Write-Host -ForegroundColor Green "The" $MimeType "MIME type has been successfully added."
} Else {
  Write-Host -ForegroundColor Red "The" $MimeType "MIME type has already been added."
}

Monday, January 16, 2012

How to change the default home page or Set Welcome Page of a SharePoint site using PowerShell Script - SharePoint 2010

By default a SharePoint 2010 publishing site uses default.aspx as its welcome page.
There are so many conditions where we use our custom web part page as the default page for our publishing site in place of general default.aspx. The best example for this is an application dashboard as the default page.

Below are four ways to set another page as your home page: (all four work for both 2007 and 2010)

1. From Site Settings (If the publishing features are enabled)
2. From SharePoint Designer
3. From code / API
4. From PowerShell

1. If the publishing features are enabled for a site then:
Go to Site Actions -> Site Settings -> Welcome Page
In SharePoint 2007

In SharePoint 2010

2. From SharePoint Designer:
Right-click the new page and click "Set as Home Page".
(For SharePoint 2007 this only appears to work from SharePoint Designer if the file is in the root of the site. I.e. the same place as default.aspx.)

3. From code / API:

using (SPSite oSiteCollection = new SPSite("http://sharepoint2010:2400"))
            {
                SPWeb oWebsite = oSiteCollection.OpenWeb();
                SPFolder oFolder = oWebsite.RootFolder;
                oFolder.WelcomePage = "SiteAssets/BecomeFan.aspx";
                oFolder.Update();
                oWebsite.Dispose();
            }

4. From PowerShell:
In SharePoint 2010, Create a powershell script file e.g. SetWelcomePage.ps1, with the following script:

Add-PsSnapin Microsoft.SharePoint.PowerShell
$assignment=Start-SPAssignment
$web=Get-SPWeb -Identity "http://sharepoint2010:2400" -AssignmentCollection $assignment
$rootFolder=$web.RootFolder
$rootFolder.WelcomePage="SiteAssets/BecomeFan.aspx"
$rootFolder.Update()
Stop-SPAssignment $assignment
$web.Update()
$web.Dispose()
Write-Host 'Welcome Page Set Successfully…'
Write-Host 'Press any key to exit…'
$x=$Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
$Host.SetShouldExit(1)

After creating the script file, just run that file by right click and Run with PowerShell:


Now, navigate back to a site and see that the homepage is now set to the given page.


Wednesday, January 11, 2012

SharePoint 2010 Database Server Memory Requirements



The memory required for SharePoint Server 2010 is directly related to the size of the content databases that you are hosting on a server that is running SQL Server.

As you add service applications and features, your requirements are likely to increase. The following table gives guidelines for the amount of memory we recommend.



Combined size of content databases
RAM recommended

Minimum for small production deployments

8 GB

Minimum for medium production deployments

16 GB

Recommendation for up to 2 terabytes

32 GB

Recommendation for the range of 2 terabytes to a maximum of 5 terabytes

64 GB


Microsoft definitions of small and medium deployments are those described in the "Reference Architectures" section of the article Capacity management and sizing for SharePoint Server 2010.
http://technet.microsoft.com/en-us/library/cc261700.aspx


These values are higher than those recommended as the minimum values for SQL Server because of the distribution of data required for a SharePoint Server 2010 environment. For more information about SQL Server system requirements, see Hardware and Software Requirements for Installing SQL Server 2008 (http://go.microsoft.com/fwlink/?LinkId=129377).

Other factors that may influence the memory required include the following:

  • The use of SQL Server mirroring.
  • The frequent use of files larger than 15 megabytes (MB).
For more information please download the whitepaper from Microsoft site :

SharePoint 2010 Storage options


Design storage architecture based on capacity and I/O requirements


The storage architecture and disk types that you select for your environment can affect system performance.
In this section:

  1. Choose a storage architecture
  2. Choose disk types
  3. Choose RAID types
Choose a storage architecture

Direct Attached Storage (DAS),
Storage Area Network (SAN),
and Network Attached Storage (NAS) storage architectures are supported with SharePoint Server 2010, although NAS is only supported for use with content databases that are configured to use remote BLOB storage. Your choice depends on factors within your business solution and your existing infrastructure.

Any storage architecture must support your availability needs and perform adequately in IOPS and latency. To be supported, the system must consistently return the first byte of data within 20 milliseconds (ms).

Direct Attached Storage (DAS)

DAS is a digital storage system that is directly attached to a server or workstation, without a storage network in between. DAS physical disk types include Serial Attached SCSI (SAS) and Serial Attached ATA (SATA).
In general, Microsoft recommend that you choose a DAS architecture when a shared storage platform cannot guarantee a response time of 20 ms and sufficient capacity for average and peak IOPs.

Storage Area Network (SAN)

SAN is an architecture to attach remote computer storage devices (such as disk arrays and tape libraries) to servers in such a way that the devices appear as locally attached to the operating system (for example, block storage).
In general, we recommend that you choose a SAN when the benefits of shared storage are important to your organization.
The benefits of shared storage include the following:
  • Easier to reallocate disk storage between servers.
  • Can serve multiple servers.
  • No limitations on the number of disks that can be accessed.

Network Attached Storage (NAS)

A NAS unit is a self-contained computer that is connected to a network. Its sole purpose is to supply file-based data storage services to other devices on the network. The operating system and other software on the NAS unit provide the functionality of data storage, file systems, and access to files, and the management of these functionalities (for example, file storage).
NAS is only supported for use with content databases that are configured to use remote BLOB storage. Any network storage architecture must respond to a ping within 1 ms and must return the first byte of data within 20 ms. This restriction does not apply to the local SQL Server FILESTREAM provider, because it only stores data locally on the same server.

For more information download paper from :



SharePoint Server 2010 Capacity Planning

I found a very useful and detailed document on SharePoint 2010 capacity planning today when I was searching for the best practices on server architecture in 2010.
This document covers almost all the concepts of capacity planning in SharePoint 2010, which primarily includes :
  1. Capacity management and sizing for SharePoint Server 2010
  2. Capacity planning for SharePoint Server 2010
  3. Performance testing for SharePoint Server 2010
  4. Monitoring and maintaining SharePoint Server 2010
  5. Software boundaries and limits
  6. Performance and capacity technical case studies
  7. Estimate performance and capacity requirements for Access Services in SharePoint Server 2010
  8. Estimate performance and capacity requirements for Excel Services in SharePoint Server 2010
  9. Estimate performance and capacity requirements for PerformancePoint Services
  10. Capacity requirements for Web Analytics Shared Service in SharePoint Server 2010
  11. Estimate performance and capacity requirements for Web Content Management in SharePoint Server 2010
  12. Estimate performance and capacity planning for workflow in SharePoint Server 2010
  13. Storage and SQL Server capacity planning and configuration (SharePoint Server 2010)


You can download this document from :
http://www.microsoft.com/download/en/details.aspx?id=21307
OR
http://min.us/mgRurPX8d



Download WSP Solution from SharePoint


Once a solution has been added to SharePoint, then there's no way to download it. Using the SharePoint object model we can easily download a WSP using the 'SaveAs' method. 
The C# code below illustrates how to download all of the solutions in the farm with just a few lines.

private void DownLoadAllSolutions()
       {
            SPSolutionCollection wspSolutions = SPFarm.Local.Solutions;
            foreach (SPSolution solution in wspSolutions)
            {
SPPersistedFile wspFile = solution.SolutionFile;
DownLoadWSP(wspFile);
            }
        }
        private void DownLoadWSP(SPPersistedFile wspFile)
{
    if (wspFile != null)
    {
string wspFileName = Path.Combine(@"c:\temp",wspFile.Name);
                if(File.Exists(wspFileName))
{
File.Delete(wspFileName);
}
wspFile.SaveAs(wspFileName);
}
}

Tuesday, January 10, 2012

Writing Errors to Sharepoint Logs

Sharepoint 2010 has provided us with an API for writing to the default ULS log file in which Sharepoint writes its logs. To do this you can make use of the SPDiagnosticsService which is available in
Microsoft.SharePoint.Administration namespace.



try
   {
    //execute your code
   }
   catch (Exception ex)
   {
    SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("YourCustomKey", TraceSeverity.Medium, EventSeverity.Error), TraceSeverity.Monitorable, ex.Message, ex.StackTrace);
    }
}

Sharepoint Adding a Mapped URL programmatically

In Sharepoint 2010, you can retrieve the URL of some common Application Pages as AccessDenied.aspx, Error.aspx, Login.aspx, Signout.aspx etc. This has been done for the purpose of enabling the user to assign custom Application page instead of the default one. One way to do this is to add a Mapping attribute in the web.config file. But in Sharepoint 2010, there is a simpler way to do this.
We can make use of GetMappedPage and UpdateMappedPage  methods. This can be done by creating a Web scoped Feature and write your code in Feature Activated and Deactivated as:



public override void FeatureActivated(SPFeatureReceiverProperties properties)
            {
                SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
                try
                {
                    if (webApp != null)
                    {
                        if (!webApp.UpdateMappedPage(SPWebApplication.SPCustomPage.AccessDenied,
                            "/_layouts/YourCustomAppPagesFolder/CustomAccessDenied.aspx"))
                        {
                            throw new ApplicationException("Error adding mapped page.");
                        }

                        // File Not Found page is set differently.
                        webApp.FileNotFoundPage = "/_layouts/1033/YourCustomFolder/YourFileNorFoundPage.htm";
                        webApp.Update(true);
                    }
                }
                catch (Exception Ex)
                {

                }
            }


            public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
            {
                SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
                try
                {
                if (webApp != null)
                {
                    //you have to set the property back to null for setting it to default
                    webApp.UpdateMappedPage(SPWebApplication.SPCustomPage.AccessDenied, null);

                    //File not found is handled differently
                    webApp.FileNotFoundPage = null;
                }
                }
                catch (Exception Ex)
                {
                }
            }
        }

Monday, January 9, 2012

Sharepoint Access Denied Page

Sometimes in your web part pages you may want to show the same "Access Denied" screen to the user that SharePoint provides by default when user has no access to any resource or page.


This can be easily achieved by making use of SPUtility Class of sharepoint as:


            try
            {
               //your custom code
               SPUtility.HandleAccessDenied(new Exception("not authorized"));
            }
            catch (Exception Ex)
            {
            }



Wednesday, January 4, 2012

MOSS Workflow Concepts

In this post, I will be covering MOSS workflows concepts, starting from What are workflows, categories, people involved, WWF. MOSS Workflows can be created using the following approaches:
-         Standard Workflow
-         SharePoint Designer Workflow
-         InfoPath Workflow
-         Custom Workflow
•          A workflow is a set of activities
•          Each activity is actually a class
–        It can be reused in multiple workflows
•          Activities can be provided by:
–        Microsoft
–        Anybody else
Core Categories of Workflow
•          Human Centric Workflow
•                    Participants are people
•                    Flexible control flow
•                    Ad-hoc
•          System Centric Workflow
•                      Participants are Services
•                      Apps Prescriptive control flow
•                      Transactional
Defining Windows Workflow Foundation
•          Windows Workflow Foundation (WF) is a framework for building workflow-based Windows applications
–        It’s targeted at developers, not information workers or business analysts
•          WF is now a standard part of Windows
–        The goal is to provide a common workflow framework for Windows applications
–        Including both system and human workflow
The Role of InfoPath Forms Services
85% of workflows use forms as the primary end user UI
Forms are used for:
•          Gathering Information
•          Configuring workflows
–        Out-of-the box workflow templates use InfoPath designed browser based forms
–        Add your own workflow templates with your own forms.
•          Starting Workflows
•          Completing tasks
•          Users are everyone using, interacting or designing workflows
The Role of SharePoint Designer
Workflow Design made easy
•          Customize SharePoint Sites
•          Design Page Layouts for Web Content Management [MOSS only]
•          Design and Create Workflows
•          Build Workflow enabled Composite SharePoint Apps
•          Users are Business IT and DEV
The Role of Visual Studio
Leverage Windows Workflow Foundation (WF)
•          Design complex workflows
–        Use the WF SDK and it’s graphical workflow designer
•          Develop and deploy your own workflow templates
–        Extend the available out-of-the-box workflows available to your SharePoint users
•          Extend WF with your own custom activities
–        Develop custom activities reusable in SharePoint Designer
•          Users are Developers
An Example WSS Workflow
I would be adding the links to the presentations & Workshops for 4 different approaches to create MOSS workflows in my next post.

Cheers!

Tuesday, January 3, 2012

Custom TreeView Column for SharePoint


SharePoint doesn’t provide any column type to represent the relational data in tree view format. E.g. Country > State > City is the best example for such data structures. This open source package provides the capability to creating tree view column within SharePoint environment.
If you are also looking for any data to represent in tree format in SharePoint 2010 then this control for you provided you are storing data in one list with parent lookup reference of same list.

http://code.google.com/p/sharepoint-treeview-column/

Use SQL Server Alias to Create SharePoint Farm


SharePoint depends on its connections to one or more SQL Server instances for the overwhelming majority of its content and configuration data. 
The loss of a SQL Server can spell disaster for SharePoint, particularly if the lost SQL Server can’t be restored and a new SQL Server instance (with a new name) must be used. The use of SQL Server names and/or addresses in difficult-to-alter SharePoint database connection strings is what makes this situation problematic.
You can get some protection and peace-of-mind for this type of scenario by utilizing SQL Server aliases on each of your SharePoint servers. Aliases act as an abstraction layer between your SharePoint servers and your SQL servers. So, instead of this:

Instead of SharePoint => SQL Server you end up with this: SharePoint => Alias => SQL Server
In this scenario, pointing your SharePoint member servers to a different back-end SQL Server is as simple as changing one or more SQL aliases. In effect, your SharePoint farm becomes decoupled from the SQL Server(s) it uses.
SQL Server aliases can be created and maintained easily using the SQL Client Network Utility (cliconfg.exe) or the SQL Server Configuration Manager which is installed with the SQL Client Tools.

How to create SQL Server Alias

  1. In SQL Server Configuration Manager, expand SQL Native Client Configuration, right-click Aliases, and then click New Alias.
  2. Press F1, or click Help.
  3. The New Alias (Alias Tab) topic describes the New Alias dialog box, and contains links to valid connection strings for each type of protocol.

SharePoint Performance Tip : BLOB Caching with MAX-AGE Attribute


When configuring BLOB caching for MOSS 2007 and SharePoint 2010, it is possible to specify an optional max-age attribute in the web.config element. This attribute determines the amount of time, in seconds, that SharePoint clients should cache resources locally (typically in the browser’s temporary files area) that are served from a WFE’s BLOB cache. For example, the following web.config element instructs clients to locally store .GIF and .JPG images that are retrieved from the WFE for 43,200 seconds (12 hours) before re-requesting them.
<BlobCache location="C:\blobCache" path="\.(gif|jpg)$" maxSize="10" max-age="43200" enabled="true" />
Resources that are served from a WFE’s BLOB cache when the max-age attribute is used are only re-requested after the max-age interval has elapsed or the browser’s local cache has been cleared. This reduction in client requests being made can save your WFE servers quite a bit of processing at the same time that the end-user experience is improved.
Be warned, though: if BLOB cache resources change on the server before the max-age interval has elapsed, clients that are caching those resources locally won’t see the changes. In order for clients to see the changes before the max-age interval has elapsed, a browser cache flush is necessary.

Thursday, December 29, 2011

SharePoint - Programmatically creating comments of a blog post in blog site

Last week, one guy faced a problem when he was trying to create "Blog Post Comments" programmatically. He was not able to increase the Comments counts (below blog post).

I have done some R&D on that and found that any blog site in SharePoint there are two main lists: 
1. Posts and 2. Comments 

We need to update the Comments list's "Post Title" column with the Posts list's "Title" column lookup. This will automatically update the comments count.

Note: Comments lists's "Post Title" field is hidden field.

I am providing the sample code for the same:

//Update Blog Post Comments Programatically
using (SPSite site = new SPSite("http://br-pc-275:3670/blog/"))
{
    using (SPWeb web = site.OpenWeb())
    {
        SPList objPostList = web.Lists["Posts"];
        SPListItem objItem = objPostList.GetItemById(1);
        SPList objCommentsList = web.Lists["Comments"];
        SPListItem objNewComment = objCommentsList.Items.Add();
        objNewComment["Title"] = "New Comment 1";
        //Id of blogPost + ";#" + Title of blogPost
        objNewComment["Post Title"] = "1" + ";#" + Convert.ToString(objItem["Title"]);
        objNewComment.Update();
    }
}

Thanks