상속: DbContext, IMyProj1DbContext, IMyProj2DbContext
        public async Task<ActionResult> Default(RegisterViewModel model)
        {
            var context = new MyDbContext();
            var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            
            // The default Validators that the UserManager uses are UserValidator and MinimumLengthValidator
            // You can tweak some of the settings as follows
            // This example sets the Password length to be 3 characters
            UserManager.UserValidator = new UserValidator<ApplicationUser>(UserManager)
            {
                AllowOnlyAlphanumericUserNames = false
            };
             UserManager.PasswordValidator = new MinimumLengthValidator(3);


            if (ModelState.IsValid)
            {
                var user = new ApplicationUser() { UserName = model.UserName };
                user.HomeTown = model.HomeTown;
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    var authManager = HttpContext.GetOwinContext().Authentication;
                    var claimsIdentity = UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                    authManager.SignIn(claimsIdentity);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError("", error);
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
예제 #2
0
        public static void OnContractToBeCompleted(object source, EventArgs e)
        {
            MyDbContext db = new MyDbContext();

            var contract = (Contract)source;

            //Get contract from db to check wheter the saving worked and the status is set
            contract = db.Contracts.Find(contract.Id);

            if (contract != null && contract.ContractStatus.Id == 1)
            {
                var tempTask = new ContractTask();

                tempTask.Description = "Vertrag vervollstaendigen";
                tempTask.TaskType = TaskTypes.VertragVervollstaendigen;
                tempTask.Contract = contract;
                tempTask.User = contract.Dispatcher;
                tempTask.IsDone = false;

                tempTask.DateCreated = DateTime.Now;

                //for Testing only - for Real App uncomment the Line after
                tempTask.Expiring = DateTime.Now.AddMinutes(Constants.LAUFZEIT_DISPATCHERTASK_MINUTEN_TEST);
                //tempTask.Expiring = DateTime.Now.AddDays(Constants.LAUFZEIT_DISPATCHERTASK_TAGE);

                db.ContractTasks.Add(tempTask);
                db.SaveChanges();

                //take care that the task gets removed
                tempTask.TriggerTaskCreatedEvent();

                System.Diagnostics.Debug.WriteLine("<Vertrag vervollstaendigen> Aufgabe erstellt");
            }
        }
예제 #3
0
    static void Main(string[] args)
    {
        // Original tutorial: http://blog.devart.com/entity-framework-code-first-support-for-oracle-mysql-postgresql-and-sqlite.html

        //--------------------------------------------------------------
        // You use the capability for configuring the behavior of the EF-provider:
        /*
        Devart.Data.Oracle.Entity.Configuration.OracleEntityProviderConfig config =
            Devart.Data.Oracle.Entity.Configuration.OracleEntityProviderConfig.Instance;

        config.Workarounds.IgnoreSchemaName = true;
         * */
        //--------------------------------------------------------------

        /*--------------------------------------------------------------
        You can set up a connection string for DbContext in different ways.
        It can be placed into the app.config (web.config) file.
        The connection string name must be identical to the DbContext descendant name.

        <add name="MyDbContext" connectionString="Data Source=ora1020;
        User Id=test;Password=test;" providerName="Devart.Data.Oracle" />

        After that, you create a context instance, while a connection string is
        enabled automatically:
        MyDbContext context = new MyDbContext();
        ---------------------------------------------------------------*/

        /*--------------------------------------------------------------
        You can choose one of database initialization
        strategies or turn off initialization:
        --------------------------------------------------------------*/
        System.Data.Entity.Database.SetInitializer<MyDbContext>(new MyDbContextDropCreateDatabaseAlways());

        /*System.Data.Entity.Database.SetInitializer
          <MyOracleContext>(new MyDbContextCreateDatabaseIfNotExists());
        System.Data.Entity.Database.SetInitializer
          <MyOracleContext>(new MyDbContextDropCreateDatabaseIfModelChanges());
        System.Data.Entity.Database.SetInitializer<MyOracleContext>(null);*/
        //--------------------------------------------------------------

        /*--------------------------------------------------------------
        Let's create MyDbContext and execute a database query.
        Depending on selected database initialization strategy,
        database tables can be deleted/added, and filled with source data.
        ---------------------------------------------------------------*/

        Console.WriteLine("Available account currencies in database:");
        using (MyDbContext context = new MyDbContext())
        {
            var list = (from d in context.AccountCurrencies
                        select d).ToList();

            foreach (var l in list)
            {
                Console.WriteLine(l.IsoCode);
            }
        }

        Console.ReadKey();
    }
예제 #4
0
파일: Program.cs 프로젝트: bmiller1985/Test
        static void Main()
        {
            try
            {
                using(var db = new MyDbContext())
                {
                    Console.WriteLine("*** Using EF directly ***");
                    var data = db.Customers.Take(10).OrderBy(x => x.CustomerId);
                    foreach(var row in data)
                    {
                        Console.WriteLine(row.CompanyName);
                    }

                    Console.WriteLine();

                    Console.WriteLine("*** Using EF via a repository ***");
                    ICustomersRepository customersRepository = new CustomersRepository(db);
                    var repoData = customersRepository.GetTop10();
                    foreach(var row in repoData)
                    {
                        Console.WriteLine(row.CompanyName);
                    }
                }
            }
            catch(Exception e)
            {
                Console.WriteLine("**************************************************");
                Console.WriteLine("********************** Exception *****************");
                Console.WriteLine();
                Console.WriteLine(e.Message);
                Console.WriteLine();
                Console.WriteLine(e.InnerException);
            }
        }
예제 #5
0
 //Gets the Departments of Dispatcher depend on the Client
 public static IQueryable<CostCenter> GetCostCentersFromClient(string client, MyDbContext db)
 {
     var query = from c in db.CostCenters
                 where c.Client.ClientName.Equals(client)
                 select c;
     return query;
 }
예제 #6
0
 public static IQueryable<ContractSubType> GetContractSubTypesFromContractTypes(string type, MyDbContext db)
 {
     var query = from s in db.ContractSubTypes
                 where s.ContractType.Description.Equals(type)
                 select s;
     return query;
 }
예제 #7
0
 //Gets the Departments of Dispatcher depend on the Client
 public static IQueryable<Department> GetDepartmentsFromClient(string client, MyDbContext db)
 {
     var query = from d in db.Departments
                 where d.Client.ClientName.Equals(client)
                 select d;
     return query;
 }
예제 #8
0
파일: UnitTest.cs 프로젝트: rpetz/Wreck
 public void TestMethod1()
 {
     var validator = new Validator();
     var ctx = new MyDbContext();
     var results = validator.CheckDbContext(ctx).AlsoCheck(DatabaseObjectType.Trigger, "dbo", "MyTrigger").Validate();
     Assert.IsTrue(!results.Any());
 }
예제 #9
0
        public void SetUp()
        {
            Database.SetInitializer(new DataSeedingInitializer());
            context = new MyDbContext("DefaultDb");

            customerRepository = new CustomerRepository(context);
            genericRepository = new GenericRepository(context);
        }
예제 #10
0
        public AccountController()
        {
            db = new MyDbContext();
            UserManager = new UserManager<MyUser>(new UserStore<MyUser>(db));
            RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));

            UserManager.UserValidator = new UserValidator<MyUser>(UserManager) { AllowOnlyAlphanumericUserNames = false };
        }
