Пример #1
0
Файл: Xxx.cs Проект: vtalas/cms
 public static void DeleteDatabaseData()
 {
     using (var db = new EfContext())
     {
         db.Database.ExecuteSqlCommand("EXEC sp_MSforeachtable @command1 = \"ALTER TABLE ? NOCHECK CONSTRAINT all\"");
         db.Database.ExecuteSqlCommand("EXEC sp_MSForEachTable @command1 = \" DELETE FROM ?\" ");
         db.Database.ExecuteSqlCommand("EXEC sp_MSForEachTable @command1 = \" ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all\" ");
     }
 }
Пример #2
0
Файл: Xxx.cs Проект: vtalas/cms
 public static void DeleteDatabaseDataGenereateSampleData()
 {
     using (var db = new EfContext())
     {
         var a = new data.EF.Initializers.SampleData(db);
         db.Database.ExecuteSqlCommand("EXEC sp_MSforeachtable @command1 = \"ALTER TABLE ? NOCHECK CONSTRAINT all\"");
         db.Database.ExecuteSqlCommand("EXEC sp_MSForEachTable @command1 = \" DELETE FROM ?\" ");
         db.Database.ExecuteSqlCommand("EXEC sp_MSForEachTable @command1 = \" ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all\" ");
         //db.Database.ExecuteSqlCommand("EXEC sp_MSForEachTable @command1 = \" IF OBJECTPROPERTY(object_id(''?''), ''TableHasIdentity'') = 1 DBCC CHECKIDENT (''?'', RESEED, 0)\" ");
         a.Generate();
     }
 }
Пример #3
0
        private static void Main(string[] args)
        {
            using (var db = new EfContext())
            {
                var roleBus = new RoleBus(db);
                var meetingBus = new MeetingBus(db);
                var userBus = new UserBus(db);

                //var permissions = new List<Permissions>
                //{
                //    Permissions.CreateMeeting,
                //    Permissions.UploadDocument
                //};
                //roleBus.Create(new Role
                //{
                //    Name = "Admin",
                //    Description = "Admin",
                //    IsActivated = true,
                //    PermissionList = permissions
                //});

                //userBus.Create(new User
                //{
                //    FullName = "Phạm Quang",
                //    Account = "quangp",
                //    Password = "******",
                //    RoleId = 2
                //});

                var meeting = new Meeting
                {
                    Name = "Quang",
                    Message = "Quang",
                    StartDate = DateTime.Now,
                    EndDate = DateTime.Now.AddDays(1),
                    UserCreatedId = 3,
                };
                //meetingBus.Create(meeting);
                //var u = userBus.Get(3);
                var m = meetingBus.Get(3);
                meetingBus.AddUsers(3, new List<int> { 3 });
            }

            Console.ReadKey();
        }
 public PosProduct(User us, Product prod)
 {
     InitializeComponent();
     context    = new EfContext();
     root       = us;
     product    = prod;
     this.Title = "Магазин - Користувач: " + root.UserName;
     if (root.Access != 1)
     {
         util.IsEnabled = false;
     }
     dateP.SelectedDate = product.Date;
     nameP.Text         = product.ProductName;
     inPriceP.Text      = product.PriceIn.ToString();
     countProdP.Text    = product.Count.ToString();
     unitProdP.Text     = product.Unit;
     markP.Text         = ((product.PriceOut - product.PriceIn) / product.PriceIn * 100).ToString();
     outPriceP.Text     = product.PriceOut.ToString();
     summaPriceP.Text   = product.Summa.ToString();
     categProdP.Text    = product.Categoryes.CategoryName;
     postProdP.Text     = prod.Suppliers.Name;
 }
