|
using System;
using System.Xml;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
namespace WCFPing.Lib
{
class ServiceProxyInstanceFactory
{
internal static object Create(ServiceProperties properties, Assembly assembly, string contractName)
{
try
{
ServiceEndpoint endPoint =
properties.Endpoints.Find(
(ServiceEndpoint e) => { return e.Contract.Name.Equals(contractName); });
if (endPoint == null)
throw new WCFPingException("Service Proxy Instance creation failed. Endpoint not found for Contract.");
List<Type> assmTypes = assembly.GetTypes().ToList<Type>();
List<Type> interfaces = assmTypes.FindAll((Type t) => { return t.IsInterface; });
Type contractType = interfaces.Find(
(Type type) =>
{
object[] attrs = type.GetCustomAttributes(typeof(ServiceContractAttribute), false);
if ((attrs == null) || (attrs.Length == 0)) return false;
ServiceContractAttribute scAttrib = (ServiceContractAttribute)attrs[0];
XmlQualifiedName qName = GetContractName(type, scAttrib.Name, scAttrib.Namespace);
if (!qName.Name.Equals(endPoint.Contract.Name)) return false;
if (!qName.Namespace.Equals(endPoint.Contract.Namespace)) return false;
return true;
});
if (contractType == null)
throw new WCFPingException("Service Proxy Instance creation failed. Contract not found.");
Type clientBaseType = typeof(ClientBase<>).MakeGenericType(contractType);
Type proxyType = assmTypes.Find(
(Type type) =>
{
return (
type.IsClass &&
contractType.IsAssignableFrom(type) &&
type.IsSubclassOf(clientBaseType));
});
//Creating instance of the proxy
Type[] paramTypes = new Type[2] { typeof(Binding), typeof(EndpointAddress) };
object[] paramValues = new object[2] { endPoint.Binding, endPoint.Address };
ConstructorInfo ctor = proxyType.GetConstructor(paramTypes);
return ctor.Invoke(paramValues);
}
catch (Exception ex) { throw new WCFPingException("Service Proxy Instance creation failed.", ex); }
}
internal static XmlQualifiedName GetContractName(Type contractType, string name, string ns)
{
const string DefaultNamespace = "http://tempuri.org/";
if (String.IsNullOrEmpty(name))
name = contractType.Name;
ns = (ns == null) ? DefaultNamespace : Uri.EscapeUriString(ns);
return new XmlQualifiedName(name, ns);
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.