/// <summary>
        /// Called when this instance is created.
        /// </summary>
        partial void OnCreated()
        {
            var loadOptions = new DataLoadOptions();

            loadOptions.AssociateWith <Survey>(survey => survey.Sections.OrderBy(section => section.RelativeOrder));
            loadOptions.AssociateWith <Section>(section => section.Questions.OrderBy(question => question.RelativeOrder));
            loadOptions.AssociateWith <Question>(question => question.Answers.OrderBy(answer => answer.RelativeOrder));
            this.LoadOptions = loadOptions;
        }
Example #2
0
        //�Private�Methods�(1)�

        partial void OnCreated()
        {
            var dlo = new DataLoadOptions();

            dlo.AssociateWith <User>(user => user.UserProjects.Where(up => up.Project.Active));
            dlo.AssociateWith <TaxonomyInfo>(ti => ti.TaxonomyDatas.Where(td => td.Active));
            dlo.LoadWith <TaxonomyInfo>(taxonomyInfo => taxonomyInfo.TaxonomyDatas);
            //dlo.LoadWith<Sku>(sku => sku.EntityInfos);
            dlo.LoadWith <EntityInfo>(ei => ei.EntityDatas);

            LoadOptions    = dlo;
            CommandTimeout = 600;
        }
Example #3
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 #4
0
        static void Main(string[] args)
        {
            // <Snippet1>
            Northwnd        db  = new Northwnd(@"c:\northwnd.mdf");
            DataLoadOptions dlo = new DataLoadOptions();

            dlo.AssociateWith <Customer>(c => c.Orders.Where(p => p.ShippedDate != DateTime.Today));
            db.LoadOptions = dlo;
            var custOrderQuery =
                from cust in db.Customers
                where cust.City == "London"
                select cust;

            foreach (Customer custObj in custOrderQuery)
            {
                Console.WriteLine(custObj.CustomerID);
                foreach (Order ord in custObj.Orders)
                {
                    Console.WriteLine("\t {0}", ord.OrderDate);
                }
            }
            // </Snippet1>

            Console.ReadLine();
        }
Example #5
0
    partial void OnCreated()
    {
        DataLoadOptions dlo = new DataLoadOptions();

        dlo.AssociateWith <MyObject>(i => i.Children.OrderBy(c => c.DisplayOrder));
        LoadOptions = dlo;
    }
Example #6
0
        static void Listing14_12()
        {
            Console.WriteLine("{0} : Begin", new StackTrace(0, true).GetFrame(0).GetMethod().Name);

            Northwind db = new Northwind(@"Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI;");

            DataLoadOptions dlo = new DataLoadOptions();

            dlo.AssociateWith <Customer>(c => from o in c.Orders
                                         where o.OrderID < 10700
                                         orderby o.OrderDate descending
                                         select o);
            db.LoadOptions = dlo;

            IQueryable <Customer> custs = from c in db.Customers
                                          where c.Country == "UK" &&
                                          c.City == "London"
                                          orderby c.CustomerID
                                          select c;

            foreach (Customer cust in custs)
            {
                Console.WriteLine("{0} - {1}", cust.CompanyName, cust.ContactName);
                foreach (Order order in cust.Orders)
                {
                    Console.WriteLine("    {0} {1}", order.OrderID, order.OrderDate);
                }
            }

            Console.WriteLine("{0} : End", new StackTrace(0, true).GetFrame(0).GetMethod().Name);
        }
Example #7
0
        void method10()
        {
            // <Snippet10>
            Northwnd db = new Northwnd(@"northwnd.mdf");
            // Preload Orders for Customer.
            // One directive per relationship to be preloaded.
            DataLoadOptions ds = new DataLoadOptions();

            ds.LoadWith <Customer>(c => c.Orders);
            ds.AssociateWith <Customer>
                (c => c.Orders.Where(p => p.ShippedDate != DateTime.Today));
            db.LoadOptions = ds;

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

            foreach (Customer custObj in custQuery)
            {
                Console.WriteLine("Customer ID: {0}", custObj.CustomerID);
                foreach (Order ord in custObj.Orders)
                {
                    Console.WriteLine("\tOrder ID: {0}", ord.OrderID);
                    foreach (OrderDetail detail in ord.OrderDetails)
                    {
                        Console.WriteLine("\t\tProduct ID: {0}", detail.ProductID);
                    }
                }
            }
            // </Snippet10>
        }
        /// <summary>
        /// Query database and load the information for project
        /// </summary>
        /// <param name="trackId">ID of loading project</param>
        public override void LoadData(int trackId)
        {
            var options = new DataLoadOptions();

            options.AssociateWith <ToDoTrack>(x => x.Samples.OrderBy(y => y.InitialTact));
            this.DataBaseContext.LoadOptions = options;
            this._currentTrack = this.DataBaseContext.Tracks.FirstOrDefault(x => x.Id == trackId);
        }
        public void DataLoadOptions_DifferentAssociateWithFields_AreNotEqual()
        {
            var dlo1 = new DataLoadOptions();

            dlo1.AssociateWith <TestEntity25>(e => e.Values);

            var dlo2 = new DataLoadOptions();

            Assert.AreNotEqual(dlo1, dlo2);
        }
Example #10
0
        static Database ReadFromDatabase(NorthwindDataContext ctx)
        {
            Database db = new Database();

            DataLoadOptions opt = new DataLoadOptions();

            opt.AssociateWith <Order>(order => order.Lines);
            ctx.LoadOptions = opt;
            db.Orders.AddRange(ctx.Orders);

            return(db);
        }
        public void DataLoadOptions_SameAssociateWithFields_AreEqual()
        {
            var dlo1 = new DataLoadOptions();

            dlo1.AssociateWith <TestEntity25>(e => e.Values);

            var dlo2 = new DataLoadOptions();

            dlo2.AssociateWith <TestEntity25>(e => e.Values);

            Assert.AreEqual(dlo1, dlo2);
            Assert.AreEqual(dlo1.GetHashCode(), dlo2.GetHashCode());
        }
