Code:
/ WCF / WCF / 3.5.30729.1 / untmp / Orcas / SP / ndp / cdf / src / WCF / Tools / xws_reg / System / ServiceModel / Install / IisHelper.cs / 2 / IisHelper.cs
//------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.ServiceModel.Install { using Microsoft.Win32; using System; using System.Collections; using System.ComponentModel; using System.Configuration; using System.DirectoryServices; using System.Runtime.InteropServices; using System.ServiceModel.Install.Configuration; using System.ServiceProcess; using System.IO; using Microsoft.Tools.ServiceModel; static class IisHelper { static bool isApplicationHostInstalled = false; static bool? isAspNetInstalled = null; static bool isWasInstalled = false; static bool isIisInstalled = false; static bool isIisAdminEnabled = false; static bool hasAttemptedRecovery = false; static IisHelper() { try { IisHelper.isApplicationHostInstalled = IIS7ConfigurationLoader.CheckApplicationHostInstalled(); } catch (System.IO.FileNotFoundException) { // FileNotFoundException means that Microsoft.Web.Administration.dll is not installed and we cannot // install ApplicationHost.config entries IisHelper.isApplicationHostInstalled = false; } IisHelper.CheckWasInstalled(); IisHelper.CheckIisInstalled(); } static internal bool GetIsXP() { const int XPMajorVersion = 5; const int XPMinorVersion = 1; return Environment.OSVersion.Version.Major == XPMajorVersion && Environment.OSVersion.Version.Minor == XPMinorVersion; } static internal bool IsRecoverable(COMException e) { return e.ErrorCode == COMErrors.HRESULT_FROM_ERROR_PATH_BUSY; } static internal bool AttemptRecovery() { // the return value is a bool indicating whether // recovery was actually attempted if (hasAttemptedRecovery) { // our recovery code recovers after running once, // if it doesn't, no need to call it any further return false; } // this block of code is here to workaround possible metabase // locking issues that are known to cause our setup to fail at times // call "iisreset /restart timeout:120" and ignore failures to ensure that the metabase // (IISADMIN) is freshly started before we try calling any of its APIs string iisresetPath = Path.Combine(Environment.SystemDirectory, @"iisreset.exe"); const string iisresetParams = "/restart /timeout:120"; EventLogger.LogInformation(SR2.GetString(SR2.IISResetNeeded, iisresetPath + " " + iisresetParams), false); // if iisreset.exe was somehow missing from the box we won't be able to recover // and the following call to TryExecuteWait will throw a FileNotFoundException InstallHelper.TryExecuteWait(OutputLevel.Normal, iisresetPath, iisresetParams); hasAttemptedRecovery = true; return true; } static internal void ValidateDirectoryEntry(DirectoryEntry entry) { try { // Call RefreshCache to force the ADS object to bind entry.RefreshCache(); } catch (COMException e) { if (GetIsXP() && IsRecoverable(e) && AttemptRecovery()) { entry.RefreshCache(); } else { throw; } } } static void CheckAspNetInstalled() { using (DirectoryEntry iisRootEntry = new DirectoryEntry(ServiceModelInstallStrings.IISAdsRoot)) { try { ValidateDirectoryEntry(iisRootEntry); PropertyValueCollection scriptMapCollection = iisRootEntry.Properties[ServiceModelInstallStrings.ScriptMaps]; // Should never be null, but being overly protective here due to timing of this checkin... if (null != scriptMapCollection) { for (int i = 0; i < scriptMapCollection.Count; i++) { string scriptMapEntry = (string)scriptMapCollection[i]; if (!String.IsNullOrEmpty(scriptMapEntry)) { // Sample script map entry: .svc,C:\WINNT\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll,1,GET,HEAD,POST,DEBUG string[] scriptMapParts = scriptMapEntry.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (scriptMapParts.Length > 1 && scriptMapParts[0].Equals(ServiceModelInstallStrings.AspNetScriptMapPath, StringComparison.OrdinalIgnoreCase) && !String.IsNullOrEmpty((string)scriptMapParts[1])) { // Verify that the ASP.NET ISAPI filter registered is the same as what we expect to register // Normalize current ISAPI filter and expected ISAPI filter in case strings contain // environment variables or are in short path form. string currentIsapiFilter = Environment.ExpandEnvironmentVariables(scriptMapParts[1]); string expectedIsapiFilter = Environment.ExpandEnvironmentVariables(InstallHelper.IsapiFilter); try { currentIsapiFilter = Path.GetFullPath(currentIsapiFilter); expectedIsapiFilter = Path.GetFullPath(expectedIsapiFilter); if (scriptMapParts[1].Equals(InstallHelper.IsapiFilter, StringComparison.OrdinalIgnoreCase)) { IisHelper.isAspNetInstalled = true; break; } } // The system could not retrieve the absolute path catch (ArgumentException) { } // The caller does not have the required permissions catch (System.Security.SecurityException) { } // Path contains a colon (":") catch (NotSupportedException) { } // The specified path, file name, or both exceed the system-defined maximum length catch (PathTooLongException) { } } } } } } catch (COMException e) { throw WrapIisError(e); } } } static internal Exception WrapIisError(COMException e) { if (e.ErrorCode == COMErrors.HRESULT_FROM_ERROR_PATH_BUSY) { return new ApplicationException(SR2.GetString(SR2.LockedIISMetabaseError), e); } return new ApplicationException(SR.GetString(SR.CorruptIISMetabaseError), e); } static void CheckWasInstalled() { try { using (ServiceController controller = new ServiceController(ServiceModelInstallStrings.WasName)) { IisHelper.isWasInstalled = controller.ServiceName.Equals(ServiceModelInstallStrings.WasName, StringComparison.OrdinalIgnoreCase); } } catch (InvalidOperationException exception) { Win32Exception innerException = exception.InnerException as Win32Exception; if (innerException == null || innerException.NativeErrorCode != ErrorCodes.ERROR_SERVICE_DOES_NOT_EXIST) { throw; } } } static void CheckIisInstalled() { try { using (ServiceController w3svcController = new ServiceController(ServiceModelInstallStrings.W3svc)) { if (w3svcController.ServiceName.Equals(ServiceModelInstallStrings.W3svc, StringComparison.OrdinalIgnoreCase)) { IisHelper.isIisInstalled = true; } else { IisHelper.isIisInstalled = false; } } // Only check the enable state for IIS6 or lower. if (IisHelper.isIisInstalled && !IisHelper.isWasInstalled) { if (IisHelper.IsServiceEnabled(ServiceModelInstallStrings.IISAdmin)) { IisHelper.isIisAdminEnabled = true; } else { IisHelper.isIisAdminEnabled = false; } } } catch (InvalidOperationException exception) { Win32Exception innerException = exception.InnerException as Win32Exception; if (innerException == null || innerException.NativeErrorCode != ErrorCodes.ERROR_SERVICE_DOES_NOT_EXIST) { throw; } } } static bool IsServiceEnabled(string serviceName) { bool isServiceEnabled = false; ServiceManagerHandle scManagerHandle = null; ServiceHandle serviceHandle = null; using (scManagerHandle = ServiceManagerHandle.OpenServiceManager()) { using (serviceHandle = scManagerHandle.OpenService(serviceName, NativeMethods.SERVICE_QUERY_CONFIG)) { QUERY_SERVICE_CONFIG serviceConfig = serviceHandle.QueryServiceConfig(); isServiceEnabled = (NativeMethods.SERVICE_DISABLED != serviceConfig.dwStartType); } } return isServiceEnabled; } internal static bool ShouldEnableIISAdmin { get { return IisHelper.isIisAdminEnabled; } } internal static bool ShouldInstallIis { get { return IisHelper.isIisInstalled; } } internal static bool ShouldInstallScriptMaps { get { if (IisHelper.isAspNetInstalled == null) { IisHelper.isAspNetInstalled = false; // What we do here is to check ASP.NET ScriptMaps only if W3SVC is installed, IISAdmin is enabled, // and WAS is not installed. This infers that this is for downlevel only because it cannot happen // that W3SVC & IISAdmin are installed and WAS is not installed on Vista or above. if (IisHelper.isIisInstalled && IisHelper.isIisAdminEnabled && !IisHelper.isWasInstalled) { IisHelper.CheckAspNetInstalled(); } } return IisHelper.isAspNetInstalled.Value; } } internal static bool ShouldInstallWas { get { return IisHelper.isWasInstalled; } } internal static bool ShouldInstallApplicationHost { get { return IisHelper.isApplicationHostInstalled; } } } } // File provided for Reference Use Only by Microsoft Corporation (c) 2007. // Copyright (c) Microsoft Corporation. All rights reserved.
Link Menu

