Imported Upstream version 4.0.0~alpha1

Former-commit-id: 806294f5ded97629b74c85c09952f2a74fe182d9
This commit is contained in:
Jo Shields
2015-04-07 09:35:12 +01:00
parent 283343f570
commit 3c1f479b9d
22469 changed files with 2931443 additions and 869343 deletions

View File

@ -0,0 +1,420 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.ComIntegration
{
using System;
using System.Collections;
using System.Runtime.InteropServices;
/*
* Stolen from ES.
* I removed SuppressUnmanagedCodeSecurity. We can re-add it later.
*/
enum COMAdminThreadingModel
{
Apartment = 0,
Free = 1,
Main = 2,
Both = 3,
Neutral = 4,
NotSpecified = 5
}
enum COMAdminIsolationLevel
{
Any = 0,
ReadUncommitted = 1,
ReadCommitted = 2,
RepeatableRead = 3,
Serializable = 4
}
[ComImport]
[Guid("790C6E0B-9194-4cc9-9426-A48A63185696")]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
internal interface ICatalog2
{
[DispId(0x00000001)]
[return: MarshalAs(UnmanagedType.Interface)]
Object GetCollection([In, MarshalAs(UnmanagedType.BStr)]
String bstrCollName);
[DispId(0x00000002)]
[return: MarshalAs(UnmanagedType.Interface)]
Object Connect([In, MarshalAs(UnmanagedType.BStr)] String connectStr);
[DispId(0x00000003)]
int MajorVersion();
[DispId(0x00000004)]
int MinorVersion();
[DispId(0x00000005)]
[return: MarshalAs(UnmanagedType.Interface)]
Object GetCollectionByQuery([In, MarshalAs(UnmanagedType.BStr)]
String collName,
[In, MarshalAs(UnmanagedType.SafeArray)]
ref Object[] aQuery);
[DispId(0x00000006)]
void ImportComponent([In, MarshalAs(UnmanagedType.BStr)] String bstrApplIdOrName,
[In, MarshalAs(UnmanagedType.BStr)] String bstrCLSIDOrProgId);
[DispId(0x00000007)]
void InstallComponent([In, MarshalAs(UnmanagedType.BStr)] String bstrApplIdOrName,
[In, MarshalAs(UnmanagedType.BStr)] String bstrDLL,
[In, MarshalAs(UnmanagedType.BStr)] String bstrTLB,
[In, MarshalAs(UnmanagedType.BStr)] String bstrPSDLL);
[DispId(0x00000008)]
void ShutdownApplication([In, MarshalAs(UnmanagedType.BStr)] String bstrApplIdOrName);
[DispId(0x00000009)]
void ExportApplication([In, MarshalAs(UnmanagedType.BStr)] String bstrApplIdOrName,
[In, MarshalAs(UnmanagedType.BStr)] String bstrApplicationFile,
[In] int lOptions);
[DispId(0x0000000a)]
void InstallApplication([In, MarshalAs(UnmanagedType.BStr)] String bstrApplicationFile,
[In, MarshalAs(UnmanagedType.BStr)] String bstrDestinationDirectory,
[In] int lOptions,
[In, MarshalAs(UnmanagedType.BStr)] String bstrUserId,
[In, MarshalAs(UnmanagedType.BStr)] String bstrPassword,
[In, MarshalAs(UnmanagedType.BStr)] String bstrRSN);
[DispId(0x0000000b)]
void StopRouter();
[DispId(0x0000000c)]
void RefreshRouter();
[DispId(0x0000000d)]
void StartRouter();
[DispId(0x0000000e)]
void Reserved1();
[DispId(0x0000000f)]
void Reserved2();
[DispId(0x00000010)]
void InstallMultipleComponents([In, MarshalAs(UnmanagedType.BStr)] String bstrApplIdOrName,
[In, MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] ref Object[] fileNames,
[In, MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] ref Object[] CLSIDS);
[DispId(0x00000011)]
void GetMultipleComponentsInfo([In, MarshalAs(UnmanagedType.BStr)] String bstrApplIdOrName,
[In] Object varFileNames,
[Out, MarshalAs(UnmanagedType.SafeArray)] out Object[] varCLSIDS,
[Out, MarshalAs(UnmanagedType.SafeArray)] out Object[] varClassNames,
[Out, MarshalAs(UnmanagedType.SafeArray)] out Object[] varFileFlags,
[Out, MarshalAs(UnmanagedType.SafeArray)] out Object[] varComponentFlags);
[DispId(0x00000012)]
void RefreshComponents();
[DispId(0x00000013)]
void BackupREGDB([In, MarshalAs(UnmanagedType.BStr)] String bstrBackupFilePath);
[DispId(0x00000014)]
void RestoreREGDB([In, MarshalAs(UnmanagedType.BStr)] String bstrBackupFilePath);
[DispId(0x00000015)]
void QueryApplicationFile([In, MarshalAs(UnmanagedType.BStr)] String bstrApplicationFile,
[Out, MarshalAs(UnmanagedType.BStr)] out String bstrApplicationName,
[Out, MarshalAs(UnmanagedType.BStr)] out String bstrApplicationDescription,
[Out, MarshalAs(UnmanagedType.VariantBool)] out bool bHasUsers,
[Out, MarshalAs(UnmanagedType.VariantBool)] out bool bIsProxy,
[Out, MarshalAs(UnmanagedType.SafeArray)] out Object[] varFileNames);
[DispId(0x00000016)]
void StartApplication([In, MarshalAs(UnmanagedType.BStr)] String bstrApplIdOrName);
[DispId(0x00000017)]
int ServiceCheck([In] int lService);
[DispId(0x00000018)]
void InstallMultipleEventClasses([In, MarshalAs(UnmanagedType.BStr)] String bstrApplIdOrName,
[In, MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] ref Object[] fileNames,
[In, MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] ref Object[] CLSIDS);
[DispId(0x00000019)]
void InstallEventClass([In, MarshalAs(UnmanagedType.BStr)] String bstrApplIdOrName,
[In, MarshalAs(UnmanagedType.BStr)] String bstrDLL,
[In, MarshalAs(UnmanagedType.BStr)] String bstrTLB,
[In, MarshalAs(UnmanagedType.BStr)] String bstrPSDLL);
[DispId(0x0000001a)]
void GetEventClassesForIID([In] String bstrIID,
[In, Out, MarshalAs(UnmanagedType.SafeArray)] ref Object[] varCLSIDS,
[In, Out, MarshalAs(UnmanagedType.SafeArray)] ref Object[] varProgIDs,
[In, Out, MarshalAs(UnmanagedType.SafeArray)] ref Object[] varDescriptions);
[DispId(0x0000001b)]
[return: MarshalAs(UnmanagedType.Interface)]
Object GetCollectionByQuery2(
[In, MarshalAs(UnmanagedType.BStr)] String bstrCollectionName,
[In, MarshalAs(UnmanagedType.LPStruct)] Object pVarQueryStrings);
[DispId(0x0000001c)]
[return: MarshalAs(UnmanagedType.BStr)]
String GetApplicationInstanceIDFromProcessID([In, MarshalAs(UnmanagedType.I4)] int lProcessID);
[DispId(0x0000001d)]
void ShutdownApplicationInstances([In, MarshalAs(UnmanagedType.LPStruct)] Object pVarApplicationInstanceID);
[DispId(0x0000001e)]
void PauseApplicationInstances([In, MarshalAs(UnmanagedType.LPStruct)] Object pVarApplicationInstanceID);
[DispId(0x0000001f)]
void ResumeApplicationInstances([In, MarshalAs(UnmanagedType.LPStruct)] Object pVarApplicationInstanceID);
[DispId(0x00000020)]
void RecycleApplicationInstances(
[In, MarshalAs(UnmanagedType.LPStruct)] Object pVarApplicationInstanceID,
[In, MarshalAs(UnmanagedType.I4)] int lReasonCode);
[DispId(0x00000021)]
[return: MarshalAs(UnmanagedType.VariantBool)]
bool AreApplicationInstancesPaused([In, MarshalAs(UnmanagedType.LPStruct)] Object pVarApplicationInstanceID);
[DispId(0x00000022)]
[return: MarshalAs(UnmanagedType.BStr)]
String DumpApplicationInstance(
[In, MarshalAs(UnmanagedType.BStr)] String bstrApplicationInstanceID,
[In, MarshalAs(UnmanagedType.BStr)] String bstrDirectory,
[In, MarshalAs(UnmanagedType.I4)] int lMaxImages);
[DispId(0x00000023)]
[return: MarshalAs(UnmanagedType.VariantBool)]
bool IsApplicationInstanceDumpSupported();
[DispId(0x00000024)]
void CreateServiceForApplication(
[In, MarshalAs(UnmanagedType.BStr)] String bstrApplicationIDOrName,
[In, MarshalAs(UnmanagedType.BStr)] String bstrServiceName,
[In, MarshalAs(UnmanagedType.BStr)] String bstrStartType,
[In, MarshalAs(UnmanagedType.BStr)] String bstrErrorControl,
[In, MarshalAs(UnmanagedType.BStr)] String bstrDependencies,
[In, MarshalAs(UnmanagedType.BStr)] String bstrRunAs,
[In, MarshalAs(UnmanagedType.BStr)] String bstrPassword,
[In, MarshalAs(UnmanagedType.VariantBool)] bool bDesktopOk);
[DispId(0x00000025)]
void DeleteServiceForApplication([In, MarshalAs(UnmanagedType.BStr)] String bstrApplicationIDOrName);
[DispId(0x00000026)]
[return: MarshalAs(UnmanagedType.BStr)]
String GetPartitionID([In, MarshalAs(UnmanagedType.BStr)] String bstrApplicationIDOrName);
[DispId(0x00000027)]
[return: MarshalAs(UnmanagedType.BStr)]
String GetPartitionName([In, MarshalAs(UnmanagedType.BStr)] String bstrApplicationIDOrName);
[DispId(0x00000028)]
void CurrentPartition([In, MarshalAs(UnmanagedType.BStr)]String bstrPartitionIDOrName);
[DispId(0x00000029)]
[return: MarshalAs(UnmanagedType.BStr)]
String CurrentPartitionID();
[DispId(0x0000002A)]
[return: MarshalAs(UnmanagedType.BStr)]
String CurrentPartitionName();
[DispId(0x0000002B)]
[return: MarshalAs(UnmanagedType.BStr)]
String GlobalPartitionID();
[DispId(0x0000002C)]
void FlushPartitionCache();
[DispId(0x0000002D)]
void CopyApplications(
[In, MarshalAs(UnmanagedType.BStr)] String bstrSourcePartitionIDOrName,
[In, MarshalAs(UnmanagedType.LPStruct)] Object pVarApplicationID,
[In, MarshalAs(UnmanagedType.BStr)] String bstrDestinationPartitionIDOrName);
[DispId(0x0000002E)]
void CopyComponents(
[In, MarshalAs(UnmanagedType.BStr)] String bstrSourceApplicationIDOrName,
[In, MarshalAs(UnmanagedType.LPStruct)] Object pVarCLSIDOrProgID,
[In, MarshalAs(UnmanagedType.BStr)] String bstrDestinationApplicationIDOrName);
[DispId(0x0000002F)]
void MoveComponents(
[In, MarshalAs(UnmanagedType.BStr)] String bstrSourceApplicationIDOrName,
[In, MarshalAs(UnmanagedType.LPStruct)] Object pVarCLSIDOrProgID,
[In, MarshalAs(UnmanagedType.BStr)] String bstrDestinationApplicationIDOrName);
[DispId(0x00000030)]
void AliasComponent(
[In, MarshalAs(UnmanagedType.BStr)] String bstrSrcApplicationIDOrName,
[In, MarshalAs(UnmanagedType.BStr)] String bstrCLSIDOrProgID,
[In, MarshalAs(UnmanagedType.BStr)] String bstrDestApplicationIDOrName,
[In, MarshalAs(UnmanagedType.BStr)] String bstrNewProgId,
[In, MarshalAs(UnmanagedType.BStr)] String bstrNewClsid);
[DispId(0x00000031)]
[return: MarshalAs(UnmanagedType.Interface)]
Object IsSafeToDelete([In, MarshalAs(UnmanagedType.BStr)] String bstrDllName);
[DispId(0x00000032)]
void ImportUnconfiguredComponents(
[In, MarshalAs(UnmanagedType.BStr)] String bstrApplicationIDOrName,
[In, MarshalAs(UnmanagedType.LPStruct)] Object pVarCLSIDOrProgID,
[In, MarshalAs(UnmanagedType.LPStruct)] Object pVarComponentType);
[DispId(0x00000033)]
void PromoteUnconfiguredComponents(
[In, MarshalAs(UnmanagedType.BStr)] String bstrApplicationIDOrName,
[In, MarshalAs(UnmanagedType.LPStruct)] Object pVarCLSIDOrProgID,
[In, MarshalAs(UnmanagedType.LPStruct)] Object pVarComponentType);
[DispId(0x00000034)]
void ImportComponents(
[In, MarshalAs(UnmanagedType.BStr)] String bstrApplicationIDOrName,
[In, MarshalAs(UnmanagedType.LPStruct)] Object pVarCLSIDOrProgID,
[In, MarshalAs(UnmanagedType.LPStruct)] Object pVarComponentType);
[DispId(0x00000035)]
[return: MarshalAs(UnmanagedType.VariantBool)]
bool Is64BitCatalogServer();
[DispId(0x00000036)]
void ExportPartition(
[In, MarshalAs(UnmanagedType.BStr)] String bstrPartitionIDOrName,
[In, MarshalAs(UnmanagedType.BStr)] String bstrPartitionFileName,
[In, MarshalAs(UnmanagedType.I4)] int lOptions);
[DispId(0x00000037)]
void InstallPartition(
[In, MarshalAs(UnmanagedType.BStr)] String bstrFileName,
[In, MarshalAs(UnmanagedType.BStr)] String bstrDestDirectory,
[In, MarshalAs(UnmanagedType.I4)] int lOptions,
[In, MarshalAs(UnmanagedType.BStr)] String bstrUserID,
[In, MarshalAs(UnmanagedType.BStr)] String bstrPassword,
[In, MarshalAs(UnmanagedType.BStr)] String bstrRSN);
[DispId(0x00000038)]
[return: MarshalAs(UnmanagedType.IDispatch)]
Object QueryApplicationFile2([In, MarshalAs(UnmanagedType.BStr)] String bstrApplicationFile);
[DispId(0x00000039)]
[return: MarshalAs(UnmanagedType.I4)]
int GetComponentVersionCount([In, MarshalAs(UnmanagedType.BStr)] String bstrCLSIDOrProgID);
}
[ComImport]
[Guid("6EB22871-8A19-11D0-81B6-00A0C9231C29")]
internal interface ICatalogObject
{
[DispId(0x00000001)]
Object GetValue([In, MarshalAs(UnmanagedType.BStr)] String propName);
[DispId(0x00000001)]
void SetValue([In, MarshalAs(UnmanagedType.BStr)] String propName,
[In] Object value);
[DispId(0x00000002)]
Object Key();
[DispId(0x00000003)]
Object Name();
[DispId(0x00000004)]
[return: MarshalAs(UnmanagedType.VariantBool)]
bool IsPropertyReadOnly([In, MarshalAs(UnmanagedType.BStr)] String bstrPropName);
bool Valid
{
[DispId(0x00000005)]
[return: MarshalAs(UnmanagedType.VariantBool)]
get;
}
[DispId(0x00000006)]
[return: MarshalAs(UnmanagedType.VariantBool)]
bool IsPropertyWriteOnly([In, MarshalAs(UnmanagedType.BStr)] String bstrPropName);
}
[ComImport]
[Guid("6EB22872-8A19-11D0-81B6-00A0C9231C29")]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
internal interface ICatalogCollection
{
[DispId(unchecked((int)0xfffffffc))]
void GetEnumerator(out IEnumerator pEnum);
[DispId(0x00000001)]
[return: MarshalAs(UnmanagedType.Interface)]
Object Item([In] int lIndex);
[DispId(0x60020002)]
int Count();
[DispId(0x60020003)]
void Remove([In] int lIndex);
[DispId(0x60020004)]
[return: MarshalAs(UnmanagedType.Interface)]
Object Add();
[DispId(0x00000002)]
void Populate();
[DispId(0x00000003)]
int SaveChanges();
[DispId(0x00000004)]
[return: MarshalAs(UnmanagedType.Interface)]
Object GetCollection([In, MarshalAs(UnmanagedType.BStr)] String bstrCollName,
[In] Object varObjectKey);
[DispId(0x00000006)]
Object Name();
bool IsAddEnabled
{
[DispId(0x00000007)]
[return: MarshalAs(UnmanagedType.VariantBool)]
get;
}
bool IsRemoveEnabled
{
[DispId(0x00000008)]
[return: MarshalAs(UnmanagedType.VariantBool)]
get;
}
[DispId(0x00000009)]
[return: MarshalAs(UnmanagedType.Interface)]
Object GetUtilInterface();
int DataStoreMajorVersion
{
[DispId(0x0000000a)]
get;
}
int DataStoreMinorVersion
{
[DispId(0x0000000b)]
get;
}
void PopulateByKey([In, MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)]
Object[] aKeys);
[DispId(0x0000000d)]
void PopulateByQuery([In, MarshalAs(UnmanagedType.BStr)] String bstrQueryString,
[In] int lQueryType);
}
[ComImport]
[Guid("F618C514-DFB8-11D1-A2CF-00805FC79235")]
internal class xCatalog { }
}