Пример #5
0
        public override void Load()
        {
            var smaContext    = new EfContext(new SMAContext());
            var sannetContext = new EfContext(new SANNETContext());

            Bind <IEfRepository <Company> >().ToMethod(_ => new EfRepository <Company>(smaContext));
            Bind <IEfRepository <Quote> >().ToMethod(_ => new EfRepository <Quote>(smaContext));
            Bind <IEfRepository <Prediction> >().ToMethod(_ => new EfRepository <Prediction>(sannetContext));
            Bind <IEfRepository <NetworkConfiguration> >().ToMethod(_ => new EfRepository <NetworkConfiguration>(sannetContext));
            Bind <IDatasetRepository>().ToMethod(_ => new DatasetRepository(sannetContext));

            Bind <ICompanyService <Company> >().ToConstructor(_ => new CompanyService <Company>(Kernel.Get <IEfRepository <Company> >())).InThreadScope();
            Bind <IQuoteService <Quote> >().ToConstructor(_ => new QuoteService <Quote>(Kernel.Get <IEfRepository <Quote> >())).InThreadScope();
            Bind <IDatasetService>().ToConstructor(_ => new DatasetService(Kernel.Get <IDatasetRepository>())).InThreadScope();
            Bind <INetworkConfigurationService <NetworkConfiguration> >().ToConstructor(_ => new NetworkConfigurationService <NetworkConfiguration>(Kernel.Get <IEfRepository <NetworkConfiguration> >())).InThreadScope();
            Bind <IPredictionService <Prediction> >().ToConstructor(_ => new PredictionService <Prediction, Quote, Company, NetworkConfiguration>(Kernel.Get <IEfRepository <Prediction> >(),
                                                                                                                                                  Kernel.Get <IQuoteService <Quote> >(),
                                                                                                                                                  Kernel.Get <ICompanyService <Company> >(),
                                                                                                                                                  Kernel.Get <IDatasetService>(),
                                                                                                                                                  Kernel.Get <INetworkConfigurationService <NetworkConfiguration> >())).InThreadScope();
            Bind <ILog>().ToMethod(_ => LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType));
        }
Пример #6
0
        public EfServiceTests()
        {
            _configurationManager = new DataBaseConfigurationManager();

            _context = new EfContext(_configurationManager.ConnectionString);

            _venueRepository     = new EfRepository <Venue>(_context);
            _layoutRepository    = new EfRepository <Layout>(_context);
            _areaRepository      = new EfRepository <Area>(_context);
            _seatRepository      = new EfRepository <Seat>(_context);
            _eventRepository     = new EfRepository <Event>(_context);
            _eventAreaRepository = new EfRepository <EventArea>(_context);
            _eventSeatRepository = new EfRepository <EventSeat>(_context);

            _seatService      = new Service <Seat, SeatDto>(_seatRepository);
            _areaService      = new Service <Area, AreaDto>(_areaRepository);
            _layoutService    = new Service <Layout, LayoutDto>(_layoutRepository);
            _venueService     = new Service <Venue, VenueDto>(_venueRepository);
            _eventService     = new Service <Event, EventDto>(_eventRepository);
            _eventAreaService = new Service <EventArea, EventAreaDto>(_eventAreaRepository);
            _eventSeatService = new Service <EventSeat, EventSeatDto>(_eventSeatRepository);
        }
Пример #7
0
        public void Can_delete_Kunde_does_delete_Tickets()
        {
            var tick1 = new Ticket();
            var tick2 = new Ticket();
            var tick3 = new Ticket();

            var kunde = new Kunde();

            kunde.Tickets.Add(tick1);
            kunde.Tickets.Add(tick2);
            kunde.Tickets.Add(tick3);

            //ticket mit Kunde speichern
            using (var con = new EfContext())
            {
                con.Kunden.Add(kunde);
                con.SaveChanges();
            }

            //delete Kunde
            using (var con = new EfContext())
            {
                var loaded = con.Kunden.Find(kunde.Id);
                loaded.Tickets.Count.Should().Be(3); //verify tickets added
                con.Kunden.Remove(loaded);
                con.SaveChanges();
            }

            //test
            using (var con = new EfContext())
            {
                var loadedKunde = con.Kunden.Find(kunde.Id);
                loadedKunde.Should().BeNull();

                con.Tickets.Find(tick1.Id).Should().BeNull();
                con.Tickets.Find(tick2.Id).Should().BeNull();
                con.Tickets.Find(tick3.Id).Should().BeNull();
            }
        }
        public void EfContext_Artikel_AutoFix()
        {
            var fix = new Fixture();

            fix.Behaviors.Add(new OmitOnRecursionBehavior());

            var art = fix.Build <Artikel>().Create();

            using (var con = new EfContext())
            {
                con.Artikel.Add(art);
                con.SaveChanges();
            }

            using (var con = new EfContext())
            {
                var loaded = con.Artikel.Find(art.Id);

                loaded.Should().NotBeNull();
                loaded.Should().BeEquivalentTo(art, x => x.IgnoringCyclicReferences());
            }
        }
        public void EfContext_delete_WorkItem_should_not_delete_Process()
        {
            var p  = new Process();
            var w1 = new WorkItem()
            {
                Time = DateTime.Now
            };
            var w2 = new WorkItem()
            {
                Time = DateTime.Now
            };

            p.WorkItems.Add(w1);
            p.WorkItems.Add(w2);

            using (var con = new EfContext())
            {
                con.Processes.Add(p);
                con.SaveChanges();
            }

            using (var con = new EfContext())
            {
                var loaded = con.WorkItems.Find(w2.Id);
                loaded.Should().NotBeNull("INSERT cascade");

                con.WorkItems.Remove(loaded);
                con.SaveChanges();
            }

            using (var con = new EfContext())
            {
                var loadedWi = con.WorkItems.Find(w2.Id);
                loadedWi.Should().BeNull();

                var loadedP = con.Processes.Find(p.Id);
                loadedP.Should().NotBeNull("No DELETE cascade");
            }
        }
