public static List <ContactModel> ListOfContactModel()
        {
            var contactList = new List <ContactModel>();

            using (var dbContext = new ContactDbContext())
            {
                var contactsFromDb = (from tblContact in dbContext.Contacts
                                      join tblCountry in dbContext.Countries on tblContact.CountryId equals tblCountry.CountryId
                                      join tblState in dbContext.States on tblContact.StateId equals tblState.StateId
                                      select new ContactModel
                {
                    ContactId = tblContact.ContactId,
                    FirstName = tblContact.ContactFName,
                    LastName = tblContact.ContactLName,
                    EmailAddress = tblContact.EmailAddress,
                    Contact1 = tblContact.ContactNumber1,
                    Contact2 = tblContact.ContactNumber2,
                    Country = tblCountry.CountryName,
                    State = tblState.StateName,
                    ImagePath = tblContact.ImagePath
                }).ToList();

                contactList = contactsFromDb;

                return(contactList);
            }
        }
        public static Contact GetContact(int contactId)
        {
            Contact contact = null;

            using (var dbContext = new ContactDbContext())
            {
                var selectedContactFromDatabase = (from tblContacts in dbContext.Contacts
                                                   join tblCountry in dbContext.Countries on tblContacts.CountryId equals tblCountry.CountryId
                                                   join tblStates in dbContext.States on tblContacts.StateId equals tblStates.StateId
                                                   where tblContacts.ContactId.Equals(contactId)
                                                   select new
                {
                    tblContacts,
                    tblCountry.CountryName,
                    tblStates.StateName
                }).FirstOrDefault();

                if (selectedContactFromDatabase != null)
                {
                    contact             = selectedContactFromDatabase.tblContacts;
                    contact.CountryName = selectedContactFromDatabase.CountryName;
                    contact.StateName   = selectedContactFromDatabase.StateName;
                }
            }

            return(contact);
        }
        public ContactService(ContactDbContext context)
        {
            _context = context;

            // Create a new Contact if collection is empty,
            if (_context.Contacts.Count() == 0)
            {
                _context.Contacts.Add(new Contact
                {
                    Name            = "Proof1",
                    Company         = "Organization X",
                    ProfileImageURL = "SomeURL",
                    Email           = "*****@*****.**",
                    BirthDate       = new DateTime(1991, 02, 28),
                    ContactPhone    = new ContactPhone
                    {
                        PersonalPhone = "2123244152",
                        WorkPhone     = "2123244153"
                    },
                    Address = new Address
                    {
                        AddressLine1 = "4321 Sesame Street",
                        AddressLine2 = "Suite 900",
                        City         = "Hollywood",
                        State        = "Los Angeles"
                    }
                });
                _context.SaveChanges();
            }
        }
Пример #4
0
        private void LoadData()
        {
            _contacts = new List <Contact>();

            using (_context = new ContactDbContext())
            {
                List <Contact> allContacts  = _context.Contact.ToList();
                List <Address> allAddresses = _context.Address.ToList();
                List <Phone>   allPhones    = _context.Phone.ToList();
                List <Date>    allDates     = _context.Date.ToList();

                foreach (Contact contact in allContacts)
                {
                    List <Address> addresses = allAddresses.FindAll(delegate(Address address) { return(address.ContactId == contact.ContactId); });
                    foreach (Address address in addresses)
                    {
                        contact.Address.Add(address);
                    }

                    List <Phone> phones = allPhones.FindAll(delegate(Phone phone) { return(phone.ContactId == contact.ContactId); });
                    foreach (Phone phone in phones)
                    {
                        contact.Phone.Add(phone);
                    }

                    List <Date> dates = allDates.FindAll(delegate(Date date) { return(date.ContactId == contact.ContactId); });
                    foreach (Date date in dates)
                    {
                        contact.Date.Add(date);
                    }

                    _contacts.Add(contact);
                }
            }
        }
Пример #5
0
 public AccountController(UserManager <IdentityUser> userManager, SignInManager <IdentityUser> signInManager,
                          ContactDbContext db)
 {
     this.userManager   = userManager;
     this.signInManager = signInManager;
     this.db            = db;
 }
        private static void Seed(ContactDbContext context)
        {
            var contacts = new [] { ContactFactory.GetContact() };

            context.AddRange(contacts);
            context.SaveChanges();
        }
