Wednesday, November 24, 2010

What is Unified Logging Service ?

Unified Logging Service (ULS) writes the error messages or custom logging information in to Sharepoint's Trace Logs.

     Though Sharepoint 2007 shipped with Unified Loging Service, it was for internal purpose only and not supported to work with custom code where as Sharepoint 2010 supports to work with custom code. This logging information is stored on a file system in the 'c:\program files\common files\Microsoft shared\web server extensions\14\Logs'. The location were all these log files are stored is called as 'ULS logs' or Trace Logs. This path can always be changed accordingly from Central Admin, under diagnostic logging settings.
   
Using Sharepoint 2010, it is very easy to log information from custom code with the help of SPDiagnosticsService class.

Ex:   SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("My Category", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);

We can acheive creating a custom logging service by inheriting from SPDiagnosticsServiceBase class.

PowerShell Basics

Powershell is an object-oriented programming language and interactive command line shell for Microsoft Windows Platforms.
We have an environment(Windows PowerShell ISE editor) as below to write code in PowerShell .

One of the greatest feature is its integration with Microsoft.Net environment and it can also integrate with other applications .
  • Cmdlets are very small .NET classes that appear as system commands.
  • Scripts are combinations of cmdlets and associated logic.
Simple Powershell script to Write a Hello message:
 write-host "Hello"
Note: It is not mandatory to define the type of variable, declare a variable before use and it is also case insensitive as we have in VBScript. Dont compare PowerShell with VBscript as we can execute a .vbs file with just double clicking it.PowerShell script can be either run from PowerShell command prompt or using a batch file.

Variable Declaration: Variable in PowerShell script begin with a $ sign.
Ex: $Testval = 10;
      write-host ("Value assigned is: " + $Testval );


Array Declaration:
Ex: $Testval = 1,2,3,7,8;
      foreach($val in $Testval )

      {
             write-host (" Value assigned is: "+ $val );
     }
 or

      for($val =0; $val - lt  $Testval.Length;$val++ )
      {
          #Write the output values to command window.
           write-host  $Testval[$val]
     }
 

Associative Array: This is similar to hash table data type where the data is maintained in key value pairs.
 Syntax: $<array name> = @{<keyname = value>;.......}
             Ex:$Testval = @{'0'= 'Sunday' ; '1' = 'Monday'; '2' = 'Tuesday'; '3' = 'Wednesday' }
                   $Testval  //to print all key value pairs at one go.
                  $Testval ['0'] //prints Sunday
            Add a new record : $Testval ['4'] = 'Thursday'
            Delete a record from collection : $Testval.Remove('1')
            To remove all records :  $Testval.Clear()
While Statement :
       $val=1
        while ($val -ne 3)
        {
              $val++
       }

If Statement :
    if($val -eq 3)
        {
              write-host "Value is 3"
       }
     elseif($val -eq 4)
     {
              write-host "Value is 4" 
     }
   else
    {
             write-host "value is neither 3 nor 4"
    }

Logical Operators :

-and
logical and
(A -eq A) -and (A -eq B)
false
-or
logical or
(A -eq B) -or (A -eq A)
true
-not
logical not
(1 -eq 1) -and -not (2 -gt 2)
true
!
logical not
(1 -eq 1) -and !(2 -gt 2)
true


Comparision Operators :

-eq
Equal (case insensitive)
-ne
Not equal (case insensitive)
-ge
Greater than or equal (case insensitive)
-gt
Greater than (case insensitive)
-lt
Less than (case insensitive)
-le
Less than or equal (case insensitive)
-like
Wildcard comparison (case insensitive)
-notlike
Wildcard comparison (case insensitive)
-match
Regular expression comparison (case insensitive)
-notmatch
Regular expression comparison (case insensitive)
-replace
Replace operator (case insensitive)
-contains
Containment operator (case insensitive)
-notcontains
Containment operator (case insensitive)

-ieq
Case insensitive equal
-ine
Case insensitive not equal
-ige
Case insensitive greater than or equal
-igt
Case insensitive greater than
-ile
Case insensitive less than or equal
-ilt
Case insensitive less than
-ilike
Case insensitive equal
-inotlike
Case insensitive equal
-imatch
Case insensitive regular expression comparison
-inotmatch
Case insensitive regular expression comparison
-ireplace
Case insensitive replace operator
-icontains
Case insensitive containment operator
-inotcontains
Case insensitive containment operator

-ceq
Equal (case sensitive)
-cne
Not equal (case sensitive)
-cge
Greater than or equal (case sensitive)
-cgt
Greater than (case sensitive)
-clt
Less than (case sensitive)
-cle
Less than or equal (case sensitive)
-clike
Wildcard comparison (case sensitive)
-cnotlike
Wildcard comparison (case sensitive)
-cmatch
Regular expression comparison (case sensitive)
-cnotmatch
Regular expression comparison (case sensitive)
-creplace
Replace operator (case sensitive)
-ccontains
Containment operator (case sensitive)
-cnotcontains
Containment operator (case sensitive)