Example #12
0
 internal static void ConditionalEagerLoading()
 {
     using (AdventureWorks adventureWorks = new AdventureWorks())
     {
         DataLoadOptions options = new DataLoadOptions();
         options.LoadWith <ProductSubcategory>(subcategory => subcategory.Products);
         options.AssociateWith <ProductSubcategory>(subcategory => subcategory.Products.Where(
                                                        product => product.ListPrice > 0));
         adventureWorks.LoadOptions = options;
         IQueryable <ProductSubcategory> subcategories = adventureWorks.ProductSubcategories;
         subcategories.ForEach(subcategory => Trace.WriteLine(
                                   $@"{subcategory.Name}: {string.Join(
                 ", ", subcategory.Products.Select(product => product.Name))}"));
     }
 }
        static Database ReadFromDatabase(this NorthwindDataContext ctx, string path)
        {
            Database db = new Database();

            DataLoadOptions opt = new DataLoadOptions();

            opt.AssociateWith <Order>(order => order.Lines);
            ctx.LoadOptions = opt;
            db.Orders.AddRange(ctx.Orders);

            using (FileStream fs = File.Create(path))
            {
                Serializer.Serialize(fs, db);
            }
            return(db);
        }
        public DataBaseViewModel(string connectionString)
        {
            dataBase = new DataBaseContext(connectionString);

            DataLoadOptions loadOptions = new DataLoadOptions();
            loadOptions.AssociateWith<Dictionary>(x => x.Words.OrderBy(y => y.Original));
            dataBase.LoadOptions = loadOptions;

            LoadLanguages();
            if (Languages.Count == 0)
            {
                AddLanguages(new Language[] {
                        new Language() { Code = "en", Name = "English" },
                        new Language() { Code = "ru", Name = "Русский" },
                        new Language() { Code = "lv", Name = "Latviešu" }
                    });
            }
        }
Example #15
0
        public Course GetByUrlName(string urlName)
        {
            var loadOptions = new DataLoadOptions();

            loadOptions.LoadWith <Course>(c => c.CourseContents);
            loadOptions.LoadWith <Course>(c => c.CoursePrerequisites);
            loadOptions.AssociateWith <Course>(c =>
                                               c.CourseContents.OrderBy(cc => cc.ModuleNumber));

            context.LoadOptions = loadOptions;
            var course = GetAll().
                         Where(c => c.IsActive && c.UrlName == urlName)
                         .OrderBy(x => x.Course_ID).FirstOrDefault();

            if (course != null)
            {
                course.Prices = PriceService.GetAllPricesForCourse(course.Course_TC, null);
            }

            return(course);
        }
        /// <summary>
        /// Handles the Load event of the MeetingsViewerForm control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        private void MeetingsViewerForm_Load(object sender, EventArgs e)
        {
            MeetingDataContext mdc = new MeetingDataContext(
                ConfigurationManager.ConnectionStrings["hamwicConnectionString"].ConnectionString);

            DataLoadOptions dlo = new DataLoadOptions();
            dlo.LoadWith<Subgroup>(s => s.Name);
            dlo.AssociateWith<Subgroup>(s => s.Name);
            mdc.LoadOptions = dlo;

            var meetings = from m in mdc.Meetings
                           from s in mdc.Subgroups
                           select new
                           {
                               m.Id,
                               m.Location_,
                               s.Name,
                               m.DateTimeFrom,
                               m.DateTimeTo
                           };
            SetupDataGridView(meetings);
        }
Example #17
0
        /// <summary>
        /// Converts LoadOptions to LinqToSql DataLoadOptions.
        /// </summary>
        /// <param name="dataContextLoadOptions">
        /// The data context load options.
        /// </param>
        /// <param name="loadOptions">
        /// The load options.
        /// </param>
        protected virtual void ApplyLoadOptions(DataLoadOptions dataContextLoadOptions, LoadOptions loadOptions)
        {
            if (dataContextLoadOptions == null)
            {
                throw new ArgumentNullException("dataContextLoadOptions");
            }

            if (loadOptions == null)
            {
                throw new ArgumentNullException("loadOptions");
            }

            foreach (LoadWithOption o in loadOptions.LoadWithOptions)
            {
                dataContextLoadOptions.LoadWith(o.Member);

                if (o.Association != null)
                {
                    dataContextLoadOptions.AssociateWith(o.Association);
                }
            }
        }
Example #18
0
        /// <summary>
        /// Handles the Load event of the MeetingsViewerForm control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        private void MeetingsViewerForm_Load(object sender, EventArgs e)
        {
            MeetingDataContext mdc = new MeetingDataContext(
                ConfigurationManager.ConnectionStrings["hamwicConnectionString"].ConnectionString);

            DataLoadOptions dlo = new DataLoadOptions();

            dlo.LoadWith <Subgroup>(s => s.Name);
            dlo.AssociateWith <Subgroup>(s => s.Name);
            mdc.LoadOptions = dlo;

            var meetings = from m in mdc.Meetings
                           from s in mdc.Subgroups
                           select new
            {
                m.Id,
                m.Location_,
                s.Name,
                m.DateTimeFrom,
                m.DateTimeTo
            };

            SetupDataGridView(meetings);
        }
Example #19
0
 public LoadOptions AssociateWith <T>(Expression <Func <T, object> > expression)
 {
     dataLoadOptions.AssociateWith <T>(expression);
     return(this);
 }
        static void Main(string[] args)
        {
            try
            {
                var cb = new SqlConnectionStringBuilder();
                cb.DataSource     = "server-1337.database.windows.net";
                cb.UserID         = "CommonUser"; // read only
                cb.Password       = "******";
                cb.InitialCatalog = "generailDB";

                using (InstagramDataContext db = new InstagramDataContext(cb.ConnectionString))
                {
                    #region Select
                    IEnumerable <string> names =
                        from u in db.comments
                        orderby u.id
                        select u.comment_text;
                    foreach (string n in names)
                    {
                        Console.WriteLine(n);
                    }
                    Console.WriteLine();
                    #endregion

                    #region Update

                    /*
                     * string upUsername = "******";
                     * user upUser =
                     *  (from u in db.users
                     *   orderby u.id
                     *   where u.id == 1
                     *   select u).Single<user>();
                     * upUser.username = upUsername;
                     * Console.WriteLine($"Update id = 1 username to '{upUsername}'");
                     * Console.WriteLine();
                     */
                    #endregion

                    #region Insert

                    /*
                     * string newUsername = "******";
                     * user newUser = new user { username = newUsername };
                     * db.users.InsertOnSubmit(newUser);
                     * Console.WriteLine($"Insert username to '{newUsername}'");
                     * Console.WriteLine();
                     */
                    #endregion

                    #region Delete

                    /*
                     * user delUser =
                     *  (from u in db.users
                     *   orderby u.id descending
                     *   select u).First<user>();
                     * if (delUser != null)
                     *  db.users.DeleteOnSubmit(delUser);
                     * Console.WriteLine($"Delete Last record");
                     * Console.WriteLine();
                     */
                    #endregion

                    db.SubmitChanges();

                    #region Select
                    names =
                        from u in db.users
                        orderby u.id
                        select u.username;
                    foreach (string n in names)
                    {
                        Console.WriteLine(n);
                    }
                    // Console.WriteLine($"There are {names.Count()} users");
                    Console.WriteLine();
                    #endregion
                }

                #region Select --Association Update--
                DataLoadOptions dl = new DataLoadOptions();
                dl.LoadWith <user>(u => u.photos);
                dl.AssociateWith <user>(u => u.photos.Where(p => true));

                using (InstagramDataContext db = new InstagramDataContext(cb.ConnectionString))
                {
                    // db.LoadOptions = dl;
                    // db.Log = Console.Out;
                    var users = from u in db.users select u;
                    foreach (var u in users)
                    {
                        Console.WriteLine($"There are {u.photos.Count()} products in category {u.username}");
                    }
                }
                # endregion
            }
            catch (InvalidOperationException e)
            {
                Console.WriteLine(e.ToString());
            }
            catch (SqlException e)
            {
                Console.WriteLine(e.ToString());
            }

            Console.ReadKey();
        }
