Simple WCF login service

Hi,

I need to create a simple WCF service with a method that accepts username and password and checks if the user with those values is in the table ( a XML file ) and if it is it returns true. Since I am complete beginner in programming, but especially in wcf I need help in solving this problem. I have tried with creating a separate class in wcf service library project that is overriding the UserNamePasswordValidator class, but got stuck very soon ( created only a if statement that throws a exception if the data is not entered ) .
Any help is welcome, thanks !
Arsen MilosevAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

it_saigeDeveloperCommented:
Perhaps something like this will meet your requirements:

Web.config -
  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <services>
      <service name="EE_Q28701603.Authenticator" behaviorConfiguration="asmx">
        <!-- Service Endpoints -->
        <endpoint address="ws" binding="wsHttpBinding" contract="EE_Q28701603.IAuthenticator">
			   <!-- 
              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>
        <endpoint address="web" binding="webHttpBinding" contract="EE_Q28701603.IAuthenticator" behaviorConfiguration = "webBehaviour"/>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        <host>
            <baseAddresses>
                <add baseAddress="http://localhost/Authenticate" />
            </baseAddresses>
	   </host>
      </service>
    </services>
    <behaviors>
        <endpointBehaviors>
            <behavior name="webBehaviour">
                <webHttp />
            </behavior>
        </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="asmx">
          <!-- 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="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

Open in new window

Authenticator.svc -
<%@ ServiceHost Language="C#" Debug="true" Service="EE_Q28701603.Authenticator" CodeBehind="Authenticator.svc.cs" %>

Open in new window

Authenticator.svc.cs -
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Activation;
using System.Xml.Linq;

namespace EE_Q28701603
{
	[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
	public class Authenticator : IAuthenticator
	{
		#region IAuthenticator Members
		public bool Authenticate(string user, string password)
		{
			var users = LoadUsers();
			if (users != null)
				return (from u in users where u.Name.Equals(user, StringComparison.OrdinalIgnoreCase) && u.Password.Equals(password) select u).Count() != 0;
			return false;
		}
		#endregion

		private static IEnumerable<User> LoadUsers()
		{
			XElement element = null;
			try
			{
				element = XElement.Load(User.XmlFile);
				return from elem in element.Descendants("User")
					  select new User
					  {
						  Name = elem.Attribute("Name").GetAsString(),
						  Password = elem.Attribute("Password").GetAsString()
					  };
			}
			catch (Exception) { ;}
			return null;
		}
	}
}

Open in new window

Base.cs -
using System;
using System.ComponentModel;

namespace EE_Q28701603
{
	public class Base : INotifyPropertyChanged
	{
		[NonSerialized]
		private PropertyChangedEventHandler fPropertyChanged;

		public event PropertyChangedEventHandler PropertyChanged
		{
			add { fPropertyChanged += value; }
			remove { fPropertyChanged -= value; }
		}

		protected virtual void OnPropertyChanged(object sender, string propertyName)
		{
			PropertyChangedEventHandler handler = fPropertyChanged;
			if (handler != null)
				handler(sender, new PropertyChangedEventArgs(propertyName));
		}
	}
}

Open in new window

Extensions.cs -
using System.Xml.Linq;

namespace EE_Q28701603
{
	static class Extensions
	{
		public static string GetAsString(this XAttribute attribute)
		{
			return (attribute != null && !string.IsNullOrEmpty(attribute.Value)) ? attribute.Value : string.Empty;
		}
	}
}

Open in new window

IAuthenticator.cs -
using System.ServiceModel;
using System.ServiceModel.Web;

namespace EE_Q28701603
{
	[ServiceContract]
	public interface IAuthenticator
	{
		[OperationContract]
		[WebInvoke(Method = "GET", 
			ResponseFormat = WebMessageFormat.Xml, 
			RequestFormat = WebMessageFormat.Xml, 
			BodyStyle = WebMessageBodyStyle.WrappedRequest, 
			UriTemplate = "/Authenticate?user={user}&password={password}")]
		bool Authenticate(string user, string password);
	}
}

Open in new window

User.cs -
using System.Web;
namespace EE_Q28701603
{
	public class User : Base
	{
		public static string XmlFile = string.Format(@"{0}/App_Data/Users.xml", HttpContext.Current.Server.MapPath("."));

		private string fName;
		private string fPassword;

		public string Name
		{
			get { return fName; }
			set
			{
				if (fName != value)
				{
					fName = value;
					OnPropertyChanged(this, "Name");
				}
			}
		}

		public string Password
		{
			get { return fPassword; }
			set
			{
				if (fPassword != value)
				{
					fPassword = value;
					OnPropertyChanged(this, "Password");
				}
			}
		}
	}
}

Open in new window

Users.xml -
<?xml version="1.0" encoding="utf-8" ?>
<Users>
	<User Name="JSmith" Password="TestSmith" />
	<User Name="JDoe" Password="TestDoe" />
</Users>

Open in new window


The Users.xml file is located in the App_Data directory with a build action of 'Copy Always'.

This produces the following output in the WCF Test Client application provided by Visual Studio:Capture.JPGAnd the following output in a web request:Capture.JPG
An example project for VS2010 can be found here: https://filedb.experts-exchange.com/incoming/ee-stuff/8427-EE_Q28701603.zip

-saige-

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Arsen MilosevAuthor Commented:
Thanks very much, now it's up to me to learn how you got to that solution.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
WCF

From novice to tech pro — start learning today.