Sql-server – Connection between IIS App Pool Identity and SQL Server

iis-7sql serverwcf

I've developed a very basic WCF service (WCF 4.0) in VS 2012. I have the AdventureWorks2012 database hosted in SQL Server 2012 and I am using IIS 7 with .Net 4.0 framework installed.

When I run the service in the local development IIS with VS 2012, everything works fine (I assume because the connection string in the web.config for the website hosting the .svc is set to use Integrated Security – The connection string is below)

<add name="AdventureWorksEntities" connectionString="metadata=res://*/ProductsModel.csdl|res://*/ProductsModel.ssdl|res://*/ProductsModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=adams_pc;initial catalog=AdventureWorks2012;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient"/>

When I publish the website to my local IIS, and run it in the ASP.NET 4.0 application pool, it seems that no connection is actually made to the database (when running a console test client, the objects from my entity model have no data in them).

I have set up users in the AdventureWorks2012 database with names of IIS APPPOOL\ASP.NET v4.0 and given then dbo.owner access to the database, but I still can't get a connection to be made.

What am I missing? Do I need to change the connection string of the hosting website?

More information:

When i run it locally (by development server I meant the local instance of IIS that runs when I debug the application) information is retrieved from the database and displays in the test console application.

When I deploy the service and change the reference in the test console application to use the hosted WCF service, no data is being retrieved at all. The exception that's thrown is a null reference exception in my test code, but that's because no data was populated into the entity model my service uses. I don't see any exceptions in terms of a database connection, but I haven't gotten to the point of learning how to pass exceptions from the service to the client. I was expecting this simple test to just work like the book I am working from did.

Also, is there something else I should do to work out exactly what the error is when it comes to making the database connection?

The Service:

Imports System.Text
Imports System.Linq
Imports System
Imports System.Collections.Generic
Imports System.ServiceModel
Imports System.ServiceModel.Web
Imports System.Runtime.Serialization
Imports ProductsEntityModel
'NOTE: You can use the "Rename" command on the context menu to change the class name "Service" in code, svc and config file together.

'WCF service that implements the service contract
'This implementation performs minimal error checking and exception handling
Public Class ProductsServiceImpl
Implements IProductsService

Public Function ChangeStockLevel(productNumber As String, newStockLevel As Short, shelf As String, bin As Short) As Boolean Implements IProductsService.ChangeStockLevel
    'Modify the current stock level of the selected product in the ProductInventory table.
    'If the update is successful then return True, otherwise return False.

    'The Product and ProductIventory tables are joined over the ProductID column.

    Try
        'Connect to the AdventureWorks database using the Entity Framework
        Using database As New AdventureWorksEntities()
            ' Find the ProductID for the specified product
            Dim qryProductID = (From p In database.Products
                             Where String.Compare(p.ProductNumber, productNumber) = 0
                             Select p.ProductID).First
            'Find the ProductInventory object that matches the paramters passed into the operation
            Dim productInv As ProductInventory = database.ProductInventories.First(Function(pi) String.Compare(pi.Shelf, shelf) = 0 And pi.Bin = bin And pi.ProductID = qryProductID)

            'Update the stock level for the ProductInventory object
            productInv.Quantity += newStockLevel

            'Save the change back to the database
            database.SaveChanges()
        End Using
    Catch ex As Exception
        Return False
    End Try
    Return True
End Function


Public Function CurrentStockLevel(ByVal productNumber As String) As Integer Implements IProductsService.CurrentStockLevel
    'Obtain the total stock level for the specified product
    'The stock level is calculated by summing the quantity of the product available in all the bins in 
    'the ProductInventory table

    'The Product and ProductInventory tables are joined over the ProductID column.
    Dim stockLevel As Integer = 0

    Try
        'Connect to the AdventureWorks database by using the Entity Framework.
        Using database As New AdventureWorksEntities()
            stockLevel = (From pi In database.ProductInventories
                          Join p In database.Products
                          On pi.ProductID Equals p.ProductID
                          Where String.Compare(p.ProductNumber, productNumber) = 0
                          Select CInt(pi.Quantity)).Sum

        End Using
    Catch ex As Exception

    End Try
    Return stockLevel
End Function

Public Function GetProduct(productNumber As String) As ProductData Implements IProductsService.GetProduct
    'Create a reference to a ProductData object
    Dim productData As ProductData = Nothing

    Try
        'Connect to the AdventureWorks database by using Entity Framework
        Using database As New AdventureWorksEntities()
            Dim matchingProduct As Product = database.Products.First(Function(p) String.Compare(p.ProductNumber, productNumber) = 0)
            productData = New ProductData With {.Name = matchingProduct.Name, .ProductNumber = matchingProduct.ProductNumber, .Color = matchingProduct.Color, .ListPrice = matchingProduct.ListPrice}
        End Using
    Catch ex As Exception

    End Try
    Return productData
End Function

