Exemple #1
0
        public static void Main(string[] args)
        {
            try
            {
                //Get Url of Web Service
                ServicesSection        servicesSection = (ServicesSection)ConfigurationManager.GetSection("system.serviceModel/services");
                ServiceEndpointElement endpoint        = servicesSection.Services[0].Endpoints[0];
                string endpointAddress = endpoint.Address.ToString();

                //Open Web Service
                //ReceiveAdapterService service = new ReceiveAdapterService();
                ServiceHost serviceHost = new ServiceHost(typeof(ReceiveAdapterService));
                serviceHost.Open();

                Console.WriteLine("---------------------------------------------------------");
                Console.WriteLine("Connect Web Services Started. To Stop, Press any key.....");
                Console.WriteLine("---------------------------------------------------------");
                Console.WriteLine("Service Url :" + endpointAddress);
            }
            catch (Exception exception)
            {
                Console.WriteLine("Error in Hosting Receive Adapter Service");
                Console.WriteLine("Press any key to quit!.............");
                Console.WriteLine(exception.Message);
                Console.WriteLine(exception.StackTrace);
            }

            Console.ReadLine();
        }
        /// <summary>
        /// 初始化WCF元数据
        /// </summary>
        /// <param name="config"></param>
        private static WCFServiceMeta InitializeWCFServiceMeta(string contextName, System.Configuration.Configuration config)
        {
            WCFServiceMeta  wm      = new WCFServiceMeta();
            ServicesSection sconfig = config.GetSection(GlobalParams.ServiceHostSession) as ServicesSection;

            if (sconfig != null)
            {
                if (sconfig.Services.Count > 0)
                {
                    wm.IsExistService        = true;
                    wm.ServicesConfiguration = sconfig;
                    wm.ContextName           = contextName.ToLower();
                    wm.ChildConfiguration    = config;
                }
                else
                {
                    wm.IsExistService = false;
                }
            }
            BehaviorsSection bconfig = config.GetSection(GlobalParams.BehaviorSession) as BehaviorsSection;

            if (bconfig != null)
            {
                wm.BehaviorsConfiguration = bconfig;
            }
            return(wm);
        }
Exemple #3
0
        public List <string> GetServiceNamesFromConfigFile()
        {
            List <string>            ServiceNames = null;
            Configuration            appConfig    = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            ServiceModelSectionGroup serviceModel = ServiceModelSectionGroup.GetSectionGroup(appConfig);
            ServicesSection          services     = serviceModel.Services;
            ServiceElementCollection sec          = services.Services;

            if (sec.Count > 0)
            {
                ServiceNames   = new List <string>();
                m_serviceTypes = new Dictionary <string, Type>();
                foreach (ServiceElement se in sec)
                {
                    ServiceNames.Add(se.Name);

                    Type t = Type.GetType(se.Name);
                    if (t == null)
                    {
                        string[] sa = se.Name.Split('.');
                        System.Reflection.Assembly a = System.Reflection.Assembly.LoadFrom(sa[0] + ".dll");
                        t = a.GetType(se.Name);
                    }

                    m_serviceTypes.Add(se.Name, t);
                }
            }
            return(ServiceNames);
        }
Exemple #4
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            WebAPIBuilder.BuildWebAPI(ServiceConfiguration.WebAPIUrl);
            WCFHost wcfHost = new WCFHost();

            if (Environment.UserInteractive && Debugger.IsAttached)
            {
                Console.WriteLine("WCFHost running on console mode.");
                Configuration            configuration   = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                ServiceModelSectionGroup serviceModel    = ServiceModelSectionGroup.GetSectionGroup(configuration);
                ServicesSection          servicesSection = serviceModel.Services;

                foreach (ServiceEndpointElement endpoint in servicesSection.Services.Cast <ServiceElement>().Select(s => s.Endpoints).SelectMany(ss => ss.OfType <ServiceEndpointElement>()))
                {
                    Console.WriteLine("Address: {0}", endpoint.Address);
                }

                wcfHost.Start();

                Console.WriteLine("Press any key to stop program...");
                Console.ReadKey();

                wcfHost.Stop();
            }
            else
            {
                ServiceBase.Run(wcfHost);
            }
        }
        public static void Main(string[] args)
        {
            try
            {
                UnityContainer container = new UnityContainer();
                container.LoadConfiguration();

                ServicesSection services = ConfigurationManager.GetSection("system.serviceModel/services") as ServicesSection;

                // enumerate over each <service> node
                foreach (ServiceElement currentServiceElement in services.Services)
                {
                    Console.WriteLine("Name: {0} / Behavior: {1}", currentServiceElement.Name, currentServiceElement.BehaviorConfiguration);

                    //// enumerate over all endpoints for that service
                    foreach (ServiceEndpointElement see in currentServiceElement.Endpoints)
                    {
                        Console.WriteLine("Endpoint: Address = {0} / Binding = {1} / Contract = {2}", see.Address, see.Binding, see.Contract);
                        ////host.AddServiceEndpoint(
                        Console.WriteLine();
                    }
                }

                ServiceModelEx.ServiceHost <DepartmentBusinessService> host1 = new ServiceModelEx.ServiceHost <DepartmentBusinessService>();
                host1.Open();

                foreach (var se in host1.Description.Endpoints)
                {
                    Console.WriteLine("ListenUri: " + se.ListenUri.ToString());
                    Console.WriteLine("Address: " + se.Address.Uri.ToString());
                    Console.WriteLine("Binding: " + se.Binding.Name);
                    Console.WriteLine("Contract :" + se.Contract.Name);
                    Console.WriteLine(string.Empty);
                }

                ////ServiceModelEx.ServiceHost<ZebraAsyncControllerFascade> hostAsync = new ServiceModelEx.ServiceHost<ZebraAsyncControllerFascade>();
                ////hostAsync.Open();

                Console.WriteLine("HOST is running");
                Console.ReadLine();

                host1.Close();
                ////hostAsync.Close();
            }
            catch (Exception ex)
            {
                Exception exc = ex;
                while (null != exc)
                {
                    Console.WriteLine(exc.Message);
                    exc = exc.InnerException;
                }

                Console.WriteLine("Press ENTER to Exit");
                Console.ReadLine();
            }
        }
