Wednesday, 29 January 2014

How to use Status Bar in SharePoint 2010?

How to use Status Bar in SharePoint 2010?


In SharePoint 2010, Status bar is used to display information/warnings without disturbing user with Javascript alerts. Please don't think it is Browser's Status bar. It's a special information bar which displays below ribbon/top bar when invoked. No Server side code or manual setup required to enable status bar. The required functions are bundled in SP.UI.Status class that defined in SP.Js/SP.Debug.Js and it's included in SharePoint master page. So no need to include Js manualy to use Status bar.

Well, Javascripts alerts are not helpful to display HTML content, images, links. Where Status bar accepts HTML content and can be invoked just with Javascript.

SP.UI.Status Functions
The SP.UI.Status class has 6 functions. They are
  1. SP.UI.Status.addStatus(strMessageHeading, strHTMLContent, boolAtBegining) This function used to display specified content in Status bar. The parameters are self explanatory. boolAtBegining parameter specifies whether this content should be shown at First(just like to give priority) and it's useful when more than one status messages invoked.
  2. SP.UI.Status.appendStatus(strStatusID, strHTMLContent) This function appends HTML content with an existing status bar content.
  3. SP.UI.Status.updateStatus(strStatusID, strHTMLContent) This function updates/replaces existing HTML content with given HTML content.
  4. SP.UI.Status.setStatusPriColor(strStatusID, strColor) This function sets/changes the color of status bar. Only four colors[red, yellow, green, blue] are allowed which specifies the priority. Red - High Priority, yellow, green, blue - Low Priority. When two colors applied on same status bar then High priority color will be considered by SharePoint.
  5. SP.UI.Status.removeStatus(strStatusID) This function removes the specific Status bar.
  6. SP.UI.Status.removeAllStatus(boolHideStatus) This function removes all Messages. If the boolHideStatus passed as true then it'll hide all status bar with messages. Otherwise it'll hide only Status Message but a thin status bar will remains in place.
How to add code?
Follow the steps to add Content Editor Webpart and add HTML/Javascript Code.
  1. Site Actions -> Edit Page (or Edit page Icon on top bar)
  2. Click Editing Tools(Tab) -> Insert (Tab) -> Webpart
  3. Select Media and Content (Section) -> Content Editor.
  4. Select Content Editor Webpart (Black triangle on top right of the webpart)-> Edit Webpart.
  5. Editing Tools (Tab) -> Format Text -> HTML -> Edit HTML Source.
Edit HTML Content of Content Editor WebPart
Demo Code
 <Script type="text/javascript">
var
 strStatusID;function showInfo()
{
  strStatusID = SP.UI.Status.addStatus(
"Information : ""<img src='/_Layouts/Images/STS_ListItem_43216.gif' align='absmiddle'> <font color='#AA0000'>Registration process <i>completed</i>.</font>"true);
  SP.UI.Status.setStatusPriColor(strStatusID, 
"yellow");
}

function
 appendInfo()
{
  SP.UI.Status.appendStatus(strStatusID, 
" Next : "" <b>You can <a href='Login.aspx'>Login Now</a>"false);
  SP.UI.Status.setStatusPriColor(strStatusID, 
"blue");
}
function updateInfo()
{
  SP.UI.Status.updateStatus(strStatusID, 
"Status Update: This content updated with " + strStatusID + " using updateStatus");
  SP.UI.Status.setStatusPriColor(strStatusID, 
"green");
}
function updateInfoRed()
{
  SP.UI.Status.setStatusPriColor(strStatusID, 
"red");
}
function removeInfo()
{
  SP.UI.Status.removeStatus(strStatusID);
}
function removeAllInfos()
{
  SP.UI.Status.removeAllStatus(
true);
}
</Script>

<
div class="ms-toolpanefooter">
  <
input type="button" onclick="Javascript:showInfo();" value="Show Info" class="UserButton" /> 
  <
input type="button" onclick="Javascript:appendInfo()" value="Append Info" class="UserButton" />   <input type="button" onclick="Javascript:updateInfo()"value="Update Info" class="UserButton" /> 
  <
input type="button" onClick="Javascript:updateInfoRed()" value="Make Red" class="UserButton" />   <input type="button" onClick="Javascript:removeInfo()" value="Remove Info" class="UserButton"/>
  