Пример #10
0
        public virtual List <Dollarmodel> FetchActiveJob()
        {
            string    er      = "Name=" + "Atlasdev";
            EfContext context = new EfContext(er);
            var       sql     = @"
                    SELECT 
                    Session,
                    Jobname,
                    Status,
                    Frequency,
                    Avgduration,
                    Description,
                    RunningOn 
                    FROM DollarActiveJob
                ";

            sql = string.Format(sql);

            var data = context.Database.SqlQuery <Dollarmodel>(sql).ToList();;

            return(data);
        }
        public ActionResult Get(int id)
        {
            Role retval = null;

            using (var db = new EfContext())
            {
                if (id == 99)
                {
                    if (db.Addresses.FirstOrDefault(x => x.Number.Equals(11)) == null)
                    {
                        Address ad = new Address
                        {
                            Number = 11,
                            City   = db.Cities.FirstOrDefault(x => x.ID == 1)
                        };
                        db.Addresses.Add(ad);
                        db.SaveChanges();

                        Shop s1 = new Shop
                        {
                            Name = "shop1",
                        };
                        db.Shops.Add(s1);

                        Shop s2 = new Shop
                        {
                            Name = "shop2",
                        };
                        db.Shops.Add(s2);

                        db.SaveChanges();
                    }
                }


                retval = db.Roles.FirstOrDefault(x => x.ID == id);
            }
            return(Json(retval, JsonRequestBehavior.AllowGet));
        }
        public WindowProg(User us)
        {
            InitializeComponent();

            context                   = new EfContext();
            root                      = us;
            this.Title                = "Магазин - Користувач: " + root.UserName + " (Для довідки натисніть F1)";
            dateStart                 = DateTime.Parse("01/01/2019");
            dateStop                  = DateTime.Parse(dateFirst.DisplayDate.ToString());
            dgProduct.ItemsSource     = context.Products.ToList();
            dgCategory.ItemsSource    = context.Categoryes.ToList();
            dgSupplier.ItemsSource    = context.Suppliers.ToList();
            dgSaleProduct.ItemsSource = context.SaleProducts.ToList();
            dgUtilProduct.ItemsSource = context.UtilProducts.ToList();
            if (root.Access != 1)
            {
                addProduct.IsEnabled = false;
            }
            if (context.Categoryes.Count() > 0)
            {
                categoryCount.Content = "Категорії товарів: " + context.Categoryes.Count();
            }
            if (context.Suppliers.Count() > 0)
            {
                supplierCount.Content = "Постачальники: " + context.Suppliers.Count();
            }
            if (context.Products.Count() > 0)
            {
                summ.Content = context.Products.Count() + " одиниць товару на загальну суму: " + context.Products.Sum(x => x.Summa) + "грн.";
            }
            if (context.UtilProducts.Count() > 0)
            {
                util.Content = "На суму: " + context.UtilProducts.Sum(x => x.Summa) + "грн.";
            }
            if (context.SaleProducts.Count() > 0)
            {
                sale.Content = "На суму: " + context.SaleProducts.Sum(x => x.Summa) + "грн.";
            }
        }
Пример #13
0
        public static List <string> FromWarmToCold(string location)
        {
            using (var context = new EfContext())
            {
                List <string> avgTemperatures = new List <string>();

                //väljer ut de poster beroende av vilken sträng input vi får (inne eller ute)
                //Sen grupperar vi det på datum-fältet.
                var resultSet = context.WeatherDataInfo
                                .Where(x => x.Location == location)
                                .GroupBy(x => x.DateAndTime.Date)
                                .Select(x => new { DateAndTime = x.Key, AvgTemp = x.Average(x => x.Temp) }) //Hämtar ut medeltemp för de grupperande datumen.
                                .OrderByDescending(x => x.AvgTemp);

                var topResult = resultSet
                                .Take(10);
                var bottomResult = resultSet
                                   .OrderBy(x => x.AvgTemp)
                                   .Take(10)
                                   .OrderByDescending(x => x.AvgTemp);

                InsideorOutSide(location);
                avgTemperatures.Add("Tio dagarna med högst temp");
                avgTemperatures.Add("**************************");
                foreach (var result in topResult)
                {
                    avgTemperatures.Add($"{result.DateAndTime:yyyy-MM-dd} \t {Math.Round(result.AvgTemp, 1)} °C");//skriver in värdena till strängar i listan.
                }
                avgTemperatures.Add("\n");
                avgTemperatures.Add("Tio dagarna med lägst temp");
                avgTemperatures.Add("**************************");
                foreach (var result in bottomResult)
                {
                    avgTemperatures.Add($"{result.DateAndTime:yyyy-MM-dd} \t {Math.Round(result.AvgTemp, 1)} °C");
                }
                return(avgTemperatures);
            }
        }
