Example #1
0
        public static Dictionary<string, decimal> ConvertToQuarter(Dictionary<string, decimal> data, MainModel mainModel)
        {
            if (!mainModel.IsItQuarter && (mainModel.EndDate - mainModel.StartDate).Days < 365)
            {
                return data;
            }
            var result = new Dictionary<string, decimal>();

            for (int i = 0; i < data.Count; i=i+3)
            {
                var ttMon = mainModel.StartDate.Month;
                while ((int)QuarterEnum.I != ttMon &&
                    (int)QuarterEnum.II != ttMon &&
                    (int)QuarterEnum.III != ttMon &&
                    (int)QuarterEnum.IV != ttMon)
                {
                    ttMon--;
                }
                var quarter = string.Format("{0}, {1}", mainModel.StartDate.Month + i > 12
                    ? ((QuarterEnum)ttMon + i - 12)
                    : ((QuarterEnum)ttMon + i),
                    mainModel.StartDate.Year + ((i + 3) / 12) - mainModel.TimeSpan);
                result.Add(quarter, data.Skip(i).Take((data.Count - i) < 3 ? data.Count - i : 3).Sum(j => j.Value));
            }

            return result;
        }
 private static int FindLowestIndentationLevel(Dictionary<int, int> levels)
 {
     var indentLevels = (levels.ContainsKey(0) && levels[0] == 0) ? levels.Skip(1) : levels;
     int lowestLevel = indentLevels.Aggregate(
         int.MaxValue, (current, level) => (level.Value < current) ? level.Value : current);
     return (lowestLevel == int.MaxValue) ? 0 : lowestLevel;
 }
Example #3
0
        public async Task<Dictionary<string, PostAnalysisResults>> Analyze( List<Post> posts ) {

            var toReturn = new Dictionary<string, PostAnalysisResults>();
            var youTubePosts = new Dictionary<string, List<Post>>();

            foreach ( var post in posts ) {
                toReturn.Add( post.Id, new PostAnalysisResults( post, ModuleEnum ) );
                var ytID = YouTubeHelpers.ExtractVideoId( post.Url.ToString() );

                if ( !string.IsNullOrEmpty( ytID ) ) {
                    if ( !youTubePosts.ContainsKey( ytID ) ) youTubePosts.Add( ytID, new List<Post>() );
                    youTubePosts[ytID].Add( post );
                }

            }
            var yt = new YouTubeService( new BaseClientService.Initializer { ApiKey = YouTubeAPIKey } );

            var req = yt.Videos.List( "snippet" );
            for ( var i = 0; i < youTubePosts.Keys.Count; i += 50 ) {
                var ids = youTubePosts.Keys.Skip( i ).Take( 50 );
                req.Id = string.Join( ",", ids );

                var ytScrape = ScrapeYouTube( youTubePosts.Skip( i ).Take( 50 ).ToDictionary( p => p.Key, p => p.Value ), toReturn );
                var response = await req.ExecuteAsync();

                foreach ( var vid in response.Items ) {
                    var redditPosts = youTubePosts[vid.Id];
                    //var scores = toReturn[post.Id].Scores;

                    var termMatches = TermMatching.Matches( vid.Snippet.Description ).Cast<Match>().Select( m => m.Value ).ToList();
                    termMatches.AddRange( TermMatching.Matches( vid.Snippet.Title ).Cast<Match>().Select( m => m.Value ).ToList().Distinct() );
                    if ( termMatches.Count > 0 ) {
                        foreach ( var post in redditPosts ) {
                            toReturn[post.Id].Scores.Add( new AnalysisScore( STRINGMATCH_SCORE * Settings.ScoreMultiplier, "YouTube video title or description has the following term(s): " + string.Join( ", ", termMatches ), "Match: " + string.Join( ", ", termMatches ), ModuleName, RemovalFlair ) );
                        }
                    }

                }
                await ytScrape;
            }

            return toReturn;
        }
		public void AttachmentStorage_GetAttachmentsAfter(string requestedStorage)
		{
			const int ITEM_COUNT = 20;
			const int SKIP_INDEX = ITEM_COUNT / 4;
			using (var storage = NewTransactionalStorage(requestedStorage))
			{
				var inputData = new Dictionary<Etag, RavenJObject>();
				storage.Batch(
					mutator =>
					{
						int index = 0;
						for (int itemIndex = 0; itemIndex < ITEM_COUNT; itemIndex++)
						{
							var item = RavenJObject.FromObject(new { Name = "Bar_" + itemIndex, Key = "Foo_" + index });
							var dataStream = new MemoryStream();
							item.WriteTo(dataStream);
							// ReSharper disable once RedundantAssignment
							var newEtag = mutator.Attachments.AddAttachment("Foo_" + (index++), null, dataStream, new RavenJObject());
							inputData.Add(newEtag, item);
						}
					});

				var etagAfterSkip = inputData.Skip(SKIP_INDEX).First().Key;

				IList<AttachmentInformation> fetchedAttachmentInformation = null;

				storage.Batch(viewer => fetchedAttachmentInformation = viewer.Attachments.GetAttachmentsAfter(etagAfterSkip, ITEM_COUNT, 4096).ToList());

				Assert.NotNull(fetchedAttachmentInformation);

				//SKIP_INDEX + 1 is because Linq's Skip() fetches items >= than index, and GetAttachmentsAfter() fetches items > than index
				var relevantInputEtags = inputData.Skip(SKIP_INDEX + 1)
												  .Select(row => row.Key)
												  .ToHashSet();

				//verify that all relevant etags were fetched
				var relevantFetchedEtags = fetchedAttachmentInformation.Select(row => row.Etag);
				Assert.True(relevantInputEtags.SetEquals(relevantFetchedEtags));
			}
		}
