[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

WCF Function that Returns and Enumeration

Posted on 2009-05-02
3
Medium Priority
?
1,561 Views
Last Modified: 2012-05-06
I'm having a heck of a time figuring this out.  I've created a WCF web service.  currently it has one function that returns an Enumeration.  The problem is that I am not able to get it to work correctly.  I cannot create an instance of the enumeration and thereforek, I cannoti use it to determine the status of my function (the function updates a table in my DB).

I've built and re-built the web service.  I then created a test web site.  I added a "service" reference to that site that points at the wsdl for the web service. (i have the web service and the test site both running using .net built in server).

One interesting thing: after i add the reference and drill down into the files, the enumertion definition appears in one file and the function in a completely seperate one (MemberService.xsd and MemberService1.xsd.

I'm attaching all my code below.  I've tried adding as a zip file so that it wouldn't get messy but unfortunately it won't allow the files inside the zip archive.

Any help would be a god send!!!!
WEB SERVICE:
 
MemberService.vb
' NOTE: If you change the class name "Service" here, you must also update the reference to "Service" in Web.config and in the associated .svc file.
Imports System
Imports System.Runtime.Serialization
Imports System.Data
Imports System.Data.SqlClient
Public Class MemberService
    Implements IMemberService
 
    Public Function UpdateMember(ByVal ExternalID As String, _
                                 ByVal MemberNumber As String, _
                                 ByVal FirstName As String, _
                                 ByVal MemberDate As String, _
                                 ByVal LastName As String, _
                                 ByVal DateofBirth As String, _
                                 ByVal Spouse As String, _
                                 ByVal NoOfChildren As String, _
                                 ByVal Address1 As String, _
                                 ByVal Address2 As String, _
                                 ByVal City As String, _
                                 ByVal State As String, _
                                 ByVal Zip As String, _
                                 ByVal Country As String, _
                                 ByVal HomePhone As String, _
                                 ByVal AlternatePhone As String, _
                                 ByVal FaxNumber As String, _
                                 ByVal EmailAddress As String, _
                                 ByVal Pwd As String _
                                 ) As Status Implements IMemberService.UpdateMember
        Dim Status As Status
        Dim AlreadyInUse As Boolean = False
        'Dim conn As String = ConfigurationManager.ConnectionStrings("YourConnectionString").ConnectionString
        'First Check to see whether UserName is already being used
 
        Using objConn As New SqlConnection(ConfigurationManager.ConnectionStrings("strConn").ConnectionString)
            Using oCom As SqlCommand = New SqlCommand
                oCom.Connection = objConn
                objConn.Open()
                Dim sSQL As String
                sSQL = "Select Count(MemberID) as Cnt "
                sSQL = sSQL & "From dbo.Members "
                sSQL = sSQL & "where Email = '" & EmailAddress & "' and ExternalID <> " & ExternalID
                oCom.CommandText = sSQL
                Using dR As SqlDataReader = oCom.ExecuteReader()
                    While dR.Read
                        If dR("Cnt") > 0 Then
                            AlreadyInUse = True
                        End If
                    End While
                End Using
            End Using
        End Using
 
        Using objConn As New SqlConnection(ConfigurationManager.ConnectionStrings("strConn").ConnectionString)
            Try
                Using oCom2 As SqlCommand = New SqlCommand
                    oCom2.Connection = objConn
                    oCom2.CommandText = "UpdateMember"
                    oCom2.CommandType = CommandType.StoredProcedure
                    oCom2.Parameters.Add(New SqlParameter("@MemberNumber", SqlDbType.VarChar)).Value = Trim(MemberNumber)
                    oCom2.Parameters.Add(New SqlParameter("@FirstName", SqlDbType.VarChar)).Value = Trim(FirstName)
                    oCom2.Parameters.Add(New SqlParameter("@LastName", SqlDbType.VarChar)).Value = Trim(LastName)
                    oCom2.Parameters.Add(New SqlParameter("@Address1", SqlDbType.VarChar)).Value = Trim(Address1)
                    oCom2.Parameters.Add(New SqlParameter("@Address2", SqlDbType.VarChar)).Value = Trim(Address2)
                    oCom2.Parameters.Add(New SqlParameter("@City", SqlDbType.VarChar)).Value = Trim(City)
                    oCom2.Parameters.Add(New SqlParameter("@State", SqlDbType.VarChar)).Value = Trim(State)
                    oCom2.Parameters.Add(New SqlParameter("@Country", SqlDbType.VarChar)).Value = Trim(Country)
                    oCom2.Parameters.Add(New SqlParameter("@Zip", SqlDbType.VarChar)).Value = Trim(Zip)
                    oCom2.Parameters.Add(New SqlParameter("@HomePhone", SqlDbType.VarChar)).Value = Trim(HomePhone)
                    oCom2.Parameters.Add(New SqlParameter("@AlternatePhone", SqlDbType.VarChar)).Value = Trim(AlternatePhone)
                    oCom2.Parameters.Add(New SqlParameter("@Fax", SqlDbType.VarChar)).Value = Trim(FaxNumber)
                    oCom2.Parameters.Add(New SqlParameter("@MemberID", SqlDbType.Int, 4))
                    oCom2.Parameters("@MemberID").Direction = ParameterDirection.Output
                    objConn.Open()
                    Dim dR2 As SqlDataReader
                    dR2 = oCom2.ExecuteReader()
                    dR2.Close()
 
                    Dim MemberID As Integer
                    MemberID = oCom2.Parameters("@MemberID").Value.ToString()
 
                    If MemberID = 0 Then
                        Status = Status.MemberAlreadyExistsBasedOnMemberNumber
                    ElseIf MemberID = -1 Then
                        Status = Status.MemberAlreadyExistsBasedOnEmail
                    Else
                        Status = Status.MemberInserted
                    End If
 
                End Using
 
            Catch ex As Exception
                Status = Status.DataBaseError
            End Try
        End Using
        Return Status
 
    End Function
 
End Class
 
IMemberService.vb
' NOTE: If you change the interface name "IService" here, you must also update the reference to "IService" in Web.config.
<ServiceContract()> _
Public Interface IMemberService
    <OperationContract()> _
    Function UpdateMember(ByVal ExternalID As String, _
                                 ByVal MemberNumber As String, _
                                 ByVal FirstName As String, _
                                 ByVal MemberDate As String, _
                                 ByVal LastName As String, _
                                 ByVal DateofBirth As String, _
                                 ByVal Spouse As String, _
                                 ByVal NoOfChildren As String, _
                                 ByVal Address1 As String, _
                                 ByVal Address2 As String, _
                                 ByVal City As String, _
                                 ByVal State As String, _
                                 ByVal Zip As String, _
                                 ByVal Country As String, _
                                 ByVal HomePhone As String, _
                                 ByVal AlternatePhone As String, _
                                 ByVal FaxNumber As String, _
                                 ByVal EmailAddress As String, _
                                 ByVal Pwd As String _
                                 ) As Status
 
 
    ' TODO: Add your service operations here
 
End Interface
 
<Serializable()> _
<DataContract()> _
Public Enum Status
    <EnumMember()> DataBaseError = 0
    <EnumMember()> MemberInserted = 1
    <EnumMember()> MemberAlreadyExistsBasedOnEmail = 2
    <EnumMember()> MemberAlreadyExistsBasedOnMemberNumber = 3
    <EnumMember()> MemberUpdated = 4
    <EnumMember()> EmailAddressAlreadyExists = 5
End Enum
 
Web.Config
<?xml version="1.0"?>
<!--
    Note: As an alternative to hand editing this file you can use the 
    web admin tool to configure settings for your application. Use
    the Website->Asp.Net Configuration option in Visual Studio.
    A full list of settings and comments can be found in 
    machine.config.comments usually located in 
    \Windows\Microsoft.Net\Framework\v2.x\Config 
-->
<configuration>
	<configSections>
		<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
			<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
				<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
				<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
					<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
					<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
					<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
					<section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
				</sectionGroup>
			</sectionGroup>
		</sectionGroup>
	</configSections>
  <connectionStrings>
    <add name="strConn" connectionString="user id=USERID;pwd=PWD;data source=SERVER_IP;initial catalog=DATABASE"/>
  </connectionStrings>
	<system.web>
		<!--
            Set compilation debug="true" to insert debugging 
            symbols into the compiled page. Because this 
            affects performance, set this value to true only 
            during development.
 
            Visual Basic options:
            Set strict="true" to disallow all data type conversions 
            where data loss can occur. 
            Set explicit="true" to force declaration of all variables.
        -->
		<compilation debug="true" strict="false" explicit="true">
			<assemblies>
				<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
				<add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
				<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
				<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
			</assemblies>
		</compilation>
		<pages>
			<namespaces>
				<clear/>
				<add namespace="System"/>
				<add namespace="System.Collections"/>
				<add namespace="System.Collections.Specialized"/>
				<add namespace="System.Configuration"/>
				<add namespace="System.Runtime.Serialization"/>
				<add namespace="System.ServiceModel"/>
				<add namespace="System.Text"/>
				<add namespace="System.Text.RegularExpressions"/>
				<add namespace="System.Linq"/>
				<add namespace="System.Web"/>
				<add namespace="System.Web.Caching"/>
				<add namespace="System.Web.SessionState"/>
				<add namespace="System.Web.Security"/>
				<add namespace="System.Web.Profile"/>
				<add namespace="System.Web.UI"/>
				<add namespace="System.Web.UI.WebControls"/>
				<add namespace="System.Web.UI.WebControls.WebParts"/>
				<add namespace="System.Web.UI.HtmlControls"/>
			</namespaces>
			<controls>
				<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
			</controls>
		</pages>
		<!--
            The <authentication> section enables configuration 
            of the security authentication mode used by 
            ASP.NET to identify an incoming user. 
        -->
		<authentication mode="Windows"/>
		<!--
            The <customErrors> section enables configuration 
            of what to do if/when an unhandled error occurs 
            during the execution of a request. Specifically, 
            it enables developers to configure html error pages 
            to be displayed in place of a error stack trace.
 
        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        -->
		<httpHandlers>
			<remove verb="*" path="*.asmx"/>
			<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
			<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
			<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
		</httpHandlers>
		<httpModules>
			<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
		</httpModules>
	</system.web>
	<system.codedom>
		<compilers>
			<compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
				<providerOption name="CompilerVersion" value="v3.5"/>
				<providerOption name="WarnAsError" value="false"/>
			</compiler>
			<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
				<providerOption name="CompilerVersion" value="v3.5"/>
				<providerOption name="OptionInfer" value="true"/>
				<providerOption name="WarnAsError" value="false"/>
			</compiler>
		</compilers>
	</system.codedom>
	<system.web.extensions>
		<scripting>
			<webServices>
				<!--
              Uncomment this section to enable the authentication service. Include 
              requireSSL="true" if appropriate. 
 
          <authenticationService enabled="true" requireSSL = "true|false"/>
          -->
				<!--
              Uncomment these lines to enable the profile service, and to choose the 
              profile properties that can be retrieved and modified in ASP.NET AJAX 
              applications.
 
           <profileService enabled="true"
                           readAccessProperties="propertyname1,propertyname2"
                           writeAccessProperties="propertyname1,propertyname2" />
          -->
				<!--
              Uncomment this section to enable the role service.
 
          <roleService enabled="true"/>
          -->
			</webServices>
			<!--
        <scriptResourceHandler enableCompression="true" enableCaching="true" />
        -->
		</scripting>
	</system.web.extensions>
	<!--
        The system.webServer section is required for running ASP.NET AJAX under Internet
        Information Services 7.0.  It is not necessary for previous version of IIS.
    -->
	<system.webServer>
		<validation validateIntegratedModeConfiguration="false"/>
		<modules>
			<add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
		</modules>
		<handlers>
			<remove name="WebServiceHandlerFactory-Integrated"/>
			<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
			<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
			<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
		</handlers>
	</system.webServer>
	<system.serviceModel>
		<services>
			<service name="MemberService" behaviorConfiguration="ServiceBehavior">
				<!-- Service Endpoints -->
				<endpoint address="" binding="wsHttpBinding" contract="IMemberService">
					<!-- 
              Upon deployment, the following identity element should be removed or replaced to reflect the 
              identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity 
              automatically.
          -->
					<identity>
						<dns value="localhost"/>
					</identity>
				</endpoint>
			</service>
		</services>
		<behaviors>
			<serviceBehaviors>
				<behavior name="ServiceBehavior">
					<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
					<serviceMetadata httpGetEnabled="true"/>
					<!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
					<serviceDebug includeExceptionDetailInFaults="false"/>
				</behavior>
			</serviceBehaviors>
		</behaviors>
	</system.serviceModel>
</configuration>
 
MemberService.svc
<%@ ServiceHost Language="VB" Debug="true" Service="MemberService" CodeBehind="~/App_Code/MemberService.vb" %>
 
 
 
TEST WEBSITE
 
Default.aspx.vb
 
Partial Class _Default
 
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim m As New MemberService.MemberServiceClient
        m.UpdateMember("55555","5555","jsmie","01/01/2010","cahan","10.31/971","","2","4619 FooBar St.","","Tampa","FL","33611","US","5613065995","8134203511","8134203511","dcahan@yahoo.com","j&jwuthy")
 
    End Sub
End Class
 
 
MemberService1.xsd (from drill down into web_references)
 
Partial Class _Default
 
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim m As New MemberService.MemberServiceClient
        m.UpdateMember("55555","5555","jsmie","01/01/2010","cahan","10.31/971","","2","4619 FooBar St.","","Tampa","FL","33611","US","5613065995","8134203511","8134203511","dcahan@yahoo.com","j&jwuthy")
 
    End Sub
End Class
 
 
MemberService.xsd
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:tns="http://schemas.datacontract.org/2004/07/" elementFormDefault="qualified" targetNamespace="http://schemas.datacontract.org/2004/07/" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:simpleType name="Status">
    <xs:restriction base="xs:string" />
  </xs:simpleType>
  <xs:element name="Status" nillable="true" type="tns:Status" />
</xs:schema>

Open in new window

0
Comment
Question by:davidcahan
2 Comments
 
LVL 7

Expert Comment

by:ydramu
ID: 24295054
This is the problem with WCF when we have a enumeration associated with WCF return values.
If we did not declare the Enumeration with Not Defined value with 0. Then the Enum returned through WCF will get error. Try to declare a enum value with NotDefined=0.
I have the similar problem, and it got fixed with this. So I feel this should solve your problem as well.
0
 
LVL 1

Accepted Solution

by:
namigop earned 2000 total points
ID: 25067300
You should decorate the enum member with the [EnumMember] attribute so that the enum type is correctly created in the generated client proxy.
In C# ,

   [DataContract]
    public enum MyTestEnum
    {
        [EnumMember]
        A=0,
        [EnumMember]
        B=1
    }
 See attached screenshot(taken from WCFStorm).  On the right hand side, the enum type was generated as a string with an xs:restriction in XSD. On the left hand-side, the correct enum type was created because the [EnumMember] attribute was used.
Hope this helps.

WCF-Enum-Serialization.png
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…
Suggested Courses
Course of the Month18 days, 10 hours left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question