예제 #1
0
        public string DeleteCustomer(int customerId)
        {
            try
            {
                using (var context = new BAEntities())
                {
                    var customerToDelete = (from cust in context.Contacts.OfType <Customer>()
                                            .Include("Reservations")
                                            where cust.ContactID == customerId
                                            select cust).Single();

                    var reservationsToDelete = customerToDelete.Reservations.ToList();

                    foreach (Reservation r in reservationsToDelete)
                    {
                        context.DeleteObject(r);
                    }

                    context.DeleteObject(customerToDelete);
                    context.SaveChanges();
                    return("Success");
                }
            }
            catch (Exception ex)
            {
                string errorMessage = null;
                //TODO: construct a message to return to the client
                return(errorMessage);
            }
        }
예제 #2
0
 private static void ConcurrencyVariousEntities()
 {
     using (var context = new BAEntities())
     {
         var add = context.Addresses.Include("Contact").First();
         add.Contact.FirstName = new String(add.Contact.FirstName.Trim().Reverse().ToArray());
         var con = context.Contacts.First();
         con.FirstName = new String(con.FirstName.Trim().Reverse().ToArray());
         var pmts = context.Payments.OrderBy("it.amount").Take(2);
         foreach (var p in pmts)
         {
             p.Amount += 1;
         }
         _persistedEntriesList = new List <PersistedStateEntry>();
         SaveMyChanges(context);
         if (_persistedEntriesList.Count > 0)
         {
             foreach (var e in _persistedEntriesList)
             {
                 var ent = e.NewEntityFromOrig(context.MetadataWorkspace);
                 context.Attach(ent);
                 context.ApplyPropertyChanges(e.EntitySetName, e.DetachedEntity);
             }
         }
     }
 }
예제 #3
0
 public List <BAGA.CustomerNameAndID> GetCustomerPickList()
 {
     using (BAEntities context = new BAEntities())
     {
         return(context.CustomerNameAndIDs.OrderBy(c => c.LastName + c.FirstName).ToList());
     }
 }
예제 #4
0
        static void TestDynamicGraphCreation()
        {
            Reservation res;

            using (var context = new BAEntities())
            {
                //test by querying for a reservation then dynamically creating a new payment
                //adding the payment to the reservation and finally saving the changes
                //the AddChildtoParentObject has no understanding of the model or classes
                //that it is wroking with.
                var query = context.Reservations;
                query.MergeOption = MergeOption.NoTracking;
                res = query.OrderBy("it.ReservationID").Skip(1).FirstOrDefault();
                var kvpParent = new KeyValuePair <string, int>("ReservationID", res.ReservationID);
                KeyValuePair <string, object>[] kvpChildValues =
                {
                    new KeyValuePair <string, object>("PaymentDate", DateTime.Now),
                    new KeyValuePair <string, object>("Amount",      (Decimal)400)
                };
                if (AddChildtoParentObject <Reservation, Payment>
                        (context, kvpParent, kvpChildValues))
                {
                    context.SaveChanges();
                }
            }
        }
예제 #5
0
        public ActionResult Login(t_admin user)
        {
            BAEntities usersEntities = new BAEntities();
            int?       userId        = usersEntities.ValidateUser(user.email, user.password).FirstOrDefault();

            string message = string.Empty;

            switch (userId.Value)
            {
            case -1:
                message = "Username and/or password is incorrect.";
                break;

            case -2:
                message = "Account has not been activated.";
                break;

            default:
                FormsAuthentication.SetAuthCookie(user.email, user.RememberMe);
                return(RedirectToAction("Index", "Admin"));
            }

            ViewBag.Message = message;
            return(View(user));
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            context      = new BAEntities();
            activities   = context.Activities.OrderBy(a => a.Name).ToList();
            destinations = context.Destinations.OrderBy(d => d.Name).ToList();
            lodgings     = context.Lodgings.OrderBy(l => l.LodgingName).ToList();
            //trips = context.Trips.Include("Activities").OrderBy("it.Destination.Name").ToList();
            trips = new ObservableCollection <Trip>(
                context.Trips.Include("Activities")
                .OrderBy("it.Destination.Name"));

            System.Windows.Data.CollectionViewSource tripViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("tripViewSource")));
            //// Load data by setting the CollectionViewSource.Source property:
            tripViewSource.Source = trips;

            System.Windows.Data.CollectionViewSource destinationViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("destinationViewSource")));
            //// Load data by setting the CollectionViewSource.Source property:
            destinationViewSource.Source = destinations;

            System.Windows.Data.CollectionViewSource lodgingViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("lodgingViewSource")));
            // Load data by setting the CollectionViewSource.Source property:
            lodgingViewSource.Source = lodgings;

            activityComboBox.ItemsSource = activities;
            EditSortDescriptions(SortAction.Add);
        }
