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

Thursday, November 25, 2010

FBA on Sharepoint 2010

There are not a lot of differences with configuring FBA for SharePoint 2010 compared to 2007, but there are a few.  For instance, SharePoint 2010 no longer supports “classic FBA”, rather forms based authentication is provided through Claims Authentication.  There is also the introduction of the Secure Store Service which is the next-gen of the Single Sign On service of old.
Both of these come into play when configuring Forms Based Authentication.
Mission
Configure an extranet web application for Claims based authentication using AD and Forms.  Store membership credentials in a SQL database.  Manage members through IIS Manager.
Game Plan
1. Configure SQL for membership store
  • Create database
  • Create SQL User
  • Add SQL user to database
2. Configure Central Admin to use SQL membership store
3. Configure Secure Store Web Service to use SQL membership store
4. Create new Web Application for extranet site
5. Configure Extranet site to use SQL membership store
So let’s begin…

1. Configure SQL for membership store

The process of creating the store is exactly the same as what we did for 2007, so I’ll just copy and paste that thank you!
The membership store is still created using the ASP.NET SQL Server Setup Wizard.  This is launched from the .NET 2.0 Framework folder on the server at:
C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regsql.exe
This wizard will take you thorough the steps and will build out the SQL database for you.
alt
Once you select to Configure SQL Server for application services, you will be prompted for theSQL Server name and database name.  You can choose an existing database to add the membership elements to, or you can type in a new name and the database will be created for you.
Once the database is created, we’re going to create and add a SQL user, rather than use integrated authentication.  If your SQL instance is not already running in mixed-mode, you can change it through Server properties in SQL Server Management Studio.  Right-click on Server in Object Explorer and select Properties, then navigate to the Security page.
image
Create SQL user
Back in object Explorer, expand Security –> Logins.  Right-click logins and select “New Login…”  On the New Login page, enter a username, password on the general page, clear all three password options for policy, expiration, and enforce change. Hit Ok and we have our SQL user.
image
Add SQL user to membership database
Now, navigate to the database we created for our membership earlier (ConlosoDevFBA), and expand to Security-> Users.  Right-click on Users and select New User….
image
Enter the name, select Login name, and give this fella the role “db_owner”.
To recap:
We created a database called ConlosoDevFBA.
We created a SQL user called FormsAuthUser
We added FormsAuthUser to ASPNetFormsAuth database and gave them the db_owner role.
We’re done with SQL.

2. Configure Central Admin Web Site to use SQL Membership Provider

SharePoint web sites out of the box are configured to use Active Directory.  So you may be wondering why we’re configuring Central Admin to use FBA when we don’t really want to login in as an FBA user.  Well, we actually don’t want to configure it to to login as a forms user, but we do need to be able to add users from out membership database when configuring site collection admins, and the like.
So all we want to do is tell the Central Admin web application to use our SQL membership provider as well as AD, so when you use the people picker to select users, it will provide results from our membership database.
Open IIS Manager on the WFE server (if more than one, then this needs to be done on every FWE that has Central Admin.  The same goes for the proceeding steps for the other web applications).
Select the SharePoint Central Administration v4 site.  On the Home Page, you’ll see many options for ASP.NET and IIS.  The ones we’re concerned with are
image
Open the Connection Strings Page.  Under Actions menu on the right, select Add… to create a new connection string.  Provide the details for the membership database for the new connection string.
image
Add Role Provider
Go back to the Web Application page and open up Providers page.  Here we will create a provider for Roles and Users.  Set feature to .NET Roles and click Add… in the Actions pane to add a new role provider.  I called it FBARoleProvider and selected the right type and connection string.
Ensure you provide an ApplicationName so the provider knows what uses to authenticate.  For a good explanation on why you need this, see Scott Guthrie’s blog.
image
Add Membership Provider
Now set feature to .NET Users and click Add… from the actions pane to add a membership provider.
image
Select the correct type and connection string, and whatever behaviors you choose.
That’s it for the providers for Central Admin.
To verify that all looks ok, we can check the web.config of the web application.  To get to the right web.config, right-click on the web application under sites, and select Explore.
image
In the web.config, you’ll see sections for the connection string and the providers.  The and  sections should look like:
image
You should also see a  section close to the bottom of the web.config file.