Example #21
0
        static void Main(string[] args)
        {
            #region linq
            {  // 流式运算符
               // 查询表达式
                {
                    // 查询运算符中Lambda表达式针对的是输入序列的每一个元素,而非输入序列整体
                    // 每一个范围变量 如n,其实例都位于Lambda表达式的私有作用域中
                    // 混合查询
                    string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" };
                    // 计算包含字母 “a” 的字符串数目
                    int num = (from n in names where n.Contains("a") select n).Count();

                    // 按照字母顺序获得第一个名字
                    string firstName = (from n in names orderby n select n).First();

                    // 单独使用流式运算符
                    num       = names.Where(n => n.Contains("a")).Count();
                    firstName = names.OrderBy(n => n).First();

                    // 延续执行
                    // 原理:实例化一个装饰了输入序列的枚举类
                    // 特点: 当枚举时才会真正执行,同时重复枚举会带来重复执行,使用ToArray 或 ToList 避免重复执行

                    //
                    Console.WriteLine("***************Linq*****************");
                    //LinqShow show = new LinqShow();
                    //show.Show();
                    int[]             seq1   = { 1, 2, 3 };
                    int[]             seq2   = { 3, 4, 5 };
                    IEnumerable <int> concat = seq1.Concat(seq2);   // 连接
                    IEnumerable <int> union  = seq1.Union(seq2);    // 连接 并去掉重复
                }
                // 子查询
                {
                    // 获取数组中长度最短的元素
                    string[]             names  = { "Tom", "Dick", "Harry", "Mary", "Jay" };
                    IEnumerable <string> query1 = names.Where(n => n.Length == names.OrderBy(n2 => n2.Length)
                                                              .Select(n2 => n2.Length).First());
                    IEnumerable <string> query2 = from n in names
                                                  where n.Length ==
                                                  (from n2 in names orderby n2.Length select n2.Length).First()
                                                  select n;
                    IEnumerable <string> query3 = from n in names
                                                  where n.Length == names.OrderBy(n2 => n2.Length).First().Length
                                                  select n;
                    IEnumerable <string> query4 = from n in names
                                                  where n.Length ==
                                                  names.Min(n2 => n2.Length)
                                                  select n;
                    IEnumerable <string> query5 = names.Where(n => n.Length == names.Min(n2 => n2.Length));
                    // 外部查询内嵌子查询的运行效率低:子查询会随外层循环迭代重复进行计算
                    // 分别执行子查询和外部查询避免低效操作
                    int shortest = names.Min(n => n.Length);
                    IEnumerable <string> query6 = from n in names
                                                  where n.Length == shortest
                                                  select n;
                }
                // 查询构造方式
                {
                    // 1.渐进式
                    // 元音字母移除 --> 所有长度大于2的名字按照字母排序
                    string[]             names  = { "Tom", "Dick", "Harry", "Mary", "Jay" };
                    IEnumerable <string> query1 = names.Select(n => Regex.Replace(n, "[aeiou]", ""))
                                                  .Where(n => n.Length > 2)
                                                  .OrderBy(n => n);

                    // 2.into关键字
                    // 触发继续查询 或 触发GroupJoin
                    IEnumerable <string> query2 = from n in names
                                                  select Regex.Replace(n, "[aeiou]", "")
                                                  into n2
                                                      where n2.Length > 2
                                                  orderby n2
                                                  select n2;

                    // 3.包装
                    IEnumerable <string> query3 = from n1 in
                                                  (
                        from n2 in names
                        select Regex.Replace(n2, "[aeiou]", "")

                                                  )
                                                  where n1.Length > 2
                                                  orderby n1
                                                  select n1;
                }
                // 映射方式
                {
                    // 1.Select new 匿名类型
                    // 元音字母移除 --> 找出所有长度大于2的名字 --> 将原始字母排序
                    string[]             names  = { "Tom", "Dick", "Harry", "Mary", "Jay" };
                    IEnumerable <string> query1 = from n in names
                                                  select new
                    {
                        Original = n,
                        Vowelles = Regex.Replace(n, "[aeiou]", "")
                    }
                    into temp
                    where temp.Vowelles.Length > 2
                    orderby temp.Original
                    select temp.Original;
                    // 2.let 在查询中定义新常量,新常量与范围变量 并存
                    IEnumerable <string> query2 = from n in names
                                                  let vowlles = Regex.Replace(n, "[aeiou]", "")
                                                                where vowlles.Length > 2
                                                                orderby n
                                                                select n;
                }
                ////////////////////////////////////////////
                ///
                // 解释型查询
                {
                    // IQuerybale
                    // L2S EF
                    // DataContext 与 ObjectContext 不是线程安全的,在多层应用中,中间层方法应当为每个客户端请求创建一个全新的上下文对象,【分散】多个请求【同时】对数据库服务器的更新

                    {
                        // 1.LINQ to SQL (L2S)
                        DataContext         dataContext = new DataContext("连接数据库字符串");
                        Table <Customer>    customers   = dataContext.GetTable <Customer>();
                        IQueryable <string> query       = from c in customers
                                                          where c.Name.Contains("a")
                                                          orderby c.Name.Length
                                                          select c.Name.ToUpper();

                        foreach (string name in query)
                        {
                            Console.WriteLine(name);
                        }
                        // 综合使用解释型查询 和 本地查询
                        // 在外部得到本地查询,其数据源于内侧的解释型查询
                        IEnumerable <string> query1 = customers.Select(c => c.Name.ToUpper())
                                                      .OrderBy(n => n)
                                                      .Pair()       // 此处开始 本地查询
                                                      .Select((n, i) => "Pari " + i + " = " + n);
                        foreach (string name in query)
                        {
                            Console.WriteLine(name);
                        }
                        // AsEnumerable<T> 将远程查询 IQueryable<T> 转化为 本地查询 IEnumerable<T>

                        // 提交
                        Customer cust = customers.OrderBy(c => c.ID).First();
                        cust.Name = "lianggan13";
                        dataContext.SubmitChanges();
                        // 关闭上下文追踪
                        dataContext.ObjectTrackingEnabled = false;

                        // 提前设置筛选条件
                        // AssociateWith 筛选特定关系的检索对象
                        DataLoadOptions options = new DataLoadOptions();
                        options.AssociateWith <Customer>(c => c.Purchases.Where(p => p.Price > 1000));
                        dataContext.LoadOptions = options;

                        // 立即加载
                        // LoadWith 在父实体加载时,也会立即加载其上的关系子体
                        options.LoadWith <Customer>(c => c.Purchases);
                        dataContext.LoadOptions = options;
                        foreach (Customer c in customers) // context.Customers
                        {
                            foreach (Purchase p in c.Purchases)
                            {
                                Console.WriteLine(c.Name + " bought a " + p.Desccription);
                            }
                        }
                    }

                    {
                        // 2.EF (Entity Data Model)
                        ObjectContext objectContext = new ObjectContext("实体连接字符串");
                        objectContext.DefaultContainerName = "LgEntities";
                        ObjectSet <Customer> customers = objectContext.CreateObjectSet <Customer>();
                        Customer             cust      = customers.Single(c => c.ID == 2);
                        // 提交
                        cust.Name = "lianggan13";
                        objectContext.SaveChanges();

                        // 关闭上下文追踪
                        customers.MergeOption = MergeOption.NoTracking;

                        // 立即加载
                        // Include
                        foreach (Customer c in customers.Include("Purchases"))
                        {
                            foreach (Purchase p in c.Purchases)
                            {
                                Console.WriteLine(p.Desccription);
                            }
                        }
                    }
                    {
                        // 委托与表达式树
                        // 本地查询使用 Enumerable 运算符,接受委托
                        // 解释型查询使用 Queryable 运算符,接受表达式树
                        var dataContext = new DataContext("数据库连接字符串");
                        var products    = dataContext.GetTable <Product>();

                        IQueryable <Product>
                        sqlQuery = products.Where(Product.IsSelling());
                        IEnumerable <Product>
                        localQuery = products.AsEnumerable().Where(Product.IsSelling().Compile());

                        // AsQueryable 将本地集合转为远程序列上执行
                    }
                }

                Console.ReadKey();
            }

            #endregion
        }