예제 #11
0
 //Gets the Client of Department
 public static IQueryable<Client> GetClientOfDepartment(string department, MyDbContext db)
 {
     var subQuery = from dep in db.Departments
                    where dep.DepartmentName.Equals(department)
                    select dep;
     var query = from c in db.Clients
                 join dep in subQuery on c.Id equals dep.Client.Id
                 select c;
     return query;
 }
예제 #12
0
 //Gets the Departments of UserEmail
 public static IQueryable<Department> GetDepartmentsOfUser(string userName, MyDbContext db)
 {
     var subQuery = from du in db.DepartmentUser_Relations
                    where du.User.UserName.Equals(userName)
                    select du;
     var query = from dep in db.Departments
                 join du in subQuery on dep.Id equals du.DepartmentID
                 select dep;
     return query;
 }
예제 #13
0
 /// 获取当前数据上下文
 /// </summary>
 /// <returns></returns>
 public static MyDbContext GetCurrentContext()
 {
     MyDbContext _nContext = CallContext.GetData("MyDbContext") as MyDbContext;
     if (_nContext == null)
     {
         _nContext = new MyDbContext();
         CallContext.SetData("MyDbContext", _nContext);
     }
     return _nContext;
 }
예제 #14
0
 /*<!--Oberhauser/-->*/
 //Gets the Departments of Dispatcher depend on the Client
 public static IQueryable<ContractUser> GetCoordinatorsFromClient(string client, MyDbContext db)
 {
     var subQuery = from c in db.CoordinatorClient_Relations
                    where c.Client.ClientName.Equals(client)
                    select c;
     var query = from u in db.Users
                 from c in subQuery
                 where (
                     u.Id.Equals(c.CoordinatorID)
                 )
                 select u;
     return query;
 }