Exemple #6
0
        public static ServiceElement GetServiceElement(string serviceName)
        {
            ServicesSection servicesSection = ConfigurationManager.GetSection("system.serviceModel/services") as ServicesSection;

            for (int i = 0; i < servicesSection.Services.Count; i++)
            {
                if (servicesSection.Services[i].Name == serviceName)
                {
                    return(servicesSection.Services[i]);
                }
            }
            throw new IndexOutOfRangeException();
        }
        void InitCache()
        {
            ServicesSection serviesSection = ConfigurationManager.GetSection("system.serviceModel/services") as ServicesSection;

            _serviceDic = new Dictionary <string, int>();
            if (serviesSection != null)
            {
                for (int i = 0; i < serviesSection.Services.Count; i++)
                {
                    _serviceDic.Add(serviesSection.Services[i].Name, 1);
                }
            }
        }
        /// <summary>
        /// 读取EndpointAddress
        /// </summary>
        /// <param name="endpointName"></param>
        /// <returns></returns>
        public static string GetEndpointAddress(string endpointName)
        {
            ServicesSection servicesSection = config.GetSection("system.serviceModel/services") as ServicesSection;

            foreach (ServiceElement service in servicesSection.Services)
            {
                foreach (ServiceEndpointElement item in service.Endpoints)
                {
                    if (item.Name == endpointName)
                    {
                        return(item.Address.ToString());
                    }
                }
            }
            return(string.Empty);
        }
Exemple #9
0
        public static ServicesSection Services(this CustomConfiguration config)
        {
            lock (_lockObjectServices)
            {
                if (_servicesSection == null)
                {
                    _servicesSection = ConfigurationManager.GetSection(ServicesSection.SectionName) as ServicesSection;

                    if (_servicesSection == null)
                    {
                        _servicesSection = new ServicesSection();
                    }
                }
            }

            return(_servicesSection);
        }