Example #22
0
        public void LinqToSqlObject04() {

            Northwind db2 = new Northwind(connString);
            db2.Log = this.OutputStreamWriter;

            DataLoadOptions ds = new DataLoadOptions();
            ds.LoadWith<Customer>(p => p.Orders);
            ds.LoadWith<Order>(p => p.OrderDetails);
            ds.AssociateWith<Order>(p=>p.OrderDetails.OrderBy(o=>o.Quantity));

            db2.LoadOptions = ds;
         
            var custs = (
                from c in db2.Customers
                where c.City == "London"
                select c );

            foreach (var cust in custs) {
                foreach (var ord in cust.Orders) {
                    foreach (var orderDetail in ord.OrderDetails) {
                        Console.WriteLine("CustomerID {0} has an OrderID {1} with ProductID {2} that has Quantity {3}.",
                            cust.CustomerID, ord.OrderID, orderDetail.ProductID, orderDetail.Quantity );
                    }
                }
            }
        }
Example #23
0
        /// <summary>Initializes all data for a zone - spawns, zone points, AA, etc.</summary>
        private bool Init(ushort zoneId, ZoneInstanceType ziType)
        {
            // Load the zone along with associated zone points, spawns, spawn groups, spawn group entries and NPCs.
            // TODO: Probably will want to load this differently when zone state persistance is in (join to a state table for spawns?)
            DataLoadOptions dlo = new DataLoadOptions();
            dlo.LoadWith<Zone>(z => z.ZonePoints);
            dlo.LoadWith<Zone>(z => z.Doors);
            dlo.LoadWith<Zone>(z => z.Spawns);
            dlo.LoadWith<Internals.Data.Spawn>(s => s.SpawnGroup);
            dlo.LoadWith<SpawnGroup>(sg => sg.SpawnGroupEntries);
            dlo.AssociateWith<SpawnGroup>(sg => sg.SpawnGroupEntries.OrderBy(sge => sge.Chance));   // sort the spawnGroupEntries by chance
            dlo.LoadWith<SpawnGroupEntry>(sge => sge.Npc);
            dlo.LoadWith<Npc>(npc => npc.Loot);
            dlo.LoadWith<Loot>(l => l.LootEntries);
            dlo.LoadWith<LootEntry>(le => le.LootDrops);
            dlo.LoadWith<LootDrop>(ld => ld.Item);  // TODO: can we trim how much of an item comes back?

            using (EmuDataContext dbCtx = new EmuDataContext())
            {
                dbCtx.ObjectTrackingEnabled = false;    // only loading referential data
                dbCtx.LoadOptions = dlo;    // TODO: use profiler to make sure we get it all in one call
                //dbCtx.Log = new Log4NetWriter(typeof(ZoneServer));
                _zone = dbCtx.Zones.Single(z => z.ZoneID == zoneId);
            }

            this.Zone.InitNewZoneStruct();
            _instanceType = ziType;

            // Load map & water map
            _map = new Map();
            _waterMap = new WaterMap();
            try
            {
                if (!_map.LoadMapFromFile(_zone.ShortName))
                    return false;

                if (!_waterMap.LoadMapFromFile(_zone.ShortName))
                    _waterMap = null;
            }
            catch (Exception e)
            {
                _log.Error("Error during map loading", e);
            }

            _mobMgr.Init();     // Must be done prior to any doors, mobs or player init

            if (_zone.Doors.Count > 0)
            {
                foreach (Door d in _zone.Doors)
                    d.EntityId = GetNewEntityId();  // Assign each door an entity Id

                _log.InfoFormat("Loaded {0} doors", _zone.Doors.Count);
            }
            else
                _log.Warn("No doors loaded");

            // TODO: Load Spawn Conditions

            SpawnTimerCallback(null);   // Load spawns NOW
            _log.InfoFormat("Loaded {0} Spawn", _mobMgr.MobCount);

            // TODO: Implement zone state persistance

            // TODO: Load corpses

            // TODO: Load traps

            // TODO: Load ground spawns

            // TODO: Load objects (tradeskill containers, maybe books, etc.)

            _maxSpellId = WorldSvc.GetMaxSpellId();
            if (_maxSpellId == 0)
                _log.Error("Max SpellId equals zero.  Problem with spell loading in world?");

            // TODO: Load blocked spells

            // TODO: Load guilds, factions, titles, AA, Tributes, corpse timers?

            // TODO: Load merchant data

            // TODO: Load petition data

            // TODO: Load graveyard

            // TODO: Load timezone data

            // TODO: Implement server time keeping in world and then sync up here (see end of orig Init and bootup routines)

            // Just before we finish, start up the various timers
            _spawnTimer.Change(30000, SPAWN_TIMER_INTERVAL);    // We've already populated the spawn list, so wait a bit
            _spawnQueueTimer.Change(5000, SPAWN_QUEUE_TIMER_INTERVAL);  // wait 5 sec before worrying about queued spawn packets
            _doorTimer.Change(10000, DOOR_TIMER_INTERVAL);  // wait 10 sec before worrying about doors

            // Initialize weather timer
            if (_zone.Weather <= 3 && _zone.Weather > 0)
            {
                Random rand = new Random();
                _weatherTimer.Change(0, (rand.Next(1800, 7200) + 30) * 2000);
            }

            return true;
        }
