ApplicationContext

Namespace: Sitko.Core.App
We found 10 examples in language CSharp for this search. You will see 59 fragments of code.
    public static void AddCPUCodeName(CPU_codename _codeName, bool _option)
    {
      try
      {
        if(Warning(_option, _codeName.Name))
        {
          using (ApplicationContext db = new ApplicationContext())
          {
            db.CPU_codename.Add(_codeName);
            db.SaveChanges();
            MessageBox.Show("Добавление прошло успешно!");
          }
        }
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.Message);
      }
    }

    public static void AddSocket(Sockets _socket, bool _options)
    {
      try
      {
        if(Warning(_options, _socket.Name))
        {
          using (ApplicationContext db = new ApplicationContext())
          {
            db.Sockets.Add(_socket);
            db.SaveChanges();
            MessageBox.Show("Добавление прошло успешно!");
          }
        }
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.Message);
      }
    }

    public static void AddChipset(Chipset _chipset, bool _option)
    {
      try
      {
        if(Warning(_option, _chipset.Name))
        {
          using(ApplicationContext db = new ApplicationContext())
          {
            db.Chipset.Add(_chipset);
            db.SaveChanges();
            MessageBox.Show("Добавление прошло успешно!");
          }
        }
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.Message);
      }
    }

    public static void AddChanel(RAM_chanels _chanel, bool _option)
    {
      try
      {
        if (Warning(_option, _chanel.Name))
        {
          using (ApplicationContext db = new ApplicationContext())
          {
            db.RAM_chanels.Add(_chanel);
            db.SaveChanges();
            MessageBox.Show("Добавление прошло успешно!");
          }
        }
      }
      catch(Exception ex)
      {
        MessageBox.Show(ex.Message);
      }
    }
    public static void AddFormFactor(Form_factors _formFactor, bool _option)
    {
      try
      {
        if (Warning(_option, _formFactor.Name))
        {
          using (ApplicationContext db = new ApplicationContext())
          {
            db.Form_factors.Add(_formFactor);
            db.SaveChanges();
            MessageBox.Show("Добавление прошло успешно!");
          }
        }
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.Message);
      }
    }
    public static void AddMemoryType(Memory_types _type, bool _option)
    {
      try
      { 
        if (Warning(_option, _type.Name))
        {
          using (ApplicationContext db = new ApplicationContext())
          {
            db.Memory_types.Add(_type);
            db.SaveChanges();
            MessageBox.Show("Добавление прошло успешно!");
          }
        }
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.Message);
      }
    }


        [HttpPost]
        [Route("add")]
        public IActionResult Add(Todo todo)
        {
            applicationContext.Add(todo);
            applicationContext.SaveChanges();
            return Redirect("list");
        }

        [HttpGet]
        [Route("{id}/delete")]
        public IActionResult Delete([FromRoute] long Id)
        {
            Todo deletedTodo = applicationContext.Todos.FirstOrDefault(t => t.Id == Id);
            applicationContext.Remove(deletedTodo);
            applicationContext.SaveChanges();
            return RedirectToAction("List");
        }

        [HttpDelete]
        [Route("{id}/delete")]
        public IActionResult DeleteWithPostman([FromRoute] long Id)
        {
            Todo deletedTodo = applicationContext.Todos.FirstOrDefault(t => t.Id == Id);
            applicationContext.Remove(deletedTodo);
            applicationContext.SaveChanges();
            return Ok();
        }

        [HttpGet]
        [Route("{id}/update")]
        public IActionResult GetUpdatePage([FromRoute] long Id)
        {
            Todo editableTodo = applicationContext.Todos.FirstOrDefault(t => t.Id == Id);
            ViewData["assignees"] = applicationContext.Assignees.ToList();
            return View("Update", editableTodo);
        }

        [HttpPost]
        [Route("{id}/update")]
        public IActionResult Update(long assigneeId, Todo todo)
        {
            if (assigneeId != 0)
            {
                todo.Assignee = (applicationContext.Assignees.Find(assigneeId));
            }
            applicationContext.Update(todo);
            applicationContext.SaveChanges();
            return RedirectToAction("List");
        }

        [HttpPut]
        [Route("{id}/update")]
        public IActionResult UpdateWithPostman([FromRoute]long id,Todo todo)
        {
            todo.Id = id;
            applicationContext.Update(todo);
            applicationContext.SaveChanges();
            return RedirectToAction("List");
        }


        [HttpGet]
        [Route("")]
        [Route("list")]
        public IActionResult List()
        {
            // Create a SQL query in the background
            var assignees = applicationContext.Assignees.ToList();
            
            return View(assignees);
        }

        [HttpPost]
        [Route("add")]
        public IActionResult Add(Assignee assignee)
        {
            applicationContext.Add(assignee);
            applicationContext.SaveChanges();
            return Redirect("list");
        }

        [HttpGet]
        [Route("{id}/todos")]
        public IActionResult ListTodos([FromRoute] long Id)
        {
            Assignee assignee = applicationContext.Assignees.Include(a => a.Todos).FirstOrDefault(a => a.Id == Id);
            List<Todo> todos = assignee.Todos;
            return View("Todos", todos);
        }

        [HttpGet]
        [Route("api/{id}/todos")]
        public Object ListTodosJson([FromRoute] long Id)
        {
            List<Todo> todos = applicationContext.Assignees.FirstOrDefault(a => a.Id == Id).Todos;
            return todos;
        }

        [HttpGet]
        [Route("{id}/delete")]
        public IActionResult Delete([FromRoute] long Id)
        {
            Todo deletedTodo = applicationContext.Todos.FirstOrDefault(t => t.Id == Id);
            applicationContext.Remove(deletedTodo);
            applicationContext.SaveChanges();
            return RedirectToAction("List");
        }

        [HttpDelete]
        [Route("{id}/delete")]
        public IActionResult DeleteWithPostman([FromRoute] long Id)
        {
            Todo deletedTodo = applicationContext.Todos.FirstOrDefault(t => t.Id == Id);
            applicationContext.Remove(deletedTodo);
            applicationContext.SaveChanges();
            return Ok();
        }


        [HttpPost]
        [Route("add")]
        public IActionResult Add(Todo todo)
        {
            applicationContext.Add(todo);
            applicationContext.SaveChanges();
            return Redirect("list");
        }

        [HttpGet]
        [Route("{id}/delete")]
        public IActionResult Delete([FromRoute] long Id)
        {
            Todo deletedTodo = applicationContext.Todos.FirstOrDefault(t => t.Id == Id);
            applicationContext.Remove(deletedTodo);
            applicationContext.SaveChanges();
            return RedirectToAction("List");
        }

        [HttpDelete]
        [Route("{id}/delete")]
        public IActionResult DeleteWithPostman([FromRoute] long Id)
        {
            Todo deletedTodo = applicationContext.Todos.FirstOrDefault(t => t.Id == Id);
            applicationContext.Remove(deletedTodo);
            applicationContext.SaveChanges();
            return Ok();
        }

        [HttpGet]
        [Route("{id}/update")]
        public IActionResult GetUpdatePage([FromRoute] long Id)
        {
            Todo editableTodo = applicationContext.Todos.FirstOrDefault(t => t.Id == Id);
            return View("Update", editableTodo);
        }

        [HttpPost]
        [Route("{id}/update")]
        public IActionResult Update(Todo todo)
        {
            applicationContext.Update(todo);
            applicationContext.SaveChanges();
            return RedirectToAction("List");
        }

        [HttpPut]
        [Route("{id}/update")]
        public IActionResult UpdateWithPostman([FromRoute]long id,Todo todo)
        {
            todo.Id = id;
            applicationContext.Update(todo);
            applicationContext.SaveChanges();
            return RedirectToAction("List");
        }

        [TestMethod]
        public void SimpleTest()
        {
            int expectedValue = 5;
            ApplicationContext context = new ApplicationContext();
            context.Resolvers.Add(Resolver.CreateSingleton(expectedValue));
            int actualValue = context.Resolve<int>();
            Assert.AreEqual(expectedValue, actualValue);
        }

        [TestMethod]
        public void SingletonTest()
        {
            ApplicationContext context = new ApplicationContext();
            context.Resolvers.Add(Resolver.CreateSingleton(new object()));
            object first = context.Resolve<object>();
            object second = context.Resolve<object>();
            Assert.AreSame(first, second);
        }

        [TestMethod]
        public void PrototypeTest()
        {
            ApplicationContext context = new ApplicationContext();
            context.Resolvers.Add(Resolver.Create(new Func<object>(() => new object()), Scope.Prototype));
            object first = context.Resolve<object>();
            object second = context.Resolve<object>();
            Assert.AreNotSame(first, second);
        }

        [TestMethod]
        public void DependencyTest()
        {
            ApplicationContext context = new ApplicationContext();
            context.Resolvers.Add(Resolver.Create(new Func<int, double>((a) => 10.1)));
            context.Resolvers.Add(Resolver.Create(new Func<int>(() => 5)));
            double value = context.Resolve<double>();
            Assert.AreEqual(10.1, value);
        }

        [TestMethod]
        public void ResolveAllTest()
        {
            ApplicationContext context = new ApplicationContext();
            context.Resolvers.Add(Resolver.Create(new Func<int>(() => 10)));
            context.Resolvers.Add(Resolver.Create(new Func<int>(() => 5)));
            List<int> values = context.ResolveAll<int>();
            Assert.IsTrue(values.Contains(10));
            Assert.IsTrue(values.Contains(5));
        }

        [TestMethod]
        public void ResolveAllWithListTypeTest()
        {
            ApplicationContext context = new ApplicationContext();
            context.Resolvers.Add(Resolver.Create(new Func<int>(() => 10)));
            context.Resolvers.Add(Resolver.Create(new Func<int>(() => 5)));
            List<int> values = context.Resolve<List<int>>();
            Assert.IsTrue(values.Contains(10));
            Assert.IsTrue(values.Contains(5));
        }


        public List<User> findAll()
        {
            using (ApplicationContext db = new ApplicationContext())
            {
                return db.Users.ToList();
            }
        }

        public User findById(int id)
        {
            using (ApplicationContext db = new ApplicationContext())
            {
                return db.Users
                    .Where(user => user.Id == id)
                    .FirstOrDefault();
            }
        }

        public List<User> findByName(String name)
        {
            using (ApplicationContext db = new ApplicationContext())
            {
                return db.Users
                .Where(user => user.Name == name)
                .ToList();
            }
        }

        public List<User> findByAge(int age)
        {
            using (ApplicationContext db = new ApplicationContext())
            {
                return db.Users
                .Where(user => user.Age == age)
                .ToList();
            }
        }

        public List<User> findByAgeInRange(int fromAge, int toAge)
        {
            using (ApplicationContext db = new ApplicationContext())
            {
                return db.Users
                .Where(user => user.Age >= fromAge && user.Age <= toAge)
                .ToList();
            }
        }

        public User addUser(User user)
        {
            using(ApplicationContext db = new ApplicationContext())
            {
                db.Users.Add(user);
                db.SaveChanges();
                return user;
            }
        }


        public async Task AddTodo(string title, string username)
        {
            if (title != null)
            {
                var user = await userService.FindByUsername(username);
                var newTodo = new Todo {Title = title, IsDone = false, UserId = user.UserId};
                applicationContext.Todos.Add(newTodo);
                await applicationContext.SaveChangesAsync();


            }
        }

        public async Task DeleteTodo(int id)
        {
            var todo = await FindTodoById(id);
            if (todo != null)
            {
                applicationContext.Todos.Remove(todo);
                await applicationContext.SaveChangesAsync();
            }
        }

        public async Task<Todo> FindTodoById(int id)
        {
            var todo = await applicationContext.Todos.FirstOrDefaultAsync(a => a.TodoId == id);
            if (todo == null)
            {
                return null;
            }

            return todo;
        }

        public async Task EditTodo(int id, string title)
        {
            var todo = await FindTodoById(id);
            if (todo != null)
            {
                todo.Title = title;
                await applicationContext.SaveChangesAsync();
            }
        }

        public async Task CompleteTodo(int id)
        {
            var todo = await FindTodoById(id);
            if (todo != null)
            {
                todo.IsDone = true;
                await applicationContext.SaveChangesAsync();
            }
        }

        [TestMethod]
        public void SimpleTest()
        {
            int expectedValue = 5;
            ApplicationContext context = new ApplicationContext();
            context.Resolvers.Add(Resolver.CreateSingleton(expectedValue));
            int actualValue = context.Resolve<int>();
            Assert.AreEqual(expectedValue, actualValue);
        }

        [TestMethod]
        public void SingletonTest()
        {
            ApplicationContext context = new ApplicationContext();
            context.Resolvers.Add(Resolver.CreateSingleton(new object()));
            object first = context.Resolve<object>();
            object second = context.Resolve<object>();
            Assert.AreSame(first, second);
        }

        [TestMethod]
        public void PrototypeTest()
        {
            ApplicationContext context = new ApplicationContext();
            context.Resolvers.Add(Resolver.Create(new Func<object>(() => new object()), Scope.Prototype));
            object first = context.Resolve<object>();
            object second = context.Resolve<object>();
            Assert.AreNotSame(first, second);
        }

        [TestMethod]
        public void DependencyTest()
        {
            ApplicationContext context = new ApplicationContext();
            context.Resolvers.Add(Resolver.Create(new Func<int, double>((a) => 10.1)));
            context.Resolvers.Add(Resolver.Create(new Func<int>(() => 5)));
            double value = context.Resolve<double>();
            Assert.AreEqual(10.1, value);
        }

        [TestMethod]
        public void ResolveAllTest()
        {
            ApplicationContext context = new ApplicationContext();
            context.Resolvers.Add(Resolver.Create(new Func<int>(() => 10)));
            context.Resolvers.Add(Resolver.Create(new Func<int>(() => 5)));
            List<int> values = context.ResolveAll<int>();
            Assert.IsTrue(values.Contains(10));
            Assert.IsTrue(values.Contains(5));
        }

        [TestMethod]
        public void ResolveAllSubclassTest()
        {
            ApplicationContext context = new ApplicationContext();
            context.Resolvers.Add(Resolver.Create(new Func<A>(() => new A())));
            context.Resolvers.Add(Resolver.Create(new Func<B>(() => new B())));
            context.Resolvers.Add(Resolver.Create(new Func<C>(() => new C())));
            List<A> aValues = context.ResolveAll<A>();
            List<B> bValues = context.ResolveAll<B>();
            List<I> iValues = context.ResolveAll<I>();
            Assert.AreEqual(2, aValues.Count);
            Assert.AreEqual(1, bValues.Count);
            Assert.AreEqual(3, iValues.Count);
        }


        public void WithInterceptor(IConsumerInterceptor interceptor)
        {
            applicationContext.ObjectFactory.AddObjectPostProcessor(new ConsumerInterceptor(interceptor, applicationContext));
        }

        public void RegisterDefaultServices(IEnumerable<Assembly> assemblies)
        {
            applicationContext.RegisterSingleton<IServiceLocator>(() => new SpringServiceLocator(applicationContext));
            foreach (var assembly in assemblies)
                applicationContext.RegisterSingletons<IBusConfigurationAware>(assembly);

            var locator = applicationContext.Get<IServiceLocator>();
            foreach (var busConfigurationAware in applicationContext.GetAll<IBusConfigurationAware>())
                busConfigurationAware.Configure(config, this, locator);

            foreach (var module in config.MessageModules)
                applicationContext.RegisterSingleton(module, module.FullName);

            applicationContext.RegisterSingleton<IReflection>(() => new SpringReflection());
            applicationContext.RegisterSingleton(config.SerializerType);
            applicationContext.RegisterSingleton<IEndpointRouter>(() => new EndpointRouter());
        }

        public void RegisterBus()
        {
            var busConfig = (RhinoServiceBusConfiguration)config;

            applicationContext.RegisterSingleton<IStartableServiceBus>(() => new DefaultServiceBus(applicationContext.Get<IServiceLocator>(),
                                                   applicationContext.Get<ITransport>(),
                                                   applicationContext.Get<ISubscriptionStorage>(),
                                                   applicationContext.Get<IReflection>(),
                                                   applicationContext.GetAll<IMessageModule>().ToArray(),
                                                   busConfig.MessageOwners.ToArray(),
                                                   applicationContext.Get<IEndpointRouter>()));

            applicationContext.RegisterSingleton(() => new CreateQueuesAction(applicationContext.Get<IQueueStrategy>(), applicationContext.Get<IServiceBus>()));
        }

        public void RegisterPrimaryLoadBalancer()
        {
            var loadBalancerConfig = (LoadBalancerConfiguration)config;

            applicationContext.RegisterSingleton(() =>
                {
                    MsmqLoadBalancer balancer = new MsmqLoadBalancer(applicationContext.Get<IMessageSerializer>(),
                                                                            applicationContext.Get<IQueueStrategy>(),
                                                                            applicationContext.Get<IEndpointRouter>(),
                                                                            loadBalancerConfig.Endpoint,
                                                                            loadBalancerConfig.ThreadCount,
                                                                            loadBalancerConfig.Transactional,
                                                                            applicationContext.Get<IMessageBuilder<Message>>());
                    balancer.ReadyForWorkListener = applicationContext.Get<MsmqReadyForWorkListener>();
                    return balancer;
                });

            applicationContext.RegisterSingleton<IDeploymentAction>(() => new CreateLoadBalancerQueuesAction(applicationContext.Get<IQueueStrategy>(), applicationContext.Get<MsmqLoadBalancer>()));
        }

        public void RegisterSecondaryLoadBalancer()
        {
            var loadBalancerConfig = (LoadBalancerConfiguration)config;

            applicationContext.RegisterSingleton<MsmqLoadBalancer>(() =>
                {
                    MsmqSecondaryLoadBalancer balancer = new MsmqSecondaryLoadBalancer(applicationContext.Get<IMessageSerializer>(),
                                                                                                        applicationContext.Get<IQueueStrategy>(),
                                                                                                        applicationContext.Get<IEndpointRouter>(),
                                                                                                        loadBalancerConfig.Endpoint,
                                                                                                        loadBalancerConfig.PrimaryLoadBalancer,
                                                                                                        loadBalancerConfig.ThreadCount,
                                                                                                        loadBalancerConfig.Transactional,
                                                                                                        applicationContext.Get<IMessageBuilder<Message>>());
                    balancer.ReadyForWorkListener = applicationContext.Get<MsmqReadyForWorkListener>();
                    return balancer;
                });

            applicationContext.RegisterSingleton<IDeploymentAction>(() => new CreateLoadBalancerQueuesAction(applicationContext.Get<IQueueStrategy>(), applicationContext.Get<MsmqLoadBalancer>()));
        }

        public void RegisterReadyForWork()
        {
            var loadBalancerConfig = (LoadBalancerConfiguration)config;

            applicationContext.RegisterSingleton(() => new MsmqReadyForWorkListener(applicationContext.Get<IQueueStrategy>(),
                                                                                    loadBalancerConfig.ReadyForWork,
                                                                                    loadBalancerConfig.ThreadCount,
                                                                                    applicationContext.Get<IMessageSerializer>(),
                                                                                    applicationContext.Get<IEndpointRouter>(),
                                                                                    loadBalancerConfig.Transactional,
                                                                                    applicationContext.Get<IMessageBuilder<Message>>()));

            applicationContext.RegisterSingleton<IDeploymentAction>(() => new CreateReadyForWorkQueuesAction(applicationContext.Get<IQueueStrategy>(), applicationContext.Get<MsmqReadyForWorkListener>()));
        }

        public static void AddData() {
            // Добавление
            using (ApplicationContext db = new ApplicationContext())
            {
                User user1 = new User { Name = "Tom", Age = 33 };
                User user2 = new User { Name = "Alice", Age = 26 };
                User user3 = new User { Name = "Stas", Age = 30 };

                // Добавление по одному
                db.Users.Add(user1);
                // добавить сразу несколько объектов
                db.Users.AddRange(user2, user3);
                db.SaveChanges();
            }
        }

        public static void ReadAllData() {
            using (ApplicationContext db = new ApplicationContext())
            {
                // получаем объекты из бд и выводим на консоль
                var users = db.Users.ToList();
                Console.WriteLine("Список объектов:");
                foreach (User u in users)
                {
                    Console.WriteLine($"{u.Id}.{u.Name} - {u.Age}");
                }
            }
        }

        public static void UpdateData() {
            // Редактирование
            using (ApplicationContext db = new ApplicationContext())
            {
                // получаем первый объект
                User user = db.Users.FirstOrDefault();
                if (user != null)
                {
                    user.Name = "Bob";
                    user.Age = 44;
                    //обновляем объект
                    //db.Users.Update(user);
                    // db.Users.UpdateRange(user1, user2);
                    db.SaveChanges();
                }
            }
        }

        public static void DeleteData() {
            // Удаление
            using (ApplicationContext db = new ApplicationContext())
            {
                // получаем первый объект
                User user = db.Users.FirstOrDefault();
                if (user != null)
                {
                    //удаляем объект
                    db.Users.Remove(user);
                    // db.Users.RemoveRange(user1, user2);
                    db.SaveChanges();
                }
            }
        }

        public static void ClearTable() {
            using (ApplicationContext db = new ApplicationContext())
            {
                db.Users.RemoveRange(db.Users);
                db.SaveChanges();
            }
        }

        #region Distributed Operations
        public static User SelectFirstOrDefault()
        {
            using (var db = new ApplicationContext())
            {
                return db.Users.FirstOrDefault();
            }
        }

Sitko.Core.App.ApplicationContext : Object

Constructors :

public ApplicationContext(String name = , String version = , IHostEnvironment environment = , IConfiguration configuration = , ILogger logger = )

Methods :

public String get_Name()
public String get_Version()
public IHostEnvironment get_Environment()
public IConfiguration get_Configuration()
public ILogger get_Logger()
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()