Developer Sandeep's Blog

October 27, 2009

Add Web service reference- Components required to enumerate web references not installed

Filed under: Visual Studio — sandeep nakarmi @ 5:24 AM

The solution

  1. Close all open Visual Studio instances
  2. Open the Command prompt available with Visual Studio and type devenv /resetskippkgs (You can directly type this to Run command or normal command prompt) 
  3. Add reference to the Web service/WCF service

http://weblogs.asp.net/cabhilash/archive/2009/10/13/add-web-service-reference-components-required-to-enumerate-web-references-not-installed.aspx

October 7, 2009

Embedding SqlServer Compact in application. Performance benchmarks and best practices

Filed under: SqlServer — Tags: — sandeep nakarmi @ 5:20 PM

Thinking of implementing SQL Server Compact in your application. !!!

Have a look at the performance benchmarks and best practices tips presented in PDC 2008 in the video below. It will help a lot.

http://channel9.msdn.com/pdc2008/PC40/   

:-) Happy coding.

September 30, 2009

Host WCF Service in SharePoint

Filed under: Sharepoint 2007 — Tags: , , — sandeep nakarmi @ 6:57 AM

Recently, I had been working on how to get a WCF service hosted in SharePoint. The requirement was to host a WCF service in SharePoint and a custom webpart would access the service. So in this post, I will illustrate how to host WCF in SharePoint.

Download SourceCode

Environment:

  • Microsoft SharePoint Server 2007
  • Visual Studio 2008
  • Visual Studio Extensions for WSS 3.0 v1.3 March CTP

1)      First let’s create a WCF service and its implementation. For this, create a project of type WCF Service Library. Name it SPService. This will create a default interface “IService.cs” and its implementation “Service.cs”. 

2)      Delete the defaut IService.cs and Service.cs files. 

3)      Add a new item of type WCF Service named SPService

4)      Modify the ISPService interface as shown below.

using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace SPService
{
    // NOTE: If you change the interface name "ISPService" here, you must also update the reference to "ISPService" in App.config.
    [ServiceContract]
    public interface ISPService
    {
        [OperationContract]
        string SayHello(string name);
    }
}

5) Modify SPService class as shown below.

using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Activation;

namespace SPService
{
    // NOTE: If you change the class name "SPService" here, you must also update the reference to "SPService" in App.config.
    [AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
    public class SPService : ISPService
    {
        #region ISPService Members

        public string SayHello(string name)
        {
            return string.Concat("Hello ",name);
        }

        #endregion
    }
}

6) Modify the web.config file as shown below.  

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <!-- When deploying the service library project, the content of the config file must be added to the host's
  app.config file. System.Configuration does not support config files for libraries. -->
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicBinding">
          <security mode="TransportCredentialOnly">
            <transport clientCredentialType="Ntlm" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
    <services>
      <service behaviorConfiguration="NewBehavior" name="SPService.SPService">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicBinding"
          name="basicBindingEndPoint" contract="SPService.ISPService" />
<!--<host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/SPService" />
          </baseAddresses>
        </host>-->      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="NewBehavior">
          <serviceDebug />
          <serviceMetadata httpGetEnabled="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

7)      Sign the project .

sign the project  

8)      Now run the project. This will bring up the WCF Test Client wizard. Test remote method by invoking the method. It should respond you as shown below.

WCF Test Client

WCF Test Client

9)      Now create a SharePoint project of template type Empty. Name it “SharePoint.WSP”. Select the option to Deploy it to GAC.

 GAC 

10)   Create the folders “RootFiles”, “ISAPI”, “SPService” in the structure as shown below. We will host the service in the folder “SPService”.

Soln

11)    Rename the “App.config” file in project SPService to “web.config”. Now in project, SharePoint.WSP, select the folder SPService and select to add an existing item. Navigate to web.config file and add it as a link.

 web config link 

12)   Similarly, add a link to assembly SPService.dll also.

 assembly link 

13)   Then in folder SPService, add an item of type “SPService.svc”. Modify the file to following. 