Example #24
0
        static Database ReadFromDatabase(this NorthwindDataContext ctx, string path) {
            Database db = new Database();
        
            DataLoadOptions opt = new DataLoadOptions();
            opt.AssociateWith<Order>(order => order.Lines);
            ctx.LoadOptions = opt;
            db.Orders.AddRange(ctx.Orders);

            using (FileStream fs = File.Create(path))
            {
                Serializer.Serialize(fs, db);
            }
            return db;            
        }
Example #25
0
        public void LinqToSqlObject03() {

            Northwind db2 = new Northwind(connString);
            db2.Log = this.OutputStreamWriter;

            DataLoadOptions ds = new DataLoadOptions();
            ds.AssociateWith<nwind.Customer>(p => p.Orders.Where(o=>o.ShipVia > 1));

            db2.LoadOptions = ds;
            var custs =
                from c in db2.Customers
                where c.City == "London"
                select c;

            foreach (var cust in custs) {
                foreach (var ord in cust.Orders) {
                    foreach (var orderDetail in ord.OrderDetails) {
                        Console.WriteLine("CustomerID {0} has an OrderID {1} that ShipVia is {2} with ProductID {3} that has name {4}.",
                            cust.CustomerID, ord.OrderID, ord.ShipVia, orderDetail.ProductID, orderDetail.Product.ProductName);
                    }
                }
            }
        }
Example #26
0
        public override void Run()
        {
            State = WorkerState.Working;
            _parsedSkuExclusions = ParseSkuInclusionAndExclusions(SkuExclusions);
            _parsedSkuInclusions = ParseSkuInclusionAndExclusions(SkuInclusions);

            _delimiter = FieldDelimiter.GetValue().ToString();
            _currentDb = new SkuDataDbDataContext();

            var dlo = new DataLoadOptions();

            dlo.LoadWith <TaxonomyInfo>(taxonomyInfo => taxonomyInfo.TaxonomyDatas);
            dlo.LoadWith <EntityInfo>(entityInfo => entityInfo.EntityDatas);
            dlo.LoadWith <SchemaInfo>(schemaInfo => schemaInfo.SchemaDatas);

            dlo.AssociateWith <TaxonomyInfo>(taxonomyInfo => taxonomyInfo.TaxonomyDatas.Where(p => p.Active));
            dlo.AssociateWith <EntityInfo>(entityInfo => entityInfo.EntityDatas.Where(p => p.Active || p.BeforeEntity));
            dlo.AssociateWith <SchemaInfo>(schemaInfo => schemaInfo.SchemaDatas.Where(p => p.Active));
            dlo.AssociateWith <TaxonomyInfo>(taxonomyInfo => taxonomyInfo.SkuInfos.Where(p => p.Active));

            _currentDb.LoadOptions    = dlo;
            _currentDb.CommandTimeout = 2000;

            _currentDb.Connection.Open();
            _currentDb.Connection.ChangeDatabase(AryaTools.Instance.InstanceData.Dc.Connection.Database);


            var fi           = new FileInfo(ExportFileName);
            var baseFileName = fi.FullName.Replace(fi.Extension, string.Empty);

            _attributeFile = new StreamWriter(baseFileName + "_attributes.txt", false, Encoding.UTF8);
            _valueFile     = new StreamWriter(baseFileName + "_values.txt", false, Encoding.UTF8);
            _skuFile       = new StreamWriter(baseFileName + "_skus.txt", false, Encoding.UTF8);

            StatusMessage = "Init";
            var allExportTaxonomyIds =
                Taxonomies.Cast <ExtendedTaxonomyInfo>().Select(p => p.Taxonomy.ID).Distinct().ToList();
            var exportTaxonomies = _currentDb.TaxonomyInfos.Where(p => allExportTaxonomyIds.Contains(p.ID)).ToList();
            var allChildren      = exportTaxonomies.SelectMany(p => p.AllChildren).Distinct().ToList();
            var allLeafChildren  = exportTaxonomies.SelectMany(p => p.AllLeafChildren).Distinct().ToList();
            var maxDepth         = 0;

            if (allChildren.Count == 0 && allLeafChildren.Count != 0)
            {
                maxDepth =
                    allLeafChildren.Select(
                        child => child.ToString().Split(new[] { TaxonomyInfo.Delimiter }, StringSplitOptions.None).Length)
                    .Max();
            }

            else if (allLeafChildren.Count == 0 && allChildren.Count != 0)
            {
                maxDepth =
                    allChildren.Select(
                        child => child.ToString().Split(new[] { TaxonomyInfo.Delimiter }, StringSplitOptions.None).Length)
                    .Max();
            }

            else if (allLeafChildren.Count != 0 && allChildren.Count != 0)
            {
                if (allLeafChildren.Count >= allChildren.Count)
                {
                    maxDepth =
                        allLeafChildren.Select(
                            child =>
                            child.ToString().Split(new[] { TaxonomyInfo.Delimiter }, StringSplitOptions.None).Length).Max();
                }

                else
                {
                    maxDepth =
                        allChildren.Select(
                            child =>
                            child.ToString().Split(new[] { TaxonomyInfo.Delimiter }, StringSplitOptions.None).Length).Max();
                }
            }
            else
            {
                StatusMessage   = "There was no data to export.";
                MaximumProgress = 1;
                CurrentProgress = 1;
                State           = WorkerState.Ready;
            }

            if (IgnoreT1Taxonomy)
            {
                maxDepth--;
            }

            for (var i = 1; i <= maxDepth; i++)
            {
                _attributeFile.Write("T" + i + "\t");
                _valueFile.Write("T" + i + "\t");
                _skuFile.Write("T" + i + "\t");
            }
            _attributeFile.WriteLine(
                "Attribute{0}Node Sku Count{0}Attr. Sku Count{0}Fill Rate{0}Navigation Order{0}Display Order{0}Global",
                _delimiter);
            _valueFile.WriteLine(
                "Attribute{0}Value{0}Uom{0}Node Sku Count{0}Attr. Value Sku Count{0}Value Fill Rate{0}Attr. Fill Rate{0}Navigation Order{0}Display Order{0}Global",
                _delimiter);
            _skuFile.WriteLine(
                "Item Id{0}Node Attr. Count{0}Node Nav. Attr. Count{0}Node Disp. Attr. Count{0}Sku Attr. Count{0}Sku Nav. Attr. Count{0}Sku Disp. Attr. Count{0}Sku Attr. Fill Rate{0}Sku Nav. Attr. Fill Rate{0}Node Disp. Attr. Fill Rate",
                _delimiter);

            CurrentProgress = 0;

            if (allChildren.Count >= allLeafChildren.Count)
            {
                MaximumProgress = allChildren.Count;
                foreach (var child in allChildren)
                {
                    WriteMetricsToFile(child, maxDepth);
                    CurrentProgress++;
                }
            }
            else if (allChildren.Count < allLeafChildren.Count)
            {
                MaximumProgress = allLeafChildren.Count;

                foreach (var child in allLeafChildren)
                {
                    WriteMetricsToFile(child, maxDepth);
                    CurrentProgress++;
                }
            }

            _attributeFile.Close();
            _valueFile.Close();
            _skuFile.Close();

            StatusMessage = "Done!";
            State         = WorkerState.Ready;
        }