Пример #14
0
        public void Can_CR_Produkt_AutoFix()
        {
            var fix = new Fixture();

            fix.Behaviors.Add(new OmitOnRecursionBehavior());

            var prod = fix.Build <Produkt>().Without(x => x.Created).Without(x => x.Modified).Create();


            //Create
            using (var con = new EfContext(testConString))
            {
                con.Produkte.Add(prod);
                con.SaveChanges();
            }

            //Read
            using (var con = new EfContext(testConString))
            {
                var loaded = con.Produkte.Find(prod.Id);

                loaded.Should().BeEquivalentTo(prod, o =>
                {
                    o.Using <DateTime>(ctx => ctx.Subject.Should().BeCloseTo(ctx.Expectation)).WhenTypeIs <DateTime>();
                    o.IgnoringCyclicReferences();
                    return(o);
                });

                ////UPDATE
                //var updated = fix.Build<Produkt>().Without(x => x.Created).Without(x => x.Modified).Create();
                //updated.Id = loaded.Id;
                //con.Entry(loaded).State = System.Data.Entity.EntityState.Detached;

                //con.Produkte.Attach(updated);
                ////con.Entry(updated).State = System.Data.Entity.EntityState.Modified;
                //con.SaveChanges();
            }
        }
Пример #15
0
        public static List <string> HumidMethod(string location)
        {
            using (var context = new EfContext())
            {
                List <string> avgHumidity = new List <string>();

                var resultSet = context.WeatherDataInfo
                                .Where(x => x.Location == location)
                                .GroupBy(x => x.DateAndTime.Date)
                                .Select(x => new { DateAndTime = x.Key, AVGHumid = x.Average(x => x.Humidity) });


                var topResult = resultSet
                                .OrderByDescending(x => x.AVGHumid)
                                .Take(15);
                var bottomResult = resultSet
                                   .OrderBy(x => x.AVGHumid)            //För att få de nedersta raderna.
                                   .Take(15)
                                   .OrderByDescending(x => x.AVGHumid); //För att få de nedersta raderna i fallande ordning.

                InsideorOutSide(location);
                avgHumidity.Add("Tio dagarna med högst fuktighet");
                avgHumidity.Add("*******************************");
                foreach (var result in topResult)
                {
                    avgHumidity.Add($"{result.DateAndTime:yyyy-MM-dd} \t {Math.Round(result.AVGHumid, 1)} %");
                }
                avgHumidity.Add("\n");
                avgHumidity.Add("Tio dagarna med lägst fuktighet");
                avgHumidity.Add("*******************************");

                foreach (var result in bottomResult)
                {
                    avgHumidity.Add($"{result.DateAndTime:yyyy-MM-dd} \t {Math.Round(result.AVGHumid, 1)} %");
                }
                return(avgHumidity);
            }
        }
Пример #16
0
        public ActionResult AddProductToSlider(int thisprodid = 0, string name = "", string description = "", string image = "", string prodid = "")
        {
            using (EfContext ctx = new EfContext())
            {
                int prodId  = 0; Int32.TryParse(prodid, out prodId);
                var product = ctx.TopProducts.FirstOrDefault(q => q.Id == prodId);
                product.Name        = name;
                product.Description = description;
                if (image != "")
                {
                    var delpath = System.AppDomain.CurrentDomain.BaseDirectory;

                    if (System.IO.File.Exists(delpath + "\\Image\\" + product.Image))
                    {
                        System.IO.File.Delete(delpath + "\\Image\\" + product.Image);
                    }


                    string base64 = image;
                    byte[] bytes  = Convert.FromBase64String(base64.Split(',')[1]);
                    Bitmap bmp;
                    using (var ms = new MemoryStream(bytes))
                    {
                        bmp = new Bitmap(ms);
                    }
                    string path = Server.MapPath("/Image/");
                    //540*690
                    Bitmap imageBig = Utils.CreateImage(bmp, 1920, 1080);
                    string NameImg  = Guid.NewGuid() + ".png";
                    string filePath = path + NameImg;
                    imageBig.Save(filePath, ImageFormat.Jpeg);
                    product.Image = NameImg;
                }
                product.ProductId = thisprodid;
                ctx.SaveChanges();
                return(Content(""));
            }
        }