-is
Is of a type
-isnot
Is not of a type
-as
Is a type, no error if conversion fails


Some important functions or commands:
       get-date # returns the current date and time
       (get-date).day #returns day of the day, similary we can display month year etc.
       $StringVal -replace("a","b") #replace the charected "a" with "b" in the string $StringVal

Tuesday, November 16, 2010

How to move a Sharepoint Designer workflow to other site collections with wsp?

In SharePoint Designer 2010, you can create reusable declarative workflows. That means workflows created in SharePoint designer can now be generic (not tied to a list) and can be moved to other Site collection or sites via .wsp file. The "Save as Template" command can be used to create a WSP file containing a reusable workflow. The workflow can also be moved to Visual Studio 2010 for further Customizations.

Steps to Move Workflow are :

1. Create a SharePoint workflow using SharePoint Designer 2010.

2. After you are done with creating a workflow, Click on "Save as Template" button on Ribbon the bar. This will create a wsp file for you workflow, which will be uploaded in the current site collection itself.

3. Now, Open the Top Level Site or Site collection, in which you created the workflow. Goto View all site content and click on "Site Assets" library. You will see your saved workflow wsp (or soluiotn package) gets upload to this library. However, to deploy it in the site colletcion you will need to download this file and upload into Solution management.

4. To download this wsp you can open up the drop-down menu for this file and Choose Sent To -> Download a Copy.

5. Now to Upload it to Solution management of this or any other site collection goto
Site Actions -> Site Settings -> Under Galleries click on Solution gallery. Then Click on Solution tab(in ribbon bar) and click on Upload Solution and browse to the aboved saved file. Once the solution is uploaded click on "Activate solution" to activate it.

5. Since the workflow is deployed as a feature, you will now activate the workflow feature for the site where you want to use the Workflow. To do this goto Site Settings of that site and click on "Manage Features" now simply activate the workflow to use it in the Site.

Please note that another option in ribbon bar "Converted to be Globally Reusable" will only save your workflow to be globaly reusable. It will not create wsp file to be deployed in another farm. Also, the workflows created at the root level of the site collection can only be converted to be Globally Reusable but other ones created in sub sites cannot.

Introduction to Sharepoint 2010 Workflows

1. SharePoint 2010 workflows are build upon the workflow engine provided .Net Framework 3.5.

2. List and Site workflows - In addition to the SharePoint lists we can now create workflows for SharePoint sites as well. These are called as "Site Workflows".

3. SharePoint Designer 2010 Changes - MS has provided a new graphical workflow designer for designing workflows. These workflows can be deployed in SharePoint Server directly from the designer.

4. Editing Out-of-Box workflows - Another Improvement in SharePoint Designer 2010 workflows is that it now allows you to edit the out-of-the-box workflows that come with SharePoint.

5. Re-usable Workflow - In addition to above, with Designer 2010 you can also create reusable declarative workflows. That means unlike SharePoint 2007 designer workflows, you don't have to bind a workflow to a specific list. You can resuse them by binding it to more than one list or multiple lists.

6. User profile in Workflow - User Profile data can now be bound to properties in workflow. This will make it possible to get information about the SharePoint user profile in the workflow itself.

7. Moving SharePoint Designer Workflows - The resuable designer workflows can now be moved to another SharePoint server or to Visual Studio 2010 with a workflow .wsp file. "Save as Template" command can be used to create the WSP file for the workflow. Moving Workflows using Sharepoint Designer 2010

8.Changes in List Events - SharePoint 2010 adds four new workflow Event Receivers for list based workflows. The four workflow event receivers available are Starting, Started, Postponed and Completed. These are similar to other SharePoint list\library event receivers and they execute code on the server in response to the event.

9. Workflow Templates - To make development easier, Visual Studio 2010 includes event receiver project types to make using the workflows and events fairly simple.

Now to Start developing workflows what do you need.

1. SharePoint designer - If you need to customize the Out-of-box workflow or wants to create a "not so complex" reusable workflow. You can however, deploy your designer workflow in any sharepoint enviornment using a wsp file.

2. Microsoft Visio - If you want to design a workflow which has complex workflow chart, you can design it in Viso and later it can be pulled in to SharePoint designer. Also, note that you can only create Sequential workflows in viso.

3. Creating Worflow in VS - Visual Studio 2010 provides templates to create workflows and creates events for the workflow.

Tips to improve performance while coding using Object Model.

Accessing List Items:
             It is always good if we get the  Items collection and then loop through each item in collection, rather than using Item Collection object in for loops.

Bad Coding: 
              SPList list  = SPContext.Current.List;
              for(int i=0;i<list.items.Count;i++)
              {
                   SPListItem listItem  =  list.items[i];
              }

Good Coding:

              SPListItemCollection items  = SPContext.Current.List.items;
              for(int i=0;i<items.Count;i++)
              {
                   SPListItem listItem = items[i];
              }