Example #27
0
 //private static DataLoadOptions _getCatalogItem2Dlo = GetCatalogItem2DataLoadOptions();
 private static DataLoadOptions GetCatalogItem2DataLoadOptions(string locale)
 {
     var res = new DataLoadOptions();
     res.LoadWith<SeoPartsCatalogItem>( c => c.NameRU );
     res.LoadWith<SeoPartsCatalogItem>( c => c.BodyRU );
     res.LoadWith<SeoPartsCatalogItem>( c => c.PageDescriptionRU );
     res.LoadWith<SeoPartsCatalogItem>( c => c.PageKeywordsRU );
     res.LoadWith<SeoPartsCatalogItem>( c => c.PageFooterRU );
     if (locale != "ru-RU")
     {
         res.LoadWith<SeoPartsCatalogItem>( c => c.SeoPartsCatalogItemsLocs );
         res.AssociateWith<SeoPartsCatalogItem>( c => c.SeoPartsCatalogItemsLocs.Where(i => i.Localization == locale) );
     }
     return res;
 }
Example #28
0
        public static OrderLine LoadOrderLineData(string clientId, int orderLineId, bool TrackEnable)
        {
            using (var dc = new DCFactory<StoreDataContext>())
            {

                DataLoadOptions options = new DataLoadOptions();
                options.LoadWith<OrderLine>(l => l.Order);
                options.LoadWith<OrderLine>(l => l.OrderLineStatusChanges);
                options.AssociateWith<OrderLine>(l => l.OrderLineStatusChanges.OrderBy(sc => sc.StatusChangeTime));
                dc.DataContext.LoadOptions = options;

                dc.DataContext.DeferredLoadingEnabled = false;
                dc.DataContext.ObjectTrackingEnabled = TrackEnable;

                var OrdLn = dc.DataContext.OrderLines.Where(l =>
                    l.OrderLineID == orderLineId &&
                    l.Order.ClientID == clientId).ToArray()[0];

                if (!TrackEnable)
                {
                    OrderLine res2 = new OrderLine();
                    Order o = new Order();
                    OrderLine res = Serializer.JsonClone<OrderLine>(OrdLn, res2);
                    res.Order = Serializer.JsonClone<Order>(OrdLn.Order, o);
                    return res;
                }
                else
                    return OrdLn;
                //return res;
            }
        }
        public override void Run()
        {
            State = WorkerState.Working;
            parsedSkuExclusions = ParseSkuInclusionAndExclusions(SkuExclusions);
            parsedSkuInclusions = ParseSkuInclusionAndExclusions(SkuInclusions);
            //parsedSkuValueInclusions = ParseSkuValueInclusions(SkuValueInclusions);

            taxonomyAttributesCache = new Dictionary <Guid, List <KeyValuePair <Attribute, SchemaData> > >();
            baseAttributeNames      = new Dictionary <string, string>();
            delimiter = FieldDelimiter.GetValue().ToString();

            //Create new context
            currentDb = new SkuDataDbDataContext();
            var dlo = new DataLoadOptions();

            projectField1Name = AryaTools.Instance.InstanceData.CurrentProject.EntityField1Name ?? string.Empty;
            dlo.LoadWith <TaxonomyInfo>(taxonomyInfo => taxonomyInfo.TaxonomyDatas);
            dlo.LoadWith <EntityInfo>(entityInfo => entityInfo.EntityDatas);
            dlo.LoadWith <SchemaInfo>(schemaInfo => schemaInfo.SchemaDatas);

            dlo.AssociateWith <TaxonomyInfo>(taxonomyInfo => taxonomyInfo.TaxonomyDatas.Where(p => p.Active));
            dlo.AssociateWith <EntityInfo>(entityInfo => entityInfo.EntityDatas.Where(p => p.Active));
            dlo.AssociateWith <SchemaInfo>(schemaInfo => schemaInfo.SchemaDatas.Where(p => p.Active));
            dlo.AssociateWith <TaxonomyInfo>(taxonomyInfo => taxonomyInfo.SkuInfos.Where(p => p.Active));

            currentDb.LoadOptions    = dlo;
            currentDb.CommandTimeout = 2000;

            currentDb.Connection.Open();
            currentDb.Connection.ChangeDatabase(AryaTools.Instance.InstanceData.Dc.Connection.Database);

            InitGlobals(GlobalAttributes.ToList());

            StatusMessage = "Init";

            var fi           = new FileInfo(ExportFileName);
            var baseFileName = fi.FullName.Replace(fi.Extension, string.Empty);

            attributeDataFile = new StreamWriter(baseFileName + "_AttributeData.txt", false, Encoding.UTF8);

            attributeDataFile.Write("ItemId{0}Taxonomy{0}Node Type", delimiter);
            foreach (var attribute in globalAttributeHeaders)
            {
                string attributeHeader = null;
                var    parts           = attribute.Split(':');
                var    noOfHeaders     = 0;
                if (parts.Count() > 1)
                {
                    Int32.TryParse(parts[1].Trim(), out noOfHeaders);
                }
                if (parts.Count() == 2 && noOfHeaders > 0)
                {
                    for (var i = 0; i < noOfHeaders; i++)
                    {
                        if (attributeHeader == null)
                        {
                            attributeHeader += parts[0].Trim() + (i + 1);
                        }
                        else
                        {
                            attributeHeader += "\t" + parts[0].Trim() + (i + 1);
                        }
                    }
                }
                else
                {
                    attributeHeader = attribute;
                }
                attributeDataFile.Write("{0}{1}", delimiter, attributeHeader);
            }

            attributeDataFile.WriteLine("{0}Rank 1{0}Att 1{0}Val 1{0}Uom 1{0}[...]", delimiter);

            CurrentProgress = 0;

            if (SkuCollection != null && SkuCollection.Any())
            {
                var taxonomies =
                    (SkuCollection.Split(2000)
                     .SelectMany(skus => currentDb.Skus.Where(s => skus.Contains(s.ItemID)))
                     .GroupBy(s => s.Taxonomy)).ToList();

                MaximumProgress = taxonomies.Count;

                foreach (var st in taxonomies)
                {
                    WriteSkusToFile(st.Key, st.ToList());
                    CurrentProgress++;
                }
            }
            else
            {
                var allExportTaxonomyIds =
                    Taxonomies.Cast <ExtendedTaxonomyInfo>().Select(p => p.Taxonomy.ID).Distinct().ToList();
                var exportTaxonomies         = currentDb.TaxonomyInfos.Where(p => allExportTaxonomyIds.Contains(p.ID)).ToList();
                var allExportChildTaxonomies = exportTaxonomies.SelectMany(p => p.AllChildren2).Distinct().ToList();

                MaximumProgress = allExportChildTaxonomies.Count;

                foreach (var exportChildTaxonomy in allExportChildTaxonomies)
                {
                    WriteTaxonomyToFile(exportChildTaxonomy);
                    CurrentProgress++;
                }
            }

            attributeDataFile.Close();

            StatusMessage = "Done!";
            State         = WorkerState.Ready;
        }
        /// <summary>
        /// Called when this instance is created.
        /// </summary>