View File

@ -0,0 +1,231 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.ComIntegration
{
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Runtime;
class ComCatalogObject
{
ICatalogObject catalogObject;
ICatalogCollection catalogCollection;
public ComCatalogObject(ICatalogObject catalogObject,
ICatalogCollection catalogCollection)
{
this.catalogObject = catalogObject;
this.catalogCollection = catalogCollection;
}
public object GetValue(string key)
{
return this.catalogObject.GetValue(key);
}
public string Name
{
get
{
return (string)(this.catalogObject.Name());
}
}
public ComCatalogCollection GetCollection(string collectionName)
{
ICatalogCollection collection;
collection = (ICatalogCollection)this.catalogCollection.GetCollection(
collectionName,
this.catalogObject.Key());
collection.Populate();
return new ComCatalogCollection(collection);
}
}
class ComCatalogCollection
{
ICatalogCollection catalogCollection;
public ComCatalogCollection(ICatalogCollection catalogCollection)
{
this.catalogCollection = catalogCollection;
}
public int Count
{
get
{
return this.catalogCollection.Count();
}
}
// (Not a property because I make a new object every time.)
public ComCatalogObject Item(int index)
{
ICatalogObject catalogObject;
catalogObject = (ICatalogObject)this.catalogCollection.Item(index);
return new ComCatalogObject(catalogObject, this.catalogCollection);
}
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
// This is kind of a half-baked IEnumerator implementation. It
// lets you use foreach(), but don't expect fancy things like
// InvalidOperationExceptions and such.
//
public struct Enumerator
{
ComCatalogCollection collection;
ComCatalogObject current;
int count;
public Enumerator(ComCatalogCollection collection)
{
this.collection = collection;
this.current = null;
this.count = -1;
}
public ComCatalogObject Current
{
get { return this.current; }
}
public bool MoveNext()
{
this.count++;
if (this.count >= collection.Count)
return false;
this.current = this.collection.Item(this.count);
return true;
}
public void Reset()
{
this.count = -1;
}
}
}
internal static class CatalogUtil
{
internal static string[] GetRoleMembers(
ComCatalogObject application,
ComCatalogCollection rolesCollection)
{
ComCatalogCollection applicationRoles;
applicationRoles = application.GetCollection("Roles");
// This is inefficient. If it turns into a
// performance problem, then we'll need to put a cache in
// somewhere.
//
List<string> roleMembers = new List<string>();
foreach (ComCatalogObject role in rolesCollection)
{
string roleName = (string)role.GetValue("Name");
// Find the role in the app roles list.
//
foreach (ComCatalogObject appRole in applicationRoles)
{
string appRoleName = (string)appRole.GetValue("Name");
if (roleName == appRoleName)
{
// Found it, put all of the user names into
// the role members list.
//
ComCatalogCollection users;
users = appRole.GetCollection("UsersInRole");
foreach (ComCatalogObject userObject in users)
{
string user = (string)userObject.GetValue("User");
roleMembers.Add(user);
}
break;
}
}
}
return roleMembers.ToArray();
}
internal static ComCatalogObject FindApplication(Guid applicationId)
{
ICatalog2 catalog = (ICatalog2)(new xCatalog());
ICatalogObject appObject = null;
ICatalogCollection partitionCollection = null;
try
{
partitionCollection = (ICatalogCollection)catalog.GetCollection(
"Partitions");
partitionCollection.Populate();
}
catch (COMException comException)
{
if (comException.ErrorCode != HR.COMADMIN_E_PARTITIONS_DISABLED)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(comException);
}
if (partitionCollection != null)
{
for (int i = 0; i < partitionCollection.Count(); i++)
{
ICatalogObject partition;
partition = (ICatalogObject)partitionCollection.Item(i);
ICatalogCollection appCollection;
appCollection = (ICatalogCollection)partitionCollection.GetCollection(
"Applications",
partition.Key());
appCollection.Populate();
appObject = FindApplication(appCollection, applicationId);
if (appObject != null)
return new ComCatalogObject(appObject, appCollection);
}
}
else
{
ICatalogCollection appCollection;
appCollection = (ICatalogCollection)catalog.GetCollection(
"Applications");
appCollection.Populate();
appObject = FindApplication(appCollection, applicationId);
if (appObject != null)
return new ComCatalogObject(appObject, appCollection);
}
return null;
}
static ICatalogObject FindApplication(ICatalogCollection appCollection,
Guid applicationId)
{
ICatalogObject appObject = null;
for (int i = 0; i < appCollection.Count(); i++)
{
appObject = (ICatalogObject)appCollection.Item(i);
Guid id = Fx.CreateGuid((string)appObject.GetValue("ID"));
if (id == applicationId)
return appObject;
}
return null;
}
}
}

View File