Exemple #10
0
        public void Start()
        {
            // get the <system.serviceModel> / <services> config section
            ServicesSection services = ConfigurationManager.GetSection("system.serviceModel/services") as ServicesSection;

            // get all classs
            var allTypes = AppDomain.CurrentDomain.GetAssemblies().ToList().SelectMany(s => s.GetTypes()).Where(t => t.IsClass == true);

            // enumerate over each <service> node
            foreach (ServiceElement service in services.Services)
            {
                Type serviceType = allTypes.SingleOrDefault(t => t.FullName == service.Name);
                if (serviceType == null)
                {
                    continue;
                }

                ServiceHost serviceHost = new ServiceHost(serviceType);

                Log.InfoFormat("Open Service Host for {0} on (at least) {1}", serviceType.Name, serviceHost.BaseAddresses.FirstOrDefault());
                serviceHost.Open();
            }



            //// a URI which is already allowed by Visual Studio by default
            //Uri baseAddress = new Uri("http://localhost:8733/Design_Time_Addresses/CEP/SimulationInformation");

            //// Create the ServiceHost.
            //ServiceHost host = new ServiceHost(typeof(SimulationInformationService), baseAddress);
            //Binding wsDualBinding = new WSDualHttpBinding();
            //host.AddServiceEndpoint(typeof(ISimulationInformationService), wsDualBinding, "http://localhost:8733/Design_Time_Addresses/CEP/SimulationInformation");

            //// Enable metadata publishing.
            //ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            //smb.HttpGetEnabled = true;
            //smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
            //host.Description.Behaviors.Add(smb);

            //// Open the ServiceHost to start listening for messages. Since
            //// no endpoints are explicitly configured, the runtime will create
            //// one endpoint per base address for each service contract implemented
            //// by the service.
            //host.Open();
        }
        /// <summary>
        /// 设置EndpointAddress
        /// </summary>
        /// <param name="endpointName"></param>
        /// <param name="address"></param>
        public static void SetEndpointAddress(string endpointName, string address)
        {
            ServicesSection clientSection = config.GetSection("system.serviceModel/services") as ServicesSection;

            foreach (ServiceElement service in clientSection.Services)
            {
                if (service.Name == endpointName)
                {
                    foreach (BaseAddressElement item in service.Host.BaseAddresses)
                    {
                        item.BaseAddress = address;
                    }
                    break;
                }
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("system.serviceModel");
        }
        /// <summary>
        /// 获取终节点集合
        /// </summary>
        /// <returns></returns>
        public static List <AppInfo> GetEndPoint()
        {
            ServicesSection servicesSection = config.GetSection("system.serviceModel/services") as ServicesSection;
            List <AppInfo>  list            = new List <AppInfo>();

            foreach (ServiceElement service in servicesSection.Services)
            {
                string endpointName = service.Name;
                foreach (BaseAddressElement item in service.Host.BaseAddresses)
                {
                    AppInfo appInfo = new AppInfo();
                    appInfo.Key   = endpointName;
                    appInfo.Value = item.BaseAddress;
                    list.Add(appInfo);
                }
            }
            return(list);
        }
Exemple #13
0
        private void GenerateServiceConfiguration()
        {
            // Get a pointer to system.serviceModel section.
            ConfigurationSectionGroup csg = configuration.SectionGroups["system.serviceModel"];

            // Notify if we get a null reference.
            Debug.Assert(csg != null, "system.serviceModel section could not be found in the configuration.");

            if (csg != null)
            {
                // Get a reference to the client section.
                ClientSection cs = csg.Sections["client"] as ClientSection;
                // Also get a reference to the services section.
                ServicesSection ss = csg.Sections["services"] as ServicesSection;

                // If there is no services section, we create a new one.
                if (ss == null)
                {
                    // Create a new services section.
                    ss = new ServicesSection();
                    // Add it to the sections collection.
                    csg.Sections.Add("services", ss);
                }

                string         fqServiceTypeName = GetFullyQulifiedTypeName(GetServiceTypeName());
                ServiceElement se = new ServiceElement(fqServiceTypeName);
                ss.Services.Add(se);

                if (cs != null)
                {
                    foreach (ChannelEndpointElement cee in cs.Endpoints)
                    {
                        // TODO: May be we will want to give an option to use fully qulified interface names
                        // in the endpoints.
                        ServiceEndpointElement see = new ServiceEndpointElement(cee.Address, cee.Contract);
                        see.BehaviorConfiguration = cee.BehaviorConfiguration;
                        see.BindingConfiguration  = cee.BindingConfiguration;
                        see.Binding = cee.Binding;
                        se.Endpoints.Add(see);
                    }
                    csg.Sections.Remove("client");
                }
            }
        }
Exemple #14
0
        /// <summary>
        /// 结束
        /// </summary>
        public void Terminate()
        {
            lock (syncLock)
            {
                ServicesSection serviesSection = ConfigurationManager.GetSection("system.serviceModel/services") as ServicesSection;

                if (serviesSection != null)
                {
                    for (int i = 0; i < serviesSection.Services.Count; i++)
                    {
                        switch (serviesSection.Services[i].Name)
                        {
                        default:
                            break;
                        }
                    }
                }
            }
        }
        public ServiceModelConfigurationManager(System.Configuration.Configuration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            this.configuration            = configuration;
            this.serviceModelSectionGroup = this.configuration.SectionGroups.Get(ServiceModelSectionName) as ServiceModelSectionGroup;

            if (serviceModelSectionGroup == null)
            {
                throw new System.Configuration.ConfigurationErrorsException();
            }

            // check for valid WCF sections
            // will throw ConfigurationErrorsException on any invalid element
            ServicesSection services = this.serviceModelSectionGroup.Services;
            ClientSection   client   = this.serviceModelSectionGroup.Client;
        }
        public static bool GetIsSelfHosting(Type contractType)
        {
            bool            isSelfHosting = false;
            ServicesSection config        = ConfigurationManager.GetSection("system.serviceModel/services") as ServicesSection;

            if (config != null)
            {
                foreach (ServiceElement service in config.Services)
                {
                    foreach (ServiceEndpointElement endpoint in service.Endpoints)
                    {
                        if (endpoint.Contract.Equals(contractType.FullName))
                        {
                            isSelfHosting = true;
                            break;
                        }
                    }
                }
            }
            return(isSelfHosting);
        }
Exemple #17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:ServiceModelConfigurationManager"/> class.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        public ServiceModelConfigurationManager(System.Configuration.Configuration configuration)
        {
            this.configuration            = configuration;
            this.serviceModelSectionGroup = ServiceModelSectionGroup.GetSectionGroup(this.configuration);

            if (serviceModelSectionGroup == null)
            {
                throw new System.Configuration.ConfigurationErrorsException(
                          Properties.Resources.ConfigurationSectionNotFoundException);
            }

            // check for valid WCF sections
            // will throw ConfigurationErrorsException on any invalid element
            ServicesSection services = this.serviceModelSectionGroup.Services;

            System.Diagnostics.Debug.Assert(services != null, "Config issue in serviceModelSectionGroup.Services");

            ClientSection client = this.serviceModelSectionGroup.Client;

            System.Diagnostics.Debug.Assert(client != null, "Config issue in serviceModelSectionGroup.Client");
        }
Exemple #18
0
        /// <summary>
        /// Registers WCF services type mappings from the given configuration excluding specified endpoints if needed.
        /// </summary>
        public static IServiceCollection AddWcfServices(this IServiceCollection container, ContextInformation ctx, Func <ServiceEndpointElement, bool> exclEndpoints)
        {
            string          servicesPath = "system.serviceModel/services";
            ServicesSection services     = (ServicesSection)(ctx != null ? ctx.GetSection(servicesPath) : ConfigurationManager.GetSection(servicesPath));

            foreach (ServiceElement service in services.Services)
            {
                Type serviceType = AppInitializer.GetType(service.Name);
                if (serviceType == null)
                {
                    continue;
                }
                foreach (ServiceEndpointElement endpoint in service.Endpoints)
                {
                    Type contractType = AppInitializer.GetType(endpoint.Contract);
                    if (contractType == null || endpoint.IsSystemEndpoint || exclEndpoints != null && exclEndpoints(endpoint))
                    {
                        continue;
                    }
                    container.AddScoped(contractType, serviceType);
                }
            }
            return(container);
        }
Exemple #19
0
        /// <summary>
        /// This method adds the neccessary configuration elements to hook up
        /// Thinktecture.ServiceModel.Extensions.Metdata extension to service the
        /// service code being generated.
        /// </summary>
        private void AddMetadataServiceBehavior()
        {
            // Get a pointer to system.serviceModel section.
            ConfigurationSectionGroup csg = configuration.SectionGroups["system.serviceModel"];

            // Notify if we get a null reference.
            Debug.Assert(csg != null, "system.serviceModel section could not be found in the configuration.");

            if (csg != null)
            {
                // Try to find the extensions element.
                ExtensionsSection extensionsSection = csg.Sections["extensions"] as ExtensionsSection;
                // Create it if it wasn't found.
                if (extensionsSection == null)
                {
                    extensionsSection = new ExtensionsSection();
                    csg.Sections.Add("extensions", extensionsSection);
                }

                // Now create the new behavior extension.
                ExtensionElement metadataServiceExtensionElement = new ExtensionElement();
                metadataServiceExtensionElement.Name = "metadataService";
                //TODO: Make this more dynamic so it can discover the assembly version etc otherwise this will always throw exceptions
                // that the behavior extension was not found in the collection.
                metadataServiceExtensionElement.Type = "Thinktecture.ServiceModel.Extensions.Metadata.StaticMetadataBehaviorElement, Thinktecture.ServiceModel.Extensions.Metadata, Version=1.1.0.0, Culture=neutral, PublicKeyToken=20fb7cabbfb92df4";

                // Add the newly created behavior extension to the extensions section.
                extensionsSection.BehaviorExtensions.Add(metadataServiceExtensionElement);

                // Try to find the behaviors element.
                BehaviorsSection behaviorsSection = csg.Sections["behaviors"] as BehaviorsSection;
                // Create it if it wasn't found.
                if (behaviorsSection == null)
                {
                    behaviorsSection = new BehaviorsSection();
                    csg.Sections.Add("behaviors", behaviorsSection);
                }

                // Add the new service behavior.
                ServiceBehaviorElement serviceBehavior = new ServiceBehaviorElement();
                serviceBehavior.Name = "metadataServiceExtension";

                behaviorsSection.ServiceBehaviors.Add(serviceBehavior);

                StaticMetadataBehaviorElement behaviorExtensionElement = new StaticMetadataBehaviorElement();
                behaviorExtensionElement.RootMetadataFileLocation = options.MetadataLocation;
                behaviorExtensionElement.MetadataUrl = "wsdl";
                serviceBehavior.Add(behaviorExtensionElement);

                // Find the service section.
                ServicesSection servicesSection = csg.Sections["services"] as ServicesSection;
                if (servicesSection != null)
                {
                    string         fqServiceTypeName = GetFullyQulifiedTypeName(GetServiceTypeName());
                    ServiceElement serviceElement    = servicesSection.Services[fqServiceTypeName] as ServiceElement;
                    if (serviceElement != null)
                    {
                        serviceElement.BehaviorConfiguration = "metadataServiceExtension";
                    }
                }
            }
        }
Exemple #20
0
 protected void LoadConfigurationSection(ServiceElement element)
 {
     ServicesSection services = ConfigUtil.ServicesSection;
 }
Exemple #21
0
        public WebHostedComPlusServiceHost(string webhostParams, Uri[] baseAddresses)
        {
            foreach (Uri address in baseAddresses)
            {
                this.InternalBaseAddresses.Add(address);
            }

            // Split up the parameter string into "clsid,appid".
            //
            string[] parameters = webhostParams.Split(',');
            if (parameters.Length != 2)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(System.ServiceModel.ComIntegration.Error.ListenerInitFailed(
                                                                              SR.GetString(SR.ServiceStringFormatError,
                                                                                           webhostParams)));
            }

            Guid clsid;
            Guid appId;

            if (!DiagnosticUtility.Utility.TryCreateGuid(parameters[0], out clsid))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(System.ServiceModel.ComIntegration.Error.ListenerInitFailed(
                                                                              SR.GetString(SR.ServiceStringFormatError,
                                                                                           webhostParams)));
            }

            if (!DiagnosticUtility.Utility.TryCreateGuid(parameters[1], out appId))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(System.ServiceModel.ComIntegration.Error.ListenerInitFailed(
                                                                              SR.GetString(SR.ServiceStringFormatError,
                                                                                           webhostParams)));
            }

            // "B" == "With dashes and curly braces"
            // (The catalog gives us GUIDs in this format)
            //
            string clsidString = clsid.ToString("B").ToUpperInvariant();

            // Look up the COM+ AdminSDK information for this
            // AppID/CLSID pair.
            //
            ComCatalogObject application;

            application = CatalogUtil.FindApplication(appId);
            if (application == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(System.ServiceModel.ComIntegration.Error.ListenerInitFailed(
                                                                              SR.GetString(SR.ApplicationNotFound,
                                                                                           appId.ToString("B").ToUpperInvariant())));
            }

            ComCatalogCollection classes;

            classes = application.GetCollection("Components");

            ComCatalogObject classObject = null;

            foreach (ComCatalogObject tempClassObject in classes)
            {
                string otherClsid = (string)tempClassObject.GetValue("CLSID");
                if (clsidString.Equals(
                        otherClsid,
                        StringComparison.OrdinalIgnoreCase))
                {
                    classObject = tempClassObject;
                    break;
                }
            }

            if (classObject == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(System.ServiceModel.ComIntegration.Error.ListenerInitFailed(
                                                                              SR.GetString(SR.ClsidNotInApplication,
                                                                                           clsidString,
                                                                                           appId.ToString("B").ToUpperInvariant())));
            }

            // Load up Indigo configuration, get the configuration for
            // this service.
            //
            ServicesSection services = ServicesSection.GetSection();
            ServiceElement  service  = null;

            foreach (ServiceElement serviceInConfig in services.Services)
            {
                Guid clsidFromConfig = Guid.Empty;
                Guid appidFromConfig = Guid.Empty;

                string[] serviceParams = serviceInConfig.Name.Split(',');
                if (serviceParams.Length != 2)
                {
                    continue;
                }


                if (!DiagnosticUtility.Utility.TryCreateGuid(serviceParams[0], out appidFromConfig))
                {
                    // We are tolerant of having non COM+ based services
                    // for webhost.
                    continue;
                }

                if (!DiagnosticUtility.Utility.TryCreateGuid(serviceParams[1], out clsidFromConfig))
                {
                    // We are tolerant of having non COM+ based services
                    // for webhost.
                    continue;
                }

                if (clsidFromConfig == clsid && appidFromConfig == appId)
                {
                    service = serviceInConfig;
                    break;
                }
            }
            if (service == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(System.ServiceModel.ComIntegration.Error.ListenerInitFailed(
                                                                              SR.GetString(SR.ClsidNotInConfiguration,
                                                                                           clsidString)));
            }


            // Hosting mode evaluation
            //
            HostingMode hostingMode;
            int         activation = (int)application.GetValue("Activation");

            if (activation == 0)
            {
                hostingMode = HostingMode.WebHostInProcess;
            }
            else
            {
                hostingMode = HostingMode.WebHostOutOfProcess;
            }

            // Now we have everything we need, do common
            // initialization.
            //
            Initialize(clsid,
                       service,
                       application,
                       classObject,
                       hostingMode);
        }
        public void Startup(IProcessInitControl control)
        {
            // Find our application object, and associated components
            // (classes) collection from the COM+ catalog.
            //
            applicationId = ContextUtil.ApplicationId;

            ComPlusDllHostInitializerTrace.Trace(TraceEventType.Information, TraceCode.ComIntegrationDllHostInitializerStarting,
                                                 SR.TraceCodeComIntegrationDllHostInitializerStarting, applicationId);

            Thread pingThread = null;

            try
            {
                pingThread = new Thread(PingProc);
                pingThread.Start(control);

                ComCatalogObject application;
                application = CatalogUtil.FindApplication(applicationId);
                if (application == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(
                                                                                  SR.GetString(SR.ApplicationNotFound,
                                                                                               applicationId.ToString("B").ToUpperInvariant())));
                }

                bool processPooled = ((int)application.GetValue("ConcurrentApps")) > 1;
                if (processPooled)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(
                                                                                  SR.GetString(SR.PooledApplicationNotSupportedForComplusHostedScenarios,
                                                                                               applicationId.ToString("B").ToUpperInvariant())));
                }

                bool processRecycled = ((int)application.GetValue("RecycleLifetimeLimit")) > 0 ||
                                       ((int)application.GetValue("RecycleCallLimit")) > 0 ||
                                       ((int)application.GetValue("RecycleActivationLimit")) > 0 ||
                                       ((int)application.GetValue("RecycleMemoryLimit")) > 0;

                if (processRecycled)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(
                                                                                  SR.GetString(SR.RecycledApplicationNotSupportedForComplusHostedScenarios,
                                                                                               applicationId.ToString("B").ToUpperInvariant())));
                }


                ComCatalogCollection classes;
                classes = application.GetCollection("Components");

                // Load up Indigo configuration.
                //
                ServicesSection services     = ServicesSection.GetSection();
                bool            foundService = false;


                foreach (ServiceElement service in services.Services)
                {
                    Guid clsidToCompare = Guid.Empty;
                    Guid appIdToCompare = Guid.Empty;

                    string[] serviceParams = service.Name.Split(',');
                    if (serviceParams.Length != 2)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.OnlyClsidsAllowedForServiceType, service.Name)));
                    }

                    if (!DiagnosticUtility.Utility.TryCreateGuid(serviceParams[0], out appIdToCompare))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.OnlyClsidsAllowedForServiceType, service.Name)));
                    }

                    if (!DiagnosticUtility.Utility.TryCreateGuid(serviceParams[1], out clsidToCompare))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.OnlyClsidsAllowedForServiceType, service.Name)));
                    }

                    foundService = false;

                    // CODEWORK: Consider farming this out across multiple threadpool threads.
                    // When it was discovered that startup time could be a problem it was too late
                    // to to do that since it can cause failure conditions that need to be considered
                    // (such as the threadpool running out) so we decided not to touch that part.
                    // But since this can potentially take a very long time on big COM apps
                    // it should be parallelized at some point.
                    foreach (ComCatalogObject classObject in classes)
                    {
                        Guid clsid = Fx.CreateGuid((string)classObject.GetValue("CLSID"));

                        if (clsid == clsidToCompare && applicationId == appIdToCompare)
                        {
                            foundService = true;
                            ComPlusDllHostInitializerTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationDllHostInitializerAddingHost,
                                                                 SR.TraceCodeComIntegrationDllHostInitializerAddingHost, applicationId, clsid, service);
                            this.hosts.Add(
                                new DllHostedComPlusServiceHost(clsid,
                                                                service,
                                                                application,
                                                                classObject));
                        }
                    }
                    if (!foundService)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString
                                                                                                                    (SR.CannotFindClsidInApplication, clsidToCompare.ToString("B").ToUpperInvariant(), applicationId.ToString("B").ToUpperInvariant())));
                    }
                }
                if (foundService == false)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.DllHostInitializerFoundNoServices());
                }

                foreach (ComPlusServiceHost host in this.hosts)
                {
                    host.Open();
                }
            }
            catch (Exception e)
            {
                DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error,
                                                    (ushort)System.Runtime.Diagnostics.EventLogCategory.ComPlus,
                                                    (uint)System.Runtime.Diagnostics.EventLogEventId.ComPlusDllHostInitializerStartingError,
                                                    applicationId.ToString(),
                                                    e.ToString());
                throw;
            }
            finally
            {
                if (null != pingThread)
                {
                    pingThread.Abort(); // We are done; stop pinging.
                }
            }
            ComPlusDllHostInitializerTrace.Trace(TraceEventType.Information, TraceCode.ComIntegrationDllHostInitializerStarted,
                                                 SR.TraceCodeComIntegrationDllHostInitializerStarted, applicationId);
        }