Public Function ListProducts() As List(Of String) Implements IProductsService.ListProducts
    'Create a list for holding product numbers
    Dim productsList As New List(Of String)

    Try
        'Connect to the AdventureWorks database by uysing the Entity Framework
        Using database As New AdventureWorksEntities()
            ' Fetch the product number of every product in the database
            Dim products = From Product In database.Products
                           Select Product.ProductNumber

            productsList = products.ToList
        End Using
    Catch ex As Exception

    End Try
    'Return the list of product numbers
    Return productsList
End Function
End Class

The Interface:

Imports System.Text
Imports System.Linq
Imports System
Imports System.Collections.Generic
Imports System.ServiceModel
Imports System.ServiceModel.Web
Imports System.Runtime.Serialization
'NOTE: You can use the "Rename" command on the context menu to change the interface name "IService" in both code and config file together.
'The Data Contact describes the details of a Product object passed to client applications (this is a return object).
<DataContract>
Public Class ProductData
<DataMember>
Public Name As String

<DataMember>
Public ProductNumber As String

<DataMember>
Public Color As String

<DataMember>
Public ListPrice As Decimal
End Class
'The Service Contact describes the operations that the WCF service provides (these are the methods available to call)
<ServiceContract>
Public Interface IProductsService

'Get the product number of every product
<OperationContract>
Function ListProducts() As List(Of String)

'Get the details of a single product
<OperationContract>
Function GetProduct(ByVal productNumber As String) As ProductData

'Get the current stock level for a product
<OperationContract>
Function CurrentStockLevel(ByVal productNumber As String) As Integer

'Change the stock level for a product
<OperationContract>
Function ChangeStockLevel(ByVal productNumber As String, ByVal newStockLevel As Short, ByVal shelf As String, ByVal bin As Int16) As Boolean

End Interface

The Client:

Imports System.ServiceModel
Imports ProductsClient.ProductsService

Module Module1

Sub Main()
    ' Create a proxy object and connect to the service
    Dim proxy As New ProductsServiceClient()

    ' Test the operations of the service

    ' Obtain a list of all the products
    Console.WriteLine("Test 1: List all products")
    Dim productNumbers As String() = proxy.ListProducts
    For Each productNumber As String In productNumbers
        Console.WriteLine("Number: {0}", productNumber)
    Next
    Console.WriteLine()

    Console.WriteLine("Test 2: Display the Details of a product")
    Dim product As ProductData = proxy.GetProduct("WB-H098")
    Console.WriteLine("Number: {0}", product.ProductNumber)
    Console.WriteLine("Name: {0}", product.Name)
    Console.WriteLine("Color: {0}", product.Color)
    Console.WriteLine("Price: {0}", product.ListPrice)
    Console.WriteLine()

    ' Query the stock level of this product
    Console.WriteLine("Test 3: Display the stock level of a product")
    Dim numInStock As Integer = proxy.CurrentStockLevel("WB-H098")
    Console.WriteLine("Number in stock: {0}", numInStock)
    Console.WriteLine()

    ' Modify the stock level of this product
    Console.WriteLine("Test 4: Modify the stock level of a product")
    If proxy.ChangeStockLevel("WB-H098", 100, "N/A", 0) Then
        numInStock = proxy.CurrentStockLevel("WB-H098")
        Console.WriteLine("Stock level changed. Current stock level: {0}", numInStock)
    Else
        Console.WriteLine("Stock level update failed.")
    End If
    Console.WriteLine()

    ' Disconnect from the service
    proxy.Close()
    Console.WriteLine("Press ENTER to finish")
    Console.ReadLine()
End Sub

End Module

And just for giggles, this is the SQL scirpt I used to set up my users in the AdventureWorks2012 database:

USE [AdventureWorks2012]
GO
CREATE USER [IIS APPPOOL\DefaultAppPool] FOR LOGIN [IIS APPPOOL\DefaultAppPool]
GO
EXEC sp_addrolemember N'db_owner', [IIS APPPOOL\DefaultAppPool]
GO
GO
CREATE USER [IIS APPPOOL\ASP.NET v4.0] FOR LOGIN [IIS APPPOOL\ASP.NET v4.0]
GO
EXEC sp_addrolemember N'db_owner', [IIS APPPOOL\ASP.NET v4.0]
GO

And here's the serviceModel part of the client's app.config so you can see the endpoint

<system.serviceModel>
    <bindings>
        <basicHttpBinding>
            <binding name="BasicHttpBinding_IProductsService" />
        </basicHttpBinding>
    </bindings>
    <client>
        <endpoint address="http://localhost/ProductsService/Service.svc" binding="basicHttpBinding"
            bindingConfiguration="BasicHttpBinding_IProductsService" contract="ProductsService.IProductsService"
            name="BasicHttpBinding_IProductsService" />
    </client>
</system.serviceModel>

Best Answer

Your service code catches all exception silently. Code like that is unacceptable :).

To debug your real exception run Your visual studio as administrator. Choose Debug -> Attach to Process -> Check "Show processes from all users" -> Select "w3wp.exe". Run your test app and wait for web service exception in visual studio.