@ -0,0 +1,249 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.ComIntegration
{
using System;
using System.ServiceModel.Description;
using System.Reflection;
using System.Net;
using System.Security;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
internal class ChannelCredentials : IChannelCredentials, IDisposable
{
protected IProvideChannelBuilderSettings channelBuilderSettings;
internal ChannelCredentials(IProvideChannelBuilderSettings channelBuilderSettings)
{
this.channelBuilderSettings = channelBuilderSettings;
}
internal static ComProxy Create(IntPtr outer, IProvideChannelBuilderSettings channelBuilderSettings)
{
if (channelBuilderSettings == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.CannotCreateChannelOption)));
ChannelCredentials ChannelCredentials = null;
ComProxy proxy = null;
try
{
ChannelCredentials = new ChannelCredentials(channelBuilderSettings);
proxy = ComProxy.Create(outer, ChannelCredentials, ChannelCredentials);
return proxy;
}
finally
{
if (proxy == null)
{
if (ChannelCredentials != null)
((IDisposable)ChannelCredentials).Dispose();
}
}
}
void IDisposable.Dispose()
{
}
void IChannelCredentials.SetWindowsCredential(string domain, string userName, string password, int impersonationLevel, bool allowNtlm)
{
lock (channelBuilderSettings)
{
KeyedByTypeCollection<IEndpointBehavior> behaviors = channelBuilderSettings.Behaviors;
NetworkCredential newCredentials = null;
if ((!String.IsNullOrEmpty(domain)) || (!String.IsNullOrEmpty(userName)) || (!String.IsNullOrEmpty(password)))
{
if (String.IsNullOrEmpty(userName))
{
userName = "";
}
System.ServiceModel.Security.SecurityUtils.PrepareNetworkCredential();
newCredentials = new NetworkCredential(userName, password, domain);
}
ClientCredentials channelCredentials = behaviors.Find<ClientCredentials>();
if (channelCredentials == null)
{
channelCredentials = new ClientCredentials();
behaviors.Add(channelCredentials);
}
channelCredentials.Windows.AllowedImpersonationLevel = (TokenImpersonationLevel)impersonationLevel;
// To disable AllowNtlm warning.
#pragma warning disable 618
channelCredentials.Windows.AllowNtlm = allowNtlm;
#pragma warning restore 618
channelCredentials.Windows.ClientCredential = newCredentials;
}
}
void IChannelCredentials.SetUserNameCredential(string userName, string password)
{
lock (channelBuilderSettings)
{
KeyedByTypeCollection<IEndpointBehavior> behaviors = channelBuilderSettings.Behaviors;
ClientCredentials channelCredentials = behaviors.Find<ClientCredentials>();
if (channelCredentials == null)
{
channelCredentials = new ClientCredentials();
behaviors.Add(channelCredentials);
}
channelCredentials.UserName.UserName = userName;
channelCredentials.UserName.Password = password;
}
}
void IChannelCredentials.SetServiceCertificateAuthentication(string storeLocation, string revocationMode, string certificationValidationMode)
{
lock (channelBuilderSettings)
{
StoreLocation location = (StoreLocation)Enum.Parse(typeof(StoreLocation), storeLocation);
X509RevocationMode mode = (X509RevocationMode)Enum.Parse(typeof(X509RevocationMode), revocationMode);
X509CertificateValidationMode validationMode = X509ServiceCertificateAuthentication.DefaultCertificateValidationMode;
if (!String.IsNullOrEmpty(certificationValidationMode))
validationMode = (X509CertificateValidationMode)Enum.Parse(typeof(X509CertificateValidationMode), certificationValidationMode);
KeyedByTypeCollection<IEndpointBehavior> behaviors = channelBuilderSettings.Behaviors;
ClientCredentials channelCredentials = behaviors.Find<ClientCredentials>();
if (channelCredentials == null)
{
channelCredentials = new ClientCredentials();
behaviors.Add(channelCredentials);
}
channelCredentials.ServiceCertificate.Authentication.TrustedStoreLocation = location;
channelCredentials.ServiceCertificate.Authentication.RevocationMode = mode;
channelCredentials.ServiceCertificate.Authentication.CertificateValidationMode = validationMode;
}
}
void IChannelCredentials.SetClientCertificateFromStore(string storeLocation, string storeName, string findType, object findValue)
{
lock (channelBuilderSettings)
{
StoreLocation location = (StoreLocation)Enum.Parse(typeof(StoreLocation), storeLocation);
StoreName name = (StoreName)Enum.Parse(typeof(StoreName), storeName);
X509FindType type = (X509FindType)Enum.Parse(typeof(X509FindType), findType);
KeyedByTypeCollection<IEndpointBehavior> behaviors = channelBuilderSettings.Behaviors;
ClientCredentials channelCredentials = behaviors.Find<ClientCredentials>();
if (channelCredentials == null)
{
channelCredentials = new ClientCredentials();
behaviors.Add(channelCredentials);
}
channelCredentials.ClientCertificate.SetCertificate(location, name, type, findValue);
}
}
void IChannelCredentials.SetClientCertificateFromStoreByName(string subjectName, string storeLocation, string storeName)
{
((IChannelCredentials)this).SetClientCertificateFromStore(storeLocation, storeName, X509CertificateInitiatorClientCredential.DefaultFindType.ToString("G"), subjectName);
}
void IChannelCredentials.SetClientCertificateFromFile(string fileName, string password, string keyStorageFlags)
{
lock (channelBuilderSettings)
{
KeyedByTypeCollection<IEndpointBehavior> behaviors = channelBuilderSettings.Behaviors;
X509Certificate2 cert;
if (!String.IsNullOrEmpty(keyStorageFlags))
{
X509KeyStorageFlags flags = (X509KeyStorageFlags)Enum.Parse(typeof(X509KeyStorageFlags), keyStorageFlags);
cert = new X509Certificate2(fileName, password, flags);
}
else
{
cert = new X509Certificate2(fileName, password);
}
ClientCredentials channelCredentials = behaviors.Find<ClientCredentials>();
if (channelCredentials == null)
{
channelCredentials = new ClientCredentials();
behaviors.Add(channelCredentials);
}
channelCredentials.ClientCertificate.Certificate = cert;
}
}
void IChannelCredentials.SetDefaultServiceCertificateFromStore(string storeLocation, string storeName, string findType, object findValue)
{
lock (channelBuilderSettings)
{
StoreLocation location = (StoreLocation)Enum.Parse(typeof(StoreLocation), storeLocation);
StoreName name = (StoreName)Enum.Parse(typeof(StoreName), storeName);
X509FindType type = (X509FindType)Enum.Parse(typeof(X509FindType), findType);
KeyedByTypeCollection<IEndpointBehavior> behaviors = channelBuilderSettings.Behaviors;
ClientCredentials channelCredentials = behaviors.Find<ClientCredentials>();
if (channelCredentials == null)
{
channelCredentials = new ClientCredentials();
behaviors.Add(channelCredentials);
}
channelCredentials.ServiceCertificate.SetDefaultCertificate(location, name, type, findValue);
}
}
void IChannelCredentials.SetDefaultServiceCertificateFromStoreByName(string subjectName, string storeLocation, string storeName)
{
((IChannelCredentials)this).SetDefaultServiceCertificateFromStore(storeLocation, storeName, X509CertificateInitiatorClientCredential.DefaultFindType.ToString("G"), subjectName);
}
void IChannelCredentials.SetDefaultServiceCertificateFromFile(string fileName, string password, string keyStorageFlags)
{
lock (channelBuilderSettings)
{
KeyedByTypeCollection<IEndpointBehavior> behaviors = channelBuilderSettings.Behaviors;
X509Certificate2 cert;
if (!String.IsNullOrEmpty(keyStorageFlags))
{
X509KeyStorageFlags flags = (X509KeyStorageFlags)Enum.Parse(typeof(X509KeyStorageFlags), keyStorageFlags);
cert = new X509Certificate2(fileName, password, flags);
}
else
{
cert = new X509Certificate2(fileName, password);
}
ClientCredentials channelCredentials = behaviors.Find<ClientCredentials>();
if (channelCredentials == null)
{
channelCredentials = new ClientCredentials();
behaviors.Add(channelCredentials);
}
channelCredentials.ServiceCertificate.DefaultCertificate = cert;
}
}
void IChannelCredentials.SetIssuedToken(string localIssuerAddres, string localIssuerBindingType, string localIssuerBinding)
{
lock (channelBuilderSettings)
{
Binding binding = null;
binding = ConfigLoader.LookupBinding(localIssuerBindingType, localIssuerBinding);
KeyedByTypeCollection<IEndpointBehavior> behaviors = channelBuilderSettings.Behaviors;
ClientCredentials channelCredentials = behaviors.Find<ClientCredentials>();
if (channelCredentials == null)
{
channelCredentials = new ClientCredentials();
behaviors.Add(channelCredentials);
}
channelCredentials.IssuedToken.LocalIssuerAddress = new EndpointAddress(localIssuerAddres);
channelCredentials.IssuedToken.LocalIssuerBinding = binding;
}
}
}
}

View File

@ -0,0 +1,51 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.ComIntegration
{
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Channels;
internal class ChannelOptions : IChannelOptions, IDisposable
{
protected IProvideChannelBuilderSettings channelBuilderSettings;
internal ChannelOptions(IProvideChannelBuilderSettings channelBuilderSettings)
{
this.channelBuilderSettings = channelBuilderSettings;
}
internal static ComProxy Create(IntPtr outer, IProvideChannelBuilderSettings channelBuilderSettings)
{
if (channelBuilderSettings == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.CannotCreateChannelOption)));
ChannelOptions channelOptions = null;
ComProxy proxy = null;
try
{
channelOptions = new ChannelOptions(channelBuilderSettings);
proxy = ComProxy.Create(outer, channelOptions, channelOptions);
return proxy;
}
finally
{
if (proxy == null)
{
if (channelOptions != null)
((IDisposable)channelOptions).Dispose();
}
}
}
void IDisposable.Dispose()
{
}
}
}

View File

@ -0,0 +1,178 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.ComIntegration
{
using System;
using System.IO;
using System.Reflection;
using System.Runtime;
using System.Runtime.InteropServices;
using System.ServiceModel;
// this is a heavily modified version of the Win32ManifestGenerator found in the CLR
class ComIntegrationManifestGenerator : MarshalByRefObject
{
internal static void GenerateManifestCollectionFile(Guid[] manifests, String strAssemblyManifestFileName, String assemblyName)
{
String title = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
String asmTitle = "<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">";
String asmEnd = "</assembly>";
String path = Path.GetDirectoryName(strAssemblyManifestFileName);
if (!String.IsNullOrEmpty(path) && !Directory.Exists(path))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(System.ServiceModel.ComIntegration.Error.DirectoryNotFound(path));
}
Stream s = null;
try
{
// manifest title
s = File.Create(strAssemblyManifestFileName);
WriteUTFChars(s, title + Environment.NewLine);
WriteUTFChars(s, asmTitle + Environment.NewLine);
WriteUTFChars(s, "<assemblyIdentity" + Environment.NewLine, 4);
WriteUTFChars(s, "name=\"" + assemblyName + "\"" + Environment.NewLine, 8);
WriteUTFChars(s, "version=\"1.0.0.0\"/>" + Environment.NewLine, 8);
for (int i = 0; i < manifests.Length; i++)
{
WriteUTFChars(s, "<dependency>" + Environment.NewLine, 4);
WriteUTFChars(s, "<dependentAssembly>" + Environment.NewLine, 8);
WriteUTFChars(s, "<assemblyIdentity" + Environment.NewLine, 12);
WriteUTFChars(s, "name=\"" + manifests[i].ToString() + "\"" + Environment.NewLine, 16);
WriteUTFChars(s, "version=\"1.0.0.0\"/>" + Environment.NewLine, 16);
WriteUTFChars(s, "</dependentAssembly>" + Environment.NewLine, 8);
WriteUTFChars(s, "</dependency>" + Environment.NewLine, 4);
}
WriteUTFChars(s, asmEnd);
}
catch (Exception e)
{
if (e is NullReferenceException || e is SEHException)
{
throw;
}
s.Close();
File.Delete(strAssemblyManifestFileName);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(System.ServiceModel.ComIntegration.Error.ManifestCreationFailed(strAssemblyManifestFileName, e.Message));
}
s.Close();
}
internal static void GenerateWin32ManifestFile(Type[] aTypes, String strAssemblyManifestFileName, String assemblyName)
{
String title = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
String asmTitle = "<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">";
String path = Path.GetDirectoryName(strAssemblyManifestFileName);
if (!String.IsNullOrEmpty(path) && !Directory.Exists(path))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(System.ServiceModel.ComIntegration.Error.DirectoryNotFound(path));
}
Stream s = null;
try
{
// manifest title
s = File.Create(strAssemblyManifestFileName);
WriteUTFChars(s, title + Environment.NewLine);
WriteUTFChars(s, asmTitle + Environment.NewLine);
WriteUTFChars(s, "<assemblyIdentity" + Environment.NewLine, 4);
WriteUTFChars(s, "name=\"" + assemblyName + "\"" + Environment.NewLine, 8);
WriteUTFChars(s, "version=\"1.0.0.0\"/>" + Environment.NewLine, 8);
AsmCreateWin32ManifestFile(s, aTypes);
}
catch (Exception e)
{
if (e is NullReferenceException || e is SEHException)
{
throw;
}
s.Close();
File.Delete(strAssemblyManifestFileName);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(System.ServiceModel.ComIntegration.Error.ManifestCreationFailed(strAssemblyManifestFileName, e.Message));
}
s.Close();
}
static void AsmCreateWin32ManifestFile(Stream s, Type[] aTypes)
{
String asmEnd = "</assembly>";
WriteTypes(s, aTypes, 4);
WriteUTFChars(s, asmEnd);
}
static void WriteTypes(Stream s, Type[] aTypes, int offset)
{
RegistrationServices regServices = new RegistrationServices();
String name = null;
Assembly asm = Assembly.GetExecutingAssembly();
string asmver = asm.ImageRuntimeVersion;
foreach (Type t in aTypes)
{
// only registrable managed types will show up in the manifest file
if (!regServices.TypeRequiresRegistration(t))
{
throw Fx.AssertAndThrow("User defined types must be registrable");
}
String strClsId = "{" + Marshal.GenerateGuidForType(t).ToString().ToUpperInvariant() + "}";
name = t.FullName;
// this type is a com imported type or Record
if (regServices.TypeRepresentsComType(t) || t.IsValueType)
{
WriteUTFChars(s, "<clrSurrogate" + Environment.NewLine, offset);
// attribute clsid
WriteUTFChars(s, " clsid=\"" + strClsId + "\"" + Environment.NewLine, offset);
// attribute class
WriteUTFChars(s, " name=\"" + name + "\"" + Environment.NewLine, offset);
// clr version
WriteUTFChars(s, " runtimeVersion=\"" + asmver + "\">" + Environment.NewLine, offset);
WriteUTFChars(s, "</clrSurrogate>" + Environment.NewLine, offset);
}
}
}
static void WriteUTFChars(Stream s, String value, int offset)
{
for (int i = 0; i < offset; i++)
{
WriteUTFChars(s, " ");
}
WriteUTFChars(s, value);
}
static void WriteUTFChars(Stream s, String value)
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(value);
s.Write(bytes, 0, bytes.Length);
}
}
}

View File

@ -0,0 +1,56 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.ComIntegration
{
using System;
using System.ServiceModel.Channels;
using System.ServiceModel;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Description;
using System.Collections.Generic;
class ComPlusContractBehavior : IContractBehavior
{
ServiceInfo info;
public ComPlusContractBehavior(ServiceInfo info)
{
this.info = info;
}
public void Validate(ContractDescription description, ServiceEndpoint endpoint)
{
}
public void AddBindingParameters(ContractDescription description,
ServiceEndpoint endpoint,
BindingParameterCollection parameters)
{
}
public void ApplyDispatchBehavior(ContractDescription description,
ServiceEndpoint endpoint,
DispatchRuntime dispatch)
{
dispatch.InstanceProvider = new ComPlusInstanceProvider(info);
dispatch.InstanceContextInitializers.Add(new ComPlusInstanceContextInitializer(info));
foreach (DispatchOperation operation in dispatch.Operations)
{
operation.CallContextInitializers.Add(
new ComPlusThreadInitializer(
description,
operation,
info));
}
}
public void ApplyClientBehavior(ContractDescription description,
ServiceEndpoint endpoint,
ClientRuntime proxy)
{
return;
}
}
}