Exemple #23
0
        /// <summary>
        /// Главная точка входа для приложения.
        /// </summary>
        static void Main()
        {
            XmlConfigurator.Configure();
            logger.Info("Starting service");

            String        baseURL   = "";
            Configuration appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            logger.Info("Getting Base URL");

            bool isService = true;

            try
            {
                baseURL = ConfigurationManager.AppSettings["baseURL"];
            }
            catch (Exception e)
            {
                logger.Fatal("Error while starting service", e);
                throw e;
            }
            try
            {
                isService = ConfigurationManager.AppSettings["runAsService"].ToLower().Equals("true");
            }
            catch (Exception e)
            {
                logger.Fatal("Error while starting service", e);
                throw e;
            }
            logger.Info(String.Format("Base URL is: {0}", baseURL));

            UriBuilder builder = new UriBuilder(baseURL);

            builder.Path = "win32lib";
            String baseHost = builder.ToString();

            ServiceModelSectionGroup serviceModel = ServiceModelSectionGroup.GetSectionGroup(appConfig);

            ServicesSection services = serviceModel.Services;

            List <ServiceHost> hosts = new List <ServiceHost>();

            logger.Info("Initializing hosts");
            try
            {
                foreach (ServiceElement svc in services.Services)
                {
                    logger.Info("Getting configuration information");
                    //svc.Name
                    String svcName = svc.Name;
                    logger.Info(String.Format("Service Name: {0}", svcName));

                    Type type = Type.GetType(svc.Name);

                    logger.Info(String.Format("Type: {0}", type));

                    String url  = baseHost + "/" + type.Name.ToLower();
                    Uri[]  URIs =
                    {
                        new Uri(url)
                    };

                    //System.Console.WriteLine(String.Format("Initializing host for URL: {0}", url));
                    logger.Info(String.Format("Initializing host for URL: {0}", url) + "");

                    //Type type = Type.GetType(svc.Name);
                    ServiceHost host = new ServiceHost(type, URIs);
                    hosts.Add(host);
                }
            }
            catch (Exception e)
            {
                logger.Fatal("Error while starting service", e);
                throw e;
            }
            logger.Info("Running Hosts");

            foreach (ServiceHost host in hosts)
            {
                host.Open();
            }
            logger.Info("Starting Windows Service");

            //while (Console.ReadKey(true).KeyChar != 'q') { ;}

            if (isService)
            {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[]
                {
                    new Win32Service()
                };
                ServiceBase.Run(ServicesToRun);
            }
            else
            {
                while (Console.ReadKey(true).KeyChar != 'q')
                {
                    ;
                }
            }
            logger.Info("Stopping Service");
            foreach (ServiceHost host in hosts)
            {
                host.Close();
            }
            logger.Info("Service exit");
        }
        public WebHostedComPlusServiceHost(string webhostParams, Uri[] baseAddresses)
        {
            Guid        guid;
            Guid        guid2;
            HostingMode webHostInProcess;

            foreach (Uri uri in baseAddresses)
            {
                base.InternalBaseAddresses.Add(uri);
            }
            string[] strArray = webhostParams.Split(new char[] { ',' });
            if (strArray.Length != 2)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(System.ServiceModel.SR.GetString("ServiceStringFormatError", new object[] { webhostParams })));
            }
            if (!DiagnosticUtility.Utility.TryCreateGuid(strArray[0], out guid))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(System.ServiceModel.SR.GetString("ServiceStringFormatError", new object[] { webhostParams })));
            }
            if (!DiagnosticUtility.Utility.TryCreateGuid(strArray[1], out guid2))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(System.ServiceModel.SR.GetString("ServiceStringFormatError", new object[] { webhostParams })));
            }
            string           str = guid.ToString("B").ToUpperInvariant();
            ComCatalogObject applicationObject = CatalogUtil.FindApplication(guid2);

            if (applicationObject == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(System.ServiceModel.SR.GetString("ApplicationNotFound", new object[] { guid2.ToString("B").ToUpperInvariant() })));
            }
            ComCatalogCollection collection  = applicationObject.GetCollection("Components");
            ComCatalogObject     classObject = null;

            ComCatalogCollection.Enumerator enumerator = collection.GetEnumerator();
            while (enumerator.MoveNext())
            {
                ComCatalogObject current = enumerator.Current;
                string           str2    = (string)current.GetValue("CLSID");
                if (str.Equals(str2, StringComparison.OrdinalIgnoreCase))
                {
                    classObject = current;
                    break;
                }
            }
            if (classObject == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(System.ServiceModel.SR.GetString("ClsidNotInApplication", new object[] { str, guid2.ToString("B").ToUpperInvariant() })));
            }
            ServicesSection section = ServicesSection.GetSection();
            ServiceElement  service = null;

            foreach (ServiceElement element2 in section.Services)
            {
                Guid     empty     = Guid.Empty;
                Guid     result    = Guid.Empty;
                string[] strArray2 = element2.Name.Split(new char[] { ',' });
                if ((((strArray2.Length == 2) && DiagnosticUtility.Utility.TryCreateGuid(strArray2[0], out result)) && (DiagnosticUtility.Utility.TryCreateGuid(strArray2[1], out empty) && (empty == guid))) && (result == guid2))
                {
                    service = element2;
                    break;
                }
            }
            if (service == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(System.ServiceModel.SR.GetString("ClsidNotInConfiguration", new object[] { str })));
            }
            if (((int)applicationObject.GetValue("Activation")) == 0)
            {
                webHostInProcess = HostingMode.WebHostInProcess;
            }
            else
            {
                webHostInProcess = HostingMode.WebHostOutOfProcess;
            }
            base.Initialize(guid, service, applicationObject, classObject, webHostInProcess);
        }
