Example #1
0
        public ActionResult Details(int id)
        {
            IPFinalDBDataContext finalDB = new IPFinalDBDataContext();

            DataLoadOptions ds = new DataLoadOptions();
            ds.LoadWith<Work_Package>(wp => wp.Package_Softwares);
            ds.LoadWith<Package_Software>(ps => ps.Software_Requirement);
            finalDB.LoadOptions = ds;

            var pack = (from p in finalDB.Work_Packages
                        where p.id == id
                        select p).Single();

            //var data = from sr in finalDB.Software_Requirements
            //           join ps in finalDB.Package_Softwares
            //           on sr.id equals ps.sr_id
            //           where ps.wp_id == id
            //           select sr;

            //foreach (var ps in data)
            //{
            //    pack.Package_Softwares.Add(new Package_Software()
            //    {
            //        Software_Requirement = ps,
            //        Work_Package = pack
            //    });
            //}

            return View(pack);
        }
        public IPhishDatabase Get()
        {
            if (_database == null)
            {
                DataLoadOptions options = new DataLoadOptions();

                //options.LoadWith<Tour>(tour => tour.Shows);

                //options.LoadWith<Show>(show => show.Sets);

                //options.LoadWith<Set>(set => set.SetSongs);
                //options.LoadWith<Set>(set => set.Show);

                //options.LoadWith<SetSong>(setSong => setSong.Song);
                //options.LoadWith<SetSong>(setSong => setSong.Set);
                

                //options.LoadWith<Song>(song => song.set

                _database = new PhishDatabase(_connectionString) 
                    { 
                        LoadOptions = options, 
                        DeferredLoadingEnabled = true, 
                        Log = (_logWriter == null ? null : _logWriter.Get()) 
                    };
            }

            return _database;
        }
Example #3
0
 partial void OnCreated()
 {
     DataLoadOptions opts = new DataLoadOptions();
     opts.LoadWith<Room>(r => r.Computers);
     
     LoadOptions = opts;
 }
        public Inti_AthleteClub GetAthleteClubByTournament(Guid athleteId, Guid tournamentId)
        {
            using (var db = new IntiDataContext(_connectionString))
            {
                var dlo = new DataLoadOptions();
                dlo.LoadWith<Inti_AthleteClub>(ac => ac.Inti_Club);
                dlo.LoadWith<Inti_AthleteClub>(ac => ac.Inti_Position);
                dlo.LoadWith<Inti_AthleteClub>(ac => ac.Inti_Athlete);
                db.LoadOptions = dlo;

                var athleteClubs = from ac in db.Inti_AthleteClub
                                   where ac.AthleteGUID == athleteId &&
                                         ac.Inti_Club.TournamentGUID == tournamentId
                                   select ac;

                if(athleteClubs.ToList().Count == 1)
                {
                    var athleteClub = athleteClubs.ToList()[0];

                    return athleteClub;
                }

                if (athleteClubs.ToList().Count > 1)
                {
                    throw new ArgumentException("More than one club for the athlete with id {0} in the same tournament.", athleteId.ToString());
                }
            }

            return null;
        }
        //[TestMethod()]
        public void Command_Should_Parse_Correctly()
        {
            // ARRANGE
            Character toon = null;
            InventoryItem invItem = new InventoryItem();

            // Get the client's character info
            string charName = "Badass";
            DataLoadOptions dlo = new DataLoadOptions();
            dlo.LoadWith<Character>(c => c.Account);
            dlo.LoadWith<Character>(c => c.Zone);
            dlo.LoadWith<Character>(c => c.InventoryItems);
            dlo.LoadWith<InventoryItem>(ii => ii.Item);
            using (EmuDataContext dbCtx = new EmuDataContext()) {
                dbCtx.ObjectTrackingEnabled = false;
                dbCtx.LoadOptions = dlo;
                toon = dbCtx.Characters.SingleOrDefault(c => c.Name == charName);
            }

            ZonePlayer zp = new ZonePlayer(1, toon, 1, new Client(new System.Net.IPEndPoint(0x2414188f, 123)));

            // ACT
            //zp.MsgMgr.ReceiveChannelMessage("someTarget", "!damage /amount:200 /type:3", 8, 0, 100);
            zp.MsgMgr.ReceiveChannelMessage("someTarget", "!damage", 8, 0, 100);

            // ASSERT
        }
Example #6
0
        static void Main(string[] args)
        {
            NorthwindDataContext context = new NorthwindDataContext();
            //var result = from item in context.Categories
            //             where item.CategoryID == 48090
            //             select item;
            var result = context.SelectCategory(48090);
            foreach (var item in result)
            {
                Console.WriteLine("{0} {1}", item.CategoryID, item.CategoryName);
            }

            //context.DeferredLoadingEnabled = false;
            var ldOptions = new DataLoadOptions();
            ldOptions.AssociateWith<Category>((c) => (c.Products));
            context.LoadOptions = ldOptions;
            context.ObjectTrackingEnabled = false; // turns DeferredLoadingEnabled to false
            var result1 = context.Categories.Where((prod) => (prod.CategoryID == 65985)).Single();
            foreach (var item in result1.Products)
            {
                Console.WriteLine("{0} {1}",item.ProductID, item.ProductName);
            }

            Console.WriteLine();
            Compile();
            //Query2();
            //DirectExe();
            //Modify();
            //Trans();
            //MyDel();
            //Track();
            CreateDB();
            Console.ReadLine();
        }
Example #7
0
 public override void PostRepoInit()
 {
     var options = new DataLoadOptions();
     options.LoadWith<Sat>(s => s.User);
     options.LoadWith<User>(u => u.Tags);
     _repo.LoadOptions = options;
 }