3. Configure Secure Store Web Service to use SQL Membership Provider

Everything we did for Central Admin site, we are going to do for theSecurityTokenServiceAppliaation which is in the SharePoint Web Services application.
image
Without redo’ing all the steps:
  • Create the connection string
  • Add the .NET role provider
  • Add the .NET users provider
    Verify connection by editing config.xml.

4. Create Extranet Web Application

Ok, finally we are ready to create our web application (called SharePoint – FBA) that will use FBA authentication.
In Central Admin, Select the Application Management page, and select Manage web applications.  Select New from the ribbon to create a new web application.
Select Claims Based Mode Authentication as Authentication Type.  Select values for all the other options until you get to the “Enable Forms Based Authentication”.
Add the values we created earlier in the section “Enable Forms Based Authentication” for role and membership provider.
image
Once the application is created, we should create a site collection.
Create Site Collection
Go to the Create Site Collection page from the Manage Applications section in Central Admin.  Select the team (or blank, or whichever you choose) template then select the site collection administrator.  At this point, we should be able to select from our SQL membership users.  Enter a user you know exists in the membership database and see if you can resolve the names.
image
I have a user with the same name in both AD and SQL, so I know I am hitting both.
Note: I jumped ahead here and added users through IIS Manager.  If you have been following this article to the letter, then you will obviously not see users in your membership database.  Do not worry about this piece for now, as you will add users to your membership store later.
At this point we have told SharePoint what role providers to use for the web app, but we still need to configure the web app through IIS manager to bind the providers.
Configure Membership Providers for Web App through IIS
In IIS Manager, browse to the new site SharePoint – FBA. For our new FBA site we need to do the following:
  • Add connection string
  • Add Providers for members and roles
  • Configure .NET Roles
  • Configure .NET Users
  • Set Authentication to Forms and Integrated
  • Add User as Site Collection Admin
image
1. Add Connection String
Same as we have done before.
image
Note: we could potentially just do this for the machine, and not have to do it for every web application.  I prefer to do it for every web app, as I’ve had mixed results otherwise.
2. Add role and user providers
Again, same as what we did before.  Open Providers page and add an entry for our role and user providers.
image image
3. Configure .NET Roles
This and the next steps are not required for the other two web applications we configured (Central Admin and SSS).
Open the .NET Roles page for our web application.  You will receive a warning that the default role provider is not trusted.  WE just need to set our default role provider toFBARoleProvider.
image
We do not have any roles in our database at this point, so let’s create two (StandardUser, SuperUser) by clicking Add… in the actions pane.
image
4. Configure .NET Users
Now we need to do the same for .NET Users.  Open the .NET Users page.  You will get a similar warning saying the default is not trusted.  Set the default provider toFBAMembershipProvider. If you had members in the database, you would now see them listed.  Assuming you don’t let’s add some.  Click Add… from the Actions pane to add users, and assign them roles.
image image
5. Set Authentication
SharePoint should have done this when you created the web application, but let’s confirm.  From the web application home page in IIS Manager, select Authentication under the IIS section. Confirm that the web application has both Integrated and Forms enabled.
6. Add User as Site Collection Admin
Now that we have everything hopefully configured correctly, we can go back to SharePoint Central Admin and add our new user as the Site Collection Administrator.  From Central Admin Application Management page, click Change site collection administrators.  Select SharePoint – FBA root site collection, and add our new user.
image
Now lets test all this business by trying to login.  Browse to your site and select to login as a forms user.
image
What the…?!  I am authenticated ok, but am not allowed in, even though I’m a site collection admin?!
Caveat
Here’s the caveat – In order for you to use IIS Manager to manage your SQL users, you need to set the default provider to our Forms provider, i.e. FBAMembershipProvider.  In order for it to work we need to set it to the SharePoint claims provider.  Go back to .NET Users and reset the default provider to “i” which is for the Microsoft.SharePoint.Administration.Claims.SPClaimsAuthMembershipProvider
image
You could work around this by creating another IIS web site, configure the same way you did for SharePoint – FBA, and use that for managing users.

You should also check the default Role Provider for the web application and ensure that is set to “c”.  If this is set to the SQL provider that you created, you will get an unexpected error after you logon.

Now let’s try to login again…
image
Success!!