예제 #15
0
 public HomeController(MyDbContext someDb = null)
 {
     //If we were given a null context, just use the default context
     if (someDb == null)
     {
         Db = new MyDbContext("MyDbContext");
     }
     else
     {
         //otherwise, use the supplied context
         Db = someDb;
     }
 }
        public DbGeography GetPersonGeography(string firstName)
        {
            using (var context = new MyDbContext())
            {
                var q = from p in context.Person_People
                    where p.FirstName == firstName
                    select p.Person_BusinessEntity.Person_BusinessEntityAddresses;

                var address = q.First().First();

                return address.Person_Address.SpatialLocation;
            }
        }
        public IList<string> GetDistinctNames()
        {
            using (var context = new MyDbContext())
            {
                var q = from p in context.Person_People select p.FirstName;

                var names = q.Distinct()
                    .OrderBy(x => x)
                    .ToList();

                return names;
            }
        }
        public IList<Person_Person> GetPeopleByFirstName(string firstName)
        {
            using (var context = new MyDbContext())
            {
                var q = from p in context.Person_People where p.FirstName == firstName select p;

                var names = q.Distinct()
                    .Include( x=> x.Person_BusinessEntity)
                    .Include(x => x.Person_BusinessEntity.Person_BusinessEntityAddresses)
                    .OrderBy(x => x.LastName)
                    .ToList();

                return names;
            }
        }
예제 #19
0
        public void Execute(IJobExecutionContext context)
        {
            System.Diagnostics.Debug.WriteLine("Aufgabe wird geloescht ");

            JobDataMap dataMap = context.JobDetail.JobDataMap;

            int taskKey = dataMap.GetInt("TaskId");

            MyDbContext db = new MyDbContext();

            ContractTask task = db.ContractTasks.Find(taskKey);
            db.ContractTasks.Remove(task);
            db.SaveChanges();

            System.Diagnostics.Debug.WriteLine("Aufgabe wurde geloescht ");
        }
예제 #20
0
        /// <summary>
        /// 
        /// Messenger Note on Task Notification
        /// 
        /// </summary>
        /// <param name="context"></param>
        public void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            int taskKey = dataMap.GetInt("TaskId");

            MyDbContext db = new MyDbContext();

            var task = db.ContractTasks.Find(taskKey);

            if (task != null && task.IsDone == false)
            {
                Messenger messenger = Messenger.Instance;
                messenger.AddToMessenger(DateTime.Now, "Aufgabe " + "<b>" + task.Description + "</b>" + " muss bald erledigt werden");
            }
        }
        public void Test2()
        {
            using (var context = new MyDbContext())
            {
                var queryable = context.Products
                    .AsQueryable()
                    .GroupBy("new ( ProductName )", "it")
                    .Select("new ( Key.ProductName AS ProductName, SUM(UnitPrice) as Total )")
                    .ToListAsync();

                foreach (var record in queryable.Result)
                {

                }
            }
        }
예제 #22
0
        public static void OnContractCompleted(object source, EventArgs e)
        {
            //Not implemented yet - Mark Task as Done
            MyDbContext db = new MyDbContext();

            var contract = (Contract)source;

            var task = db.ContractTasks.Where(t => t.Contract.Id == contract.Id && t.TaskType == TaskTypes.VertragVervollstaendigen).SingleOrDefault();
            task.IsDone = true;

            db.Entry(task).State = EntityState.Modified;
            db.SaveChanges();

            //take care that the task gets removed
            task.TriggerTaskDoneEvent();

            System.Diagnostics.Debug.WriteLine("Vertrag vervollstaendigt");
        }
        // GET: ClaimsIdentityFactory
        public async Task<ActionResult> Index(LoginViewModel model, string returnUrl)
        {
            var context = new MyDbContext();
            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            userManager.ClaimsIdentityFactory = new MyClaimsIdentityFactory<ApplicationUser>();

            // Create a User to SignIn
            var user = await userManager.FindAsync(model.UserName, model.Password);

            //SignIn the User by generating a ClaimsIdentity            
            var claimsIdentity = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

            // This claimsIdentity should have a claim called LastLoginTime
            var authManager = HttpContext.GetOwinContext().Authentication;
            authManager.SignIn(claimsIdentity);
            
            return RedirectToLocal(returnUrl);
        }
예제 #24
0
        public static void OnDispatcherSet(object source, EventArgs e)
        {
            MyDbContext db = new MyDbContext();

            Contract tempContract = (Contract)source;

            //The dispatcher has to be loaded here because the nav property is not set at this point yet
            ContractUser dispatcher = db.Users.Find(tempContract.DispatcherId);

            //Notify Dispatcher
            dynamic email = new Email("DispatcherMail");
            email.to = dispatcher.Email;

            email.from = applicationEmail;
            email.contractId = tempContract.Id;

            email.Send();
            System.Diagnostics.Debug.WriteLine("Email wurde abgeschickt");
        }