Example #8
0
    public IEnumerable<DataTransfer.Algorithm> GetAlgorithms(string platformName) {
      roleVerifier.AuthenticateForAnyRole(OKBRoles.OKBAdministrator, OKBRoles.OKBUser);

      using (OKBDataContext okb = new OKBDataContext()) {
        DataLoadOptions dlo = new DataLoadOptions();
        dlo.LoadWith<Algorithm>(x => x.AlgorithmClass);
        dlo.LoadWith<Algorithm>(x => x.DataType);
        dlo.LoadWith<Algorithm>(x => x.AlgorithmUsers);
        okb.LoadOptions = dlo;

        var query = okb.Algorithms.Where(x => x.Platform.Name == platformName);
        List<Algorithm> results = new List<Algorithm>();

        if (roleVerifier.IsInRole(OKBRoles.OKBAdministrator)) {
          results.AddRange(query);
        } else {
          foreach (var alg in query) {
            if (alg.AlgorithmUsers.Count() == 0 || userManager.VerifyUser(userManager.CurrentUserId, alg.AlgorithmUsers.Select(y => y.UserGroupId).ToList())) {
              results.Add(alg);
            }
          }
        }
        return results.Select(x => Convert.ToDto(x)).ToArray();
      }
    }
        /// <summary>
        /// Update profile
        /// </summary>
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            using (var context = new PetShopDataContext())
            {
                var options = new DataLoadOptions();
                options.LoadWith<Profile>(p => p.AccountList);
                context.LoadOptions = options;

                var profile = context.Profile.GetProfile(User.Identity.Name);

                if (!string.IsNullOrEmpty(profile.Username) && AddressForm.IsValid)
                {
                    if (profile.AccountList.Count > 0)
                    {
                        Account account = profile.AccountList[0];
                        UpdateAccount(ref account, AddressForm.Address);
                    }
                    else
                    {
                        var account = new Account();
                        profile.AccountList.Add(account);
                        account.UniqueID = profile.UniqueID;

                        UpdateAccount(ref account, AddressForm.Address);
                    }

                    context.SubmitChanges();
                }
            }
            lblMessage.Text = "Your profile information has been successfully updated.<br>&nbsp;";
        }
Example #10
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!IsPostBack)
     {
         int personId = 0;
         if (Request.QueryString["id"] != null && int.TryParse(TamperProofString.QueryStringDecode(Request.QueryString["id"]), out personId))
         {
             Ajancy.Kimia_Ajancy db = new Ajancy.Kimia_Ajancy(Public.ConnectionString);
             DataLoadOptions dlo = new DataLoadOptions();
             dlo.LoadWith<Ajancy.Person>(p => p.DrivingLicenses);
             dlo.LoadWith<Ajancy.Person>(p => p.DriverCertifications);
             dlo.LoadWith<Ajancy.DriverCertification>(dc => dc.DriverCertificationCars);
             dlo.LoadWith<Ajancy.DriverCertificationCar>(dcc => dcc.CarPlateNumber);
             dlo.LoadWith<Ajancy.CarPlateNumber>(cpn => cpn.PlateNumber);
             dlo.LoadWith<Ajancy.CarPlateNumber>(cpn => cpn.Car);
             dlo.LoadWith<Ajancy.Car>(c => c.FuelCards);
             dlo.LoadWith<Ajancy.Car>(c => c.CarType);
             db.LoadOptions = dlo;
             SetPerson(db.Persons.FirstOrDefault<Ajancy.Person>(p => p.PersonID == personId));
             db.Dispose();
         }
         else
         {
             Response.Redirect("~/Default.aspx");
         }
     }
 }
        public void Save(params ContentType[] contentTypes)
        {
            using (var ts = new TransactionScope())
            using (var dataContext = new ContentDataContext(connectionString))
            {
                var loadOptions = new DataLoadOptions();
                loadOptions.LoadWith<ContentTypeItem>(ct => ct.ContentActionItems);

                dataContext.LoadOptions = loadOptions;

                var contentTypeItems = dataContext.ContentTypeItems.ToList();
                var itemsToDelete = from data in contentTypeItems
                                    where !contentTypes.Any(t => t.Type == data.Type && t.ControllerName == data.ControllerName)
                                    select data;

                var itemsToUpdate = (from data in contentTypeItems
                                     let type = contentTypes.SingleOrDefault(t => t.Type == data.Type && t.ControllerName == data.ControllerName)
                                     where type != null
                                     select new { data, type }).ToList();

                var itemsToInsert = (from type in contentTypes
                                     where !contentTypeItems.Any(t => t.Type == type.Type && t.ControllerName == type.ControllerName)
                                     select CreateContentTypeItem(type)).ToList();

                itemsToUpdate.ForEach(i => UpdateContentTypeItem(i.data, i.type, dataContext));

                dataContext.ContentTypeItems.DeleteAllOnSubmit(itemsToDelete);
                dataContext.ContentTypeItems.InsertAllOnSubmit(itemsToInsert);

                dataContext.SubmitChanges();
                ts.Complete();
            }
        }
        public void ExecuteQueryLoadWith()
        {
            var db = new TrackerDataContext { Log = Console.Out };
            db.DeferredLoadingEnabled = false;
            db.ObjectTrackingEnabled = false;

            DataLoadOptions options = new DataLoadOptions();
            options.LoadWith<Task>(t => t.CreatedUser);

            db.LoadOptions = options;

            var q1 = db.User
                .ByEmailAddress("*****@*****.**");

            var q2 = db.Task
                .Where(t => t.LastModifiedBy == "*****@*****.**");

            var result = db.ExecuteQuery(q1, q2);

            Assert.IsNotNull(result);

            var userResult = result.GetResult<User>();
            Assert.IsNotNull(userResult);

            var users = userResult.ToList();
            Assert.IsNotNull(users);

            var taskResult = result.GetResult<Task>();
            Assert.IsNotNull(taskResult);

            var tasks = taskResult.ToList();
            Assert.IsNotNull(tasks);
        }