View File

@ -0,0 +1,430 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.ComIntegration
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using ServiceModelSR = System.ServiceModel.SR;
using WsdlNS = System.Web.Services.Description;
static class ComPlusServiceHostTrace
{
public static void Trace(TraceEventType type, int traceCode, string description, ServiceInfo info)
{
if (DiagnosticUtility.ShouldTrace(type))
{
ComPlusServiceHostSchema record = new ComPlusServiceHostSchema(info.AppID, info.Clsid);
TraceUtility.TraceEvent(type, traceCode, ServiceModelSR.GetString(description), record);
}
}
public static void Trace(TraceEventType type, int traceCode, string description, ServiceInfo info, ContractDescription contract)
{
if (DiagnosticUtility.ShouldTrace(type))
{
XmlQualifiedName contractQName = new XmlQualifiedName(contract.Name, contract.Namespace);
ComPlusServiceHostCreatedServiceContractSchema record = new
ComPlusServiceHostCreatedServiceContractSchema(info.AppID, info.Clsid,
contractQName, contract.ContractType.ToString());
TraceUtility.TraceEvent(type, traceCode, ServiceModelSR.GetString(description), record);
}
}
public static void Trace(TraceEventType type, int traceCode, string description, ServiceInfo info, ServiceDescription service)
{
if (DiagnosticUtility.ShouldTrace(type))
{
WsdlExporter exporter = new WsdlExporter();
string serviceNs = NamingHelper.DefaultNamespace;
XmlQualifiedName serviceQName = new XmlQualifiedName("comPlusService", serviceNs);
exporter.ExportEndpoints(service.Endpoints, serviceQName);
WsdlNS.ServiceDescription wsdl = exporter.GeneratedWsdlDocuments[serviceNs];
ComPlusServiceHostStartedServiceDetailsSchema record =
new ComPlusServiceHostStartedServiceDetailsSchema(info.AppID, info.Clsid, wsdl);
TraceUtility.TraceEvent(type, traceCode, ServiceModelSR.GetString(description), record);
}
}
public static void Trace(TraceEventType type, int traceCode, string description, ServiceInfo info, ServiceEndpointCollection endpointCollection)
{
if (DiagnosticUtility.ShouldTrace(type))
{
foreach (ServiceEndpoint endpoint in endpointCollection)
{
ComPlusServiceHostCreatedServiceEndpointSchema record =
new ComPlusServiceHostCreatedServiceEndpointSchema(info.AppID, info.Clsid, endpoint.Contract.Name,
endpoint.Address.Uri, endpoint.Binding.Name);
TraceUtility.TraceEvent(type, traceCode, ServiceModelSR.GetString(description), record);
}
}
}
}
static class ComPlusDllHostInitializerTrace
{
public static void Trace(TraceEventType type, int traceCode, string description, Guid appid)
{
if (DiagnosticUtility.ShouldTrace(type))
{
ComPlusDllHostInitializerSchema record =
new ComPlusDllHostInitializerSchema(appid);
TraceUtility.TraceEvent(type, traceCode, ServiceModelSR.GetString(description), record);
}
}
public static void Trace(TraceEventType type, int traceCode, string description, Guid appid, Guid clsid, ServiceElement service)
{
if (DiagnosticUtility.ShouldTrace(type))
{
foreach (ServiceEndpointElement endpointElement in service.Endpoints)
{
ComPlusDllHostInitializerAddingHostSchema record =
new ComPlusDllHostInitializerAddingHostSchema(appid, clsid, service.BehaviorConfiguration, service.Name,
endpointElement.Address.ToString(), endpointElement.BindingConfiguration, endpointElement.BindingName, endpointElement.BindingNamespace,
endpointElement.Binding, endpointElement.Contract);
TraceUtility.TraceEvent(type, traceCode, ServiceModelSR.GetString(description), record);
}
}
}
}
static class ComPlusTLBImportTrace
{
public static void Trace(TraceEventType type, int traceCode, string description, Guid iid, Guid typeLibraryID)
{
if (DiagnosticUtility.ShouldTrace(type))
{
ComPlusTLBImportSchema record =
new ComPlusTLBImportSchema(iid, typeLibraryID);
TraceUtility.TraceEvent(type, traceCode, ServiceModelSR.GetString(description), record);
}
}
public static void Trace(TraceEventType type, int traceCode, string description, Guid iid, Guid typeLibraryID, string assembly)
{
if (DiagnosticUtility.ShouldTrace(type))
{
ComPlusTLBImportFromAssemblySchema record =
new ComPlusTLBImportFromAssemblySchema(iid, typeLibraryID, assembly);
TraceUtility.TraceEvent(type, traceCode, ServiceModelSR.GetString(description), record);
}
}
public static void Trace(TraceEventType type, int traceCode, string description, Guid iid, Guid typeLibraryID, ImporterEventKind eventKind, int eventCode, string eventMsg)
{
if (DiagnosticUtility.ShouldTrace(type))
{
ComPlusTLBImportConverterEventSchema record =
new ComPlusTLBImportConverterEventSchema(iid, typeLibraryID, eventKind, eventCode, eventMsg);
TraceUtility.TraceEvent(type, traceCode, ServiceModelSR.GetString(description), record);
}
}
}
static class ComPlusInstanceCreationTrace
{
public static void Trace(TraceEventType type, int traceCode, string description, ServiceInfo info, Message message, Guid incomingTransactionID)
{
if (DiagnosticUtility.ShouldTrace(type))
{
WindowsIdentity callerIdentity = MessageUtil.GetMessageIdentity(message);
Uri from = null;
if (message.Headers.From != null)
from = message.Headers.From.Uri;
ComPlusInstanceCreationRequestSchema record =
new ComPlusInstanceCreationRequestSchema(info.AppID, info.Clsid,
from, incomingTransactionID, callerIdentity.Name);
TraceUtility.TraceEvent(type, traceCode, ServiceModelSR.GetString(description), record, null, null, message);
}
}
public static void Trace(TraceEventType type, int traceCode, string description, ServiceInfo info, Message message, int instanceID, Guid incomingTransactionID)
{
if (DiagnosticUtility.ShouldTrace(type))
{
WindowsIdentity callerIdentity = MessageUtil.GetMessageIdentity(message);
Uri from = null;
if (message.Headers.From != null)
from = message.Headers.From.Uri;
ComPlusInstanceCreationSuccessSchema record =
new ComPlusInstanceCreationSuccessSchema(info.AppID, info.Clsid,
from, incomingTransactionID, callerIdentity.Name, instanceID);
TraceUtility.TraceEvent(type, traceCode, ServiceModelSR.GetString(description), record, null, null, message);
}
}
public static void Trace(TraceEventType type, int traceCode, string description, ServiceInfo info, InstanceContext instanceContext, int instanceID)
{
if (DiagnosticUtility.ShouldTrace(type))
{
ComPlusInstanceReleasedSchema record =
new ComPlusInstanceReleasedSchema(info.AppID, info.Clsid, instanceID);
TraceUtility.TraceEvent(type, traceCode, ServiceModelSR.GetString(description), record);
}
}
}
static class ComPlusActivityTrace
{
internal static readonly Guid IID_IComThreadingInfo = new Guid("000001ce-0000-0000-C000-000000000046");
internal static readonly Guid IID_IObjectContextInfo = new Guid("75B52DDB-E8ED-11d1-93AD-00AA00BA3258");
public static void Trace(TraceEventType type, int traceCode, string description)
{
if (DiagnosticUtility.ShouldTrace(type))
{
Guid guidLogicalThreadID = Guid.Empty;
Guid guidActivityID = Guid.Empty;
IComThreadingInfo comThreadingInfo;
comThreadingInfo = (IComThreadingInfo)SafeNativeMethods.CoGetObjectContext(IID_IComThreadingInfo);
if (comThreadingInfo != null)
{
comThreadingInfo.GetCurrentLogicalThreadId(out guidLogicalThreadID);
IObjectContextInfo contextInfo = comThreadingInfo as IObjectContextInfo;
if (contextInfo != null)
{
contextInfo.GetActivityId(out guidActivityID);
}
}
ComPlusActivitySchema record =
new ComPlusActivitySchema(guidActivityID, guidLogicalThreadID,
System.Threading.Thread.CurrentThread.ManagedThreadId, SafeNativeMethods.GetCurrentThreadId());
TraceUtility.TraceEvent(type, traceCode, ServiceModelSR.GetString(description), record);
}
}
}
static class ComPlusMethodCallTrace
{
static readonly Guid IID_IComThreadingInfo = new Guid("000001ce-0000-0000-C000-000000000046");
static readonly Guid IID_IObjectContextInfo = new Guid("75B52DDB-E8ED-11d1-93AD-00AA00BA3258");
public static void Trace(TraceEventType type, int traceCode, string description, ServiceInfo info, Uri from, string action, string callerIdentity,
Guid iid, int instanceID, bool traceContextTransaction)
{
if (DiagnosticUtility.ShouldTrace(type))
{
ComPlusMethodCallSchema record = null;
Guid guidContextTrsansactionID = Guid.Empty;
if (traceContextTransaction)
{
IComThreadingInfo comThreadingInfo;
comThreadingInfo = (IComThreadingInfo)SafeNativeMethods.CoGetObjectContext(IID_IComThreadingInfo);
if (comThreadingInfo != null)
{
IObjectContextInfo contextInfo = comThreadingInfo as IObjectContextInfo;
if (contextInfo != null)
{
if (contextInfo.IsInTransaction())
contextInfo.GetTransactionId(out guidContextTrsansactionID);
}
}
if (guidContextTrsansactionID != Guid.Empty)
{
record = new ComPlusMethodCallContextTxSchema(from, info.AppID, info.Clsid, iid, action,
instanceID, System.Threading.Thread.CurrentThread.ManagedThreadId, SafeNativeMethods.GetCurrentThreadId(), callerIdentity, guidContextTrsansactionID);
}
}
else
{
record = new ComPlusMethodCallSchema(from, info.AppID, info.Clsid, iid, action,
instanceID, System.Threading.Thread.CurrentThread.ManagedThreadId, SafeNativeMethods.GetCurrentThreadId(), callerIdentity);
}
if (record != null)
TraceUtility.TraceEvent(type, traceCode, ServiceModelSR.GetString(description), record);
}
}
public static void Trace(TraceEventType type, int traceCode, string description, ServiceInfo info, Uri from, string action, string callerIdentity,
Guid iid, int instanceID, Guid incomingTransactionID, Guid currentTransactionID)
{
if (DiagnosticUtility.ShouldTrace(type))
{
ComPlusMethodCallTxMismatchSchema record = new ComPlusMethodCallTxMismatchSchema(from, info.AppID, info.Clsid, iid, action,
instanceID, System.Threading.Thread.CurrentThread.ManagedThreadId, SafeNativeMethods.GetCurrentThreadId(), callerIdentity,
incomingTransactionID, currentTransactionID);
TraceUtility.TraceEvent(type, traceCode, ServiceModelSR.GetString(description), record);
}
}
public static void Trace(TraceEventType type, int traceCode, string description, ServiceInfo info, Uri from, string action, string callerIdentity,
Guid iid, int instanceID, Guid guidIncomingTransactionID)
{
if (DiagnosticUtility.ShouldTrace(type))
{
ComPlusMethodCallNewTxSchema record = new ComPlusMethodCallNewTxSchema(from, info.AppID, info.Clsid, iid, action,
instanceID, System.Threading.Thread.CurrentThread.ManagedThreadId, SafeNativeMethods.GetCurrentThreadId(), callerIdentity,
guidIncomingTransactionID);
TraceUtility.TraceEvent(type, traceCode, ServiceModelSR.GetString(description), record);
}
}
}
static class ComPlusServiceMonikerTrace
{
public static void Trace(TraceEventType type, int traceCode, string description, Dictionary<MonikerHelper.MonikerAttribute, string> propertyTable)
{
if (DiagnosticUtility.ShouldTrace(type))
{
string address = null;
string contract = null;
string binding = null;
string bindingConfig = null;
string spnIdentity = null;
string upnIdentity = null;
string dnsIdentity = null;
string wsdlText = null;
string mexAddress = null;
string mexBinding = null;
string mexBindingConfiguration = null;
string mexSpnIdentity = null;
string mexUpnIdentity = null;
string mexDnsIdentity = null;
string contractNamespace = null;
string bindingNamespace = null;
WsdlNS.ServiceDescription wsdl = null;
propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Wsdl, out wsdlText);
propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Contract, out contract);
propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Address, out address);
propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Binding, out binding);
propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.BindingConfiguration, out bindingConfig);
propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.SpnIdentity, out spnIdentity);
propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.UpnIdentity, out upnIdentity);
propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.DnsIdentity, out dnsIdentity);
propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexAddress, out mexAddress);
propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexBinding, out mexBinding);
propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexBindingConfiguration, out mexBindingConfiguration);
propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexSpnIdentity, out mexSpnIdentity);
propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexUpnIdentity, out mexUpnIdentity);
propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexDnsIdentity, out mexDnsIdentity);
propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.ContractNamespace, out contractNamespace);
propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.BindingNamespace, out bindingNamespace);
if (!String.IsNullOrEmpty(wsdlText))
{
TextReader reader = new StringReader(wsdlText);
wsdl = WsdlNS.ServiceDescription.Read(reader);
}
ComPlusServiceMonikerSchema record = new ComPlusServiceMonikerSchema(address, contract, contractNamespace, wsdl, spnIdentity, upnIdentity,
dnsIdentity, binding, bindingConfig, bindingNamespace, mexAddress, mexBinding, mexBindingConfiguration, mexSpnIdentity, mexUpnIdentity, mexDnsIdentity);
TraceUtility.TraceEvent(type, traceCode, ServiceModelSR.GetString(description), record);
}
}
}
static class ComPlusWsdlChannelBuilderTrace
{
public static void Trace(TraceEventType type, int traceCode, string description, XmlQualifiedName bindingQname, XmlQualifiedName contractQname,
WsdlNS.ServiceDescription wsdl, ContractDescription contract, Binding binding, XmlSchemas schemas)
{
if (DiagnosticUtility.ShouldTrace(type))
{
string name = "Service";
if (wsdl.Name != null)
name = wsdl.Name;
Type contractType = contract.ContractType;
XmlQualifiedName serviceName = new XmlQualifiedName(name, wsdl.TargetNamespace);
foreach (XmlSchema schema in schemas)
{
ComPlusWsdlChannelBuilderSchema record = new ComPlusWsdlChannelBuilderSchema(bindingQname, contractQname, serviceName,
(contractType != null) ? contractType.ToString() : null, (binding != null) ? (binding.GetType()).ToString() : null, schema);
TraceUtility.TraceEvent(type, traceCode, ServiceModelSR.GetString(description), record);
}
}
}
}
static class ComPlusMexChannelBuilderMexCompleteTrace
{
public static void Trace(TraceEventType type, int traceCode, string description, ServiceEndpointCollection serviceEndpointsRetrieved)
{
if (DiagnosticUtility.ShouldTrace(type))
{
int nIndex = 0;
ComPlusMexBuilderMetadataRetrievedEndpoint[] endpoints = new ComPlusMexBuilderMetadataRetrievedEndpoint[serviceEndpointsRetrieved.Count];
foreach (ServiceEndpoint endpoint in serviceEndpointsRetrieved)
{
endpoints[nIndex++] = new ComPlusMexBuilderMetadataRetrievedEndpoint(endpoint);
}
ComPlusMexBuilderMetadataRetrievedSchema record = new ComPlusMexBuilderMetadataRetrievedSchema(endpoints);
TraceUtility.TraceEvent(type, traceCode, ServiceModelSR.GetString(description), record);
}
}
}
static class ComPlusMexChannelBuilderTrace
{
public static void Trace(TraceEventType type, int traceCode, string description, ContractDescription contract, Binding binding, string address)
{
if (DiagnosticUtility.ShouldTrace(type))
{
ComPlusMexChannelBuilderSchema record = new ComPlusMexChannelBuilderSchema(contract.Name, contract.Namespace, binding.Name, binding.Namespace, address);
TraceUtility.TraceEvent(type, traceCode, ServiceModelSR.GetString(description), record);
}
}
}
static class ComPlusTypedChannelBuilderTrace
{
public static void Trace(TraceEventType type, int v, string description, Type contractType, Binding binding)
{
if (DiagnosticUtility.ShouldTrace(type))
{
ComPlusTypedChannelBuilderSchema record = new ComPlusTypedChannelBuilderSchema(contractType.ToString(),
(binding != null) ? (binding.GetType()).ToString() : null);
TraceUtility.TraceEvent(type, v, ServiceModelSR.GetString(description), record);
}
}
}
static class ComPlusChannelCreatedTrace
{
public static void Trace(TraceEventType type, int traceCode, string description, Uri address, Type contractType)
{
if (DiagnosticUtility.ShouldTrace(type))
{
ComPlusChannelCreatedSchema record = new ComPlusChannelCreatedSchema(address, (contractType != null) ? contractType.ToString() : null);
TraceUtility.TraceEvent(type, traceCode, ServiceModelSR.GetString(description), record);
}
}
}
static class ComPlusDispatchMethodTrace
{
public static void Trace(TraceEventType type, int traceCode, string description,
Dictionary<UInt32, System.ServiceModel.ComIntegration.DispatchProxy.MethodInfo> dispToOperationDescription)
{
if (DiagnosticUtility.ShouldTrace(type))
{
UInt32 dispIndex = 10;
System.ServiceModel.ComIntegration.DispatchProxy.MethodInfo methodInfo = null;
while (dispToOperationDescription.TryGetValue(dispIndex, out methodInfo))
{
ComPlusDispatchMethodSchema record = new ComPlusDispatchMethodSchema(methodInfo.opDesc.Name, methodInfo.paramList, methodInfo.ReturnVal);
TraceUtility.TraceEvent(type, traceCode, ServiceModelSR.GetString(description), record);
dispIndex++;
}
}
}
}
static class ComPlusTxProxyTrace
{
public static void Trace(TraceEventType type, int traceCode, string description, Guid appid, Guid clsid, Guid transactionID, int instanceID)
{
if (DiagnosticUtility.ShouldTrace(type))
{
ComPlusTxProxySchema record = new ComPlusTxProxySchema(appid, clsid, transactionID, instanceID);
TraceUtility.TraceEvent(type, traceCode, ServiceModelSR.GetString(description), record);
}
}
}
}