Example #5
0
        public ActionResult Part_Agreement_Good_Page()
        {
            string provence = Request.Params["provence"];
            string city = Request.Params["city"];
            string price = Request.Params["price"];
            string gys = Request.Params["gys"];
            string id = Request.Params["id"];//商品类别id
            string type = Request.Params["type"];//品牌名称
            // string id = "665";
            // string type = "联想";
            int page = 1;
            if (!string.IsNullOrWhiteSpace(Request.Params["page"]))
            {
                int.TryParse(Request.Params["page"], out page);
            }
            var q = Query<商品>.Where(
                o => o.采购信息.参与协议采购 
                    && o.审核数据.审核状态 == 审核状态.审核通过 
                    && o.商品信息.品牌 != null
                    );

            IEnumerable<BsonValue> p_l = null;
            var q_gys = Query.Null;
            if (!string.IsNullOrEmpty(gys))//根据所有条件查找或根据名称查找
            {
                q_gys = q_gys.And(Query<供应商>.Matches(o => o.企业基本信息.企业名称, gys));
            }

            if (!string.IsNullOrEmpty(provence) && provence != "不限省份")//根据省份查找
            {
                
                q_gys = q_gys.And(Query<供应商>.Where(o=>o.供应商用户信息.协议供应商所属地区.Any(p=>p.省份.Contains(provence))));
                if (!string.IsNullOrEmpty(city) && city != "不限城市")//根据城市查找
                {
                    q_gys = q_gys.And(Query<供应商>.Where(o=>o.供应商用户信息.协议供应商所属地区.Any(p=>p.城市.Contains(city))));
                }
            }
            if (q_gys != null)
            { 
                p_l = 用户管理.列表用户<供应商>(0, 0,
                    Fields<供应商>.Include(o => o.Id),
                    Query<供应商>.EQ(o => o.审核数据.审核状态, 审核状态.审核通过).And(q_gys)
                    ).Select(o => o["_id"]);
            }
            if (!string.IsNullOrEmpty(price))//根据价格查找
            {
            }
            List<商品> good = null;
            if (p_l != null)
            {
                //good = 商品管理.查询分类下商品(long.Parse(id), 0, 0, q.And(Query<商品>.In(o => o.商品信息.所属供应商.用户ID, p_l)), false, SortBy.Ascending("销售信息.价格"));
                good = 商品管理.查询分类下商品(long.Parse(id), 0, 0, q.And(Query<商品>.In(o => o.商品信息.所属供应商.用户ID, p_l))).ToList();
                good.Sort((_1, _2) => _1.销售信息.价格 > _2.销售信息.价格?1:_1.销售信息.价格 < _2.销售信息.价格?-1:0);
            }
            else
            {
                //good = 商品管理.查询分类下商品(long.Parse(id), 0, 0, q, false, SortBy.Ascending("销售信息.价格"));
                good = 商品管理.查询分类下商品(long.Parse(id), 0, 0, q).ToList();
                good.Sort((_1, _2) => _1.销售信息.价格 > _2.销售信息.价格?1:_1.销售信息.价格 < _2.销售信息.价格?-1:0);
            }
            var listagree = new Dictionary<商品, List<string>>();
            
            foreach (var k in good)
            {
                var brand = k.商品信息.品牌 != null ? k.商品信息.品牌.ToLower().Replace(" ", "") : null;
                var t = string.IsNullOrWhiteSpace(type)
                    ? string.IsNullOrWhiteSpace(type)
                    : (!string.IsNullOrWhiteSpace(type) && brand == type);
                if (t)
                {
                    var gh = 商品管理.查询分类下商品(long.Parse(id), 0, 0, q.And(Query<商品>.Where(p => p.商品信息.型号!=null && p.商品信息.型号 == k.商品信息.型号))).ToList();
                    gh.Sort((_1, _2) => _1.销售信息.价格 > _2.销售信息.价格 ? 1 : _1.销售信息.价格 < _2.销售信息.价格 ? -1 : 0);

                    var min_Price = k.销售信息.价格.ToString();
                    var max_Price = k.销售信息.价格.ToString();
                    if (gh.Any())
                    {
                        min_Price = gh.First().销售信息.价格.ToString();
                        max_Price = gh.Last().销售信息.价格.ToString();
                    }
                    var li = new List<string>();
                    li.Add(min_Price);
                    li.Add(max_Price);
                    listagree.Add(k, li);
                }
            }
            long listcount = listagree.Count();
            long maxpagesize = Math.Max((listcount + PAGESIZE_AGREEGOOD - 1) / PAGESIZE_AGREEGOOD, 1);

            ViewData["currentPage"] = page;
            ViewData["pagecount"] = maxpagesize;
            ViewData["商品分类ID"] = id;
            int start_index = PAGESIZE_AGREEGOOD * (page - 1);

            ViewData["分类商品"] = listagree.Skip(start_index).Take(PAGESIZE_AGREEGOOD).ToList();
            return PartialView("Part_Agreement/Part_Agreement_Good_Page");
        }
		public void AttachmentStorage_GetAttachmentsAfter_With_TakeParameter_And_MaxSizeParameter(string requestedStorage)
		{
			var input = new List<dynamic>
			           {
				           new { SkipIndex = 5, Take = 10, MaxSize = 4096},
						   new { SkipIndex = 10, Take = 3, MaxSize = 4096},
						   new { SkipIndex = 6, Take = 15, MaxSize = 4096},
						   new { SkipIndex = 6, Take = 15, MaxSize = 256},
						   new { SkipIndex = 5, Take = 0, MaxSize = 4096},
						   new { SkipIndex = 5, Take = 15, MaxSize = 0},
						   new { SkipIndex = 0, Take = 15, MaxSize = 4096},
					   };

			foreach (var d in input)
			{
				var skipIndex = (int)d.SkipIndex;
				var take = (int)d.Take;
				var maxSize = (int)d.MaxSize;

				var itemCount = (skipIndex + take) * 3;
				using (var storage = NewTransactionalStorage(requestedStorage))
				{
					var inputData = new Dictionary<Etag, RavenJObject>();
					storage.Batch(
						mutator =>
						{
							int index = 0;
							for (int itemIndex = 0; itemIndex < itemCount; itemIndex++)
							{
								var item = RavenJObject.FromObject(new { Name = "Bar_" + itemIndex, Key = "Foo_" + index });
								var dataStream = new MemoryStream();
								item.WriteTo(dataStream);
								// ReSharper disable once RedundantAssignment
								var newEtag = mutator.Attachments.AddAttachment("Foo_" + (index++), null, dataStream, new RavenJObject());
								inputData.Add(newEtag, item);
							}
						});

					var etagAfterSkip = inputData.Skip(skipIndex).First().Key;

					IList<AttachmentInformation> fetchedAttachmentInformation = null;
					storage.Batch(viewer => fetchedAttachmentInformation = viewer.Attachments.GetAttachmentsAfter(etagAfterSkip, take, maxSize).ToList());

					if (maxSize == 0 || take == 0)
						Assert.Empty(fetchedAttachmentInformation);
					else
					{
						//skipIndex + 1 is because Linq's Skip() fetches items >= than index, and GetAttachmentsAfter() fetches items > than index
						var inputDataAfterSkip = inputData.Skip(skipIndex + 1)
							.Take(take)
							.ToDictionary(item => item.Key, item => item.Value);

						var filteredInputData = new Dictionary<Etag, RavenJObject>();
						//limit resulting data by accumulated size
						var totalSizeCounter = 0;
						storage.Batch(viewer =>
						{
							foreach (var item in inputDataAfterSkip)
							{
								var itemSize = viewer.Attachments.GetAttachment(item.Value.Value<string>("Key")).Size;
								totalSizeCounter += itemSize;

								if (totalSizeCounter >= maxSize) break;
								filteredInputData.Add(item.Key, item.Value);
							}
						});

						//verify that all relevant etags were fetched
						Assert.Empty(filteredInputData.Keys
							.Except(fetchedAttachmentInformation.Select(row => row.Etag)));
						Assert.Empty(fetchedAttachmentInformation.Select(row => row.Etag)
							.Except(filteredInputData.Keys));

						for (int itemIndex = skipIndex + 1, fetchedItemIndex = 0;
							itemIndex < skipIndex + 1 + ((filteredInputData.Count < take) ? filteredInputData.Count : take);
							itemIndex++, fetchedItemIndex++)
						{
							var fetchedItem = fetchedAttachmentInformation[fetchedItemIndex];
							Assert.Equal(fetchedItem.Key, filteredInputData[fetchedItem.Etag].Value<string>("Key"));
						}
					}
				}

			}
		}
        public override IOpenSearchResponse GetResponse()
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();

            AtomFeed feed = new AtomFeed();

            int count = string.IsNullOrEmpty(parameters["count"]) ? 20 : int.Parse(parameters["count"]);
            int page = string.IsNullOrEmpty(parameters["startPage"]) ? 1 : int.Parse(parameters["startPage"]);
            int index = string.IsNullOrEmpty(parameters["startIndex"]) ? 1 : int.Parse(parameters["startIndex"]);
            string type = string.IsNullOrEmpty(parameters["auxtype"]) ? "aux_resorb" : parameters["auxtype"];
            bool withOrbits = parameters["orbits"] == "true";

            int absindex = index + ((page - 1) * count);
            int queryindex = absindex % 20;
            int querypage = (absindex / 20) + 1;

            List<AtomItem> items = new List<AtomItem>();

            while (items.Count() < count)
            {

                Uri url = BuildUrl(qcBaseUrl, count, index, page, type, parameters["start"], parameters["stop"]);

                var request = HttpWebRequest.Create(url);

                log.DebugFormat("Query: {0}", url);

                HtmlDocument doc = new HtmlDocument();

                using (var response = request.GetResponse())
                {
                    doc.Load(response.GetResponseStream());
                }

                Dictionary<string, Uri> list = new Dictionary<string, Uri>();

                var pagesli = doc.DocumentNode.SelectNodes("/html/body/div/div/div/div[1]/div/ul/li");
                int lastpage = 1;

                if (pagesli != null)
                {
                    lastpage = pagesli.Max(li =>
                    {
                        int pageo = 0;
                        if (int.TryParse(li.FirstChild.InnerText, out pageo))
                            return pageo;
                        return 0;
                    });
                }

                if (lastpage < querypage)
                    break;

                var trs = doc.DocumentNode.SelectNodes("/html/body/div/div/div/div[1]/table/tbody/tr");

                if (trs == null)
                    break;

                foreach (HtmlNode tr in trs)
                {
                    var a = tr.SelectSingleNode("td/a");
                    log.Debug(a.InnerText);
                    HtmlAttribute href = a.Attributes["href"];
                    var producturl = new Uri(string.Format("{0}/{1}/{2}", qcBaseUrl, type, href.Value));
                    log.Debug(producturl);
                    list.Add(a.InnerText, producturl);
                }

                if (list.Count() == 0)
                    break;

                if (items.FirstOrDefault(i => i.Identifier == list.Last().Key.Replace(".EOF", "")) != null)
                    break;

                items.AddRange(BuildAtomItem(list.Skip(queryindex - 1).Take(count - items.Count()), withOrbits));

                queryindex = 1;
                page++;

            }

            feed.Items = items;

            sw.Stop();

            return new Terradue.OpenSearch.Response.AtomOpenSearchResponse(feed, sw.Elapsed);
        }
Example #8
0
        public async Task PostMulipartFormdataShouldEchoAllValuesCorrectly()
        {
            if (Helper.IsNetworkAvailable())
            {
                var fields = new Dictionary<String, String>
                {
                    { "myname", "foo" },
                    { "bar", "this is some longer text" },
                    { "yeti", "0" },
                };
                var result = await PostDocumentAsync(fields, MimeTypes.MultipartForm);
                var rows = result.QuerySelectorAll("tr");
                var raw = result.QuerySelector("#input").TextContent;

                Assert.AreEqual(3, rows.Length);

                Assert.AreEqual("myname", rows[0].QuerySelector("th").TextContent);
                Assert.AreEqual(fields["myname"], rows[0].QuerySelector("td").TextContent);

                Assert.AreEqual("bar", rows[1].QuerySelector("th").TextContent);
                Assert.AreEqual(fields["bar"], rows[1].QuerySelector("td").TextContent);

                Assert.AreEqual("yeti", rows[2].QuerySelector("th").TextContent);
                Assert.AreEqual(fields["yeti"], rows[2].QuerySelector("td").TextContent);

                var lines = raw.Split('\n');

                Assert.AreEqual(15, lines.Length);

                var emptyLines = new[] { 0, 3, 7, 11, 14 };
                var sameLines = new[] { 1, 5, 9 };
                var nameLines = new[] { 2, 6, 10 };
                var valueLines = new[] { 4, 8, 12 };

                foreach (var emptyLine in emptyLines)
                    Assert.AreEqual(String.Empty, lines[emptyLine]);

                for (int i = 1; i < sameLines.Length; i++)
                    Assert.AreEqual(lines[sameLines[0]], lines[sameLines[i]]);

                Assert.AreEqual(lines[sameLines[0]] + "--", lines[lines.Length - 2]);

                for (int i = 0; i < nameLines.Length; i++)
                {
                    var field = fields.Skip(i).First();
                    Assert.AreEqual("Content-Disposition: form-data; name=\"" + field.Key + "\"", lines[nameLines[i]]);
                    Assert.AreEqual(field.Value, lines[valueLines[i]]);
                }
            }
        }