Example #13
0
 /// <summary>
 /// User Manager 
 /// </summary>
 public UserManager()
 {
     db = new BizzyQuoteDataContext(Properties.Settings.Default.BizzyQuoteConnectionString);
     var options = new DataLoadOptions();
     options.LoadWith<User>(u => u.Company);
     db.LoadOptions = options;
 }
        private IEnumerable GetServerData(GridCommand command)
        {
            DataLoadOptions loadOptions = new DataLoadOptions();
            loadOptions.LoadWith<Order>(o => o.Customer);

            var dataContext = new NorthwindDataContext
            {
                LoadOptions = loadOptions
            };

            IQueryable<Order> data = dataContext.Orders;

            //Apply filtering
            data = data.ApplyFiltering(command.FilterDescriptors);

            ViewData["Total"] = data.Count();

            //Apply sorting
            data = data.ApplySorting(command.GroupDescriptors, command.SortDescriptors);

            //Apply paging
            data = data.ApplyPaging(command.Page, command.PageSize);

            //Apply grouping
            if (command.GroupDescriptors.Any())
            {
                return data.ApplyGrouping(command.GroupDescriptors);
            }
            return data.ToList();
        }
 public TaskRepository()
 {
     _dataContext = new DataContextDataContext();
     DataLoadOptions dlo = new DataLoadOptions();
     dlo.LoadWith<Task>(t => t.Project);
     dlo.LoadWith<Task>(t => t.Priority);
     _dataContext.LoadOptions = dlo;
 }
Example #16
0
 private static DataLoadOptions GetDefaultDataLoadOptions()
 {
     var lo = new DataLoadOptions();
     lo.LoadWith<Employee>(c => c.StructDivision);
     lo.LoadWith<EmployeeRole>(c => c.Role);
     lo.LoadWith<Employee>(c => c.EmployeeRoles);
     return lo;
 }
Example #17
0
        public Repository(string strConnection)
        {
            m_ctx = new DataContext(strConnection);

            DataLoadOptions dlo = new DataLoadOptions();
            dlo.LoadWith<Artist>(c => c.Genre);
            m_ctx.LoadOptions = dlo;
        }
		internal void AddFactory(Type elementType, Type dataReaderType, object mapping, DataLoadOptions options, SqlExpression projection, IObjectReaderFactory factory)
		{
			this.list.AddFirst(new LinkedListNode<CacheInfo>(new CacheInfo(elementType, dataReaderType, mapping, options, projection, factory)));
			if(this.list.Count > this.maxCacheSize)
			{
				this.list.RemoveLast();
			}
		}
Example #19
0
 private static DataLoadOptions GetDefaultDataLoadOptions()
 {
     var lo = new DataLoadOptions();
     lo.LoadWith<Document>(c => c.Employee);
     lo.LoadWith<Document>(c => c.Employee1);
     lo.LoadWith<DocumentTransitionHistory>(c=>c.Employee);
     return lo;
 }
Example #20
0
		internal AdoCompiledQuery(IReaderProvider provider, Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, ICompiledSubQuery[] subQueries)
		{
			this.originalShape = provider.Services.Context.LoadOptions;
			this.query = query;
			this.queryInfos = queryInfos;
			this.factory = factory;
			this.subQueries = subQueries;
		}
			public CacheInfo(Type elementType, Type dataReaderType, object mapping, DataLoadOptions options, SqlExpression projection, IObjectReaderFactory factory)
			{
				this.elementType = elementType;
				this.dataReaderType = dataReaderType;
				this.options = options;
				this.mapping = mapping;
				this.projection = projection;
				this.factory = factory;
			}
Example #22
0
 public ModelDataContext() :
         base(Settings.Default.MyBlogConnectionString, xmlSource)
 {
     var ds = new DataLoadOptions();
     ds.LoadWith<Post>(p => p.Comments);
     ds.LoadWith<Post>(p => p.CategoryLinks);
     ds.LoadWith<PostCategoryLink>(o => o.PostCategory);
     this.LoadOptions = ds;
 }
Example #23
0
 public HeraldDBDataContext()
     : base(ConfigurationManager.ConnectionStrings["Herald"].ConnectionString, mappingSource)
 {
     Log = new Logger();
     if (LoadOptions != null) return; // only if not specified explicitly outside
     var options = new DataLoadOptions();
     options.LoadWith<Message>(message => message.MessageItems);
     LoadOptions = options;
 }
        private IEnumerable<Order> GetOrders()
        {
            DataLoadOptions loadOptions = new DataLoadOptions();

            loadOptions.LoadWith<Order>(o => o.Customer);
            northwind.LoadOptions = loadOptions;

            return northwind.Orders;
        }
Example #25
0
 /// <summary>
 /// Quote Manager 
 /// </summary>
 public QuoteManager()
 {
     db = new BizzyQuoteDataContext(Properties.Settings.Default.BizzyQuoteConnectionString);
     var options = new DataLoadOptions();
     options.LoadWith<Quote>(q => q.QuoteItems);
     options.LoadWith<QuoteItem>(qi => qi.Material);
     options.LoadWith<QuoteItem>(qi => qi.Product);
     db.LoadOptions = options;
 }