partial         void OnCreated()
        {
            var loadOptions = new DataLoadOptions();
            loadOptions.AssociateWith<Survey>(survey => survey.Sections.OrderBy(section => section.RelativeOrder));
            loadOptions.AssociateWith<Section>(section => section.Questions.OrderBy(question => question.RelativeOrder));
            loadOptions.AssociateWith<Question>(question => question.Answers.OrderBy(answer => answer.RelativeOrder));
            this.LoadOptions = loadOptions;
        }
Example #31
0
 public static DataLoadOptions TpAssociateWith <T>(this DataLoadOptions loadOptions, Expression <Func <T, Object> > expression)
 {
     loadOptions.AssociateWith <T>(expression);
     return(loadOptions);
 }
Example #32
0
        public static Order LoadOrderData(string clientId, int orderId)
        {
            using (var dc = new DCFactory<StoreDataContext>())
            {
                DataLoadOptions options = new DataLoadOptions();
                options.LoadWith<Order>(o => o.OrderLines);
                options.LoadWith<OrderLine>(l => l.OrderLineStatusChanges);
                options.AssociateWith<OrderLine>(l => l.OrderLineStatusChanges.OrderBy(sc => sc.StatusChangeTime));
                dc.DataContext.LoadOptions = options;

                dc.DataContext.DeferredLoadingEnabled = false;

                Order res;

                if (SiteContext.Current.User.Role == SecurityRole.Manager && AcctgRefCatalog.RmsFranches[SiteContext.Current.InternalFranchName].isLite)
                {
                    res = dc.DataContext.Orders.Single(o =>
                        o.OrderID == orderId);
                }
                else
                {
                    res = dc.DataContext.Orders.Single(o =>
                        o.OrderID == orderId &&
                        o.ClientID == clientId);
                }

                foreach (var l in res.OrderLines)
                {
                    var parent = l.ParentOrderLine;
                }
                return res;
            }
        }
Example #33
0
        public override void Run()
        {
            State = WorkerState.Working;
            _parsedSkuExclusions = ParseSkuInclusionAndExclusions(SkuExclusions);
            _parsedSkuInclusions = ParseSkuInclusionAndExclusions(SkuInclusions);

            _delimiter = FieldDelimiter.GetDbValue().ToString();

            //Create new context
            _currentDb = new NatalieDbDataContext();
            var dlo = new DataLoadOptions();

            dlo.LoadWith <TaxonomyInfo>(taxonomyInfo => taxonomyInfo.TaxonomyDatas);
            dlo.LoadWith <EntityInfo>(entityInfo => entityInfo.EntityDatas);
            dlo.LoadWith <SchemaInfo>(schemaInfo => schemaInfo.SchemaDatas);

            //dlo.AssociateWith<TaxonomyInfo>(taxonomyInfo => taxonomyInfo.TaxonomyDatas.Where(p => p.Active));
            dlo.AssociateWith <EntityInfo>(entityInfo => entityInfo.EntityDatas.Where(p => p.Active));
            dlo.AssociateWith <SchemaInfo>(schemaInfo => schemaInfo.SchemaDatas.Where(p => p.Active));
            //dlo.AssociateWith<TaxonomyInfo>(taxonomyInfo => taxonomyInfo.SkuInfos.Where(p => p.Active));

            _currentDb.LoadOptions    = dlo;
            _currentDb.CommandTimeout = 2000;

            _currentDb.Connection.Open();
            _currentDb.Connection.ChangeDatabase(NatalieTools.Instance.InstanceData.Dc.Connection.Database);

            _separator = NatalieTools.Instance.InstanceData.CurrentProject.ListSeparator;

            StatusMessage = "Init";

            var fi = new FileInfo(ExportFileName);

            _baseFileName = fi.FullName.Replace(fi.Extension, string.Empty);

            //_taxonomyFile = new StreamWriter(_baseFileName + "_Classification.txt", false, Encoding.UTF8);
            //_taxonomyFile.WriteLine("ItemId{0}New Taxonomy{0}Node Type{0}Old Taxonomy", _delimiter);

            var exportTaxonomyIds =
                Taxonomies.Cast <ExtendedTaxonomyInfo>().Select(p => p.Taxonomy.ID).Distinct().ToList();
            var exportTaxonomies = _currentDb.TaxonomyInfos.Where(p => exportTaxonomyIds.Contains(p.ID)).ToList();

            var allExportTaxonomies =
                exportTaxonomies.SelectMany(p => p.AllChildren2).Union(exportTaxonomies).Distinct().ToList();

            var exportGroups = allExportTaxonomies.GroupBy(GetTaxPrefix).ToList();

            CurrentProgress = 0;
            MaximumProgress = exportGroups.Count();

            foreach (var grp in exportGroups)
            {
                WriteTaxonomyToFile(grp.Select(g => g), grp.Key);
                CurrentProgress++;
            }

            //_taxonomyFile.Close();

            StatusMessage = "Done!";
            State         = WorkerState.Ready;
        }