Example #9
0
        /// <summary>
        /// Load a starship form the old .sss format
        /// </summary>
        /// <param name="fs">Filestream open to active .sss file</param>
        /// <returns>Starship imported from old format</returns>
        /// <exception cref="FormatException">If string values stored in numeric fields</exception>
        /// <exception cref="ArgumentException">If non-standard classes listed</exception>
        public Starship LoadSSS(FileStream fs)
        {
            Dictionary<String, String> file = new Dictionary<string, string>();
            using (StreamReader sr = new StreamReader(fs))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    int pos = line.IndexOf(":");
                    if (pos > 0)
                    {
                        file.Add(line.Substring(0, pos), line.Substring(pos + 1, line.Length - pos - 1));
                    }
                }
            }
            Starship ship = new Starship();
            if (!(String.IsNullOrWhiteSpace(file["customhullname"]) || String.IsNullOrWhiteSpace(file["customhullspeed"]) || String.IsNullOrWhiteSpace(file["customhullman"])
                || String.IsNullOrWhiteSpace(file["customhulldet"]) || String.IsNullOrWhiteSpace(file["customhullint"]) || String.IsNullOrWhiteSpace(file["customhullarmour"])
                || String.IsNullOrWhiteSpace(file["customhullturret"]) || String.IsNullOrWhiteSpace(file["customhullspace"]) || String.IsNullOrWhiteSpace(file["customhullclass"])))
            {
                int sp = 0;
                if (!String.IsNullOrWhiteSpace(file["customhullsp"]))
                    sp = int.Parse(file["customhullsp"]);
                HullType type = HullType.None;
                switch (file["customhullclass"])
                {
                    case "Battle":
                        type = HullType.BattleCruiser;
                        break;
                    case "Grand":
                        type = HullType.GrandCruiser;
                        break;
                    default:
                        type = (HullType)Enum.Parse(typeof(HullType), file["customhullclass"]);
                        break;
                }
                int prow = 0;
                int port = 0;
                int starboard = 0;
                int aft = 0;
                int dorsal = 0;
                int keel = 0;
                for (int i = 1; i <= 6; i++)
                {
                    switch (file["customslot" + i])
                    {
                        case "Prow":
                            prow++;
                            break;
                        case "Port":
                            port++;
                            break;
                        case "Starboard":
                            starboard++;
                            break;
                        case "Dorsal":
                            dorsal++;
                            break;
                        case "Keel":
                            keel++;
                            break;
                        case "Aft":
                            aft++;
                            break;
                    }
                }
                Hulls.Add(new Hull(file["customhullname"], int.Parse(file["customhullspeed"]), int.Parse(file["customhullman"]), int.Parse(file["customhulldet"]), int.Parse(file["customhullint"]),
                    int.Parse(file["customhullarmour"]), int.Parse(file["customhullspace"]), sp, type, file["customhullspecial"], RuleBook.Custom, 0, int.Parse(file["customhullturret"]), prow, dorsal,
                    (port + starboard) / 2, keel, aft));

            }
            ship.Hull = Hulls.Where(x => x.Name.Equals(file["hull"], StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            HullType shipClass = HullType.None;
            if (ship.Hull != null)
                shipClass = ship.Hull.HullTypes;
            //now that ship class and hopefully hull is set, can add custom weapons, then other components custom components can have their hulltypes == shipClass
            for (int i = 1; i <= 6; i++)
            {
                //add each custom weapon - check for duplication
                if (!(String.IsNullOrWhiteSpace(file["customweapon" + i]) || String.IsNullOrWhiteSpace(file["customweapon" + i + "type"]) || String.IsNullOrWhiteSpace(file["customweapon" + i + "range"])))
                {
                    String name = file["customweapon" + i];
                    WeaponType type = WeaponType.Macrobattery;
                    switch (file["customweapon" + i + "type"])
                    {
                        case "Lance":
                            type = WeaponType.Lance;
                            break;
                        case "Landing Bays":
                            type = WeaponType.LandingBay;
                            break;
                        case "Torpedo Tubes":
                            type = WeaponType.TorpedoTube;
                            break;
                        case "Nova Cannon":
                            type = WeaponType.NovaCannon;
                            break;
                    }
                    WeaponSlot slots = WeaponSlot.Auxiliary;//just to be very certain not to have uninitialised
                    if (!String.IsNullOrWhiteSpace(file["customslot" + i]))
                    {
                        slots = (WeaponSlot)Enum.Parse(typeof(WeaponSlot), file["customslot" + i]);
                    }
                    else
                    {
                        switch (type)
                        {
                            case WeaponType.Macrobattery:
                                if (name.IndexOf("Broadside", StringComparison.OrdinalIgnoreCase) >= 0)//ignorecase search for broadside to apply broadside rules
                                    slots = WeaponSlot.Side;
                                else
                                    slots = WeaponSlot.All;
                                break;
                            case WeaponType.Lance:
                                slots = WeaponSlot.Lance;
                                break;
                            case WeaponType.LandingBay:
                                slots = WeaponSlot.Side;
                                break;
                            //case WeaponType.NovaCannon:
                            //    slots = WeaponSlot.Prow;
                            //    break;
                            //case WeaponType.TorpedoTube:
                            //    slots = WeaponSlot.Prow | WeaponSlot.Keel;
                            //    break;
                        }
                    }
                    int str = 0;
                    if (!String.IsNullOrWhiteSpace(file["customweapon" + i + "str"]))
                        str = int.Parse(file["customweapon" + i + "str"]);
                    DiceRoll damage = new DiceRoll(file["customweapon" + i + "dice"]);
                    if (!String.IsNullOrWhiteSpace(file["customweapon" + i + "damage"]))
                        damage += int.Parse(file["customweapon" + i + "damage"]);
                    int range = int.Parse(file["customweapon" + i + "range"]);
                    int crit = 0;
                    if (!String.IsNullOrWhiteSpace(file["customweapon" + i + "crit"]))
                        crit = int.Parse(file["customweapon" + i + "crit"]);
                    int space = 0;
                    if (!String.IsNullOrWhiteSpace(file["customweapon" + i + "space"]))
                        space = int.Parse(file["customweapon" + i + "space"]);
                    int sp = 0;
                    if (!String.IsNullOrWhiteSpace(file["customweapon" + i + "sp"]))
                        sp = int.Parse(file["customweapon" + i + "sp"]);
                    int power = 0;
                    if (!String.IsNullOrWhiteSpace(file["customweapon" + i + "power"]))
                        power = int.Parse(file["customweapon" + i + "power"]);
                    string special = file["customweapon" + i + "special"];
                    HullType weaponClass = HullType.All;
                    if (ship.Hull != null)
                        weaponClass = ship.Hull.HullTypes;
                    switch (type)
                    {
                        case WeaponType.TorpedoTube:
                            Weapons.Add(new TorpedoTubes(name, weaponClass, power, space, sp, str, 0, RuleBook.Custom, 0, special: special));
                            break;
                        case WeaponType.NovaCannon:
                            Weapons.Add(new NovaCannon(name, weaponClass, power, space, sp, damage, range, RuleBook.Custom, 0, special));
                            break;
                        case WeaponType.LandingBay:
                            Weapons.Add(new LandingBay(name, weaponClass, slots, power, space, sp, str, RuleBook.Custom, 0, special: special));
                            break;
                        default:
                            Weapons.Add(new Weapon(name, type, weaponClass, slots, power, space, sp, str, damage, crit, range, RuleBook.Custom, 0, special: special));
                            break;
                    }
                }
            }
            int length = ship.Weapons.Length;
            for (int i = 0; i < length; i++)
            {
                //add each weapon
                string name = file["weapon" + (length - i)];
                switch (name)
                {
                    case Old.BombardmentCannons:
                        name = Names.BombardmentCannons;
                        break;
                    case Old.JovianMissiles:
                        name = Names.JovianMissiles;
                        break;
                    case Old.LatheGravCulverin:
                        name = Names.LatheGravCulverin;
                        break;
                    case Old.MarsBroadsides:
                        name = Names.MarsBroadsides;
                        break;
                    case Old.MarsMacrocannons:
                        name = Names.MarsMacrocannons;
                        break;
                    case Old.MezoaLanceBattery:
                        name = Names.MezoaLanceBattery;
                        break;
                    case Old.MezoaLance:
                        name = Names.MezoaLance;
                        break;
                    case Old.RyzaPlasma:
                        name = Names.RyzaPlasma;
                        break;
                }
                Weapon weapon = Weapons.Where(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                if (weapon != null)
                {
                    Quality quality = Quality.Common;
                    if (!String.IsNullOrWhiteSpace(file["weapon" + (length - i) + "quality"]))
                        quality = (Quality)Enum.Parse(typeof(Quality), file["weapon" + (length - i) + "quality"]);
                    WeaponQuality wq = WeaponQuality.None;
                    //wxq1 & wxq2 for WeaponQuality, weapxmod for turbo
                    for (int j = 1; j <= 2; j++)
                    {
                        switch (file["w" + (length - i) + "q" + j])
                        {
                            case "Space":
                                wq |= WeaponQuality.Space;
                                break;
                            case "Range":
                                wq |= WeaponQuality.Range;
                                break;
                            case "Crit Rating":
                                wq |= WeaponQuality.Crit;
                                break;
                            case "Strength":
                                wq |= WeaponQuality.Strength;
                                break;
                            case "Damage":
                                wq |= WeaponQuality.Damage;
                                break;
                        }
                    }
                    Quality turbo = Quality.None;
                    if (!String.IsNullOrWhiteSpace(file["weap" + (length - i) + "mod"]))
                        turbo = (Quality)Enum.Parse(typeof(Quality), file["weap" + (length - i) + "mod"]);
                    if (quality != Quality.Common || turbo != Quality.None)
                        ship.Weapons[i] = new Weapon(weapon.Name, weapon.Type, weapon.HullTypes, weapon.Slots, weapon.RawPower, weapon.RawSpace, weapon.RawSP, weapon.RawStrength, weapon.RawDamage, weapon.RawCrit, weapon.RawRange,
                            weapon.Origin, weapon.PageNumber, quality, wq, weapon.RawSpecial, turbo, weapon.ComponentOrigin);
                    else
                        ship.Weapons[i] = weapon;
                }
            }
            if (!(String.IsNullOrWhiteSpace(file["customplasmaname"]) || String.IsNullOrWhiteSpace(file["customplasmapower"]) || String.IsNullOrWhiteSpace(file["customplasmaspace"])))
            {
                string name = file["customplasmaname"];
                int power = int.Parse(file["customplasmapower"]);
                int space = int.Parse(file["customplasmaspace"]);
                int sp = 0;
                if (!String.IsNullOrWhiteSpace(file["customplasmasp"]))
                {
                    sp = int.Parse(file["customplasmasp"]);
                }
                string special = file["customplasmaspecial"];
                PlasmaDrives.Add(new PlasmaDrive(name, shipClass, power, space, special, RuleBook.Custom, 0, sp));
            }
            if (!(String.IsNullOrWhiteSpace(file["customwarpname"]) || String.IsNullOrWhiteSpace(file["customwarppower"]) || String.IsNullOrWhiteSpace(file["customwarpspace"])))
            {
                string name = file["customwarpname"];
                int power = int.Parse(file["customwarppower"]);
                int space = int.Parse(file["customwarpspace"]);
                int sp = 0;
                if (!String.IsNullOrWhiteSpace(file["customwarpsp"]))
                {
                    sp = int.Parse(file["customwarpsp"]);
                }
                string special = file["customwarpspecial"];
                WarpDrives.Add(new WarpDrive(name, shipClass, power, space, RuleBook.Custom, 0, sp, special));
            }
            if (!(String.IsNullOrWhiteSpace(file["customgellarname"]) || String.IsNullOrWhiteSpace(file["customgellarpower"])))
            {
                string name = file["customgellarname"];
                int power = int.Parse(file["customgellarpower"]);
                int sp = 0;
                if (!String.IsNullOrWhiteSpace(file["customgellarsp"]))
                {
                    sp = int.Parse(file["customgellarsp"]);
                }
                string special = file["customgellarspecial"];
                GellarFields.Add(new GellarField(name, shipClass, power, special, RuleBook.Custom, 0, sp));
            }
            bool shieldsDone = false;//if a custom shield was used, don't count the custom shields twice
            if (!(String.IsNullOrWhiteSpace(file["customvoidname"]) || String.IsNullOrWhiteSpace(file["customvoidpower"])
                || String.IsNullOrWhiteSpace(file["customvoidspace"])))
            {
                string name = file["customvoidname"];
                int power = int.Parse(file["customvoidpower"]);
                int space = int.Parse(file["customvoidspace"]);
                int sp = 0;
                int str = 0;
                if(!String.IsNullOrWhiteSpace(file["customshield"]))
                    int.Parse(file["customshield"]);
                if (!String.IsNullOrWhiteSpace(file["customvoidsp"]))
                {
                    sp = int.Parse(file["customvoidsp"]);
                }
                string special = file["customvoidspecial"];
                VoidShields.Add(new VoidShield(name, shipClass, power, space, str, RuleBook.Custom, 0, special, sp: sp));
                shieldsDone = true;
            }
            if (!(String.IsNullOrWhiteSpace(file["custombridgename"]) || String.IsNullOrWhiteSpace(file["custombridgepower"]) || String.IsNullOrWhiteSpace(file["custombridgespace"])))
            {
                string name = file["custombridgename"];
                int power = int.Parse(file["custombridgepower"]);
                int space = int.Parse(file["custombridgespace"]);
                int sp = 0;
                if (!String.IsNullOrWhiteSpace(file["custombridgesp"]))
                {
                    sp = int.Parse(file["custombridgesp"]);
                }
                string special = file["custombridgespecial"];
                Bridges.Add(new Bridge(name, shipClass, power, space, RuleBook.Custom, 0, special, sp));
            }
            if (!(String.IsNullOrWhiteSpace(file["customlifename"]) || String.IsNullOrWhiteSpace(file["customlifepower"]) || String.IsNullOrWhiteSpace(file["customlifespace"])))
            {
                string name = file["customlifename"];
                int power = int.Parse(file["customlifepower"]);
                int space = int.Parse(file["customlifespace"]);
                int sp = 0;
                if (!String.IsNullOrWhiteSpace(file["customlifesp"]))
                {
                    sp = int.Parse(file["customlifesp"]);
                }
                string special = file["customlifespecial"];
                LifeSustainers.Add(new LifeSustainer(name, shipClass, power, space, 0, RuleBook.Custom, 0, special, sp: sp));
            }
            if (!(String.IsNullOrWhiteSpace(file["customcrewname"]) || String.IsNullOrWhiteSpace(file["customcrewpower"]) || String.IsNullOrWhiteSpace(file["customcrewspace"])))
            {
                string name = file["customcrewname"];
                int power = int.Parse(file["customcrewpower"]);
                int space = int.Parse(file["customcrewspace"]);
                int sp = 0;
                if (!String.IsNullOrWhiteSpace(file["customcrewsp"]))
                {
                    sp = int.Parse(file["customcrewsp"]);
                }
                string special = file["customcrewspecial"];
                CrewQuarters.Add(new CrewQuarters(name, shipClass, power, space, 0, RuleBook.Custom, 0, special, sp: sp));
            }
            if (!(String.IsNullOrWhiteSpace(file["customaugurname"]) || String.IsNullOrWhiteSpace(file["customaugurpower"])))
            {
                string name = file["customaugurname"];
                int power = int.Parse(file["customaugurpower"]);
                int sp = 0;
                if (!String.IsNullOrWhiteSpace(file["customaugursp"]))
                {
                    sp = int.Parse(file["customaugursp"]);
                }
                string special = file["customaugurspecial"];
                AugurArrays.Add(new Augur(name, power, RuleBook.Custom, 0, special: special, sp: sp));
            }
            if (!String.IsNullOrWhiteSpace(file["custommachine"]))
                ship.GMMachineSpirit = file["custommachine"];
            if (!String.IsNullOrWhiteSpace(file["customhistory"]))
                ship.GMShipHistory = file["customhistory"];
            if (!String.IsNullOrWhiteSpace(file["customspeed"]))
                ship.GMSpeed = int.Parse(file["customspeed"]);
            if (!String.IsNullOrWhiteSpace(file["customint"]))
                ship.GMHullIntegrity = int.Parse(file["customint"]);
            if (!String.IsNullOrWhiteSpace(file["customdet"]))
                ship.GMDetection = int.Parse(file["customdet"]);
            if (!String.IsNullOrWhiteSpace(file["customman"]))
                ship.GMManoeuvrability = int.Parse(file["customman"]);
            if (!String.IsNullOrWhiteSpace(file["customarmour"]))
                ship.GMArmour = int.Parse(file["customarmour"]);
            if (!String.IsNullOrWhiteSpace(file["customturret"]))
                ship.GMTurretRating = int.Parse(file["customturret"]);
            if (!String.IsNullOrWhiteSpace(file["custommorale"]))
                ship.GMMorale = int.Parse(file["custommorale"]);
            if (!String.IsNullOrWhiteSpace(file["customcrew"]))
                ship.GMCrewPopulation = int.Parse(file["customcrew"]);
            if (!(shieldsDone || String.IsNullOrWhiteSpace(file["customshield"])))
                ship.GMShields = int.Parse(file["customshield"]);
            ship.GMSpecial = file["customspecial"];
            //custom components as one blob
            if (!(String.IsNullOrWhiteSpace(file["customcomppower"]) && String.IsNullOrWhiteSpace(file["customcompgenerate"])))
            {
                bool doBoth = !(String.IsNullOrWhiteSpace(file["customcomppower"]) || String.IsNullOrWhiteSpace(file["customcompgenerate"]));//if both present, separate comps for generate
                if (doBoth)
                    ship.SupplementalComponents.Add(new Supplemental("Custom Generators", ship.Hull.HullTypes, int.Parse(file["customcompgenerate"]), 0, 0, RuleBook.Custom, 0, generated: true));
                bool usingPower = doBoth || !String.IsNullOrWhiteSpace(file["customcompgenerate"]);
                int space = 0;
                if (!String.IsNullOrWhiteSpace(file["customcompspace"]))
                    space = int.Parse(file["customcompspace"]);
                int sp = 0;
                if (!String.IsNullOrWhiteSpace(file["customcompsp"]))
                    sp = int.Parse(file["customcompsp"]);
                ship.SupplementalComponents.Add(new Supplemental("Custom Components", ship.Hull.HullTypes, (usingPower ? int.Parse(file["customcomppower"]) : int.Parse(file["customcompgenerate"])), space, sp, RuleBook.Custom, 0, special: file["customcomponents"], generated: !usingPower));//account for power being used or generated, all added as one blob to be shown in special field
            }
            //essential components
            {//Plasmadrive
                string name = file["plasma"];
                PlasmaDrive plasma = null;
                HullType size = HullType.None;
                bool modified = false;
                name = name.Replace(" Pattern", "-Pattern");
                if (name.Equals(Old.SprintTrader))
                    name = Names.SprintTrader;
                if (name.Equals(Old.EscortDrive))
                    name = Names.EscortDrive;
                if (name.StartsWith("Modified "))
                {
                    modified = true;
                    name = name.Substring(9);
                }
                if (name.Equals(Old.Viperdrive))
                    name = Names.Viperdrive;
                if (name.StartsWith(Names.WarcruiserDrive))
                {
                    if (name.EndsWith("Large"))
                        size = HullType.CruiserPlus;
                    else
                        size = HullType.LightCruiser;
                    plasma = PlasmaDrives.Where(x => x.Name.Equals(Names.WarcruiserDrive) && x.HullTypes == size).FirstOrDefault();
                }
                else if (name.StartsWith(Names.MimicDrive))
                {
                    switch (name.Substring(Names.MimicDrive.Length))
                    {
                        case "Huge":
                            size = HullType.CruiserPlus;
                            break;
                        case "Large":
                            size = HullType.LightCruiser;
                            break;
                        case "Medium":
                            size = HullType.Raider | HullType.Frigate;
                            break;
                        case "Small":
                            size = HullType.Transport;
                            break;
                    }
                    plasma = PlasmaDrives.Where(x => x.Name.Equals(Names.MimicDrive) && x.HullTypes == size).FirstOrDefault();
                }
                else
                {
                    plasma = PlasmaDrives.Where(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                }
                if (plasma != null)
                {
                    Quality quality = Quality.Common;
                    if (!String.IsNullOrEmpty(file["plasmaquality"]))
                    {
                        quality = (Quality)Enum.Parse(typeof(Quality), file["plasmaquality"]);
                        if (quality == Quality.Good)
                        {
                            switch (file["plasmachoice"])
                            {
                                case "Power":
                                    quality = Quality.Efficient;
                                    break;
                                case "Space":
                                    quality = Quality.Slim;
                                    break;
                            }
                        }
                    }
                    ship.PlasmaDrive = new PlasmaDrive(plasma.RawName, plasma.HullTypes, plasma.RawPower, plasma.RawSpace, plasma.RawSpecial, plasma.Origin, plasma.PageNumber, plasma.RawSP, quality, plasma.Speed, plasma.Manoeuvrability, plasma.ComponentOrigin, modified);
                }//Warp Drive
                WarpDrive warp = WarpDrives.Where(x => x.Name.Equals(file["warp"], StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                if (warp != null)
                {
                    Quality quality = Quality.Common;
                    if (!String.IsNullOrEmpty(file["warpquality"]))
                    {
                        quality = (Quality)Enum.Parse(typeof(Quality), file["warpquality"]);
                        if (quality == Quality.Good)
                        {
                            switch (file["warpchoice"])
                            {
                                case "Power":
                                    quality = Quality.Efficient;
                                    break;
                                case "Space":
                                    quality = Quality.Slim;
                                    break;
                            }
                        }
                    }
                    ship.WarpDrive = new WarpDrive(warp.Name, warp.HullTypes, warp.RawPower, warp.RawSpace, warp.Origin, warp.PageNumber, warp.RawSP, warp.RawSpecial, quality, warp.ComponentOrigin);
                }//Gellar Field
                GellarField gellar = GellarFields.Where(x => x.Name.Equals(file["gellar"], StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                if (gellar != null)
                {
                    Quality quality = Quality.Common;
                    if (!String.IsNullOrEmpty(file["gellarquality"]))
                    {
                        quality = (Quality)Enum.Parse(typeof(Quality), file["gellarquality"]);
                    }
                    ship.GellarField = new GellarField(gellar.Name, gellar.HullTypes, gellar.RawPower, gellar.RawSpecial, gellar.Origin, gellar.PageNumber, gellar.RawSP, gellar.NavigateWarp, quality, gellar.ComponentOrigin);
                }//Void shield
                name = file["void"];
                if (name.Equals(Old.RepulsorShield))
                    name = Names.RepulsorShield;
                VoidShield shield = VoidShields.Where(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                if (shield != null)
                {
                    Quality quality = Quality.Common;
                    if (!String.IsNullOrEmpty(file["voidquality"]))
                    {
                        quality = (Quality)Enum.Parse(typeof(Quality), file["voidquality"]);
                        if (quality == Quality.Good)
                        {
                            switch (file["voidchoice"])
                            {
                                case "Power":
                                    quality = Quality.Efficient;
                                    break;
                                case "Space":
                                    quality = Quality.Slim;
                                    break;
                            }
                        }
                    }
                    ship.VoidShield = new VoidShield(shield.Name, shield.HullTypes, shield.RawPower, shield.RawSpace, shield.Strength, shield.Origin, shield.PageNumber, shield.RawSpecial, quality, shield.RawSP, shield.ComponentOrigin);
                }//Ship's Bridge
                name = file["bridge"];
                size = HullType.All;
                if (name.EndsWith(", Large"))
                {
                    size = HullType.AllCruiser;
                }
                else if (name.EndsWith(", Small"))
                {
                    size = ~HullType.AllCruiser;
                }
                Bridge bridge = Bridges.Where(x => name.StartsWith(x.Name, StringComparison.OrdinalIgnoreCase) && (x.HullTypes & size) != 0).FirstOrDefault();
                if (bridge != null)
                {
                    Quality quality = Quality.Common;
                    if (!String.IsNullOrEmpty(file["bridgequality"]))
                    {
                        quality = (Quality)Enum.Parse(typeof(Quality), file["bridgequality"]);
                        if (quality == Quality.Good)
                        {
                            switch (file["bridgechoice"])
                            {
                                case "Power":
                                    quality = Quality.Efficient;
                                    break;
                                case "Space":
                                    quality = Quality.Slim;
                                    break;
                            }
                        }
                    }
                    ship.ShipBridge = new Bridge(bridge.Name, bridge.HullTypes, bridge.RawPower, bridge.RawSpace, bridge.Origin, bridge.PageNumber, bridge.RawSpecial, bridge.RawSP, quality, bridge.Manoeuvrability, bridge.BSModifier, bridge.Command, bridge.Repair, bridge.Pilot, bridge.NavigateWarp, bridge.ComponentOrigin, bridge.MiningObjective, bridge.CreedObjective, bridge.MilitaryObjective, bridge.TradeObjective, bridge.CriminalObjective, bridge.ExplorationObjective);
                }//Life Sustainer
                name = file["life"];
                size = HullType.All;
                name = name.Replace("Vitae ", "Vitae-");
                if (name.EndsWith(", Large"))
                {
                    size = HullType.AllCruiser;
                }
                else if (name.EndsWith(", Small"))
                {
                    size = ~HullType.AllCruiser;
                }
                LifeSustainer sustainer = LifeSustainers.Where(x => name.StartsWith(x.Name, StringComparison.OrdinalIgnoreCase) && (x.HullTypes & size) != 0).FirstOrDefault();
                if (sustainer != null)
                {
                    Quality quality = Quality.Common;
                    if (!String.IsNullOrEmpty(file["lifequality"]))
                    {
                        quality = (Quality)Enum.Parse(typeof(Quality), file["lifequality"]);
                        if (quality == Quality.Good)
                        {
                            switch (file["lifechoice"])
                            {
                                case "Power":
                                    quality = Quality.Efficient;
                                    break;
                                case "Space":
                                    quality = Quality.Slim;
                                    break;
                            }
                        }
                    }
                    ship.LifeSustainer = new LifeSustainer(sustainer.Name, sustainer.HullTypes, sustainer.RawPower, sustainer.RawSpace, sustainer.Morale, sustainer.Origin, sustainer.PageNumber, sustainer.RawSpecial, quality, sustainer.RawSP, sustainer.MoraleLoss, sustainer.CrewLoss, sustainer.ComponentOrigin);
                }//crew quarters
                name = file["quarters"];
                size = HullType.All;
                if (name.EndsWith(", Large"))
                {
                    size = HullType.AllCruiser;
                }
                else if (name.EndsWith(", Small"))
                {
                    size = ~HullType.AllCruiser;
                }
                CrewQuarters quarters = CrewQuarters.Where(x => name.StartsWith(x.Name, StringComparison.OrdinalIgnoreCase) && (x.HullTypes & size) != 0).FirstOrDefault();
                if (quarters != null)
                {
                    Quality quality = Quality.Common;
                    if (!String.IsNullOrEmpty(file["quartersquality"]))
                    {
                        quality = (Quality)Enum.Parse(typeof(Quality), file["quartersquality"]);
                        if (quality == Quality.Good)
                        {
                            switch (file["quarterschoice"])
                            {
                                case "Power":
                                    quality = Quality.Efficient;
                                    break;
                                case "Space":
                                    quality = Quality.Slim;
                                    break;
                            }
                        }
                    }
                    ship.CrewQuarters = new CrewQuarters(quarters.Name, quarters.HullTypes, quarters.RawPower, quarters.RawSpace, quarters.Morale, quarters.Origin, quarters.PageNumber, quarters.RawSpecial, quality, quarters.RawSP, quarters.MoraleLoss, quarters.ComponentOrigin);
                }//Augur Arrays
                Augur arrays = AugurArrays.Where(x => x.Name.Equals(file["augur"], StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                if (arrays != null)
                {
                    Quality quality = Quality.Common;
                    if (!String.IsNullOrEmpty(file["augurquality"]))
                    {
                        quality = (Quality)Enum.Parse(typeof(Quality), file["augurquality"]);
                    }
                    ship.AugurArrays = new Augur(arrays.Name, arrays.RawPower, arrays.Origin, arrays.PageNumber, arrays.DetectionRating, arrays.RawSpecial, quality, arrays.RawSP, arrays.Manoeuvrability, arrays.BSModifier, arrays.MiningObjective, arrays.CreedObjective, arrays.MilitaryObjective, arrays.TradeObjective, arrays.CriminalObjective, arrays.ExplorationObjective, arrays.ComponentOrigin);
                }
            }//end of essential components
            switch (file["machine"])
            {
                case "A Nose For Trouble":
                    ship.MachineSpirit = MachineSpirit.ANoseForTrouble;
                    break;
                case "Blasphemous Tendencies":
                    ship.MachineSpirit = MachineSpirit.BlasphemousTendencies;
                    break;
                case "Martial Hubris":
                    ship.MachineSpirit = MachineSpirit.MartialHubris;
                    break;
                case "Rebellious":
                    ship.MachineSpirit = MachineSpirit.Rebellious;
                    break;
                case "Stoic":
                    ship.MachineSpirit = MachineSpirit.Stoic;
                    break;
                case "Skittish":
                    ship.MachineSpirit = MachineSpirit.Skittish;
                    break;
                case "Wrothful":
                    ship.MachineSpirit = MachineSpirit.Wrothful;
                    break;
                case "Resolute":
                    ship.MachineSpirit = MachineSpirit.Resolute;
                    break;
                case "Adventurous":
                    ship.MachineSpirit = MachineSpirit.Adventurous;
                    break;
                case "Ancient and Wise":
                    ship.MachineSpirit = MachineSpirit.AncientAndWise;
                    break;
            }
            switch (file["history"])
            {
                case "Reliquary of Mars":
                    ship.ShipHistory = ShipHistory.ReliquaryOfMars;
                    break;
                case "Haunted":
                    ship.ShipHistory = ShipHistory.Haunted;
                    break;
                case "Emissary of the Imperator":
                    ship.ShipHistory = ShipHistory.EmissaryOfTheImperator;
                    break;
                case "Wolf in Sheeps Clothing":
                    ship.ShipHistory = ShipHistory.WolfInSheepsClothing;
                    break;
                case "Turbulent Past":
                    ship.ShipHistory = ShipHistory.TurbulentPast;
                    break;
                case "Death Cult":
                    ship.ShipHistory = ShipHistory.DeathCult;
                    break;
                case "Wrested from a Space Hulk":
                    ship.ShipHistory = ShipHistory.WrestedFromASpaceHulk;
                    break;
                case "Temperamental Warp Engine":
                    ship.ShipHistory = ShipHistory.TemperamentalWarpEngine;
                    break;
                case "Finances in Arrears":
                    ship.ShipHistory = ShipHistory.FinancesInArrears;
                    break;
                case "Xenophilous":
                    ship.ShipHistory = ShipHistory.Xenophilous;
                    break;
            }
            if (!String.IsNullOrWhiteSpace(file["crew"]))
                ship.CrewRace = (Race)Enum.Parse(typeof(Race), file["crew"]);
            if (!String.IsNullOrWhiteSpace(file["crewrating"]))
            {
                CrewRating rating = 0;
                if (Enum.TryParse<CrewRating>(file["crewrating"], out rating))
                    ship.CrewRating = (int)rating;
                else
                    ship.CrewRating = (int)Enum.Parse(typeof(ServitorQuality), file["crewrating"]);
            }
            if (!String.IsNullOrWhiteSpace(file["crewmod"]))
                ship.GMCrewRating = int.Parse(file["crewmod"]);
            if (!String.IsNullOrWhiteSpace(file["arrestor"]))
                ship.ArresterEngines = (Quality)Enum.Parse(typeof(Quality), file["arrestor"]);
            if (!String.IsNullOrWhiteSpace(file["cherubim"]))
                ship.CherubimAerie = (Quality)Enum.Parse(typeof(Quality), file["cherubim"]);
            if (!String.IsNullOrWhiteSpace(file["improvements"]))
                ship.CrewImprovements = (Quality)Enum.Parse(typeof(Quality), file["imperovements"]);
            if (!String.IsNullOrWhiteSpace(file["disciplinarium"]))
                ship.Disciplinarium = (Quality)Enum.Parse(typeof(Quality), file["disciplinarium"]);
            if (!String.IsNullOrWhiteSpace(file["distribute"]))
                ship.DistributedCargoHold = (Quality)Enum.Parse(typeof(Quality), file["distributed"]);
            if (!String.IsNullOrWhiteSpace(file["mimic"]))
                ship.MimicDrive = (Quality)Enum.Parse(typeof(Quality), file["mimic"]);
            if (!String.IsNullOrWhiteSpace(file["ostentatious"]))
                ship.OstentatiousDisplayOfWealth = (Quality)Enum.Parse(typeof(Quality), file["ostentatious"]);
            if (!String.IsNullOrWhiteSpace(file["overload"]))
                ship.OverloadShieldCapacitors = (Quality)Enum.Parse(typeof(Quality), file["overload"]);
            if (!String.IsNullOrWhiteSpace(file["resolution"]))
                ship.ResolutionArena = (Quality)Enum.Parse(typeof(Quality), file["resolution"]);
            if (!String.IsNullOrWhiteSpace(file["secondary"]))
                ship.SecondaryReactor = (Quality)Enum.Parse(typeof(Quality), file["secondary"]);
            if (!String.IsNullOrWhiteSpace(file["starchart"]))
                ship.StarchartCollection = (Quality)Enum.Parse(typeof(Quality), file["starchart"]);
            if (!String.IsNullOrWhiteSpace(file["trooper"]))
                ship.StormTrooperDetachment = (Quality)Enum.Parse(typeof(Quality), file["trooper"]);
            if (!String.IsNullOrWhiteSpace(file["superior"]))
                ship.SuperiorDamageControl = (Quality)Enum.Parse(typeof(Quality), file["superior"]);
            if (!String.IsNullOrWhiteSpace(file["targeting"]))
                ship.TargettingMatrix = (Quality)Enum.Parse(typeof(Quality), file["targeting"]);
            if (!String.IsNullOrWhiteSpace(file["vaulted"]))
                ship.VaultedCeilings = (Quality)Enum.Parse(typeof(Quality), file["vaulted"]);
            switch (file["background"])
            {
                case "Thulian Explorator Vessel":
                    ship.Background = Background.ThulianExploratorVessel;
                    break;
                case "Reaver of the Unbeholden Reaches":
                    ship.Background = Background.ReaverOfTheUnbeholdenReaches;
                    break;
                case "Veteran of the Angevin Crusade":
                    ship.Background = Background.VeteranOfTheAngevinCrusade;
                    break;
                case "Implacable Foe of The Fleet":
                    ship.Background = Background.ImplacableFoeOfTheFleet;
                    break;
                case "Steadfast Ally of the Fleet":
                    ship.Background = Background.SteadfastAllyofTheFleet;
                    break;
                case "Planet-Bound for Millenia":
                    if (!String.IsNullOrWhiteSpace(file["hullloss"]))
                    {
                        byte loss = byte.Parse(file["hullloss"]);
                        ship.Background = (Background)loss;//and it to get number of hull lost
                    }
                    else
                        ship.Background = Background.PlanetBoundForMillenia;
                    break;
            }
            //supplemental components
            if (shipClass == HullType.None)
                shipClass = HullType.All;//if not set by a hull, now set assumed class to max
            foreach (KeyValuePair<String, String> pair in file.Skip(243))//supplemental components start after the first 243 entries
            {
                if (!String.IsNullOrWhiteSpace(pair.Value))
                {
                    String name = pair.Key.Replace("†","");
                    Quality quality = Quality.Common;
                    if (name.StartsWith("Poor Quality "))
                    {
                        name = name.Substring(13);
                        quality = Quality.Poor;
                    }
                    else if (name.StartsWith("Slim "))
                    {
                        name = name.Substring(5);
                        quality = Quality.Slim;
                    }
                    else if (name.StartsWith("Efficient "))
                    {
                        name = name.Substring(10);
                        quality = Quality.Efficient;
                    }
                    else if (name.StartsWith("Good Quality "))
                    {
                        name = name.Substring(13);
                        quality = Quality.Good;
                    }
                    else if (name.StartsWith("Best Quality"))
                    {
                        name = name.Substring(13);
                        quality = Quality.Best;
                    }
                    switch (name)
                    {
                        case Old.CogitatorInterlink:
                            name = Names.CogitatorInterlink;
                            break;
                        case Old.JammingSystem:
                            name = Names.JammingSystem;
                            break;
                    }
                    //check for all with same name, then get the largest one(ships capable of say cruiser and transport use cruiser size if that is what is available)
                    Supplemental component = Supplementals.Where(x => name.StartsWith(x.Name, StringComparison.OrdinalIgnoreCase)).OrderByDescending(x => x.HullTypes).FirstOrDefault();
                    int count = int.Parse(pair.Value);
                    if (component != null)
                    {
                        for (int i = 0; i < count; i++)
                            ship.SupplementalComponents.Add(new Supplemental(component.Name, component.HullTypes, component.RawPower, component.RawSpace, component.RawSP, component.Origin, component.PageNumber, component.RamDamage, component.RawSpecial, quality, component.Speed, component.Manoeuvrability, component.HullIntegrity, component.Armour, component.TurretRating, component.Morale, component.CrewPopulation, component.ProwArmour, component.CrewRating, component.MiningObjective, component.CreedObjective, component.MilitaryObjective, component.TradeObjective, component.CriminalObjective, component.ExplorationObjective, component.PowerGenerated, component.DetectionRating, component.AuxiliaryWeapon, component.MacrobatteryModifier, component.BSModifier, component.NavigateWarp, component.CrewLoss, component.MoraleLoss, component.ComponentOrigin, component.Replace, component.Max));
                    }
                }
            }
            return ship;
        }
        /// <summary>
        /// Update the binder >> not_reviewed tag for the documents
        /// </summary>
        /// <param name="reviewsetRecord"></param>
        private void UpdateTag(DocumentRecordCollection reviewsetRecord)
        {
            var indexManagerProxy = new IndexManagerProxy(reviewsetRecord.ReviewsetDetails.MatterId, reviewsetRecord.ReviewsetDetails.CollectionId);
            var documentList = reviewsetRecord.DocumentTags.
                GroupBy(item => item.DocumentId).ToDictionary(group => group.Key, group => group.ToList());
            var tagsList = new Dictionary<string, KeyValuePair<string, string>>();

            // create key value pair for every document to be updated in Search Sub System
            foreach (var document in documentList)
            {
                var strTags = string.Join(",", document.Value.Where(x => x.Status == 1).
                    Select(t => String.Format(EVSearchSyntax.TagValueFormat + "{0}", t.TagId)).ToArray());
                tagsList.Add(document.Key,
                             string.IsNullOrEmpty(strTags)
                                 ? new KeyValuePair<string, string>(EVSystemFields.Tag, string.Empty)
                                 : new KeyValuePair<string, string>(EVSystemFields.Tag, strTags));
            }

            const int batchSize = 1000;
            var processedCount = 0;
            while (processedCount != tagsList.Count)
            {
                Dictionary<string, KeyValuePair<string, string>> batchTags;
                if ((tagsList.Count - processedCount) < batchSize)
                {
                    batchTags = tagsList.Skip(processedCount).Take(tagsList.Count - processedCount).ToDictionary(x => x.Key, x => x.Value);
                    processedCount += tagsList.Count - processedCount;
                }
                else
                {
                    batchTags = tagsList.Skip(processedCount).Take(batchSize).ToDictionary(x => x.Key, x => x.Value);
                    processedCount += batchSize;
                }

                if (!batchTags.Any()) continue;

                var docs = batchTags.Select(doc => new DocumentBeo()
                {
                    Id = doc.Key,
                    Fields = new Dictionary<string, string> { { doc.Value.Key, doc.Value.Value } }
                }).ToList();

                indexManagerProxy.BulkUpdateDocumentsAsync(docs);
            }
        }
Example #11
0
        public ulong S_1(Dictionary<ulong, int> guesses)
        {
            ulong start = 1;
            ulong stop = 10;
            while(stop<guesses.First().Key)
            {
                start *= 10;
                stop *= 10;
            }

            var poss = new List<ulong>();

            foreach (var g in guesses.Take(1))
            {
                ulong guess = g.Key;
                int correct = g.Value;

                for (ulong i = start; i < guess; i++)
                {
                    ulong diff = guess - i;
                    int count = 0;

                    while (diff > 0)
                    {
                        if (diff%10 == 0)
                        {
                            count++;
                            if (count > correct)
                            {
                                //continue to for loop
                                diff = 0;
                            }
                        }

                        diff /= 10;
                    }

                    if (count == correct)
                        poss.Add(i);

                }
                for (ulong i = guess + 1; i < stop; i++)
                {
                    ulong diff = i - guess;
                    int count = 0;

                    while (diff > 0)
                    {
                        if (diff%10 == 0)
                        {
                            count++;
                            if (count > correct)
                            {
                                //continue to for loop
                                diff = 0;
                            }
                        }

                        diff /= 10;
                    }

                    if (count == correct)
                        poss.Add(i);
                }
            }

            foreach (var g in guesses.Skip(1))
            {
                ulong guess = g.Key;
                int correct = g.Value;

                foreach (var p in poss)
                {
                    ulong diff = p > guess ? p - guess : guess - p;
                    int count = 0;

                    while (diff > 0)
                    {
                        if (diff%10 == 0)
                        {
                            count++;
                            if (count > correct)
                            {
                                //continue to for loop
                                diff = 0;
                            }
                        }

                        diff /= 10;
                    }

                    if (count != correct)
                        poss.Remove(p);
                }
            }

            Debug.Assert(poss.Count==1);

            return poss.Single();
        }
        public ResultCreazioneFile GetModello770(int idCondominio, int idAzienda, int anno, int? idFornitoreModello770, DateTime dataDichiarazione, int? numeroIscrizioneCaf, bool intermediarioDichiarazioneCondominio, bool enteDichiarante, PersonaDTO firmatarioDichiarazione, PersonaDTO intermediarioDichiarazione)
        {
            byte[] bytes = null;
            var message = string.Empty;
            const int progressivoInvioTelematico = 0;
            const int numeroInviiTelematici = 0;

            var numeroRecordB = 0;
            int numeroRecordD = 0;
            const int numeroRecordI = 0;

            StreamWriter sw = null;
            try
            {
                var fileName = Path.GetTempPath() + "\\" + Guid.NewGuid();
                if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
                    fileName = System.Deployment.Application.ApplicationDeployment.CurrentDeployment.DataDirectory + "\\" + Guid.NewGuid();
                if (File.Exists(fileName))
                    File.Delete(fileName);

                var condominio = _daoFactory.GetCondominioDao().GetById(idCondominio, false);

                // =============================================================================================
                // Ritenute da inserire nel modello 770
                // =============================================================================================
                var ritenute = _ritenutaService.GetByCondominioAnno(idCondominio, idAzienda, anno);

                // -----------------------------------------------------------------
                // Raggruppamento per periodo riferimento, tributo, data versamento
                // -----------------------------------------------------------------
                var ritenutePerMese = from item in ritenute
                                      group item by item.GetPeriodoRiferimento(false) + "¥" + item.PagamentoRiferimento.ScadenzaRiferimento.SpesaRiferimento.FornitoreRiferimento.CodiceTributo + "¥" + item.GetDataVersamento().GetValueOrDefault().ToShortDateString() into itemPerMese
                                      select itemPerMese;

                // =============================================================================================
                // Creazione del file
                // =============================================================================================
                // calcolo eventuali importi versati in eccesso
                var importiVersatiInEccesso = ritenute.Where(item => item.Tipo == TipoVersamentoRitenutaEnum.Eccesso).Sum(item => item.Importo.GetValueOrDefault());

                using (sw = File.CreateText(fileName))
                {
                    var codiceFiscale = condominio.Azienda.CodiceFiscale;
                    if (intermediarioDichiarazione != null)
                        codiceFiscale = intermediarioDichiarazione.CodiceFiscale;
                    if (intermediarioDichiarazioneCondominio)
                        codiceFiscale = condominio.CodiceFiscale;

                    writeTestataA("77S", codiceFiscale, anno, progressivoInvioTelematico, numeroInviiTelematici, sw);
                    writeRowB(condominio, dataDichiarazione, importiVersatiInEccesso > 0, ritenute.Count > 0, idFornitoreModello770, numeroIscrizioneCaf, intermediarioDichiarazioneCondominio, enteDichiarante, firmatarioDichiarazione, intermediarioDichiarazione, sw);
                    numeroRecordB++;

                    // ---------------------------------------------------------------------
                    //  Scrittura quadro ST e SX
                    // ---------------------------------------------------------------------
                    var datiST = new Dictionary<string, DatiST>();
                    var index = 0;
                    var countRow = 0;
                    foreach (var itemGroup in ritenutePerMese)
                    {
                        countRow++;

                        // Nel calcolo dell'importo delle ritenute operate NON devono essere compresi gli importi versati in eccesso
                        // Nel calcolo dell'importo delle ritenute versate DEVONO essere compresi gli importi versati in eccesso
                        datiST.Add(itemGroup.Key, new DatiST(itemGroup.Sum(item => item.Importo.GetValueOrDefault()), itemGroup.Where(item => item.Tipo == TipoVersamentoRitenutaEnum.Normale).Sum(item => item.ImportoInteressi.GetValueOrDefault()), itemGroup.Where(item => item.Tipo == TipoVersamentoRitenutaEnum.Normale).Sum(item => item.ImportoSanzione.GetValueOrDefault()), itemGroup.Sum(item => item.ImportoConInteressi)));
                        if(countRow == 12)
                        {
                            index++;

                            // -------------------------------------------------------------------------------------------------------------------------
                            // Un solo record può contenere al massimo 10 elementi ST, i dati sono quindi suddivisi in gruppi di 10 - bugid#7872
                            // -------------------------------------------------------------------------------------------------------------------------
                            // Si precisa che qualora la tabella che costituisce la seconda parte del record di tipo “D” ed “I”
                            // non  fosse  sufficiente  ad  accogliere  tutti  i  dati  della 
                            // dichiarazione, sarà necessario predisporre un nuovo record dello stesso tipo. In generale, 
                            // la presenza di più di un record di tipo “D” ed “I”  all’interno di 
                            // una stessa dichiarazione può derivare da due possibili situazioni: 
                            //
                            //     i  dati  da  registrare  sono  in  numero  tale  da  non  poter  essere  interamente  contenuti 
                            //      nella tabella del record; in tal caso è necessario predisporre un nuovo record dello 
                            //      stesso  tipo  con  lo  stesso  valore  del  campo  “Progressivo  modulo”; 
                            //
                            //     i  dati  da  registrare  sono  relativi  a  più  prospetti  ST,  SV,  SX,  SY  caratterizzati  da 
                            //      differenti  valori  del  campo  posto  in  alto  a  destra    (“Mod.  N.”); in  questo  caso  è  necessario 
                            //      predisporre  più  record  caratterizzati  da  differenti  valori  del  “Progressivo  modulo”. 
                            // -------------------------------------------------------------------------------------------------------------------------

                            var countSameModule = Math.Ceiling(Convert.ToDecimal(countRow) / 10m);
                            for (var i = 0; i < countSameModule; i++)
                            {
                                writeRowD(condominio, index, i*10, datiST.Skip(i*10).Take(10), importiVersatiInEccesso, sw);
                                importiVersatiInEccesso = 0;
                                numeroRecordD++;
                            }

                            countRow = 0;
                            datiST.Clear();
                        }
                    }
                    if (datiST.Count > 0)
                    {
                        index++;
                        writeRowD(condominio, index, 0, datiST, importiVersatiInEccesso, sw);
                        importiVersatiInEccesso = 0;
                        numeroRecordD++;
                    }

                    writePiedeZ(numeroRecordB, numeroRecordD, numeroRecordI, sw);
                }

                var infile = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
                bytes = new byte[infile.Length];
                infile.Read(bytes, 0, bytes.Length);

                return new ResultCreazioneFile(bytes, message);
            }
            catch (Exception ex)
            {
                _log.ErrorFormat("Errore inaspettato durante la creazione del file per il modello 770 - {0} - condominio:{1} - anno:{2}", ex, Library.Utility.GetMethodDescription(), idCondominio, anno);
                message = "Si sono verificati problemi inaspettati durante la generazione del modello 770." + Environment.NewLine + "Controllare il log per ulteriori dettagli.";
                return new ResultCreazioneFile(bytes, message);
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                    sw.Dispose();
                }
            }
        }
Example #13
0
        public static void Put_RandomDelete_ByteArray(int cnt, int durationSec, bool speed, int payloadSizeMin, int payloadSizeMax, int deleteFreq, bool isParallel)
        {
            using (var pile = new DefaultPile())
              {
            pile.AllocMode = speed ? AllocationMode.FavorSpeed : AllocationMode.ReuseSpace;
            pile.Start();
            var startTime = DateTime.UtcNow;
            var tasks = new List<Task>();
            for (var t = 0; t < (isParallel ? (System.Environment.ProcessorCount - 1) : 1); t++)
              tasks.Add(Task.Factory.StartNew(() =>
            {
              var wlc = 0;
              while (true)
              {
                if ((DateTime.UtcNow - startTime).TotalSeconds >= durationSec) return;

                var dict = new Dictionary<int, CheckByteArray>();

                Console.WriteLine("Starting a batch of {0}".Args(cnt));
                for (int i = 0; i < cnt; i++)
                {
                  var payloadSize = NFX.ExternalRandomGenerator.Instance.NextScaledRandomInteger(payloadSizeMin, payloadSizeMax);
                  var val = new byte[payloadSize];
                  val[0] = (byte)NFX.ExternalRandomGenerator.Instance.NextRandomInteger;
                  val[payloadSize - 1] = (byte)NFX.ExternalRandomGenerator.Instance.NextRandomInteger;

                  var ptr = pile.Put(val);

                  var element = new CheckByteArray(ptr, payloadSize - 1, val[0], val[payloadSize - 1]);
                  dict.Add(i, element);

                  if (dict.Count > 0 && i % deleteFreq == 0)
                  {
                    while (true)
                    {
                      var idx = i - NFX.ExternalRandomGenerator.Instance.NextScaledRandomInteger(0, i);

                      CheckByteArray stored;
                      if (dict.TryGetValue(idx, out stored))
                      {
                        ptr = stored.Ptr;
                        pile.Delete(ptr);
                        dict.Remove(idx);
                        break;
                      }
                    }
                  }

                  if (dict.Count > 16 && NFX.ExternalRandomGenerator.Instance.NextScaledRandomInteger(0, 100) > 98)
                  {
                    var toRead = NFX.ExternalRandomGenerator.Instance.NextScaledRandomInteger(8, 64);
                    wlc++;
                    if (wlc % 125 == 0)
                      Console.WriteLine("Thread {0} is reading {1} elements, total {2}"
                        .Args(Thread.CurrentThread.ManagedThreadId, toRead, dict.Count));
                    for (var k = 0; k < toRead; k++)
                    {
                      var kvp = dict.Skip(NFX.ExternalRandomGenerator.Instance.NextScaledRandomInteger(0, dict.Count - 1)).First();
                      var buf = pile.Get(kvp.Value.Ptr) as byte[];
                      Assert.AreEqual(kvp.Value.FirstByte, buf[0]);
                      Assert.AreEqual(kvp.Value.LastByte, buf[kvp.Value.IdxLast]);
                    }
                  }
                }

                Console.WriteLine("Thread {0} is doing final read of {1} elements".Args(Thread.CurrentThread.ManagedThreadId, dict.Count));
                foreach (var kvp in dict)
                {
                  var buf = pile.Get(kvp.Value.Ptr) as byte[];
                  Assert.AreEqual(kvp.Value.FirstByte, buf[0]);
                  Assert.AreEqual(kvp.Value.LastByte, buf[kvp.Value.IdxLast]);
                }
              }
            }, TaskCreationOptions.LongRunning));
            Task.WaitAll(tasks.ToArray());
              }
        }
Example #14
0
        public static void appendEvent(string ClassName, string Method, Dictionary<string, string> Properties)
        {
            deleteLastXLinesInFile(FilePath, 3);

            sw = new StreamWriter(FilePath, true);
            sw.WriteLine("      <div class='panel-group'>");
            sw.WriteLine("        <div class='panel panel-default " + TestParametersClass.StepStatus + "'>");
            sw.WriteLine("          <div class='panel-heading " + TestParametersClass.StepStatus + "'>");
            sw.WriteLine("            <h3 class='panel-title'>");
            sw.WriteLine("              <a data-toggle='collapse' id='Toggle' href='#collapse" + Properties["Step ID"] + "'>Step ID: " + Properties["Step ID"] + "</a>");
            sw.WriteLine("              <p class='" + TestParametersClass.StepStatus + "' id='StepResult'>Step " + TestParametersClass.StepStatus + "</p>");
            sw.WriteLine("            </h3>");
            sw.WriteLine("          </div>");
            sw.WriteLine("          <div id='collapse" + Properties["Step ID"] + "' class='panel-collapse collapse in'>");
            sw.WriteLine("            <div class='panel-body'>");
            sw.WriteLine("              <div class='table'>");
            sw.WriteLine("                <div class='PropertiesTableCell'>");
            sw.WriteLine("                  <TABLE class='PropertiesTable'>");

            foreach (KeyValuePair<string, string> entry in Properties.Skip(2))
            {
                string Name = entry.Key;
                string Value = entry.Value;

                if (Value != "")
                {
                    sw.WriteLine("                    <TR>");
                    sw.WriteLine("                      <TD class='PropertyName" + Properties["Step Status"] + "'>" + Name + "</TD>");
                    sw.WriteLine("                      <TD class='PropertyValue" + Properties["Step Status"] + "'>" + Value + "</TD>");
                    sw.WriteLine("                    </TR>");
                }
            }

            sw.WriteLine("                  </TABLE>");
            sw.WriteLine("                </div>");
            sw.WriteLine("                <div class='ScreenshotCell'>");

            if (TestParametersClass.BrowserOpen)
            {
                sw.WriteLine("                  <a href='" + TestParametersClass.LocalScreenshotFilePathForResultFile + "'>");
                sw.WriteLine("                    <img class='ScreenshotMini' src='" + TestParametersClass.LocalScreenshotFilePathForResultFile + "'>");
                sw.WriteLine("                  </a>");
            }

            sw.WriteLine("                </div>");
            sw.WriteLine("              </div>");
            sw.WriteLine("            </div>");
            sw.WriteLine("          </div>");
            sw.WriteLine("        </div>");
            sw.WriteLine("      </div>");
            sw.WriteLine("    </div>");
            sw.WriteLine("  </BODY>");
            sw.WriteLine("</HTML>");
            sw.Dispose();
        }
Example #15
0
        private SyncResponse IndexProcess(Dictionary<object, Dictionary<string, object>> data, SyncResponse syncResponse)
        {
            var c = 0;
            while (c < data.Count())
            {
                var partialData = data.Skip(c).Take(_config.BulkSize).ToDictionary(x => x.Key, x => x.Value);

                var bulkResponse = BulkIndexProcess(partialData);

                syncResponse.BulkResponses.Add(bulkResponse);
                syncResponse.IndexedDocuments += bulkResponse.AffectedDocuments;
                syncResponse.Success = syncResponse.Success && bulkResponse.Success;

                log.Info(String.Format("bulk duration: {0}ms. so far {1} documents have been indexed successfully.", bulkResponse.Duration, syncResponse.IndexedDocuments));
                c += _config.BulkSize;
            }

            return syncResponse;
        }