Пример #17
0
        private static void SetupFetchMultipleChain(List <Test> tests)
        {
            const string TestName = "Fetch Multiple Chained Collections";

            // add dashing
            tests.Add(
                new Test(
                    Providers.Dashing,
                    TestName,
                    i => {
                using (var dashingSession = dashingConfig.BeginSession()) {
                    return(dashingSession.Query <Blog>().FetchMany(b => b.Posts).ThenFetch(p => p.Tags).SingleOrDefault(b => b.BlogId == i / 5));
                }
            }));

            // add dashing without transaction
            tests.Add(
                new Test(
                    Providers.Dashing,
                    TestName,
                    i => {
                using (var dashingSession = dashingConfig.BeginTransactionLessSession()) {
                    return(dashingSession.Query <Blog>().FetchMany(b => b.Posts).ThenFetch(p => p.Tags).SingleOrDefault(b => b.BlogId == i / 5));
                }
            },
                    "without Transaction"));

            // add EF
            tests.Add(
                new Test(
                    Providers.EntityFramework,
                    TestName,
                    i => {
                using (var EfDb = new EfContext()) {
                    return(EfDb.Blogs.Include(b => b.Posts.Select(p => p.Tags)).SingleOrDefault(b => b.BlogId == i / 5));
                }
            }));
        }
Пример #18
0
        public static void ReadCSVFile(string filePath)
        {
            //Samlar alla rader i filen till en sträng-array.
            string[] resultSet = File.ReadAllLines(filePath);
            using (var context = new EfContext())
            {
                //loopar alla poster i tabellen, tolkar datatyperna och sätter värdet på alla fällt för alla poster.
                foreach (var data in resultSet)
                {
                    WeatherData wdInfo   = new WeatherData();
                    string[]    wdString = data.Split(",");
                    wdInfo.DateAndTime = DateTime.Parse(wdString[0]);
                    wdInfo.Location    = wdString[1];
                    wdInfo.Temp        = decimal.Parse(wdString[2], CultureInfo.InvariantCulture);
                    wdInfo.Humidity    = int.Parse(wdString[3], CultureInfo.InvariantCulture);

                    //lägg till posterna till tabelln i databasen.
                    context.Add(wdInfo);
                }
                //sparar ändringar i databasen.
                context.SaveChanges();
            }
        }
Пример #19
0
        public void EfContext_can_add_Patient()
        {
            var p = new Patient()
            {
                Name       = $"Fred_{Guid.NewGuid()}",
                GebDatum   = DateTime.Now.AddYears(-50),
                Geschlecht = Geschlecht.Männlich,
                Adresse    = "Steinstr. 12"
            };

            using (var con = new EfContext())
            {
                con.Patienten.Add(p);
                con.SaveChanges();
            }

            using (var con = new EfContext())
            {
                var loaded = con.Patienten.Find(p.Id);
                Assert.IsNotNull(loaded);
                Assert.AreEqual(p.Name, loaded.Name);
            }
        }
Пример #20
0
        private static void MergeTemperatureControlledZone(ZoneSaverInput input, EfContext c, Domain.Zone zone)
        {
            if (input.TemperatureSensorId.HasValue)
            {
                zone.TemperatureControlledZone = zone.TemperatureControlledZone ?? new Domain.TemperatureControlledZone
                {
                    LowSetPoint             = 4.0f,
                    HighSetPoint            = 20.0f,
                    Hysteresis              = 0.5f,
                    ScheduleDefaultSetPoint = 4.0f
                };

                zone.TemperatureControlledZone.TemperatureSensor   = c.TemperatureSensors.Find(input.TemperatureSensorId.Value);
                zone.TemperatureControlledZone.TemperatureSensorId = zone.TemperatureControlledZone.TemperatureSensor.TemperatureSensorId;
            }
            else if (zone.TemperatureControlledZone != null)
            {
                c.Remove(zone.TemperatureControlledZone);

                zone.TemperatureControlledZoneId = null;
                zone.TemperatureControlledZone   = null;
            }
        }