<input type="button" onClick="Javascript:removeAllInfos()" value="Remove All Infos" class="UserButton"/>
</
div>
Add Status
Append Status
Update Status
Change Color of Status Bar
Remove Status


Status bar is used at client side(browser) to display message. If you want to fetch data from status bar then use a hidden variable and assign same value which u pass to status bar via Java Script.
If you want to pass data from Server side to client side then

Add the below function in Javascript.
function showInfo(strMessage)
{
strStatusID = SP.UI.Status.addStatus(strMessage, true);
SP.UI.Status.setStatusPriColor(strStatusID, "yellow");
}
Add a label "lblScripter"
Then in Server Side Code add
lblScripter.Text = "<Script language='javascript;>showInfo('" + strYourMessage + "');</script>";
This will invoke the Javascript and show the statusbar. 

How to Hide Top Bar, Ribbon, Quick Launch in SharePoint 2010?

How to Hide Top Bar, Ribbon, Quick Launch in SharePoint 2010?

Top Bar, Ribbon, Quick Launch are come up with Application Pages by default. If you want to open the page in Dialog Framework then those elements will take more space and make the layout cluttered. You can remove these elements by creating new page layout which is cumbersome/time consuming.
One way to hide these controls is by passing a Parameter with the URL. [ ?IsDlg=1 ] SharePoint will hide these elements when It gets IsDlg Parameter on URL.
But every time we can't pass these parameters. Then how to get rid of these elements?
Simple Just add the below css Code in Application Page under PlaceHolderMain section.
<style type="text/css">
    #s4-ribbonrow.ms-cui-topBar2.s4-notdlg.s4-pr s4-ribbonrowhidetitle.s4-notdlg noindex#ms-cui-ribbonTopBars#s4-titlerow#s4-pr s4-notdlg s4-titlerowhidetitle#s4-leftpanel-content {display:none !important;}
    .s4-ca{margin-left:0px !importantmargin-right:0px !important;}
</style>
This will hide the elements and only the content will be shown.
Note : If you use this code in SharePoint Site Pages with Content Editor Webpart then you can't check in the page since the toolbar goes hidden.
If you still want to use this code on Site Pages then add Content Editor Webpart and paste the above code. When you want to make other changes then open the page in browser with parameters [ ?Contents=1 ] which opens the page in WebPart maintenance mode. Remove the content editor webpart and re-open the page. Make the changes and add content editor webpart at last along the CSS Code. To check in the page use Site Pages Library.

How to use Notifications in SharePoint 2010?

How to use Notifications in SharePoint 2010?


In SharePoint 2010, Notifications is another way to display information/warnings without distracting user. It'll be shown in top right below Topbar and Ribbon. Just like Status bar, No Server side code or manual setup required to use Notifications. The required functions are bundled in SP.UI.Notify class that defined in SP.Js/SP.Debug.Js and it's included in SharePoint master page. So no manual include of Js is required.

Well, Status bar is used to display content and to hide developer has to invvoke RemoveStatus or RemoveStatusAll Method, whereas Notifications by default getting hide after few seconds. It's possible to make notifications Sticky(stay until closed by code).

SP.UI.Status Notify
The SP.UI.Notify class has 2 functions. They are
  1. SP.UI.Notify.addNotification(strHTMLContent, boolIsSticky) This function used to display specified content in Notification area. The parameters are self explanatory. boolIsSticky parameter specifies whether this content should be shown as sticky(true) or hide after few seconds(false). It's possible to show multiple Notifications at a time and they getting aligned themselves.
  2. SP.UI.Notify.removeNotification(strNotifyID) This function hides the Notification that passed as parameter.
Sample Code
<
Script type="text/javascript">
var
 strNotificationID, strStickyNotificationID;function showNofication()
{
  strNotificationID = SP.UI.Notify.addNotification(
"Quick Info : <font color='#AA0000'>Registration in Progress..</font> <img src='/_Layouts/Images/kpiprogressbar.gif' align='absmiddle'> "false);
  strStickyNotificationID = SP.UI.Notify.addNotification(
"Sticky Notes : <font color='#AA0000'>Welcome to My World.</font> <img src='/_Layouts/Images/lg_ICPINNED.gif' align='absmiddle'> "true);
}
function removeNofication()
{
  
if (strStickyNotificationID != null)
    SP.UI.Notify.removeNotification(strStickyNotificationID);
}
</Script>