This book is available now!
Buy at Amazon US or
Buy at Amazon UK
- TypeBuilder.cs
- ResourceDefaultValueAttribute.cs
- ValidatorCompatibilityHelper.cs
- RecognizerStateChangedEventArgs.cs
- EntityDataSourceQueryBuilder.cs
- SHA256.cs
- EventDescriptor.cs
- SolidBrush.cs
- Marshal.cs
- RoutedEvent.cs
- ZipIOExtraField.cs
- Parser.cs
- HttpHeaderCollection.cs
- XmlWriterTraceListener.cs
- OdbcFactory.cs
- SafeHandles.cs
- UIElementCollection.cs
- WindowCollection.cs
- SetUserPreferenceRequest.cs
- ApplicationBuildProvider.cs
- MemberHolder.cs
- BitArray.cs
- AnnouncementDispatcherAsyncResult.cs
- IMembershipProvider.cs
- SaveFileDialogDesigner.cs
- MimeXmlImporter.cs
- ListViewInsertEventArgs.cs
- EventTrigger.cs
- DispatcherTimer.cs
- BoundPropertyEntry.cs
- XPathExpr.cs
- ClientApiGenerator.cs
- SyndicationLink.cs
- StylusEventArgs.cs
- ValidationEventArgs.cs
- CuspData.cs
- CapabilitiesState.cs
- XmlnsCache.cs
- ColumnResizeUndoUnit.cs
- DataGridViewColumnEventArgs.cs
- TripleDESCryptoServiceProvider.cs
- SoapCodeExporter.cs
- ObjectIDGenerator.cs
- XPathArrayIterator.cs
- DataGridViewRow.cs
- NegotiationTokenAuthenticatorState.cs
- RotateTransform3D.cs
- StoreContentChangedEventArgs.cs
- ConnectivityStatus.cs
- SizeLimitedCache.cs
- RelatedPropertyManager.cs
- CodeComment.cs
- SchemaExporter.cs
- GeneralTransform.cs
- NativeCppClassAttribute.cs
- SamlSubject.cs
- DrawListViewItemEventArgs.cs
- Freezable.cs
- GroupJoinQueryOperator.cs
- CompilerCollection.cs
- TreeNodeBinding.cs
- Matrix3DValueSerializer.cs
- TextPointer.cs
- DataIdProcessor.cs
- DataGridViewRowDividerDoubleClickEventArgs.cs
- ScrollProviderWrapper.cs
- SHA1CryptoServiceProvider.cs
- LinqDataSourceValidationException.cs
- ForceCopyBuildProvider.cs
- PlanCompilerUtil.cs
- ImageListStreamer.cs
- ErrorStyle.cs
- InfoCard.cs
- ExpandableObjectConverter.cs
- WhereQueryOperator.cs
- ChangePassword.cs
- FormViewDeletedEventArgs.cs
- PropertyDescriptors.cs
- StructuredTypeInfo.cs
- StreamingContext.cs
- SortExpressionBuilder.cs
- SQLConvert.cs
- ByteAnimationBase.cs
- PartialCachingAttribute.cs
- LineGeometry.cs
- CustomServiceCredentials.cs
- StreamHelper.cs
- clipboard.cs
- XmlElementAttribute.cs
- TableLayoutSettingsTypeConverter.cs
- ExternalCalls.cs
- RangeValidator.cs
- TimelineGroup.cs
- OverflowException.cs
- PropertyMap.cs
- HtmlInputSubmit.cs
- Pointer.cs
- RsaEndpointIdentity.cs
- Highlights.cs
- StylusDevice.cs