<%@ Assembly Name="SPService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ee2ed923e46a9fcd" %>
<%@ ServiceHost Service="SPService.SPService,SPService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ee2ed923e46a9fcd" %>

You can retrieve the full assembly signature using a reflector.

 reflector 

14)   Go to the WSP view (View – > Other Windows -> WSP View). The manifest.xml file should look like below.

 manifest 

15)   Now set site url in the properties of project SharePoint.WSP where the solution will be deployed. Then deploy the solution.

prop 

16)    Now try to access the service with the url http://sandeep-pc/_vti_bin/spservice/spservice.svc . At this point you may receive an VirtualPath error like below.

 err 

Exception: System.ArgumentException: virtualPath
at System.ServiceModel.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) 

at Microsoft.SharePoint.ApplicationRuntime.SPRequestModule.IsExcludedPath(Stri­ng virtualPath) 
at Microsoft.SharePoint.ApplicationRuntime.SPVirtualPathProvider.FileExists(St­ring virtualPath) 
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceA­vailable(String normalizedVirtualPath) 
at System.ServiceModel.ServiceHostingEnvironment.EnsureServiceAvailableFast(St­ring relativeVirtualPath)
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.HandleRequest()
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.BeginRequest() 
at System.ServiceModel.Activation.HttpHandler.ProcessRequest(HttpContext context)
 

The problem here is that SPVirtualPathProvider isn’t coded to handle URLs that start with ‘~’;

        See workaround references for this:

17)    As a workaround, follow the procedure below.  

18)   Add a folder named WCFSupport, in the project SharePoint.WSP. In this folder, add a new class file named “WCFVirtualPathProvider” and add the following lines of code.

class WCFVirtualPathProvider : VirtualPathProvider
    {
        public override string CombineVirtualPaths(string basePath, string relativePath)
        {
            return Previous.CombineVirtualPaths(basePath, relativePath);
        }

        public override System.Runtime.Remoting.ObjRef CreateObjRef(Type requestedType)
        {
            return Previous.CreateObjRef(requestedType);
        }

        public override bool DirectoryExists(string virtualDir)
        {
            return Previous.DirectoryExists(virtualDir);
        }

        public override bool FileExists(string virtualPath)
        {
            // Patches requests to WCF services: That is a virtual path ending with ".svc"     
            string patchedVirtualPath = virtualPath;
            if (virtualPath.StartsWith("~", StringComparison.Ordinal) &amp;&amp;
              virtualPath.EndsWith(".svc", StringComparison.InvariantCultureIgnoreCase))
            {
                patchedVirtualPath = virtualPath.Remove(0, 1);
            }
            return Previous.FileExists(patchedVirtualPath);
        }

        public override System.Web.Caching.CacheDependency GetCacheDependency(string virtualPath,
                   System.Collections.IEnumerable virtualPathDependencies, DateTime utcStart)
        {
            return Previous.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart);
        }

        public override string GetCacheKey(string virtualPath)
        {
            return Previous.GetCacheKey(virtualPath);
        }

        public override VirtualDirectory GetDirectory(string virtualDir)
        {
            return Previous.GetDirectory(virtualDir);
        }

        public override VirtualFile GetFile(string virtualPath)
        {
            return Previous.GetFile(virtualPath);
        }

        public override string GetFileHash(string virtualPath, System.Collections.IEnumerable virtualPathDependencies)
        {
            return Previous.GetFileHash(virtualPath, virtualPathDependencies);
        }

        protected override void Initialize()
        {
            base.Initialize();
        }
    }

19)   Create another class file named “WCFVPPRegModule” and add the following lines of code.

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Hosting;

namespace SharePoint.WSP.WCFSupport
{
    class WCFVPPRegModule : IHttpModule
    {
        #region IHttpModule Members

        public void Dispose()
        {
            // do nothing
        }

        public void Init(HttpApplication context)
        {
            if (!wcfProviderInitialized)
            {
                lock (locker)
                {
                    WCFVirtualPathProvider wcfVPP = new WCFVirtualPathProvider();
                    HostingEnvironment.RegisterVirtualPathProvider(wcfVPP);
                    wcfProviderInitialized = true;
                }
            }
        }