Example #26
0
    protected void btnSave_Click(object sender, EventArgs e)
    {
        int personId = 0;
        if (this.Page.IsValid && int.TryParse(TamperProofString.QueryStringDecode(Request.QueryString["id"]), out personId))
        {
            DataLoadOptions dlo = new DataLoadOptions();
            dlo.LoadWith<Ajancy.Person>(p => p.User);
            db = new Ajancy.Kimia_Ajancy(Public.ConnectionString);
            db.LoadOptions = dlo;
            Ajancy.Person person = db.Persons.First<Ajancy.Person>(p => p.PersonID == personId);
            if (person.NationalCode != this.txtNationalCode.Text.Trim()) // Nationalcode is changed
            {
                person.NationalCode = this.txtNationalCode.Text;
                person.User.UserName = this.txtNationalCode.Text;
            }

            person.User.ProvinceID = Public.ToByte(this.drpProvince.SelectedValue);
            person.User.CityID = Public.ToShort(this.drpCity.SelectedValue);
            person.FirstName = this.txtFirstName.Text.Trim();
            person.LastName = this.txtLastName.Text.Trim();
            person.Father = this.txtFather.Text.Trim();
            person.BirthCertificateNo = this.txtBirthCertificateNo.Text.Trim();
            person.BirthCertificateSerial = this.txtBirthCertificateSerial.Text.Trim();
            person.BirthCertificateSerie = this.txtBirthCertificateSerie.Text.Trim();
            person.BirthCertificateAlfa = this.drpBirthCertificateAlfa.SelectedValue;
            person.Gender = Public.ToByte(this.drpGender.SelectedValue);
            person.Marriage = Public.ToByte(this.drpMarriage.SelectedValue);
            person.BirthDate = this.txtBirthDate.GeorgianDate;
            person.BirthPlace = this.txtBirthPlace.Text.Trim();
            person.BirthCertificatePlace = this.txtBirthCertificatePlace.Text.Trim();
            person.FamilyMembersCount = this.txtFamilyMembersCount.Text.Trim();
            person.Education = Public.ToByte(this.drpEducation.SelectedValue);
            person.MilitaryService = Public.ToByte(this.drpMilitaryService.SelectedValue);
            person.Religion = Public.ToByte(this.drpReligion.SelectedValue);
            person.Subreligion = this.txtSubreligion.Text.Trim();
            person.JobStatus = Public.ToByte(this.drpJobStatus.SelectedValue);
            person.Phone = this.txtPhone.Text.Trim();
            person.Mobile = this.txtMobile.Text.Trim();
            person.PostalCode = this.txtPostalCode.Text.Trim();
            person.Address = this.txtAddress.Text.Trim();

            try
            {
                db.SubmitChanges();
                DisposeContext();
                Response.Redirect("~/Message.aspx?mode=17");
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("duplicate key"))
                {
                    this.lblMessage.Text = "کد ملی تکراری میباشد";
                }
            }
        }
    }
        public RecordingsContext(string connectionString)
            : base(connectionString)
        {
            if (DatabaseExists()) UpdateDatabase();
            else CreateNewDatabase();

            var options = new DataLoadOptions();
            options.LoadWith<Recording>(r => r.RecordingTags);
            LoadOptions = options;
        }
Example #28
0
 public Product GetProductWithImages(int productId)
 {
     using(var context = new ECommerceDbDataContext(_conStr))
     {
         var loadOptions = new DataLoadOptions();
         loadOptions.LoadWith<Product>(p => p.Images);
         context.LoadOptions = loadOptions;
         return context.Products.Where(p => p.ProductId == productId).FirstOrDefault();
     }
 }
 public Product GetProductById(int id)
 {
     using (var context = new ECommerceDataContext(_connectionString))
     {
         var dataLoadOptions = new DataLoadOptions();
         dataLoadOptions.LoadWith<Product>(p => p.Images);
         context.LoadOptions = dataLoadOptions;
         return context.Products.Where(p => p.ProductId == id).First();
     }
 }
        public SettingsRepository()
        {
            var loadOptions = new DataLoadOptions();

            loadOptions.LoadWith<Settings>(s => s.Server);
            loadOptions.LoadWith<Settings>(s => s.Language);
            loadOptions.LoadWith<Settings>(s => s.PhotoResolution);

            _context.LoadOptions = loadOptions;
        }
        public BagDAOLinq(bool isLoadWith)
        {
            if (isLoadWith)
            {
                base.DataContext.DeferredLoadingEnabled = false;

                DataLoadOptions options = new DataLoadOptions();

                options.LoadWith <INVBagFair>(d => d.FairID);
                //options.LoadWith<ADMDivision>(d => d.ADMCountry);

                base.DataContext.LoadOptions = options;
            }
            else
            {
                base.DataContext.DeferredLoadingEnabled = true;
            }
        }
        public mediacao Obter(int id)
        {
            dbDataContext db = new dbDataContext();

            // função que carrega a mediação e todos os dados vinculados a ela
            // na forma de seus objetos completos

            DataLoadOptions options = new DataLoadOptions();

            options.LoadWith <mediacao>(m => m.mediacao_partes);
            options.LoadWith <mediacao>(m => m.local);
            options.LoadWith <mediacao_parte>(mp => mp.pessoa);
            options.LoadWith <mediacao>(m => m.mediador);
            db.LoadOptions = options;
            var query = from m in db.mediacaos where m.id == id select m;

            return(query.FirstOrDefault());
        }
Example #33
0
        internal static void AssociationChanges()
        {
            using (AdventureWorks adventureWorks = new AdventureWorks())
            {
                DataLoadOptions loadOptions = new DataLoadOptions();
                loadOptions.LoadWith <ProductCategory>(entity => entity.ProductSubcategories);
                adventureWorks.LoadOptions = loadOptions;
                ProductCategory category = adventureWorks.ProductCategories.First();
                Trace.WriteLine(category.ProductSubcategories.Count);                                       // 12.
                ProductSubcategory[] subcategories = category.ProductSubcategories.ToArray();
                Trace.WriteLine(subcategories.All(subcategory => subcategory.ProductCategory == category)); // True.

                category.ProductSubcategories.Clear();
                Trace.WriteLine(category.ProductSubcategories.Count);                                   // 0.
                Trace.WriteLine(adventureWorks.GetChangeSet().Updates.Count);                           // 12.
                Trace.WriteLine(subcategories.All(subcategory => subcategory.ProductCategory == null)); // True.
            }
        }