Пример #7
0
        public ActionResult Edit(int id)
        {
            Contact contact = null;

            contact = ContactDbRepository.GetContact(id);  // a private method which we have created previously

            if (contact == null)
            {
                return(HttpNotFound("Contact Not Found"));
            }

            //fetching States and Countries for dropdownlist
            var allCounteries = new List <Country>();
            var allStates     = new List <State>();

            using (var dbContext = new ContactDbContext())
            {
                allCounteries = dbContext.Countries.OrderBy(c => c.CountryName).ToList();
                allStates     = dbContext.States.Where(s => s.CountryId.Equals(contact.CountryId)).OrderBy(s => s.StateName).ToList();
            }
            ViewBag.Countries = new SelectList(allCounteries, "CountryId", "CountryName", contact.CountryId);
            ViewBag.States    = new SelectList(allStates, "StateId", "StateName", contact.StateId);

            return(View(contact));
        }
Пример #8
0
        public ContactDbContext GetDbContext(bool useSqlLite = false)
        {
            var builder = new DbContextOptionsBuilder <ContactDbContext>();

            if (useSqlLite)
            {
                builder.UseSqlite("DataSource=:memory:", x => { });
            }
            else
            {
                builder.UseInMemoryDatabase(Guid.NewGuid().ToString());
            }

            var dbContext = new ContactDbContext(builder.Options);

            if (useSqlLite)
            {
                // SQLite needs to open connection to the DB.
                // Not required for in-memory-database.
                dbContext.Database.OpenConnection();
            }

            dbContext.Database.EnsureCreated();

            return(dbContext);
        }
Пример #9
0
        static void Main(string[] args)
        {   /*
             * Department accounting = new Department { Id = Guid.NewGuid(), name = "hr", Location = "Vasai" };
             * Employee sachin = new Employee { Id = Guid.NewGuid(), name = "Sachin", address = "Palghar", age = 39 };
             * sachin.depatartment = accounting;
             * accounting.Employees.Add(sachin);
             * ContactDbContext db = new ContactDbContext();
             * db.Employees.Add(sachin);
             * db.SaveChanges();
             *
             * Department marketing = new Department { Id = Guid.NewGuid(), name = "marketing", Location = "Mumbai" };
             * Employee vishal = new Employee { Id = Guid.NewGuid(), name = "vishal", address = "Kurla", age = 29 };
             * Employee shehan = new Employee { Id = Guid.NewGuid(), name = "shehan", address = "Virar", age = 22 };
             * Employee romy = new Employee { Id = Guid.NewGuid(), name = "romy", address = "Vasai", age = 25 };
             * vishal.depatartment = marketing;
             * shehan.depatartment = marketing;
             * romy.depatartment = marketing;
             * marketing.Employees.Add(vishal);
             * marketing.Employees.Add(shehan);
             * marketing.Employees.Add(romy);
             * ContactDbContext db = new ContactDbContext();
             * db.Departents.Add(marketing);
             * db.SaveChanges();
             */
            ContactDbContext db = new ContactDbContext();

            Query(db);

            Console.WriteLine("Done");
            Console.ReadLine();
        }
Пример #10
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ContactDbContext dBContext)
        {
            app.UseSwagger();

            app.UseSwaggerUI(c =>
                             c.SwaggerEndpoint("/swagger/v1/swagger.json", "Contract Api")
                             );

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            dBContext.Database.Migrate();

            app.UseExceptionHandler(a => a.Run(async context =>
            {
                var exceptionHandlerPathFeature = context.Features.Get <IExceptionHandlerPathFeature>();
                var exception = exceptionHandlerPathFeature.Error;

                var result = JsonConvert.SerializeObject(new { error = exception.Message });
                context.Response.ContentType = "application/json";
                await context.Response.WriteAsync(result);
            }));

            app.UseHttpsRedirection();
            app.UseMvc();
        }
 public static void AddContact(Contact contact)
 {
     using (var dbContext = new ContactDbContext())
     {
         dbContext.Contacts.Add(contact);
         dbContext.SaveChanges();
     }
 }
Пример #12
0
 // GET api/<controller>
 public IEnumerable <Organization> Get()
 {
     using (var ctx = new ContactDbContext())
     {
         var orgs = ctx.Organizations.Include("People").ToList();
         return(orgs);
     }
 }
Пример #13
0
 public static Dao GetInstance(string dbPath)
 {
     if (instance == null)
     {
         instance = new Dao();
         _db      = new ContactDbContext(dbPath);
     }
     return(instance);
 }
Пример #14
0
 public IList <ContactDTO> Execute()
 {
     using (var db = new ContactDbContext())
     {
         return(contactFirstLevelQuery.GetSource(db)
                .Select(mapper.MapContactToContactDTOExpression)
                .ToList());
     }
 }
 public ContactsController(ContactDbContext context,
                           IAuthorizationService authorizationService,
                           UserManager <IdentityUser> userManager
                           )
 {
     _userManager          = userManager;
     _authorizationService = authorizationService;
     _context = context;
 }