Пример #21
0
        public ActionResult Index(Admin admin)
        {
            SHA1   sha1     = new SHA1CryptoServiceProvider();
            string password = admin.AdminPassword;
            string result   = Convert.ToBase64String(sha1.ComputeHash(Encoding.UTF8.GetBytes(password)));

            admin.AdminPassword = result;

            EfContext context       = new EfContext();
            var       adminUserInfo = context.Admins.FirstOrDefault(x => x.AdminUserName == admin.AdminUserName &&
                                                                    x.AdminPassword == result);


            if (adminUserInfo != null)
            {
                FormsAuthentication.SetAuthCookie(adminUserInfo.AdminUserName, false);
                Session["AdminUserName"] = adminUserInfo.AdminUserName;
                return(RedirectToAction("Index", "AdminCategory"));
            }

            ViewBag.ErrorMessage = "Kullanıcı Adı veya Şifreniz Yanlış!";
            return(View());
        }
Пример #22
0
        public void EfContext_can_add_Patient_AutoFixture_FluentAssertions()
        {
            var fix = new Fixture();

            fix.Behaviors.Add(new OmitOnRecursionBehavior());

            var p = fix.Create <Patient>();

            using (var con = new EfContext())
            {
                con.Patienten.Add(p);
                con.SaveChanges();
            }

            using (var con = new EfContext())
            {
                var loaded = con.Patienten.Find(p.Id);
                loaded.Should().NotBeNull();     //Assert.IsNotNull(loaded);
                loaded.Name.Should().Be(p.Name); // Assert.AreEqual(p.Name, loaded.Name);

                loaded.Should().BeEquivalentTo(p, x => x.IgnoringCyclicReferences());
            }
        }
Пример #23
0
        private static List <string> MetrologicalSeasonFall()
        {
            List <string> dates = new List <string>();

            using (var context = new EfContext())
            {
                var q1 = context.WeatherDataInfo
                         .Where(x => x.Location == "Ute" && x.DateAndTime > DateTime.Parse("2016-08-01"))
                         .GroupBy(x => x.DateAndTime.Date)
                         .Select(x => new { day = x.Key, tempAVG = x.Average(x => x.Temp) });

                var q2 = q1
                         .OrderBy(x => x.day);

                int turnCounter = 0;

                foreach (var wd in q2)
                {
                    if (wd.tempAVG < 10)
                    {
                        turnCounter++;
                        //Console.WriteLine(wd.day + " " + wd.tempAVG);
                        dates.Add($"{wd.day:yyyy/MM/dd} | {Math.Round(wd.tempAVG, 1)}");
                        if (turnCounter == 5)
                        {
                            return(dates);
                        }
                    }
                    else
                    {
                        dates.Clear();
                        turnCounter = 0; //The count starts over.
                    }
                }
                return(dates);
            }
        }
Пример #24
0
        private static bool MetrologicalSeasonWinter()
        {
            using (var context = new EfContext())
            {
                var q1 = context.WeatherDataInfo
                         .Where(x => x.Location == "Ute" && x.DateAndTime > DateTime.Parse("2016-08-01"))
                         .GroupBy(x => x.DateAndTime.Date)
                         .Select(x => new { day = x.Key, TempAvg = x.Average(x => x.Temp) });

                int turnCounter = 0;
                foreach (var wd in q1)
                {
                    if (wd.TempAvg <= 0)
                    {
                        turnCounter++;
                        //lika med 5 så returnerar vi true och skriver ut en sträng med aktuellt datum.
                        if (turnCounter == 5)
                        {
                            Console.WriteLine(wd.day + " " + wd.TempAvg);
                            return(true);
                        }
                    }
                    else
                    {
                        //Räkningen startar om.
                        turnCounter = 0;
                    }
                }
                //går vi ur loopen och turnCounter inte gått upp till 5 fanns det inga datum som uppfyllde vilkåren.
                //returneras false hittades inget datum.
                if (turnCounter == 0)
                {
                    Console.WriteLine("Inget datum hittades");
                }
                return(false);
            }
        }
Пример #25
0
        private static DateTime MetrologicalSeasonWinter()
        {
            using (var context = new EfContext())
            {
                var q1 = context.WeatherDataInfo
                         .Where(x => x.Location == "Ute" && x.DateAndTime > DateTime.Parse("2016-08-01"))
                         .GroupBy(x => x.DateAndTime.Date)
                         .Select(x => new { day = x.Key, tempAVG = x.Average(x => x.Temp) });

                var q2 = q1
                         .OrderBy(x => x.day);



                int turnCounter = 0;

                foreach (var wd in q2)
                {
                    if (wd.tempAVG <= 0)
                    {
                        turnCounter++;

                        if (turnCounter == 5)
                        {
                            Console.WriteLine(wd.day + " " + wd.tempAVG);
                            return(wd.day);
                        }
                    }
                    else
                    {
                        turnCounter = 0; //The count starts over.
                    }
                }
                return(DateTime.Parse("2099-12-12")); //Data for winter season not found.
            }
        }
