Ejemplo n.º 1
0
        public void OnLoad(IBinder Binder)
        {
            Binder.Bind <IAudioWriterItem, WaveItem>();

            WindowsModule.Load(Binder);

            FFmpegModule.Load(Binder);

            BindViewModels(Binder);
            BindSettings(Binder);
            BindImageWriters(Binder);
            BindVideoWriterProviders(Binder);
            BindVideoSourceProviders(Binder);
            BindAudioSource(Binder);
            BindUpdateChecker(Binder);

            // Recent
            Binder.Bind <IRecentList, RecentListRepository>();
            Binder.Bind <IRecentItemSerializer, FileRecentSerializer>();
            Binder.Bind <IRecentItemSerializer, UploadRecentSerializer>();

            Binder.Bind <IImageUploader, ImgurUploader>();
            Binder.Bind <IIconSet, MaterialDesignIcons>();
            Binder.Bind <IImgurApiKeys, ApiKeys>();
            Binder.Bind <IYouTubeApiKeys, ApiKeys>();

            Binder.BindSingleton <HotKeyManager>();

            Binder.Bind <ILocalizationProvider>(() => LanguageManager.Instance);

            Binder.Bind <IFpsManager, FpsManager>();
        }
Ejemplo n.º 2
0
        public static void image_mqtt_ingest(
            [MqttTrigger("site/+/grids/+/sensors/image/#")] IMqttMessage message,
            ILogger logger,
            IBinder binder)
        {
            // topic structure: sites/xx/grids/dd/sensors/image/bin/#
            // topic structure: sites/xx/grids/dd/sensors/image/status/#
            var topicParts = message.Topic.Split('/');
            var siteid     = topicParts[1];
            var imagepath  = string.Join('/', topicParts.Skip(6).SkipLast(1));
            var blobname   = topicParts.Last();

            logger.LogInformation($"CreateBlobUsingBinder function processed: {message}");
            using (var writer = binder.Bind <Stream>(new BlobAttribute(
                                                         $"brc-images/sites/{siteid}/{imagepath}/{blobname}.jpg", FileAccess.Write)))
            {
                writer.Write(message.GetMessage());
            };

            using (var writer = binder.Bind <Stream>(new BlobAttribute(
                                                         $"brc-images/sites/{siteid}/{imagepath}/latest.jpg", FileAccess.Write)))
            {
                writer.Write(message.GetMessage());
            };
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Creates the window.
        /// </summary>
        /// <param name="rootModel">The root model.</param>
        /// <param name="isDialog">Inidcates a dialog window.</param>
        /// <param name="context">The context.</param>
        /// <param name="handleShutdownModel">The handle shutdown model.</param>
        /// <returns></returns>
        protected virtual Window CreateWindow(object rootModel, bool isDialog, object context, Action <ISubordinate, Action> handleShutdownModel)
        {
            var view = EnsureWindow(rootModel, _viewStrategy.GetView(rootModel, null, context), isDialog);

            _binder.Bind(rootModel, view, context);

            var screen = rootModel as IPresenter;

            if (screen != null)
            {
                screen.Initialize();
                screen.Activate();

                view.Activated += delegate
                {
                    screen.Activate();
                };
                view.Closing += (s, e) => OnShutdownAttempted(screen, view, handleShutdownModel, e);

                view.Closed += delegate
                {
                    screen.Deactivate();
                    screen.Shutdown();
                };
            }

            return(view);
        }
Ejemplo n.º 4
0
        public IBinding Add <TConcretion>() where TConcretion : TAbstraction
        {
            var binding = _binder.Bind <TAbstraction, TConcretion>().InList();

            _bindings.Add(binding);
            return(binding);
        }
Ejemplo n.º 5
0
        void IStatus.Enter()
        {
            _Binder.Bind <ICastSkill>(this);
            _Player.SetSkillVelocity(_Caster.GetShiftDirection(), _Caster.GetShiftSpeed());
            _Player.CastBegin(_Caster.Data.Id);

            _MoveController.Backward   = _Caster.GetBackward();
            _MoveController.Forward    = _Caster.GetForward();
            _MoveController.RunForward = _Caster.GetRunForward();
            _MoveController.TurnLeft   = _Caster.GetTurnLeft();
            _MoveController.TurnRight  = _Caster.GetTurnRight();

            _Binder.Bind <IMoveController>(_MoveController);

            if (_Caster.CanDisarm())
            {
                _Binder.Bind <IBattleSkill>(this);
            }

            _CastTimer.Reset();

            _DatumPosition = _Player.GetPosition();
            var strength = _Player.Strength(-_Caster.Data.StrengthCost);

            _Overdraft = strength < 0.0f;
        }
Ejemplo n.º 6
0
 void IStatus.Enter()
 {
     _Binder.Bind <IEquipmentNotifier>(_Player.Equipment);
     _Binder.Bind <IBagNotifier>(_Player.Bag);
     _Player.ResetProperty();
     _ToDone();
 }
Ejemplo n.º 7
0
        public void Init()
        {
            this.injector = new InjectionContainer();
            this.binder   = this.injector as IBinder;

            //Binds some objects to use on tests.
            binder.Bind <IMockInterface>().To <MockIClassWithAttributes>();
            binder.Bind <MockIClassWithoutAttributes>().ToSingleton().As("singleton");
            binder.Bind <MockIClass>().ToSingleton();

            this.containerIdentifierTests = new InjectionContainer();
            var mockClass1 = new MockIClass()
            {
                property1 = "MockClass1"
            };
            var mockClass2 = new MockIClassWithoutAttributes()
            {
                property1 = "MockClass2"
            };
            var mockClass3 = new MockIClassWithAttributes()
            {
                property1 = "MockClass3"
            };

            this.containerIdentifierTests.Bind <MockIClass>().To(mockClass1).As(TestIdentifier.MockClass);
            this.containerIdentifierTests.Bind <MockIClassWithoutAttributes>().To(mockClass2).As(TestIdentifier.MockClass);
            this.containerIdentifierTests.Bind <MockIClassWithAttributes>().To(mockClass3).As(TestIdentifier.MockClass);
            this.containerIdentifierTests.Bind <IMockInterface>().To(mockClass1).As(TestIdentifier.MockClass1);
            this.containerIdentifierTests.Bind <IMockInterface>().To(mockClass2).As(TestIdentifier.MockClass2);
            this.containerIdentifierTests.Bind <IMockInterface>().To(mockClass3).As(TestIdentifier.MockClass3);
            this.containerIdentifierTests.Bind <IMockInterface>().To <MockIClass>().As(TestIdentifier.MockClassSingle);
        }
        public override async Task BindAsync(IBinder binder, Stream stream, IReadOnlyDictionary<string, string> bindingData)
        {
            string boundQueueName = QueueName;
            if (bindingData != null)
            {
                boundQueueName = _queueNameBindingTemplate.Bind(bindingData);
            }

            if (FileAccess == FileAccess.Write)
            {
                Stream queueStream = binder.Bind<Stream>(new QueueAttribute(boundQueueName));
                await queueStream.CopyToAsync(stream);
            }
            else
            {
                IAsyncCollector<byte[]> collector = binder.Bind<IAsyncCollector<byte[]>>(new QueueAttribute(boundQueueName));
                byte[] bytes;
                using (MemoryStream ms = new MemoryStream())
                {
                    stream.CopyTo(ms);
                    bytes = ms.ToArray();
                }
                await collector.AddAsync(bytes);
            }
        }
Ejemplo n.º 9
0
        public void OnLoad(IBinder Binder)
        {
            Binder.BindSingleton <CrashLogsViewModel>();
            Binder.BindSingleton <FileNameFormatViewModel>();
            Binder.BindSingleton <LicensesViewModel>();
            Binder.BindSingleton <ProxySettingsViewModel>();
            Binder.BindSingleton <SoundsViewModel>();
            Binder.BindSingleton <RecentViewModel>();
            Binder.BindSingleton <UpdateCheckerViewModel>();
            Binder.BindSingleton <ScreenShotViewModel>();
            Binder.BindSingleton <RecordingViewModel>();
            Binder.BindSingleton <MainViewModel>();
            Binder.BindSingleton <HotkeysViewModel>();
            Binder.BindSingleton <FFmpegLogViewModel>();
            Binder.BindSingleton <FFmpegCodecsViewModel>();
            Binder.BindSingleton <ViewConditionsModel>();

            Binder.BindSingleton <VideoSourcesViewModel>();
            Binder.BindSingleton <VideoWritersViewModel>();
            Binder.Bind <IRefreshable>(Binder.Get <VideoWritersViewModel>);

            Binder.BindSingleton <CustomOverlaysViewModel>();
            Binder.BindSingleton <CustomImageOverlaysViewModel>();
            Binder.BindSingleton <CensorOverlaysViewModel>();

            Binder.BindSingleton <FFmpegLog>();
            Binder.Bind <IFFmpegLogRepository>(ServiceProvider.Get <FFmpegLog>);
        }
Ejemplo n.º 10
0
        public void OnLoad(IBinder Binder)
        {
            BindViewModels(Binder);
            BindSettings(Binder);
            BindImageWriters(Binder);
            BindVideoWriterProviders(Binder);
            BindVideoSourceProviders(Binder);
            BindAudioSource(Binder);
            BindUpdateChecker(Binder);

            // Recent
            Binder.Bind <IRecentList, RecentListRepository>();
            Binder.Bind <IRecentItemSerializer, FileRecentSerializer>();
            Binder.Bind <IRecentItemSerializer, UploadRecentSerializer>();

            Binder.Bind <IDialogService, DialogService>();
            Binder.Bind <IClipboardService, ClipboardService>();
            Binder.Bind <IImageUploader, ImgurUploader>();
            Binder.Bind <IIconSet, MaterialDesignIcons>();
            Binder.Bind <IImgurApiKeys, ApiKeys>();
            Binder.Bind <IYouTubeApiKeys, ApiKeys>();

            Binder.BindSingleton <FullScreenItem>();
            Binder.BindSingleton <FFmpegLog>();
            Binder.BindSingleton <HotKeyManager>();
            Binder.Bind(() => LanguageManager.Instance);
        }
Ejemplo n.º 11
0
        public void Init()
        {
            this.binder = new Binder();

            //Binds some objects to use on tests.
            binder.Bind <IMockInterface>().To <MockIClassWithAttributes>();
            binder.Bind(typeof(MockClassWithDependencies)).ToSelf();
        }
Ejemplo n.º 12
0
 public void OnLoad(IBinder Binder)
 {
     Binder.Bind <ICmdlineVerb, StartCmdOptions>();
     Binder.Bind <ICmdlineVerb, ShotCmdOptions>();
     Binder.Bind <ICmdlineVerb, FFmpegCmdOptions>();
     Binder.Bind <ICmdlineVerb, ListCmdOptions>();
     Binder.Bind <ICmdlineVerb, UploadCmdOptions>();
 }
Ejemplo n.º 13
0
 static void BindSettings(IBinder Binder)
 {
     Binder.BindSingleton <Settings>();
     Binder.Bind(() => Binder.Get <Settings>().Audio);
     Binder.Bind(() => Binder.Get <Settings>().Sounds);
     Binder.Bind(() => Binder.Get <Settings>().Video);
     Binder.Bind(() => Binder.Get <Settings>().UI);
 }
Ejemplo n.º 14
0
        public override void Enter()
        {
            _Binder.Bind <IInventoryController>(this);
            _Binder.Bind <IMoveController>(_MoveController);
            _Binder.Bind <INormalSkill>(this);

            _Player.Normal();
        }
Ejemplo n.º 15
0
        public void Init()
        {
            this.binder = new Binder();

            //Binds some objects to use on tests.
            binder.Bind<IMockInterface>().To<MockIClassWithAttributes>();
            binder.Bind(typeof(MockClassWithDependencies)).ToSelf();
        }
Ejemplo n.º 16
0
 static void BindSettings(IBinder Binder)
 {
     Binder.BindSingleton <Settings>();
     Binder.Bind(() => ServiceProvider.Get <Settings>().Audio);
     Binder.Bind(() => ServiceProvider.Get <Settings>().Proxy);
     Binder.Bind(() => ServiceProvider.Get <Settings>().Sounds);
     Binder.Bind(() => ServiceProvider.Get <Settings>().Imgur);
 }
Ejemplo n.º 17
0
 public static void Load(IBinder Binder)
 {
     Binder.Bind <IPlatformServices, WindowsPlatformServices>();
     Binder.Bind <IDialogService, DialogService>();
     Binder.Bind <IClipboardService, ClipboardService>();
     Binder.Bind <IImagingSystem, DrawingImagingSystem>();
     Binder.Bind <IWebCamProvider, WebcamProvider>();
 }
Ejemplo n.º 18
0
 static void BindSettings(IBinder Binder)
 {
     Binder.BindSingleton <Settings>();
     Binder.Bind(() => Binder.Get <Settings>().ImageEditor);
     Binder.Bind(() => Binder.Get <Settings>().Audio);
     Binder.Bind(() => Binder.Get <Settings>().Proxy);
     Binder.Bind(() => Binder.Get <Settings>().Sounds);
     Binder.Bind(() => Binder.Get <Settings>().Imgur);
 }
Ejemplo n.º 19
0
 public IScopedBindingBuilder To <ImplementationType>(string name = null) where ImplementationType : InterfaceType, new()
 {
     if (name != null)
     {
         _name = name;
     }
     _binding = _binder.Bind <InterfaceType, ImplementationType>(_name);
     return(this);
 }
Ejemplo n.º 20
0
 static void BindAudioSource(IBinder Binder)
 {
     // Check if Bass is available
     if (BassAudioSource.Available)
     {
         Binder.Bind <AudioSource, BassAudioSource>();
     }
     else
     {
         Binder.Bind <AudioSource, NAudioSource>();
     }
 }
Ejemplo n.º 21
0
        static void BindUpdateChecker(IBinder Binder)
        {
            var version = ServiceProvider.AppVersion;

            if (version?.Major == 0)
            {
                Binder.Bind <IUpdateChecker, DevUpdateChecker>();
            }
            else
            {
                Binder.Bind <IUpdateChecker, UpdateChecker>();
            }
        }
Ejemplo n.º 22
0
        static void BindUpdateChecker(IBinder Binder)
        {
            var version = Assembly.GetEntryAssembly()?.GetName().Version;

            if (version?.Major == 0)
            {
                Binder.Bind <IUpdateChecker, DevUpdateChecker>();
            }
            else
            {
                Binder.Bind <IUpdateChecker, UpdateChecker>();
            }
        }
Ejemplo n.º 23
0
        static void BindViewModels(IBinder Binder)
        {
            Binder.BindSingleton <TimerModel>();
            Binder.BindSingleton <MainModel>();
            Binder.BindSingleton <ScreenShotModel>();
            Binder.BindSingleton <RecordingModel>();
            Binder.BindSingleton <WebcamModel>();
            Binder.BindSingleton <VideoSourcesViewModel>();
            Binder.BindSingleton <VideoWritersViewModel>();
            Binder.BindSingleton <KeymapViewModel>();

            Binder.Bind <IRefreshable>(Binder.Get <WebcamModel>);
            Binder.Bind <IRefreshable>(Binder.Get <VideoWritersViewModel>);
        }
Ejemplo n.º 24
0
        public static async Task <IActionResult> NegotiatBindingAsync(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "negotiate")] HttpRequest req,
            IBinder binder,
            ILogger log)
        {
            string AUTH_HEADER_NAME = "Authorization";
            string BEARER_PREFIX    = "Bearer ";

            if (req.Headers.ContainsKey(AUTH_HEADER_NAME) && req.Headers[AUTH_HEADER_NAME].ToString().StartsWith(BEARER_PREFIX))
            {
                var token = req.Headers[AUTH_HEADER_NAME].ToString().Substring(BEARER_PREFIX.Length);

                if (token.Equals("cloud-app"))
                {
                    var conn = binder.Bind <SignalRConnectionInfo>(new SignalRConnectionInfoAttribute {
                        HubName = "agro", UserId = "cloud-app"
                    });

                    return(new OkObjectResult(conn));
                }

                log.LogInformation("with binding " + token);
                IAuthentication auth = new Authentication(
                    Environment.GetEnvironmentVariable("clientID", EnvironmentVariableTarget.Process),
                    Environment.GetEnvironmentVariable("tenant", EnvironmentVariableTarget.Process),
                    Environment.GetEnvironmentVariable("tenantID", EnvironmentVariableTarget.Process),
                    Environment.GetEnvironmentVariable("validAudiences", EnvironmentVariableTarget.Process).Split(";")
                    );
                var claims = await auth.ValidateAccessToken(token);

                string ObjectIdAAD = claims.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                var    queries     = new CommonQueries(ConfigManager.GetDbArguments);
                // extract userId from token
                var userId = await queries.GetUserIdFromAAD(ObjectIdAAD);

                var connectionInfo = binder.Bind <SignalRConnectionInfo>(new SignalRConnectionInfoAttribute {
                    HubName = "agro", UserId = userId
                });
                log.LogInformation("negotiated " + connectionInfo);
                //https://gist.github.com/ErikAndreas/72c94a0c8a9e6e632f44522c41be8ee7
                // connectionInfo contains an access key token with a name identifier claim set to the authenticated user
                return(new OkObjectResult(connectionInfo));
            }
            else
            {
                // temporal, para conectar winform sin autenticación
                return(new UnauthorizedResult());
            }
        }