        #endregion

        static bool wcfProviderInitialized = false;
        static object locker = new object();
    }
}

 
20)    Now after we have created the HttpModule, we need to register this in the web.config file of the root web application. This can be done manually or by creating a feature receiver which will apply the modification to the web.config file. I am going to use the later one. These feature receiver will be scoped at WebApplication and enabling this feature will apply the necessary modification to get the service running.  

21)   Add a new class file named “WCFSupportReceive.csr” in the folder “WCFSupport” and change it to below.

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Security;

namespace SharePoint.WSP.WCFSupport
{
    [Guid("1860F007-6E2B-4a95-A8B6-371AB8F6B012")]
    class WCFSupportReceiver : SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
            if (webApp != null)
            {
                foreach (ModificationEntry entry in Entries)
                {
                    webApp.WebConfigModifications.Add(CreateModification(entry.Name, entry.XPath, entry.Value));
                }
                SPFarm.Local.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
            }      
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
            if (webApp != null)
            {

                foreach (ModificationEntry entry in Entries)
                {
                    webApp.WebConfigModifications.Remove(CreateModification(entry.Name, entry.XPath, entry.Value));
                }

                SPFarm.Local.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
            }    
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties){}

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties){}
      
        private struct ModificationEntry
        {
            public string Name;
            public string XPath;
            public string Value;
            public ModificationEntry(string Name, string XPath, string Value)
            {
                this.Name = Name;
                this.XPath = XPath;
                this.Value = Value;
            }
        }

private ModificationEntry[] Entries = {
              new ModificationEntry(
                  "add[@name='WCFVPPRegModule']",
                   "configuration/system.web/httpModules",
                   @"<add name=""WCFVPPRegModule"" type=""SharePoint.WSP.WCFSupport.WCFVPPRegModule,SharePoint.WSP, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1948038ea0d4e8e4"" />"
                   )
            };

        public SPWebConfigModification CreateModification(string Name, string XPath, string Value)
        {
            SPWebConfigModification modification = new SPWebConfigModification(Name, XPath);
            modification.Owner = WebConfigModificationOwner;
            modification.Sequence = 0;
            modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
            modification.Value = Value;
            return modification;

        }
        private const string WebConfigModificationOwner = "SharePoint.WSP";
    }
}

Note: The ModificationEntry[] is used to define the set of configurational changes needed to be made to web.config file. For now, we just need to register a http module, so there is just one entry defined. Use reflector to find the full signed signature of the assembly. Make sure that the PublicKeyToken matches to that of the assembly.

22)   Then go to WSP View (View – > Other Windows-> WSP View). This is how it looks in WSP View.

 wsp 

23)   Change the feature.xml of the WCFSupportReceiver as shown below.

<?xml version="1.0" encoding="utf-8"?>
<Feature Id="1860f007-6e2b-4a95-a8b6-371ab8f6b012"
         Title="WCFSupportReceiver"
         Description="Enable WCFSupport for SPService"
         Scope="WebApplication"
         Version="1.0.0.0"
         Hidden="FALSE"
         ReceiverAssembly="SharePoint.WSP, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1948038ea0d4e8e4"
         ReceiverClass="SharePoint.WSP.WCFSupport.WCFSupportReceiver"
         DefaultResourceFile="core"
         xmlns="http://schemas.microsoft.com/sharepoint/">
  <ElementManifests />
</Feature>

The key things to note here are:

  • The feature is scoped at WebApplication since we are making change in the web.config file of the web application. Also this means that in each web application, this feature has to be activated in order to acecess WCF Service.
  • Use the reflector to get the full assembly signature for the ReceiverAssembly. 

24)   Now everything set, deploy the project. Go to “Manage Web Application Features” of the web application into which the solution was deployed. Activate the WCFSupportFeaure feature if it  is not yet activated. You can also verify this by opening web.config file of web application and see for the entry for “WCFSupportReceiver”.

 config

 25)   Navigate to the url again: http://sandeep-pc/_vti_bin/spservice/spservice.svc .You should see a response like below.

 25 