Example #34
0
        public void LinqToSqlInsert02()
        {
            Northwind db = CreateDB();

            var ds = new DataLoadOptions();

            ds.LoadWith <Category>(c => c.Products);
            db.LoadOptions = ds;

            var q = from c in db.Categories
                    where c.CategoryName == "Temp Widgets"
                    select c;

            var newCategory = new Category
            {
                CategoryName = "Temp Widgets",
                Description  = "Widgets are the customer-facing analogues to sprockets and cogs."
            };

            var newProduct = new Product
            {
                ProductName = "temp Blue Widget",
                UnitPrice   = 34.56m,
                Category    = newCategory
            };

            db.Categories.InsertOnSubmit(newCategory);
            db.SubmitChanges();

            var reloadedProduct = db.Products.First(p => p.ProductID == newProduct.ProductID);

            Assert.AreEqual(reloadedProduct.ProductName, newProduct.ProductName);
            Assert.AreEqual(reloadedProduct.UnitPrice, newProduct.UnitPrice);
            Assert.AreEqual(reloadedProduct.Category.CategoryID, newProduct.CategoryID);

            var reloadedCategory = reloadedProduct.Category;

            Assert.AreEqual(reloadedCategory.CategoryName, newCategory.CategoryName);
            Assert.AreEqual(reloadedCategory.Description, reloadedCategory.Description);

            db.Products.DeleteOnSubmit(newProduct);
            db.Categories.DeleteOnSubmit(newCategory);
            db.SubmitChanges();
        }
Example #35
0
        public void LinqToSqlInsert03()
        {
            Northwind db = CreateDB();

            var ds = new DataLoadOptions();

            ds.LoadWith <Employee>(p => p.EmployeeTerritories);
            ds.LoadWith <EmployeeTerritory>(p => p.Territory);

            db.LoadOptions = ds;
            var q = from e in db.Employees where e.FirstName == "Nancy" select e;


            if (db.Employees.Any(e => e.FirstName == "Test Kira" && e.LastName == "Test Smith"))
            {
                Assert.Ignore();
            }


            var newEmployee = new Employee {
                FirstName = "Test Kira", LastName = "Test Smith"
            };
            var newTerritory = new Territory
            {
                TerritoryID          = "12345",
                TerritoryDescription = "Test Anytown",
                Region = db.Regions.First()
            };

            var newEmployeeTerritory = new EmployeeTerritory {
                Employee = newEmployee, Territory = newTerritory
            };

            db.Employees.InsertOnSubmit(newEmployee);
            db.Territories.InsertOnSubmit(newTerritory);
            db.EmployeeTerritories.InsertOnSubmit(newEmployeeTerritory);
            db.SubmitChanges();

            // cleanup
            db.EmployeeTerritories.DeleteOnSubmit(newEmployeeTerritory);
            db.Territories.DeleteOnSubmit(newTerritory);
            db.Employees.DeleteOnSubmit(newEmployee);
            db.SubmitChanges();
        }
Example #36
0
        internal List <PlayerStandingsResultsDto> GetStandings(string divisionName, string seasonName, string leagueName)
        {
            // Include certain properties on Match.
            var loadOptions = new DataLoadOptions();

            loadOptions.LoadWith <Match>(x => x.MatchSets);
            loadOptions.LoadWith <Match>(x => x.Division);
            loadOptions.LoadWith <Match>(x => x.Player);
            loadOptions.LoadWith <Match>(x => x.Player1);
            this.LoadOptions = loadOptions;

            var query = from match in Matches
                        where match.Division.Name == divisionName &&
                        match.Division.Season.Name == seasonName &&
                        match.Division.Season.League.Name == leagueName
                        orderby match.Id
                        select match;

            var playerIdToStandingsMapping = new Dictionary <int, PlayerStandingsResultsDto>();
            var standings = new PlayerStandingsResultsDto();

            int previousMatchId = 0;

            foreach (var match in query)
            {
                if (match.Id == previousMatchId)
                {
                    continue;
                }
                previousMatchId = match.Id;
                UpdateHomeResults(match, playerIdToStandingsMapping);
                UpdateAwayResults(match, playerIdToStandingsMapping);
            }

            //return playerIdToStandingsMapping.Values.ToList()
            //    .OrderByDescending(x => x.MatchesWon).ThenByDescending(x => x.SetsWon).ThenByDescending(x => x.GamesWon)
            //    .ThenBy(x => x.SetsLost).ThenBy(x => x.GamesLost).ToList();

            return(playerIdToStandingsMapping.Values.ToList()
                   .OrderByDescending(x => x.MatchesWon - x.MatchesLost)
                   .ThenByDescending(x => x.SetsWon - x.SetsLost)
                   .ThenByDescending(x => x.GamesWon - x.GamesLost)
                   .ToList());
        }
Example #37
0
        public IObjectReaderFactory Compile(SqlExpression expression, Type elementType)
        {
            //-------------------------SOURCE CODE--------------------------
            object identity = this.services.Context.Mapping.Identity;
            //--------------------------------------------------------------
            //var bf = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty;
            //object identity = typeof(MetaModel).InvokeMember("Identity", bf, null, services.Context.Mapping, null);
            //--------------------------------------------------------------
            DataLoadOptions      loadOptions = services.Context.LoadOptions;
            IObjectReaderFactory factory     = null;
            ReaderFactoryCache   data        = null;
            bool flag = SqlProjectionComparer.CanBeCompared(expression);

            if (flag)
            {
                data = (ReaderFactoryCache)Thread.GetData(cacheSlot);
                if (data == null)
                {
                    data = new ReaderFactoryCache(maxReaderCacheSize);
                    Thread.SetData(cacheSlot, data);
                }
                factory = data.GetFactory(elementType, dataReaderType, identity, loadOptions, expression);
            }
            if (factory == null)
            {
                var           gen          = new Generator(this, elementType);
                DynamicMethod method       = CompileDynamicMethod(gen, expression, elementType);
                var           t            = typeof(ObjectMaterializer <>).MakeGenericType(new[] { dataReaderType });
                var           delegateType = typeof(Func <,>).MakeGenericType(new[] { t, elementType });
                var           delegate2    = method.CreateDelegate(delegateType);

                factory = (IObjectReaderFactory)
                          Activator.CreateInstance(typeof(ObjectReaderFactory <,>).MakeGenericType(new[] { dataReaderType, elementType }),
                                                   BindingFlags.NonPublic | BindingFlags.Instance, null,
                                                   new object[] { delegate2, gen.NamedColumns, gen.Globals, gen.Locals }, null);
                if (flag)
                {
                    expression = new SourceExpressionRemover().VisitExpression(expression);
                    data.AddFactory(elementType, dataReaderType, identity, loadOptions, expression, factory);
                }
            }
            return(factory);
        }