예제 #25
0
        // http://trentacular.com/2010/08/linq-to-entities-wild-card-like-extension-method/
        static void Main(string[] args)
        {
            using (var context = new MyDbContext())
            {
                context.Database.Log = (sql) => Debug.WriteLine(sql);
#if BEFORE
                var q =
                    context.Stores.Where(
                        h => h.Name.StartsWith("E") && h.Name.EndsWith("E"));
#else
                var q = context.Stores.WhereStartsAndEndsWith(h => h.Name, "E");
#endif

                foreach (var storeName in q.Select(s => s.Name).ToList())
                {
                    Console.WriteLine(storeName);
                }
            }

            Console.ReadLine();
        }
예제 #26
0
        /// <summary>
        /// 
        /// Checks if the Task stil exists and if its not done yet.
        /// Then it sends a notification to the responsible person
        /// 
        /// </summary>
        /// <param name="context"></param>
        public void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            int taskKey = dataMap.GetInt("TaskId");

            MyDbContext db = new MyDbContext();

            var task = db.ContractTasks.Find(taskKey);

            if (task != null && task.IsDone == false)
            {
                var contract = db.Contracts.Find(task.Contract.Id);
                var contractOwner = contract.Owner;
                if (contractOwner == null)
                {
                    return;
                }

                MailUtility.NotifyOnEscalation(task, contractOwner.Email);
                System.Diagnostics.Debug.WriteLine("Benachrichtigung ueber Eskalation abgeschickt");
            }
        }
예제 #27
0
        public static ContractStatus checkContractStatus(Contract contract, MyDbContext db)
        {
            if(contract.ContractStatus != null)
            {
                string currentStatus = contract.ContractStatus.Description;
                if(currentStatus == "deleted" || currentStatus == "closed")
                {
                    return contract.ContractStatus;
                }
                if(currentStatus == "repealed")
                {
                    //Not implemented yet
                    return contract.ContractStatus;
                }
            }

            if (getAbsoluteContractStatus(contract) > 8)
            {

                return db.ContractStatuses.Where(b => b.Description == "active").FirstOrDefault();
            }

            return db.ContractStatuses.Where(b => b.Description == "incomplete").FirstOrDefault();
        }
        public async Task<ActionResult> Customize(RegisterViewModel model)
        {
            var context = new MyDbContext();
            var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));

            // The default Validators that the UserManager uses are UserValidator and MinimumLengthValidator
            // If you want to have complete control over validation then you can write your own validators.
            UserManager.UserValidator = new MyUserValidation();
            UserManager.PasswordValidator = new MyPasswordValidation();
            UserManager.PasswordHasher = new PasswordHasher();


            if (ModelState.IsValid)
            {
                var user = new ApplicationUser() { UserName = model.UserName };
                user.HomeTown = model.HomeTown;
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    var authManager = HttpContext.GetOwinContext().Authentication;
                    var claimsIdentity = UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                    authManager.SignIn(claimsIdentity);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError("", error);
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return View("Index",model);
        }
예제 #29
0
 //Gets the Dispatchers depend on the Department
 public static IQueryable<ContractUser> GetDispatchersFromDepartment(string department, MyDbContext db)
 {
     /*
     var subQuery =  from du in db.DU_Relations
                     where du.Department.DepartmentName.Equals(selection)
                     select du;
     var query = from u in db.Users
                 join du in subQuery on u.Id equals du.UserID
                 select u;
     var data = new SelectList(query, "Id", "UserName").ToList();
     return Json(data);
     */
     var subQuery = from dep in db.Departments
                    where dep.DepartmentName.Equals(department)
                    select dep;
     var query = from u in db.Users
                 from dep in subQuery
                 where (
                     u.Id.Equals(dep.DispatcherId)
                     || u.Id.Equals(dep.ViceDispatcherId)
                 )
                 select u;
     return query;
 }
예제 #30
0
 public InvoiceLineRepository(MyDbContext context) : base(context)
 {
 }
예제 #31
0
 public TestController(IDemoStudentAppService demoStudentAppService, MyDbContext db)
 {
     this._demoStudentAppService = demoStudentAppService;
     this._db = db;
 }
예제 #32
0
 public EfDeleteUserCommand(MyDbContext context) : base(context)
 {
 }
예제 #33
0
 public OrderF()
 {
     context = new MyDbContext();
 }
예제 #34
0
 public KategoriRepository(MyDbContext _db) : base(_db)
 {
 }
예제 #35
0
 public LogsRepository(MyDbContext context)
 {
     _context = context;
 }
예제 #36
0
 public BrandsController(MyDbContext myDbContext)
 {
     _myDbContext = myDbContext;
 }