View File

@ -0,0 +1,244 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.ComIntegration
{
using System;
using System.EnterpriseServices;
using System.IO;
using System.Reflection;
using System.Runtime;
using System.Runtime.InteropServices;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Transactions;
class ComPlusInstanceContextInitializer : IInstanceContextInitializer
{
ServiceInfo info;
static readonly Guid IID_IServiceActivity = new Guid("67532E0C-9E2F-4450-A354-035633944E17");
static readonly Guid DefaultPartitionId = new Guid("41E90F3E-56C1-4633-81C3-6E8BAC8BDD70");
private static object manifestLock = new object();
private static string manifestFileName = Guid.NewGuid().ToString();
static ComPlusInstanceContextInitializer()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += new ResolveEventHandler(ResolveAssembly);
}
public ComPlusInstanceContextInitializer(ServiceInfo info)
{
this.info = info;
if (this.info.HasUdts())
{
string tempPath = String.Empty;
lock (manifestLock)
{
try
{
tempPath = Path.GetTempPath();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(System.ServiceModel.ComIntegration.Error.CannotAccessDirectory(tempPath));
}
string manifestDirectory = tempPath + this.info.AppID.ToString();
if (Directory.Exists(manifestDirectory))
Directory.Delete(manifestDirectory, true);
}
}
}
public void Initialize(InstanceContext instanceContext, Message message)
{
object serviceConfig = null;
serviceConfig = SetupServiceConfig(instanceContext, message);
IServiceActivity activity;
activity = (IServiceActivity)SafeNativeMethods.CoCreateActivity(
serviceConfig,
IID_IServiceActivity);
ComPlusSynchronizationContext syncContext;
bool postSynchronous = (this.info.ThreadingModel ==
ThreadingModel.MTA);
syncContext = new ComPlusSynchronizationContext(activity,
postSynchronous);
instanceContext.SynchronizationContext = syncContext;
instanceContext.Closing += this.OnInstanceContextClosing;
Marshal.ReleaseComObject(serviceConfig);
}
public void OnInstanceContextClosing(object sender, EventArgs args)
{
InstanceContext instanceContext = (InstanceContext)sender;
ComPlusSynchronizationContext syncContext;
syncContext = (ComPlusSynchronizationContext)instanceContext.SynchronizationContext;
syncContext.Dispose();
}
static Assembly ResolveAssembly(object sender, ResolveEventArgs args)
{
int indexOfComma = args.Name.IndexOf(",", StringComparison.Ordinal);
if (indexOfComma != -1)
{
Guid assemblyGuid = Guid.Empty;
string assemblyGuidString = args.Name.Substring(0, indexOfComma).Trim().ToLowerInvariant();
if (Guid.TryParse(assemblyGuidString, out assemblyGuid))
{
return TypeCacheManager.Provider.ResolveAssembly(assemblyGuid);
}
}
return null;
}
object SetupServiceConfig(InstanceContext instanceContext, Message message)
{
object serviceConfig = new CServiceConfig();
// Threading
//
IServiceThreadPoolConfig threadPoolConfig;
threadPoolConfig = (IServiceThreadPoolConfig)(serviceConfig);
switch (this.info.ThreadingModel)
{
case ThreadingModel.MTA:
threadPoolConfig.SelectThreadPool(ThreadPoolOption.MTA);
break;
case ThreadingModel.STA:
threadPoolConfig.SelectThreadPool(ThreadPoolOption.STA);
break;
default:
Fx.Assert("Unexpected threading model");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.UnexpectedThreadingModel());
}
threadPoolConfig.SetBindingInfo(BindingOption.BindingToPoolThread);
// SxS activation context properties
//
// Manifest for VARIANT UDT types
//
// this only gets executed if we actually have UDTs
if (this.info.HasUdts())
{
IServiceSxsConfig sxsConfig = serviceConfig as IServiceSxsConfig;
if (sxsConfig == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(System.ServiceModel.ComIntegration.Error.QFENotPresent());
}
lock (manifestLock)
{
string tempPath = String.Empty;
try
{
tempPath = Path.GetTempPath();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(System.ServiceModel.ComIntegration.Error.CannotAccessDirectory(tempPath));
}
string manifestDirectory = tempPath + this.info.AppID.ToString() + @"\";
if (!Directory.Exists(manifestDirectory))
{
try
{
Directory.CreateDirectory(manifestDirectory);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(System.ServiceModel.ComIntegration.Error.CannotAccessDirectory(manifestDirectory));
}
Guid[] assemblyGuids = this.info.Assemblies;
ComIntegrationManifestGenerator.GenerateManifestCollectionFile(assemblyGuids, manifestDirectory + manifestFileName + @".manifest", manifestFileName);
foreach (Guid g in assemblyGuids)
{
Type[] types = this.info.GetTypes(g);
if (types.Length > 0)
{
String guidStr = g.ToString();
ComIntegrationManifestGenerator.GenerateWin32ManifestFile(types, manifestDirectory + guidStr + @".manifest", guidStr);
}
}
}
sxsConfig.SxsConfig(CSC_SxsConfig.CSC_NewSxs);
sxsConfig.SxsName(manifestFileName + @".manifest");
sxsConfig.SxsDirectory(manifestDirectory);
}
}
// Partitions
//
if (this.info.PartitionId != DefaultPartitionId)
{
IServicePartitionConfig partitionConfig;
partitionConfig = (IServicePartitionConfig)(serviceConfig);
partitionConfig.PartitionConfig(PartitionOption.New);
partitionConfig.PartitionID(this.info.PartitionId);
}
// Transactions
//
IServiceTransactionConfig transactionConfig;
transactionConfig = (IServiceTransactionConfig)(serviceConfig);
transactionConfig.ConfigureTransaction(
TransactionConfig.NoTransaction);
if ((this.info.TransactionOption == TransactionOption.Required) ||
(this.info.TransactionOption == TransactionOption.Supported))
{
Transaction messageTransaction = null;
messageTransaction = MessageUtil.GetMessageTransaction(message);
if (messageTransaction != null)
{
TransactionProxy proxy = new TransactionProxy(info.AppID, info.Clsid);
proxy.SetTransaction(messageTransaction);
instanceContext.Extensions.Add(proxy);
IServiceSysTxnConfig sysTxnconfing = (IServiceSysTxnConfig)transactionConfig;
IntPtr pUnk = TransactionProxyBuilder.CreateTransactionProxyTearOff(proxy);
sysTxnconfing.ConfigureBYOTSysTxn(pUnk);
Marshal.Release(pUnk);
}
}
return serviceConfig;
}
}
}

View File

