Thursday, December 30, 2010

Creating a Custom WCF Web Services for Sharepoint 2010

Windows Communication Foundation:
Windows Communication Foundation(WCF) takes many existing communication technologies, such as Web Services, Windows Remoting, Microsoft Message Queuing, and abstracts them into a single technology. In most cases, this simplifies the way you communicate with other applications. It also allows you to communicate with other applications without being coupled to a specific technology. In this we are going to create a simple WCF service and we are going to host that service inside SharePoint site (in the _vti_bin folder) .
Steps Involved:
Create a WCF Service:
The following steps should be followed to create a WCF service using Visual Studio 2010.
  1. Open Visual Studio 2010.
  2. Go to File => New => Project.

    1.gif
  3. Select Empty SharePoint Project under installed template category SharePoint and name it as WCF.
  4. Target the .Net Framework 3.5.
  5. Click OK.
  6. In the SharePoint Customization Wizard, enter the URL of the local site where you want to use(http://demo2010a:5000/) and select Deploy as a farm solution.
  7. Right click the Solution Explorer , click Add and select SharePoint Mapped Folder.

    2.gif
  8. In Add SharePoint Mapped Folder select ISAPI.

    3.gif
  9. Right click on ISAPI and Add a New Folder.

    4.gif
  10. Name the folder as WCF.
  11. Right click on WCF and Add a New item.
  12. Select a text file from the installed templates and name it as Service.svc.

    5.gif
  13. Add another text file and name it as web.config.

    6.gif
  14. Right click on the ISAPI and Add a new item.
  15. Select a Class file from the installed templates and name it as Service.cs.

    7.gif
  16. Again add a new item , select Interface file and name it as IService.cs.

    8.gif
  17. Solution Explorer should like the below one.

    9.gif
  18. Add a reference to the Microsoft.SharePoint.Client.ServerRuntime assembly. This assembly contains the Service Host Factory classes, as well as some attributes we need later on.
IService.cs:
using System;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Runtime.Serialization;usingSystem.ServiceModel;usingSystem.Text;namespace WCF.ISAPI{    [ServiceContract]    publicinterfaceIService    {        [OperationContract]        stringgetTime();    }}
Service.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Activation;
namespace WCF.ISAPI
{
    [ServiceBehavior]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
     public class Service : IService    {
         public string getTime()
       {
              returnDateTime.Now.ToString();
       }
    }  
}

Service.svc:
To get Version, PublicKeyToken, and Assembly type name use SN.EXE utitlity.

<%@ServiceHostDebug="true"Language="C#"CodeBehind="Service.cs"Service="WCF.ISAPI.Service,WCF, PublicKeyToken=1b762f52dfc6b6d8,Version=1.0.0.0, Culture=Neutral"%>

web.config:
xml version="1.0"?>

<configuration>
  <system.serviceModel>
    <services>
      <service behaviorConfiguration="WCF.ISAPI.ServiceBehaviour"
        name="WCF.ISAPI.Service">
        <endpoint address=""
                  binding="basicHttpBinding"
                  contract="WCF.ISAPI.Service" >
          <identity>
            <dns value="localhost" />
          identity>
        endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://demo2010a:5000/">add>
          baseAddresses>
        host>
      service>
    services>
    <behaviors>
      <serviceBehaviors>
        <behavior name=" WCF.ISAPI.ServiceBehaviour">
          
          <serviceMetadata httpGetEnabled="true"/>
          
          <serviceDebug includeExceptionDetailInFaults="false"/>
        behavior>
      serviceBehaviors>
    behaviors>
  system.serviceModel>
configuration>

Checking anonymous authentication to the SharePoint site:

  1. Go to Run and type inetmgr.

    10.gif
  2. Expand sites and click on SharePoint- 5000(SharePoint Site where we are going to deploy the WCF service).

    11.gif
  3. Click Authentication as shown in the above figure.

    12.gif
  4. Check whether the status of Anonymous Authentication is enabled.
Testing the Service:
  1. Deploy the Project.
  2. Go to the URL http://demo2010a:5000/_vti_bin/WCF/Service.svc.

    13.gif
  3. We have successfully created WCF service and hosted inside SharePoint (_vti_bin folder).

View diagnostic logs (SharePoint Server 2010)

You can use data from the Universal Logging System (ULS) logs in Microsoft SharePoint Server 2010 to troubleshoot problems in the farm. The ULS log can collect data at varying levels depending upon the logging settings. You can use Windows PowerShell to filter the data, display it in various ways, and output the data to a data grid with which you can filter, sort, group, and export data to Microsoft Excel 2010.

View and filter log events by using Windows PowerShell

You can use Windows PowerShell to view and filter log events. You cannot view or filter log events by using Central Administration.

To view and filter log events by using Windows PowerShell

  1. Verify that you meet the following minimum requirements: See Add-SPShellAdmin.
  2. On the Start menu, click All Programs.
  3. Click Microsoft SharePoint 2010 Products.
  4. Click SharePoint 2010 Management Shell.
  5. At the Windows PowerShell command prompt, type one of the following commands:
    • All trace events:

      Get-SPLogEvent
    • By level:

      Get-SPLogEvent | Where-Object {$_.Level -eq [Information | Warning | Error | Critical | Verbose | Unexpected | Monitorable | High | Medium]}
    • By area:

      Get-SPLogEvent | Where-Object {$_.Area -eq }

      Where  is the value of the Area property.
    • By category:

      Get-SPLogEvent | Where-Object {$_.Category -eq

      Where  is the value of the Category property.
    • By event ID:

      Get-SPLogEvent | Where-Object {$_.EventID -eq }

      Where  is the value of the EventID property.
    • By message text:

      Get-SPLogEvent | Where-Object {$_.Message -like "**"}

      Where  is the string found in the event message.
    • By process:

      Get-SPLogEvent | Where-Object {$_.Process -like "**"}

      Where  is the value of the Process property.
    Ff463595.Tip(en-us,office.14).gifTip:
    By default, the command retrieves data from the default ULS log folder. To view and filter trace events that are on shared folder on a network, use theDirectory parameter of the Get-SPLogEvent cmdlet.
    To view more details about each trace event, use Format-List at the end of the command. For example, Get-SPLogEvent | Where-Object {$_.Area -eq "SharePoint Foundation"} | Format-List.
For more information, see Get-SPLogEvent.
Ff463595.note(en-us,office.14).gifNote:
We recommend that you use Windows PowerShell when performing command-line administrative tasks. The Stsadm command-line tool has been deprecated, but is included to support compatibility with previous product versions.

View and export diagnostic logs by using the Windows PowerShell Out-GridView cmdlet

Windows PowerShell provides a powerful and easy-to-use feature that displays tabular data resulting from Windows PowerShell commands in a filterable, searchable data grid in a separate window. You can use this grid to view log events and to perform the following operations on the data:
  • Sort the data by any column.
  • View the data in groups.
  • Filter the data by Level, Area, Category, Message, Event ID, or Timestamp.
  • Search the data for any string.
  • Export raw or sorted or filtered data to a spreadsheet.
Ff463595.note(en-us,office.14).gifNote:
The Out-GridView cmdlet cannot be used with cmdlets that use the Format verb. The Out-GridView cmdlet receives objects whereas the cmdlets that use theFormat verb return only formatted text. However, you can pre-filter the data sent to the grid view by using the Where-Object pipeline — for example, Get-SPLogEvent | Where-Object {$_.Area -eq "SharePoint Foundation"} | Out-GridView.
If the grid is displaying more than several hundred rows, it might run slowly, especially if performing complex filtering operations. For faster performance, export the data to Excel 2010.
For more information, see Out-GridView (http://go.microsoft.com/fwlink/?LinkId=181248) and Out-GridView Revisited (http://go.microsoft.com/fwlink/?LinkId=181249).

To view and filter diagnostic logs by using Windows PowerShell

  1. Verify that you meet the following minimum requirements: See Add-SPShellAdmin.
  2. On the Start menu, click All Programs.
  3. Click Microsoft SharePoint 2010 Products.
  4. Click SharePoint 2010 Management Shell.
  5. At the Windows PowerShell command prompt, type the following command:
    Get-SPLogEvent | Out-GridView
  6. To view the results in groups:
    1. Right-click the column header, click Show In Groups, and then click the column header for the value by which you want to group the results.
    2. To expand or collapse a specific group, click the arrow next to the group name.
    3. To remove grouping, right-click the column header, and then click Show In Groups.
  7. To sort columns, click the column header.
  8. To search for a specific string, type the string in the Search box. Search is performed over all columns and rows. To clear the search, click Clear All.
  9. To filter data on only one criterion, type the following in the Search box: :. For example, to search for all log entries raised by Windows SharePoint Foundation 2010, type the following: Area:SharePoint Foundation. To clear the filter, click Clear All.
  10. To filter data by using more than one criterion or by using criteria with “contains, begins with, ends with” or other methods:
    1. Click Query.
    2. Click Add.
    3. Click the check box for the properties that you want to filter on, and then click OK.
    4. Click contains to change to a different filter method. The methods available are containsdoes not containstarts withequalsdoes not equalends withis empty, and is not empty.
    5. Type a value in the text box.
    6. Repeat steps “e” and “f” for each property you selected in step “c”.
    7. When all the filtering criteria are specified, click the search button to filter the data grid.
    8. To clear a specific filter, click the X button.
    9. To clear all the filters, collapse the query view and click the Clear All button.

To export grid data to a spreadsheet

  1. Select the rows that you want to export. You can select multiple rows by using SHIFT+DRAG to select a block of rows, CTRL+CLICK to select specific rows, or CTRL+A to select all rows.
    You can also filter and sort the results before you copy the data into a spreadsheet. When you sort or filter data, only the resulting viewable data is copied over.
  2. Copy the selected rows by using CTRL+C.
  3. Open the spreadsheet workbook page, and then paste the copied rows into it by using CTRL+V.

Monday, December 20, 2010

Access web.config in SharePoint timer job

In SharePoint customization we have the requirements to write custom code for web parts, timer jobs etc. In this post I want to tell you some interesting things in SharePoint. I have written some timer jobs to deploy into my SharePoint server to match some requirements or to solve some problems.
My requirement is, I want to access the web application or web site configuration [web.config] file in the SharePoint timer job. But, the limitations in SharePoint stops me to access the configuration files in timer job. Below are the problems I faced.
  • SharePoint timer job is running in different process named OWSTIMER.EXE.
  • SharePoint web application or site will run with the help of process W3WP.EXE.
  • So, the application configuration file is associated with the W3WP.EXE, so there is no way to access the web.config file in the owstimer.exe process at all. The context is completely different and out of domain. So, we need to call or access the web.config file explicitly in timer job. How to?
  • Remember, always C# is completely object oriented and you can access everything through objects.
  • Usually the timer job installed as a feature. And all the logic of the timer job will go inside the Execute() method. So, write below statements in that method and access the complete web.config file. Below is the example of accessing appsettings. 

  1. SPWebApplication webApplication = this.Parent as SPWebApplication;  
  2. Configuration config = WebConfigurationManager.OpenWebConfiguration("/", webApplication.Name);  
  3. String appValue = config.AppSettings.Settings["appSettingKey"].Value;  


WebConfigurationManager is the class which is in the namespace Systen.Web.Configuration. This way, you can access the config settings from a web.config of a SharePoint web site. Hope you understood this well and please let me know what you think.

Wednesday, December 15, 2010

How to: Debug a Timer Job

To debug a timer job in Visual Studio 2010
  1. On the Start menu, point to Administrative Tools, and then click Services.
  2. In the Services window, make sure the SharePoint 2010 Timer service is started.
  3. Open the Visual Studio 2010 project that contains your timer job.
    Ff798310.note(en-us,PandP.10).gifNote:
    Make sure that the code has not changed since you deployed the timer job; otherwise, the debugger will not match your source code to the deployed assembly.
  4. Set a breakpoint in the Execute method of your job definition class.
    Ff798310.3aebdfeb-2b19-41aa-a8e2-431acfdc1185(en-us,PandP.10).png
  5. On the Debug menu, click Attach to Process.
  6. In the Attach to Process dialog box, click OWSTIMER.EXE, and then click Attach.
    Ff798310.85cd2ff8-42a3-47c4-8940-5565d391b020(en-us,PandP.10).png
  7. If the Attach Security Warning dialog box is displayed, click Attach.
  8. In the SharePoint Central Administration Web site, click Monitoring, and then click Review job definitions.
  9. Click the name of your job, and then click Run Now on the Edit Timer Job page.
  10. Verify that the Visual Studio 2010 debugger stops execution on your breakpoint.
    Ff798310.9a4a3603-9483-48d3-a7df-49c81490d044(en-us,PandP.10).png