Exemple #25
0
        public void Startup(IProcessInitControl control)
        {
            this.applicationId = ContextUtil.ApplicationId;
            ComPlusDllHostInitializerTrace.Trace(TraceEventType.Information, 0x50008, "TraceCodeComIntegrationDllHostInitializerStarting", this.applicationId);
            Thread thread = null;

            try
            {
                thread = new Thread(new ParameterizedThreadStart(DllHostInitializeWorker.PingProc));
                thread.Start(control);
                ComCatalogObject applicationObject = CatalogUtil.FindApplication(this.applicationId);
                if (applicationObject == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(System.ServiceModel.SR.GetString("ApplicationNotFound", new object[] { this.applicationId.ToString("B").ToUpperInvariant() })));
                }
                if (((int)applicationObject.GetValue("ConcurrentApps")) > 1)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(System.ServiceModel.SR.GetString("PooledApplicationNotSupportedForComplusHostedScenarios", new object[] { this.applicationId.ToString("B").ToUpperInvariant() })));
                }
                if ((((((int)applicationObject.GetValue("RecycleLifetimeLimit")) > 0) || (((int)applicationObject.GetValue("RecycleCallLimit")) > 0)) || (((int)applicationObject.GetValue("RecycleActivationLimit")) > 0)) || (((int)applicationObject.GetValue("RecycleMemoryLimit")) > 0))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ListenerInitFailed(System.ServiceModel.SR.GetString("RecycledApplicationNotSupportedForComplusHostedScenarios", new object[] { this.applicationId.ToString("B").ToUpperInvariant() })));
                }
                ComCatalogCollection collection = applicationObject.GetCollection("Components");
                ServicesSection      section    = ServicesSection.GetSection();
                bool flag3 = false;
                foreach (ServiceElement element in section.Services)
                {
                    Guid     empty    = Guid.Empty;
                    Guid     result   = Guid.Empty;
                    string[] strArray = element.Name.Split(new char[] { ',' });
                    if (strArray.Length != 2)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("OnlyClsidsAllowedForServiceType", new object[] { element.Name })));
                    }
                    if (!DiagnosticUtility.Utility.TryCreateGuid(strArray[0], out result))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("OnlyClsidsAllowedForServiceType", new object[] { element.Name })));
                    }
                    if (!DiagnosticUtility.Utility.TryCreateGuid(strArray[1], out empty))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("OnlyClsidsAllowedForServiceType", new object[] { element.Name })));
                    }
                    flag3 = false;
                    ComCatalogCollection.Enumerator enumerator = collection.GetEnumerator();
                    while (enumerator.MoveNext())
                    {
                        ComCatalogObject current = enumerator.Current;
                        Guid             clsid   = Fx.CreateGuid((string)current.GetValue("CLSID"));
                        if ((clsid == empty) && (this.applicationId == result))
                        {
                            flag3 = true;
                            ComPlusDllHostInitializerTrace.Trace(TraceEventType.Verbose, 0x50009, "TraceCodeComIntegrationDllHostInitializerAddingHost", this.applicationId, clsid, element);
                            this.hosts.Add(new DllHostedComPlusServiceHost(clsid, element, applicationObject, current));
                        }
                    }
                    if (!flag3)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("CannotFindClsidInApplication", new object[] { empty.ToString("B").ToUpperInvariant(), this.applicationId.ToString("B").ToUpperInvariant() })));
                    }
                }
                if (!flag3)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.DllHostInitializerFoundNoServices());
                }
                foreach (ComPlusServiceHost host in this.hosts)
                {
                    host.Open();
                }
            }
            catch (Exception exception)
            {
                DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error, EventLogCategory.ComPlus, (EventLogEventId)(-1073610729), new string[] { this.applicationId.ToString(), exception.ToString() });
                throw;
            }
            finally
            {
                if (thread != null)
                {
                    thread.Abort();
                }
            }
            ComPlusDllHostInitializerTrace.Trace(TraceEventType.Information, 0x5000a, "TraceCodeComIntegrationDllHostInitializerStarted", this.applicationId);
        }