Example #34
0
        public override void Run()
        {
            State = WorkerState.Working;
            _parsedSkuExclusions = ParseSkuInclusionAndExclusions(SkuExclusions);
            _parsedSkuInclusions = ParseSkuInclusionAndExclusions(SkuInclusions);
            //parsedSkuValueInclusions = ParseSkuValueInclusions(SkuValueInclusions);

            _taxonomyAttributesCache = new Dictionary <Guid, List <Tuple <Attribute, decimal, decimal> > >();
            _baseAttributeNames      = new Dictionary <string, string>();
            _delimiter = FieldDelimiter.GetValue().ToString();

            //Create new context
            _currentDb = new SkuDataDbDataContext();
            var dlo = new DataLoadOptions();

            _projectField1Name = AryaTools.Instance.InstanceData.CurrentProject.EntityField1Name ?? string.Empty;
            dlo.LoadWith <TaxonomyInfo>(taxonomyInfo => taxonomyInfo.TaxonomyDatas);
            dlo.LoadWith <EntityInfo>(entityInfo => entityInfo.EntityDatas);
            dlo.LoadWith <SchemaInfo>(schemaInfo => schemaInfo.SchemaDatas);

            //dlo.AssociateWith<TaxonomyInfo>(taxonomyInfo => taxonomyInfo.TaxonomyDatas.Where(p => p.Active));
            //dlo.AssociateWith<EntityInfo>(entityInfo => entityInfo.EntityDatas.Where(p => p.Active));
            dlo.AssociateWith <SchemaInfo>(schemaInfo => schemaInfo.SchemaDatas.Where(p => p.Active));
            //dlo.AssociateWith<TaxonomyInfo>(taxonomyInfo => taxonomyInfo.SkuInfos.Where(p => p.Active));

            _currentDb.LoadOptions    = dlo;
            _currentDb.CommandTimeout = 2000;

            _currentDb.Connection.Open();
            _currentDb.Connection.ChangeDatabase(AryaTools.Instance.InstanceData.Dc.Connection.Database);

            InitGlobals(GlobalAttributes);

            StatusMessage = "Init";

            var fi           = new FileInfo(ExportFileName);
            var baseFileName = fi.FullName.Replace(fi.Extension, string.Empty);

            _taxonomyFile = new StreamWriter(baseFileName + "_Classification.txt", false, Encoding.UTF8);
            _taxonomyFile.WriteLine("ItemId{0}New Taxonomy{0}Node Type{0}Old Taxonomy", _delimiter);

            _attributeDataFile = new StreamWriter(baseFileName + "_AttributeData.txt", false, Encoding.UTF8);
            if (GenerateFileWithBlankValues)
            {
                _blankValuesAttributeDataFile = new StreamWriter(baseFileName + "_AttributeBlanks.txt", false,
                                                                 Encoding.UTF8);
            }

            _attributeDataFile.Write("ItemId{0}Taxonomy{0}Node Type", _delimiter);
            if (GenerateFileWithBlankValues)
            {
                _blankValuesAttributeDataFile.Write("ItemId{0}Taxonomy{0}Node Type", _delimiter);
            }
            foreach (var attribute in _globalAttributeHeaders)
            {
                string attributeHeader = null;
                var    parts           = attribute.Split(':');
                var    noOfHeaders     = 0;
                if (parts.Count() > 1)
                {
                    Int32.TryParse(parts[1].Trim(), out noOfHeaders);
                }
                if (parts.Count() == 2 && noOfHeaders > 0)
                {
                    for (var i = 0; i < noOfHeaders; i++)
                    {
                        if (attributeHeader == null)
                        {
                            attributeHeader += parts[0].Trim() + (i + 1);
                        }
                        else
                        {
                            attributeHeader += "\t" + parts[0].Trim() + (i + 1);
                        }
                    }
                }
                else
                {
                    attributeHeader = attribute;
                }
                _attributeDataFile.Write("{0}{1}", _delimiter, attributeHeader);
                if (GenerateFileWithBlankValues)
                {
                    _blankValuesAttributeDataFile.Write("{0}{1}", _delimiter, attributeHeader);
                }
            }
            if (ExportRanks)
            {
                _attributeDataFile.Write("{0}Rank 1", _delimiter);
                if (GenerateFileWithBlankValues)
                {
                    _blankValuesAttributeDataFile.Write("{0}Rank 1", _delimiter);
                }
            }

            _attributeDataFile.Write("{0}Att 1", _delimiter);
            if (GenerateFileWithBlankValues)
            {
                _blankValuesAttributeDataFile.Write("{0}Att 1", _delimiter);
            }

            if (ExportNewValueColumn)
            {
                _attributeDataFile.Write("{0}New Value 1", _delimiter);
                if (GenerateFileWithBlankValues)
                {
                    _blankValuesAttributeDataFile.Write("{0}New Value 1", _delimiter);
                }
            }

            _attributeDataFile.Write("{0}Val 1", _delimiter);
            if (IncludeUoM)
            {
                _attributeDataFile.Write("{0}Uom 1", _delimiter);
            }
            if (IncludeField1)
            {
                _attributeDataFile.Write("{0}Field 1 1", _delimiter);
            }
            if (IncludeField2)
            {
                _attributeDataFile.Write("{0}Field 2 1", _delimiter);
            }
            if (IncludeField3)
            {
                _attributeDataFile.Write("{0}Field 3 1", _delimiter);
            }
            if (IncludeField4)
            {
                _attributeDataFile.Write("{0}Field 4 1", _delimiter);
            }
            if (IncludeField5)
            {
                _attributeDataFile.Write("{0}Field 5 1", _delimiter);
            }
            _attributeDataFile.WriteLine("{0}[...]", _delimiter);

            if (GenerateFileWithBlankValues)
            {
                _blankValuesAttributeDataFile.Write("{0}Val 1", _delimiter);
                if (IncludeUoM)
                {
                    _blankValuesAttributeDataFile.Write("{0}Uom 1", _delimiter);
                }
                if (IncludeField1)
                {
                    _blankValuesAttributeDataFile.Write("{0}Field 1 1", _delimiter);
                }
                if (IncludeField2)
                {
                    _blankValuesAttributeDataFile.Write("{0}Field 2 1", _delimiter);
                }
                if (IncludeField3)
                {
                    _blankValuesAttributeDataFile.Write("{0}Field 3 1", _delimiter);
                }
                if (IncludeField4)
                {
                    _blankValuesAttributeDataFile.Write("{0}Field 4 1", _delimiter);
                }
                if (IncludeField5)
                {
                    _blankValuesAttributeDataFile.Write("{0}Field 5 1", _delimiter);
                }
                _blankValuesAttributeDataFile.WriteLine("{0}[...]", _delimiter);
            }

            var exportTaxonomyIds =
                Taxonomies.Cast <ExtendedTaxonomyInfo>().Select(p => p.Taxonomy.ID).Distinct().ToList();
            var exportTaxonomies = _currentDb.TaxonomyInfos.Where(p => exportTaxonomyIds.Contains(p.ID)).ToList();

            var allExportTaxonomies =
                exportTaxonomies.SelectMany(p => p.AllChildren2).Union(exportTaxonomies).Distinct().ToList();

            CurrentProgress = 0;
            MaximumProgress = allExportTaxonomies.Count;

            foreach (var exportChildTaxonomy in allExportTaxonomies)
            {
                WriteTaxonomyToFile(exportChildTaxonomy);
                CurrentProgress++;
            }

            _taxonomyFile.Close();
            _attributeDataFile.Close();
            if (GenerateFileWithBlankValues)
            {
                _blankValuesAttributeDataFile.Close();
            }

            StatusMessage = "Done!";
            State         = WorkerState.Ready;
        }