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
- ToolboxItemFilterAttribute.cs
- DesignUtil.cs
- ActivityWithResultConverter.cs
- WebBrowserContainer.cs
- TraceSection.cs
- Options.cs
- VerticalAlignConverter.cs
- EqualityComparer.cs
- XLinq.cs
- DoubleLinkList.cs
- PatternMatcher.cs
- ContainerAction.cs
- ContextMenu.cs
- CustomErrorsSectionWrapper.cs
- FillRuleValidation.cs
- ValuePatternIdentifiers.cs
- WaitHandleCannotBeOpenedException.cs
- QueryCacheManager.cs
- CompilerErrorCollection.cs
- HtmlFormParameterReader.cs
- GeneralTransform3DCollection.cs
- WebPart.cs
- MetadataItem_Static.cs
- SpecialNameAttribute.cs
- FlowLayoutSettings.cs
- EnumDataContract.cs
- WebConfigurationManager.cs
- AssemblyBuilderData.cs
- IWorkflowDebuggerService.cs
- WriteStateInfoBase.cs
- DefaultPropertyAttribute.cs
- BaseTreeIterator.cs
- HttpTransportSecurityElement.cs
- FixedTextPointer.cs
- DbConnectionPoolCounters.cs
- GrammarBuilder.cs
- FontInfo.cs
- SystemSounds.cs
- DispatcherFrame.cs
- RNGCryptoServiceProvider.cs
- FocusWithinProperty.cs
- TraceLevelStore.cs
- ManagedWndProcTracker.cs
- ScalarType.cs
- SqlRetyper.cs
- ClickablePoint.cs
- LockRecursionException.cs
- AuthenticationModuleElementCollection.cs
- SmiMetaData.cs
- QilLiteral.cs
- HtmlControl.cs
- AmbientLight.cs
- PtsHost.cs
- XmlQueryContext.cs
- WebControlsSection.cs
- CollectionViewProxy.cs
- NavigationProperty.cs
- PageAsyncTaskManager.cs
- ConsumerConnectionPoint.cs
- IApplicationTrustManager.cs
- RepeatButtonAutomationPeer.cs
- ToolboxComponentsCreatedEventArgs.cs
- Claim.cs
- TraceListener.cs
- ContextStaticAttribute.cs
- SiteMapSection.cs
- _NativeSSPI.cs
- SignatureGenerator.cs
- SchemaImporterExtension.cs
- MaskedTextBox.cs
- DbMetaDataColumnNames.cs
- XmlSchemaAttributeGroup.cs
- XmlLanguage.cs
- StopStoryboard.cs
- CustomSignedXml.cs
- CatalogPartChrome.cs
- SplineQuaternionKeyFrame.cs
- CellParaClient.cs
- shaperfactoryquerycacheentry.cs
- XmlElementCollection.cs
- SignedInfo.cs
- ReliableSession.cs
- EmptyControlCollection.cs
- SnapshotChangeTrackingStrategy.cs
- WebExceptionStatus.cs
- WorkflowMarkupSerializationManager.cs
- Inflater.cs
- NeedSkipTokenVisitor.cs
- VoiceInfo.cs
- DWriteFactory.cs
- PipelineDeploymentState.cs
- MatrixAnimationUsingKeyFrames.cs
- MetadataException.cs
- DecoratedNameAttribute.cs
- VariableReference.cs
- SyndicationSerializer.cs
- LinqDataSourceInsertEventArgs.cs
- EntityReference.cs
- ValueUtilsSmi.cs
- MenuCommand.cs