@ -0,0 +1,181 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.ComIntegration
{
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.EnterpriseServices;
using System.Runtime;
using System.Runtime.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Dispatcher;
using SafeCloseHandle = System.IdentityModel.SafeCloseHandle;
class ComPlusInstanceProvider : IInstanceProvider
{
ServiceInfo info;
static readonly Guid IID_IUnknown = new Guid("00000000-0000-0000-C000-000000000046");
public ComPlusInstanceProvider(ServiceInfo info)
{
this.info = info;
}
public object GetInstance(InstanceContext instanceContext)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ComPlusInstanceProviderRequiresMessage0)));
}
// We call ContextUtil.IsInTransaction and ContextUtil.TransactionId, from a non-APTCA assembly. There is no identified security vulnerability with these properties,
// so we can't justify adding a demand for full trust here. Both properties call code marked as usafe, but no user input is passed to it and results are not
// cached (so there is no leak as a side-effect).
[SuppressMessage(FxCop.Category.Security, FxCop.Rule.AptcaMethodsShouldOnlyCallAptcaMethods)]
public object GetInstance(InstanceContext instanceContext, Message message)
{
object result = null;
Guid incomingTransactionID = Guid.Empty;
if (ContextUtil.IsInTransaction)
incomingTransactionID = ContextUtil.TransactionId;
ComPlusInstanceCreationTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationInstanceCreationRequest,
SR.TraceCodeComIntegrationInstanceCreationRequest, this.info, message, incomingTransactionID);
WindowsIdentity callerIdentity = null;
callerIdentity = MessageUtil.GetMessageIdentity(message);
WindowsImpersonationContext impersonateContext = null;
try
{
try
{
if (this.info.HostingMode ==
HostingMode.WebHostOutOfProcess)
{
if (SecurityUtils.IsAtleastImpersonationToken(new SafeCloseHandle(callerIdentity.Token, false)))
impersonateContext = callerIdentity.Impersonate();
else
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new COMException (SR.GetString(SR.BadImpersonationLevelForOutOfProcWas), HR.ERROR_BAD_IMPERSONATION_LEVEL));
}
CLSCTX clsctx = CLSCTX.SERVER;
if (PlatformSupportsBitness && (this.info.HostingMode ==
HostingMode.WebHostOutOfProcess))
{
if (this.info.Bitness == Bitness.Bitness32)
{
clsctx |= CLSCTX.ACTIVATE_32_BIT_SERVER;
}
else
{
clsctx |= CLSCTX.ACTIVATE_64_BIT_SERVER;
}
}
result = SafeNativeMethods.CoCreateInstance(
info.Clsid,
null,
clsctx,
IID_IUnknown);
}
finally
{
if (impersonateContext != null)
impersonateContext.Undo();
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
Uri from = null;
if (message.Headers.From != null)
from = message.Headers.From.Uri;
DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error,
(ushort)System.Runtime.Diagnostics.EventLogCategory.ComPlus,
(uint)System.Runtime.Diagnostics.EventLogEventId.ComPlusInstanceCreationError,
from == null ? string.Empty : from.ToString(),
this.info.AppID.ToString(),
this.info.Clsid.ToString(),
incomingTransactionID.ToString(),
callerIdentity.Name,
e.ToString());
throw TraceUtility.ThrowHelperError(e, message);
}
TransactionProxy proxy = instanceContext.Extensions.Find<TransactionProxy>();
if (proxy != null)
{
proxy.InstanceID = result.GetHashCode();
}
ComPlusInstanceCreationTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationInstanceCreationSuccess,
SR.TraceCodeComIntegrationInstanceCreationSuccess, this.info, message, result.GetHashCode(), incomingTransactionID);
return result;
}
public void ReleaseInstance(InstanceContext instanceContext, object instance)
{
int instanceID = instance.GetHashCode();
IDisposable disposable = instance as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
else
{
// All ServicedComponents are disposable, so we don't
// have to worry about getting a ServicedComponent
// here.
//
Marshal.ReleaseComObject(instance);
}
ComPlusInstanceCreationTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationInstanceReleased,
SR.TraceCodeComIntegrationInstanceReleased, this.info, instanceContext, instanceID);
}
static bool platformSupportsBitness;
static bool platformSupportsBitnessSet;
static bool PlatformSupportsBitness
{
get
{
if (!platformSupportsBitnessSet)
{
// Bitness is supported on Windows 2003 Server SP1 or
// greater.
//
if (Environment.OSVersion.Version.Major > 5)
platformSupportsBitness = true;
else if (Environment.OSVersion.Version.Major == 5)
{
if (Environment.OSVersion.Version.Minor > 2)
platformSupportsBitness = true;
else if (Environment.OSVersion.Version.Minor == 2)
{
if (!string.IsNullOrEmpty(Environment.OSVersion.ServicePack))
platformSupportsBitness = true;
}
}
platformSupportsBitnessSet = true;
}
return platformSupportsBitness;
}
}
}
}

View File

@ -0,0 +1,114 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#pragma warning disable 1634, 1691
namespace System.ServiceModel.ComIntegration
{
using System;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Description;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Diagnostics;
using System.Runtime.InteropServices;
using System.ServiceModel;
using System.ServiceModel.Configuration;
using System.Diagnostics;
using System.ServiceModel.Diagnostics;
abstract class ComPlusServiceHost : ServiceHostBase
{
ServiceInfo info;
protected void Initialize (Guid clsid,
ServiceElement service,
ComCatalogObject applicationObject,
ComCatalogObject classObject,
HostingMode hostingMode)
{
VerifyFunctionality();
this.info = new ServiceInfo(clsid,
service,
applicationObject,
classObject,
hostingMode);
base.InitializeDescription(new UriSchemeKeyedCollection());
}
protected override void ApplyConfiguration()
{
}
protected override ServiceDescription CreateDescription(out IDictionary<string, ContractDescription> implementedContracts)
{
try
{
ComPlusServiceLoader loader = new ComPlusServiceLoader(this.info);
ServiceDescription description = loader.Load(this);
implementedContracts = null;
return description;
}
catch (Exception e)
{
DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error,
(ushort)System.Runtime.Diagnostics.EventLogCategory.ComPlus,
(uint)System.Runtime.Diagnostics.EventLogEventId.ComPlusServiceHostStartingServiceError,
this.info.AppID.ToString(),
this.info.Clsid.ToString(),
e.ToString());
throw;
}
}
protected override void InitializeRuntime()
{
ComPlusServiceHostTrace.Trace(TraceEventType.Information, TraceCode.ComIntegrationServiceHostStartingService,
SR.TraceCodeComIntegrationServiceHostStartingService, this.info);
try
{
DispatcherBuilder dispatcherBuilder = new DispatcherBuilder();
dispatcherBuilder.InitializeServiceHost(this.Description, this);
}
catch (Exception e)
{
if (System.ServiceModel.DiagnosticUtility.ShouldTraceError)
{
DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error,
(ushort)System.Runtime.Diagnostics.EventLogCategory.ComPlus,
(uint)System.Runtime.Diagnostics.EventLogEventId.ComPlusServiceHostStartingServiceError,
this.info.AppID.ToString(),
this.info.Clsid.ToString(),
e.ToString());
}
throw;
}
ComPlusServiceHostTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationServiceHostStartedServiceDetails,
SR.TraceCodeComIntegrationServiceHostStartedServiceDetails, this.info, this.Description);
ComPlusServiceHostTrace.Trace(TraceEventType.Information, TraceCode.ComIntegrationServiceHostStartedService,
SR.TraceCodeComIntegrationServiceHostStartedService, this.info);
}
protected override void OnClose(TimeSpan timeout)
{
ComPlusServiceHostTrace.Trace(TraceEventType.Information, TraceCode.ComIntegrationServiceHostStoppingService,
SR.TraceCodeComIntegrationServiceHostStoppingService, this.info);
base.OnClose(timeout);
ComPlusServiceHostTrace.Trace(TraceEventType.Information, TraceCode.ComIntegrationServiceHostStoppedService,
SR.TraceCodeComIntegrationServiceHostStoppedService, this.info);
}
protected void VerifyFunctionality()
{
object serviceConfig = new CServiceConfig();
IServiceSysTxnConfig sysTxnconfing = serviceConfig as IServiceSysTxnConfig;
if (sysTxnconfing == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(System.ServiceModel.ComIntegration.Error.QFENotPresent());
}
}
}
}

View File

@ -0,0 +1,120 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.ComIntegration
{
using System;
using System.ServiceModel.Description;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Diagnostics;
using System.ServiceModel.Diagnostics;
class ComPlusServiceLoader
{
ServiceInfo info;
ConfigLoader configLoader;
ComPlusTypeLoader typeLoader;
public ComPlusServiceLoader (ServiceInfo info)
{
this.info = info;
this.typeLoader = new ComPlusTypeLoader(info);
this.configLoader = new ConfigLoader(typeLoader);
}
public ServiceDescription Load(ServiceHostBase host)
{
ServiceDescription service = new ServiceDescription(this.info.ServiceName);
// ServiceBehaviorAttribute needs to go first in the behaviors collection (before config stuff)
AddBehaviors(service);
this.configLoader.LoadServiceDescription(host, service, this.info.ServiceElement, host.LoadConfigurationSectionHelper);
ValidateConfigInstanceSettings(service);
ComPlusServiceHostTrace.Trace(TraceEventType.Information, TraceCode.ComIntegrationServiceHostCreatedServiceEndpoint,
SR.TraceCodeComIntegrationServiceHostCreatedServiceEndpoint, this.info, service.Endpoints);
return service;
}
void AddBehaviors(ServiceDescription service)
{
// The philosophy here is to respect settings from configuration
// At the moment, none of the settings we care about can be modified
// through configuration. That may change in the future.
// However, we never want to silently overwrite a user's configuration.
// So we should either accept overrides or reject them, but never
// silently update them.
//
ServiceBehaviorAttribute serviceBehavior = EnsureBehaviorAttribute(service);
serviceBehavior.InstanceProvider = new ComPlusInstanceProvider(this.info);
serviceBehavior.InstanceContextMode = InstanceContextMode.Single;
// SHOULD: There is no reason to not allow concurrency at this level
serviceBehavior.ConcurrencyMode = ConcurrencyMode.Multiple;
serviceBehavior.UseSynchronizationContext = false;
service.Behaviors.Add(new SecurityCookieModeValidator());
if (AspNetEnvironment.Enabled)
{
AspNetCompatibilityRequirementsAttribute aspNetCompatibilityRequirements = service.Behaviors.Find<AspNetCompatibilityRequirementsAttribute>();
if (aspNetCompatibilityRequirements == null)
{
aspNetCompatibilityRequirements = new AspNetCompatibilityRequirementsAttribute();
service.Behaviors.Add(aspNetCompatibilityRequirements);
}
}
}
ServiceBehaviorAttribute EnsureBehaviorAttribute(ServiceDescription service)
{
ServiceBehaviorAttribute serviceBehavior;
if (service.Behaviors.Contains(typeof(ServiceBehaviorAttribute)))
{
serviceBehavior = (ServiceBehaviorAttribute)service.Behaviors[typeof(ServiceBehaviorAttribute)];
}
else
{
serviceBehavior = new ServiceBehaviorAttribute();
service.Behaviors.Insert(0, serviceBehavior);
}
return serviceBehavior;
}
void ValidateConfigInstanceSettings(ServiceDescription service)
{
ServiceBehaviorAttribute serviceBehavior = EnsureBehaviorAttribute(service);
foreach (ServiceEndpoint endpoint in service.Endpoints)
{
if (endpoint != null && !endpoint.InternalIsSystemEndpoint(service))
{
if (endpoint.Contract.SessionMode == SessionMode.Required)
{
if (serviceBehavior.InstanceContextMode == InstanceContextMode.PerCall)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(System.ServiceModel.ComIntegration.Error.InconsistentSessionRequirements());
serviceBehavior.InstanceContextMode = InstanceContextMode.PerSession;
}
else
{
if (serviceBehavior.InstanceContextMode == InstanceContextMode.PerSession)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(System.ServiceModel.ComIntegration.Error.InconsistentSessionRequirements());
serviceBehavior.InstanceContextMode = InstanceContextMode.PerCall;
}
}
}
if (serviceBehavior.InstanceContextMode == InstanceContextMode.Single)
serviceBehavior.InstanceContextMode = InstanceContextMode.PerSession;
}
}
}

View File