예제 #37
0
 public UsersRepo(MyDbContext db)
 {
     _db = db;
 }
        public static List <DataGridGamesView> Update(List <DataGridGamesView> AllGames)
        {
            using (var cnt = new MyDbContext())
            {
                List <LibraryDataGDBLink> links = LibraryDataGDBLink.GetLibraryData().ToList();
                List <DataGridGamesView>  q     = new List <DataGridGamesView>();
                var games = (from g in cnt.Game
                             where g.hidden != true
                             select g).ToList();
                foreach (var game in games)
                {
                    DataGridGamesView d = new DataGridGamesView();
                    d.ID = game.gameId;

                    d.System     = GSystem.GetSystemName(game.systemId);
                    d.LastPlayed = DbEF.FormatDate(game.gameLastPlayed);
                    d.Favorite   = game.isFavorite;

                    d.Country = game.Country;

                    if (game.romNameFromDAT != null)
                    {
                        if (game.romNameFromDAT.Contains("(USA)"))
                        {
                            d.Country = "US";
                        }
                        if (game.romNameFromDAT.Contains("(Europe)"))
                        {
                            d.Country = "EU";
                        }
                    }


                    d.Flags     = game.OtherFlags;
                    d.Language  = game.Language;
                    d.Publisher = game.Publisher;
                    d.Year      = game.Year;

                    if (game.gameNameFromDAT != null && game.gameNameFromDAT != "")
                    {
                        d.Game = game.gameNameFromDAT;
                    }
                    else
                    {
                        d.Game = game.gameName;
                    }

                    //d.DatName = game.gameNameFromDAT;
                    d.DatRom = game.romNameFromDAT;

                    if (game.gdbId != null && game.gdbId > 0)
                    {
                        var link = links.Where(x => x.GDBId == game.gdbId).SingleOrDefault(); // LibraryDataGDBLink.GetLibraryData(game.gdbId.Value);
                        if (link != null)
                        {
                            if (link.Publisher != null && link.Publisher != "")
                            {
                                d.Publisher = link.Publisher;
                            }

                            d.Developer = link.Developer;

                            if (link.Year != null && link.Year != "")
                            {
                                d.Year = DbEF.ReturnYear(link.Year);
                            }
                            d.Players = link.Players;
                            d.Coop    = link.Coop;
                            d.ESRB    = link.ESRB;
                        }
                    }

                    q.Add(d);
                }


                return(q);

                //AllGames = ng;
            }
        }
예제 #39
0
 public TaiKhoanDAO()
 {
     db = new MyDbContext();
 }
예제 #40
0
 public CityRepository(MyDbContext myContext)
 {
     _myContext = myContext;
 }
예제 #41
0
 public TradeRepository(MyDbContext context) : base(context)
 {
 }
예제 #42
0
 public PlayableController(MyDbContext context, MyHelperService helper)
 {
     _context = context;
     _helper  = helper;
 }
예제 #43
0
 public MyHelperService(MyDbContext context)
 {
     _context = context;
 }