Ejemplo n.º 25
0
        public static void Load(IBinder Binder)
        {
            Binder.BindSingleton <FFmpegSettings>();
            Binder.BindAsInterfaceAndClass <IVideoWriterProvider, FFmpegWriterProvider>();
            Binder.BindAsInterfaceAndClass <IVideoWriterProvider, StreamingWriterProvider>();

            foreach (var audioItem in FFmpegAudioItem.Items)
            {
                Binder.Bind <IAudioWriterItem>(() => audioItem);
            }

            Binder.Bind <IVideoConverter>(() => new FFmpegGifConverter());
            Binder.Bind <IVideoConverter>(() => new FFmpegVideoConverter(new Vp8VideoCodec()));
            Binder.Bind <IVideoConverter>(() => new FFmpegVideoConverter(new Vp9VideoCodec()));
        }
Ejemplo n.º 26
0
 public void OnLoad(IBinder Binder)
 {
     Binder.Bind <IMessageProvider, FakeMessageProvider>();
     Binder.Bind <IRegionProvider>(() => FakeRegionProvider.Instance);
     Binder.Bind <ISystemTray, FakeSystemTray>();
     Binder.Bind <IMainWindow, FakeWindowProvider>();
     Binder.Bind <IPreviewWindow, FakePreviewWindow>();
     Binder.Bind <IVideoSourcePicker>(() => FakeVideoSourcePicker.Instance);
     Binder.Bind <IAudioPlayer, FakeAudioPlayer>();
     Binder.Bind <IFFmpegViewsProvider, FakeFFmpegViewsProvider>();
     Binder.Bind <IFFmpegLogRepository, FakeFFmpegLogRepository>();
 }