@ -0,0 +1,110 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.ComIntegration
{
using System;
using System.Diagnostics;
using System.Runtime;
using System.Runtime.InteropServices;
using System.ServiceModel.Diagnostics;
using System.Threading;
class ComPlusSynchronizationContext : SynchronizationContext
{
IServiceActivity activity;
bool postSynchronous;
public ComPlusSynchronizationContext(IServiceActivity activity,
bool postSynchronous)
{
this.activity = activity;
this.postSynchronous = postSynchronous;
}
public override void Send(SendOrPostCallback d, Object state)
{
Fx.Assert("Send should never be called");
}
public override void Post(SendOrPostCallback d, Object state)
{
ComPlusActivityTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationEnteringActivity,
SR.TraceCodeComIntegrationEnteringActivity);
ServiceCall call = new ServiceCall(d, state);
if (this.postSynchronous)
{
this.activity.SynchronousCall(call);
}
else
{
this.activity.AsynchronousCall(call);
}
ComPlusActivityTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationLeftActivity,
SR.TraceCodeComIntegrationLeftActivity);
}
public void Dispose()
{
while (Marshal.ReleaseComObject(this.activity) > 0);
}
class ServiceCall : IServiceCall
{
SendOrPostCallback callback;
Object state;
public ServiceCall(SendOrPostCallback callback,
Object state)
{
this.callback = callback;
this.state = state;
}
public void OnCall()
{
ServiceModelActivity activity = null;
try
{
Guid guidLogicalThreadID = Guid.Empty;
if (DiagnosticUtility.ShouldUseActivity)
{
IComThreadingInfo comThreadingInfo;
comThreadingInfo = (IComThreadingInfo)SafeNativeMethods.CoGetObjectContext(ComPlusActivityTrace.IID_IComThreadingInfo);
if (comThreadingInfo != null)
{
comThreadingInfo.GetCurrentLogicalThreadId(out guidLogicalThreadID);
activity = ServiceModelActivity.CreateBoundedActivity(guidLogicalThreadID);
}
ServiceModelActivity.Start(activity, SR.GetString(SR.TransferringToComplus, guidLogicalThreadID.ToString()), ActivityType.TransferToComPlus);
}
ComPlusActivityTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationExecutingCall, SR.TraceCodeComIntegrationExecutingCall);
this.callback(this.state);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
DiagnosticUtility.InvokeFinalHandler(e);
}
finally
{
if (activity != null)
{
activity.Dispose();
activity = null;
}
}
}
}
}
}

View File

@ -0,0 +1,327 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.ComIntegration
{
using System;
using System.Runtime.Diagnostics;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Description;
using System.Security.Principal;
using System.ServiceModel;
using System.Transactions;
using System.Diagnostics;
using System.ServiceModel.Diagnostics;
using System.EnterpriseServices;
using SR = System.ServiceModel.SR;
using System.Globalization;
class ComPlusThreadInitializer : ICallContextInitializer
{
ServiceInfo info;
ComPlusAuthorization comAuth;
Guid iid;
public ComPlusThreadInitializer(ContractDescription contract,
DispatchOperation operation,
ServiceInfo info)
{
this.info = info;
iid = contract.ContractType.GUID;
if (info.CheckRoles)
{
string[] serviceRoleMembers = null;
string[] contractRoleMembers = null;
string[] operationRoleMembers = null;
// Figure out the role members we want...
//
serviceRoleMembers = info.ComponentRoleMembers;
foreach (ContractInfo contractInfo in this.info.Contracts)
{
if (contractInfo.IID == iid)
{
contractRoleMembers = contractInfo.InterfaceRoleMembers;
foreach (OperationInfo opInfo in contractInfo.Operations)
{
if (opInfo.Name == operation.Name)
{
operationRoleMembers = opInfo.MethodRoleMembers;
break;
}
}
if (operationRoleMembers == null)
{
// Did not find the operation
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(
SR.GetString(SR.ComOperationNotFound,
contract.Name,
operation.Name)));
}
break;
}
}
this.comAuth = new ComPlusAuthorization(serviceRoleMembers,
contractRoleMembers,
operationRoleMembers);
}
}
public object BeforeInvoke(
InstanceContext instanceContext,
IClientChannel channel,
Message message)
{
ComPlusServerSecurity serverSecurity = null;
WindowsImpersonationContext impersonateContext = null;
bool errorTraced = false;
WindowsIdentity identity = null;
Uri from = null;
object instance = null;
int instanceID = 0;
string action = null;
TransactionProxy proxy = null;
Transaction tx = null;
Guid incomingTransactionID = Guid.Empty;
// The outer try block is to comply with FXCOP's WrapVulnerableFinallyClausesInOuterTry rule.
try
{
try
{
identity = MessageUtil.GetMessageIdentity(message);
if (message.Headers.From != null)
from = message.Headers.From.Uri;
instance = instanceContext.GetServiceInstance(message);
instanceID = instance.GetHashCode();
action = message.Headers.Action;
ComPlusMethodCallTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationInvokingMethod,
SR.TraceCodeComIntegrationInvokingMethod, this.info, from, action, identity.Name, iid, instanceID, false);
// Security
//
if (this.info.CheckRoles)
{
if (!this.comAuth.IsAuthorizedForOperation(identity))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.CallAccessDenied());
}
}
if (this.info.HostingMode != HostingMode.WebHostOutOfProcess)
{
// NOTE: This has the side effect of setting up
// the COM server security thing, so be sure
// to clear it with Dispose() eventually.
//
serverSecurity = new ComPlusServerSecurity(identity,
this.info.CheckRoles);
}
// Transactions
//
proxy = instanceContext.Extensions.Find<TransactionProxy>();
if (proxy != null)
{
// This makes the Tx header Understood.
tx = MessageUtil.GetMessageTransaction(message);
if (tx != null)
{
incomingTransactionID = tx.TransactionInformation.DistributedIdentifier;
}
try
{
if (tx != null)
{
proxy.SetTransaction(tx);
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.TransactionMismatch());
}
ComPlusMethodCallTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationInvokingMethodNewTransaction,
SR.TraceCodeComIntegrationInvokingMethodNewTransaction, this.info, from, action, identity.Name, iid, instanceID, incomingTransactionID);
}
catch (FaultException e)
{
Transaction txProxy = proxy.CurrentTransaction;
Guid currentTransactionID = Guid.Empty;
if (txProxy != null)
currentTransactionID = txProxy.TransactionInformation.DistributedIdentifier;
string identityName = String.Empty;
if (null != identity)
identityName = identity.Name;
DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error,
(ushort)System.Runtime.Diagnostics.EventLogCategory.ComPlus,
(uint)System.Runtime.Diagnostics.EventLogEventId.ComPlusInvokingMethodFailedMismatchedTransactions,
incomingTransactionID.ToString("B").ToUpperInvariant(),
currentTransactionID.ToString("B").ToUpperInvariant(),
from.ToString(),
this.info.AppID.ToString("B").ToUpperInvariant(),
this.info.Clsid.ToString("B").ToUpperInvariant(),
iid.ToString(),
action,
instanceID.ToString(CultureInfo.InvariantCulture),
System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(CultureInfo.InvariantCulture),
SafeNativeMethods.GetCurrentThreadId().ToString(CultureInfo.InvariantCulture),
identityName,
e.ToString());
errorTraced = true;
throw;
}
}
else
{
ComPlusMethodCallTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationInvokingMethodContextTransaction,
SR.TraceCodeComIntegrationInvokingMethodContextTransaction, this.info, from, action, identity.Name, iid, instanceID, true);
}
// Impersonation
//
if (this.info.HostingMode == HostingMode.WebHostOutOfProcess)
{
impersonateContext = identity.Impersonate();
}
CorrelationState correlationState;
correlationState = new CorrelationState(impersonateContext,
serverSecurity,
from,
action,
identity.Name,
instanceID);
impersonateContext = null;
serverSecurity = null;
return correlationState;
}
finally
{
if (impersonateContext != null)
impersonateContext.Undo();
if (serverSecurity != null)
((IDisposable)serverSecurity).Dispose();
}
}
catch (Exception e)
{
if (errorTraced == false)
{
if (DiagnosticUtility.ShouldTraceError)
{
DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error,
(ushort)System.Runtime.Diagnostics.EventLogCategory.ComPlus,
(uint)System.Runtime.Diagnostics.EventLogEventId.ComPlusInvokingMethodFailed,
from == null ? string.Empty : from.ToString(),
this.info.AppID.ToString("B").ToUpperInvariant(),
this.info.Clsid.ToString("B").ToUpperInvariant(),
iid.ToString("B").ToUpperInvariant(),
action,
instanceID.ToString(CultureInfo.InvariantCulture),
System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(CultureInfo.InvariantCulture),
SafeNativeMethods.GetCurrentThreadId().ToString(CultureInfo.InvariantCulture),
identity.Name,
e.ToString());
}
}
throw;
}
}
public void AfterInvoke(object correlationState)
{
CorrelationState state = (CorrelationState)correlationState;
if (state != null)
{
ComPlusMethodCallTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationInvokedMethod,
SR.TraceCodeComIntegrationInvokedMethod, this.info, state.From, state.Action, state.CallerIdentity, iid, state.InstanceID, false);
state.Cleanup();
}
}
class CorrelationState
{
WindowsImpersonationContext impersonationContext;
ComPlusServerSecurity serverSecurity;
Uri from;
string action;
string callerIdentity;
int instanceID;
public CorrelationState(WindowsImpersonationContext context,
ComPlusServerSecurity serverSecurity,
Uri from,
string action,
string callerIdentity,
int instanceID)
{
this.impersonationContext = context;
this.serverSecurity = serverSecurity;
this.from = from;
this.action = action;
this.callerIdentity = callerIdentity;
this.instanceID = instanceID;
}
public Uri From
{
get
{
return this.from;
}
}
public string Action
{
get
{
return this.action;
}
}
public string CallerIdentity
{
get
{
return this.callerIdentity;
}
}
public int InstanceID
{
get
{
return this.instanceID;
}
}
public void Cleanup()
{
if (this.impersonationContext != null)
this.impersonationContext.Undo();
if (this.serverSecurity != null)
((IDisposable)this.serverSecurity).Dispose();
}
}
}
}

View File

@ -0,0 +1,21 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.ComIntegration
{
using System;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Xml;
using System.ServiceModel.Dispatcher;
static class ComPlusTraceRecord
{
public static void SerializeRecord (XmlWriter xmlWriter, object o)
{
DataContractSerializer serializer = DataContractSerializerDefaults.CreateSerializer(((o == null) ? typeof(object) : o.GetType()), DataContractSerializerDefaults.MaxItemsInObjectGraph);
serializer.WriteObject(xmlWriter, o);
}
}
}

View File