Пример #26
0
        public ContentResult GetSelected(string idgroup = "")
        {
            int idGroup = 0; Int32.TryParse(idgroup, out idGroup);

            using (EfContext ctx = new EfContext())
            {
                // var a = ctx.GlobalGroups.Select(k=>k.Groups.FirstOrDefault(j=>j.Name==group)).Select(dd=>dd.Id);


                //var groupid = ctx.GlobalGroups.Where(g => g.Id == idGlobalGroup).Select(p => p.Groups.FirstOrDefault(j => j.Name == group).Id).ToList().FirstOrDefault();
                MapSelectData msd = new MapSelectData();

                msd.Brends      = ctx.Products.Where(j => j.Group.Id == idGroup && j.InStock == true).Where(d => (d.Brend.Name != "" ? true : false)).Select(p => p.Brend.Name).Distinct().ToList();
                msd.Countryes   = ctx.Products.Where(j => j.Group.Id == idGroup && j.InStock == true).Where(d => (d.Country.Name != "" ? true : false)).Select(p => p.Country.Name).Distinct().ToList();
                msd.Fillers     = ctx.Products.Where(j => j.Group.Id == idGroup && j.InStock == true).Where(d => (d.Filler.Name != "" ? true : false)).Select(p => p.Filler.Name).Distinct().ToList();
                msd.Materials   = ctx.Products.Where(j => j.Group.Id == idGroup && j.InStock == true).Where(d => (d.Material.Name != "" ? true : false)).Select(p => p.Material.Name).Distinct().ToList();
                msd.TypeClothes = ctx.Products.Where(j => j.Group.Id == idGroup && j.InStock == true).Where(d => (d.TypeCloth.Name != "" ? true : false)).Select(p => p.TypeCloth.Name).Distinct().ToList();
                msd.Specials    = ctx.Products.Where(j => j.Group.Id == idGroup && j.InStock == true).Where(d => (d.Special.Name != "" ? true : false)).Select(p => p.Special.Name).Distinct().ToList();


                string json = JsonConvert.SerializeObject(msd);
                return(Content(json, "application/json"));
            }
        }
Пример #27
0
        public ActionResult GetBasketProduct(string[] id)
        {
            id = id[0].Split(',');
            int               temp       = 0;
            Mapper            mapper     = new Mapper();
            List <MapProduct> mapProduct = new List <MapProduct>();

            if (id.Length >= 1)
            {
                using (EfContext ctx = new EfContext())
                {
                    foreach (var value in id)
                    {
                        Int32.TryParse(value, out temp);
                        var product = ctx.Products.FirstOrDefault(q => q.Id == temp);

                        mapProduct.Add(mapper.MappingProduct(product));
                    }
                }
            }
            string json = JsonConvert.SerializeObject(mapProduct);

            return(Content(json, "application/json"));
        }
        public void can_create_read_testdata_with_autofixture()
        {
            var fix = new Fixture();

            //fix.Customize<Stock>(x => x.Without(y => y.Id));
            //fix.Customize<Storage>(x => x.Without(y => y.Id));
            //fix.Customize<Bulk>(x => x.Without(y => y.Id));
            //fix.Customize<Section>(x => x.Without(y => y.Id));

            fix.Behaviors.Add(new OmitOnRecursionBehavior());

            var stock = fix.Build <Stock>().Create <Stock>();

            using (var con = new EfContext())
            {
                con.Stocks.Add(stock);
                con.SaveChanges();
            }

            using (var con = new EfContext())
            {
                var loaded = con.Stocks.Find(stock.Id);
                loaded.Should().BeEquivalentTo(stock, x => x.IgnoringCyclicReferences());
            }


            //Stock loadedOhneLL;
            //using (var con = new EfContext())
            //{

            //    loadedOhneLL = con.Stocks.Include(x => x.Sections)
            //                             .Include(x => x.Sections.Select(y => y.Storages))
            //                             .FirstOrDefault(x => x.Id == stock.Id);
            //}
            //loadedOhneLL.Should().BeEquivalentTo(stock, x => x.IgnoringCyclicReferences());
        }
Пример #29
0
        static void Main(string[] args)
        {
            var efContext          = new EfContext();
            var productsRepository = new ProductsRepository(efContext);

            productsRepository.InitializeMockData();
            var mediator        = new Mediator(productsRepository);
            var actionsRegistry = new ActionsRegistry(mediator);

            while (true)
            {
                Console.Write("\nCommand: ");

                var command = Console.ReadLine();
                if (string.IsNullOrWhiteSpace(command))
                {
                    WriteError("Please choose command, query or pass 'exit' to leave an application.");
                    continue;
                }

                if (command.ToLower() == "exit")
                {
                    break;
                }

                try
                {
                    actionsRegistry.Run(command);
                    WriteSuccess();
                }
                catch (Exception e)
                {
                    WriteError(e.Message);
                }
            }
        }
