public static ISender GetSender() { var settings = GetSettings(); var builder = new BlipClientBuilder().UsingAccessKey(settings.BotIdentifier, settings.BotAccessKey).UsingRoutingRule(Lime.Messaging.Resources.RoutingRule.Instance); return(builder.Build()); }
static async Task MainAsync(string[] args, CancellationToken cancellationToken) { var client = new BlipClientBuilder() .UsingAccessKey("animaisdemo", "V01WNEJtVDBvRVRod1Bycm11Umw=") .Build(); Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); await client.StartAsync( async m => { Console.WriteLine("Message '{0}' received from '{1}': {2}", m.Id, m.From, m.Content); await client.SendMessageAsync("Pong!", m.From, cancellationToken); return(true); }, n => { Console.WriteLine("Notification '{0}' received from '{1}': {2}", n.Id, n.From, n.Event); return(TaskUtil.TrueCompletedTask); }, c => { Console.WriteLine("Command '{0}' received from '{1}': {2} {3}", c.Id, c.From, c.Method, c.Uri); return(TaskUtil.TrueCompletedTask); }, cancellationToken); Console.WriteLine("Client started. Press enter to stop."); Console.ReadLine(); await client.StopAsync(cancellationToken); Console.WriteLine("Client stopped. Press enter to exit."); Console.ReadLine(); }
/// <summary> /// Configures the authorization key inside the builder /// </summary> /// <param name="builder"></param> /// <param name="authorizationKey"></param> public static BlipClientBuilder UsingAuthorizationKey(this BlipClientBuilder builder, string authorizationKey) { authorizationKey = authorizationKey.Replace(KEY_PREFIX, ""); var decodedTokens = authorizationKey.FromBase64().Split(':'); var identifier = decodedTokens[0]; var accessKey = decodedTokens[1].ToBase64(); return(builder.UsingAccessKey(identifier, accessKey)); }
public CustomSender(IConfiguration configuration) { _configuration = configuration; (string botIdentifier, string botAccessKey) = GetBotConfiguration(); var builder = new BlipClientBuilder() .UsingAccessKey(botIdentifier, botAccessKey) .UsingRoutingRule(Lime.Messaging.Resources.RoutingRule.Instance); // Deve ser Instance, caso contrário poderá receber mensagens de clientes!! _client = builder.Build(); _isStarted = false; }
static async Task Main(string[] args) { var client = new BlipClientBuilder() .UsingAccessKey("", "") .Build(); Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); var listener = new BlipChannelListener(client, true, Log.Logger); listener.AddMessageReceiver( new LambdaMessageReceiver(async(message, cancellationToken) => { Console.WriteLine("Message '{0}' received from '{1}': {2}", message.Id, message.From, message.Content); await client.SendMessageAsync($"You said '{message.Content}'.", message.From, cancellationToken); }), m => Task.FromResult(m.Type == MediaType.TextPlain)); listener.AddNotificationReceiver( new LambdaNotificationReceiver((notification, cancellationToken) => { Console.WriteLine("Notification '{0}' received from '{1}': {2}", notification.Id, notification.From, notification.Event); return(Task.CompletedTask); })); listener.AddCommandReceiver( new LambdaCommandReceiver((command, cancellationToken) => { Console.WriteLine("Command '{0}' received from '{1}': {2} {3}", command.Id, command.From, command.Method, command.Uri); return(Task.CompletedTask); })); using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30))) { await client.StartAsync(listener, cts.Token); } Console.WriteLine("Client started. Press enter to stop."); Console.ReadLine(); using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30))) { await client.StopAsync(cts.Token); } Console.WriteLine("Client stopped. Press enter to exit."); Console.ReadLine(); }
/// <summary> /// Creates and starts an application with the given settings. /// </summary> /// <param name="cancellationToken"></param> /// <param name="application">The application instance. If not defined, the class will look for an application.json file in the current directory.</param> /// <param name="builder">The builder instance to be used.</param> /// <param name="typeResolver">The resolver for type names.</param> /// <param name="logger">The logger instance to be used.</param> public static async Task <IStoppable> StartAsync( CancellationToken cancellationToken, Application application = null, BlipClientBuilder builder = null, ITypeResolver typeResolver = null, ILogger logger = null) { if (application == null) { if (!File.Exists(DefaultApplicationFileName)) { throw new FileNotFoundException($"Could not find the '{DefaultApplicationFileName}' file", DefaultApplicationFileName); } application = Application.ParseFromJsonFile(DefaultApplicationFileName); } if (builder == null) { builder = new BlipClientBuilder(new TcpTransportFactory(), logger); } if (application.Identifier != null) { if (application.Password != null) { builder = builder.UsingPassword(application.Identifier, application.Password); } else if (application.AccessKey != null) { builder = builder.UsingAccessKey(application.Identifier, application.AccessKey); } else { throw new ArgumentException("At least an access key or password must be defined", nameof(application)); } } else { builder = builder.UsingGuest(); } if (application.Instance != null) { builder = builder.UsingInstance(application.Instance); } if (application.RoutingRule != null) { builder = builder.UsingRoutingRule(application.RoutingRule.Value); } if (application.Domain != null) { builder = builder.UsingDomain(application.Domain); } if (application.Scheme != null) { builder = builder.UsingScheme(application.Scheme); } if (application.HostName != null) { builder = builder.UsingHostName(application.HostName); } if (application.Port != null) { builder = builder.UsingPort(application.Port.Value); } if (application.SendTimeout != 0) { builder = builder.WithSendTimeout(TimeSpan.FromMilliseconds(application.SendTimeout)); } if (application.SessionEncryption.HasValue) { builder = builder.UsingEncryption(application.SessionEncryption.Value); } if (application.SessionCompression.HasValue) { builder = builder.UsingCompression(application.SessionCompression.Value); } if (application.Throughput != 0) { builder = builder.WithThroughput(application.Throughput); } if (application.DisableNotify) { builder = builder.WithAutoNotify(false); } if (application.ChannelCount.HasValue) { builder = builder.WithChannelCount(application.ChannelCount.Value); } if (application.ReceiptEvents != null && application.ReceiptEvents.Length > 0) { builder = builder.WithReceiptEvents(application.ReceiptEvents); } else if (application.ReceiptEvents != null) { builder = builder.WithReceiptEvents(new[] { Event.Failed }); } if (typeResolver == null) { typeResolver = new TypeResolver(); } var localServiceProvider = BuildServiceProvider(application, typeResolver); localServiceProvider.RegisterService(typeof(BlipClientBuilder), builder); var client = await BuildClientAsync(application, builder.Build, localServiceProvider, typeResolver, cancellationToken, logger : logger); var stoppables = new IStoppable[2]; stoppables[0] = client; var startable = await BuildStartupAsync(application, localServiceProvider, typeResolver); if (startable != null) { stoppables[1] = startable as IStoppable; } return(new StoppableWrapper(stoppables)); }
public void ConfigureServices(IServiceCollection services) { // Insert AppSettings var appSettings = Configuration.Get <AppSettings>(); services.AddSingleton(appSettings); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddCors(); var documentResolver = new DocumentTypeResolver().WithBlipDocuments(); services.AddSingleton <IEnvelopeSerializer>(new EnvelopeSerializer(documentResolver)); #region Dependency injection // Serilog var loggerConfiguration = new LoggerConfiguration() .ReadFrom.Configuration(Configuration) .Enrich.WithMachineName() .Enrich.WithProperty("Application", "Take.Api.Desk") .Enrich.WithExceptionDetails() .CreateLogger(); services.AddSingleton <ILogger>(loggerConfiguration); services.AddHostedService <CheckQueueStatusBll>(); // Initialize Blip CLients var container = new Container(); foreach (var cfg in appSettings.BotConfigurations.Bots) { var blipClient = new BlipClientBuilder() .UsingHostName("msging.net") .UsingPort(55321) .UsingAccessKey(cfg.BotId, cfg.BotAccessKey) .UsingRoutingRule(RoutingRule.Instance) .UsingInstance(cfg.BotId) .WithChannelCount(1) .Build(); services.AddBlipClientToContainer(container, blipClient, cfg.BotId); } services.AddSingleton <IContainer>(container); services.AddMvc().AddJsonOptions(options => { foreach (var settingsConverter in JsonNetSerializer.Settings.Converters) { options.SerializerSettings.Converters.Add(settingsConverter); } }); // Injections Layer services.AddInjectionsBll(); #endregion services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "Take desk", Version = "v1", Description = "Api" }); }); }
public static IServiceCollection AddBlip(this IServiceCollection serviceCollection) { var applicationJsonPath = Path.Combine( Path.GetDirectoryName( Assembly.GetEntryAssembly().Location), Bootstrapper.DefaultApplicationFileName); if (!File.Exists(applicationJsonPath)) { throw new InvalidOperationException($"Could not find the application file in '{applicationJsonPath}'"); } var application = Application.ParseFromJsonFile(applicationJsonPath); if (string.IsNullOrEmpty(application.Identifier)) { var rawApplicationJson = File.ReadAllText(applicationJsonPath); var applicationJson = JObject.Parse(rawApplicationJson); var authorizationHeader = applicationJson["authorization"]?.ToString(); if (authorizationHeader != null) { var authorization = authorizationHeader.Split(' ')[1].FromBase64(); var identifierAndAccessKey = authorization.Split(':'); application.Identifier = identifierAndAccessKey[0]; application.AccessKey = identifierAndAccessKey[1].ToBase64(); } } var workingDir = Path.GetDirectoryName(applicationJsonPath); if (string.IsNullOrWhiteSpace(workingDir)) { workingDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); } var envelopeBuffer = new EnvelopeBuffer(); var envelopeSerializer = new EnvelopeSerializer(new DocumentTypeResolver().WithMessagingDocuments()); var clientBuilder = new BlipClientBuilder( new WebTransportFactory(envelopeBuffer, envelopeSerializer, application)); IStoppable stoppable; using (var cts = new CancellationTokenSource(StartTimeout)) { stoppable = Bootstrapper .StartAsync( cts.Token, application, clientBuilder, new TypeResolver(workingDir)) .GetAwaiter() .GetResult(); } serviceCollection.AddSingleton(application); serviceCollection.AddSingleton(stoppable); serviceCollection.AddSingleton <IEnvelopeBuffer>(envelopeBuffer); serviceCollection.AddSingleton <IEnvelopeSerializer>(envelopeSerializer); return(serviceCollection); }