Exemple #26
0
        /// <summary>
        /// 初始化
        /// </summary>
        public void Startup()
        {
            lock (syncLock)
            {
                //RandomHelper.Initialize();
                ServicesSection serviesSection = ConfigurationManager.GetSection("system.serviceModel/services") as ServicesSection;

                if (serviesSection != null)
                {
                    for (int i = 0; i < serviesSection.Services.Count; i++)
                    {
                        switch (serviesSection.Services[i].Name)
                        {
                        case "Games.NBall.ServiceContract.Service.ArenaService":
                            new ArenaBootstrapper().Startup();
                            break;

                        case "Games.NBall.ServiceContract.Service.PlayerKillService":
                            new PlayerKillBootstrapper().Startup();
                            break;

                        case "Games.NBall.ServiceContract.Service.ManagerService":
                            new ManagerBootstrapper().Startup();
                            break;

                        case "Games.NBall.ServiceContract.Service.OnlineService":
                            new OnlineBootstrapper().Startup();
                            break;

                        case "Games.NBall.ServiceContract.Service.ItemService":
                            new ItemBootstrapper().Startup();
                            break;

                        case "Games.NBall.ServiceContract.Service.MailService":
                            new MailBootstrapper().Startup();
                            break;

                        case "Games.NBall.ServiceContract.Service.ManagerSkillService":
                            Games.NBall.Core.ManagerSkill.ManagerSkillRules.StartService();
                            break;

                        case "Games.NBall.ServiceContract.Service.TeammemberService":
                            new TeammemberBootstrapper().Startup();
                            break;

                        case "Games.NBall.ServiceContract.Service.TrainThreadService":
                            new TrainThreadBootstrapper().Startup();
                            break;

                        case "Games.NBall.ServiceContract.Service.LadderService":
                            new LadderBootstrapper().Startup();
                            break;

                        case "Games.NBall.ServiceContract.Service.DailycupService":
                            new DailycupBootstrapper().Startup();
                            break;

                        case "Games.NBall.ServiceContract.Service.SkillCardService":
                            Games.NBall.Core.SkillCard.SkillCardRules.StartService();
                            break;

                        case "Games.NBall.ServiceContract.Service.FriendService":
                            new FriendBootstrapper().Startup();
                            break;

                        case "Games.NBall.ServiceContract.Service.RankService":
                            new RankBootstrapper().Startup();
                            break;

                        case "Games.NBall.ServiceContract.Service.TaskService":
                            new TaskBootstrapper().Startup();
                            break;

                        case "Games.NBall.ServiceContract.Service.ActivityService":
                            new ActivityBootstrapper().Startup();
                            break;

                        case "Games.NBall.ServiceContract.Service.GambleService":
                            new GambleBootstrapper().Startup();
                            break;

                        case "Games.NBall.ServiceContract.Service.StatisticService":
                            new StatisticBootstrapper().Startup();
                            break;

                        case "Games.NBall.ServiceContract.Service.CrossDataService":
                            new CrossDataBootstrapper().Startup();
                            break;

                        default:
                            break;
                        }
                    }
                }
            }
        }