Note:Most of us will get complete item collection then we later check a condition.
It is good practice to get only necessary rows and columns rather then complete 
collection,which will improve the performance as well.
 
Using SPQuery to get specific rows:
 SPQuery query = new SPQuery();
 query.RowLimit = 100;//Limiting the number of rows to retrieve.
 SPListItemCollection items = SPContext.Current.List.GetItems(query);
 
Using SPQuery to get specific Columns:
SPQuery query =  new SPQuery();
query.ViewFields = "<FieldRef Name='ID'/><FieldRef Name='Name'/>"
SPListItemCollection items = SPContext.Current.List.GetItems(query);
Always check with SPDisposeCheck tool to avoid unnecessary memory leeks.
SPDisposeCheck: 
It is good practice to run all your projects through SPDisposeCheck tool 
before doing any deployments.

Monday, November 15, 2010

How to Install and Remove a solution from Sharepoint Farm?

Installing a solution to Sharepoint Farm:

We can install a solution package by loading Microsoft.SharePoint.Powershell snap-in and then calling the Add-SPSolution cmdlet passing the –LiteralPath parameter using a value that contains the physical path to the solution package file.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction  "SilentlyContinue"
Add-SPSolution -LiteralPath "C:\SolutionCollections\TestFeature.wsp"
Once you have added the solution package using the Add-SPSolution cmdlet, you can deploy it using the Install-SPSolution cmdlet. Note that once the solution package has been added, you refer to it using the –Identity parameter whose value should be the name of the solution package file without any path.
Add-PSSnapin Microsoft.SharePoint.PowerShell   -ErrorAction"SilentlyContinue"
Add-SPSolution -LiteralPath "C:\SolutionCollections\TestFeature.wsp"
Install-SPSolution -Identity "TestFeature.wsp"  -Local -GACDeployment
You should also observe that the call to Install-SPSolution includes two additional parameters which are –Local and –GACDeployment. The –Local parameter tells SharePoint Foundation that it only needs to worry about deploying the solution package on the local server which can speed things up when developing on a single-server farm. The other parameter –GACDeployment is required whenever you are deploying a solution package which installs an assembly in the GAC.

Retracting and Removing a Solution:

If you want to remove a solution package from a farm after it has been deployed you must retract it and then remove it. The act of retracting reverses the act of deployment. For example, retracting a solution will force SharePoint Foundation to delete all the files it copied during deployment as well as uninstalling features and deleting assemblies from the GAC. Once you have retracted a solution you can then remove it which deletes the solution package file from the configuration database.
You can retract a solution package using the Uninstall-SPSolution cmdlet. When calling Uninstall-SPSolution you should pass the -Identity parameter and the -Local parameter in the same manner as when calling Install-SPSolution. You should also pass the –Confirm parameter with a value of $false because failing to do so can cause the cmdlet to prompt the user. This can cause problems because it has the effect of freezing Visual Studio when you execute a script that prompts the user for a response.
Add-PSSnapin Microsoft.SharePoint.PowerShell  -ErrorAction "SilentlyContinue"
$SolutionPackageName = "TestFeature.wsp"
Uninstall-SPSolution -Identity $SolutionPackageName  -Local -Confirm:$false
Once you have retracted the solution using the Uninstall-SPSolution cmdlet, you can then remove it by calling Remove-SPSolution which instructs SharePoint Foundation to delete the solution package file from the configuration database.
Add-PSSnapin Microsoft.SharePoint.PowerShell   -ErrorAction "SilentlyContinue"
$SolutionPackageName = "TestFeature.wsp"
Uninstall-SPSolution -Identity $SolutionPackageName  -Local -Confirm:$false
Remove-SPSolution -Identity $SolutionPackageName  -Confirm:$false
Of course, these calls to Uninstall-SPSolution and Remove-SPSolution will fail if the solution package is not currently installed and deployed. Therefore, it makes sense to add a call to Get-SPSolution and conditional logic to determine whether the solution package is currently installed and deployed before attempting to retract it or remove it.
Add-PSSnapin Microsoft.SharePoint.PowerShell   -ErrorAction "SilentlyContinue"
$SolutionPackageName = "C:\SolutionCollections\TestFeature.wsp"
$solution = Get-SPSolution | where-object {$_.Name -eq $SolutionPackageName}
# check to see if solution package has been installed
if ($solution -ne $null) {
# check to see if solution package is currently deployed
if($solution.Deployed -eq $true){
Uninstall-SPSolution -Identity $SolutionPackageName  -Local -Confirm:$false
}
}

We can also check the status of the timer job that installs/uninstalls solution, using $solution.JobExists

while ( $solution.JobExists )
{
write-host "."
sleep 1
}
write-host "solution deployed"

Monday, November 8, 2010

How to take a Farm Backup?

We need to execute the below command from Sharepoint 2010 Management shell

Backup-SPFarm -Directory <Path of file to take backup> -BackupMethod Full