Ejemplo n.º 27
0
        public static void Run([QueueTrigger("success-charges", Connection = "")]
                               Transaction transaction, IBinder binder,
                               [Table("payments")] out Payment payment,
                               ILogger log)
        {
            log.LogInformation($"ProcessSuccessCharge function processed: {transaction}");

            payment = new Payment
            {
                PartitionKey  = "stripe",
                RowKey        = transaction.Id,
                ChargeId      = transaction.ChargeId,
                Amount        = transaction.Amount,
                CardType      = transaction.CardType,
                Currency      = transaction.Currency,
                CustomerEmail = transaction.CustomerEmail,
                CustomerId    = transaction.CustomerId,
                CustomerName  = transaction.CustomerName,
                Product       = transaction.Product,
                DateCreated   = transaction.DateCreated
            };

            using (var license = binder.Bind <TextWriter>(new BlobAttribute($"licenses/{transaction.Id}.lic")))
            {
                license.WriteLine($"Transaction ID: {transaction.ChargeId}");
                license.WriteLine($"Email: {transaction.CustomerEmail}");
                license.WriteLine($"Amount payed: {transaction.Amount}  {transaction.Currency}");
                license.WriteLine($"license key: {transaction.Id}");
            }
        }
Ejemplo n.º 28
0
        public static void Run(
            [QueueTrigger("WebPlans", Connection = "AzureWebJobsStorage")] QueryPlan queryPlan,
            TraceWriter log,
            IBinder binder)
        {
            log.Info($"Received an query plan: Plan {queryPlan.PlanId} from Product {queryPlan.ProductId}");

            var blob = new BlobAttribute($"parsedplans/{queryPlan.PlanId}.txt")
            {
                Connection = "AzureWebJobsStorage"
            };

            using (var outputBlob = binder.Bind <TextWriter>(blob))
            {
                outputBlob.WriteLine($"PlanId: {queryPlan.PlanId}");
                outputBlob.WriteLine($"ProductId: {queryPlan.ProductId}");
                outputBlob.WriteLine($"Email: {queryPlan.Email}");
                outputBlob.WriteLine($"Plan: {queryPlan.Plan}");
                outputBlob.WriteLine($"PurchaseDate: {System.DateTime.UtcNow}");

                var md5  = System.Security.Cryptography.MD5.Create();
                var hash = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(queryPlan.Email + "secret"));
                outputBlob.WriteLine($"SecretCode: {System.BitConverter.ToString(hash).Replace("-", "")}");
            }
        }