Пример #30
0
        public void EfContext_can_add_Episode()
        {
            var ep = new Episode()
            {
                Season = 7,
                Title  = $"Testfolge_{Guid.NewGuid()}",
                Length = TimeSpan.FromMinutes(111)
            };


            using (var con = new EfContext())
            {
                con.Episodes.Add(ep);
                int result = con.SaveChanges();

                Assert.AreEqual(1, result);
            }

            using (var con = new EfContext())
            {
                var loaded = con.Episodes.Find(ep.Id);
                Assert.AreEqual(ep.Title, loaded.Title);
            }
        }
 public AddProduct(User us)
 {
     InitializeComponent();
     context    = new EfContext();
     root       = us;
     this.Title = "Магазин(Новий товар) - Користувач: " + root.UserName;
     if (context.Categoryes.Count() != 0)
     {
         categProd.ItemsSource = context.Categoryes.Select(x => x.CategoryName).ToList();
     }
     else
     {
         categProd.ItemsSource = "";
     }
     if (context.Suppliers.Count() != 0)
     {
         postProd.ItemsSource = context.Suppliers.Select(x => x.Name).ToList();
     }
     else
     {
         postProd.ItemsSource = "";
     }
     nameProd.Focus();
 }
Пример #32
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, EfContext efContext)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
                {
                    HotModuleReplacement = true
                });
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            app.UseStatusCodePagesWithRedirects("/error");

            AddTestData(efContext);
        }
Пример #33
0
        public virtual List <AtlaserrorModel> FetchErrorList(string server)
        {
            string    er      = "Name=" + server;
            EfContext context = new EfContext(er);
            var       sql     = @"
                    SELECT 
                    UniqueIDError,
                    Description ,
                    CAST(SysBeginDateTime AS varchar(max)) as SysBeginDateTime,
                    MachineName ,                    
                    AppName ,
                    TransactionID ,
                    BucketID
                    FROM tblError e WITH(NOLOCK)
                    WHERE SysBeginDateTime >(SELECT CAST(GETDATE() as DATE))                    
                    ORDER BY e.SysBeginDateTime DESC
                ";

            sql = string.Format(sql);

            var data = context.Database.SqlQuery <AtlaserrorModel>(sql).ToList();;

            return(data);
        }
Пример #34
0
 public UnitOfWork()
 {
     _context = IoC.Resolve<EfContext>();
 }
        public static void Init()
        {
            using (var db = new EfContext())
            {
                if (db.Accounts.Any())
                    return;

                var account = new Account
                {
                    Name = "My Test Account",
                    Paid = true,
                    PaidUtc = new DateTime(2016, 1, 1),
                };
                db.Accounts.Add(account);
                var user = new User
                {
                    Name = "Joe User",
                    Account = account,
                    Active = true,
                };
                db.Users.Add(user);
                var account2 = new Account
                {
                    Name = "Another Test Account",
                    Paid = false,
                };
                db.Accounts.Add(account2);
                var user2 = new User
                {
                    Name = "Late Paying User",
                    Account = account2
                };
                db.Users.Add(user2);
                db.MutateMes.Add(new MutateMe());

                var human = new Human
                {
                    Id = 1,
                    Name = "Han Solo",
                    Height = 5.6430448
                };
                db.Heros.Add(human);
                var stormtrooper = new Stormtrooper
                {
                    Id = 2,
                    Name = "FN-2187",
                    Height = 4.9,
                    Specialization = "Imperial Snowtrooper"
                };
                db.Heros.Add(stormtrooper);
                var droid = new Droid
                {
                    Id = 3,
                    Name = "R2-D2",
                    PrimaryFunction = "Astromech"
                };
                db.Heros.Add(droid);
                var vehicle = new Vehicle
                {
                    Id = 1,
                    Name = "Millennium falcon",
                    Human = human
                };
                db.Vehicles.Add(vehicle);
                
                var vehicle2 = new Vehicle
                {
                    Id = 2,
                    Name = "Speeder bike",
                    Human = stormtrooper
                };
                db.Vehicles.Add(vehicle2);
                
                db.SaveChanges();
            }
        }
Пример #36
0
 //static readonly ILog Log = LogManager.GetLogger<SampleData>();
 public SampleData(EfContext context)
 {
     Context = context;
     SecurityProvider.EnsureInitialized(true);
 }
 public EfContext Get()
 {
     return dataContext ?? (dataContext = new EfContext());
 }