예제 #7
0
        public string InsertCustomer(BAGA.Customer cust)
        {
            if (cust.CustomerTypeID == 0)
            {
                cust.CustomerTypeID = 1;
            }

            cust.AddDate = DateTime.Now.AddYears(-1);
            try
            {
                using (var context = new BAEntities())
                {
                    RemoveTripsFromGraph(cust);
                    context.Contacts.AddObject(cust);
                    context.SaveChanges();
                }
                return(cust.ContactID.ToString());
            }
            catch (Exception ex)
            {
                string errorMessage = null;
                //TODO: construct a message to return to the client
                return(errorMessage);
            }
        }
        private static void InvokePreCompiledQuery()
        {
            //only compile the query if it hasn't already been compiled. When it's been
            //compiled, the Func (_customersFromCountry) will NOT be null

            if (_customersFromCountry == null)
            {
                _customersFromCountry = CompiledQuery.Compile <BAEntities, string, IQueryable <Customer> >
                                            ((BAEntities ctx, string dest) =>
                                            from Customer c in ctx.Contacts.OfType <Customer>()
                                            where c.Reservations.FirstOrDefault().Trip.Destination.Name == dest
                                            select c);
            }

            var context = new BAEntities();
            var loc     = "Malta";
            IQueryable <Customer> custs = _customersFromCountry.Invoke(context, loc);
            var custlist = custs.ToList();

            Console.WriteLine("{0} Customer Count = {1}", loc, custlist.Count);

            loc      = "Vermont";
            custs    = _customersFromCountry.Invoke(context, loc);
            custlist = custs.ToList();
            Console.WriteLine("{0} Customer Count = {1}", loc, custlist.Count);

            loc      = "Australia";
            custs    = _customersFromCountry.Invoke(context, loc);
            custlist = custs.ToList();
            Console.WriteLine("{0} Customer Count = {1}", loc, custlist.Count);

            Console.WriteLine("Press any key to continue....");
            Console.ReadKey();
        }
예제 #9
0
 private static void CallObjectStateEntryVisualizer()
 {
     using (BAEntities context = new BAEntities())
     {
         //get a random entity
         var address = context.Addresses.FirstOrDefault();
         context.VisualizeEntityState(address);
     }
 }
예제 #10
0
        public void Can_A_Contact_With_An_Address_EagerLoad()
        {
            var context = new BAEntities();

            context.ContextOptions.LazyLoadingEnabled = false;
            var contact = context.Contacts.Include("Addresses").Where(c => c.Addresses.Any()).FirstOrDefault();

            Assert.IsNotNull(contact);
            Assert.IsTrue(contact.Addresses.Count > 0);
        }
예제 #11
0
 public List <Trip> GetUpcomingTrips()
 {
     using (BAEntities context = new BAEntities())
     {
         //lazyloading will create major problems during serialization, so turning it off
         context.ContextOptions.LazyLoadingEnabled = false;
         return(context.Trips.Include("Destination")
                .Where(t => t.StartDate > DateTime.Today).ToList());
     }
 }
예제 #12
0
 private static void InsertContactToTestSaveChangesCustomization()
 {
     using (var context = new BAEntities())
     {
         var contact  = Contact.CreateContact("Funny", "Name-Here");
         var customer = new Customer();
         customer.Contact = contact;
         context.Customers.AddObject(customer);
         context.SaveChanges();
     }
 }
예제 #13
0
 static void PopulateForecastandQueryLodgings()
 {
     GetGoogleWeather();  //create xml file with forecast info
     using (var context = new BAEntities())
     {
         var lodgings = context.Lodgings.Take(3).ToList();
         foreach (var l in lodgings)
         {
             Console.WriteLine("{0}: Forecast = {1}", l.LodgingName.Trim(), l.TomorrowForecast);
         }
         Console.WriteLine("Press any key to continue...");
         Console.ReadKey();
     }
 }