Ejemplo n.º 29
0
        public async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "signalr/negotiate")] HttpRequest req,
            IBinder binder)
        {
            var rpr = await _requestProcessor.ProcessAsync(req);

            if (!rpr.IsSuccess)
            {
                return(HttpUtilities.BadRequest(rpr.Message));
            }

            if (!(await rpr.Context.CheckAccessAsync()))
            {
                return(HttpUtilities.BadRequest($"Invalid auth header for {rpr.Context.Host}"));
            }

            await SetupEndpointAsync(rpr.Context.InstanceName);
            await SetupRouteAsync(rpr.Context);

            var hubName        = rpr.Context.InstanceName;
            var userId         = rpr.Context.Token.Id;
            var connectionInfo = binder.Bind <SignalRConnectionInfo>(
                new SignalRConnectionInfoAttribute
            {
                HubName = hubName,
                UserId  = userId
            });

            _log.LogInformation($"Negotiated connection to {hubName}");
            return(HttpUtilities.Ok(connectionInfo));
        }
Ejemplo n.º 30
0
 /// <summary>
 /// Reads a message from the "orders" queue and writes a blob in the "orders" container
 /// </summary>
 public static void QueueToBlob(
     [QueueTrigger("orders")] string orders, 
     IBinder binder)
 {
     TextWriter writer = binder.Bind<TextWriter>(new BlobAttribute("orders/" + orders));
     writer.Write("Completed");
 }