26)   So the service has been hosted. To test the service, following the procedures below.

  1. Create a console application.
  2. Add the service reference to the above hosted service.
  3. Modify the client code to the following.
using System;
using System.Collections.Generic;
using System.Text;

namespace TestClient
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Service.SPServiceClient client = new TestClient.Service.SPServiceClient();
                string response = client.SayHello("sandeep");

                Console.WriteLine(string.Format("Response from server: {0}", response));
            }
            catch (Exception exc)
            {
                Console.WriteLine(string.Format("Error:{0}", exc.Message));
            }
            Console.ReadLine();
        }
    }
}

This is the output of the client application.

 output

 I would suggest you to have a look at the following references that I went through to get this done.

References:

September 23, 2009

Create a simple WCF Service and Client application.

Filed under: WCF — sandeep nakarmi @ 8:04 PM
In this post, I will demonstrate how to create a simple WCF client and service console application. This post is intended for beginners who can follow the following steps to get a basic WCF Service up and running.

Minimum requirement: .Net framework 3.0.

For this, we will create three projects.

  • A service class Library: This library will contain the Service Contract, Operation Contracts and Data Contracts that will be shared by both WCF service and client applications.
  • WCF service application: A console application that will host the service.
  • WCF client application:  A console application that will call a remote wcf service method and display the response from the service.

Lets start by creating the service class library.

1) Create a class library application and name it WCFServiceLibrary.

2) Delete the default Class1.cs file and add new interface file named “IService.cs”.

3) Add reference to the Syste.ServiceModel in the project and then add the corresponding using directives.  Then make the following change in the IService interface.       

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace WCFServiceLibrary
{
    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        int GetProduct(int x, int y);
    }
}

Here we add a definition for method GetProduct which will return the product of two numbers passed in as parameter.

4) Add another cs file named “Service.cs”. Implement the “IService.cs” interface and its method. 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WCFServiceLibrary
{
    class Service : IService
    {
        #region IService Members
        public int GetProduct(int x, int y)
        {
            return x * y;
        }
        #endregion
    }
}

5) Now since we have the service library with a method exposed, lets create a service application now.

6) Create a console application named “WCFService” and add reference to the WCFServiceLibrary project. Also add reference to System.ServiceModel. Add the following using directive.

using System.ServiceModel
using WCFServiceLibrary;

7) Lets now create a configuration file for the WCF Service. This configuration file will define the Endpoint binding, endpoint address and behaviors for the service. Add a new app.config file to the WCFService project.

8) Open the WCF Service Configuration Editor, Tools -> WCF Service Configuration Editor. Then select the app.config file created in above step. You can now follow the wizard to create the binding for the service.

8.a) Since we are creating a config file for service, select the “Create a New Service” link.

8.b) In Service Type step,  browse to the WCFServiceLibrary.dll and select the type “WCFServiceLibrary.Service”. 

         8_b

        8_b_2

8.c) Click Next, and you will see the Contract for the service. 

        8_c

8.d) Click next; here you need to select the mode you want to use for binding, Http, Tcp, Named Pipes etc. Select Tcp and click next. Now set the endpoint address like below: 

        8_d

       8_d_2

 Click Next and finish the wizard.

8.e) Then go to “Endpoints” node and give the name for configuration as TcpBinding. Then save the project.

       8_e

8. f) Select root Services node and then create a binding configuration by selecting “(Default )Click to create”. Supply the name of the binding as NetTcpBinding. With rest set to default, save the config file.

9) Now add the following lines of code to the program.cs file of WCFService project.                                         


namespace WCFService
 {
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
               ServiceHost host = new ServiceHost(typeof(WCFServiceLibrary.Service));
                host.Open();
                Console.WriteLine(string.Format("The service is running....."));
            }
            catch (Exception exc)
            {
                Console.WriteLine(string.Format("Error: {0}",exc.Message));
            }
            Console.ReadLine();         
        }
    }
 }

                                                                                                                                                                                                          When you run the service you should see a console open up with message “The service is running…..”  

