public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] UserLocation userLocation,
            ILogger log,
            ExecutionContext context)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            var container    = ContainerHelper.Build(context);
            var locationRepo = (ICurrentLocationRepository)container.GetService(typeof(ICurrentLocationRepository));
            var mapsRepo     = (IAzureMapsRepository)container.GetService(typeof(IAzureMapsRepository));

            var assistantsDTO = await locationRepo.GetUsers(UserType.CareRecipient);

            var assistantsLocations = assistantsDTO.Select(t => t.ToUserLocation());
            var closestUserIds      = await mapsRepo.GetClosestUserIds(assistantsLocations, userLocation);

            var requestObject = new RequestHelpPushNotification()
            {
                SourceDeviceId  = userLocation.UserId.ToString(),
                TargetDeviceIds = closestUserIds.ToArray(),
                Type            = "RequestNearbyHelp",
            };

            var nextBodySerialized = JsonConvert.SerializeObject(requestObject);

            var(nextStatus, nextResponseMessage) = await HttpClientHelper.PostAsync(requestHelpPushUrl, nextBodySerialized);

            if (nextStatus == System.Net.HttpStatusCode.OK ||
                nextStatus == System.Net.HttpStatusCode.Created ||
                nextStatus == System.Net.HttpStatusCode.Accepted)
            {
                return((ActionResult) new OkObjectResult($"Successfully triggered the next step. Push Notifications. Body used : {nextBodySerialized}"));
            }

            return((ActionResult) new BadRequestObjectResult($"Failed to trigger the next step. Push Notifications. Body used : {nextBodySerialized}"));
        }
    public static async System.Threading.Tasks.Task RunAsync(
        [EventHubTrigger("stegawiothub", Connection = "EventHubConnStr", ConsumerGroup = "azurefunctionsconsumergroup")] EventData eventHubMessage,
        DateTime enqueuedTimeUtc,
        Int64 sequenceNumber,
        string offset,
        ILogger log,
        ExecutionContext context)
    {
        log.LogInformation($"Event: {Encoding.UTF8.GetString(eventHubMessage.Body)}");
        // Metadata accessed by binding to EventData
        log.LogInformation($"EnqueuedTimeUtc={eventHubMessage.SystemProperties.EnqueuedTimeUtc}");
        log.LogInformation($"SequenceNumber={eventHubMessage.SystemProperties.SequenceNumber}");
        log.LogInformation($"Offset={eventHubMessage.SystemProperties.Offset}");
        // Metadata accessed by using binding expressions in method parameters
        log.LogInformation($"EnqueuedTimeUtc={enqueuedTimeUtc}");
        log.LogInformation($"SequenceNumber={sequenceNumber}");
        log.LogInformation($"Offset={offset}");

        var container    = ContainerHelper.Build(context);
        var repo         = (ICurrentLocationRepository)container.GetService(typeof(ICurrentLocationRepository));
        var userLocation = JsonConvert.DeserializeObject <UserLocation>(Encoding.UTF8.GetString(eventHubMessage.Body));
        var res          = await repo.SaveLocationAsync(userLocation);

        if (res)
        {
            log.LogInformation($"Successfully stored location. User: {userLocation.UserId}. Lat: {userLocation.Location.gpsLat}. Long: {userLocation.Location.gpsLong}.");
        }
        else
        {
            log.LogError($"Failed to save user location.");
        }
    }
        /// <summary>
        /// Loads the list of DataHelpers found in the form.
        /// </summary>
        private void LoadListOfDataHelpers()
        {
            int index = 0;

            try
            {
                DHComboBox.Items.Clear();
                Control ctrl = (Control)context.Instance;

                foreach (Control childCtrl in ContainerHelper.Controls(ctrl.FindForm()))
                {
                    if (childCtrl is DataHelper)
                    {
                        index = DHComboBox.Items.Add(childCtrl);
                        if ((_dataHelperBindingInfo != null) && (_dataHelperBindingInfo.BindingControl != null) &&
                            (_dataHelperBindingInfo.BindingControl.Equals(childCtrl)))
                        {
                            DHComboBox.SelectedIndex = index;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
Exemple #4
0
        /// <summary>
        /// Remove the event handlers for a control (Disable).
        /// </summary>
        /// <param name="ctrl">The control.</param>
        /// <param name="eventName">The event name.</param>
        static internal void DisableControlEvents(Control ctrl, string eventName)
        {
            Delegate[] _eventDelegates = ContainerHelper.GetEventSubscribers(ctrl, eventName);

            if (_eventDelegates != null)
            {
                EventInfo eventInfo = ctrl.GetType().GetEvent(eventName);
                if (eventInfo != null)
                {
                    if (!_eventsDisabled.ContainsKey(ctrl))
                    {
                        _eventsDisabled.Add(ctrl, new Dictionary <string, List <Delegate> >());
                    }

                    if (!_eventsDisabled[ctrl].ContainsKey(eventName))
                    {
                        _eventsDisabled[ctrl].Add(eventName, new List <Delegate>());
                    }

                    foreach (Delegate del in _eventDelegates)
                    {
                        _eventsDisabled[ctrl][eventName].Add(del);
                        eventInfo.RemoveEventHandler(ctrl, del);
                    }
                }
            }
        }
            protected override void Arrange()
            {
                var container = ContainerHelper.CreateContainer(new Options());

                _assemblyDataProvider = container.Resolve <IEnumerable <IAssemblyDataProvider> >()
                                        .Single(x => x is AssemblyDataProvider);
            }
 private static void ListContainers(ContainerHelper containerHelper)
 {
     foreach (var container in containerHelper.Containers)
     {
         Console.WriteLine($"Account Name: {container.Value.AccountName}, Container Name: {container.Value.Name}");
     }
 }
        public ContainerizeFileTask(string filePath, ContainerizationSettingsModel settingsModel) : base(ResourceType.File, filePath)
        {
            InnerTask = new Task(() =>
            {
                if (Path.GetExtension(filePath).Equals(settingsModel.Extension))
                {
                    return;
                }

                ContainerHelper.ContainerizeFile(filePath, AesHelper.GetNewAesKey(), settingsModel.Password);
                var newPath = FileGeneratorHelper.GetValidFileNameForDirectory(
                    DirectoryHelper.GetDirectoryPath(filePath),
                    Path.GetFileNameWithoutExtension(filePath),
                    settingsModel.Extension);

                File.Move(filePath, newPath);

                Result.Value = new FileModel
                {
                    File    = Path.GetFileName(filePath),
                    Time    = DateTime.Now,
                    Secured = newPath
                };
            });
        }
        private static void ListBlobs(ContainerHelper containerHelper)
        {
            string containerName;

            ListContainers(containerHelper);
            Console.Write("Enter the container name you want to list the blob in: ");
            containerName = Console.ReadLine();
            if (containerHelper.ContainerExists(containerName))
            {
                var blobs = containerHelper.GetBlobs(containerName);
                Console.WriteLine();
                if (blobs?.Count() == 0)
                {
                    Console.WriteLine("Container is empty");
                }
                else
                {
                    foreach (var blob in blobs)
                    {
                        Console.WriteLine($"Name: {blob.Name}, Type: {blob.Properties.BlobType}, Tier: {blob.Properties.AccessTier}, Size: {blob.Properties.ContentLength} Bytes");
                    }
                }
            }
            else
            {
                Console.WriteLine($"No container is named {containerName}");
            }
        }
Exemple #9
0
        /// <summary>
        /// Creates a copy of the baseControl.
        /// </summary>
        /// <param name="baseControl">The base control to use as template.</param>
        /// <returns>A copy or null.</returns>
        private static Object CloneObject(Object baseControl)
        {
            Object result = null;

            if (baseControl != null)
            {
                ICloneable control = baseControl as ICloneable;
                if (control != null)
                {
                    result = control.Clone();
                }
                else
                {
                    result = Activator.CreateInstance(baseControl.GetType());
                    Dictionary <string, object> listOfProperties = GetPropertiesToCopy(baseControl);
                    foreach (PropertyInfo propertyInfo in baseControl.GetType().GetProperties())
                    {
                        if (propertyInfo.Name.Equals("Name", StringComparison.CurrentCultureIgnoreCase))
                        {
                            propertyInfo.SetValue(result, "DinamicallyLoadedControl", null);
                        }
                        else if (listOfProperties.ContainsKey(propertyInfo.Name))
                        {
                            try
                            {
                                propertyInfo.SetValue(result, listOfProperties[propertyInfo.Name], null);
                            }
                            catch (Exception e)
                            {
                                Trace.TraceError("CloneObject {0}", e.Message);
                            }
                        }
                    }
                }
                AddCloneToContainer(baseControl, result);

                DoExtraBindings(baseControl, result);
                //Bind the same events set in the base control to the new control
                foreach (EventInfo eventInfo in baseControl.GetType().GetEvents())
                {
                    Delegate[] eventDelegates = ContainerHelper.GetEventSubscribers(baseControl, eventInfo.Name);
                    //The event in the new control will be bound to the same delegates of the base control
                    if (eventDelegates != null)
                    {
                        foreach (Delegate del in eventDelegates)
                        {
                            try
                            {
                                eventInfo.AddEventHandler(result, del);
                            }
                            catch (Exception e)
                            {
                                Trace.TraceError("CloneObject {0}", e.Message);
                            }
                        }
                    }
                }
            }
            return(result);
        }
Exemple #10
0
            public void Should_throw_error()
            {
                _container = ContainerHelper.CreateContainer();

                // Arrange
                _templateWriterData = new TemplateWriterData
                {
                    Model = new
                    {
                        NamespaceName = namespaceName,
                        ClassName     = "testClass",
                        InterfaceName = "testInterfaceName"
                    },
                    TemplateSet = new TemplateSet {
                        Name = templateName
                    },
                    OutputPath = $"{Environment.CurrentDirectory}\\Output.cs"
                };

                // Act
                var exception = Assert.ThrowsAsync <KeyNotFoundException>(
                    async() => await _container.Resolve <ITemplateWriter>()
                    .WriteAsync(_templateWriterData, CancellationToken.None));

                // Assert
                exception.Message.ShouldMatch($"The given key '{templateName}' was not present in the dictionary.");
            }
Exemple #11
0
        private static void RegisterContainer()
        {
            var builder = ContainerHelper.ObterContainerBuilder();

            #region Controllers

            // Registra os controllers no container pelo seu próprio tipo concreto
            // Registrando no container os controllers
            var controllers = typeof(HomeController).Assembly;

            builder.RegisterAssemblyTypes(controllers)
            .Where(t => t.Namespace == "Web.Controllers")
            .AsSelf();

            #endregion

            builder.RegisterFilterProvider();

            var container = builder.Build();
            container.Resolve <ISessionFactory>();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            HttpContext.Current.Application["DependencyResolver"] = DependencyResolver.Current;
        }
        private void AddCommandExecute()
        {
            var cityRepository = ContainerHelper.Container.Resolve <ICityRepository>();
            var cityInstance   = cityRepository.GetCityByName(CityName);


            if (cityInstance == null)
            {
                MessageBox.Show("Incorect City", "Error", MessageBoxButton.OK);
                return;
            }

            cityInstance.ForecastInfo = cityRepository.GetCityForecastByName(CityName).Forecast;

            if (cityInstance.ForecastInfo == null)
            {
                MessageBox.Show("Incorect City", "Error", MessageBoxButton.OK);
                return;
            }

            var cityWeatherControlViewModel = ContainerHelper.Resolve <ICityWeatherControlViewModel>(new
            {
                city = cityInstance,
                mainWindowViewModel = _mainWindowViewModel
            });

            _mainWindowViewModel.ViewModels.Add(cityWeatherControlViewModel as ViewModelBase);
            _mainWindowViewModel.ViewModels.Remove(this);
            _mainWindowViewModel.AddButtonVisibility = Visibility.Visible;
        }
 public void GetItemCacheKeyTest()
 {
     //var obj = new TestContainerBag1() as IBaseContainerBag;//使用接口或基类
     var shortKey = "abc123";
     var result = ContainerHelper.GetItemCacheKey(typeof(TestContainerBag1),shortKey);
     Assert.AreEqual("Container:Senparc.Weixin.Containers.Tests.TestContainerBag1:" + shortKey, result);
 }
Exemple #14
0
        private void AddCommandExecute()
        {
            AddButtonVisibility = Visibility.Hidden;
            var addCityControlViewModelBase = ContainerHelper.Resolve <IAddCityControlViewModel>(new { mainWindowViewModel = this }) as ViewModelBase;

            ViewModels.Add(addCityControlViewModelBase);
        }
        /// <summary>
        /// Patches the events for a specific treeview.
        /// </summary>
        /// <param name="treeView">The TreeView.</param>
        private static void CorrectEventsForTreeView(TreeView treeView)
        {
            if (EventsPatched.ContainsKey(treeView))
            {
                throw new InvalidOperationException("Events for this TreeView has been previously patched: '" + treeView.Name + "'");
            }

            EventsPatched.Add(treeView, new Dictionary <string, List <Delegate> >());
            foreach (string eventName in EventsToCorrect.Keys)
            {
                EventInfo eventInfo = treeView.GetType().GetEvent(eventName);
                if (eventInfo == null)
                {
                    throw new InvalidOperationException("Event info for event '" + eventName + "' could not be found");
                }

                EventsPatched[treeView].Add(eventName, new List <Delegate>());
                Delegate[] eventDelegates = ContainerHelper.GetEventSubscribers(treeView, eventName);
                if (eventDelegates != null)
                {
                    foreach (Delegate del in eventDelegates)
                    {
                        EventsPatched[treeView][eventName].Add(del);
                        eventInfo.RemoveEventHandler(treeView, del);
                    }
                }
                eventInfo.AddEventHandler(treeView, EventsToCorrect[eventName]);
            }
        }
Exemple #16
0
        /// <summary>
        /// Patches the events for a specific button.
        /// </summary>
        /// <param name="btn"></param>
        private static void CorretEventsForButton(Button btn)
        {
            Delegate[] EventDelegates = null;

            if (EventsPatched.ContainsKey(btn))
            {
                throw new InvalidOperationException("Events for this button has been previously patched: '" + btn.Name + "'");
            }

            EventsPatched.Add(btn, new Dictionary <string, List <Delegate> >());
            foreach (string eventName in EventsToCorrect.Keys)
            {
                EventInfo eInfo = btn.GetType().GetEvent(eventName);
                if (eInfo == null)
                {
                    throw new InvalidOperationException("Event info for event '" + eventName + "' could not be found");
                }

                EventsPatched[btn].Add(eventName, new List <Delegate>());
                EventDelegates = ContainerHelper.GetEventSubscribers(btn, eventName);
                if (EventDelegates != null)
                {
                    foreach (Delegate del in EventDelegates)
                    {
                        EventsPatched[btn][eventName].Add(del);
                        eInfo.RemoveEventHandler(btn, del);
                    }
                }
                eInfo.AddEventHandler(btn, EventsToCorrect[eventName]);
            }
        }
Exemple #17
0
        public void SetUp()
        {
            _fileSystem = new MockFileSystem(new Dictionary <string, MockFileData>
            {
                { @"C:\build\MySolution.sln", new MockFileData(string.Empty) }
            });

            _repositoryReader = new Mock <IRepositoryReader>();
            _analyzer         = new Mock <IMSBuildSolutionAnalyzer>();
            var container = ContainerHelper.ConfigureContainer()
                            .WithRegistrations(c =>
            {
                c.RegisterInstance <IFileSystem>(_fileSystem);
                c.RegisterInstance(_repositoryReader.Object);
                c.RegisterInstance(_analyzer.Object);
            })
                            .Build();

            _args = new string[]
            {
                "--solution", @"C:\build\MySolution.sln",
                "--from-commit", "commit"
            };
            _command = container.Resolve <ArbiterRootCommand>();
            _console = container.Resolve <IConsole>();
        }
Exemple #18
0
        public void ModuleManagerRunCalled()
        {
            // Have to use a non-mocked container because of IsRegistered<> extension method, Registrations property,and ContainerRegistration
            var mockedModuleInitializer = new Mock <IModuleInitializer>();
            var mockedModuleManager     = new Mock <IModuleManager>();
            var regionAdapterMappings   = new RegionAdapterMappings();
            var container             = ContainerHelper.CreateContainerExtension();
            var regionBehaviorFactory = new RegionBehaviorFactory(container);

            container.RegisterInstance <IContainerExtension>(container);
            container.RegisterInstance <IModuleCatalog>(new ModuleCatalog());
            container.RegisterInstance <IModuleInitializer>(mockedModuleInitializer.Object);
            container.RegisterInstance <IModuleManager>(mockedModuleManager.Object);
            container.RegisterInstance <RegionAdapterMappings>(regionAdapterMappings);

            container.RegisterSingleton(typeof(RegionAdapterMappings), typeof(RegionAdapterMappings));
            container.RegisterSingleton(typeof(IRegionManager), typeof(RegionManager));
            container.RegisterSingleton(typeof(IEventAggregator), typeof(EventAggregator));
            container.RegisterSingleton(typeof(IRegionViewRegistry), typeof(RegionViewRegistry));
            container.RegisterSingleton(typeof(IRegionBehaviorFactory), typeof(RegionBehaviorFactory));
            container.RegisterSingleton(typeof(IRegionNavigationJournalEntry), typeof(RegionNavigationJournalEntry));
            container.RegisterSingleton(typeof(IRegionNavigationJournal), typeof(RegionNavigationJournal));
            container.RegisterSingleton(typeof(IRegionNavigationService), typeof(RegionNavigationService));
            container.RegisterSingleton(typeof(IRegionNavigationContentLoader), typeof(RegionNavigationContentLoader));

            container.RegisterInstance <SelectorRegionAdapter>(new SelectorRegionAdapter(regionBehaviorFactory));
            container.RegisterInstance <ItemsControlRegionAdapter>(new ItemsControlRegionAdapter(regionBehaviorFactory));
            container.RegisterInstance <ContentControlRegionAdapter>(new ContentControlRegionAdapter(regionBehaviorFactory));

            var bootstrapper = new MockedContainerBootstrapper(container.GetBaseContainer());

            bootstrapper.Run(false);

            mockedModuleManager.Verify(mm => mm.Run(), Times.Once());
        }
 public void GetCacheKeyNamespaceTest()
 {
     var obj = new TestContainerBag1() as IBaseContainerBag;//使用接口或基类
     var result = ContainerHelper.GetCacheKeyNamespace(obj.GetType());
     Console.WriteLine(result);
     Assert.AreEqual("Container:Senparc.Weixin.Containers.Tests.TestContainerBag1", result);
 }
Exemple #20
0
 //出队
 public static void OutQueue(Timer timer)
 {
     LogHelper.WriteInfo("当前出队时间:" + DateTime.Now.ToString("yyyyMMdd hh:mm:ss"));
     timer.Stop();
     try
     {
         while (!PrduQueue.IsEmpty)
         {
             PrduQueue.TryDequeue(out KiaserTask kiaser);
             //写入学校表
             var container = ContainerHelper.GetContainer();
             var manager   = container.Resolve <ISchooBLL>();//通过resolve方法取得对象
             var model     = new EIC_School
             {
                 ID         = Guid.NewGuid().ToString(),
                 SchoolCode = kiaser.SchoolCode,
                 SchoolName = kiaser.SchoolName
             };
             var kiasers = manager.Add(model);
         }
     }
     catch (Exception ex)
     {
         LogHelper.WriteError(ex.Message);
     }
     timer.Start();
 }
        public DialogEditChannelViewModel()
        {
            this.useHoldingBay = true;

            _holdingBay = ContainerHelper.GetService <IHoldingBay>();

            NewYtChannel = (YTChannel)_holdingBay.GetEntry("CHANNEL_NEW", false); // do not remove object from our repo
        }
Exemple #22
0
        public PlayerView()
        {
            _eventBus = ContainerHelper.GetService <IEventBus>();

            _eventBus.SubscribeEvent("VideoIdChanged", VideoIdChangedHandler);

            InitializeComponent();
        }
Exemple #23
0
        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnQuery_Click(object sender, EventArgs e)
        {
            var Builder = ContainerHelper.GetContainer();
            var manager = Builder.Resolve <ISchooBLL>();//通过resolve方法取得对象
            var temp    = manager.GetOneDataById("a6409499-a5d7-4108-96ad-15ff2a2f884a");

            MessageBox.Show(temp.SchoolName);
        }
Exemple #24
0
        //查询一笔学生数据
        public static string GetOneDataById()
        {
            var Builder = ContainerHelper.GetContainer();
            var manager = Builder.Resolve <ISchooBLL>();//通过resolve方法取得对象
            var temp    = manager.GetOneDataById("a6409499-a5d7-4108-96ad-15ff2a2f884a");

            return(temp.SchoolName);
        }
Exemple #25
0
        public async Task CanPullImage()
        {
            var sut = new ContainerHelper();

            Action <string> write = (s) => Console.WriteLine(s);

            await sut.PullImage(@"shawnseabrook/build:20", write, write, write);
        }
Exemple #26
0
        private void button1_Click(object sender, EventArgs e)
        {
            var Builder = ContainerHelper.GetContainer();
            var manager = Builder.Resolve <ISchooBLL>();//通过resolve方法取得对象
            var temp    = manager.MySelf();

            MessageBox.Show(temp.ToString());
        }
Exemple #27
0
        private static void RegisterContainer()
        {
            var builder = ContainerHelper.ObterContainerBuilder();

            RegisterWebAssembly(builder);
            builder.RegisterFilterProvider();
            SetupAutofacDependencyResolver(ContainerHelper.ResolveSectionFactory(builder));
        }
        private void ShowForecastForSelectedDayCommandExecute()
        {
            var dataContext = ContainerHelper.Resolve <IHourlyForecastForSelectedDayViewModel>();

            _dailyForecast.ForEach(r =>
                                   dataContext.HourlyForecast.Add(
                                       ContainerHelper.Resolve <IHourlyForecastControlViewModel>(new { forecast = r })));
            _dialogManager.ShowHourlyForecastDialog(dataContext, Date);
        }
Exemple #29
0
        /// <summary>
        /// 注册容器组件
        /// </summary>
        /// <param name="containerBuilder"></param>
        public static void RegisterContainerHelper(ContainerBuilder containerBuilder)
        {
            //注册组件--------------------------------
            var container = containerBuilder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); //注册到mvc DI容器中以获取到每请求缓存的实例

            ContainerHelper.RegisterContainer(container);
        }
        public void SetUp()
        {
            var container = ContainerHelper.ConfigureContainer().Build();

            _command = container.Resolve <CleanCommand>();
            _locator = container.Resolve <IMSBuildLocator>();

            _locator.RegisterDefaults();
        }