Example #38
0
        public void Run(RuleContext context)
        {
            context.Success = true;

            if (HttpContext.Current != null)
            {
                var task = (Task)context.TrackedObject.Current;

                using (var db = new TrackerDataContext())
                {
                    var options = new DataLoadOptions();
                    options.LoadWith <UserRole>(r => r.Role);
                    db.LoadOptions = options;

                    User currentUser = db.User.GetByEmailAddress(HttpContext.Current.User.Identity.Name);
                    context.Success = (null == db.UserRole.GetUserRole("Newb", currentUser.Id));
                }
            }
        }
        public List <CACCCheckInDb.Class> GetClassesByDeptName(string departmentName)
        {
            logger.Debug("Opening DataContext to CACCCheckIn DB.");
            CACCCheckInDb.CACCCheckInDbDataContext db = new CACCCheckInDb.CACCCheckInDbDataContext();
            db.Log = logwriter;

            DataLoadOptions dlo = new DataLoadOptions();

            dlo.LoadWith <CACCCheckInDb.Class>(r => r.Department);
            db.LoadOptions = dlo;

            logger.DebugFormat("Querying CACCCheckIn DB for Classes with Department.Name=[{0}].",
                               departmentName);
            List <CACCCheckInDb.Class> classes = (from c in db.Classes
                                                  where c.Department.Name.Equals(departmentName)
                                                  select c).ToList();

            return(classes);
        }
Example #40
0
        public void FindById_Should_Return_Correct_Vote()
        {
            using (BeginTransaction())
            {
                var loadOptions = new DataLoadOptions();
                loadOptions.LoadWith <StoryVote>(v => v.User);
                loadOptions.LoadWith <StoryVote>(v => v.Story);
                _database.LoadOptions = loadOptions;

                var vote = CreateNewStoryVote();
                _database.InsertOnSubmit(vote);
                _database.SubmitChanges();

                var storyId = vote.StoryId;
                var userId  = vote.UserId;

                Assert.NotNull(_voteRepository.FindById(storyId, userId));
            }
        }
Example #41
0
        public void AddTag_For_Existing_Story_Should_Increase_Tags_Collection()
        {
            using (BeginTransaction())
            {
                var options = new DataLoadOptions();
                options.LoadWith <Story>(s => s.StoryTagsInternal);
                _database.LoadOptions = options;

                GenerateStoriesAndSave();
                _database.SubmitChanges();
                var story     = _database.StoryDataSource.First();
                var tagsCount = story.Tags.Count;
                story.AddTag(new Tag {
                    Id = Guid.NewGuid(), Name = "Dummy"
                });

                Assert.Equal(tagsCount + 1, story.Tags.Count);
            }
        }
 public List <Setting> GetSettingsWithTypes()
 {
     try
     {
         using (var ctx = new DatabaseModelDataContext())
         {
             DataLoadOptions dlo = new DataLoadOptions();
             dlo.LoadWith <Setting>(x => x.SettingsType);
             ctx.LoadOptions = dlo;
             var settings = ctx.Settings.ToList();
             return(settings);
         }
     }
     catch (Exception e)
     {
         Log.Error("Database error - GetSettings:", e);
         throw;
     }
 }
Example #43
0
 public IEnumerable <MarkerCategory> GetMarkerCategoriesWithAllMarkers()
 {
     using (var context = new ManufacturingDataContext(_connectionString))
     {
         var loadOptions = new DataLoadOptions();
         loadOptions.LoadWith <MarkerCategory>(m => m.Marker);
         loadOptions.LoadWith <MarkerCategory>(m => m.Department);
         loadOptions.LoadWith <MarkerCategory>(m => m.BodyStyle);
         loadOptions.LoadWith <MarkerCategory>(m => m.Sleeve);
         loadOptions.LoadWith <MarkerCategory>(m => m.Markers);
         loadOptions.LoadWith <Marker>(m => m.MarkerDetails);
         loadOptions.LoadWith <MarkerDetail>(m => m.Size);
         context.LoadOptions = loadOptions;
         return(context.MarkerCategories.Where(x => !x.Deleted).ToList().Select(m => {
             m.Markers = m.Markers.Where(ma => !ma.Deleted).ToEntitySet();
             return m;
         }));
     }
 }
        public UpazilaPSDAOLinq(bool isLoadWith)
        {
            if (isLoadWith)
            {
                base.DataContext.DeferredLoadingEnabled = false;

                DataLoadOptions options = new DataLoadOptions();

                options.LoadWith <ADMUpazilaPS>(u => u.DistrictID);
                options.LoadWith <ADMDistrict>(d => d.DivisionID);
                options.LoadWith <ADMDivision>(d => d.CountryID);

                base.DataContext.LoadOptions = options;
            }
            else
            {
                base.DataContext.DeferredLoadingEnabled = true;
            }
        }
Example #45
0
        internal ShoppingListAdditionalItem[] GetShoppingListAdditionalItems(int menuId)
        {
            using (DataContext)
            {
                try
                {
                    DataLoadOptions dlo = new DataLoadOptions();
                    dlo.LoadWith <ShoppingListAdditionalItem>(slai => slai.GeneralItem);
                    DataContext.LoadOptions = dlo;

                    var list = DataContext.ShoppingListAdditionalItems.Where(slai => slai.MenuId == menuId);
                    return(list.ToArray());
                }
                catch
                {
                    return(null);
                }
            }
        }