@ -0,0 +1,417 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.ComIntegration
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.EnterpriseServices;
using System.Reflection;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Dispatcher;
using System.Xml;
using SR = System.ServiceModel.SR;
class ComPlusTypeLoader : IContractResolver
{
ServiceInfo info;
bool transactionFlow;
ITypeCacheManager interfaceResolver;
Dictionary<Guid, ContractDescription> contracts;
public ComPlusTypeLoader(ServiceInfo info)
{
this.info = info;
this.transactionFlow = info.TransactionOption == TransactionOption.Required ||
info.TransactionOption == TransactionOption.Supported;
this.interfaceResolver = new TypeCacheManager();
this.contracts = new Dictionary<Guid, ContractDescription>();
}
void ValidateInterface(Guid iid)
{
// Filter known invalid IIDs
if (!ComPlusTypeValidator.IsValidInterface(iid))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(SR.GetString(SR.InvalidWebServiceInterface, iid)));
}
// Filter out interfaces with no configured methods
bool configuredInterface = false;
foreach (ContractInfo contractInfo in this.info.Contracts)
{
if (contractInfo.IID == iid)
{
if (contractInfo.Operations.Count == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(SR.GetString(SR.RequireConfiguredMethods, iid)));
}
configuredInterface = true;
break;
}
}
// Filter out interfaces that aren't configured at all
if (!configuredInterface)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(SR.GetString(SR.RequireConfiguredInterfaces, iid)));
}
}
ContractDescription CreateContractDescriptionInternal(Guid iid, Type type)
{
ComContractElement contractConfigElement = ConfigLoader.LookupComContract(iid);
if (contractConfigElement == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(SR.GetString(SR.InterfaceNotFoundInConfig, iid)));
if (String.IsNullOrEmpty(contractConfigElement.Name) || String.IsNullOrEmpty(contractConfigElement.Namespace))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(SR.GetString(SR.CannotHaveNullOrEmptyNameOrNamespaceForIID, iid)));
ContractDescription contract = new ContractDescription(contractConfigElement.Name, contractConfigElement.Namespace);
contract.ContractType = type;
contract.SessionMode = contractConfigElement.RequiresSession ? SessionMode.Required : SessionMode.Allowed;
bool methodFound = false;
List<Guid> guidList = new List<Guid>();
foreach (ComPersistableTypeElement typeElement in contractConfigElement.PersistableTypes)
{
Guid typeGuid = Fx.CreateGuid(typeElement.ID);
guidList.Add(typeGuid);
}
IDataContractSurrogate contractSurrogate = null;
// We create a surrogate when the persistable types config section is there
// even if we have no types that we allow.
// That way we have control over the error when the client tries to make a call
// persistable type.
if (guidList.Count > 0 || contractConfigElement.PersistableTypes.EmitClear)
{
contractSurrogate = new DataContractSurrogateForPersistWrapper(guidList.ToArray());
}
foreach (ComMethodElement configMethod in contractConfigElement.ExposedMethods)
{
methodFound = false;
foreach (MethodInfo method in type.GetMethods())
{
if (method.Name == configMethod.ExposedMethod)
{
OperationDescription operation = CreateOperationDescription(contract, method, contractConfigElement, (null != contractSurrogate));
ConfigureOperationDescriptionBehaviors(operation, contractSurrogate);
contract.Operations.Add(operation);
methodFound = true;
break;
}
}
if (!methodFound)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(SR.GetString(SR.MethodGivenInConfigNotFoundOnInterface, configMethod.ExposedMethod, iid)));
}
if (contract.Operations.Count == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(SR.GetString(SR.NoneOfTheMethodsForInterfaceFoundInConfig, iid)));
ConfigureContractDescriptionBehaviors(contract);
return contract;
}
void ConfigureContractDescriptionBehaviors(ContractDescription contract)
{
// OperationSelectorBehavior
contract.Behaviors.Add(new OperationSelectorBehavior());
// ComPlusContractBehavior
ComPlusContractBehavior comPlusContractBehavior = new ComPlusContractBehavior(this.info);
contract.Behaviors.Add(comPlusContractBehavior);
}
void ConfigureOperationDescriptionBehaviors(OperationDescription operation, IDataContractSurrogate contractSurrogate)
{
// DataContractSerializerOperationBehavior
DataContractSerializerOperationBehavior contractSerializer = new DataContractSerializerOperationBehavior(operation, TypeLoader.DefaultDataContractFormatAttribute);
if (null != contractSurrogate)
{
contractSerializer.DataContractSurrogate = contractSurrogate;
}
operation.Behaviors.Add(contractSerializer);
// OperationInvokerBehavior
operation.Behaviors.Add(new OperationInvokerBehavior());
if (info.TransactionOption == TransactionOption.Supported || info.TransactionOption == TransactionOption.Required)
{
operation.Behaviors.Add(new TransactionFlowAttribute(TransactionFlowOption.Allowed));
}
// OperationBehaviorAttribute
OperationBehaviorAttribute operationBehaviorAttribute = new OperationBehaviorAttribute();
operationBehaviorAttribute.TransactionAutoComplete = true;
operationBehaviorAttribute.TransactionScopeRequired = false;
operation.Behaviors.Add(operationBehaviorAttribute);
}
//
// Note - the code below this line a paraphrase of the SM reflection code in TypeLoader.cs
// Ideally we would be re-using their code, but our assumptions are too disjoint
// for that to be realistic at the time of writing (12/2004).
//
OperationDescription CreateOperationDescription(ContractDescription contract, MethodInfo methodInfo, ComContractElement config, bool allowReferences)
{
XmlName operationName = new XmlName(ServiceReflector.GetLogicalName(methodInfo));
XmlName returnValueName = TypeLoader.GetReturnValueName(operationName);
if (ServiceReflector.IsBegin(methodInfo) || ServiceReflector.IsTask(methodInfo))
{
Fx.Assert("No async operations allowed");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.NoAsyncOperationsAllowed());
}
if (contract.Operations.FindAll(operationName.EncodedName).Count != 0)
{
Fx.Assert("Duplicate operation name");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.DuplicateOperation());
}
OperationDescription operationDescription = new OperationDescription(operationName.EncodedName, contract);
operationDescription.SyncMethod = methodInfo;
operationDescription.IsInitiating = true;
operationDescription.IsTerminating = false;
operationDescription.KnownTypes.Add(typeof(Array));
operationDescription.KnownTypes.Add(typeof(DBNull));
operationDescription.KnownTypes.Add(typeof(CurrencyWrapper));
operationDescription.KnownTypes.Add(typeof(ErrorWrapper));
if (allowReferences)
operationDescription.KnownTypes.Add(typeof(PersistStreamTypeWrapper));
foreach (ComUdtElement udt in config.UserDefinedTypes)
{
Type knownType;
Guid typeLibID = Fx.CreateGuid(udt.TypeLibID);
TypeCacheManager.Provider.FindOrCreateType(typeLibID, udt.TypeLibVersion, Fx.CreateGuid(udt.TypeDefID), out knownType, false);
this.info.AddUdt(knownType, typeLibID);
operationDescription.KnownTypes.Add(knownType);
}
string ns = contract.Namespace;
XmlQualifiedName contractQName = new XmlQualifiedName(contract.Name, ns);
string requestAction = NamingHelper.GetMessageAction(contractQName,
operationName.DecodedName,
null,
false);
string responseAction = NamingHelper.GetMessageAction(contractQName,
operationName.DecodedName,
null,
true);
MessageDescription inMessage = CreateIncomingMessageDescription(contract,
methodInfo,
ns,
requestAction,
allowReferences);
MessageDescription outMessage = CreateOutgoingMessageDescription(contract,
methodInfo,
returnValueName,
ns,
responseAction,
allowReferences);
operationDescription.Messages.Add(inMessage);
operationDescription.Messages.Add(outMessage);
return operationDescription;
}
MessageDescription CreateIncomingMessageDescription(ContractDescription contract,
MethodInfo methodInfo,
string ns,
string action,
bool allowReferences)
{
ParameterInfo[] parameters = ServiceReflector.GetInputParameters(methodInfo, false);
return CreateParameterMessageDescription(contract,
parameters,
null,
null,
null,
methodInfo.Name,
ns,
action,
MessageDirection.Input,
allowReferences);
}
MessageDescription CreateOutgoingMessageDescription(ContractDescription contract,
MethodInfo methodInfo,
XmlName returnValueName,
string ns,
string action,
bool allowReferences)
{
ParameterInfo[] parameters = ServiceReflector.GetOutputParameters(methodInfo, false);
return CreateParameterMessageDescription(contract,
parameters,
methodInfo.ReturnType,
methodInfo.ReturnTypeCustomAttributes,
returnValueName,
methodInfo.Name,
ns,
action,
MessageDirection.Output,
allowReferences);
}
MessageDescription CreateParameterMessageDescription(ContractDescription contract,
ParameterInfo[] parameters,
Type returnType,
ICustomAttributeProvider returnCustomAttributes,
XmlName returnValueName,
string methodName,
string ns,
string action,
MessageDirection direction,
bool allowReferences)
{
MessageDescription messageDescription = new MessageDescription(action, direction);
messageDescription.Body.WrapperNamespace = ns;
for (int index = 0; index < parameters.Length; index++)
{
ParameterInfo parameter = parameters[index];
Type parameterType = TypeLoader.GetParameterType(parameter);
if (!ComPlusTypeValidator.IsValidParameter(parameterType, parameter, allowReferences))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(SR.GetString(SR.InvalidWebServiceParameter,
parameter.Name,
parameterType.Name,
methodName,
contract.Name)));
}
MessagePartDescription messagePart = CreateMessagePartDescription(parameterType,
new XmlName(parameter.Name),
ns,
index);
messageDescription.Body.Parts.Add(messagePart);
}
XmlName xmlName = new XmlName(methodName);
if (returnType == null)
{
messageDescription.Body.WrapperName = xmlName.EncodedName;
}
else
{
messageDescription.Body.WrapperName = TypeLoader.GetBodyWrapperResponseName(xmlName).EncodedName;
if (!ComPlusTypeValidator.IsValidParameter(returnType, returnCustomAttributes, allowReferences))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(SR.GetString(SR.InvalidWebServiceReturnValue,
returnType.Name,
methodName,
contract.Name)));
}
MessagePartDescription messagePart = CreateMessagePartDescription(returnType,
returnValueName,
ns,
0);
messageDescription.Body.ReturnValue = messagePart;
}
return messageDescription;
}
MessagePartDescription CreateMessagePartDescription(Type bodyType,
XmlName name,
string ns,
int index)
{
MessagePartDescription partDescription = new MessagePartDescription(name.EncodedName, ns);
partDescription.SerializationPosition = index;
partDescription.MemberInfo = null;
partDescription.Type = bodyType;
partDescription.Index = index;
return partDescription;
}
ContractDescription ResolveIMetadataExchangeToContract()
{
// Use ServiceModel's TypeLoader to load the IMetadataExchange contract
TypeLoader typeLoader = new TypeLoader();
return typeLoader.LoadContractDescription(typeof(IMetadataExchange));
}
public ContractDescription ResolveContract(string contractTypeString)
{
Guid iid;
if (ServiceMetadataBehavior.MexContractName == contractTypeString)
iid = typeof(IMetadataExchange).GUID;
else
{
if (!DiagnosticUtility.Utility.TryCreateGuid(contractTypeString, out iid))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(SR.GetString(SR.ContractTypeNotAnIID, contractTypeString)));
}
ValidateInterface(iid);
}
// Check our cache to see if we already have one
ContractDescription contract;
if (this.contracts.TryGetValue(iid, out contract))
{
return contract;
}
// If this is not IMetadataExchange continue
if (iid != typeof(IMetadataExchange).GUID)
{
Type type;
// Generate a managed type corresponding to the interface in question
try
{
this.interfaceResolver.FindOrCreateType(this.info.ServiceType, iid, out type, false, true);
}
catch (InvalidOperationException e)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(e.Message));
}
contract = CreateContractDescriptionInternal(iid, type);
}
else
contract = ResolveIMetadataExchangeToContract();
contracts.Add(iid, contract);
ComPlusServiceHostTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationServiceHostCreatedServiceContract,
SR.TraceCodeComIntegrationServiceHostCreatedServiceContract, this.info, contract);
return contract;
}
}
}

View File

@ -0,0 +1,64 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.ComIntegration
{
using System;
using System.Reflection;
using System.EnterpriseServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.ServiceModel;
static class ComPlusTypeValidator
{
static Guid IID_Object = new Guid("{65074F7F-63C0-304E-AF0A-D51741CB4A8D}");
static Guid IID_IDisposable = new Guid("{805D7A98-D4AF-3F0F-967F-E5CF45312D2C}");
static Guid IID_IManagedObject = new Guid("{C3FCC19E-A970-11D2-8B5A-00A0C9B7C9C4}");
static Guid IID_IProcessInitializer = new Guid("{1113F52D-DC7F-4943-AED6-88D04027E32A}");
static Guid IID_IRemoteDispatch = new Guid("{6619A740-8154-43BE-A186-0319578E02DB}");
static Guid IID_IServicedComponentInfo = new Guid("{8165B19E-8D3A-4D0B-80C8-97DE310DB583}");
public static bool IsValidInterface(Guid iid)
{
if (iid == IID_Object ||
iid == IID_IDisposable ||
iid == IID_IManagedObject ||
iid == IID_IProcessInitializer ||
iid == IID_IRemoteDispatch ||
iid == IID_IServicedComponentInfo ||
iid.ToString("D").EndsWith("C000-000000000046", StringComparison.OrdinalIgnoreCase)) //other ole/com standard interfaces
{
return false;
}
return true;
}
public static bool IsValidParameter(Type type, ICustomAttributeProvider attributeProvider, bool allowReferences)
{
object[] attributes = System.ServiceModel.Description.ServiceReflector.GetCustomAttributes(attributeProvider, typeof(MarshalAsAttribute), true);
foreach (MarshalAsAttribute attr in attributes)
{
UnmanagedType marshalAs = attr.Value;
if (marshalAs == UnmanagedType.IDispatch ||
marshalAs == UnmanagedType.Interface ||
marshalAs == UnmanagedType.IUnknown)
{
return allowReferences;
}
}
XsdDataContractExporter exporter = new XsdDataContractExporter();
if (!exporter.CanExport(type))
{
return false;
}
return true;
}
}
}

View File

@ -0,0 +1,79 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.ComIntegration
{
using System;
using System.Runtime;
using System.Runtime.InteropServices;
using System.ServiceModel;
class ComProxy : IDisposable
{
IntPtr inner;
IDisposable ccw;
internal static ComProxy Create(IntPtr outer, object obj, IDisposable disp)
{
if (outer == IntPtr.Zero)
{
throw Fx.AssertAndThrow("Outer cannot be null");
}
IntPtr inner = IntPtr.Zero;
inner = Marshal.CreateAggregatedObject(outer, obj);
int refCount = Marshal.AddRef(inner);
// Workaround for the CLR ref count issue.
if (3 == refCount)
Marshal.Release(inner);
Marshal.Release(inner);
return new ComProxy(inner, disp);
}
internal ComProxy(IntPtr inner, IDisposable disp)
{
this.inner = inner;
ccw = disp;
}
internal void QueryInterface(ref Guid riid, out IntPtr tearoff)
{
if (inner == IntPtr.Zero)
{
throw Fx.AssertAndThrow("Inner should not be Null at this point");
}
int hr = Marshal.QueryInterface(inner, ref riid, out tearoff);
if (hr != HR.S_OK)
{
throw Fx.AssertAndThrow("QueryInterface should succeed");
}
}
void IDisposable.Dispose()
{
Dispose(true);
}
void Dispose(bool disposing)
{
if (inner == IntPtr.Zero)
{
throw Fx.AssertAndThrow("Inner should not be Null at this point");
}
Marshal.Release(inner);
if (disposing)
{
if (ccw != null)
ccw.Dispose();
}
}
public ComProxy Clone()
{
if (inner == IntPtr.Zero)
{
throw Fx.AssertAndThrow("Inner should not be Null at this point");
}
Marshal.AddRef(inner);
return new ComProxy(inner, null);
}
}
}

Some files were not shown because too many files have changed in this diff Show More