Пример #16
0
        public ActionResult Add(Contact contact, HttpPostedFileBase file)
        {
            #region step#1 : Fetch Countries and States

            var allCountries = new List <Country>();
            var allStates    = new List <State>();
            using (var dbContext = new ContactDbContext())
            {
                allCountries = dbContext.Countries.OrderBy(c => c.CountryName).ToList();
                if (contact.ContactId > 0)
                {
                    // Fetching all the states whose countryId == contact.CountryId (i.e all the states of respective selected country)
                    allStates = dbContext.States.Where(s => s.CountryId.Equals(contact.CountryId)).OrderBy(s => s.StateName).ToList();
                }
            }
            ViewData["Countries"] = new SelectList(allCountries, "CountryId", "CountryName", contact.CountryId);
            ViewData["States"]    = new SelectList(allStates, "StateId", "StateName", contact.StateId);
            #endregion

            #region step#2 : Validate the file if selected

            if (file != null)
            {
                if (file.ContentLength > (512 * 1000))  // if file size > then 512KB
                {
                    ModelState.AddModelError("FileErrorMessage", "File size must be within 512KB");
                }

                bool isFileTypeValid = false;

                isFileTypeValid = ContactDbRepository.ValidateFileType(file);

                if (isFileTypeValid == false)
                {
                    ModelState.AddModelError("FileErrorMessage", "only .png , .gif, .jpeg , .jpg file types are allowed");
                }
            }
            #endregion

            #region step#3 : Validate Model and Save the data into the database

            if (ModelState.IsValid)
            {
                if (file != null)
                {
                    string targetPath = Server.MapPath("~/Content/Images");
                    ContactDbRepository.SaveImageFile(contact, file, targetPath);
                }

                ContactDbRepository.AddContact(contact); // adding and saving contact data into database

                return(RedirectToAction("AllContacts", "Home"));
            }
            #endregion

            return(View(contact));
        }
Пример #17
0
        public ActionResult Edit(Contact contact, HttpPostedFileBase file)
        {
            #region//fetching States and Countries for dropdownlist
            var allCounteries = new List <Country>();
            var allStates     = new List <State>();
            using (var dbContext = new ContactDbContext())
            {
                allCounteries = dbContext.Countries.OrderBy(c => c.CountryName).ToList();
                if (allCounteries.Count > 0)
                {
                    allStates = dbContext.States.Where(s => s.CountryId.Equals(contact.CountryId)).OrderBy(s => s.StateName).ToList();
                }
            }
            ViewBag.Countries = new SelectList(allCounteries, "CountryId", "CountryName", contact.CountryId);
            ViewBag.States    = new SelectList(allStates, "StateId", "StateName", contact.StateId);

            #endregion

            #region// Validate File
            if (file != null)
            {
                if (file.ContentLength > (512 * 1000)) //if file size > 512KB
                {
                    ModelState.AddModelError("FileErrorMessage", "File size must be within a range of 512KB");
                }

                bool isFileTypeValid = false;

                isFileTypeValid = ContactDbRepository.ValidateFileType(file);

                if (isFileTypeValid == false)
                {
                    ModelState.AddModelError("FileErrorMessage", "Only .png, .gif, .jpg , .jpeg Types are allow");
                }
            }
            #endregion

            #region //Validate Model and Save changes into the database
            if (ModelState.IsValid)
            {
                if (file != null)
                {
                    string targetPath = Server.MapPath("~/Content/Images");
                    ContactDbRepository.SaveImageFile(contact, file, targetPath);
                }

                ContactDbRepository.UpdateContact(contact, file);

                return(RedirectToAction("AllContacts", "Home"));
            }
            else
            {
                return(View(contact));
            }
            #endregion
        }
Пример #18
0
        public static ContactDbContext Create()
        {
            var options = new DbContextOptionsBuilder <ContactDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var context = new ContactDbContext(options);

            context.Database.EnsureCreated();

            var aquaman = new Contact
            {
                Id        = new Guid("735bdfd9-ffe5-4fdc-98bc-55ccdd078ec4"),
                FirstName = "Arthur",
                LastName  = "Curry",
                Email     = "*****@*****.**",
                ImageUrl  = "aquaman.jpg",
                Address   = new ContactAddress
                {
                    City    = "Atlantis City",
                    Street1 = "One Atlantis Way"
                }
            };
            var batman = new Contact
            {
                Id        = new Guid("d424facc-c58b-4cd5-bcc0-1550662fd8ef"),
                FirstName = "Bruce",
                LastName  = "Wayne",
                Email     = "*****@*****.**",
                ImageUrl  = "batman.jpg",
                Address   = new ContactAddress
                {
                    City    = "Gotham City",
                    Street1 = "The Batcave"
                }
            };
            var black_panther = new Contact
            {
                Id        = new Guid("cc0bc2ed-8c1a-4c70-8de6-e6149f099a25"),
                FirstName = "King",
                LastName  = "T'Challa",
                Email     = "*****@*****.**",
                ImageUrl  = "black_panther.jpg",
                Address   = new ContactAddress
                {
                    City    = "Central Wakanda",
                    Street1 = "The Royal Palace of Wakanda"
                }
            };

            context.Contacts.AddRange(aquaman, batman, black_panther);

            context.SaveChanges();

            return(context);
        }