<
div class="ms-toolpanefooter">
  <
input type="button" onclick="Javascript:showNofication();" value="Show Nofitication" class="UserButton" />
  
<input type="button" onclick="Javascript:removeNofication()" value="Remove Nofitication" class="UserButton" /> </div>
Notifications

How to set Favicon for SharePoint 2010 site?

How to set Favicon for SharePoint 2010 site?


What is Favicon?
Sometimes we come across some websites which shows their logo instead of explorer logo in Address bar. A typical example is Google, login to google with IE and watch address bar. You can see google logo then the URL. This icon is stored in the PC when we add the sites as bookmarks. When you open bookmarks menu the site name will show with the icon.
Favicon Preview

How to create Favicon?
It's very easy to create favicon. All you need is the company logo or image(in JPG/PNG/GIF format) which you want to create based on and internet connection. Open browser and enterhttp://tools.dynamicdrive.com/favicon/ . Then click Choose File Button and select your image. Click Create Icon Button. Now the site will create favicon based on image given and it's ready to download. Download and save it in your PC.

How to set Favicon to the SharePoint 2010 site?
SharePoint 2010 comes with a orange Favicon and it's present in SharePoint Root Folder\Template\Images [eg. C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\IMAGES\]. Open this folder and search for favicon.ico and rename the file to FaviconBackup.ico. Now copy your favicon to this folder and make sure it's named as "favicon.ico". Now restart IIS(open Command Prompt -> IISReset), clear browser cache/temproary internet files. Close the browser and reopen then browse the SharePoint site.

If mulitple sites are hosted in same farm and need to set different favicons for different sites then we have to update Master Page Code. Open the site with SharePoint Designer 2010 and select Master pages -> v4.master. The default.master is still present in SharePoint 2010 for backward compatibility and visual upgrade. But SharePoint 2010 uses v4.master only. Now click "Edit File" link to add the favicon code. If it asks for check out, click yes and continue.

Find <SharePoint:SPShortcutIcon ID="SPShortcutIcon1" runat="server" IconUrl="/_layouts/images/favicon.ico"/> and change the path of favicon. Save and close (If you have checked out then you need to check in and site collection administrator has to approve it via Site Settings -> Galleries -> Master pages and page layouts -> Check in and Approve). Now reset IIS/clear browser cache and check.
To get this working for multiple browsers:
<SharePoint:SPShortcutIcon ID="SPShortcutIcon1" runat="server" IconUrl="/_layouts/images/favicon.ico"/>
...
..
Then, just above </head>, add the following:
<link rel="shortcut icon" type="image/x-icon" href="/_layouts/images/favicon.ico" />
<link rel="icon" type="image/ico" href="/_layouts/images/favicon.ico" />
<link rel="icon" type="image/png" href="/_layouts/images/favicon.png" > 

How to use ULS in SharePoint 2010 for Custom Code Exception Logging?

How to use ULS in SharePoint 2010 for Custom Code Exception Logging?


What is ULS in SharePoint 2010?
ULS stands for Unified Logging Service which captures and writes Exceptions/Logs in Log File(A Plain Text File with .log extension). SharePoint logs Each and every exceptions with ULS. SharePoint Administrators should know ULS and it's very useful when anything goes wrong. but when you ask any SharePoint 2007 Administrator to check log file then most of them will Kill you. Because read and understand the log file is not so easy. Imagine open a plain text file of 20 MB in NotePad and go thru line by line.

Now Microsoft developed a tool "ULS Viewer" to view those Log files in easily readable format. This tools also helps to filter events based on exception priority. You can read on this blog to know in details about ULS Viewer .

Where to get ULS Viewer?
ULS Viewer is developed by Microsoft and available to download for free. URL : http://code.msdn.microsoft.com/ULSViewer/Release/ProjectReleases.aspx?ReleaseId=3308
Note: Eventhought this tool developed by Microsoft, it's not supported by Microsoft. Means you can't support for this tool from Microsoft and use it on your own Risk. By the way what's the risk in viewing Log Files?!