Example #46
0
        public void AddTag_For_Existing_User_Should_Increase_Tags_Collection()
        {
            using (BeginTransaction())
            {
                var options = new DataLoadOptions();
                options.LoadWith <User>(u => u.UserTagsInternal);
                _database.LoadOptions = options;

                CreateNewUserAndSave();

                var user      = _database.UserDataSource.First();
                int tagsCount = user.Tags.Count;
                user.AddTag(new Tag {
                    Id = Guid.NewGuid(), Name = "Dummy"
                });

                Assert.Equal(tagsCount + 1, user.Tags.Count);
            }
        }
 internal IObjectReaderFactory GetFactory(Type elementType, Type dataReaderType, object mapping, DataLoadOptions options, SqlExpression projection)
 {
     for (LinkedListNode <CacheInfo> info = this.list.First; info != null; info = info.Next)
     {
         if (elementType == info.Value.elementType &&
             dataReaderType == info.Value.dataReaderType &&
             mapping == info.Value.mapping &&
             DataLoadOptions.ShapesAreEquivalent(options, info.Value.options) &&
             SqlProjectionComparer.AreSimilar(projection, info.Value.projection)
             )
         {
             // move matching item to head of list to reset its lifetime
             this.list.Remove(info);
             this.list.AddFirst(info);
             return(info.Value.factory);
         }
     }
     return(null);
 }
Example #48
0
        internal GeneralItem GetGeneralItem(int ItemId)
        {
            using (DataContext)
            {
                try
                {
                    DataLoadOptions dlo = new DataLoadOptions();
                    dlo.LoadWith <GeneralItem>(sd => sd.ShoppingListAdditionalItems);
                    DataContext.LoadOptions = dlo;

                    GeneralItem dep = DataContext.GeneralItems.Single(sd => sd.GeneralItemId == ItemId);
                    return(dep);
                }
                catch
                {
                    return(null);
                }
            }
        }
 public List <Event> GetNumberOfEventsWithTypes(int numberOfEvents)
 {
     try
     {
         using (var ctx = new DatabaseModelDataContext())
         {
             var dlo = new DataLoadOptions();
             dlo.LoadWith <Event>(k => k.Notification);
             dlo.LoadWith <Event>(e => e.EventType);
             ctx.LoadOptions = dlo;
             return(ctx.Events.OrderByDescending(x => x.Created).Take(numberOfEvents).ToList());
         }
     }
     catch (Exception e)
     {
         Log.Error("Database error - GetNumberOfEventsWithTypes: " + e);
         throw;
     }
 }
Example #50
0
        internal GeneralItem[] GetGeneralItemsList()
        {
            using (DataContext)
            {
                try
                {
                    DataLoadOptions dlo = new DataLoadOptions();
                    dlo.LoadWith <GeneralItem>(sd => sd.ShoppingListAdditionalItems);
                    DataContext.LoadOptions = dlo;

                    var list = DataContext.GeneralItems.OrderBy(sd => sd.SortOrder);
                    return(list.ToArray());
                }
                catch
                {
                    return(null);
                }
            }
        }
Example #51
0
        async Task <Movie> GetMovieInfo(int id)
        {
            using (var context = new MoviesContext())
            {
                var dlo = new DataLoadOptions();
                dlo.LoadWith <Database.Movies>(li => li.MovieStreamSet);
                dlo.LoadWith <Database.MovieStreamSet>(li => li.StreamCookie);
                context.LoadOptions = dlo;

                var movie               = context.Movies.Single(li => li.Id == id);
                var movieStreams        = new List <Contracts.DTA.MovieStreamSet>();
                var firstMovieStreamSet = movie.MovieStreamSet.FirstOrDefault();
                if (firstMovieStreamSet == null)
                {
                    throw new InvalidOperationException(string.Format("Movie {0} does not have a stream attached", movie.Id));
                }

                if (firstMovieStreamSet.StreamCookie.Any(li => li.ExpirationDate < DateTime.UtcNow))
                {
                    await IssueStreamParse(firstMovieStreamSet);

                    context.SubmitChanges();
                }

                for (var i = 1; i < movie.MovieStreamSet.Count; i++)
                {
                    var streamSet = movie.MovieStreamSet[i];
                    if (streamSet.StreamCookie.Any(li => li.ExpirationDate >= DateTime.UtcNow))
                    {
                        // add a record just with an id and null streams
                        movieStreams.Add(new Contracts.DTA.MovieStreamSet {
                            Id = streamSet.Id
                        });
                        continue;
                    }

                    movieStreams.Add(streamSet.ToDTA());
                }

                return(movie.ToDTA());
            }
        }
Example #53
0
        private ActionResult getAssessmentReportItem(int uid, int[] itemID)
        {
            DataLoadOptions ops = new DataLoadOptions();

            ops.LoadWith <LessonFitnessAssessment>(f => f.LessonFitnessAssessmentReport);
            ops.LoadWith <LessonFitnessAssessmentReport>(f => f.FitnessAssessmentItem);
            models.GetDataContext().LoadOptions = ops;

            var items = models.GetTable <LessonFitnessAssessment>().Where(u => u.UID == uid)
                        .Where(u => u.LessonFitnessAssessmentReport.Count(r => itemID.Contains(r.ItemID) && (r.TotalAssessment.HasValue || r.SingleAssessment.HasValue)) > 0);

            if (items.Count() == 0)
            {
                return(View("EmptyAssessment"));
            }
            else
            {
                return(View(items));
            }
        }
Example #54
0
        internal Article GetArticleById(int articleId)
        {
            using (DataContext)
            {
                try
                {
                    DataLoadOptions dlo = new DataLoadOptions();
                    dlo.LoadWith <Article>(art => art.ArticleId);
                    DataContext.LoadOptions = dlo;

                    Article article = DataContext.Articles.SingleOrDefault(a => a.ArticleId == articleId);

                    return(article);
                }
                catch
                {
                    return(null);
                }
            }
        }
