InfoCardService.cs source code in C# .NET

Source code for the .NET framework in C#

                        

Code:

/ WCF / WCF / 3.5.30729.1 / untmp / Orcas / SP / ndp / cdf / src / WCF / infocard / Service / managed / Microsoft / InfoCards / InfoCardService.cs / 1 / InfoCardService.cs

                            //------------------------------------------------------------------------------ 
// Copyright (c) Microsoft Corporation.  All rights reserved.
//-----------------------------------------------------------------------------
//
// Presharp uses the c# pragma mechanism to supress its warnings. 
// These are not recognised by the base compiler so we need to explictly
// disable the following warnings. See http://winweb/cse/Tools/PREsharp/userguide/default.asp 
// for details. 
//
#pragma warning disable 1634, 1691      // unknown message, unknown pragma 



namespace Microsoft.InfoCards 
{
    using System; 
    using System.Text; 
    using System.IO;
    using System.Collections; 
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Runtime.InteropServices;
    using System.Security.AccessControl; 
    using System.Security.Principal;
    using System.ServiceProcess; 
    using System.Threading; 
    using System.Reflection;
    using Microsoft.InfoCards.Diagnostics; 
    using System.Net;
    using System.Net.Security;
    using IDT = Microsoft.InfoCards.Diagnostics.InfoCardTrace;
 
    //
    // Summary: 
    // This is the class that receives service control manager messages and acts accordingly, such as 
    // starting or stopping the service.
    // 
    internal class InfoCardService : ServiceBase
    {
        public const int WindowsVistaMajorVersion = 6;
 
        public const string FullServiceName = "idsvc";
 
 
        //
        // Declare service stopping delegate. 
        //
        static public event EventHandler Stopping;

        // 
        // An instance of a delegate passed out to native code.  It's
        // held here so that the garbage collector doesn't get rid of it 
        // while native code is still using it. 
        //
        RpcCallbacks m_rpcCallbacks; 

        static public LifeTimeMonitor LifeTimeMonitor = null;

 
        public InfoCardService()
        { 
            // 
            // Set privileges on our exe
            // 
            // For downlevel: This is being called by managed code so that it can be overridden
            // by the service update
            //
            // For XP Tablet PC, we need debug privileges in order to locate the instance of tcserver 
            // that is associated with our desktop.
            // 
            // For LH+ the code to strip privileges exists in S.SM.Install.dll. 
            // So we'd also need to change registry setting with update.
            // 

            bool isTabletPC = (0 != NativeMethods.GetSystemMetrics( NativeMethods.SM_TABLETPC ));
            bool isDownlevel = (Environment.OSVersion.Version.Major < WindowsVistaMajorVersion);
            bool isXPTabletPC = isTabletPC && isDownlevel; 

            if( 0 != NativeMcppMethods.AdjustPrivilegesWrapper( isXPTabletPC ) ) 
            { 
                //
                // Not an expected condition, should crash the service. 
                //
                Crash( new Win32Exception() );
            }
 
            try
            { 
                NativeMcppMethods.AdjustServiceProcessSecurity(); 
            }
            catch( Win32Exception e ) 
            {
                Crash( e );
            }
 
            ServiceName = InfoCardService.FullServiceName;
            CanStop = true; 
            CanShutdown = true; 
            CanPauseAndContinue = false;
            CanHandleSessionChangeEvent = true; 
            CanHandlePowerEvent = false;
            AutoLog = true;

            m_rpcCallbacks.uiAgentRequestAuthorize = 
                new RpcAuthorizeCallback( UIAgentRequest.Authorize );
 
            m_rpcCallbacks.uiAgentRequestBindToService = 
                new RpcUIAgentBindToServiceCallback( UIAgentRequest.BindToService );
 
            m_rpcCallbacks.clientRequestAuthorize =
                new RpcAuthorizeCallback( ClientRequest.Authorize );

            m_rpcCallbacks.clientRequestBindToService = 
                new RpcClientBindToServiceCallback( ClientUIRequest.BindToService );
 
            m_rpcCallbacks.requestFactoryProcessNewRequest = 
                new RpcProcessNewRequestCallback( RequestFactory.ProcessNewRequest );
 
            m_rpcCallbacks.allocMem =
                new RpcAllocMemCallback( Marshal.AllocHGlobal );

            m_rpcCallbacks.freeMem = 
                new RpcFreeMemCallback( Marshal.FreeHGlobal );
 
            m_rpcCallbacks.rundownClientContext = 
                new RpcRundownClientContextHandle( ClientUIRequest.RemoveAndDisposeContextMapping );
 

            //
            // Create the service lifetime monitor.
            // 
            InfoCardService.LifeTimeMonitor = new LifeTimeMonitor();
 
            // 
            // The .NET validator does NO CRL check by default. Also it does not check for peer trust.
            // This will get invoked for all https interactions from managed code. 
            // To remove the inconsistency between this and the CardSpace validator, implement the callback in the .NET validator.
            // The callback we implement will check for CRL offline and/or peer trust.
            //
            ServicePointManager.ServerCertificateValidationCallback = 
                new RemoteCertificateValidationCallback( InfoCardX509Validator.ValidateChainOrPeerCallback );
        } 
 

 
        protected override void Dispose( bool disposing )
        {
            base.Dispose( disposing );
        } 