How to use ULS in SharePoint 2010 Custom Code?
ULS can be extended to use in user solutions to log exceptions. In Detail, Developer can use ULS to log his own application errors and exceptions on SharePoint Log files. So now all in Single Place (That's why it's called "Unified Logging"). Well in this article I am going to use Waldek's Code (Reference Link). However the article is core and am writing container for that (Basically how to implement the code in Detail). Let's see the steps.
  1. Open Visual Studio 2010 -> File -> New Project -> Visual C# -> Windows -> Class Library -> Name : ULSLogger (Make sure you've selected .net Framework 3.5)
    Create Class Library Project


     
  2. In Solution Explorer Panel, Rename the Class1.cs to LoggingService.cs

     
  3. Right Click on References -> Add Reference -> Under .Net tab select "Microsoft.SharePoint"
    Add Microsoft.SharePoint Reference


     
  4. Right Click on the Project -> Properties. Select "Signing" Tab -> Check "Sign the Assembly".

     
  5. In the below drop down select <New> and enter "ULSLogger", uncheck the "Protect my key with a Password" option.
     
  6. Now copy the below code and paste. (Or Just refer.. :-) )

    using System;using System.Collections.Generic;using System.Linq;using System.Text;using Microsoft.SharePoint;using Microsoft.SharePoint.Administration;using System.Runtime.InteropServices;namespace ULSLogger
    {
    public class LoggingService : SPDiagnosticsServiceBase{public static string vsDiagnosticAreaName = "Venkats SharePoint Logging Service";public static string CategoryName = "vsProject";public static uint uintEventID = 700; // Event IDprivate static LoggingService _Current;public static LoggingService Current
    {
     get  {   if (_Current == null)
        {
          _Current = 
    new LoggingService();
        }
       return _Current;
      }
    }
    private LoggingService()
    base("Venkats SharePoint Logging Service"SPFarm.Local)
    {}
    protected override IEnumerable<SPDiagnosticsArea> ProvideAreas()
    {
    List<SPDiagnosticsArea> areas = new List<SPDiagnosticsArea>
     {
      new SPDiagnosticsArea(vsDiagnosticAreaName, new List<SPDiagnosticsCategory>
       {
        new SPDiagnosticsCategory(CategoryName, TraceSeverity.Medium, EventSeverity.Error)
       })
      };
    return areas;
    }
    public static string LogErrorInULS(string errorMessage)
    {
    string strExecutionResult = "Message Not Logged in ULS. ";try
     
    {  SPDiagnosticsCategory category = LoggingService.Current.Areas[vsDiagnosticAreaName].Categories[CategoryName];  LoggingService.Current.WriteTrace(uintEventID, category, TraceSeverity.Unexpected, errorMessage);
      strExecutionResult = 
    "Message Logged";
    }
    catch (Exception ex)
    {
     strExecutionResult += ex.Message;
    }
    return strExecutionResult;
    }
    public static string LogErrorInULS(string errorMessage, TraceSeverity tsSeverity)
    {
    string strExecutionResult = "Message Not Logged in ULS. ";try {
     
    SPDiagnosticsCategory category = LoggingService.Current.Areas[vsDiagnosticAreaName].Categories[CategoryName]; LoggingService.Current.WriteTrace(uintEventID, category, tsSeverity, errorMessage);
     strExecutionResult = 
    "Message Logged";
     }
    catch (Exception ex)
     {
      strExecutionResult += ex.Message;
      }
    return strExecutionResult;
     }
    }
    }

     
  7. Just build the solution and it's ready to use now.
