public override bool Resolve(IWorkflowContext context) { if (string.IsNullOrEmpty(ParameterName)) { throw new ArgumentNullException("ParameterName"); } bool result = false; object obj1 = null; if (ParameterName.Equals("$User.RoleName$")) { obj1 = string.Join("|", context.FlowInstance.Creator.Roles.Select(o => o.RoleType.Name)); } else { if (!Env.TryResolve(ParameterName, out obj1)) { if (context.Parameter != null && context.Parameter.Count > 0 && context.Parameter.Keys.Contains(ParameterName, StringComparer.Create(Thread.CurrentThread.CurrentCulture, true))) { obj1 = context.Parameter[ParameterName]; } } } var op = AllColumnOperator.OperatorMapping[Operator]; object obj2 = ParameterValue; if (ParameterValue.IsNotNullOrEmpty() && Env.TryResolve(ParameterValue, out obj2)) { result = op.Operate(obj1, obj2); } else { result = op.Operate(obj1, ParameterValue); } Log("{6}:参数名【{0}】解析为:{1},参数值【{2}】解析为:{3},运算符:{4},结果:{5}".FormatTo(ParameterName, obj1, ParameterValue, obj2, op.GetType().GetDisplayName(), result, context.FlowInstance.Id)); return(result); }
private IDictionary <string, string> CreateCaseInsensitiveDictionary() { return(new NullIfNotFoundDictionary <string, string>(StringComparer.Create(this.culture, true))); }
/// <summary> /// Find a value from a System.Enum by trying several possible variants /// of the string value of the enum. /// </summary> /// <param name="type">Type of enum</param> /// <param name="value">Value for which to search</param> /// <param name="culture">The culture used to calculate the name variants</param> /// <returns></returns> public static object FindEnumValue(this Type type, string value, CultureInfo culture) { #if FRAMEWORK && !PocketPC var ret = Enum.GetValues(type) .Cast <Enum>() .FirstOrDefault(v => v.ToString().GetNameVariants(culture).Contains(value, StringComparer.Create(culture, true))); if (ret == null) { var enumValueAsUnderlyingType = Convert.ChangeType(value, Enum.GetUnderlyingType(type), culture); if (enumValueAsUnderlyingType != null && Enum.IsDefined(type, enumValueAsUnderlyingType)) { ret = (Enum)Enum.ToObject(type, enumValueAsUnderlyingType); } } return(ret); #else return(Enum.Parse(type, value, true)); #endif }
public static void Main() { // Create a list of string. List <string> list = new List <string>(); // Get the tr-TR (Turkish-Turkey) culture. CultureInfo turkish = new CultureInfo("tr-TR"); // Get the culture that is associated with the current thread. CultureInfo thisCulture = Thread.CurrentThread.CurrentCulture; // Get the standard StringComparers. StringComparer invCmp = StringComparer.InvariantCulture; StringComparer invICCmp = StringComparer.InvariantCultureIgnoreCase; StringComparer currCmp = StringComparer.CurrentCulture; StringComparer currICCmp = StringComparer.CurrentCultureIgnoreCase; StringComparer ordCmp = StringComparer.Ordinal; StringComparer ordICCmp = StringComparer.OrdinalIgnoreCase; // Create a StringComparer that uses the Turkish culture and ignores case. StringComparer turkICComp = StringComparer.Create(turkish, true); // Define three strings consisting of different versions of the letter I. // LATIN CAPITAL LETTER I (U+0049) string capitalLetterI = "I"; // LATIN SMALL LETTER I (U+0069) string smallLetterI = "i"; // LATIN SMALL LETTER DOTLESS I (U+0131) string smallLetterDotlessI = "\u0131"; // Add the three strings to the list. list.Add(capitalLetterI); list.Add(smallLetterI); list.Add(smallLetterDotlessI); // Display the original list order. Display(list, "The original order of the list entries..."); // Sort the list using the invariant culture. list.Sort(invCmp); Display(list, "Invariant culture..."); list.Sort(invICCmp); Display(list, "Invariant culture, ignore case..."); // Sort the list using the current culture. Console.WriteLine("The current culture is \"{0}\".", thisCulture.Name); list.Sort(currCmp); Display(list, "Current culture..."); list.Sort(currICCmp); Display(list, "Current culture, ignore case..."); // Sort the list using the ordinal value of the character code points. list.Sort(ordCmp); Display(list, "Ordinal..."); list.Sort(ordICCmp); Display(list, "Ordinal, ignore case..."); // Sort the list using the Turkish culture, which treats LATIN SMALL LETTER // DOTLESS I differently than LATIN SMALL LETTER I. list.Sort(turkICComp); Display(list, "Turkish culture, ignore case..."); }
/// <summary> /// Handles the upload button event. We save the file to disk, attempt to read a Lab Kit from it, and attempt to save it to the DB /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnLabKitUpload_Click(object sender, EventArgs e) { DataTable dt = null; List <int> labKitLoci = new List <int>(); // make sure we have a lab kit name if (string.IsNullOrEmpty(txtLabKitName.Text)) { MessageBox.Show("Please enter a name for the Lab Kit."); return; } // make sure a file has been uploaded with this post if (string.IsNullOrEmpty(FileUpload1.FileName)) { MessageBox.Show("Please select a Lab Kit file."); return; } try { string connString = string.Empty; string extension = string.Empty; // determine file type if (FileUpload1.FileName.EndsWith(".xlsx")) { extension = ".xlsx"; } else if (FileUpload1.FileName.EndsWith(".xls")) { extension = ".xls"; } // save file string filename = DateTime.Now.Ticks.ToString() + extension; FileUpload1.SaveAs(Server.MapPath("~/Admin/Upload/" + filename)); // create connection string switch (extension) { case ".xlsx": connString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath("~/Admin/Upload/") + filename + ";Extended Properties='Excel 12.0;HDR=No;IMEX=1';"); break; case ".xls": connString = string.Format("Provider=Microsoft.Jet.OLEDB.12.0;Data Source=" + Server.MapPath("~/Admin/Upload/") + filename + ";Extended Properties='Excel 8.0;HDR=No;IMEX=1';"); break; } // create a dropout rate table DataTable dtDropouts = new DataTable(); dtDropouts.Columns.Add(new DataColumn("LabKitID", typeof(Guid))); dtDropouts.Columns.Add(new DataColumn("LocusID", typeof(int))); dtDropouts.Columns.Add(new DataColumn("TypeID", typeof(int))); dtDropouts.Columns.Add(new DataColumn("DropOptionID", typeof(int))); dtDropouts.Columns.Add(new DataColumn("DropoutRate", typeof(double))); dtDropouts.Columns.Add(new DataColumn("NoOfPersonsInvolvd", typeof(int))); dtDropouts.Columns.Add(new DataColumn("Deducible", typeof(string))); DataTable dtLocus = bi.GetLocus(Guid.Empty); // get drop out rates // for 1 through 4 people, obviously for (int i = 1; i <= 4; i++) { // open the file and read the data from the sheet which we are working (named "1 person" and so on) using (OleDbConnection cn = new OleDbConnection(connString)) { cn.Open(); string query = string.Empty; switch (extension) { case ".xlsx": query = "SELECT * FROM [" + i + " person$]"; break; case ".xls": query = "SELECT * FROM [" + i + " person$]"; break; } // read file OleDbDataAdapter adapter = new OleDbDataAdapter(query, cn); dt = new DataTable(); adapter.Fill(dt); } string deducible = string.Empty; List <DropOutRow> vals = new List <DropOutRow>(); // get loci int rowIdx = 2, colIdx = 2; List <string> locusNames = new List <string>(); while (colIdx < dt.Columns.Count && dt.Rows[rowIdx][colIdx].ToString().Trim() != string.Empty) { locusNames.Add(dt.Rows[rowIdx][colIdx++].ToString().Trim()); } Dictionary <string, int> locusIDMap = new Dictionary <string, int>(); foreach (DataRow dr in dtLocus.Rows) { if (locusNames.Contains(dr["FieldName"].ToString(), StringComparer.Create(CultureInfo.CurrentCulture, true))) { locusIDMap.Add(dr["FieldName"].ToString().ToUpper(), Convert.ToInt32(dr["FieldValue"].ToString())); } } locusNames.Clear(); foreach (string locus in locusIDMap.Keys) { locusNames.Add(locus); } // set up the lab kit loci. we will be sending these to the database later if (labKitLoci.Count == 0) { foreach (string locus in locusIDMap.Keys) { labKitLoci.Add(locusIDMap[locus]); } } // get the deducible, PHET1, for persons i (which will be 1 through 4, see above) int firstRow = 3, firstCol = 2, type = 1, persons = i; deducible = "Yes"; vals.AddRange(CreateRows(dt, deducible, locusNames, locusIDMap, firstRow, firstCol, type, persons)); // get the deducible, PHET2, for persons i (which will be 1 through 4, see above) firstRow = 14; firstCol = 2; type = 2; persons = i; deducible = "Yes"; vals.AddRange(CreateRows(dt, deducible, locusNames, locusIDMap, firstRow, firstCol, type, persons)); // get the deducible, PHOM1, for persons i (which will be 1 through 4, see above) firstRow = 25; firstCol = 2; type = 3; persons = i; deducible = "Yes"; vals.AddRange(CreateRows(dt, deducible, locusNames, locusIDMap, firstRow, firstCol, type, persons)); // if we're doing more than one person, then get the non-deducible too if (i > 1) { // get the non-deducible, PHET1, for persons i (which will be 1 through 4, see above) firstRow = 38; firstCol = 2; type = 1; persons = i; deducible = "No"; vals.AddRange(CreateRows(dt, deducible, locusNames, locusIDMap, firstRow, firstCol, type, persons)); // get the non-deducible, PHET2, for persons i (which will be 1 through 4, see above) firstRow = 49; firstCol = 2; type = 2; persons = i; deducible = "No"; vals.AddRange(CreateRows(dt, deducible, locusNames, locusIDMap, firstRow, firstCol, type, persons)); // get the non-deducible, PHOM1, for persons i (which will be 1 through 4, see above) firstRow = 60; firstCol = 2; type = 3; persons = i; deducible = "No"; vals.AddRange(CreateRows(dt, deducible, locusNames, locusIDMap, firstRow, firstCol, type, persons)); } // go through our DropOutRows we created from the Excel file and add them to our table foreach (DropOutRow drow in vals) { DataRow dr = dtDropouts.NewRow(); dr["LocusID"] = drow.LocusID; dr["TypeID"] = drow.TypeID; dr["DropOptionID"] = drow.DropOptionID; dr["DropoutRate"] = drow.DropoutRate; dr["NoOfPersonsInvolvd"] = drow.NoOfPersonsInvolvd; dr["Deducible"] = drow.Deducible; dtDropouts.Rows.Add(dr); } vals.Clear(); } // create a dropins table DataTable dtDropins = new DataTable(); dtDropins.Columns.Add(new DataColumn("LabKitID", typeof(Guid))); dtDropins.Columns.Add(new DataColumn("DropInRateID", typeof(string))); dtDropins.Columns.Add(new DataColumn("Type", typeof(string))); dtDropins.Columns.Add(new DataColumn("DropInRate", typeof(double))); // get drop in rates // open the file and get the data from the dropins table using (OleDbConnection cn = new OleDbConnection(connString)) { cn.Open(); string query = string.Empty; switch (extension) { case ".xlsx": query = "SELECT * FROM [Drop-in$]"; break; case ".xls": query = "SELECT * FROM [Drop-in$]"; break; } // read file OleDbDataAdapter adapter = new OleDbDataAdapter(query, cn); dt = new DataTable(); adapter.Fill(dt); } // go through the specific areas in the file for (int i = 2; i <= 7; i++) { DataRow dr = dtDropins.NewRow(); dr["DropinRateID"] = dt.Rows[i][0]; dr["Type"] = dt.Rows[i][1]; dr["DropInRate"] = dt.Rows[i][2]; dtDropins.Rows.Add(dr); } // save the lab kit name and get back a GUID for it string guid = bi.SaveLabKit(txtLabKitName.Text, ""); Log.Info(Context.User.Identity.Name, Request.FilePath, Session, "Uploaded Lab Kit", guid); // add that GUID to the tables of drop-ins and drop-outs foreach (DataRow dr in dtDropouts.Rows) { dr["LabKitID"] = guid; } foreach (DataRow dr in dtDropins.Rows) { dr["LabKitID"] = guid; } // save the drop-ins and drop-outs to the database bi.SaveLabKitData(guid, dtDropouts, dtDropins, labKitLoci); // refresh the list of lab kits (should now include the new one) DataTable dt2 = bi.GetLabKits(); this.gvLabKits.DataSource = dt2; this.gvLabKits.DataBind(); txtLabKitName.Text = string.Empty; } catch (Exception ex) { // handle errors Log.Error(Context.User.Identity.Name, Request.FilePath, Session, "Error Adding Lab Kit", "File Parsing Error", ex); MessageBox.Show("There was an error reading the uploaded file. Please try uploading an Excel file in the correct format."); return; } }
public DescendingComparer(CultureInfo iCulture, bool iIgnoreCase) { fComparer = StringComparer.Create(iCulture, iIgnoreCase); }
private static void CreateCsvFile() { var answer = ReadUntilValid("Create CSV? ", "Not a valid answer.", a => new[] { "y", "yes", "1", "true", "n", "no", "0", "false" }.Contains(a, StringComparer.Create(CultureInfo.CurrentCulture, true))); if (!new[] { "y", "yes", "1", "true" }.Contains(answer, StringComparer.Create(CultureInfo.CurrentCulture, true))) { return; } int rowCount = 0; ReadUntilValid("How many rows? ", "You need to specify a valid integer.", s => int.TryParse(s, NumberStyles.Number, CultureInfo.CurrentCulture, out rowCount)); var rowsWrittenText = "Rows written: "; Console.Write(rowsWrittenText); using (var stream = File.Open(FileName, FileMode.Create)) using (var writer = new StreamWriter(stream)) using (var csv = new CsvWriter(writer)) { csv.Configuration.RegisterClassMap <TestClassMap>(); var stopwatch = new Stopwatch(); stopwatch.Start(); for (var i = 1; i <= rowCount; i++) { var row = new TestClass { IntColumn = i, StringColumn = string.Format("Row {0}", i), DateColumn = DateTime.Now, BoolColumn = i % 2 == 0, GuidColumn = Guid.NewGuid() }; Console.CursorLeft = rowsWrittenText.Length; csv.WriteRecord(row); Console.Write("{0:N0}", i); } stopwatch.Stop(); Console.WriteLine("Time: {0}", stopwatch.Elapsed); } Console.WriteLine(); }
private async Task <IEnumerable <Meeting> > SetMeetingList() { var scraperUtility = new ScraperUtilities(); var textUtility = new TextUtility(); var url = "https://meetings.ca.org/api/v1/meetings?area=Sweden¤t_day=0&order=city"; var handler = new HttpClientHandler(); var httpClient = new HttpClient(handler, false); var response = await httpClient.GetAsync(url); var caMeetings = new List <CAJsonToClass>(); var culture = new CultureInfo("sv-SE"); if (response.IsSuccessStatusCode) { var stream = await response.Content.ReadAsStreamAsync(); var ret = scraperUtility.DeserializeFromStream(stream).ToString(); caMeetings = JsonConvert.DeserializeObject <List <CAJsonToClass> >(ret); } var meetingList = new List <Meeting>(); if (null != caMeetings && caMeetings.Any()) { var dayAndTime = new List <MeetingSpecific>(); foreach (var caMeeting in caMeetings.OrderBy(m => m.group.name, StringComparer.Create(culture, false))) { var meeting = new Meeting(); var meetingExist = false; if (meetingList.Any(m => m.GroupName.Trim() == caMeeting.group.name.Trim())) { meeting = meetingList.Where(m => m.GroupName.Trim() == caMeeting.group.name.Trim()).FirstOrDefault(); meetingExist = true; } if (!meetingExist) { meeting.Id = caMeeting.group.id; meeting.GroupName = caMeeting.group.name.Trim(); meeting.Email = caMeeting.group.email; meeting.Phone = caMeeting.group.phone; meeting.GroupLink = caMeeting.group.web; meeting.Address.City = !string.IsNullOrWhiteSpace(caMeeting.group.location.localized_city) ? caMeeting.group.location.localized_city : caMeeting.group.location.city; meeting.Address.Street = !string.IsNullOrWhiteSpace(caMeeting.group.location.localized_road) ? caMeeting.group.location.localized_road : caMeeting.group.location.road; var district = new District { DistrictName = !string.IsNullOrWhiteSpace(caMeeting.group.location.localized_county) ? caMeeting.group.location.localized_county : caMeeting.group.location.county, Id = caMeeting.group.id }; var districtsList = new List <District> { district }; meeting.Address.Districts = districtsList.AsEnumerable(); var success = double.TryParse(caMeeting.group.location.lng, out double longLat); meeting.Address.Longitude = (success) ? longLat : 0; success = double.TryParse(caMeeting.group.location.lat, out longLat); meeting.Address.Lattitude = (success) ? longLat : 0; meeting.Language = caMeeting.group.location.language; Regex regEx = new Regex(@"(https?://[^\s]+)"); var description = caMeeting.description.Replace("\r\n", "<br>"); description = regEx.Replace(description, "<a href=\"$1\" target=\"_blank\">$1</a>"); meeting.AdditionalInformationHtmlString = description; meeting.Note = caMeeting.group.description; meeting.Address.LocationLink = string.Format("https://maps.google.com/maps?q={0}", caMeeting.group.location.localized_formatted_address); meeting.Address.LocalizedAddress = !string.IsNullOrWhiteSpace(caMeeting.group.location.localized_formatted_address) ? caMeeting.group.location.localized_formatted_address : caMeeting.group.location.formatted_address; } var meetingSpecifics = new MeetingSpecific(); var tags = new List <MeetingTypes>(); foreach (var tag in caMeeting.tags) { var type = scraperUtility.GetMeetingTypesCA(tag.word); if (type == MeetingTypes.NotSet) { continue; } tags.Add(type); } meetingSpecifics.MeetingTypes = tags.AsEnumerable(); if (tags.Any()) { meetingSpecifics.MeetingType = tags[0]; } var meetingDay = (int)Enum.Parse(typeof(WeekdayNames), caMeeting.day); meetingSpecifics.Id = meetingDay; meetingSpecifics.MeetingDay = meetingDay; DateTime.TryParse(caMeeting.time, out DateTime dateTime); TimeSpan startTime = dateTime.TimeOfDay; TimeSpan endTime = dateTime.AddMinutes(caMeeting.duration).TimeOfDay; meetingSpecifics.StartTime = startTime; meetingSpecifics.EndTime = endTime; dayAndTime = (null != meeting.DayAndTime && meeting.DayAndTime.Any()) ? meeting.DayAndTime.ToList() : new List <MeetingSpecific>(); if (null != dayAndTime && !dayAndTime.Any()) { for (var t = 0; t < 7; t++) { dayAndTime.Add(new MeetingSpecific { MeetingDay = t, StartTime = TimeSpan.FromTicks(0), EndTime = TimeSpan.FromTicks(0) }); } } if (null != dayAndTime) { if (dayAndTime.Any() && !dayAndTime.Contains(meetingSpecifics) && null == dayAndTime.FirstOrDefault(d => d.MeetingDay == meetingSpecifics.MeetingDay && meetingSpecifics.StartTime.Ticks == d.StartTime.Ticks) && meetingSpecifics.StartTime.Ticks > 0) { for (var t = 0; t < 7; t++) { dayAndTime.Add(new MeetingSpecific { MeetingDay = t, StartTime = TimeSpan.FromTicks(0), EndTime = TimeSpan.FromTicks(0) }); } } for (var t = 0; t < dayAndTime.Count; t++) { if (dayAndTime.Contains(meetingSpecifics) || meetingSpecifics.StartTime.Ticks <= 0) { continue; } if (dayAndTime[t].MeetingDay == meetingSpecifics.MeetingDay && dayAndTime[t].StartTime.Ticks <= 0 && meetingSpecifics.StartTime.Ticks > 0) { dayAndTime[t] = meetingSpecifics; } } } var lastRow = (dayAndTime.Count > 7) ? dayAndTime.GetRange(dayAndTime.Count - 7, 7).Sum(t => t.StartTime.Ticks) : -1; if (lastRow <= 0) { dayAndTime.RemoveRange(dayAndTime.Count - 7, 7); } meeting.DayAndTime = dayAndTime.AsEnumerable(); if (meetingExist) { var indexMeeting = meetingList.Where(m => m.GroupName.Trim() == caMeeting.group.name.Trim()).FirstOrDefault(); var index = meetingList.IndexOf(indexMeeting); if (index != -1) { meetingList[index] = meeting; } } else { meetingList.Add(meeting); } } } return(meetingList); }
private void Load() { string selectedSpell = spellList.SelectedItem as string; string selectedPlayer = playerList.SelectedItem as string; bool isPlayerOnly = showPlayers.IsChecked.Value; Records.Clear(); Spells.Clear(); Spells.Add("All Spells"); Players.Clear(); Players.Add("All Casters"); var playerDDTotals = new Dictionary <string, SpellDamageStats>(); var playerDoTTotals = new Dictionary <string, SpellDamageStats>(); var uniqueSpells = new Dictionary <string, byte>(); var uniquePlayers = new Dictionary <string, byte>(); var fights = fightOption.SelectedIndex == 0 ? (Application.Current.MainWindow as MainWindow).GetFightTable()?.GetFights() : (Application.Current.MainWindow as MainWindow).GetFightTable()?.GetSelectedFights(); foreach (var fight in fights) { foreach (var kv in fight.DDDamage) { if (!isPlayerOnly || PlayerManager.Instance.IsVerifiedPlayer(kv.Value.Caster)) { if (!playerDDTotals.TryGetValue(kv.Key, out SpellDamageStats ddStats)) { ddStats = new SpellDamageStats { Caster = kv.Value.Caster, Spell = kv.Value.Spell }; playerDDTotals[kv.Key] = ddStats; uniqueSpells[kv.Value.Spell] = 1; uniquePlayers[kv.Value.Caster] = 1; } ddStats.Max = Math.Max(ddStats.Max, kv.Value.Max); ddStats.Total += kv.Value.Total; ddStats.Count += kv.Value.Count; } } foreach (var kv in fight.DoTDamage) { if (!isPlayerOnly || PlayerManager.Instance.IsVerifiedPlayer(kv.Value.Caster)) { if (!playerDoTTotals.TryGetValue(kv.Key, out SpellDamageStats dotStats)) { dotStats = new SpellDamageStats { Caster = kv.Value.Caster, Spell = kv.Value.Spell }; playerDoTTotals[kv.Key] = dotStats; uniqueSpells[kv.Value.Spell] = 1; uniquePlayers[kv.Value.Caster] = 1; } dotStats.Max = Math.Max(dotStats.Max, kv.Value.Max); dotStats.Total += kv.Value.Total; dotStats.Count += kv.Value.Count; } } } foreach (var stats in playerDoTTotals.Values) { AddRow(stats, Labels.DOT); } foreach (var stats in playerDDTotals.Values) { AddRow(stats, Labels.DD); } foreach (var key in uniqueSpells.Keys.OrderBy(k => k, StringComparer.Create(new CultureInfo("en-US"), true))) { Spells.Add(key); } foreach (var key in uniquePlayers.Keys.OrderBy(k => k, StringComparer.Create(new CultureInfo("en-US"), true))) { Players.Add(key); } spellList.SelectedIndex = (Spells.IndexOf(selectedSpell) is int s && s > -1) ? s : 0; playerList.SelectedIndex = (Players.IndexOf(selectedPlayer) is int p && p > -1) ? p : 0; if (dataGrid.ItemsSource is ListCollectionView view) { view.SortDescriptions.Clear(); view.SortDescriptions.Add(new SortDescription("Avg", ListSortDirection.Descending)); } titleLabel.Content = Records.Count == 0 ? NODATA : "Spell Damage Stats for " + uniqueSpells.Count + " Unique Spells"; }
public ContentManager( Game game, FileSystem fileSystem, GraphicsDevice graphicsDevice, SageGame sageGame) { using (GameTrace.TraceDurationEvent("ContentManager()")) { _game = game; FileSystem = fileSystem; GraphicsDevice = graphicsDevice; SageGame = sageGame; Language = LanguageUtility.ReadCurrentLanguage(game.Definition, fileSystem); TranslationManager = Translation.TranslationManager.Instance; Translation.TranslationManager.LoadGameStrings(fileSystem, Language, game.Definition); LocaleSpecificEncoding = Encoding.GetEncoding(TranslationManager.CurrentLanguage.TextInfo.ANSICodePage); void OnLanguageChanged(object sender, EventArgs e) { throw new NotImplementedException("Encoding change on LanguageChanged not implemented yet"); } TranslationManager.LanguageChanged += OnLanguageChanged; AddDisposeAction(() => TranslationManager.LanguageChanged -= OnLanguageChanged); IniDataContext = new IniDataContext(); SubsystemLoader = Content.SubsystemLoader.Create(game.Definition, FileSystem, game, this); switch (sageGame) { // Only load these INI files for a subset of games, because we can't parse them for others yet. // TODO: Defer subsystem loading until necessary case SageGame.CncGenerals: case SageGame.CncGeneralsZeroHour: SubsystemLoader.Load(Subsystem.Core); SubsystemLoader.Load(Subsystem.Audio); SubsystemLoader.Load(Subsystem.Players); SubsystemLoader.Load(Subsystem.ParticleSystems); SubsystemLoader.Load(Subsystem.ObjectCreation); SubsystemLoader.Load(Subsystem.Locomotors); SubsystemLoader.Load(Subsystem.Sciences); SubsystemLoader.Load(Subsystem.Weapons); SubsystemLoader.Load(Subsystem.FXList); SubsystemLoader.Load(Subsystem.Multiplayer); SubsystemLoader.Load(Subsystem.LinearCampaign); SubsystemLoader.Load(Subsystem.Wnd); SubsystemLoader.Load(Subsystem.Terrain); SubsystemLoader.Load(Subsystem.Credits); SubsystemLoader.Load(Subsystem.Damage); SubsystemLoader.Load(Subsystem.SpecialPower); SubsystemLoader.Load(Subsystem.InGameUI); SubsystemLoader.Load(Subsystem.Rank); break; case SageGame.Bfme: case SageGame.Bfme2: case SageGame.Bfme2Rotwk: SubsystemLoader.Load(Subsystem.Core); SubsystemLoader.Load(Subsystem.Audio); SubsystemLoader.Load(Subsystem.Players); SubsystemLoader.Load(Subsystem.ParticleSystems); SubsystemLoader.Load(Subsystem.ObjectCreation); SubsystemLoader.Load(Subsystem.Locomotors); SubsystemLoader.Load(Subsystem.Sciences); SubsystemLoader.Load(Subsystem.Weapons); SubsystemLoader.Load(Subsystem.FXList); SubsystemLoader.Load(Subsystem.Multiplayer); SubsystemLoader.Load(Subsystem.LinearCampaign); SubsystemLoader.Load(Subsystem.Wnd); SubsystemLoader.Load(Subsystem.Terrain); SubsystemLoader.Load(Subsystem.Credits); SubsystemLoader.Load(Subsystem.Damage); SubsystemLoader.Load(Subsystem.SpecialPower); SubsystemLoader.Load(Subsystem.InGameUI); SubsystemLoader.Load(Subsystem.Rank); SubsystemLoader.Load(Subsystem.ExperienceLevels); SubsystemLoader.Load(Subsystem.AttributeModifiers); break; case SageGame.Cnc3: case SageGame.Ra3: SubsystemLoader.Load(Subsystem.Core); break; default: break; } UpgradeManager.Initialize(_game.AssetStore); FontManager = new FontManager(Language, StringComparer.Create(TranslationManager.CurrentLanguage, true)); } }
/// <summary> /// Find a value from a System.Enum by trying several possible variants /// of the string value of the enum. /// </summary> /// <param name="type">Type of enum</param> /// <param name="value">Value for which to search</param> /// <param name="culture">The culture used to calculate the name variants</param> /// <returns></returns> public static object FindEnumValue(this Type type, string value, CultureInfo culture) { #if FRAMEWORK var ret = Enum.GetValues(type) .Cast <Enum>() .FirstOrDefault(v => v.ToString().GetNameVariants(culture).Contains(value, StringComparer.Create(culture, true))); if (ret == null) { int enumValueAsInt; if (Int32.TryParse(value, out enumValueAsInt) && Enum.IsDefined(type, enumValueAsInt)) { ret = (Enum)Enum.ToObject(type, enumValueAsInt); } } return(ret); #else return(Enum.Parse(type, value, true)); #endif }
public static void GenerateObsSignals() { var bands = new Dictionary <SatelliteSystem, int[]> { { SatelliteSystem.Gps, new[] { 1, 2, 5 } }, { SatelliteSystem.Glo, new[] { 1, 2 } }, { SatelliteSystem.Gal, new[] { 1, 5, 6, 7, 8 } }, { SatelliteSystem.Bds, new[] { 2, 6, 7 } }, { SatelliteSystem.Irnss, new[] { 5, 9 } }, { SatelliteSystem.Qzss, new[] { 1, 2, 5, 6 } }, { SatelliteSystem.Sbas, new[] { 1, 5 } } }; var attributes = new Dictionary <SatelliteSystem, ObsAttribute[]> { { SatelliteSystem.Gps, new[] { ObsAttribute.P, ObsAttribute.C, ObsAttribute.D, ObsAttribute.Y, ObsAttribute.M, ObsAttribute.N, ObsAttribute.I, ObsAttribute.Q, ObsAttribute.S, ObsAttribute.L, ObsAttribute.X, ObsAttribute.W } }, { SatelliteSystem.Glo, new[] { ObsAttribute.P, ObsAttribute.C } }, { SatelliteSystem.Gal, new[] { ObsAttribute.A, ObsAttribute.B, ObsAttribute.C, ObsAttribute.I, ObsAttribute.Q, ObsAttribute.X, ObsAttribute.Z, } }, { SatelliteSystem.Bds, new[] { ObsAttribute.I, ObsAttribute.Q, ObsAttribute.X } }, { SatelliteSystem.Irnss, new[] { ObsAttribute.A, ObsAttribute.B, ObsAttribute.C, ObsAttribute.X } }, { SatelliteSystem.Qzss, new[] { ObsAttribute.I, ObsAttribute.Q, ObsAttribute.S, ObsAttribute.L, ObsAttribute.X } }, { SatelliteSystem.Sbas, new[] { ObsAttribute.C } } }; using (var file = File.Create(Path.Combine(Environment.CurrentDirectory, "codes"))) { List <string> z = new List <string>(); var sw = new StreamWriter(file); foreach (var oType in Enum.GetNames(typeof(ObsType))) { var result = from band in bands join attr in attributes on band.Key equals attr.Key select new { bands = band.Value, attr = attr.Value }; var temp = from r in result from rb in r.bands from ra in r.attr select String.Format("{0}{1}{2}", oType, rb, ra); z.AddRange(temp); } foreach (var obs in z.Distinct(StringComparer.Create(CultureInfo.InvariantCulture, true))) { sw.WriteLine(obs + ","); } } }
public static IQueryable OrderBy <T>(this IQueryable source, string ordering, Func <Type> getDynamicListTypeCallback, params object[] values) { if (source == null) { throw new ArgumentNullException("source"); } if (ordering == null) { throw new ArgumentNullException("ordering"); } IQueryable <T> typedSource = source as IQueryable <T>; if (!ordering.Contains(",")) { bool descending = false; if (ordering.IndexOf(" descending", StringComparison.CurrentCultureIgnoreCase) >= 0) { ordering = ordering.Replace(" descending", ""); descending = true; } if (ordering.IndexOf(" desc", StringComparison.CurrentCultureIgnoreCase) >= 0) { ordering = ordering.Replace(" desc", ""); descending = true; } LambdaExpression lambda = DynamicExpression.ParseLambda <T>(source.ElementType, typeof(object), ordering, false, values); if (lambda.Parameters.Count > 0 && lambda.Parameters[0].Type == typeof(T)) { //source list is DynamicNode and the lambda returns a Func<object> Func <T, object> func = (Func <T, object>)lambda.Compile(); //get the values out var query = typedSource.ToList().ConvertAll(item => new { node = item, key = EvaluateDynamicNodeFunc(item, func) }); if (query.Count == 0) { return(source); } var types = from i in query group i by i.key.GetType() into g where g.Key != typeof(DynamicNull) orderby g.Count() descending select new { g, Instances = g.Count() }; var dominantType = types.First().g.Key; // NH - add culture dependencies StringComparer comp = StringComparer.Create(CultureInfo.CurrentCulture, true); if (!descending) { // if the dominant type is a string we'll ensure that strings are sorted based on culture settings on node if (dominantType.FullName == "System.String") { return(query.OrderBy(item => item.key.ToString(), comp).Select(item => item.node).AsQueryable()); } else { return(query.OrderBy(item => GetObjectAsTypeOrDefault(item.key, dominantType)).Select(item => item.node).AsQueryable()); } } else { if (dominantType.FullName == "System.String") { return(query.OrderByDescending(item => item.key.ToString(), comp).Select(item => item.node).AsQueryable()); } else { return(query.OrderByDescending(item => GetObjectAsTypeOrDefault(item.key, dominantType)).Select(item => item.node).AsQueryable()); } } } } bool isDynamicNodeList = false; if (typedSource != null) { isDynamicNodeList = true; } ParameterExpression[] parameters = new ParameterExpression[] { Expression.Parameter(source.ElementType, "") }; var parser = new ExpressionParser <T>(parameters, ordering, values, false); IEnumerable <DynamicOrdering> orderings = parser.ParseOrdering(); Expression queryExpr = source.Expression; string methodAsc = "OrderBy"; string methodDesc = "OrderByDescending"; foreach (DynamicOrdering o in orderings) { if (!isDynamicNodeList) { queryExpr = Expression.Call( typeof(Queryable), o.Ascending ? methodAsc : methodDesc, new Type[] { source.ElementType, o.Selector.Type }, queryExpr, Expression.Quote(Expression.Lambda(o.Selector, parameters))); } else { //reroute each stacked Expression.Call into our own methods that know how to deal //with DynamicNode queryExpr = Expression.Call( getDynamicListTypeCallback(), o.Ascending ? methodAsc : methodDesc, null, queryExpr, Expression.Quote(Expression.Lambda(o.Selector, parameters)) ); } methodAsc = "ThenBy"; methodDesc = "ThenByDescending"; } if (isDynamicNodeList) { return(typedSource.Provider.CreateQuery(queryExpr)); } return(source.Provider.CreateQuery(queryExpr)); }
private void InitAttributes() { StringComparer caseInsensitiveComparer = StringComparer.Create(CultureInfo.InvariantCulture, true); Attributes = new Dictionary <string, MMEAttribute>(caseInsensitiveComparer); }
public ContentManager( Game game, FileSystem fileSystem, GraphicsDevice graphicsDevice, SageGame sageGame) { using (GameTrace.TraceDurationEvent("ContentManager()")) { _game = game; FileSystem = fileSystem; GraphicsDevice = graphicsDevice; SageGame = sageGame; Language = LanguageUtility.ReadCurrentLanguage(game.Definition, fileSystem.RootDirectory); TranslationManager = Translation.TranslationManager.Instance; Translation.TranslationManager.LoadGameStrings(fileSystem, Language, sageGame); LocaleSpecificEncoding = Encoding.GetEncoding(TranslationManager.CurrentLanguage.TextInfo.ANSICodePage); TranslationManager.LanguageChanged += (sender, e) => throw new NotImplementedException("Encoding change on LanguageChanged not implemented yet"); IniDataContext = new IniDataContext(); SubsystemLoader = Content.SubsystemLoader.Create(game.Definition, FileSystem, game, this); switch (sageGame) { // Only load these INI files for a subset of games, because we can't parse them for others yet. case SageGame.CncGenerals: case SageGame.CncGeneralsZeroHour: case SageGame.Bfme: case SageGame.Bfme2: case SageGame.Bfme2Rotwk: SubsystemLoader.Load(Subsystem.Core); // TODO: Defer subsystem loading until necessary SubsystemLoader.Load(Subsystem.Audio); SubsystemLoader.Load(Subsystem.Players); SubsystemLoader.Load(Subsystem.ParticleSystems); SubsystemLoader.Load(Subsystem.ObjectCreation); SubsystemLoader.Load(Subsystem.Locomotors); SubsystemLoader.Load(Subsystem.Weapons); SubsystemLoader.Load(Subsystem.FXList); SubsystemLoader.Load(Subsystem.Multiplayer); SubsystemLoader.Load(Subsystem.LinearCampaign); SubsystemLoader.Load(Subsystem.Wnd); SubsystemLoader.Load(Subsystem.Terrain); SubsystemLoader.Load(Subsystem.Credits); SubsystemLoader.Load(Subsystem.Damage); break; case SageGame.Cnc3: SubsystemLoader.Load(Subsystem.Core); break; default: break; } FontManager = new FontManager(Language, StringComparer.Create(TranslationManager.CurrentLanguage, true)); } }
/// <summary> /// /// </summary> private void LoadInterWiki() { string text; if (!Globals.UnitTestMode) { text = Tools.GetHTML("http://en.wikipedia.org/w/index.php?title=Wikipedia:AutoWikiBrowser/IW&action=raw"); } else { text = @"<!--InterwikiLocalAlphaBegins--> ru, sq, en <!--InterwikiLocalAlphaEnds--> <!--InterwikiLocalFirstBegins--> en, sq, ru <!--InterwikiLocalFirstEnds-->"; } string interwikiLocalAlphaRaw = remExtra(Tools.StringBetween(text, "<!--InterwikiLocalAlphaBegins-->", "<!--InterwikiLocalAlphaEnds-->")); string interwikiLocalFirstRaw = remExtra(Tools.StringBetween(text, "<!--InterwikiLocalFirstBegins-->", "<!--InterwikiLocalFirstEnds-->")); int no = 0; int size = IWSplit.Matches(interwikiLocalFirstRaw).Count + 1; InterwikiLocalAlpha = new string[IWSplit.Matches(interwikiLocalAlphaRaw).Count + 1]; foreach (string s in interwikiLocalAlphaRaw.Split(new [] { "," }, StringSplitOptions.RemoveEmptyEntries) ) { InterwikiLocalAlpha[no] = s.Trim().ToLower(); no++; } InterwikiLocalFirst = new string[size]; no = 0; foreach (string s in interwikiLocalFirstRaw.Split(new [] { "," }, StringSplitOptions.RemoveEmptyEntries) ) { InterwikiLocalFirst[no] = s.Trim().ToLower(); no++; } InterwikiAlpha = (string[])InterwikiLocalFirst.Clone(); Array.Sort(InterwikiAlpha, StringComparer.Create(new System.Globalization.CultureInfo("en-US", true), true)); string[] temp = (string[])InterwikiAlpha.Clone(); temp[Array.IndexOf(temp, "en")] = ""; InterwikiAlphaEnFirst = new string[size]; InterwikiAlphaEnFirst[0] = "en"; no = 1; foreach (string s in temp) { if (s.Trim().Length > 0) { InterwikiAlphaEnFirst[no] = s; no++; } } }
public void CultureOrderBy() { string[] source = new[] { "Apple0", "Æble0", "Apple1", "Æble1", "Apple2", "Æble2" }; CultureInfo dk = new CultureInfo("da-DK"); CultureInfo au = new CultureInfo("en-AU"); StringComparer comparerDk = StringComparer.Create(dk, ignoreCase: false); StringComparer comparerAu = StringComparer.Create(au, ignoreCase: false); // we don't provide a defined sorted result set because the Windows culture sorting // provides a different result set to the Linux culture sorting. But as we're really just // concerned that OrderBy default string ordering matches current culture then this // should be sufficient string[] resultDK = source.ToArray(); Array.Sort(resultDK, comparerDk); string[] resultAU = source.ToArray(); Array.Sort(resultAU, comparerAu); string[] check; using (new ThreadCultureChange(dk)) { check = source.OrderBy(x => x).ToArray(); Assert.Equal(resultDK, check, StringComparer.Ordinal); } using (new ThreadCultureChange(au)) { check = source.OrderBy(x => x).ToArray(); Assert.Equal(resultAU, check, StringComparer.Ordinal); } using (new ThreadCultureChange(dk)) // "dk" whilst GetEnumerator { IEnumerator <string> s = source.OrderBy(x => x).GetEnumerator(); using (new ThreadCultureChange(au)) // but "au" whilst accessing... { int idx = 0; while (s.MoveNext()) // sort is done on first MoveNext, so should have "au" sorting { Assert.Equal(resultAU[idx++], s.Current, StringComparer.Ordinal); } } } using (new ThreadCultureChange(au)) { // "au" whilst GetEnumerator IEnumerator <string> s = source.OrderBy(x => x).GetEnumerator(); using (new ThreadCultureChange(dk)) { // but "dk" on first MoveNext bool moveNext = s.MoveNext(); Assert.True(moveNext); // ensure changing culture after MoveNext doesn't affect sort using (new ThreadCultureChange(au)) // "au" whilst GetEnumerator { int idx = 0; while (moveNext) // sort is done on first MoveNext, so should have "dk" sorting { Assert.Equal(resultDK[idx++], s.Current, StringComparer.Ordinal); moveNext = s.MoveNext(); } } } } }
public void SetUp() { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; EvaluatorMock = new Mock <INodeEvaluator>(); EvaluatorMock.Setup(m => m.KnownComparers).Returns(new Dictionary <Type, IComparer> { { typeof(string), StringComparer.Create(CultureInfo.InvariantCulture, false) } }); EvaluatorMock.Setup(m => m.FlushOutput()).Returns(() => { var temp = consoleOutput; consoleOutput = null; return(temp); }); EvaluatorMock.Setup(m => m.InvokeMember("\"aaa\"", "ToUpper", new object[] { })).Returns("AAA"); EvaluatorMock.Setup(m => m.InvokeMethod("ToUpper", new object[] { "aaa" })).Returns("AAA"); EvaluatorMock.Setup(m => m.InvokeMember(5, "ToString", new object[] { })).Returns("5"); EvaluatorMock.Setup(m => m.InvokeMethod("ToDouble", new object[] { "2.45", 0, "en-us" })).Returns(2.45); EvaluatorMock.Setup(m => m.InvokeMethod("ToDouble", new object[] { "2,45", 0, "cs-cz" })).Returns(2.45); EvaluatorMock.Setup(m => m.InvokeMethod("ToDouble", new object[] { "2,45" })).Returns(2.45); EvaluatorMock.Setup(m => m.InvokeMethod("ToDateTime", new object[] { "10/5/2010" })).Returns(DateTime.Parse("10/5/2010")); EvaluatorMock.Setup(m => m.InvokeMethod("ToDateTime", new object[] { "12/31/2017 11:59 PM" })).Returns(DateTime.Parse("12/31/2017 11:59 PM")); EvaluatorMock.Setup(m => m.InvokeMethod("ToTimeSpan", new object[] { "1:00:00" })).Returns(TimeSpan.Parse("1:00:00")); EvaluatorMock.Setup(m => m.InvokeMethod("ToDateTime", new object[] { "10.5.2010" })).Returns(DateTime.Parse("10.5.2010", CultureInfo.GetCultureInfo("cs-cz"))); EvaluatorMock.Setup(m => m.InvokeMethod("ToDateTime", new object[] { "31.12.2017 11:59 PM" })).Returns(DateTime.Parse("31.12.2017 11:59 PM", CultureInfo.GetCultureInfo("cs-cz"))); EvaluatorMock.Setup(m => m.InvokeMethod("List", It.IsAny <object[]>())).Returns <string, object[]>((name, items) => items as IList); EvaluatorMock .Setup(m => m.InvokeMember(It.IsAny <object>(), "toupper", It.IsAny <object[]>())) .Returns <object, string, object[]>((word, methodName, args) => { return((word.ToString()).ToUpper()); }); EvaluatorMock.Setup(m => m.InvokeMethod("GetDict", new object[] { })).Returns(new Dictionary <string, int>() { { "one", 1 } }); EvaluatorMock.Setup(m => m.InvokeMethod("print", It.IsAny <object[]>())).Returns <string, object[]>((methodName, objectToPrint) => { consoleOutput += Convert.ToString(objectToPrint[0]); return(null); }); EvaluatorMock.Setup(m => m.InvokeMethod("println", It.IsAny <object[]>())).Returns <string, object[]>((methodName, objectToPrint) => { consoleOutput += Convert.ToString(objectToPrint[0]); string temp = consoleOutput; consoleOutput = null; return(temp); }); EvaluatorMock.Setup(m => m.GetVariableValue("string")).Returns(typeof(string)); EvaluatorMock.Setup(m => m.InvokeMember(typeof(string), "Empty", null)).Returns(string.Empty); EvaluatorMock.Setup(m => m.InvokeMember(string.Empty, "Length", null)).Returns(0); EvaluatorMock.Setup(m => m.GetVariableValue("DocumentName")).Returns("This is sparta!"); EvaluatorMock.Setup(m => m.InvokeMember("This is sparta!", "ToString", new object[] { })).Returns("This is sparta!"); EvaluatorMock.Setup(m => m.GetVariableValue("DocumentName2")).Returns("This is sparta!"); EvaluatorMock.Setup(m => m.InvokeMember("This is sparta!", "ToString", new object[] { "defaultValue" })).Returns("defaultValue"); EvaluatorMock.Setup(m => m.InvokeMember("\"string\"", "ToUpper", new object[] { })).Returns("STRING"); EvaluatorMock.Setup(m => m.InvokeMethod("Cache", new object[] { "STRING" })).Returns("STRING - Cached"); EvaluatorMock.Setup(m => m.GetVariableValue("GlobalObjects")).Returns("GlobalObjects"); EvaluatorMock.Setup(m => m.InvokeMember("GlobalObjects", "Users", null)).Returns("Users"); EvaluatorMock.Setup(m => m.GetVariableValue("Users")).Returns("Users"); EvaluatorMock.Setup(m => m.InvokeMember("Users", "RandomSelection", new object[] { })).Returns("RandomName"); EvaluatorMock.Setup(m => m.GetVariableValue("RandomName")).Returns("RandomName"); EvaluatorMock.Setup(m => m.InvokeMember("RandomName", "UserName", null)).Returns("John Doe"); EvaluatorMock.Setup(m => m.InvokeMember("Users", "GetItem", new object[] { 0 })).Returns("FirstUser"); EvaluatorMock.Setup(m => m.GetVariableValue("FirstUser")).Returns("FirstUser"); EvaluatorMock.Setup(m => m.InvokeMember("FirstUser", "UserName", null)).Returns("Echo from Dollhouse"); EvaluatorMock.Setup(m => m.GetVariableValue("UserEnabled")).Returns(true); EvaluatorMock.Setup(m => m.InvokeMember("Users", "Any", new object[] { false })).Returns("Jack Nenabled"); EvaluatorMock.Setup(m => m.InvokeIndexer("Users", 1)).Returns('s'); EvaluatorMock.Setup(m => m.InvokeMember('s', "UserName", null)).Returns("Alpha from Dollhouse"); EvaluatorMock.Setup(m => m.InvokeIndexer("\"hello\"", 1)).Returns('e'); EvaluatorMock.Setup(m => m.InvokeIndexer(new Dictionary <string, int>() { { "one", 1 } }, "one")).Returns(1); EvaluatorMock.Setup(m => m.InvokeIndexer(It.IsAny <IList>(), It.IsAny <int>())).Returns <IList, int>((collection, index) => { return(collection[index]); }); var ct = new CancellationTokenSource(); ct.CancelAfter(15000); EvaluatorMock.Setup(m => m.GetCancellationToken()).Returns(ct.Token); Visitor = new KSharpVisitor(EvaluatorMock.Object); }
IDictionary <string, string> GetVMNames(IEnumerable <string> vmNames, IList <string> vmExclude, VmNameType nameType) { IDictionary <string, string> d = new Dictionary <string, string>(); string query; string vmIdField; if (UseWMIV2NameSpace) { query = "SELECT VirtualSystemIdentifier, ElementName FROM Msvm_VirtualSystemSettingData WHERE VirtualSystemType = 'Microsoft:Hyper-V:System:Realized'"; vmIdField = "VirtualSystemIdentifier"; } else { query = "SELECT SystemName, ElementName FROM Msvm_VirtualSystemSettingData WHERE SettingType = 3"; vmIdField = "SystemName"; } var inField = nameType == VmNameType.ElementName ? "ElementName" : vmIdField; var scope = new ManagementScope(GetWMIScope()); if (vmNames != null && vmNames.Any()) { query += $" AND ({GetORStr(inField, vmNames)})"; } using (var searcher = new ManagementObjectSearcher(scope, new ObjectQuery(query))) { using (var moc = searcher.Get()) foreach (var mo in moc) { using (mo) { if (vmExclude == null || !vmExclude.Contains((string)mo["ElementName"], StringComparer.Create(CultureInfo.InvariantCulture, true))) { d.Add((string)mo[vmIdField], (string)mo["ElementName"]); } } } } return(d); }
public IQueryable <Transaction> FindTransactionsWithin(UserParameters parameters, IQueryable <Transaction> transactions) { var lookup = new HashSet <string>(parameters.Usernames, StringComparer.Create(CultureInfo.CurrentCulture, true)); return(transactions.Where(x => !lookup.Contains(x.Username))); }
private static void SelectTest() { while (true) { var question = new StringBuilder(); question.AppendLine("1) Parse"); question.AppendLine("2) Parse and count bytes"); question.AppendLine("q) Quit"); question.Append("Select test to run: "); var option = ReadUntilValid(question.ToString(), "Not a valid option.", s => new[] { "1", "2" }.Contains(s, StringComparer.Create(CultureInfo.CurrentCulture, true))); switch (option) { case "1": ParseTest(); break; case "2": ParseCountingBytesTest(); break; case "q": return; } } }
public IReadOnlyCollection <object> Read(Stream excelStream, string worksheetName, Type type, CultureInfo cultureInfo) { using (var package = new ExcelPackage(excelStream)) { package.Compatibility.IsWorksheets1Based = true; var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); var propertiesByName = properties .ToDictionary ( p => { var displayAttribute = p.GetCustomAttribute <DisplayAttribute>(); return (displayAttribute != null && !String.IsNullOrWhiteSpace(displayAttribute.Name) ? displayAttribute.Name : p.Name); }, StringComparer.Create(cultureInfo, true) ); var worksheet = package.Workbook.Worksheets[worksheetName]; var worksheetDimension = worksheet.Dimension; if (worksheetDimension == null) { throw new ExcelWorksheetEmptyException(); } var columnNoAndPropertyMaps = new Dictionary <int, PropertyInfo>(); for (var columnNo = 1; columnNo <= worksheetDimension.Columns; columnNo++) { var cell = worksheet.Cells[1, columnNo]; if (string.IsNullOrWhiteSpace(cell.Text)) { continue; } if (!propertiesByName.TryGetValue(cell.Text, out var property)) { throw new ExcelInvalidHeaderNameException(1, columnNo, cell.Address); } columnNoAndPropertyMaps.Add(columnNo, property); } if (columnNoAndPropertyMaps.Count == 0) { throw new ExcelWorksheetEmptyException(); } var items = new List <object>(); for (var rowNo = 2; rowNo <= worksheetDimension.Rows; rowNo++) { var isOk = false; var item = Activator.CreateInstance(type); foreach (var columnNoAndPropertyMap in columnNoAndPropertyMaps) { var cell = worksheet.Cells[rowNo, columnNoAndPropertyMap.Key]; if (string.IsNullOrWhiteSpace(cell.Text)) { continue; } var propertyType = Nullable.GetUnderlyingType(columnNoAndPropertyMap.Value.PropertyType) ?? columnNoAndPropertyMap.Value.PropertyType; object value; try { value = Convert.ChangeType(cell.Text, propertyType, cultureInfo); } catch (FormatException ex) { throw new ExcelInvalidCellValueException(rowNo, columnNoAndPropertyMap.Key, cell.Address, columnNoAndPropertyMap.Value.Name, ex); } if (value != null) { columnNoAndPropertyMap.Value.SetValue(item, value); } isOk = true; } if (isOk) { items.Add(item); } } return(items.AsReadOnly()); } }
private void Initialize(CultureInfo CultureInfo, int StartingHashCapacity = 0) { if (StartingHashCapacity > 0) { this.m_KeyedNodesHash = new Dictionary <string, Node>(StartingHashCapacity, StringComparer.Create(CultureInfo, true)); } else { this.m_KeyedNodesHash = new Dictionary <string, Node>(StringComparer.Create(CultureInfo, true)); } this.m_ItemsList = new FastList(); this.m_Iterators = new ArrayList(); this.m_CultureInfo = CultureInfo; }
private static ushort[] CreateMappingTable(CacheKey cacheKey) { return(GetOrdering(CreateMappingTable(StringComparer.Create( cacheKey.CultureInfo, cacheKey.IgnoreCase)))); }
protected override bool Apply(object x) { var cpr = StringComparer.Create(CultureInfo.InvariantCulture, false); return(cpr.Compare(x.ToString(), Reference.ToString()) < 0); }
/// <inheritdoc /> public object ReadValue <TInput>(ref Reader <TInput> reader, Field field) { ReferenceCodec.MarkValueField(reader.Session); uint type = default; CompareOptions options = default; int lcid = default; uint fieldId = 0; while (true) { var header = reader.ReadFieldHeader(); if (header.IsEndBaseOrEndObject) { break; } fieldId += header.FieldIdDelta; switch (fieldId) { case 0: type = UInt32Codec.ReadValue(ref reader, header); break; case 1: options = (CompareOptions)UInt64Codec.ReadValue(ref reader, header); break; case 2: lcid = Int32Codec.ReadValue(ref reader, header); break; default: reader.ConsumeUnknownField(header); break; } } if (type == 0) { return(null); } else if (type == 1) { if (options.HasFlag(CompareOptions.IgnoreCase)) { return(StringComparer.OrdinalIgnoreCase); } else { return(StringComparer.Ordinal); } } else if (type == 2) { if (lcid == CultureInfo.InvariantCulture.LCID) { if (options == CompareOptions.None) { return(StringComparer.InvariantCulture); } else if (options == CompareOptions.IgnoreCase) { return(StringComparer.InvariantCultureIgnoreCase); } // Otherwise, perhaps some other options were specified, in which case we fall-through to create a new comparer. } var cultureInfo = CultureInfo.GetCultureInfo(lcid); var result = StringComparer.Create(cultureInfo, options); return(result); } ThrowNotSupported(field, type); return(null); }
private IDictionary <string, string> CreateDictionary() { return(new NullIfNotFoundDictionary <string, string>(StringComparer.Create(this.culture, false))); }
public override StringComparer ToStringComparer() { return(StringComparer.Create(m_culture, m_ignoreCase)); }
public JREndean.Lang.Chainings.IfThenElseVoid <TValue> Equals(TValue equal) { return(new Chainings.IfThenElseVoid <TValue>(this.value, StringComparer.Create(System.Globalization.CultureInfo.InvariantCulture, true).Compare(this.value, equal) == 0)); }
private static StandardDialect TestDialect(CultureInfo culture, DialectCasing casing) { var dialect = new StandardDialect(culture, casing); Assert.IsInstanceOf <StandardSelfObject>(dialect.Self); Assert.AreEqual(dialect.Culture, culture); Assert.AreEqual('"', dialect.EndStringLiteralCharacter); Assert.AreEqual('}', dialect.EndTagCharacter); Assert.AreEqual(culture.NumberFormat.CurrencyDecimalSeparator[0], dialect.NumberDecimalSeparatorCharacter); Assert.AreEqual('"', dialect.StartStringLiteralCharacter); Assert.AreEqual('{', dialect.StartTagCharacter); Assert.AreEqual('\\', dialect.StringLiteralEscapeCharacter); Assert.NotNull(dialect.FlowSymbols); Assert.AreEqual("(", dialect.FlowSymbols.GroupOpen); Assert.AreEqual(")", dialect.FlowSymbols.GroupClose); Assert.AreEqual(",", dialect.FlowSymbols.Separator); Assert.AreEqual(".", dialect.FlowSymbols.MemberAccess); var expectedComparer = StringComparer.Create(dialect.Culture, casing == DialectCasing.IgnoreCase); Assert.AreEqual(dialect.IdentifierComparer, expectedComparer); Assert.AreEqual(dialect.StringLiteralComparer, expectedComparer); Func <string, string> transformer = input => input; if (casing == DialectCasing.LowerCase) { transformer = input => input.ToLower(culture); } else if (casing == DialectCasing.UpperCase) { transformer = input => input.ToUpper(culture); } Assert.AreEqual(5, dialect.SpecialKeywords.Count); Assert.IsTrue(dialect.SpecialKeywords.ContainsKey(transformer("True")) && dialect.SpecialKeywords[transformer("True")].Equals(true)); Assert.IsTrue(dialect.SpecialKeywords.ContainsKey(transformer("False")) && dialect.SpecialKeywords[transformer("False")].Equals(false)); Assert.IsTrue(dialect.SpecialKeywords.ContainsKey(transformer("Undefined")) && dialect.SpecialKeywords[transformer("Undefined")] == null); Assert.IsTrue(dialect.SpecialKeywords.ContainsKey(transformer("NaN")) && dialect.SpecialKeywords[transformer("NaN")].Equals(double.NaN)); Assert.IsTrue(dialect.SpecialKeywords.ContainsKey(transformer("Infinity")) && dialect.SpecialKeywords[transformer("Infinity")].Equals(double.PositiveInfinity)); Assert.AreEqual(7, dialect.Directives.Count); foreach (var directive in dialect.Directives) { if (directive is ConditionalInterpolationDirective) { Assert.AreEqual(transformer("{$ IF $}"), directive.ToString()); } else if (directive is ForEachDirective) { Assert.AreEqual(transformer("{FOR EACH ? IN $}...{END}"), directive.ToString()); } else if (directive is IfDirective) { Assert.AreEqual(transformer("{IF $ THEN}...{END}"), directive.ToString()); } else if (directive is IfElseDirective) { Assert.AreEqual(transformer("{IF $ THEN}...{ELSE}...{END}"), directive.ToString()); } else if (directive is InterpolationDirective) { Assert.AreEqual("{$}", directive.ToString()); } else if (directive is RepeatDirective) { Assert.AreEqual(transformer("{REPEAT $ TIMES}...{END}"), directive.ToString()); } else if (directive is PreFormattedUnParsedTextDirective) { Assert.AreEqual(transformer("{PREFORMATTED}...{END}"), directive.ToString()); } else { Assert.Fail(); } } Assert.AreEqual(24, dialect.Operators.Count); foreach (var @operator in dialect.Operators) { if (@operator is RelationalEqualsOperator) { Assert.AreEqual("==", @operator.ToString()); } else if (@operator is RelationalNotEqualsOperator) { Assert.AreEqual("!=", @operator.ToString()); } else if (@operator is RelationalGreaterThanOperator) { Assert.AreEqual(">", @operator.ToString()); } else if (@operator is RelationalGreaterThanOrEqualsOperator) { Assert.AreEqual(">=", @operator.ToString()); } else if (@operator is RelationalLowerThanOperator) { Assert.AreEqual("<", @operator.ToString()); } else if (@operator is RelationalLowerThanOrEqualsOperator) { Assert.AreEqual("<=", @operator.ToString()); } else if (@operator is LogicalAndOperator) { Assert.AreEqual("&&", @operator.ToString()); } else if (@operator is LogicalOrOperator) { Assert.AreEqual("||", @operator.ToString()); } else if (@operator is LogicalNotOperator) { Assert.AreEqual("!", @operator.ToString()); } else if (@operator is BitwiseAndOperator) { Assert.AreEqual("&", @operator.ToString()); } else if (@operator is BitwiseOrOperator) { Assert.AreEqual("|", @operator.ToString()); } else if (@operator is BitwiseXorOperator) { Assert.AreEqual("^", @operator.ToString()); } else if (@operator is BitwiseNotOperator) { Assert.AreEqual("~", @operator.ToString()); } else if (@operator is BitwiseShiftLeftOperator) { Assert.AreEqual("<<", @operator.ToString()); } else if (@operator is BitwiseShiftRightOperator) { Assert.AreEqual(">>", @operator.ToString()); } else if (@operator is ArithmeticDivideOperator) { Assert.AreEqual("/", @operator.ToString()); } else if (@operator is ArithmeticModuloOperator) { Assert.AreEqual("%", @operator.ToString()); } else if (@operator is ArithmeticMultiplyOperator) { Assert.AreEqual("*", @operator.ToString()); } else if (@operator is ArithmeticNegateOperator) { Assert.AreEqual("-", @operator.ToString()); } else if (@operator is ArithmeticNeutralOperator) { Assert.AreEqual("+", @operator.ToString()); } else if (@operator is ArithmeticSubtractOperator) { Assert.AreEqual("-", @operator.ToString()); } else if (@operator is ArithmeticSumOperator) { Assert.AreEqual("+", @operator.ToString()); } else if (@operator is SequenceOperator) { Assert.AreEqual("..", @operator.ToString()); } else if (@operator is FormatOperator) { Assert.AreEqual(":", @operator.ToString()); } else { Assert.Fail(); } } return(dialect); }