Ejemplo n.º 31
0
        void IStatus.Enter()
        {
            _Player.Make();
            _Formulas = _Player.GetFormulas();

            _Binder.Bind <IMakeSkill>(this);
        }
        public static async Task <InvitationCodeResponse> CreateUserInvitation(
            [HttpTrigger(AuthorizationLevel.Function, WebRequestMethods.Http.Post)] InvitationCodeRequest request,
            IBinder binder,
            ILogger log)
        {
            log.LogInformation("A new user invitation was requested.");

            // Create a new invitation code that cannot easily be guessed by others and is unique so that it cannot
            // conflict with an invitation code for another user (as at this point the invitation code already represents
            // the user-to-be).
            var invitationCode = Guid.NewGuid().ToString();

            // Write the user invitation request to persistent storage in a way that it can easily be retrieved using
            // just the invitation code.
            using (var blobOutputStream = binder.Bind <Stream>(new BlobAttribute($"userinvitations/{invitationCode}.json", FileAccess.Write)))
            {
                await JsonSerializer.SerializeAsync(blobOutputStream, request);
            };
            log.LogInformation($"User invitation was stored in persistent storage with invitation code \"{invitationCode}\".");

            // Return the invitation code for the user back to the caller (along with the original request).
            return(new InvitationCodeResponse {
                Request = request, InvitationCode = invitationCode
            });
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Binds both as Inteface as Class
        /// </summary>
        static void BindAsInterfaceAndClass <TInterface, TClass>(IBinder Binder) where  TClass : TInterface
        {
            Binder.BindSingleton <TClass>();

            // ReSharper disable once ConvertClosureToMethodGroup
            Binder.Bind <TInterface>(() => ServiceProvider.Get <TClass>());
        }
Ejemplo n.º 34
0
 // This function will get triggered/executed when a new message is written
 // on an Azure Queue called queue.
 public static void ProcessQueueMessage([QueueTrigger("afro")] String message, TextWriter log, IBinder binder, Int32 dequeueCount)
 {
     log.WriteLine("este es el intento numero{0}", dequeueCount);
     if (dequeueCount <= 5)
     {
         binder.Bind<QueueAttribute>(new QueueAttribute("afro-poison"));
     }
     throw new Exception("throw perra");
 }
Ejemplo n.º 35
0
        public static void RecordTime(IBinder binder, TextWriter logger)
        {
            var start = $"{DateTime.UtcNow:yyyyMMdd-HHmmss}";

            var blobAttribute = new BlobAttribute($"output/{start}");
            var blob = binder.Bind<CloudBlockBlob>(blobAttribute);

            blob.UploadText(start);
            logger.WriteLine(start);

            //RecordTimeAndSleep(start, blob, logger);
            RecordTimes(start, blob, logger);
        }
Ejemplo n.º 36
0
        public static void BackupFile(
            string fileContent,
            string fileName,
            IBinder binder,
            TextWriter log)
        {
            log.WriteLine("Backing up file in Azure Storage: " + fileName);

            // Use IBinder because property binding doesn't work without a trigger attribute
            // if it would work, the code would be much simpler
            TextWriter backupFile = binder.Bind<TextWriter>(new BlobAttribute("backup/" + fileName));
            backupFile.Write(fileContent);
        }
Ejemplo n.º 37
0
        public void Init()
        {
            this.injector = new InjectionContainer();
            this.binder = this.injector as IBinder;

            //Binds some objects to use on tests.
            binder.Bind<IMockInterface>().To<MockIClassWithAttributes>();
            binder.Bind<MockIClassWithoutAttributes>().ToSingleton().As("singleton");
            binder.Bind<MockIClass>().ToSingleton();

            this.containerIdentifierTests = new InjectionContainer();
            var mockClass1 = new MockIClass() { property1 = "MockClass1" };
            var mockClass2 = new MockIClassWithoutAttributes() { property1 = "MockClass2" };
            var mockClass3 = new MockIClassWithAttributes() { property1 = "MockClass3" };
            this.containerIdentifierTests.Bind<MockIClass>().To(mockClass1).As(TestIdentifier.MockClass);
            this.containerIdentifierTests.Bind<MockIClassWithoutAttributes>().To(mockClass2).As(TestIdentifier.MockClass);
            this.containerIdentifierTests.Bind<MockIClassWithAttributes>().To(mockClass3).As(TestIdentifier.MockClass);
            this.containerIdentifierTests.Bind<IMockInterface>().To(mockClass1).As(TestIdentifier.MockClass1);
            this.containerIdentifierTests.Bind<IMockInterface>().To(mockClass2).As(TestIdentifier.MockClass2);
            this.containerIdentifierTests.Bind<IMockInterface>().To(mockClass3).As(TestIdentifier.MockClass3);
            this.containerIdentifierTests.Bind<IMockInterface>().To<MockIClass>().As(TestIdentifier.MockClassSingle);
        }
Ejemplo n.º 38
0
        void ScanAndRegisterHandlers(IBinder binder, IScanner scanner) 
        {
            var handlerTups = scanner.ScanTypes(typeof(Registrar).Assembly)
                                        .Where(t => !t.IsAbstract)
                                        .Select(t => new {
                                            ImplType = t,
                                            IntType = t.GetInterfaces()
                                                            .SingleOrDefault(i => i.IsGenericType
                                                                                && i.GetGenericTypeDefinition() == typeof(IQueryHandler<,>))
                                        })
                                        .Where(tup => tup.IntType != null);

            foreach(var tup in handlerTups) {
                binder.Bind(tup.IntType, tup.ImplType);
            }
        }
        /// <summary>
        /// Waits for message from the queue and creates shuffles
        /// </summary>
        /// <param name="shufflerequests">The message received from queue</param>
        public static void CreateShuffle(
            [QueueInput] ShuffleRequestMessage shufflerequests,
            IBinder binder)
        {
            string shuffleId = shufflerequests.ShuffleId;

            ImageProcessingJobs processor = new ImageProcessingJobs();
            string shuffle = processor.CreateShuffle(shuffleId);

            Stream shuffleBlob = binder.Bind<Stream>(new BlobOutputAttribute("shuffle" + shuffleId + @"/shuffle.jpg"));

            using (Stream localShuffle = File.OpenRead(shuffle))
            {
                localShuffle.CopyTo(shuffleBlob);
            }
        }
        /// <summary>
        /// Waits for message from the queue and creates shuffles
        /// </summary>
        /// <param name="shufflerequest">The message received from queue</param>
        public static void CreateShuffle(
            [QueueTrigger("shufflerequests")] ShuffleRequestMessage shufflerequest,
            IBinder binder)
        {
            string shuffleId = shufflerequest.ShuffleId;

            ImageProcessingJobs processor = new ImageProcessingJobs();
            string shuffle = processor.CreateShuffle(shuffleId);

            BlobAttribute attribute = new BlobAttribute("shuffle" + shuffleId + @"/shuffle.jpg", FileAccess.Write);
            Stream shuffleBlob = binder.Bind<Stream>(attribute);

            using (Stream localShuffle = File.OpenRead(shuffle))
            {
                localShuffle.CopyTo(shuffleBlob);
            }
        }
        public override async Task BindAsync(IBinder binder, Stream stream, IReadOnlyDictionary<string, string> bindingData)
        {
            string boundBlobPath = Path;
            if (bindingData != null)
            {
                boundBlobPath = _pathBindingTemplate.Bind(bindingData);
            }

            Stream blobStream = binder.Bind<Stream>(new BlobAttribute(boundBlobPath, FileAccess));
            if (FileAccess == FileAccess.Write)
            {
                await stream.CopyToAsync(blobStream);
            }
            else
            {
                await blobStream.CopyToAsync(stream);
            }
        }
        public void Bind(IBinder binder)
        {
            Mock<IUnitOfWork> mock = new Mock<IUnitOfWork>();
            mock.Setup(m => m.Products.GetAll()).Returns(new List<Product>
            {
                new Product {ProductID=1,Name = "Table", Price = 25, Category="Kitchen"},
                new Product {ProductID=2,Name = "Ball", Price = 179,Category = "Outside"},
                new Product {ProductID=3,Name = "Oven", Price = 95, Category="Kitchen"},
                new Product {ProductID=4,Name = "KeyBoard", Price = 10,Category = "Office"},
                new Product {ProductID=5,Name = "Phone", Price = 20,Category = "Office"},
                new Product {ProductID=6,Name = "Mouse", Price = 45,Category = "Office"},
                new Product {ProductID=7,Name = "TV", Price = 34, Category = "Office"},
                new Product {ProductID=8,Name = "Glass", Price = 47,Category = "Kitchen"},
                new Product {ProductID=9,Name = "Plate", Price = 88, Category="Kitchen"},
                new Product {ProductID=10,Name = "Fork", Price = 44, Category="Kitchen"},
                new Product {ProductID=11,Name = "Knife", Price = 66, Category ="Kitchen"}
            }.AsQueryable());

            //binder.BindToConstant<IUnitOfWork, IUnitOfWork>(mock.Object);
            binder.Bind<IUnitOfWork, StefanStoreUow>();
        }
 /// <summary>
 /// Same as "BlobNameFromQueueMessage" but using IBinder 
 /// </summary>
 public static void BlobIBinder(
     [QueueTrigger("persons")] Person persons, 
     IBinder binder)
 {
     TextWriter writer = binder.Bind<TextWriter>(new BlobAttribute("persons/" + persons.Name + "BlobIBinder"));
     writer.Write("Hello " + persons.Name);
 }
Ejemplo n.º 44
0
        public void Register(IBinder x, IScanner scanner) 
        {
            x.Bind<HttpContext>(_ => HttpContext.Current);
            x.Bind<HttpContextBase>(_ => new HttpContextWrapper(HttpContext.Current));

            x.Bind(c => c.Resolve<HttpContext>().Request);
            x.Bind(c => c.Resolve<HttpContext>().Response);
            x.Bind(c => c.Resolve<HttpContext>().Server);
            x.Bind(c => c.Resolve<HttpContext>().Session);

            x.BindSingleton<ICache>(_ => new BrigitaCache(MemoryCache.Default));
            x.Bind<ICacheManager, MemoryCacheManager>();

            //x.Register<IRoutePublisher, RoutePublisher>();

            x.Bind<IEventPublisher, EventPublisher>();
            x.Bind<ISubscriptionService, SubscriptionService>();

            x.Bind<IGenericAttributeService, GenericAttributeService>();

            x.Bind<IPluginFinder, BrigitaPluginFinder>();

            x.Bind<ILogger, NullLogger>();


            x.BindGeneric(typeof(IRepo<>), typeof(Repo<>));
                        
            x.Bind<ILinkProvider, LinkProvider>();

            x.Bind<IMediator, Mediator>();

            x.Bind<IPicSource, PicSource>();
            x.Bind<IPictureService, PictureService>();

            x.Bind<ILocaleContext, LocaleContext>();
            x.Bind<ILocaleCodeProvider, LocaleCodeProvider>();
            
            x.BindGeneric(typeof(ILocalizer<>), typeof(Localizer<>));
            x.BindGeneric(typeof(IStringLocalizer<>), typeof(StringLocalizer<>));
            x.BindGeneric(typeof(ICurrencyLocalizer<>), typeof(CurrencyLocalizer<>));


            x.Bind<IWorkContext, BrigitaWorkContext>();




            x.Bind<IPageHelper, PageHelper>();
            x.Bind<ILinkHelper, LinkHelper>();

            //!!!!!!!! JUST FOR TESTING... !!!!!!!!!
            x.Bind(new StoreInformationSettings());
            x.Bind(new TaxSettings());
            x.Bind(new CurrencySettings());
            x.Bind(new LocalizationSettings());
            x.Bind(new CustomerSettings());
            x.Bind(new CommonSettings());
            x.Bind(new CatalogSettings());
            x.Bind(new SeoSettings());
            x.Bind(new MediaSettings());
            x.Bind<ISettingService, SettingService>();

            x.Bind<IUserAgentHelper, UserAgentHelper>();
            x.Bind<IWebHelper, WebHelper>();

            /*x.Bind<IWorkContext, WebWorkContext>();*/
            x.Bind<IStoreContext, WebStoreContext>();

            x.Bind<ICategories, BrigitaCategories>();
            x.Bind<IScopedCategories, ScopedCategories>();

            x.Bind<IProducts, BrigitaProducts>();


            x.Bind<ICustomerService, CustomerService>();
            x.Bind<IVendorService, VendorService>();
            x.Bind<IStoreService, BrigitaStores>();
            x.Bind<IAuthenticationService, FormsAuthenticationService>();
            x.Bind<ILanguageService, LanguageService>();
            x.Bind<ICurrencyService, CurrencyService>();
            x.Bind<IStoreMappingService, StoreMappingService>();

            x.Bind<IPageHeadBuilder, PageHeadBuilder>();


            //data layer
            var dataSettingsManager = new DataSettingsManager();
            var dataProviderSettings = dataSettingsManager.LoadSettings();
            x.Bind<DataSettings>(c => dataSettingsManager.LoadSettings());

            x.BindTransient<BaseDataProviderManager, EfDataProviderManager>();
            x.BindTransient<IDataProvider>(c => c.Resolve<BaseDataProviderManager>().LoadDataProvider());

            if(dataProviderSettings != null && dataProviderSettings.IsValid()) {
                var efDataProviderManager = new EfDataProviderManager(dataSettingsManager.LoadSettings());
                var dataProvider = efDataProviderManager.LoadDataProvider();
                dataProvider.InitConnectionFactory();

                x.Bind<IDbContext>(c => new NopObjectContext(dataProviderSettings.DataConnectionString, false, false));
            }
            else {
                x.Bind<IDbContext>(c => new NopObjectContext(dataSettingsManager.LoadSettings().DataConnectionString, false, false));
            }

            x.BindGeneric(typeof(IRepository<>), typeof(EfRepository<>));



            //all entities taken from the db should be auto cached, 


            var controllerTypes = scanner.ScanTypes(typeof(Registrar).Assembly)
                                            .Where(t => !t.IsAbstract
                                                        && typeof(IController).IsAssignableFrom(t));

            foreach(var type in controllerTypes) {
                x.Bind(type, type);
            }

        }
 public void Bind(IBinder binder)
 {
     binder.Bind<IProductService,ProductService>();
        binder.Bind<INavigationService, NavigationService>();
        binder.Bind<ICartService, CartService>();
 }