예제 #44
0
        private void btneliminar_Click(object sender, EventArgs e)
        {
            if (txtnombre.Text != "")
            {
                var idCtl = moduloInicio.ObtenerIdControl(iduser);  //listado controles del usuario
                int i     = 0;
                while (moduloInicio.Existe("select * from pyme.controls where IdUsuario=" + iduser + ";") && i < idCtl.Count)
                {
                    if (!moduloInicio.Existe("select * from pyme.trabajadorcontrols where Control_IdControl=" + idCtl[i].IdControl + ";"))
                    {
                        if (!moduloInicio.Existe("select * from pyme.cursocontrols where Control_IdControl=" + idCtl[i].IdControl + ";"))
                        {
                            if (!moduloInicio.Existe("select * from pyme.epicontrols where Control_IdControl=" + idCtl[i].IdControl + ";"))
                            {
                                if (!moduloInicio.Existe("select * from pyme.periodocontrols where Control_IdControl=" + idCtl[i].IdControl + ";"))
                                {
                                    if (!moduloInicio.Existe("select * from pyme.agenda where IdUsuario=" + iduser + ";"))
                                    {
                                    }
                                    else
                                    {
                                        MessageBox.Show("no se puede eliminar, agenda asociada"); return;
                                    }
                                }
                                else
                                {
                                    MessageBox.Show("no se puede eliminar, controles/periodos asociados"); return;
                                }
                            }
                            else
                            {
                                MessageBox.Show("no se puede eliminar, controles/epi asociados"); return;
                            }
                        }
                        else
                        {
                            MessageBox.Show("no se puede eliminar, controles/curso asociados"); return;
                        }
                    }
                    else
                    {
                        MessageBox.Show("no se puede eliminar, controles/trabajador asociados"); return;
                    }
                    i++;
                }
                // eliminar controles de un usuario
                moduloInicio.OperarSql("delete from pyme.controls where IdUsuario=" + iduser + ";");

                if (MessageBox.Show("Este proceso borra el usuario " + datagridUsuarios.CurrentRow.Cells[1].Value.ToString().ToUpper() + " de la bd, lo quieres hacer S/N", "CUIDADO", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    using (MyDbContext context = new MyDbContext())
                    {
                        Usuario usuario = context.Usuarios.Where(x => x.IdUsuario == iduser).FirstOrDefault();
                        context.Usuarios.Remove(usuario);
                        context.SaveChanges();
                    }
                    Recarga();
                }
                btnAlta.Enabled = true;
            }
            else
            {
                MessageBox.Show("Usuario no seleccionado");
            }
        }
예제 #45
0
        //Сохранение/Изменение
        private void Save_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                using (MyDbContext db = new MyDbContext())
                {
                    User    thisUser = db.Users.Find(App.CurrentUser.Id);
                    MedCard test     = db.MedCards.FirstOrDefault(p => p.ID == thisUser.Id);

                    if (Bday_textbox.SelectedDate <= DateTime.Now.Date && Bday_textbox.SelectedDate > DateTime.Now.AddYears(-150).Date)
                    {
                        if (test == null)
                        {
                            MedCard card = new MedCard();
                            card.ID         = thisUser.Id;
                            card.Name       = Name_textbox.Text;
                            card.Surname    = Surname_textbox.Text;
                            card.Patronymic = Patronymic_textbox.Text;
                            card.Gender     = Gender.Text;
                            card.BDay       = DateTime.ParseExact(Bday_textbox.Text, "dd.MM.yyyy",
                                                                  System.Globalization.CultureInfo.InvariantCulture);
                            card.City    = City_textbox.Text;
                            card.Street  = Street_textbox.Text;
                            card.House   = Convert.ToInt32(House_textbox.Text);
                            card.Housing = Housing.Text;
                            card.Flat    = Flat_textbox.Text;
                            card.Image   = PathImage;
                            db.MedCards.AddRange(new List <MedCard> {
                                card
                            });
                            db.SaveChanges();
                            MaterialMessageBox.Show("Сохранение/Изменение прошло успешна", "Уведомление");
                        }
                        else
                        {
                            db.MedCards.Find(thisUser.Id).Name       = Name_textbox.Text.Trim();
                            db.MedCards.Find(thisUser.Id).Surname    = Surname_textbox.Text.Trim();
                            db.MedCards.Find(thisUser.Id).Patronymic = Patronymic_textbox.Text.Trim();
                            db.MedCards.Find(thisUser.Id).Gender     = Gender.Text.Trim();
                            db.MedCards.Find(thisUser.Id).BDay       = DateTime.ParseExact(Bday_textbox.Text, "dd.MM.yyyy",
                                                                                           System.Globalization.CultureInfo.InvariantCulture);
                            db.MedCards.Find(thisUser.Id).City    = City_textbox.Text.Trim();
                            db.MedCards.Find(thisUser.Id).Street  = Street_textbox.Text.Trim();
                            db.MedCards.Find(thisUser.Id).House   = Convert.ToInt32(House_textbox.Text);
                            db.MedCards.Find(thisUser.Id).Housing = Housing.Text.Trim();
                            db.MedCards.Find(thisUser.Id).Flat    = Flat_textbox.Text.Trim();
                            db.MedCards.Find(thisUser.Id).Image   = PathImage;
                            AdMainImage.Source = new BitmapImage(new Uri(PathImage, UriKind.Absolute));
                            db.SaveChanges();
                            MaterialMessageBox.Show("Сохранение/Изменение прошло успешна", "Уведомление");
                        }
                    }
                    else
                    {
                        MaterialMessageBox.Show("Некорретная дата, попробуйте ещё раз", "Уведомление");
                        Bday_textbox.Text = "";
                    }
                }
            }
            catch (Exception ex) { MaterialMessageBox.Show("Упс.. Что-то пошло не так", "Уведомление"); }
        }
예제 #46
0
 public BillsItemService(MyDbContext dbContext)
 {
     DbContext = dbContext;
 }
예제 #47
0
 public SkillRepository(MyDbContext myDbContext) : base(myDbContext)
 {
 }
예제 #48
0
 public BaseService(MyDbContext dbContext)
 {
     DbContext = dbContext;
 }
예제 #49
0
 public NoteRepository(MyDbContext _context)
 {
     context = _context;
 }
예제 #50
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="dbcontext"></param>
 /// <returns></returns>
 public async Task Connect(MyDbContext dbcontext)
 {
     _DbContext = dbcontext;
     await Run();
 }
예제 #51
0
 public ProductController(MyDbContext db, IHostingEnvironment env)
 {
     this.db  = db;
     this.env = env;
 }
예제 #52
0
 public Handler(MyDbContext context)
 {
     this._context = context;
 }