Exemple #27
0
        /// <summary>
        /// 服务列表
        /// </summary>
        /// <returns></returns>
        protected override IEnumerable <Type> GetHostServiceType()
        {
            ServicesSection serviesSection = ConfigurationManager.GetSection("system.serviceModel/services") as ServicesSection;

            if (serviesSection != null)
            {
                Type[] types = new Type[serviesSection.Services.Count];

                for (int i = 0; i < serviesSection.Services.Count; i++)
                {
                    switch (serviesSection.Services[i].Name)
                    {
                    case "Games.NBall.ServiceContract.Service.ArenaService":
                        types[i] = typeof(ArenaService);
                        break;

                    case "Games.NBall.ServiceContract.Service.PlayerKillService":
                        types[i] = typeof(PlayerKillService);
                        break;

                    case "Games.NBall.ServiceContract.Service.ManagerService":
                        types[i] = typeof(ManagerService);
                        break;

                    case "Games.NBall.ServiceContract.Service.OnlineService":
                        types[i] = typeof(OnlineService);
                        break;

                    case "Games.NBall.ServiceContract.Service.AdminService":
                        types[i] = typeof(AdminService);
                        break;

                    case "Games.NBall.ServiceContract.Service.MailService":
                        types[i] = typeof(MailService);
                        break;

                    case "Games.NBall.ServiceContract.Service.ItemService":
                        types[i] = typeof(ItemService);
                        break;

                    case "Games.NBall.ServiceContract.Service.ManagerSkillService":
                        types[i] = typeof(ManagerSkillService);
                        break;

                    case "Games.NBall.ServiceContract.Service.TeammemberService":
                        types[i] = typeof(TeammemberService);
                        break;

                    case "Games.NBall.ServiceContract.Service.ScoutingService":
                        types[i] = typeof(ScoutingService);
                        break;

                    case "Games.NBall.ServiceContract.Service.LeagueService":
                        types[i] = typeof(LeagueService);
                        break;

                    case "Games.NBall.ServiceContract.Service.MallService":
                        types[i] = typeof(MallService);
                        break;

                    case "Games.NBall.ServiceContract.Service.TrainThreadService":
                        types[i] = typeof(TrainThreadService);
                        break;

                    case "Games.NBall.ServiceContract.Service.LadderService":
                        types[i] = typeof(LadderService);
                        break;

                    case "Games.NBall.ServiceContract.Service.DailycupService":
                        types[i] = typeof(DailycupService);
                        break;

                    case "Games.NBall.ServiceContract.Service.MatchDataService":
                        types[i] = typeof(MatchDataService);
                        break;

                    case "Games.NBall.ServiceContract.Service.SkillCardService":
                        types[i] = typeof(SkillCardService);
                        break;

                    case "Games.NBall.ServiceContract.Service.FriendService":
                        types[i] = typeof(FriendService);
                        break;

                    case "Games.NBall.ServiceContract.Service.RankService":
                        types[i] = typeof(RankService);
                        break;

                    case "Games.NBall.ServiceContract.Service.TaskService":
                        types[i] = typeof(TaskService);
                        break;

                    case "Games.NBall.ServiceContract.Service.ActivityService":
                        types[i] = typeof(ActivityService);
                        break;

                    case "Games.NBall.ServiceContract.Service.GambleService":
                        types[i] = typeof(GambleService);
                        break;

                    case "Games.NBall.ServiceContract.Service.CrossDataService":
                        types[i] = typeof(CrossDataService);
                        break;

                    default:
                        types[i] = typeof(object);
                        break;
                    }
                }

                return(types);
            }
            else
            {
                return(base.GetHostServiceType());
            }
        }