public void TestServiceConfiguration() { string groupName = "group1"; string masterTaskId = "task0"; string driverId = "Driver Id"; int numTasks = 3; int fanOut = 2; var serializer = new AvroConfigurationSerializer(); var groupCommunicationDriver = GroupCommunicationTests.GetInstanceOfGroupCommDriver(driverId, masterTaskId, groupName, fanOut, numTasks); //driver side to prepar for service config var codecConfig = CodecConfiguration<int>.Conf .Set(CodecConfiguration<int>.Codec, GenericType<IntCodec>.Class) .Build(); var driverServiceConfig = groupCommunicationDriver.GetServiceConfiguration(); var serviceConfig = Configurations.Merge(driverServiceConfig, codecConfig); //wrap it before serializing var wrappedSeriveConfig = TangFactory.GetTang().NewConfigurationBuilder() .BindNamedParameter<ServicesConfigurationOptions.ServiceConfigString, string>( GenericType<ServicesConfigurationOptions.ServiceConfigString>.Class, new AvroConfigurationSerializer().ToString(serviceConfig)) .Build(); var serviceConfigString = serializer.ToString(wrappedSeriveConfig); //the configuration string is received at Evaluator side var serviceConfig2 = new ServiceConfiguration(serviceConfigString); Assert.AreEqual(serializer.ToString(serviceConfig), serializer.ToString(serviceConfig2.TangConfig)); }
public override ServiceHostBase CreateServiceHost (string service, Uri[] baseAddresses) { ServiceHost host = new ServiceHost(typeof(IssHosted.ServiceInterfaces.EchoService), baseAddresses); host.AddServiceEndpoint(typeof(IEchoService), new ServiceproviderBinding(true), ""); host.AddServiceEndpoint(typeof(IEchoService), new ServiceproviderBinding(false), ""); // Configure our certificate and issuer certificate validation settings on the service credentials host.Credentials.ServiceCertificate.SetCertificate(SigningCertificateNameGenevaService, StoreLocation.LocalMachine, StoreName.My); // Enable metadata generation via HTTP GET ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpsGetEnabled = true; smb.HttpGetEnabled = true; host.Description.Behaviors.Add(smb); host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpsBinding(), "mex"); host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex"); // Configure the service host to use the Geneva Framework ServiceConfiguration configuration = new ServiceConfiguration(); configuration.IssuerNameRegistry = new TrustedIssuerNameRegistry(); configuration.SecurityTokenHandlers.Configuration.AudienceRestriction.AllowedAudienceUris.Add(new Uri("http://localhost/Echo/service.svc/Echo")); configuration.SecurityTokenHandlers.Configuration.AudienceRestriction.AllowedAudienceUris.Add(new Uri("http://localhost:6020/Echo")); configuration.SecurityTokenHandlers.Configuration.AudienceRestriction.AllowedAudienceUris.Add(new Uri("https://172.30.161.162:8181/poc-provider/ProviderService")); configuration.SecurityTokenHandlers.Configuration.AudienceRestriction.AllowedAudienceUris.Add(new Uri("https://172.16.232.1:8181/poc-provider/ProviderService")); configuration.SecurityTokenHandlers.Configuration.AudienceRestriction.AllowedAudienceUris.Add(new Uri("http://csky-pc/test/Service1.svc")); FederatedServiceCredentials.ConfigureServiceHost(host, configuration); return host; }
protected override void OnStart(string[] args) { _shareManager.Start(); ShareConfiguration dataShare = new FileSystemShareConfiguration() { Name = "Data", Path = "X:\\" }; ShareConfiguration backupShare = new FileSystemShareConfiguration() { Name = "Time Capsule", Path = "X:\\Backups\\Time Capsule" }; ServerConfiguration afpServer = new AppleFilingProtocolServerConfiguration() { Name = "Skynet", TimeMachineShares = { "Time Capsule" } }; ServiceConfiguration service = new ServiceConfiguration() { Servers = { afpServer }, Shares = { dataShare, backupShare } }; _shareManager.Configuration = service; }
public static Functions.CRMConfig GetCRMConfig(ServiceConfiguration serviceConfig) { Functions.CRMConfig crmconfig = new Functions.CRMConfig { CRMURL = serviceConfig["CRMUrl"].ToString(), CRMOrganization = serviceConfig["CRMOrganization"].ToString() }; if (!serviceConfig.ServiceAuthentication.Impersonate && !string.IsNullOrEmpty(serviceConfig.ServiceAuthentication.UserName.Trim()) && !string.IsNullOrEmpty(serviceConfig.ServiceAuthentication.Password.Trim())) { // Static credentials if (serviceConfig.ServiceAuthentication.UserName.Contains("\\")) { char[] sp = { '\\' }; string[] user = serviceConfig.ServiceAuthentication.UserName.Split(sp); crmconfig.CRMDomain = user[0].Trim(); crmconfig.CRMUsername = user[1].Trim(); } else { crmconfig.CRMUsername = serviceConfig.ServiceAuthentication.UserName.Trim(); } crmconfig.CRMPassword = serviceConfig.ServiceAuthentication.Password; } return crmconfig; }
/// <summary> /// Genera un log de tipo "Warning" cuando se ha intentado ejecutar /// un servicio que está deshabilitado. /// </summary> /// <param name="pConfig">configuración del servicio.</param> /// <param name="pServiceError">pServiceError </param> internal static void LogNotAvailableExcecution(ServiceConfiguration pConfig, out ServiceError pServiceError) { pServiceError = new ServiceError(); StringBuilder s = new StringBuilder(); s.AppendLine("Se ha intentado ejecutar un servicio que está configurado como no disponible."); s.AppendLine("Service :"); s.AppendLine(pConfig.Handler); pServiceError.Type = FwkExceptionTypes.TechnicalException.ToString(); pServiceError.Message = s.ToString(); pServiceError.ErrorId = "7006"; pServiceError.Assembly = "Fwk.BusinessFacades"; pServiceError.Class = "Audit"; pServiceError.Namespace = "Fwk.BusinessFacades"; pServiceError.UserName = Environment.UserName; pServiceError.Machine = Environment.MachineName; try { /// TODO: ver prefijo del log Event ev = new Event(EventType.Error,Fwk.Bases.ConfigurationsHelper.HostApplicationName, pServiceError.GetXml(), pServiceError.Machine, pServiceError.UserName); Fwk.Logging.StaticLogger.Log(ev); } catch { } }
public ServerLogin(ServiceConfiguration config) : base(config) { accountDatabase = new ClientAccountDatabase(config); server.serverDelegate = this; }
public static void Configure(ServiceConfiguration config) { var tcpAddr = new Uri("net.tcp://localhost:880/EntityService"); //var se = new ServiceEndpoint(new ContractDescription("IEntityService"), new NetTcpBinding(), new EndpointAddress(tcpAddr)); //config.AddServiceEndpoint(se); config.Description.Behaviors.Add(new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true }); config.AddServiceEndpoint(typeof (IEntityService), new NetTcpBinding(), tcpAddr); }
public ServerDefault(ServiceConfiguration configuration) { this.configuration = configuration; msgHandler = new NetworkMessageHandler(); server = new NetworkServer(); server.serverDelegate = this; SetupMessageHandlers(); }
private void listBox1_Click(object sender, EventArgs e) { if (((System.Windows.Forms.ListBox)(sender)).Text != String.Empty) { _SelectedServiceConfiguration = (ServiceConfiguration)((System.Windows.Forms.ListBox)(sender)).SelectedItem; lblServiceName.Text = _SelectedServiceConfiguration.Name; } }
public static void Configure(ServiceConfiguration config) { config.AddServiceEndpoint(typeof(IMessageProcessor), new WSHttpBinding(), new Uri(StartupUri)); var serviceMetadataBehavior = new ServiceMetadataBehavior { HttpGetUrl = new Uri(StartupUri), HttpGetEnabled = true, MetadataExporter = {PolicyVersion = PolicyVersion.Policy15} }; config.Description.Behaviors.Add(serviceMetadataBehavior); }
public static void Configure(ServiceConfiguration config) { //ServiceEndpoint se = new ServiceEndpoint(new ContractDescription("IService1"), new BasicHttpBinding(), new EndpointAddress("http://localhost/testservice/service1.svc")); //se.Behaviors.Add(new MyEndpointBehavior()); //config.AddServiceEndpoint(se); config.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true }); config.Description.Behaviors.Add(new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true }); var etcd = new EtcdClient(new Uri("http://localhost:4001/v2/keys/")); etcd.Set("local/EtcdPrototype.IService1/url", config.BaseAddresses.First().ToString()); // etcd.Set("local/EtcdPrototype.IService1/binding",config.) }
/// <summary> /// Modo consulta /// </summary> /// <param name="pServiceConfiguration"><see cref="ServiceConfiguration"/></param> /// <returns></returns> internal static DialogResult ShowQuery(ServiceConfiguration pServiceConfiguration) { using (frmEdit wfrmEdit = new frmEdit()) { wfrmEdit.ctrlService1.ShowAction = Action.Query; wfrmEdit.ctrlService1.EntityParam = pServiceConfiguration; wfrmEdit.ctrlService1.Populate(); wfrmEdit.btnSearchFile.Enabled = false; wfrmEdit.ShowDialog(); wfrmEdit.Text = wfrmEdit.ctrlService1.Text; return wfrmEdit.DialogResult; } }
public static void AreEqualServiceConfiguration(ServiceConfiguration actual, string serviceName, RoleInfo[] roles = null) { Assert.AreEqual<string>(actual.serviceName, serviceName); if (roles != null) { Assert.AreEqual<int>(actual.Role.Length, roles.Length); int length = roles.Length; for (int i = 0; i < length; i++) { Assert.IsTrue(roles[i].Equals(actual.Role[i])); } } }
public override bool CheckAccess(OperationContext operationContext) { int index = operationContext.RequestContext.RequestMessage.Headers.FindHeader("Security", WSSecurity10Constants.Namespace); if (index < 0) { return false; } var securityHeader = operationContext.RequestContext.RequestMessage.Headers.GetReaderAtHeader(index); var configuration = new ServiceConfiguration(true); securityHeader.Read(); if (!configuration.SecurityTokenHandlers.CanReadToken(securityHeader)) return false; if (configuration.ServiceCertificate != null) { SecurityToken xtoken; using (var xprovider = new X509SecurityTokenProvider(configuration.ServiceCertificate)) { xtoken = xprovider.GetToken(new TimeSpan(10, 1, 1)); } var outOfBandTokens = new Collection<SecurityToken>(); outOfBandTokens.Add(xtoken); configuration.SecurityTokenHandlers[typeof(EncryptedSecurityToken)].Configuration.ServiceTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(new ReadOnlyCollection<SecurityToken>(outOfBandTokens), false); } SecurityToken token = configuration.SecurityTokenHandlers.ReadToken(securityHeader); if (configuration.CertificateValidationMode == X509CertificateValidationMode.None) { configuration.CertificateValidator = X509CertificateValidator.None; } var claimsCollection = configuration.SecurityTokenHandlers.ValidateToken(token); IClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsCollection); SetPrincipal(operationContext, claimsPrincipal); return true; }
private static void StartHost() { ServiceHost host = new ServiceHost(typeof(Service)); // add message security endpoint via code host.AddServiceEndpoint( typeof(IService), new ClientSamlHttpBinding(SecurityMode.Message), "Message"); var config = new ServiceConfiguration(); config.SecurityTokenHandlers.AddOrReplace(new ClientSaml11SecurityTokenHandler()); FederatedServiceCredentials.ConfigureServiceHost(host, config); host.Open(); host.Description.Endpoints.ToList().ForEach(ep => Console.WriteLine(ep.Address)); }
/// <summary> /// Call this method to set up the service as claims aware. /// </summary> /// <param name="config"></param> public static void Configure(ServiceConfiguration config) { var secureSettings = config.GetSecureSettingsForService(); var serviceRootUrl = config.GetServiceRootUrl(); if (secureSettings.IsNull()) return; TurnOfSslCertificateValidation(secureSettings); config.IdentityConfiguration = new IdentityConfiguration() { TrustedStoreLocation = new StoreLocation(), AudienceRestriction = { AudienceMode = AudienceUriMode.Always }, SaveBootstrapContext = true, IssuerTokenResolver = new IssuerTokenResolver(), CertificateValidationMode = secureSettings.CertificateValidationMode.ParseAsEnum(X509CertificateValidationMode.PeerTrust), }; config.IdentityConfiguration.AudienceRestriction.AllowedAudienceUris.Add(new Uri(string.Format(secureSettings.Audience, serviceRootUrl))); config.IdentityConfiguration.IssuerNameRegistry = CreateIssuerNameRegistry(secureSettings); config.UseIdentityConfiguration = true; ThumbprintResolver.RegisterServiceHost(config); }
/// <summary> /// Ejecuta un servicio de negocio dentro de un ámbito transaccional. /// </summary> /// <param name="pRequest">Request con datos de entrada.</param> /// <param name="serviceConfiguration">configuración del servicio.</param> /// <returns>XML con datos de salida del servicio.</returns> /// <date>2008-04-07T00:00:00</date> /// <author>moviedo</author> public static IServiceContract RunNonTransactionalProcess(IServiceContract pRequest, ServiceConfiguration serviceConfiguration) { ServiceError wServiceError = null; return RunService(pRequest, serviceConfiguration, out wServiceError); }
public void SaveConfiguration(ServiceConfiguration config) { var c = JsonConvert.SerializeObject(config); File.WriteAllText(Path.Combine(GetConfigFolder(), "service.txt"), c); }
private async Task AddGeneratedCodeAsync(string metadata, string outputDirectory, LanguageOption languageOption, ServiceConfiguration serviceConfiguration) { await MessageLogger.WriteMessageAsync(LogMessageCategory.Information, "Generating Client Proxy for OData V4..."); ServiceConfigurationV4 servConfiguration = serviceConfiguration as ServiceConfigurationV4; ODataT4CodeGenerator t4CodeGenerator = CodeGeneratorFactory.Create(); t4CodeGenerator.MetadataDocumentUri = metadata; t4CodeGenerator.UseDataServiceCollection = servConfiguration.UseDataServiceCollection; t4CodeGenerator.TargetLanguage = languageOption == LanguageOption.GenerateCSharpCode ? ODataT4CodeGenerator.LanguageOption.CSharp : ODataT4CodeGenerator.LanguageOption.VB; t4CodeGenerator.IgnoreUnexpectedElementsAndAttributes = servConfiguration.IgnoreUnexpectedElementsAndAttributes; t4CodeGenerator.EnableNamingAlias = servConfiguration.EnableNamingAlias; t4CodeGenerator.NamespacePrefix = servConfiguration.NamespacePrefix; t4CodeGenerator.MakeTypesInternal = servConfiguration.MakeTypesInternal; t4CodeGenerator.GenerateMultipleFiles = servConfiguration.GenerateMultipleFiles; t4CodeGenerator.ExcludedOperationImports = servConfiguration.ExcludedOperationImports; t4CodeGenerator.ExcludedBoundOperations = servConfiguration.ExcludedBoundOperations; t4CodeGenerator.ExcludedSchemaTypes = servConfiguration.ExcludedSchemaTypes; var headers = new List <string>(); if (servConfiguration.CustomHttpHeaders != null) { var headerElements = servConfiguration.CustomHttpHeaders.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); foreach (var headerElement in headerElements) { // Trim header for empty spaces var header = headerElement.Trim(); headers.Add(header); } } t4CodeGenerator.CustomHttpHeaders = headers; t4CodeGenerator.IncludeWebProxy = servConfiguration.IncludeWebProxy; t4CodeGenerator.WebProxyHost = servConfiguration.WebProxyHost; t4CodeGenerator.IncludeWebProxyNetworkCredentials = servConfiguration.IncludeWebProxyNetworkCredentials; t4CodeGenerator.WebProxyNetworkCredentialsUsername = servConfiguration.WebProxyNetworkCredentialsUsername; t4CodeGenerator.WebProxyNetworkCredentialsPassword = servConfiguration.WebProxyNetworkCredentialsPassword; t4CodeGenerator.WebProxyNetworkCredentialsDomain = servConfiguration.WebProxyNetworkCredentialsDomain; var tempFile = Path.GetTempFileName(); var referenceFolder = outputDirectory; // Csdl file name is this format [ServiceName]Csdl.xml var csdlFileName = string.Concat(servConfiguration.ServiceName, Common.Constants.CsdlFileNameSuffix); var metadataFile = Path.Combine(referenceFolder, csdlFileName); await FileHandler.AddFileAsync(tempFile, metadataFile, new ODataFileOptions { SuppressOverwritePrompt = true }); FileHandler.SetFileAsEmbeddedResource(csdlFileName); t4CodeGenerator.EmitContainerPropertyAttribute = FileHandler.EmitContainerPropertyAttribute(); t4CodeGenerator.MetadataFilePath = metadataFile; t4CodeGenerator.MetadataFileRelativePath = csdlFileName; using (StreamWriter writer = File.CreateText(tempFile)) { await writer.WriteAsync(t4CodeGenerator.TransformText()); await writer.FlushAsync(); if (t4CodeGenerator.Errors != null && t4CodeGenerator.Errors.Count > 0) { foreach (var err in t4CodeGenerator.Errors) { await MessageLogger.WriteMessageAsync(LogMessageCategory.Warning, err.ToString()).ConfigureAwait(false); } } } var outputFile = Path.Combine(referenceFolder, $"{this.GeneratedFileNamePrefix(servConfiguration.GeneratedFileNamePrefix)}{(languageOption == LanguageOption.GenerateCSharpCode ? ".cs" : ".vb")}"); await FileHandler.AddFileAsync(tempFile, outputFile, new ODataFileOptions { SuppressOverwritePrompt = true }); t4CodeGenerator.MultipleFilesManager?.GenerateFiles(servConfiguration.GenerateMultipleFiles, FileHandler, MessageLogger, referenceFolder, true, servConfiguration.OpenGeneratedFilesInIDE); await MessageLogger.WriteMessageAsync(LogMessageCategory.Information, "Client Proxy for OData V4 was generated."); }
public void AddServiceConfiguration(string providerName, ServiceConfiguration pServiceConfiguration) { SimpleFacade wSimpleFacade = CreateSimpleFacade(); wSimpleFacade.AddServiceConfiguration(providerName, pServiceConfiguration); }
private async Task AddT4FileAsync(string metadata, string outputDirectory, LanguageOption languageOption, ServiceConfiguration serviceConfiguration) { await MessageLogger.WriteMessageAsync(LogMessageCategory.Information, "Adding T4 files for OData V4..."); var t4IncludeTempFile = Path.GetTempFileName(); var t4Folder = Path.Combine(this.CurrentAssemblyPath, "Templates"); var referenceFolder = outputDirectory; var servConfiguration = serviceConfiguration as ServiceConfigurationV4; // generate .ttinclude using (StreamWriter writer = File.CreateText(t4IncludeTempFile)) { var ttIncludeText = File.ReadAllText(Path.Combine(t4Folder, "ODataT4CodeGenerator.ttinclude")); if (languageOption == LanguageOption.GenerateVBCode) { ttIncludeText = Regex.Replace(ttIncludeText, "(output extension=)\".cs\"", "$1\".vb\""); } await writer.WriteAsync(ttIncludeText); await writer.FlushAsync(); } await FileHandler.AddFileAsync(t4IncludeTempFile, Path.Combine(referenceFolder, this.GeneratedFileNamePrefix(servConfiguration.GeneratedFileNamePrefix) + ".ttinclude")); await FileHandler.AddFileAsync(Path.Combine(t4Folder, "ODataT4CodeGenFilesManager.ttinclude"), Path.Combine(referenceFolder, "ODataT4CodeGenFilesManager.ttinclude")); var csdlTempFile = Path.GetTempFileName(); // Csdl file name is this format [ServiceName]Csdl.xml var csdlFileName = string.Concat(servConfiguration.ServiceName, Common.Constants.CsdlFileNameSuffix); var metadataFile = Path.Combine(referenceFolder, csdlFileName); // When the T4 file is added to the target project, the proxy and metadata files // are not automatically generated. To avoid ending up with an empty metadata file with // warnings, we pre-populate it with the root element. The content will later be overwritten with the actual metadata when T4 template is run by the user. using (StreamWriter writer = File.CreateText(csdlTempFile)) { await writer.WriteLineAsync("<edmx:Edmx Version=\"4.0\" xmlns:edmx=\"http://docs.oasis-open.org/odata/ns/edmx\">"); await writer.WriteLineAsync("</edmx:Edmx>"); } await FileHandler.AddFileAsync(csdlTempFile, metadataFile, new ODataFileOptions { SuppressOverwritePrompt = true }); FileHandler.SetFileAsEmbeddedResource(csdlFileName); var t4TempFile = Path.GetTempFileName(); using (StreamWriter writer = File.CreateText(t4TempFile)) { var text = File.ReadAllText(Path.Combine(t4Folder, "ODataT4CodeGenerator.tt")); text = Regex.Replace(text, "ODataT4CodeGenerator(\\.ttinclude)", this.GeneratedFileNamePrefix(servConfiguration.GeneratedFileNamePrefix) + "$1"); text = Regex.Replace(text, "(public const string MetadataDocumentUri = )\"\";", "$1@\"" + servConfiguration.Endpoint + "\";"); text = Regex.Replace(text, "(public const bool UseDataServiceCollection = ).*;", "$1" + servConfiguration.UseDataServiceCollection.ToString(CultureInfo.InvariantCulture).ToLower(CultureInfo.InvariantCulture) + ";"); text = Regex.Replace(text, "(public const string NamespacePrefix = )\"\\$rootnamespace\\$\";", "$1\"" + servConfiguration.NamespacePrefix + "\";"); if (languageOption == LanguageOption.GenerateCSharpCode) { text = Regex.Replace(text, "(public const string TargetLanguage = )\"OutputLanguage\";", "$1\"CSharp\";"); } else if (languageOption == LanguageOption.GenerateVBCode) { text = Regex.Replace(text, "(public const string TargetLanguage = )\"OutputLanguage\";", "$1\"VB\";"); } text = Regex.Replace(text, "(public const bool EnableNamingAlias = )true;", "$1" + servConfiguration.EnableNamingAlias.ToString(CultureInfo.InvariantCulture).ToLower(CultureInfo.InvariantCulture) + ";"); text = Regex.Replace(text, "(public const bool IgnoreUnexpectedElementsAndAttributes = )true;", "$1" + servConfiguration.IgnoreUnexpectedElementsAndAttributes.ToString(CultureInfo.InvariantCulture).ToLower(CultureInfo.InvariantCulture) + ";"); text = Regex.Replace(text, "(public const bool MakeTypesInternal = )false;", "$1" + servConfiguration.MakeTypesInternal.ToString(CultureInfo.InvariantCulture).ToLower(CultureInfo.InvariantCulture) + ";"); text = Regex.Replace(text, "(public const bool GenerateMultipleFiles = )false;", "$1" + servConfiguration.GenerateMultipleFiles.ToString(CultureInfo.InvariantCulture).ToLower(CultureInfo.InvariantCulture) + ";"); var customHeaders = servConfiguration.CustomHttpHeaders ?? ""; text = Regex.Replace(text, "(public const string CustomHttpHeaders = )\"\";", "$1@\"" + customHeaders + "\";"); text = Regex.Replace(text, "(public const string MetadataFilePath = )\"\";", "$1@\"" + metadataFile + "\";"); text = Regex.Replace(text, "(public const string MetadataFileRelativePath = )\"\";", "$1@\"" + csdlFileName + "\";"); if (servConfiguration.ExcludedOperationImports?.Any() == true) { text = Regex.Replace(text, "(public const string ExcludedOperationImports = )\"\";", "$1\"" + string.Join(",", servConfiguration.ExcludedOperationImports) + "\";"); } if (servConfiguration.ExcludedBoundOperations?.Any() == true) { text = Regex.Replace(text, "(public const string ExcludedBoundOperations = )\"\";", "$1\"" + string.Join(",", servConfiguration.ExcludedBoundOperations) + "\";"); } if (servConfiguration.ExcludedSchemaTypes?.Any() == true) { text = Regex.Replace(text, "(public const string ExcludedSchemaTypes = )\"\";", "$1\"" + string.Join(",", servConfiguration.ExcludedSchemaTypes) + "\";"); } await writer.WriteAsync(text); await writer.FlushAsync(); } await FileHandler.AddFileAsync(t4TempFile, Path.Combine(referenceFolder, this.GeneratedFileNamePrefix(servConfiguration.GeneratedFileNamePrefix) + ".tt")); await MessageLogger.WriteMessageAsync(LogMessageCategory.Information, "T4 files for OData V4 were added."); }
/** <inheritDoc /> */ public Task DeployAsync(ServiceConfiguration configuration) { AsyncInstance.Deploy(configuration); return(AsyncInstance.GetTask()); }
/// <summary> /// Valida que el servicio está disponible para ser ejecutado. /// </summary> /// <param name="serviceConfiguration">configuración del servicio.</param> /// <param name="result"></param> /// <date>2008-04-07T00:00:00</date> /// <author>moviedo</author> public static void ValidateAvailability(ServiceConfiguration serviceConfiguration, out IServiceContract result) { result = null; // Validación de disponibilidad del servicio. if (!serviceConfiguration.Available) { result = TryGetResultInstance(serviceConfiguration); ServiceError wServiceError; #region < Log > Audit.LogNotAvailableExcecution(serviceConfiguration, out wServiceError); #endregion result.Error = wServiceError; } }
public static void UseLog4Net(this ServiceConfiguration config) { config.Use(new Log4NetLoggerFactory()); }
internal void Service ( [Description("Cache names")] string[] names, [Description("Cache root paths")] string[] paths, [DefaultValue(DefaultMaxConnections), Description(MaxConnectionsDescription)] uint maxConnections, [DefaultValue(DefaultGracefulShutdownSeconds), Description(GracefulShutdownSecondsDescription)] uint gracefulShutdownSeconds, [DefaultValue(ServiceConfiguration.GrpcDisabledPort), Description(GrpcPortDescription)] uint grpcPort, [Description("Name of the memory mapped file used to share GRPC port. 'CASaaS GRPC port' if not specified.")] string grpcPortFileName, [DefaultValue(null), Description("Writable directory for service operations (use CWD if null)")] string dataRootPath, [DefaultValue(null), Description("Duration of inactivity after which a session will be timed out.")] double?unusedSessionTimeoutSeconds, [DefaultValue(null), Description("Duration of inactivity after which a session with a heartbeat will be timed out.")] double?unusedSessionHeartbeatTimeoutSeconds, [DefaultValue(false), Description("Stop running service")] bool stop, [DefaultValue(Constants.OneMB), Description("Max size quota in MB")] int maxSizeQuotaMB, [DefaultValue(ServiceConfiguration.GrpcDisabledPort), Description(RemoteGrpcPortDescription)] uint backingGrpcPort, [DefaultValue(null), Description("Name of scenario for backing CAS service")] string backingScenario, [DefaultValue("None"), Description("Ring Id. Used only for telemetry.")] string ringId, [DefaultValue("None"), Description("Stamp Id. Used only for telemetry.")] string stampId, [DefaultValue(null), Description("nLog configuration path. If empty, it is disabled")] string nLogConfigurationPath, [DefaultValue(null), Description("Whether to use Azure Blob logging or not")] string nLogToBlobStorageSecretName, [DefaultValue(null), Description("If using Azure Blob logging, where to temporarily store logs")] string nLogToBlobStorageWorkspacePath ) { Initialize(); if (stop) { IpcUtilities.SetShutdown(_scenario); return; } if (names == null || paths == null) { throw new CacheException("At least one cache name/path is required."); } if (names.Length != paths.Length) { throw new CacheException("Mismatching lengths of names/paths arguments."); } var caches = new Dictionary <string, string>(); for (var i = 0; i < names.Length; i++) { caches.Add(names[i], paths[i]); } var serverDataRootPath = !string.IsNullOrWhiteSpace(dataRootPath) ? new AbsolutePath(dataRootPath) : new AbsolutePath(Environment.CurrentDirectory); var cancellationTokenSource = new CancellationTokenSource(); #if NET_FRAMEWORK var configuration = new ServiceConfiguration(caches, serverDataRootPath, maxConnections, gracefulShutdownSeconds, (int)grpcPort, grpcPortFileName); if (!configuration.IsValid) { throw new CacheException($"Invalid service configuration, error=[{configuration.Error}]"); } var localContentServerConfiguration = new LocalServerConfiguration(configuration); if (unusedSessionTimeoutSeconds != null) { localContentServerConfiguration.UnusedSessionTimeout = TimeSpan.FromSeconds(unusedSessionTimeoutSeconds.Value); } if (unusedSessionHeartbeatTimeoutSeconds != null) { localContentServerConfiguration.UnusedSessionHeartbeatTimeout = TimeSpan.FromSeconds(unusedSessionHeartbeatTimeoutSeconds.Value); } if (_scenario != null) { _logger.Debug($"scenario=[{_scenario}]"); } var exitSignal = new ManualResetEvent(false); Console.CancelKeyPress += (sender, args) => { exitSignal.Set(); args.Cancel = true; }; using (var exitEvent = IpcUtilities.GetShutdownWaitHandle(_scenario)) { var server = new LocalContentServer( _fileSystem, _logger, _scenario, path => new FileSystemContentStore( _fileSystem, SystemClock.Instance, path, new ConfigurationModel(inProcessConfiguration: ContentStoreConfiguration.CreateWithMaxSizeQuotaMB((uint)maxSizeQuotaMB))), localContentServerConfiguration); using (server) { var context = new Context(_logger); try { var result = server.StartupAsync(context).Result; if (!result.Succeeded) { throw new CacheException(result.ErrorMessage); } int completedIndex = WaitHandle.WaitAny(new WaitHandle[] { exitSignal, exitEvent }); var source = completedIndex == 0 ? "control-C" : "exit event"; _tracer.Always(context, $"Shutdown by {source}."); } finally { var result = server.ShutdownAsync(context).Result; if (!result.Succeeded) { _tracer.Warning(context, $"Failed to shutdown store: {result.ErrorMessage}"); } } } } #else Console.CancelKeyPress += (sender, args) => { cancellationTokenSource.Cancel(); args.Cancel = true; }; var localCasSettings = LocalCasSettings.Default(maxSizeQuotaMB, serverDataRootPath.Path, names[0], grpcPort, grpcPortFileName); localCasSettings.ServiceSettings.ScenarioName = _scenario; var distributedContentSettings = DistributedContentSettings.CreateDisabled(); if (backingGrpcPort != ServiceConfiguration.GrpcDisabledPort) { distributedContentSettings.BackingGrpcPort = (int)backingGrpcPort; distributedContentSettings.BackingScenario = backingScenario; } LoggingSettings loggingSettings = null; if (!string.IsNullOrEmpty(nLogConfigurationPath)) { loggingSettings = new LoggingSettings() { NLogConfigurationPath = nLogConfigurationPath, Configuration = new AzureBlobStorageLogPublicConfiguration() { SecretName = nLogToBlobStorageSecretName, WorkspaceFolderPath = nLogToBlobStorageWorkspacePath, } }; } var distributedCacheServiceConfiguration = new DistributedCacheServiceConfiguration(localCasSettings, distributedContentSettings, loggingSettings); // Ensure the computed keyspace is computed based on the hostInfo's StampId distributedCacheServiceConfiguration.UseStampBasedIsolation = false; var distributedCacheServiceArguments = new DistributedCacheServiceArguments( logger: _logger, copier: new DistributedCopier(), copyRequester: null, host: new EnvironmentVariableHost(), hostInfo: new HostInfo(null, null, new List <string>()), cancellation: cancellationTokenSource.Token, dataRootPath: serverDataRootPath.Path, configuration: distributedCacheServiceConfiguration, keyspace: null) { TelemetryFieldsProvider = new TelemetryFieldsProvider(ringId, stampId, serviceName: "Service"), }; DistributedCacheServiceFacade.RunAsync(distributedCacheServiceArguments).GetAwaiter().GetResult(); // Because the facade completes immediately and named wait handles don't exist in CORECLR, // completion here is gated on Control+C. In the future, this can be redone with another option, // such as a MemoryMappedFile or GRPC heartbeat. This is just intended to be functional. cancellationTokenSource.Token.WaitHandle.WaitOne(); #endif }
public Task <Repository> CreateService(string org, ServiceConfiguration serviceConfig) { throw new NotImplementedException(); }
public bool UpdateServiceInformationInApplication(string org, string app, ServiceConfiguration applicationInformation) { throw new NotImplementedException(); }
public EmailEngineAgent(ConnectorCredential credential, string engagementAccount, ServiceConfiguration configuration) { this.serviceUri = new Uri(credential.ConnectorUri); this.actorId = new ActorId(string.Format(AgentIdFormat, credential.ConnectorName, credential.ConnectorId, engagementAccount, Random.Next(1, configuration.ActorAccountMaxCount))); this.connector = ActorProxy.Create <IEmailConnector>(this.actorId, this.serviceUri); }
//Mtodo que audita static void DoAudit(ServiceConfiguration pServiceConfiguration, IServiceContract pRequest, IServiceContract wResponse) { if ((AuditMode)FacadeHelper.ServiceDispatcherConfig.AuditMode == AuditMode.Required) Audit.LogSuccessfulExecution(pRequest, wResponse); else { if (pServiceConfiguration.Audit == true) { Audit.LogSuccessfulExecution(pRequest, wResponse); } } //Si ocurre un error cualquiera se loguea el mismo if (wResponse.Error != null) Audit.LogNonSucessfulExecution(pRequest, wResponse); }
static TestConnectedServiceHandlerContext SetupContext(ServiceConfiguration serviceConfig) { return(SetupContext(serviceConfig, EnvDTE.CodeModelLanguageConstants.vsCMLanguageCSharp)); }
/// <summary> /// Obtiene un objeto Response :: IServiceContract /// </summary> /// <param name="pServiceConfiguration"><see cref="ServiceConfiguration"/></param> /// <returns>IServiceContract</returns> static IServiceContract GetResponse(ServiceConfiguration pServiceConfiguration) { IServiceContract wResponse; try { wResponse = (IServiceContract)ReflectionFunctions.CreateInstance(pServiceConfiguration.Response); } catch (Exception ex) { System.Text.StringBuilder wMessage = new StringBuilder(); wMessage.Append("El servicio " + pServiceConfiguration.Handler); wMessage.AppendLine(" no se puede ejecutar debido a que esta faltando el assembly "); wMessage.Append(pServiceConfiguration.Response); wMessage.Append(" en el despachador de servicio"); throw GetTechnicalException(wMessage.ToString(), "7003", ex); } return wResponse; }
public override void ExecuteCmdlet() { try { var allSACs = StorSimpleClient.GetAllStorageAccountCredentials(); var existingSac = allSACs.Where(x => x.Name.Equals(StorageAccountName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); if (existingSac == null) { throw new ArgumentException(string.Format(Resources.SACNotFoundWithName, StorageAccountName)); } string encryptedKey; string thumbprint; string endpoint = GetEndpointFromHostname(existingSac.Hostname); if (!ValidateAndEncryptStorageCred(StorageAccountName, StorageAccountKey, endpoint, out encryptedKey, out thumbprint)) { return; } var serviceConfig = new ServiceConfiguration() { AcrChangeList = new AcrChangeList(), CredentialChangeList = new SacChangeList() { Added = new List <StorageAccountCredential>(), Deleted = new List <string>(), Updated = new[] { new StorageAccountCredential() { InstanceId = existingSac.InstanceId, CloudType = existingSac.CloudType, Hostname = existingSac.Hostname, Login = existingSac.Login, Password = encryptedKey ?? existingSac.Password, UseSSL = UseSSL ?? existingSac.UseSSL, VolumeCount = existingSac.VolumeCount, Name = existingSac.Name, IsDefault = existingSac.IsDefault, PasswordEncryptionCertThumbprint = thumbprint, Location = existingSac.Location }, } } }; if (WaitForComplete.IsPresent) { WriteVerbose("About to run a task to update your Storage Access credential!"); var taskStatus = StorSimpleClient.ConfigureService(serviceConfig); HandleSyncTaskResponse(taskStatus, "update"); if (taskStatus.AsyncTaskAggregatedResult == AsyncTaskAggregatedResult.Succeeded) { var updatedSac = StorSimpleClient.GetAllStorageAccountCredentials() .Where(x => x.Name.Equals(StorageAccountName, StringComparison.InvariantCultureIgnoreCase)); WriteObject(updatedSac); } } else { WriteVerbose("About to create a task to update your Storage Access credential!"); var taskResponse = StorSimpleClient.ConfigureServiceAsync(serviceConfig); HandleAsyncTaskResponse(taskResponse, "update"); } } catch (Exception exception) { this.HandleException(exception); } }
/// <summary> /// Crea un ámbito de transacción en base a la configuración del servicio de negocio. /// </summary> /// <param name="serviceConfiguration">configuración del servicio de negocio.</param> /// <returns>ámbito de transacción. <see cref="TransactionScopeHandler"/> </returns> /// <date>2008-04-07T00:00:00</date> /// <author>moviedo</author> private static TransactionScopeHandler CreateTransactionScopeHandler(ServiceConfiguration serviceConfiguration) { //Creación del ámbito de la transacción. TransactionScopeHandler wResult = new TransactionScopeHandler(serviceConfiguration.TransactionalBehaviour, serviceConfiguration.IsolationLevel, new TimeSpan(0, 0, 0)); return wResult; }
public async Task MultipleCaches() { const string cacheName1 = "test1"; const string cacheName2 = "test2"; using (var testDirectory0 = new DisposableDirectory(FileSystem)) using (var testDirectory1 = new DisposableDirectory(FileSystem)) using (var testDirectory2 = new DisposableDirectory(FileSystem)) { var config = CreateStoreConfiguration(); var rootPath1 = testDirectory1.Path; await config.Write(FileSystem, rootPath1); var rootPath2 = testDirectory2.Path; await config.Write(FileSystem, rootPath2); var grpcPort = PortExtensions.GetNextAvailablePort(); var grpcPortFileName = Guid.NewGuid().ToString(); var serviceConfiguration = new ServiceConfiguration( new Dictionary <string, AbsolutePath> { { cacheName1, rootPath1 }, { cacheName2, rootPath2 } }, testDirectory0.Path, ServiceConfiguration.DefaultMaxConnections, ServiceConfiguration.DefaultGracefulShutdownSeconds, grpcPort, grpcPortFileName); using (var server = CreateServer(serviceConfiguration)) { var factory = new MemoryMappedFileGrpcPortSharingFactory(Logger, grpcPortFileName); var reader = factory.GetPortReader(); var port = reader.ReadPort(); var rpcConfig = new ServiceClientRpcConfiguration(port); using (var store1 = new ServiceClientContentStore( Logger, FileSystem, new ServiceClientContentStoreConfiguration(cacheName1, rpcConfig, Scenario))) using (var store2 = new ServiceClientContentStore( Logger, FileSystem, new ServiceClientContentStoreConfiguration(cacheName2, rpcConfig, Scenario))) { try { var rs = await server.StartupAsync(_context); rs.ShouldBeSuccess(); var storeBoolResult1 = await store1.StartupAsync(_context); storeBoolResult1.ShouldBeSuccess(); var storeBoolResult2 = await store2.StartupAsync(_context); storeBoolResult2.ShouldBeSuccess(); IContentSession session1 = null; IContentSession session2 = null; try { var createSessionResult1 = store1.CreateSession(_context, "session1", ImplicitPin.None); createSessionResult1.ShouldBeSuccess(); var createSessionResult2 = store2.CreateSession(_context, "session2", ImplicitPin.None); createSessionResult2.ShouldBeSuccess(); using (createSessionResult1.Session) using (createSessionResult2.Session) { var r1 = await createSessionResult1.Session.StartupAsync(_context); r1.ShouldBeSuccess(); session1 = createSessionResult1.Session; var r2 = await createSessionResult2.Session.StartupAsync(_context); r2.ShouldBeSuccess(); session2 = createSessionResult2.Session; var r3 = await session1.PutRandomAsync( _context, ContentHashType, false, RandomContentByteCount, Token); var pinResult = await session1.PinAsync(_context, r3.ContentHash, Token); pinResult.ShouldBeSuccess(); r3 = await session2.PutRandomAsync( _context, ContentHashType, false, RandomContentByteCount, Token); pinResult = await session2.PinAsync(_context, r3.ContentHash, Token); pinResult.ShouldBeSuccess(); } } finally { if (session2 != null) { await session2.ShutdownAsync(_context).ShouldBeSuccess(); } if (session1 != null) { await session1.ShutdownAsync(_context).ShouldBeSuccess(); } } } finally { BoolResult r1 = null; BoolResult r2 = null; if (store1.StartupCompleted) { r1 = await store1.ShutdownAsync(_context); } if (store2.StartupCompleted) { r2 = await store2.ShutdownAsync(_context); } var r3 = await server.ShutdownAsync(_context); r1?.ShouldBeSuccess(); r2?.ShouldBeSuccess(); r3?.ShouldBeSuccess(); } } } } }
public AssetService(ServiceConfiguration config) { Configuration = config as AssetServiceConfiguration; LoadBuildManifestAsync(); }
protected abstract IStartupShutdown CreateServer(ServiceConfiguration serviceConfiguration);
public override async Task AddGeneratedClientCodeAsync(string metadata, string outputDirectory, LanguageOption languageOption, ServiceConfiguration serviceConfiguration) { if ((serviceConfiguration as ServiceConfigurationV4).IncludeT4File) { await AddT4FileAsync(metadata, outputDirectory, languageOption, serviceConfiguration); } else { await AddGeneratedCodeAsync(metadata, outputDirectory, languageOption, serviceConfiguration); } }
public Config(string filePath) : base(filePath) { ServiceConfiguration = new ServiceConfiguration(MixUntilAnonymitySet, PrivacyLevelSome, PrivacyLevelFine, PrivacyLevelStrong, GetBitcoinP2pEndPoint(), DustThreshold); }
/// <summary> /// Mapeta Fwk.Bases.ServiceConfiguration a Fwk.Bases.Connector.SingleService.ServiceConfiguration /// </summary> /// <param name="pServiceConfiguration"></param> /// <returns></returns> private static Fwk.Bases.Connector.Singleservice.ServiceConfiguration GetServiceConfigurationProxy(ServiceConfiguration pServiceConfiguration) { Fwk.Bases.Connector.Singleservice.ServiceConfiguration wServiceConfigurationProxy = null; wServiceConfigurationProxy = new Fwk.Bases.Connector.Singleservice.ServiceConfiguration(); wServiceConfigurationProxy.Audit = pServiceConfiguration.Audit; wServiceConfigurationProxy.name = pServiceConfiguration.Name; wServiceConfigurationProxy.Handler = pServiceConfiguration.Handler; wServiceConfigurationProxy.Request = pServiceConfiguration.Request; wServiceConfigurationProxy.Response = pServiceConfiguration.Response; wServiceConfigurationProxy.CreatedDateTime = pServiceConfiguration.CreatedDateTime; wServiceConfigurationProxy.ApplicationId = pServiceConfiguration.ApplicationId; wServiceConfigurationProxy.Available = pServiceConfiguration.Available; wServiceConfigurationProxy.Description = pServiceConfiguration.Description; wServiceConfigurationProxy.Audit = pServiceConfiguration.Audit; wServiceConfigurationProxy.CreatedUserName = pServiceConfiguration.CreatedUserName; String name = Enum.GetName(typeof(Fwk.Transaction.IsolationLevel), pServiceConfiguration.IsolationLevel); wServiceConfigurationProxy.IsolationLevel = (Fwk.Bases.Connector.Singleservice.IsolationLevel) Enum.Parse(typeof(Fwk.Bases.Connector.Singleservice.IsolationLevel), pServiceConfiguration.IsolationLevel.ToString()); wServiceConfigurationProxy.TransactionalBehaviour = (Fwk.Bases.Connector.Singleservice.TransactionalBehaviour) Enum.Parse(typeof(Fwk.Bases.Connector.Singleservice.TransactionalBehaviour), pServiceConfiguration.TransactionalBehaviour.ToString()); return(wServiceConfigurationProxy); }
public P2pBlockProvider(NodesGroup nodes, CoreNode coreNode, WasabiSynchronizer syncer, ServiceConfiguration serviceConfiguration, Network network) { Nodes = nodes; CoreNode = coreNode; Synchronizer = syncer; ServiceConfiguration = serviceConfiguration; Network = network; }
public override void ExecuteCmdlet() { try { string endpoint = string.IsNullOrEmpty(Endpoint) ? StorSimpleConstants.DefaultStorageAccountEndpoint : Endpoint; //validate storage account credentials bool storageAccountPresent; string encryptedKey; string thumbprint; string location = GetStorageAccountLocation(StorageAccountName, out storageAccountPresent); if (!storageAccountPresent || !ValidateAndEncryptStorageCred(StorageAccountName, StorageAccountKey, endpoint, out encryptedKey, out thumbprint)) { return; } var serviceConfig = new ServiceConfiguration() { AcrChangeList = new AcrChangeList(), CredentialChangeList = new SacChangeList() { Added = new[] { new StorageAccountCredential() { CloudType = CloudType.Azure, Hostname = GetHostnameFromEndpoint(endpoint), Login = StorageAccountName, Password = encryptedKey, PasswordEncryptionCertThumbprint = thumbprint, UseSSL = UseSSL, Name = StorageAccountName, Location = location }, }, Deleted = new List <string>(), Updated = new List <StorageAccountCredential>() } }; if (WaitForComplete.IsPresent) { var taskStatus = StorSimpleClient.ConfigureService(serviceConfig); HandleSyncTaskResponse(taskStatus, "create"); if (taskStatus.AsyncTaskAggregatedResult == AsyncTaskAggregatedResult.Succeeded) { var createdSac = StorSimpleClient.GetAllStorageAccountCredentials() .Where(x => x.Name.Equals(StorageAccountName, StringComparison.InvariantCultureIgnoreCase)); WriteObject(createdSac); } } else { var taskResponse = StorSimpleClient.ConfigureServiceAsync(serviceConfig); HandleAsyncTaskResponse(taskResponse, "create"); } } catch (Exception exception) { this.HandleException(exception); } }
public static void Configure(ServiceConfiguration serviceConfiguration) { serviceConfiguration.ApplyCustomAuthentication(typeof(IMyService), Config.ServiceEndpoint); }
/// <summary> /// Ejecuta un servicio de negocio dentro de un ámbito transaccional. /// </summary> /// <param name="pData">XML con datos de entrada.</param> /// <param name="serviceConfiguration">configuración del servicio.</param> /// <returns>XML con datos de salida del servicio.</returns> /// <date>2008-04-07T00:00:00</date> /// <author>moviedo</author> public static string RunNonTransactionalProcess(string pData, ServiceConfiguration serviceConfiguration) { ServiceError wServiceError = null; return RunService(pData, serviceConfiguration, out wServiceError); }
public ClientAccountDatabase(ServiceConfiguration config) { Debug.Log("ClientAccountDatabase: dir=" + config.accountDatabaseDir + ", pass=" + config.accountDatabasePassword); accounts = new Database <ClientAccount>(config.accountDatabaseDir, config.accountDatabasePassword); }
/// <summary> /// Ejecuta el servicio de negocio. /// </summary> /// <param name="pRequest">Request de entrada que se pasa al servicio</param> /// <param name="pServiceConfiguration">configuración del servicio.</param> /// <param name="pserviError">serviError</param> /// <returns>XML que representa el resultado de la ejecución del servicio.</returns> /// <date>2007-08-07T00:00:00</date> /// <author>moviedo</author> static IServiceContract RunService(IServiceContract pRequest, ServiceConfiguration pServiceConfiguration, out ServiceError pserviError) { IServiceContract wResponse = null; try { pRequest.InitializeServerContextInformation(); // obtención del Response. Type wServiceType = ReflectionFunctions.CreateType(pServiceConfiguration.Handler); object wServiceInstance = Activator.CreateInstance(wServiceType); wResponse = (wServiceType.GetMethod("Execute").Invoke(wServiceInstance, new object[] { pRequest }) as IServiceContract); wResponse.InitializeServerContextInformation(); } #region [manage Exception] catch (System.IO.FileNotFoundException ex) { wResponse = GetResponse(pServiceConfiguration);// (IServiceContract)ReflectionFunctions.CreateInstance(pServiceConfiguration.Response); wResponse.Error = new ServiceError(); System.Text.StringBuilder wMessage = new StringBuilder(); wResponse.Error.ErrorId = "7003"; #region Message wMessage.Append("El despachador de servicio no pudo encontrar alguna de los siguientes assemblies \r\n"); wMessage.Append("o alguna de sus dependencias: \r\n"); wMessage.Append("Servicio: "); wMessage.Append(pServiceConfiguration.Handler); wMessage.Append(Environment.NewLine); wMessage.Append("Request: "); wMessage.Append(pServiceConfiguration.Request); wMessage.Append(Environment.NewLine); wMessage.Append("Response: "); wMessage.Append(pServiceConfiguration.Response); wMessage.Append(Environment.NewLine); wMessage.Append("Mensaje original :"); wMessage.Append(Environment.NewLine); wMessage.Append(ex.Message); #endregion wResponse.Error.Message = wMessage.ToString(); FillServiceError(wResponse.Error, ex); } catch (System.Reflection.TargetInvocationException ex) { wResponse = GetResponse(pServiceConfiguration); wResponse.Error = GetServiceError(ex.InnerException); } catch (TypeLoadException tl) { wResponse = GetResponse(pServiceConfiguration); System.Text.StringBuilder wMessage = new StringBuilder(); wResponse.Error = new ServiceError(); wResponse.Error.ErrorId = "7002"; wMessage.Append("No se encuentra el o los assemblies para cargar el servicio " + pServiceConfiguration.Name); wMessage.AppendLine(); wMessage.AppendLine(tl.Message); wResponse.Error.Message = wMessage.ToString(); FillServiceError(wResponse.Error, tl); } catch (Exception ex) { wResponse = GetResponse(pServiceConfiguration);// (IServiceContract)ReflectionFunctions.CreateInstance(pServiceConfiguration.Response); wResponse.Error = GetServiceError(ex); } #endregion pserviError = wResponse.Error; #region < Log > //Audito ensegundo plano Action actionAudit = () => { DoAudit(pServiceConfiguration, pRequest, wResponse); }; Task.Factory.StartNew(actionAudit); #endregion return wResponse; }
public static void Main(string[] args) { try { int workerThreads; int completionPortThreads; System.Threading.ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads); if (workerThreads < 16) { workerThreads = 16; System.Threading.ThreadPool.SetMinThreads(workerThreads, completionPortThreads); } IConfigurationBuilder builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .AddCommandLine(args); IConfigurationRoot configuration = builder.Build(); ServiceConfiguration.LoadConfig(configuration.GetSection("ServiceConfiguration")); int port = 15683; bool secureOnly = true; IConfigurationSection sectionBootstrap = configuration.GetSection("LWM2MBootstrap"); if (sectionBootstrap != null) { IConfigurationSection sectionPort = sectionBootstrap.GetSection("Port"); if (sectionPort != null) { if (!int.TryParse(sectionPort.Value, out port)) { port = 15683; } } IConfigurationSection sectionSecure = sectionBootstrap.GetSection("SecureOnly"); if (sectionSecure != null) { if (!bool.TryParse(sectionSecure.Value, out secureOnly)) { secureOnly = true; } } } Version version = Assembly.GetExecutingAssembly().GetName().Version; Console.Write("LWM2M Bootstrap ("); Console.Write(version.ToString()); Console.WriteLine(")"); if (ServiceConfiguration.ExternalUri == null) { ServiceConfiguration.ExternalUri = new Uri(string.Concat("coaps://", ServiceConfiguration.Hostname, ":", (port + 1).ToString())); } ServiceConfiguration.DisplayConfig(); BusinessLogicFactory.Initialise(); BootstrapServer bootstrapServer = new BootstrapServer(); //bootstrapServer.PSKIdentities.LoadFromFile("PSKIdentities.xml"); bootstrapServer.Port = port; bootstrapServer.SecureOnly = secureOnly; bootstrapServer.Start(); ServiceEventMessage message = new ServiceEventMessage(); Imagination.Model.BootstrapServer bootstrap = new Imagination.Model.BootstrapServer(); bootstrap.Url = ServiceConfiguration.ExternalUri.ToString(); //PSKIdentity pskIdentity = new PSKIdentity(); //pskIdentity.Identity = "Test1"; //pskIdentity.Secret = "TestSecret"; //bootstrap.AddServerIdentity(pskIdentity); message.AddParameter("BootstrapServer", bootstrap); BusinessLogicFactory.ServiceMessages.Publish("Bootstrap.Start", message, TMessagePublishMode.Confirms); _ShutdownEvent = new ManualResetEvent(false); Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e) { _ShutdownEvent.Set(); e.Cancel = true; }; Console.Write("Listening on port "); Console.WriteLine(port.ToString()); Console.WriteLine("Press Ctrl+C to stop the server."); _ShutdownEvent.WaitOne(); Console.WriteLine("Exiting."); bootstrapServer.Stop(); BusinessLogicFactory.ServiceMessages.Stop(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
/// <summary> /// Ejecuta el servicio de negocio. /// </summary> /// <param name="pData">XML con datos de entrada.</param> /// <param name="pServiceConfiguration">configuración del servicio.</param> /// <param name="pserviError"></param> /// <returns>XML que representa el resultado de la ejecución del servicio.</returns> /// <date>2007-08-07T00:00:00</date> /// <author>moviedo</author> static string RunService(string pData, ServiceConfiguration pServiceConfiguration, out ServiceError pserviError) { IServiceContract wRequest = null; IServiceContract wResponse = null; // Obtencion del Request. wRequest = (IServiceContract)ReflectionFunctions.CreateInstance(pServiceConfiguration.Request); if (wRequest == null) { System.Text.StringBuilder wMessage = new StringBuilder(); wMessage.Append("Verifique que este assemblie se encuentra en el host del despachador de servicios"); wMessage.Append("El servicio " + pServiceConfiguration.Handler); wMessage.AppendLine(" no se puede ejecutar debido a que esta faltando el assembly "); wMessage.Append(pServiceConfiguration.Request); wMessage.Append(" en el despachador de servicio"); throw GetTechnicalException(wMessage.ToString(), "7002", null); } wRequest.SetXml(pData); wRequest.InitializeServerContextInformation(); wResponse = RunService(wRequest, pServiceConfiguration, out pserviError); return wResponse.GetXml(); }
public async Task TestServicesAsync(string networkString) { await RuntimeParams.LoadAsync(); var network = Network.GetNetwork(networkString); var blocksToDownload = new List <uint256>(); if (network == Network.Main) { blocksToDownload.Add(new uint256("00000000000000000037c2de35bd85f3e57f14ddd741ce6cee5b28e51473d5d0")); blocksToDownload.Add(new uint256("000000000000000000115315a43cb0cdfc4ea54a0e92bed127f4e395e718d8f9")); blocksToDownload.Add(new uint256("00000000000000000011b5b042ad0522b69aae36f7de796f563c895714bbd629")); } else if (network == Network.TestNet) { blocksToDownload.Add(new uint256("0000000097a664c4084b49faa6fd4417055cb8e5aac480abc31ddc57a8208524")); blocksToDownload.Add(new uint256("000000009ed5b82259ecd2aa4cd1f119db8da7a70e7ea78d9c9f603e01f93bcc")); blocksToDownload.Add(new uint256("00000000e6da8c2da304e9f5ad99c079df2c3803b49efded3061ecaf206ddc66")); } else { throw new NotSupportedNetworkException(network); } var dataDir = Path.Combine(Global.Instance.DataDir, EnvironmentHelpers.GetCallerFileName()); BitcoinStore bitcoinStore = new BitcoinStore(Path.Combine(dataDir, EnvironmentHelpers.GetMethodName()), network, new IndexStore(network, new SmartHeaderChain()), new AllTransactionStore(), new MempoolService()); await bitcoinStore.InitializeAsync(); var addressManagerFolderPath = Path.Combine(dataDir, "AddressManager"); var addressManagerFilePath = Path.Combine(addressManagerFolderPath, $"AddressManager{network}.dat"); var blocksFolderPath = Path.Combine(dataDir, "Blocks", network.ToString()); var connectionParameters = new NodeConnectionParameters(); AddressManager addressManager = null; try { addressManager = await NBitcoinHelpers.LoadAddressManagerFromPeerFileAsync(addressManagerFilePath); Logger.LogInfo($"Loaded {nameof(AddressManager)} from `{addressManagerFilePath}`."); } catch (DirectoryNotFoundException) { addressManager = new AddressManager(); } catch (FileNotFoundException) { addressManager = new AddressManager(); } catch (OverflowException) { File.Delete(addressManagerFilePath); addressManager = new AddressManager(); } catch (FormatException) { File.Delete(addressManagerFilePath); addressManager = new AddressManager(); } connectionParameters.TemplateBehaviors.Add(new AddressManagerBehavior(addressManager)); connectionParameters.TemplateBehaviors.Add(bitcoinStore.CreateUntrustedP2pBehavior()); using var nodes = new NodesGroup(network, connectionParameters, requirements: Constants.NodeRequirements); KeyManager keyManager = KeyManager.CreateNew(out _, "password"); WasabiSynchronizer syncer = new WasabiSynchronizer(network, bitcoinStore, new Uri("http://localhost:12345"), Global.Instance.TorSocks5Endpoint); ServiceConfiguration serviceConfig = new ServiceConfiguration(MixUntilAnonymitySet.PrivacyLevelStrong.ToString(), 2, 21, 50, new IPEndPoint(IPAddress.Loopback, network.DefaultPort), Money.Coins(Constants.DefaultDustThreshold)); CachedBlockProvider blockProvider = new CachedBlockProvider( new P2pBlockProvider(nodes, null, syncer, serviceConfig, network), new FileSystemBlockRepository(blocksFolderPath, network)); using Wallet wallet = Wallet.CreateAndRegisterServices( network, bitcoinStore, keyManager, syncer, nodes, dataDir, new ServiceConfiguration(MixUntilAnonymitySet.PrivacyLevelStrong.ToString(), 2, 21, 50, new IPEndPoint(IPAddress.Loopback, network.DefaultPort), Money.Coins(Constants.DefaultDustThreshold)), syncer, blockProvider); Assert.True(Directory.Exists(blocksFolderPath)); try { var mempoolTransactionAwaiter = new EventsAwaiter <SmartTransaction>( h => bitcoinStore.MempoolService.TransactionReceived += h, h => bitcoinStore.MempoolService.TransactionReceived -= h, 3); var nodeConnectionAwaiter = new EventsAwaiter <NodeEventArgs>( h => nodes.ConnectedNodes.Added += h, h => nodes.ConnectedNodes.Added -= h, 3); nodes.Connect(); var downloadTasks = new List <Task <Block> >(); using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(4)); foreach (var hash in blocksToDownload) { downloadTasks.Add(blockProvider.GetBlockAsync(hash, cts.Token)); } await nodeConnectionAwaiter.WaitAsync(TimeSpan.FromMinutes(3)); var i = 0; var hashArray = blocksToDownload.ToArray(); foreach (var block in await Task.WhenAll(downloadTasks)) { Assert.True(File.Exists(Path.Combine(blocksFolderPath, hashArray[i].ToString()))); i++; } await mempoolTransactionAwaiter.WaitAsync(TimeSpan.FromMinutes(1)); } finally { // So next test will download the block. foreach (var hash in blocksToDownload) { await blockProvider.BlockRepository.RemoveAsync(hash, CancellationToken.None); } if (wallet is { })
/// <summary> /// Almacena la configuración de un nuevo servicio de negocio. /// </summary> /// <param name="providerName">Nombre del proveedor de la metadata de servicio</param> /// <param name="serviceConfiguration"></param> public static void AddServiceConfiguration(string providerName, ServiceConfiguration serviceConfiguration) { ServiceMetadata.AddServiceConfiguration(providerName, serviceConfiguration); }
/// <summary> /// Update the service configuration. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='config'> /// The personalizer service configuration. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <ServiceConfiguration> UpdateAsync(this IServiceConfigurationOperations operations, ServiceConfiguration config, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(config, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
static IServiceContract TryGetResultInstance(ServiceConfiguration serviceConfiguration) { return (IServiceContract)Fwk.HelperFunctions.ReflectionFunctions.CreateInstance(serviceConfiguration.Response); }
/// <summary> /// Update the service configuration. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='config'> /// The personalizer service configuration. /// </param> public static ServiceConfiguration Update(this IServiceConfigurationOperations operations, ServiceConfiguration config) { return(operations.UpdateAsync(config).GetAwaiter().GetResult()); }
/// <summary> /// Ruta prefija donde se deberan obtener los assemblies. /// Por defecto se retorna \bin del servicio /// </summary> /// <param name="serviceConfiguration"></param> /// <returns>Ruta prefijada del servicio</returns> private static string GePatch(ServiceConfiguration serviceConfiguration) { String wAssembliesPath = String.Empty; if (serviceConfiguration.ApplicationId != null) { if (serviceConfiguration.ApplicationId.Length == 0) { return String.Empty; } } else { return String.Empty; } wAssembliesPath = Fwk.Configuration.ConfigurationManager.GetProperty("AssembliesPath", serviceConfiguration. ApplicationId); //Si no existe tal carpeta por defecto se busca en el \bin de la aplicacion if (!Directory.Exists(wAssembliesPath)) wAssembliesPath = String.Empty; return wAssembliesPath; }
/// <summary> /// Update the service configuration. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='config'> /// The personalizer service configuration. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse <ServiceConfiguration> UpdateWithHttpMessages(this IServiceConfigurationOperations operations, ServiceConfiguration config, Dictionary <string, List <string> > customHeaders = null) { return(operations.UpdateWithHttpMessagesAsync(config, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult()); }
public void GetServiceValidationTest(ServiceConfiguration serviceConfiguration, Dictionary <string, string> expected) { Assert.Equal(expected["ContentString"], JsonSerializer.Serialize(serviceConfiguration, typeof(ServiceConfiguration), NitroServiceSerializerOptions.JsonSerializerOptions)); }
/** <inheritDoc /> */ public Task DeployAsync(ServiceConfiguration configuration) { return(_services.DeployAsync(configuration)); }
private void btnDeserializeServiceConfigurationManager_Click(object sender, EventArgs e) { ServiceConfigurationCollection list = new ServiceConfigurationCollection(); ServiceConfiguration c = new ServiceConfiguration(); c.Audit = true; c.Description = "Servicio de prueba"; c.IsolationLevel = Fwk.Transaction.IsolationLevel.ReadCommitted; c.Name = "pepep"; c.TransactionalBehaviour = Fwk.Transaction.TransactionalBehaviour.Suppres; c.Request = "BuscarPaisesPorParametros.BuscarPaisesPorParametrosRequest , GestionarPaisesISVC"; c.Response = "BuscarPaisesPorParametros.BuscarPaisesPorParametrosResponse , GestionarPaisesISVC"; list.Add(c); c = new ServiceConfiguration(); c.Audit = true; c.Description = "ModificarLocalidadService "; c.IsolationLevel = Fwk.Transaction.IsolationLevel.ReadCommitted; c.Name = "ModificarLocalidadService"; c.TransactionalBehaviour = Fwk.Transaction.TransactionalBehaviour.Suppres; c.Request = "BuscarPaisesPorParametros.BuscarPaisesPorParametrosRequest , GestionarPaisesISVC"; c.Response = "BuscarPaisesPorParametros.BuscarPaisesPorParametrosResponse , GestionarPaisesISVC"; list.Add(c); txtEntidadSimple.Text = c.GetXml(); txtCollection.Text = SerializationFunctions.SerializeToXml(list); }
protected override IStartupShutdown CreateServer(ServiceConfiguration serviceConfiguration) { return(new ServiceProcess(serviceConfiguration, Scenario, WaitForServerReadyTimeoutMs, WaitForExitTimeoutMs)); }
/// <summary> /// This method is used to do all the initialization for this class. /// </summary> /// <param name="context">The <see cref="HttpApplication"/> object which contains this module.</param> public void Init(HttpApplication context) { _serviceConfiguration = FederatedAuthentication.ServiceConfiguration; InitializeModule(context); }
public SocialService(ServiceConfiguration config) { _configuration = config as SocialServiceConfiguration; }