public object Invoke(object instance, object[] inputs, out object[] outputs) { Message message = inputs[0] as Message; outputs = null; #pragma warning disable 56506 // [....], message.Properties is never null if (message == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR2.GetString(SR2.HttpUnhandledOperationInvokerCalledWithoutMessage))); } // We might be here because we desire a redirect... Uri newLocation = null; Uri to = message.Headers.To; if (message.Properties.ContainsKey(WebHttpDispatchOperationSelector.RedirectPropertyName)) { newLocation = message.Properties[WebHttpDispatchOperationSelector.RedirectPropertyName] as Uri; } if (newLocation != null && to != null) { // ...redirect Message redirectResult = WebOperationContext.Current.CreateStreamResponse(s => HelpHtmlBuilder.CreateTransferRedirectPage(to.AbsoluteUri, newLocation.AbsoluteUri).Save(s, SaveOptions.OmitDuplicateNamespaces), Atom10Constants.HtmlMediaType); WebOperationContext.Current.OutgoingResponse.Location = newLocation.AbsoluteUri; WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.TemporaryRedirect; WebOperationContext.Current.OutgoingResponse.ContentType = HtmlContentType; // Note that no exception is thrown along this path, even if the debugger is attached if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.WebRequestRedirect, SR2.GetString(SR2.TraceCodeWebRequestRedirect, to, newLocation)); } return(redirectResult); } // otherwise we are here to issue either a 404 or a 405 bool uriMatched = false; if (message.Properties.ContainsKey(WebHttpDispatchOperationSelector.HttpOperationSelectorUriMatchedPropertyName)) { uriMatched = (bool)message.Properties[WebHttpDispatchOperationSelector.HttpOperationSelectorUriMatchedPropertyName]; } #pragma warning enable 56506 Message result = null; Uri helpUri = this.HelpUri != null?UriTemplate.RewriteUri(this.HelpUri, WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.Host]) : null; if (uriMatched) { WebHttpDispatchOperationSelectorData allowedMethodsData = null; if (message.Properties.TryGetValue(WebHttpDispatchOperationSelector.HttpOperationSelectorDataPropertyName, out allowedMethodsData)) { WebOperationContext.Current.OutgoingResponse.Headers[HttpResponseHeader.Allow] = allowedMethodsData.AllowHeader; } result = WebOperationContext.Current.CreateStreamResponse(s => HelpHtmlBuilder.CreateMethodNotAllowedPage(helpUri).Save(s, SaveOptions.OmitDuplicateNamespaces), Atom10Constants.HtmlMediaType); } else { result = WebOperationContext.Current.CreateStreamResponse(s => HelpHtmlBuilder.CreateEndpointNotFound(helpUri).Save(s, SaveOptions.OmitDuplicateNamespaces), Atom10Constants.HtmlMediaType); } WebOperationContext.Current.OutgoingResponse.StatusCode = uriMatched ? HttpStatusCode.MethodNotAllowed : HttpStatusCode.NotFound; WebOperationContext.Current.OutgoingResponse.ContentType = HtmlContentType; try { if (!uriMatched) { if (Debugger.IsAttached) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR2.GetString(SR2.WebRequestDidNotMatchOperation, OperationContext.Current.IncomingMessageHeaders.To))); } else { DiagnosticUtility.TraceHandledException(new InvalidOperationException(SR2.GetString(SR2.WebRequestDidNotMatchOperation, OperationContext.Current.IncomingMessageHeaders.To)), TraceEventType.Warning); } } else { if (Debugger.IsAttached) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR2.GetString(SR2.WebRequestDidNotMatchMethod, WebOperationContext.Current.IncomingRequest.Method, OperationContext.Current.IncomingMessageHeaders.To))); } else { DiagnosticUtility.TraceHandledException(new InvalidOperationException(SR2.GetString(SR2.WebRequestDidNotMatchMethod, WebOperationContext.Current.IncomingRequest.Method, OperationContext.Current.IncomingMessageHeaders.To)), TraceEventType.Warning); } } } catch (InvalidOperationException) { // catch the exception - its only used for tracing } return(result); }
private void GetBase64(byte[] buffer, int offset, int count) { DiagnosticUtility.DebugAssert(_type == ValueHandleType.Base64, ""); _bufferReader.GetBase64(_offset, buffer, offset, count); }
private string GetQNameDictionaryText() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.QName, ""); return(string.Concat(PrefixHandle.GetString(PrefixHandle.GetAlphaPrefix(_length)), ":", _bufferReader.GetDictionaryString(_offset))); }
private double GetDouble() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.Double, ""); return(_bufferReader.GetDouble(_offset)); }
private UniqueId GetUniqueId() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.UniqueId, ""); return(_bufferReader.GetUniqueId(_offset)); }
private int GetInt32() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.Int32, ""); return(_bufferReader.GetInt32(_offset)); }
private ulong GetUInt64() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.UInt64, ""); return(_bufferReader.GetUInt64(_offset)); }
void OnConnectionModeKnownCore(ConnectionModeReader modeReader, bool isCached) { lock (ThisLock) { if (isDisposed) { return; } connectionReaders.Remove(modeReader); } bool closeReader = true; try { FramingMode framingMode; try { framingMode = modeReader.GetConnectionMode(); } catch (CommunicationException exception) { TraceEventType eventType = modeReader.Connection.ExceptionEventType; DiagnosticUtility.TraceHandledException(exception, eventType); return; } catch (TimeoutException exception) { if (!isCached) { exception = new TimeoutException(SR.Format(SR.ChannelInitializationTimeout, channelInitializationTimeout), exception); ErrorBehaviorHelper.ThrowAndCatch(exception); } TraceEventType eventType = modeReader.Connection.ExceptionEventType; DiagnosticUtility.TraceHandledException(exception, eventType); return; } switch (framingMode) { case FramingMode.Duplex: OnDuplexConnection(modeReader.Connection, modeReader.ConnectionDequeuedCallback, modeReader.StreamPosition, modeReader.BufferOffset, modeReader.BufferSize, modeReader.GetRemainingTimeout()); break; case FramingMode.Singleton: OnSingletonConnection(modeReader.Connection, modeReader.ConnectionDequeuedCallback, modeReader.StreamPosition, modeReader.BufferOffset, modeReader.BufferSize, modeReader.GetRemainingTimeout()); break; default: { Exception inner = new InvalidDataException(SR.Format( SR.FramingModeNotSupported, framingMode)); Exception exception = new ProtocolException(inner.Message, inner); FramingEncodingString.AddFaultString(exception, FramingEncodingString.UnsupportedModeFault); ErrorBehaviorHelper.ThrowAndCatch(exception); return; } } closeReader = false; } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (!ExceptionHandlerHelper.HandleTransportExceptionHelper(e)) { throw; } // containment -- the reader is aborted, no need for additional containment } finally { if (closeReader) { modeReader.Dispose(); } } }
private async Task <Tuple <object, object[]> > InvokeAsync(object instance, object[] inputs) { EnsureIsInitialized(); if (instance == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxNoServiceObject)); } if (inputs == null) { if (inputParameterCount > 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxInputParametersToServiceNull, inputParameterCount))); } } else if (inputs.Length != inputParameterCount) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxInputParametersToServiceInvalid, inputParameterCount, inputs.Length))); } object[] outputs = EmptyArray <object> .Allocate(outputParameterCount); //AsyncMethodInvoker.StartOperationInvokePerformanceCounters(taskMethod.Name); object returnValue; bool callFailed = true; bool callFaulted = false; //ServiceModelActivity activity = null; //Activity boundActivity = null; try { //AsyncMethodInvoker.CreateActivityInfo(ref activity, ref boundActivity); //AsyncMethodInvoker.StartOperationInvokeTrace(taskMethod.Name); //if (DiagnosticUtility.ShouldUseActivity) //{ // string activityName = SR.Format(SR.ActivityExecuteMethod, taskMethod.DeclaringType.FullName, taskMethod.Name); // ServiceModelActivity.Start(activity, activityName, ActivityType.ExecuteUserCode); //} returnValue = invokeDelegate(instance, inputs, outputs); if (returnValue == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("task"); } var returnValueTask = returnValue as Task; if (returnValueTask != null) { // Only return once the task has completed await returnValueTask; } callFailed = false; return(Tuple.Create(returnValue, outputs)); } catch (SecurityException e) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(AuthorizationBehavior.CreateAccessDeniedFaultException()); } catch (FaultException) { callFaulted = true; throw; } catch (Exception e) { TraceUtility.TraceUserCodeException(e, taskMethod); throw; } finally { //if (boundActivity != null) //{ // ((IDisposable)boundActivity).Dispose(); //} //ServiceModelActivity.Stop(activity); // Any exception above means InvokeEnd will not be called, so complete it here. if (callFailed || callFaulted) { //AsyncMethodInvoker.StopOperationInvokeTrace(callFailed, callFaulted, TaskMethod.Name); //AsyncMethodInvoker.StopOperationInvokePerformanceCounters(callFailed, callFaulted, TaskMethod.Name); } } }
public void InDoubt(Enlistment enlistment) { DiagnosticUtility.FailFast("Should have voted read only"); }
public void Commit(Guid guid) { DiagnosticUtility.FailFast("Commit not supported: BYOT only!"); }
public bool TryReadChars(char[] chars, int offset, int count, out int actual) { DiagnosticUtility.DebugAssert(offset + count <= chars.Length, string.Format("offset '{0}' + count '{1}' MUST BE <= chars.Length '{2}'", offset, count, chars.Length)); if (_type == ValueHandleType.Unicode) { return(TryReadUnicodeChars(chars, offset, count, out actual)); } if (_type != ValueHandleType.UTF8) { actual = 0; return(false); } int charOffset = offset; int charCount = count; byte[] bytes = _bufferReader.Buffer; int byteOffset = _offset; int byteCount = _length; bool insufficientSpaceInCharsArray = false; var encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); while (true) { while (charCount > 0 && byteCount > 0) { // fast path for codepoints U+0000 - U+007F byte b = bytes[byteOffset]; if (b >= 0x80) { break; } chars[charOffset] = (char)b; byteOffset++; byteCount--; charOffset++; charCount--; } if (charCount == 0 || byteCount == 0 || insufficientSpaceInCharsArray) { break; } int actualByteCount; int actualCharCount; try { // If we're asking for more than are possibly available, or more than are truly available then we can return the entire thing if (charCount >= encoding.GetMaxCharCount(byteCount) || charCount >= encoding.GetCharCount(bytes, byteOffset, byteCount)) { actualCharCount = encoding.GetChars(bytes, byteOffset, byteCount, chars, charOffset); actualByteCount = byteCount; } else { Decoder decoder = encoding.GetDecoder(); // Since x bytes can never generate more than x characters this is a safe estimate as to what will fit actualByteCount = Math.Min(charCount, byteCount); // We use a decoder so we don't error if we fall across a character boundary actualCharCount = decoder.GetChars(bytes, byteOffset, actualByteCount, chars, charOffset); // We might have gotten zero characters though if < 4 bytes were requested because // codepoints from U+0000 - U+FFFF can be up to 3 bytes in UTF-8, and represented as ONE char // codepoints from U+10000 - U+10FFFF (last Unicode codepoint representable in UTF-8) are represented by up to 4 bytes in UTF-8 // and represented as TWO chars (high+low surrogate) // (e.g. 1 char requested, 1 char in the buffer represented in 3 bytes) while (actualCharCount == 0) { // Note the by the time we arrive here, if actualByteCount == 3, the next decoder.GetChars() call will read the 4th byte // if we don't bail out since the while loop will advance actualByteCount only after reading the byte. if (actualByteCount >= 3 && charCount < 2) { // If we reach here, it means that we're: // - trying to decode more than 3 bytes and, // - there is only one char left of charCount where we're stuffing decoded characters. // In this case, we need to back off since decoding > 3 bytes in UTF-8 means that we will get 2 16-bit chars // (a high surrogate and a low surrogate) - the Decoder will attempt to provide both at once // and an ArgumentException will be thrown complaining that there's not enough space in the output char array. // actualByteCount = 0 when the while loop is broken out of; decoder goes out of scope so its state no longer matters insufficientSpaceInCharsArray = true; break; } else { DiagnosticUtility.DebugAssert(byteOffset + actualByteCount < bytes.Length, string.Format("byteOffset {0} + actualByteCount {1} MUST BE < bytes.Length {2}", byteOffset, actualByteCount, bytes.Length)); // Request a few more bytes to get at least one character actualCharCount = decoder.GetChars(bytes, byteOffset + actualByteCount, 1, chars, charOffset); actualByteCount++; } } // Now that we actually retrieved some characters, figure out how many bytes it actually was actualByteCount = encoding.GetByteCount(chars, charOffset, actualCharCount); } } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateEncodingException(bytes, byteOffset, byteCount, exception)); } // Advance byteOffset += actualByteCount; byteCount -= actualByteCount; charOffset += actualCharCount; charCount -= actualCharCount; } _offset = byteOffset; _length = byteCount; actual = (count - charCount); return(true); }
/// <summary> /// Initializes a new instance of the <see cref="AsymmetricSignatureProvider"/> class used to create and verify signatures. /// </summary> /// <param name="key"> /// The <see cref="AsymmetricSecurityKey"/> that will be used for cryptographic operations. /// </param> /// <param name="algorithm"> /// The signature algorithm to apply. /// </param> /// <param name="willCreateSignatures"> /// If this <see cref="AsymmetricSignatureProvider"/> is required to create signatures then set this to true. /// <para> /// Creating signatures requires that the <see cref="AsymmetricSecurityKey"/> has access to a private key. /// Verifying signatures (the default), does not require access to the private key. /// </para> /// </param> /// <exception cref="ArgumentNullException"> /// 'key' is null. /// </exception> /// <exception cref="ArgumentNullException"> /// 'algorithm' is null. /// </exception> /// <exception cref="ArgumentException"> /// 'algorithm' contains only whitespace. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// willCreateSignatures is true and <see cref="AsymmetricSecurityKey"/>.KeySize is less than <see cref="SignatureProviderFactory.MinimumAsymmetricKeySizeInBitsForSigning"/>. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <see cref="AsymmetricSecurityKey"/>.KeySize is less than <see cref="SignatureProviderFactory.MinimumAsymmetricKeySizeInBitsForVerifying"/>. Note: this is always checked. /// </exception> /// <exception cref="InvalidOperationException"> /// Is thrown if the <see cref="AsymmetricSecurityKey.GetHashAlgorithmForSignature"/> throws. /// </exception> /// <exception cref="InvalidOperationException"> /// Is thrown if the <see cref="AsymmetricSecurityKey.GetHashAlgorithmForSignature"/> returns null. /// </exception> /// <exception cref="InvalidOperationException"> /// Is thrown if the <see cref="AsymmetricSecurityKey.GetSignatureFormatter"/> throws. /// </exception> /// <exception cref="InvalidOperationException"> /// Is thrown if the <see cref="AsymmetricSecurityKey.GetSignatureFormatter"/> returns null. /// </exception> /// <exception cref="InvalidOperationException"> /// Is thrown if the <see cref="AsymmetricSecurityKey.GetSignatureDeformatter"/> throws. /// </exception> /// <exception cref="InvalidOperationException"> /// Is thrown if the <see cref="AsymmetricSecurityKey.GetSignatureDeformatter"/> returns null. /// </exception> /// <exception cref="InvalidOperationException"> /// Is thrown if the <see cref="AsymmetricSignatureFormatter.SetHashAlgorithm"/> throws. /// </exception> /// <exception cref="InvalidOperationException"> /// Is thrown if the <see cref="AsymmetricSignatureDeformatter.SetHashAlgorithm"/> throws. /// </exception> public AsymmetricSignatureProvider(AsymmetricSecurityKey key, string algorithm, bool willCreateSignatures = false) { if (key == null) { throw new ArgumentNullException("key"); } if (algorithm == null) { throw new ArgumentNullException("algorithm"); } if (string.IsNullOrWhiteSpace(algorithm)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, WifExtensionsErrors.WIF10002, "algorithm")); } if (willCreateSignatures) { if (key.KeySize < SignatureProviderFactory.MinimumAsymmetricKeySizeInBitsForSigning) { throw new ArgumentOutOfRangeException("key.KeySize", key.KeySize, string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10531, key.GetType(), SignatureProviderFactory.MinimumAsymmetricKeySizeInBitsForSigning)); } } if (key.KeySize < SignatureProviderFactory.MinimumAsymmetricKeySizeInBitsForVerifying) { throw new ArgumentOutOfRangeException("key.KeySize", key.KeySize, string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10530, key.GetType(), SignatureProviderFactory.MinimumAsymmetricKeySizeInBitsForVerifying)); } this.key = key; try { this.hash = this.key.GetHashAlgorithmForSignature(algorithm); } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10518, algorithm, this.key.ToString(), ex), ex); } if (this.hash == null) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10511, algorithm, this.key.ToString())); } if (willCreateSignatures) { try { this.formatter = this.key.GetSignatureFormatter(algorithm); this.formatter.SetHashAlgorithm(this.hash.GetType().ToString()); } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10514, algorithm, this.key.ToString(), ex), ex); } if (this.formatter == null) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10515, algorithm, this.key.ToString())); } } try { this.deformatter = this.key.GetSignatureDeformatter(algorithm); this.deformatter.SetHashAlgorithm(this.hash.GetType().ToString()); } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10516, algorithm, this.key.ToString(), ex), ex); } if (this.deformatter == null) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10517, algorithm, this.key.ToString())); } }
private void Initialize(CoordinationServiceConfiguration config) { DebugTrace.TraceEnter(this, "Initialize"); this.config = config; this.security = new CoordinationServiceSecurity(); if ((config.Mode == 0) || ((config.Mode & ~(CoordinationServiceMode.ProtocolService | CoordinationServiceMode.Formatter)) != 0)) { DiagnosticUtility.FailFast("Invalid CoordinationServiceMode"); } if ((config.Mode & CoordinationServiceMode.ProtocolService) == 0) { if (!string.IsNullOrEmpty(config.BasePath)) { DiagnosticUtility.FailFast("A base path must not be provided if protocol service mode is not enabled"); } if (!string.IsNullOrEmpty(config.HostName)) { DiagnosticUtility.FailFast("A hostname must not be provided if protocol service mode is not enabled"); } } else { if (string.IsNullOrEmpty(config.BasePath)) { DiagnosticUtility.FailFast("A base path must be provided if protocol service mode is enabled"); } if (string.IsNullOrEmpty(config.HostName)) { DiagnosticUtility.FailFast("A hostname must be provided if protocol service mode is enabled"); } if (config.X509Certificate == null) { DiagnosticUtility.FailFast("No authentication mechanism was provided for the protocol service"); } } this.globalAclAuthz = new GlobalAclOperationRequirement(config.GlobalAclWindowsIdentities, config.GlobalAclX509CertificateThumbprints, this.protocolVersion); if ((this.config.Mode & CoordinationServiceMode.ProtocolService) != 0) { this.httpsBaseAddressUri = new UriBuilder(Uri.UriSchemeHttps, this.config.HostName, this.config.HttpsPort, this.config.BasePath).Uri; this.namedPipeBaseAddressUri = new UriBuilder(Uri.UriSchemeNetPipe, "localhost", -1, this.config.HostName + "/" + this.config.BasePath).Uri; } this.namedPipeActivationBinding = new NamedPipeBinding(this.protocolVersion); if (this.config.RemoteClientsEnabled) { this.windowsActivationBinding = new WindowsRequestReplyBinding(this.protocolVersion); } this.interopDatagramBinding = new Microsoft.Transactions.Wsat.Messaging.InteropDatagramBinding(this.protocolVersion); this.interopRegistrationBinding = new Microsoft.Transactions.Wsat.Messaging.InteropRegistrationBinding(this.httpsBaseAddressUri, this.config.SupportingTokensEnabled, this.protocolVersion); this.interopActivationBinding = new Microsoft.Transactions.Wsat.Messaging.InteropActivationBinding(this.httpsBaseAddressUri, this.protocolVersion); ClientCredentials item = new ClientCredentials { ClientCertificate = { Certificate = this.config.X509Certificate }, ServiceCertificate = { DefaultCertificate = this.config.X509Certificate } }; if ((this.config.Mode & CoordinationServiceMode.ProtocolService) != 0) { this.interopDatagramChannelFactory = this.CreateChannelFactory <IDatagramService>(this.interopDatagramBinding); this.interopDatagramChannelFactory.Endpoint.Behaviors.Remove <ClientCredentials>(); this.interopDatagramChannelFactory.Endpoint.Behaviors.Add(item); this.OpenChannelFactory <IDatagramService>(this.interopDatagramChannelFactory); this.interopRegistrationChannelFactory = this.CreateChannelFactory <IRequestReplyService>(this.interopRegistrationBinding); this.interopRegistrationChannelFactory.Endpoint.Behaviors.Remove <ClientCredentials>(); this.interopRegistrationChannelFactory.Endpoint.Behaviors.Add(item); this.OpenChannelFactory <IRequestReplyService>(this.interopRegistrationChannelFactory); } if ((config.Mode & CoordinationServiceMode.Formatter) != 0) { if (this.config.X509Certificate != null) { this.interopActivationChannelFactory = this.CreateChannelFactory <IRequestReplyService>(this.interopActivationBinding); this.interopActivationChannelFactory.Endpoint.Behaviors.Remove <ClientCredentials>(); this.interopActivationChannelFactory.Endpoint.Behaviors.Add(item); this.OpenChannelFactory <IRequestReplyService>(this.interopActivationChannelFactory); } this.namedPipeActivationChannelFactory = this.CreateChannelFactory <IRequestReplyService>(this.namedPipeActivationBinding); this.OpenChannelFactory <IRequestReplyService>(this.namedPipeActivationChannelFactory); if (this.config.RemoteClientsEnabled) { this.windowsActivationChannelFactory = this.CreateChannelFactory <IRequestReplyService>(this.windowsActivationBinding); this.OpenChannelFactory <IRequestReplyService>(this.windowsActivationChannelFactory); } } this.requestReplyChannelCache = new ChannelMruCache <IRequestReplyService>(); if ((this.config.Mode & CoordinationServiceMode.ProtocolService) != 0) { this.datagramChannelCache = new ChannelMruCache <IDatagramService>(); } DebugTrace.TraceLeave(this, "Initialize"); }
private string GetEscapedCharsText() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.EscapedUTF8, ""); return(_bufferReader.GetEscapedString(_offset, _length)); }
public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result) { if (instance == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxNoServiceObject)); } object returnVal = null; //bool callFailed = true; //bool callFaulted = false; //ServiceModelActivity activity = null; //Activity boundOperation = null; try { //AsyncMethodInvoker.GetActivityInfo(ref activity, ref boundOperation); Task <Tuple <object, object[]> > invokeTask = result as Task <Tuple <object, object[]> >; if (invokeTask == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.SFxInvalidCallbackIAsyncResult); } AggregateException ae = null; Tuple <object, object[]> tuple = null; Task task = null; if (invokeTask.IsFaulted) { Fx.Assert(invokeTask.Exception != null, "Task.IsFaulted guarantees non-null exception."); ae = invokeTask.Exception; } else { Fx.Assert(invokeTask.IsCompleted, "Task.Result is expected to be completed"); tuple = invokeTask.Result; task = tuple.Item1 as Task; if (task == null) { outputs = tuple.Item2; return(null); } if (task.IsFaulted) { Fx.Assert(task.Exception != null, "Task.IsFaulted guarantees non-null exception."); ae = task.Exception; } } if (ae != null && ae.InnerException != null) { if (ae.InnerException is FaultException) { // If invokeTask.IsFaulted we produce the 'callFaulted' behavior below. // Any other exception will retain 'callFailed' behavior. //callFaulted = true; //callFailed = false; } if (ae.InnerException is SecurityException) { DiagnosticUtility.TraceHandledException(ae.InnerException, TraceEventType.Warning); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(AuthorizationBehavior.CreateAccessDeniedFaultException()); } invokeTask.GetAwaiter().GetResult(); } // Task cancellation without an exception indicates failure but we have no // additional information to provide. Accessing Task.Result will throw a // TaskCanceledException. For consistency between void Tasks and Task<T>, // we detect and throw here. if (task.IsCanceled) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TaskCanceledException(task)); } outputs = tuple.Item2; returnVal = isGenericTask ? taskTResultGetMethod.Invoke(task, Type.EmptyTypes) : null; //callFailed = false; return(returnVal); } finally { //if (boundOperation != null) //{ // ((IDisposable)boundOperation).Dispose(); //} //ServiceModelActivity.Stop(activity); //AsyncMethodInvoker.StopOperationInvokeTrace(callFailed, callFaulted, TaskMethod.Name); //AsyncMethodInvoker.StopOperationInvokePerformanceCounters(callFailed, callFaulted, TaskMethod.Name); } }
private int GetChar() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.Char, ""); return(_offset); }
// static initializer will run before properties are accessed static X509SubjectAlternativeNameConstants() { // Extracted a well-known X509Extension byte[] x509ExtensionBytes = new byte[] { 48, 36, 130, 21, 110, 111, 116, 45, 114, 101, 97, 108, 45, 115, 117, 98, 106, 101, 99, 116, 45, 110, 97, 109, 101, 130, 11, 101, 120, 97, 109, 112, 108, 101, 46, 99, 111, 109 }; const string subjectName = "not-real-subject-name"; string x509ExtensionFormattedString = string.Empty; try { X509Extension x509Extension = new X509Extension(SanOid, x509ExtensionBytes, true); x509ExtensionFormattedString = x509Extension.Format(false); // Each OS has a different dNSName identifier and delimiter // On Windows, dNSName == "DNS Name" (localizable), on Linux, dNSName == "DNS" // e.g., // Windows: x509ExtensionFormattedString is: "DNS Name=not-real-subject-name, DNS Name=example.com" // Linux: x509ExtensionFormattedString is: "DNS:not-real-subject-name, DNS:example.com" // Parse: <identifier><delimiter><value><separator(s)> int delimiterIndex = x509ExtensionFormattedString.IndexOf(subjectName) - 1; Delimiter = x509ExtensionFormattedString[delimiterIndex]; // Make an assumption that all characters from the the start of string to the delimiter // are part of the identifier Identifier = x509ExtensionFormattedString.Substring(0, delimiterIndex); int separatorFirstChar = delimiterIndex + subjectName.Length + 1; int separatorLength = 1; for (int i = separatorFirstChar + 1; i < x509ExtensionFormattedString.Length; i++) { // We advance until the first character of the identifier to determine what the // separator is. This assumes that the identifier assumption above is correct if (x509ExtensionFormattedString[i] == Identifier[0]) { break; } separatorLength++; } Separator = x509ExtensionFormattedString.Substring(separatorFirstChar, separatorLength); SeparatorArray = new string[1] { Separator }; SuccessfullyInitialized = true; } catch (Exception ex) { SuccessfullyInitialized = false; DiagnosticUtility.TraceHandledException( new FormatException(string.Format(CultureInfo.InvariantCulture, "There was an error parsing the SubjectAlternativeNames: '{0}'. See inner exception for more details.{1}Detected values were: Identifier: '{2}'; Delimiter:'{3}'; Separator:'{4}'", x509ExtensionFormattedString, Environment.NewLine, Identifier, Delimiter, Separator), ex), TraceEventType.Warning); } }
private long GetInt64() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.Int64 || _type == ValueHandleType.TimeSpan || _type == ValueHandleType.DateTime, ""); return(_bufferReader.GetInt64(_offset)); }
/// <summary> /// Decodes the string into the header, payload and signature /// </summary> /// <param name="jwtEncodedString">Base64Url encoded string.</param> internal void Decode(string jwtEncodedString) { if (jwtEncodedString.Split(new char[] { '.' }).Length == 2) { jwtEncodedString += "."; } string[] tokenParts = jwtEncodedString.Split(new char[] { '.' }, 4); if (tokenParts.Length != 3) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10709, "jwtEncodedString", jwtEncodedString)); } try { this.header = JwtHeader.Base64UrlDeserialize(tokenParts[0]); // if present, "typ" should be set to "JWT" or "http://openid.net/specs/jwt/1.0" string type = this.header.Typ; if (type != null) { if (!(StringComparer.Ordinal.Equals(type, JwtConstants.HeaderType) || StringComparer.Ordinal.Equals(type, JwtConstants.HeaderTypeAlt))) { throw new SecurityTokenException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10702, JwtConstants.HeaderType, JwtConstants.HeaderTypeAlt, type)); } } } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10703, "header", tokenParts[0], jwtEncodedString), ex); } try { this.payload = JwtPayload.Base64UrlDeserialize(tokenParts[1]); } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10703, "payload", tokenParts[1], jwtEncodedString), ex); } // ensure signature is well-formed, GitIssue 103 if (!string.IsNullOrEmpty(tokenParts[2])) { try { Base64UrlEncoder.Decode(tokenParts[2]); } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10703, "signature", tokenParts[1], jwtEncodedString), ex); } } this.rawData = jwtEncodedString; this.rawHeader = tokenParts[0]; this.rawPayload = tokenParts[1]; this.rawSignature = tokenParts[2]; }
private float GetSingle() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.Single, ""); return(_bufferReader.GetSingle(_offset)); }
unsafe public virtual int GetBytes(byte[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (chars == null) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars))); } if (charIndex < 0) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.ValueMustBeNonNegative))); } if (charIndex > chars.Length) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.OffsetExceedsBufferSize, chars.Length))); } if (charCount < 0) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charCount), SR.Format(SR.ValueMustBeNonNegative))); } if (charCount > chars.Length - charIndex) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - charIndex))); } if (bytes == null) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(bytes))); } if (byteIndex < 0) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.ValueMustBeNonNegative))); } if (byteIndex > bytes.Length) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.OffsetExceedsBufferSize, bytes.Length))); } if (charCount == 0) { return(0); } if ((charCount % 4) != 0) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Length, charCount.ToString(NumberFormatInfo.CurrentInfo)))); fixed(byte *_char2val = s_char2val) { fixed(byte *_chars = &chars[charIndex]) { fixed(byte *_bytes = &bytes[byteIndex]) { byte *pch = _chars; byte *pchMax = _chars + charCount; byte *pb = _bytes; byte *pbMax = _bytes + bytes.Length - byteIndex; while (pch < pchMax) { DiagnosticUtility.DebugAssert(pch + 4 <= pchMax, ""); byte pch0 = pch[0]; byte pch1 = pch[1]; byte pch2 = pch[2]; byte pch3 = pch[3]; if ((pch0 | pch1 | pch2 | pch3) >= 128) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Sequence, "?", charIndex + (int)(pch - _chars)))); } // xx765432 xx107654 xx321076 xx543210 // 76543210 76543210 76543210 int v1 = _char2val[pch0]; int v2 = _char2val[pch1]; int v3 = _char2val[pch2]; int v4 = _char2val[pch3]; if (!IsValidLeadBytes(v1, v2, v3, v4) || !IsValidTailBytes(v3, v4)) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Sequence, "?", charIndex + (int)(pch - _chars)))); } int byteCount = (v4 != 64 ? 3 : (v3 != 64 ? 2 : 1)); if (pb + byteCount > pbMax) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlArrayTooSmall), nameof(bytes))); } pb[0] = (byte)((v1 << 2) | ((v2 >> 4) & 0x03)); if (byteCount > 1) { pb[1] = (byte)((v2 << 4) | ((v3 >> 2) & 0x0F)); if (byteCount > 2) { pb[2] = (byte)((v3 << 6) | ((v4 >> 0) & 0x3F)); } } pb += byteCount; pch += 4; } return((int)(pb - _bytes)); } } } }
private decimal GetDecimal() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.Decimal, ""); return(_bufferReader.GetDecimal(_offset)); }
unsafe public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { if (bytes == null) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(bytes))); } if (byteIndex < 0) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.ValueMustBeNonNegative))); } if (byteIndex > bytes.Length) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.OffsetExceedsBufferSize, bytes.Length))); } if (byteCount < 0) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteCount), SR.Format(SR.ValueMustBeNonNegative))); } if (byteCount > bytes.Length - byteIndex) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, bytes.Length - byteIndex))); } int charCount = GetCharCount(bytes, byteIndex, byteCount); if (chars == null) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars))); } if (charIndex < 0) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.ValueMustBeNonNegative))); } if (charIndex > chars.Length) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.OffsetExceedsBufferSize, chars.Length))); } if (charCount < 0 || charCount > chars.Length - charIndex) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlArrayTooSmall), nameof(chars))); } // We've computed exactly how many chars there are and verified that // there's enough space in the char buffer, so we can proceed without // checking the charCount. if (byteCount > 0) { fixed(char *_val2char = s_val2char) { fixed(byte *_bytes = &bytes[byteIndex]) { fixed(char *_chars = &chars[charIndex]) { byte *pb = _bytes; byte *pbMax = pb + byteCount - 3; char *pch = _chars; // Convert chunks of 3 bytes to 4 chars while (pb <= pbMax) { // 76543210 76543210 76543210 // xx765432 xx107654 xx321076 xx543210 // Inspect the code carefully before you change this pch[0] = _val2char[(pb[0] >> 2)]; pch[1] = _val2char[((pb[0] & 0x03) << 4) | (pb[1] >> 4)]; pch[2] = _val2char[((pb[1] & 0x0F) << 2) | (pb[2] >> 6)]; pch[3] = _val2char[pb[2] & 0x3F]; pb += 3; pch += 4; } // Handle 1 or 2 trailing bytes if (pb - pbMax == 2) { // 1 trailing byte // 76543210 xxxxxxxx xxxxxxxx // xx765432 xx10xxxx xxxxxxxx xxxxxxxx pch[0] = _val2char[(pb[0] >> 2)]; pch[1] = _val2char[((pb[0] & 0x03) << 4)]; pch[2] = '='; pch[3] = '='; } else if (pb - pbMax == 1) { // 2 trailing bytes // 76543210 76543210 xxxxxxxx // xx765432 xx107654 xx3210xx xxxxxxxx pch[0] = _val2char[(pb[0] >> 2)]; pch[1] = _val2char[((pb[0] & 0x03) << 4) | (pb[1] >> 4)]; pch[2] = _val2char[((pb[1] & 0x0F) << 2)]; pch[3] = '='; } else { // 0 trailing bytes DiagnosticUtility.DebugAssert(pb - pbMax == 3, ""); } } } } } return(charCount); }
private Guid GetGuid() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.Guid, ""); return(_bufferReader.GetGuid(_offset)); }
unsafe public override int GetByteCount(char[] chars, int index, int count) { if (chars == null) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars))); } if (index < 0) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(index), SR.Format(SR.ValueMustBeNonNegative))); } if (index > chars.Length) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(index), SR.Format(SR.OffsetExceedsBufferSize, chars.Length))); } if (count < 0) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative))); } if (count > chars.Length - index) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - index))); } if (count == 0) { return(0); } if ((count % 4) != 0) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Length, count.ToString(NumberFormatInfo.CurrentInfo)))); fixed(byte *_char2val = s_char2val) { fixed(char *_chars = &chars[index]) { int totalCount = 0; char *pch = _chars; char *pchMax = _chars + count; while (pch < pchMax) { DiagnosticUtility.DebugAssert(pch + 4 <= pchMax, ""); char pch0 = pch[0]; char pch1 = pch[1]; char pch2 = pch[2]; char pch3 = pch[3]; if ((pch0 | pch1 | pch2 | pch3) >= 128) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Sequence, new string(pch, 0, 4), index + (int)(pch - _chars)))); } // xx765432 xx107654 xx321076 xx543210 // 76543210 76543210 76543210 int v1 = _char2val[pch0]; int v2 = _char2val[pch1]; int v3 = _char2val[pch2]; int v4 = _char2val[pch3]; if (!IsValidLeadBytes(v1, v2, v3, v4) || !IsValidTailBytes(v3, v4)) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Sequence, new string(pch, 0, 4), index + (int)(pch - _chars)))); } int byteCount = (v4 != 64 ? 3 : (v3 != 64 ? 2 : 1)); totalCount += byteCount; pch += 4; } return(totalCount); } } } unsafe public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
private XmlDictionaryString GetDictionaryString() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.Dictionary, ""); return(_bufferReader.GetDictionaryString(_offset)); }
private string GetUnicodeCharsText() { DiagnosticUtility.DebugAssert(_type == ValueHandleType.Unicode, ""); return(_bufferReader.GetUnicodeString(_offset, _length)); }
public string GetString() { ValueHandleType type = _type; if (type == ValueHandleType.UTF8) { return(GetCharsText()); } switch (type) { case ValueHandleType.False: return("false"); case ValueHandleType.True: return("true"); case ValueHandleType.Zero: return("0"); case ValueHandleType.One: return("1"); case ValueHandleType.Int8: case ValueHandleType.Int16: case ValueHandleType.Int32: return(XmlConverter.ToString(ToInt())); case ValueHandleType.Int64: return(XmlConverter.ToString(GetInt64())); case ValueHandleType.UInt64: return(XmlConverter.ToString(GetUInt64())); case ValueHandleType.Single: return(XmlConverter.ToString(GetSingle())); case ValueHandleType.Double: return(XmlConverter.ToString(GetDouble())); case ValueHandleType.Decimal: return(XmlConverter.ToString(GetDecimal())); case ValueHandleType.DateTime: return(XmlConverter.ToString(ToDateTime())); case ValueHandleType.Empty: return(string.Empty); case ValueHandleType.Unicode: return(GetUnicodeCharsText()); case ValueHandleType.EscapedUTF8: return(GetEscapedCharsText()); case ValueHandleType.Char: return(GetCharText()); case ValueHandleType.Dictionary: return(GetDictionaryString().Value); case ValueHandleType.Base64: byte[] bytes = ToByteArray(); DiagnosticUtility.DebugAssert(bytes != null, ""); return(Base64Encoding.GetString(bytes, 0, bytes.Length)); case ValueHandleType.List: return(XmlConverter.ToString(ToList())); case ValueHandleType.UniqueId: return(XmlConverter.ToString(ToUniqueId())); case ValueHandleType.Guid: return(XmlConverter.ToString(ToGuid())); case ValueHandleType.TimeSpan: return(XmlConverter.ToString(ToTimeSpan())); case ValueHandleType.QName: return(GetQNameDictionaryText()); case ValueHandleType.ConstString: return(s_constStrings[_offset]); default: throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException()); } }
/// <summary> /// Returns the extension element, or null if the type cannot be loaded in certain situations (see the code for details). /// </summary> TServiceModelExtensionElement CreateNewSection(string name) { if (this.ContainsKey(name) && !(name == ConfigurationStrings.Clear || name == ConfigurationStrings.Remove)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(SR.GetString(SR.ConfigDuplicateItem, name, this.GetType().Name), this.ElementInformation.Source, this.ElementInformation.LineNumber)); } TServiceModelExtensionElement retval = null; Type elementType; ContextInformation evaluationContext = ConfigurationHelpers.GetEvaluationContext(this); #if DESKTOP try #endif { elementType = GetExtensionType(evaluationContext, name); } #if DESKTOP catch (ConfigurationErrorsException e) { // Work-around for bug 219506@CSDMain: if the extension type cannot be loaded, we'll ignore // the exception when running in win8 app container and reading from machine.config. if (System.ServiceModel.Channels.AppContainerInfo.IsRunningInAppContainer && evaluationContext.IsMachineLevel) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); return(null); } else { throw; } } #endif if (null != elementType) { if (this.CollectionElementBaseType.IsAssignableFrom(elementType)) { retval = (TServiceModelExtensionElement)Activator.CreateInstance(elementType); retval.ExtensionCollectionName = this.extensionCollectionName; retval.ConfigurationElementName = name; retval.InternalInitializeDefault(); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(SR.GetString(SR.ConfigInvalidExtensionElement, name, this.CollectionElementBaseType.FullName), this.ElementInformation.Source, this.ElementInformation.LineNumber)); } } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(SR.GetString(SR.ConfigInvalidExtensionElementName, name, this.extensionCollectionName), this.ElementInformation.Source, this.ElementInformation.LineNumber)); } return(retval); }