        // 
        // Summary: 
        // Starts the service.
        // 
        // Remarks:
        // Starts the native RPC layer and passes out the static delegates that that layer needs to call
        // back in to managed code when an RPC request is received.
        // 
        protected override void OnStart( string[] args )
        { 
            base.OnStart( args ); 

            AppDomain dom = AppDomain.CurrentDomain; 

            dom.SetPrincipalPolicy( PrincipalPolicy.WindowsPrincipal );

            using( HGlobalSafeHandle callbacks = HGlobalSafeHandle.Construct( Marshal.SizeOf( m_rpcCallbacks ) ) ) 
            {
                Marshal.StructureToPtr( m_rpcCallbacks, callbacks.DangerousGetHandle(), false ); 
 
                uint status = NativeMcppMethods.InfoCardStartRpcServerWrapper(
                    InfoCardUIAgent.UiAgentFullPath, 
                    callbacks.DangerousGetHandle() );

                if( 0 != status )
                { 
                    throw IDT.ThrowHelperError( new Win32Exception( (int)status ) );
                } 
            } 

        } 
        //
        // Summary:
        // Called when the SCM wants the service stop.  When called the native RPC layer is stopped.
        protected override void OnStop() 
        {
            try 
            { 
                InfoCardUIAgent.DoShutdown();
                NativeMcppMethods.InfoCardStopRpcServerWrapper(); 

                //
                // Raise service stopping event.
                // 
                OnStopping();
            } 
            #pragma warning suppress 56500  // do not catch all exceptions. 
            catch( Exception e )
            { 
                IDT.TraceAndLogException( e );
                //
                // We need to catch the exception becuase we are shutting down
                //      if it throws, it will leave the SCM in and invalid state. 
                //
            } 
            finally 
            {
                base.OnStop( ); 
            }
        }

        // 
        // Summary:
        // Raises service stopping event to registered handlers. 
        // 
        protected virtual void OnStopping()
        { 
            if( null != Stopping )
            {
                Stopping( this, new EventArgs() );
            } 
        }
 
        // 
        // Summary:
        //  Called whenever something changes about the TS Sessions on the machine. 
        //
        protected override void OnSessionChange( SessionChangeDescription changeDescription )
        {
            // 
            // If this is a SessionLogOff then we want to make sure that we shut down any UIAgents in that session.
            // This prevents any following users from logging in and seeing the ui from the previous user of that 
            // session. 
            //
            if( System.ServiceProcess.SessionChangeReason.SessionLogoff == changeDescription.Reason ) 
            {
                InfoCardUIAgent.OnLogout( (uint)changeDescription.SessionId );
            }
        } 

        // 
        // Summary: 
        // Called when an unrecoverable error has occurred.
        // 
        static public void Crash()
        {
            InfoCardService.Crash( null );
        } 

        // 
        // Summary: 
        // Called when an unrecoverable error has occurred.
        // Log that something awful happened, and failfast the process. 
        //
        // Parameters:
        // e     - The exception that is at the root of the unrecoverable error.  This is logged to the
        //         debug output stream. 
        //
        static public void Crash( Exception e ) 
        { 

#if DEBUG 
            Debugger.Log( 0, "", SR.GetString( SR.ServiceEncounteredFatalError ) );
            string failFastMessage;
            if ( null != e )
            { 
                Debugger.Log( 0, "", e.ToString() );
                IDT.TraceDebug( "Fatal exception - terminating service {0} ({1})\n{2}", e.Message, e.Source, e.StackTrace ); 
                failFastMessage = e.Message; 
            }
            else 
            {
                failFastMessage = SR.GetString( SR.ServiceCrashedWithoutException );
            }
            if( Debugger.IsAttached ) 
            {
                Debugger.Launch(); 
                Debugger.Break(); 
            }
 
            Microsoft.InfoCards.Diagnostics.InfoCardTrace.FailFast( failFastMessage );

            Environment.Exit( 1 );
#else 
            IDT.FailFast( e.Message );
#endif 
        } 

    } 
}

// File provided for Reference Use Only by Microsoft Corporation (c) 2007.
// Copyright (c) Microsoft Corporation. All rights reserved.
                        

Link Menu

Network programming in C#, Network Programming in VB.NET, Network Programming in .NET
This book is available now!
Buy at Amazon US or
Buy at Amazon UK