예제 #53
0
        private void btnReport_Click(object sender, EventArgs e)
        {
            if (rbDetailedHistory.Checked)
            {
                if (cbReportFor.selectedIndex == 0 || (cbReportFor.selectedIndex == 1 &&
                                                       cbPropertyType.selectedIndex > -1 &&
                                                       cbProperty.selectedIndex > -1))
                {
                    var dt = new DataTable();
                    dt.Columns.Add("Customer");
                    dt.Columns.Add("Price");
                    dt.Columns.Add("Method");
                    dt.Columns.Add("Period");
                    dt.Columns.Add("Start");
                    dt.Columns.Add("End");
                    dt.Columns.Add("Property");
                    // ReSharper disable ConvertIfStatementToSwitchStatement
                    if (cbReportFor.selectedIndex == 0)
                    {
                        var properties = _db.Properties.ToList();
                        foreach (var property in properties)
                        {
                            var contracts = _db.Contracts.Where(c => c.PropertyId == property.Id).ToList();
                            foreach (var contract in contracts)
                            {
                                var customers = _db.Clients.Where(c => c.Id == contract.ClientId).ToList();
                                foreach (var customer in customers)
                                {
                                    dt.Rows.Add(customer.Name, contract.Price, contract.Method,
                                                contract.PayEvery + " " + contract.Period,
                                                contract.Start.ToShortDateString(), contract.End.ToShortDateString(),
                                                property.Name);
                                }
                            }
                        }

                        var rpt = new rptDetailedHistory();
                        rpt.SetDataSource(dt);
                        rpt.PrintToPrinter(1, true, 0, 0);
                    }
                    else if (cbReportFor.selectedIndex == 1)
                    {
                        if (cbProperty.selectedIndex >= 0 || cbPropertyType.selectedIndex >= 0)
                        {
                            var propertyId = int.Parse(cbTempProperty.SelectedValue.ToString());
                            var property   = _db.Properties.Find(propertyId);
                            if (property == null)
                            {
                                return;
                            }
                            var contracts = _db.Contracts.Where(c => c.PropertyId == property.Id).ToList();
                            foreach (var contract in contracts)
                            {
                                var customers = _db.Clients.Where(c => c.Id == contract.ClientId).ToList();
                                foreach (var customer in customers)
                                {
                                    dt.Rows.Add(customer.Name, contract.Price, contract.Method,
                                                contract.PayEvery + " " + contract.Period,
                                                contract.Start.ToShortDateString(), contract.End.ToShortDateString());
                                }
                            }

                            var rpt = new rptDetailedHistory();
                            rpt.SetDataSource(dt);
                            rpt.PrintToPrinter(1, true, 0, 0);
                        }
                        else
                        {
                            MessageBox.Show(@"Please fill all the fields", "", MessageBoxButtons.OK,
                                            MessageBoxIcon.Error);
                        }
                    }
                }
                else
                {
                    MessageBox.Show(@"Please fill all the fields", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else if (rbOccupation.Checked)
            {
                if (cbReportFor2.selectedIndex == 0 || (cbReportFor2.selectedIndex == 1 &&
                                                        cbPropertyType2.selectedIndex > -1 &&
                                                        cbProperty2.selectedIndex > -1))
                {
                    var dt = new DataTable();
                    dt.Columns.Add("Property");
                    dt.Columns.Add("PropertyType");
                    dt.Columns.Add("Status");
                    dt.Columns.Add("Client");
                    dt.Columns.Add("Start");
                    dt.Columns.Add("End");
                    dt.Columns.Add("Rate");
                    if (cbReportFor2.selectedIndex == 0)
                    {
                        var properties = _db.Properties.ToList();
                        foreach (var property in properties)
                        {
                            var contract = _db.Contracts.FirstOrDefault(c => c.PropertyId == property.Id);
                            if (contract != null)
                            {
                                var contracts = _db.Contracts.Where(c => c.PropertyId == property.Id).ToList();
                                foreach (var c in contracts)
                                {
                                    var client = _db.Clients.Find(c.ClientId);
                                    // ReSharper disable once PossibleNullReferenceException
                                    dt.Rows.Add(property.Name, property.BuildingType.ToString(),
                                                property.Status.ToString(),
                                                client.Name, c.Start.ToShortDateString(), c.End.ToShortDateString(),
                                                c.Price);
                                }
                            }
                            else
                            {
                                dt.Rows.Add(property.Name, property.BuildingType.ToString(), property.Status.ToString(),
                                            "", "", "", "");
                            }
                        }
                        var rpt = new rptAllOccupation();
                        rpt.SetDataSource(dt);
                        rpt.PrintToPrinter(1, true, 0, 0);
                    }
                    else if (cbReportFor2.selectedIndex == 1)
                    {
                        var propertyId = int.Parse(cbTempProperty.SelectedValue.ToString());
                        var property   = _db.Properties.Find(propertyId);
                        if (property == null)
                        {
                            return;
                        }
                        var contract = _db.Contracts.Where(c => c.PropertyId == property.Id)
                                       .OrderByDescending(c => c.Id).FirstOrDefault();
                        if (contract != null)
                        {
                            var client = _db.Clients.Find(contract.ClientId);
                            // ReSharper disable once PossibleNullReferenceException
                            dt.Rows.Add(property.Name, property.BuildingType.ToString(), property.Status.ToString(),
                                        client.Name, contract.Start.ToShortDateString(), contract.End.ToShortDateString(),
                                        contract.Price);
                        }
                        else
                        {
                            dt.Rows.Add(property.Name, property.BuildingType.ToString(), property.Status.ToString(),
                                        "", "", "", "");
                        }
                        var rpt = new rptAllOccupation();
                        rpt.SetDataSource(dt);
                        rpt.PrintToPrinter(1, true, 0, 0);
                    }
                }
                else
                {
                    MessageBox.Show(@"Please fill all the fields", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else if (rbCashFlow.Checked)
            {
                // ReSharper disable NotAccessedVariable
                double collectedTotal    = 0;
                double notCollectedTotal = 0;
                var    start             = dtpStart.Value;
                var    end = dtpEnd.Value;

                var dt = new DataTable();
                dt.Columns.Add("Client");
                dt.Columns.Add("Property");
                dt.Columns.Add("PaymentDate");
                dt.Columns.Add("Amount");
                dt.Columns.Add("Status");
                dt.Columns.Add("CollectedTotal");
                dt.Columns.Add("NotCollectedTotal");
                var payments = _db.Payments.Where(p => p.PaymentDate >= start && p.PaymentDate <= end).ToList();
                using (var db = new MyDbContext())
                {
                    foreach (var payment in payments)
                    {
                        var contract = db.Contracts.Find(payment.ContractId);
                        if (contract == null)
                        {
                            continue;
                        }
                        // ReSharper disable PossibleNullReferenceException
                        var property = db.Properties.Find(contract.PropertyId);
                        var client   = db.Clients.Find(contract.ClientId);
                        dt.Rows.Add(client.Name, property.Name,
                                    string.IsNullOrWhiteSpace(payment.PaymentDate.ToShortDateString())
                                ? contract.PayDate.ToShortDateString()
                                : payment.PaymentDate.ToShortDateString(),
                                    payment.PayedAmount.ToString(CultureInfo.InvariantCulture), "Collected");
                        collectedTotal += payment.PayedAmount;
                    }
                }


                if (chbUncollected.Checked)
                {
                    // ReSharper disable once RedundantAssignment
                    var contractsPending = new List <Contract>();
                    using (var db = new MyDbContext())
                    {
                        contractsPending = db.Contracts.Where(c =>
                                                              c.PayStatus.Equals("Pending") && c.PayDate >= start && c.PayDate <= end).ToList();
                    }

                    foreach (var contract in contractsPending)
                    {
                        using (var db = new MyDbContext())
                        {
                            var property = db.Properties.Find(contract.PropertyId);

                            var client = db.Clients.Find(contract.ClientId);

                            dt.Rows.Add(client.Name, property.Name, contract.PayDate.ToShortDateString(),
                                        contract.Price.ToString(CultureInfo.InvariantCulture), "Not Collected");
                            notCollectedTotal += contract.Price;
                        }
                    }
                }


                var rpt = new rptCashFlow();
                var textCollectedTotal    = (TextObject)rpt.ReportDefinition.ReportObjects["CollectedTotal"];
                var textNotCollectedTotal = (TextObject)rpt.ReportDefinition.ReportObjects["NotCollectedTotal"];
                textCollectedTotal.Text    = collectedTotal.ToString(CultureInfo.InvariantCulture);
                textNotCollectedTotal.Text = notCollectedTotal.ToString(CultureInfo.InvariantCulture);
                rpt.SetDataSource(dt);
                rpt.PrintToPrinter(1, true, 0, 0);
            }
        }
예제 #54
0
 public ComandValidator(MyDbContext context)
 {
     RuleFor(x => x.categoryFormVm).SetValidator(new CategoryValidator(context));
 }
예제 #55
0
 public ChiTietHdsController(MyDbContext context)
 {
     _context = context;
 }
예제 #56
0
 public LotRepository(MyDbContext db)
 {
     this.db = db;
 }
예제 #57
0
 public UsersController(MyDbContext context)
 {
     _context = context;
 }
예제 #58
0
 public UserService(IOptions <AppSettings> appSettings, MyDbContext context)
 {
     _appSettings = appSettings.Value;
     _context     = context;
 }
예제 #59
0
 public MonitorBeurtController()
 {
     db = new MyDbContext();
     UserManager = new UserManager<MyUser>(new UserStore<MyUser>(db));
     RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));
 }
예제 #60
0
 public TarifsController(MyDbContext context)
 {
     _context = context;
 }