예제 #14
0
 public BAGA.Customer GetCustomer(int customerId)
 {
     using (var context = new BAEntities())
     {
         //lazyloading will create major problems during serialization so turning it off
         context.ContextOptions.LazyLoadingEnabled = false;
         var cust =
             from c in context.Contacts.OfType <Customer>()
             .Include("Reservations.Trip.Destination")
             where c.ContactID == customerId
             select c;
         return(cust.Single());
     }
 }
예제 #15
0
        private static void DeleteReservations(BAEntities context, List <int> reservationsToDelete)
        {
            if (null != reservationsToDelete)
            {
                var query = from reservation in context.Reservations
                            join reservationId in reservationsToDelete
                            on reservation.ReservationID equals reservationId
                            where reservation.Payments.Count == 0
                            select reservation;


                foreach (var reservation in query)
                {
                    context.DeleteObject(reservation);
                }
            }
        }
 public void GetCustomers()
 {
     if (_context == null)
     {
         _context = new BAEntities();
     }
     //put a lock on the context during this operation;
     lock (_context)
     {
         var contactquery = from c in _context.Contacts
                            where c.LastName.StartsWith("S")
                            select c;
         _conList = contactquery.ToList();
     }
     if (_callback != null)
     {
         _callback(_conList);
     }
 }
        public static void EmailThreadingSample()
        {
            var emailThread = new EmailThreadClass();

            using (var context = new BAEntities())
            {
                var custs =
                    from cust in context.Contacts.OfType <Customer>()
                    .Include("Reservations.Trip.Destination")
                    select cust;
                foreach (var cust in custs)
                {
                    if (cust.Reservations
                        .Any(r => r.Trip.StartDate > DateTime.Today.AddDays(6)))
                    {
                        //new thread for upcoming trip emails
                        var workerThread =
                            new Thread(emailThread.UpcomingTripEmails);
                        workerThread.Start(cust);
                    }
                    else if (cust.Reservations
                             .Any(r => r.Trip.StartDate > DateTime.Today
                                  & r.Trip.StartDate <= DateTime.Today.AddDays(6)))
                    {
                        //new thread for very soon trip emails
                        var workerThread = new Thread(emailThread.NextWeek);
                        workerThread.Start(cust);
                    }
                    else //no future trips
                    {
                        //new thread for no upcmoing trips emails
                        var workerThread =
                            new Thread(emailThread.ComeBackEmails);
                        workerThread.Start(cust);
                    }
                }
                Console.WriteLine("Complete...");
                Console.ReadKey();
            }
        }
예제 #18
0
        public string UpdateCustomer(CustomerUpdate customerUpdate)
        {
            try
            {
                var modifiedCustomer = customerUpdate.Customer;
                using (var context = new BAEntities())
                {
                    RemoveTripsFromGraph(modifiedCustomer);
                    context.Contacts.Attach(modifiedCustomer);
                    context.ObjectStateManager.ChangeObjectState(modifiedCustomer, EntityState.Modified);
                    //Code for Existing and New Reservations will go here;
                    context.ContextOptions.LazyLoadingEnabled = false;
                    foreach (var res in modifiedCustomer.Reservations)
                    {
                        if (res.ReservationID > 0)
                        {
                            context.ObjectStateManager.ChangeObjectState(res, EntityState.Modified);
                        }
                        else
                        {
                            context.ObjectStateManager.ChangeObjectState(res, EntityState.Added);
                        }
                    }
                    context.ContextOptions.LazyLoadingEnabled = true;
                    //Code for Deleted Reservations will go here;
                    List <int> deleteResIDs = customerUpdate.ReservationsToDelete;

                    DeleteReservations(context, deleteResIDs);

                    context.SaveChanges();
                }
                return("Success");
            }
            catch (Exception ex)
            {
                return("Error: " + ex.Message);
            }
        }