Пример #19
0
        public IHttpActionResult Post([FromBody] Organization organization)
        {
            using (var ctx = new ContactDbContext())
            {
                ctx.Organizations.Add(organization);
                ctx.SaveChanges();
            }

            return(Ok());
        }
Пример #20
0
 public IList <ContactDTO> Execute()
 {
     using (var db = new ContactDbContext())
     {
         return(firstLevelQuery.GetSource(db)
                .Where(c => c.Email.Contains(Filter))
                .Select(mapper.MapContactToContactDTOExpression)
                .ToList());
     }
 }
Пример #21
0
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;

            using (var db = new ContactDbContext())
            {
                db.Database.Migrate();
            }
        }
        public static ContactDbContext CreateInMemoryDbContext()
        {
            var builder = new DbContextOptionsBuilder <ContactDbContext>();

            builder.UseInMemoryDatabase(Guid.NewGuid().ToString());
            var dbcontext = new ContactDbContext(builder.Options);

            dbcontext.Database.EnsureCreated();
            return(dbcontext);
        }
Пример #23
0
        public DbContextFixture()
        {
            Random rnd = new Random();

            rnd.Next().ToString();
            var options = new DbContextOptionsBuilder <ContactDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString()).UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking).Options;

            context = new ContactDbContext(options);
        }
Пример #24
0
 public IHttpActionResult AddPerson([FromUri] int orgId, [FromBody] Person person)
 {
     using (var ctx = new ContactDbContext())
     {
         var organization = ctx.Organizations.Single(x => x.Id == orgId);
         person.Organization = organization;
         ctx.People.Add(person);
         ctx.SaveChanges();
     }
     return(Ok());
 }
Пример #25
0
 public void Delete(int id)
 {
     using (var db = new ContactDbContext())
     {
         var contact = new Contact {
             Id = id
         };
         db.Contacts.Attach(contact);
         db.Contacts.Remove(contact);
     }
 }
        public static ContactDbContext CreateContext()
        {
            var options = new DbContextOptionsBuilder <ContactDbContext>()
                          .UseInMemoryDatabase("TestContact")
                          .Options;

            var context = new ContactDbContext(options);

            Seed(context);

            return(context);
        }
Пример #27
0
        public static ContactDbContext GetContactDbContext(string dbName)
        {
            var options = new DbContextOptionsBuilder <ContactDbContext>()
                          .UseInMemoryDatabase(databaseName: dbName)
                          .Options;

            var dbContext = new ContactDbContext(options);

            dbContext.Seed();

            return(dbContext);
        }
Пример #28
0
 public PersonListViewModel()
 {
     using (var db = new ContactDbContext())
     {
         People = new ObservableCollection <Person>(db.People.ToList());
         //var people = db.People.ToList();
         //foreach (var person in people)
         //{
         //    People.Add(person);
         //};
     };
 }
Пример #29
0
        public ContactController(ContactDbContext context)
        {
            _context = context;

            if (_context.Contacts.Count() == 0)
            {
                _context.Contacts.Add(new Contact {
                    Name = "Manoj Mohan", Phone = "9686569319", eMail = "*****@*****.**", ZipCode = "134109"
                });
                _context.SaveChanges();
            }
        }
Пример #30
0
        public static void Main()
        {
            var random = RandomDataGenerator.Instance;
            var db = new ContactDbContext();

            var contacts = new ContactInfoGenerator(random, db, 20);

            contacts.Generate();

            db.SaveChanges();

            Console.WriteLine(db.Contacts.Count());
        }
Пример #31
0
        private void btnInsert_Click(object sender, EventArgs e)
        {
            Contact contact = ReadForm();

            using (_context = new ContactDbContext())
            {
                _context.Contact.Add(contact);
                _context.Address.AddRange(contact.Address);
                _context.Date.AddRange(contact.Date);
                _context.Phone.AddRange(contact.Phone);
                _context.SaveChanges();
            }
        }
 public ContactInfoGenerator(IRandomDataGenerator random, ContactDbContext contact, int count)
     : base(random, contact, count)
 {
 }
 public DataGenerator(IRandomDataGenerator random, ContactDbContext contacts, int numberToGenerate)
 {
     this.random = random;
     this.db = contacts;
     this.count = numberToGenerate;
 }