This ULS solution can be used in SharePoint Webparts or Console Application. Lets see how to use it in a Console Application.
SharePoint Server 2010 must be installed in the same Server or the application must be hosted in SharPoint Server 2010 environment. The console application must be set to "x64" Platform target.
  1. Create a New Console Application. (Visual Studio -> File -> New Project -> C# -> Windows -> Console Application)
  2. Right Click on References -> Add Reference -> Under .Net tab select "Microsoft.SharePoint"
  3. Open Program.cs add "using Microsoft.SharePoint.Administration;"
  4. Right Click on References -> Add Reference -> Under "Browse" tab select the "ULSLogger.dll" which we created first. (Path : ULSLogger\ULSLogger\bin\Debug\)
  5. Right Click on Project -> Properties -> Select "Build" Tab -> Under "Platform Target" option select "x64".
  6. Open the Program.cs and paste the below code.

    using System;using System.Collections.Generic;using System.Linq;using System.Text;
    using Microsoft.SharePoint.Administration;using ULSLogger;

    namespace ULSLoggerClient
    {

      class Program  {
       static void Main(string[] args)
        {

         Console.WriteLine("ULS Logging Started.");

         string strResult = LoggingService.LogErrorInULS("My Application is Working Fine.");     Console.WriteLine("ULS Logging Info. Result : " + strResult);

         string strResult = LoggingService.LogErrorInULS("My Application got an Exception.", TraceSeverity.High);
         Console.WriteLine("ULS Logging Waring Result : " + strResult);     Console.WriteLine("ULS Logging Completed.");     Console.ReadLine();
        }
      }
    }


     
  7. Just build the solution and execute. It'll log the message on the log file. Make sure you are using Farm Administrator User ID.
    ULS Logging Console Application


     
You can play with Message and TraceSeverity as required.
Now Open ULS Viewer(Read Second section of this article to get ULS Viewer) -> File -> Open From -> ULS -> Select First Option to open the default ULS Log.
Select ULS Log File


It's Uls RealTime and will show all log entries in readable table format. Right Click on a row and select "Filter By This Item". Select "Event ID" and enter value "700" that we used in the application.
ULS Log Viewer - Log Filter


Click Ok and now you'll see the Exceptions/Logs which logged by our application. SharePoint by default log each and every exceptions on ULS so it'll take couple of minutes to list all Exceptions. See the Status bar on ULS Viewer. If it's "uls Running" then it's still reading the Logs to display. Provide your Filters and wait for few minutes.
ULS Log Viewer


If you want to see High Priority Messages only then Click Icons except Red Cross Icon on the Toolbar. The tooltip will tell what's the icons used for. 

Document Sets in SharePoint 2010

Document Sets in SharePoint 2010:-

Document Set is a new feature introduced in SharePoint 2010 as part of content/document management. Document set helps to manage group of documents as a single entity. Actualy Document set is a content type that can be attached to any document library and make use of it's features.

Advantages of Document Sets
Consider a type "Project", each project has requirements document, project effort estimation spreadsheet, project plan presentation. To standardize the project management process, it's enforced to have all these documents for every project. In SharePoint 2007 it's not so easy to group different documents in same document library as each document is individual item. But this can be done within few minutes with Document sets feature. Documents sets will have Templates for each document, ie a predefined format document for review document, effort estimation, project plan presentation can be attached while defining this document set content type. Each library which uses this content type will get those document templates when user creates new document set.

Apart from these document sets can be versioned. It can have it's own customized Welcome page which is like home page for the project. Document Set content type basically inhertited from "Document" content type. Other content types also can be added if required. Workflows can be attached and few more options provided in SharePoint designer for document sets.

 


How to enable Document Sets?
Document sets by default won't be enabled in SharePoint 2010. It's a feature and has to be enabled manualy. Then document sets Content type has to be customized (if required). After that it can be attached to Document libraries. First keep all project document templates (Requirements document, Effort Estimation, Project Plan Presentation) ready.
 
  1. Login to SharePoint 2010 site -> Site settings -> Site Administration -> Site Collection Features -> Document Sets -> Activate.

 
  1. Site Settings -> Galleries -> Site Content types -> Document Set Content Types -> Document Set.

 

  1. Select Document Set Settings.

 
  1. Under Default Content section select the templates. Click "Add new default content" to select and upload more template documents.

 
  1. Now we'll create new document library. If you want to attach to existing document library then skip this step.

 
  1. Open the document library -> Library (Tab) -> Library Settings.

 
  1. Under General Settings select Advanced Settings. We need to enable allow management of content types setting.

 
  1. Under Content types Select Yes for "Allow management of content types?" and save/Click Ok.


 
  1. Now in the library settings page Content types section will be shown. Select "Add from existing site content types".


 
  1. Under "Select Content types" section select "Document Set" and Add. Now click Ok.


 
  1. In library settings -> Content types section -> Document sets -> Settings -> Name and description. Change name as "Project Plan".


 
  1. Open the document library -> Documents (Tab) -> New Document -> Project Plan.


 
  1. Provide a project name for eg. "Aqua" -> Ok.


 
  1. Now a Project Plan Document set created with all default template documents. You'll be landed in Project Plan Welcome Page. :)


 
To change Welcome page and other settings, check Document Sets Content type settings.

Note: Document sets is feature of Microsoft SharePoint Server 2010 (MSS 2010) and won't be available on SharePoint Foundation 2010.