예제 #19
0
        private static void DynamicEsqlTest()
        {
            using (var context = new BAEntities())
            {
                var eSql    = SingleEntityEsql <Reservation>(90, context);
                var query   = context.CreateQuery <DbDataRecord>(eSql);
                var results = query.Execute(MergeOption.AppendOnly);

                foreach (IExtendedDataRecord record in results)
                {
                    var fieldMetadata = record.DataRecordInfo.FieldMetadata;

                    for (int i = 0; i < record.FieldCount; i++)
                    {
                        //If the navigation property is an Entity, list its fields.
                        switch (fieldMetadata[i].FieldType.TypeUsage.
                                EdmType.BuiltInTypeKind)
                        {
                        case BuiltInTypeKind.EntityType:
                            DisplayFields(((EntityObject)(record[i])).EntityKey, context);
                            break;

                        case BuiltInTypeKind.CollectionType:
                        {
                            var collection = (System.Collections.ICollection)(record[i]);
                            foreach (EntityObject entity in collection)
                            {
                                DisplayFields(entity.EntityKey, context);
                            }
                        }
                        break;
                        }
                    }
                    Console.WriteLine("Press any key to continue...");
                    Console.ReadKey();
                }
            }
        }
예제 #20
0
        private static void UpdateEntitiesandRelationships()
        {
            using (var context = new BAEntities())
            {
                var con = context.Contacts.First();
                con.FirstName = new String(con.FirstName.Trim().Reverse().ToArray());
                var pmt = context.Payments.FirstOrDefault();
                pmt.ReservationReference.EntityKey = new EntityKey("BAEntities.Reservations", "ReservationID", 13);
                //'Dim oses = context.ObjectStateManager.GetObjectStateEntries
                SaveMyChanges(context);

                if (_persistedEntriesList.Count > 0)
                {
                    foreach (var e in _persistedEntriesList)
                    {
                        var ent = e.NewEntityFromOrig(context.MetadataWorkspace);
                        context.Attach(ent);
                        context.ApplyPropertyChanges(e.EntitySetName, e.DetachedEntity);
                    }
                }
                SaveMyChanges(context);
            }
        }
예제 #21
0
 public DataBridge2()
 {
     _context    = new BAEntities();
     _tripBridge = new TripBridge(_context);
 }
 public TripBridge(BAEntities context)
 {
     _context = context;
 }
예제 #23
0
        static void GetGoogleWeather()
        {
            var forecasts = new List <LodgingForecast>();

            using (var context = new BAEntities())
            {
                var lodgingCityCountry = from l in context.Lodgings
                                         select new
                {
                    l.LodgingID,
                    l.Contact.Addresses.FirstOrDefault().City,
                    l.Contact.Addresses.FirstOrDefault().StateProvince,
                    l.Contact.Addresses.FirstOrDefault().CountryRegion
                };
                foreach (var l in lodgingCityCountry)
                {
                    string uri;
                    if ((l.StateProvince == null && l.City == null && l.CountryRegion == null) == false)
                    {
                        string region;
                        if (l.CountryRegion != null)
                        {
                            region = "," + l.CountryRegion.Trim();
                        }
                        else
                        {
                            region = "";
                        }


                        if (l.StateProvince != null)
                        {
                            uri = "http://www.google.com/ig/api?weather=" + l.City.Trim() + "," + l.StateProvince.Trim() + region;
                        }
                        else
                        {
                            uri = "http://www.google.com/ig/api?weather=" + l.City.Trim() + region;
                        }
                        XElement googleRSS = XElement.Load(uri);
                        var      items     = from item in googleRSS.Elements("weather")
                                             .Elements("forecast_conditions")
                                             select item;
                        if (items.Count() > 0)
                        {
                            var tomorrow = items.ToList()[1];
                            forecasts.Add(new LodgingForecast
                            {
                                LodgingId = l.LodgingID,
                                Forecast  = (String)tomorrow.Element("condition").Attribute("data").Value
                                            + ", Low: " + (String)tomorrow.Element("low").Attribute("data").Value
                                            + ", High: " + (String)tomorrow.Element("high").Attribute("data").Value
                            });
                        }
                    }
                }
                var forecastsXml = new XElement("Forecasts",
                                                from f in forecasts
                                                select new XElement("Lodging",
                                                                    new XAttribute("ID", f.LodgingId),
                                                                    new XAttribute("forecast", f.Forecast)));

                var doc = new XDocument(
                    new XDeclaration("1.0", "utf-8", "yes"),
                    new XComment("LodgingForecasts"), forecastsXml);
                doc.Save(@"LodgingForecasts.xml");
            }
        }