Example #55
0
        public static void SetChildLoadOptions(DataLoadOptions loadOptions)
        {
            return;

            /*
             * loadOptions.LoadWith<PersonRegistration>(pr => pr.PersonAttributes);
             * loadOptions.LoadWith<PersonRegistration>(pr => pr.PersonRelationships);
             * loadOptions.LoadWith<PersonRegistration>(pr => pr.PersonState);
             * loadOptions.LoadWith<PersonRegistration>(pr => pr.ActorRef);
             * loadOptions.LoadWith<PersonRegistration>(pr => pr.LifecycleStatus);
             *
             *
             * Effect.SetChildLoadOptions(loadOptions);
             * CountryRef.SetChildLoadOptions(loadOptions);
             *
             * CprBroker.Data.Part.PersonAttributes.SetChildLoadOptions(loadOptions);
             * PersonRelationship.SetChildLoadOptions(loadOptions);
             * PersonState.SetChildLoadOptions(loadOptions);
             */
        }
Example #56
0
 public DtoFactStaffEmployee[] GetEmployeesForTimeSheet(int idDepartment, DtoApprover approver, DateTime dateStart, DateTime dateEnd)
 {
     using (var db = new KadrDataContext())
     {
         //var depsId = GetDepartmentsIdList(idDepartment);
         var loadOptions = new DataLoadOptions();
         loadOptions.LoadWith((FactStaffWithHistory fswh) => fswh.PlanStaff);
         loadOptions.LoadWith((PlanStaff ps) => ps.Post);
         loadOptions.LoadWith((Post p) => p.Category);
         loadOptions.LoadWith((PlanStaff ps) => ps.WorkShedule);
         loadOptions.LoadWith((FactStaffWithHistory fswh) => fswh.Employee);
         loadOptions.LoadWith((OK_Otpusk oko) => oko.OK_Otpuskvid);
         db.LoadOptions = loadOptions;
         var ts = new TimeSheetManaget(idDepartment, dateStart, dateEnd, approver.EmployeeLogin, db);
         return
             (ts.GetAllEmployees()
              .Select(s => DtoClassConstructor.DtoFactStaffEmployee(db, s.idFactStaffHistory))
              .ToArray());
     }
 }
Example #57
0
        public void method2()
        {
            // <Snippet2>
            Northwnd        db  = new Northwnd(@"c:\northwnd.mdf");
            DataLoadOptions dlo = new DataLoadOptions();

            dlo.LoadWith <Customer>(c => c.Orders);
            db.LoadOptions = dlo;

            var londonCustomers =
                from cust in db.Customers
                where cust.City == "London"
                select cust;

            foreach (var custObj in londonCustomers)
            {
                Console.WriteLine(custObj.CustomerID);
            }
            // </Snippet2>
        }
        public decimal GetTotalAmountSpentOnIces()
        {
            using (var context = new TruckDataContext(@"Data Source=.\sqlexpress;Initial Catalog=Truck;Integrated Security=True"))
            {
                var loadOptions = new DataLoadOptions();
                loadOptions.LoadWith <AddStock>(e => e.Product);
                context.LoadOptions = loadOptions;
                var twinPops         = context.AddStocks.Where(d => d.Id == 1);
                var totalTwinsAdded  = twinPops.Sum(d => d.Amount);
                var averageTwinPrice = context.Products.First(p => p.Id == 1).AveragePrice;
                var totalTwin        = totalTwinsAdded * averageTwinPrice;

                var luigi             = context.AddStocks.Where(d => d.Id == 2);
                var totalLuigiAdded   = luigi.Sum(d => d.Amount);
                var averageLuigiPrice = context.Products.First(p => p.Id == 2).AveragePrice;
                var totalLuigi        = totalLuigiAdded * averageLuigiPrice;

                return(totalTwin + totalLuigi);
            }
        }
Example #59
0
 public DtoTimeSheet GetTimeSheet(int idTimeSheet, bool isEmpty = false)
 {
     using (var db = new KadrDataContext())
         using (var dbloger = new DataContextLoger("GetTimeSheetLog.sql", FileMode.OpenOrCreate, db))
         {
             var loadOptions = new DataLoadOptions();
             loadOptions.LoadWith((TimeSheet ts) => ts.TimeSheetRecords);
             loadOptions.LoadWith((TimeSheet ts) => ts.Dep);
             loadOptions.LoadWith((Dep d) => d.Department);
             loadOptions.LoadWith((TimeSheetRecord tsr) => tsr.FactStaffHistory);
             loadOptions.LoadWith((FactStaffWithHistory f) => f.FactStaff);
             loadOptions.LoadWith((FactStaff f) => f.Employee);
             loadOptions.LoadWith((FactStaffWithHistory f) => f.FactStaff.PlanStaff);
             loadOptions.LoadWith((PlanStaff p) => p.Post);
             loadOptions.LoadWith((Post p) => p.Category);
             db.LoadOptions = loadOptions;
             //return DtoClassConstructor.DtoTimeSheet(db, idTimeSheet, isEmpty);
             return(db.TimeSheetView.Where(f => f.id == idTimeSheet).Select(s => DtoClassConstructor.DtoTimeSheet(s, isEmpty)).FirstOrDefault());
         }
 }
Example #60
0
        internal Meal GetMeal(int mealId)
        {
            using (DataContext)
            {
                try
                {
                    DataLoadOptions dlo = new DataLoadOptions();
                    dlo.LoadWith <Meal>(m => m.MealRecipes);
                    DataContext.LoadOptions = dlo;

                    Meal item = DataContext.Meals.SingleOrDefault(m => m.MealId == mealId);

                    return(item);
                }
                catch
                {
                    return(null);
                }
            }
        }