10) Now since the service is running, lets create a client to access the remote service. Create a console application named “WCFClient” and add the reference to the System.ServiceModel, WCFServiceLibrary project. Then add the following using directives in the program.cs file.


using System.ServiceModel;
using System.ServiceModel.Channels;
using WCFServiceLibrary;

11) Now let’s create the app.config file for the client. Again we are going to use the “WCF Service Configuration Editor”. The catch here is that, now we can just specify the app.config file of the service application and it will automatically generate the settings for the client according to the service. So follow the steps below to get this done.

  • Add a new app.config file to the WCFClient application.
  • Open the WCF Service Configuraiton Editor and select to open this app.config file.
  • Select the Client node in the left tree and on the right side you will see a link label Create a New Client. Click it.
  • Select the “From service config” option and browse to the app.config file of the WCFService application which we created at the end of step 8.
  • Proceed by selecting next, and provide “ClientTcpBinding” as name when you are prompted for the client configuration name. Proceed to finish and then save the config file.

         Remove the <identity> section if exists. The configuration file should look like this.


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
      <bindings>
          <netTcpBinding>
              <binding name="NetTcpBinding" />
          </netTcpBinding>
      </bindings>
      <client>
    <endpoint address="net.tcp://localhost:8080/Service" binding="netTcpBinding"
   bindingConfiguration="NetTcpBinding" contract="WCFServiceLibrary.IService"
         name="ClientTcpBinding">             
    </endpoint>
     </client>
  </system.serviceModel>
</configuration>
12) Now add the following codes of line to the program.cs file of WCFClient project.

namespace WCFClient
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
ChannelFactory<WCFServiceLibrary.IService> factory = new ChannelFactory<IService>("ClientTcpBinding");
                factory.Open();
                IService remoteService = factory.CreateChannel();
                int x=4;
                int y=4;
                int retVal = remoteService.GetProduct(x, y);

                Console.WriteLine(string.Format("The product of {0} and {1} is {2} ",x,y,retVal));
            }
            catch (Exception exc)
            {
                Console.WriteLine(string.Format("Error:{0}",exc.Message));
            }
            Console.ReadLine();
        }
    }
}
13) Now run the WCFService application first. Right Click WCFService->Debug->Start New Instance.

        13

14) Run the WCFClient project with WCFClient->Debug->Start New Instance. You should see the following output.

        14

So here we learned how to create a WCF Service, host it in console application, program the client to access this remote service exposed method. We also learned how to use the WCF Service Configuration Editor tool which saved us from manually editing the configuration file and saved our time. 

Happy Coding :-)

September 13, 2009

VSeWSS Service Error: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.

Filed under: VseWss 1.3 March CTP — sandeep nakarmi @ 10:11 AM

I was working on VseWSS 1.3 March CTP version and i was trying to add the Enterprise logging ability in sharepoint web parts. Since in VseWSS 1.3 has the feature that the referenced assemblies are also included in package and are installed in GAC, i opted with this version, other wise i was working with version 1.2.

So in order to add the logging feature, i just created a new sharepoint web part project and referenced the following enterprise library references in the project.

  • Microsoft.Practices.EnterpriseLibrary.Logging.dll
  • Microsoft.Practices.EnterpriseLibrary.Common.dll
  • Microsoft.Practices.ObjectBuilder2.dll

Having created a simple hello world webpart, i tried to deploy the project. But just then, this error occurred.

Error 1 VSeWSS Service Error: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.

Log file written to: C:\Windows\system32\config\systemprofile\AppData\Roaming\Microsoft\VSeWSS 1.3\VSeWSS1.3 service.log 

After searching a bit on the web, i was very disappointed that this is yet another problem in version VseWSS 1.3. The only solution for this was to add the assemblies to GAC manually, clean the project and perform iisreset. Then only it worked.

See the following links for references:

 Well i am looking for alternatives as a work around for this. May be the post build script solution suggested in the link above. :-(

Older Posts »

Blog at WordPress.com.