protected virtual object GetValueObject(PropertyInfo propertyInfo, string value) { var propertyType = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType; var typeCode = Type.GetTypeCode(propertyType); switch (typeCode) { case TypeCode.Boolean: return(Boolean.Parse(value)); case TypeCode.Char: return(Char.Parse(value)); case TypeCode.SByte: return(SByte.Parse(value, this.Culture)); case TypeCode.Byte: return(Byte.Parse(value, this.Culture)); case TypeCode.Int16: return(Int16.Parse(value, this.Culture)); case TypeCode.UInt16: return(UInt16.Parse(value, this.Culture)); case TypeCode.Int32: return(Int32.Parse(value, this.Culture)); case TypeCode.UInt32: return(UInt32.Parse(value, this.Culture)); case TypeCode.Int64: return(Int64.Parse(value, this.Culture)); case TypeCode.UInt64: return(UInt64.Parse(value, this.Culture)); case TypeCode.Single: return(Single.Parse(value, this.Culture)); case TypeCode.Double: return(Double.Parse(value, this.Culture)); case TypeCode.Decimal: return(Decimal.Parse(value, this.Culture)); case TypeCode.DateTime: return(DateTime.Parse(value, this.Culture)); case TypeCode.String: return(value as string); case TypeCode.Object: Guid guid; if (Guid.TryParse(value, out guid)) { return(guid); } TimeSpan timeSpan; if (TimeSpan.TryParse(value, out timeSpan)) { return(timeSpan); } DateTimeOffset dateTimeOffset; if (DateTimeOffset.TryParse(value, out dateTimeOffset)) { return(dateTimeOffset); } break; } return(null); }
public static UInt32 HexToUInt32(string hex) => UInt32.Parse(hex.Remove(0, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
public static string Unescape(string input) { var length = input.Length; int start = 0; int count = 0; var output = StringBuilderThreadStatic.Allocate(); for (; count < length;) { if (input[count] == JsonUtils.QuoteChar) { if (start != count) { output.Append(input, start, count - start); } count++; start = count; continue; } if (input[count] == JsonUtils.EscapeChar) { if (start != count) { output.Append(input, start, count - start); } start = count; count++; if (count >= length) { continue; } //we will always be parsing an escaped char here var c = input[count]; switch (c) { case 'a': output.Append('\a'); count++; break; case 'b': output.Append('\b'); count++; break; case 'f': output.Append('\f'); count++; break; case 'n': output.Append('\n'); count++; break; case 'r': output.Append('\r'); count++; break; case 'v': output.Append('\v'); count++; break; case 't': output.Append('\t'); count++; break; case 'u': if (count + 4 < length) { var unicodeString = input.Substring(count + 1, 4); var unicodeIntVal = UInt32.Parse(unicodeString, NumberStyles.HexNumber); output.Append(ConvertFromUtf32((int)unicodeIntVal)); count += 5; } else { output.Append(c); } break; case 'x': if (count + 4 < length) { var unicodeString = input.Substring(count + 1, 4); var unicodeIntVal = uint.Parse(unicodeString, NumberStyles.HexNumber); output.Append(ConvertFromUtf32((int)unicodeIntVal)); count += 5; } else if (count + 2 < length) { var unicodeString = input.Substring(count + 1, 2); var unicodeIntVal = uint.Parse(unicodeString, NumberStyles.HexNumber); output.Append(ConvertFromUtf32((int)unicodeIntVal)); count += 3; } else { output.Append(input, start, count - start); } break; default: output.Append(c); count++; break; } start = count; } else { count++; } } output.Append(input, start, length - start); return(StringBuilderThreadStatic.ReturnAndFree(output)); }
public override void Update(ViewModelReturnData VMReturnData) { if (VMReturnData.NewCardIssuer_Active) { this.View.Visibility = Visibility.Visible; #region Navigationbar details VMReturnData.ViewTitle = "New Issuer Card"; VMReturnData.SubTitle = "New Issuer details"; //VMReturnData.CurrentPageNumber = 1; //VMReturnData.TotalPageNumber = 4; VMReturnData.MenuButtonEnabled = Visibility.Collapsed; VMReturnData.HelpButtonEnabled = Visibility.Visible; #endregion if (IssuerFileCardBtnPressed) { IssuerFileCardBtnPressed = false; MernokPasswordFile mernokPasswordFile = MernokPasswordManager.ReadMernokPasswordFile(V); OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.Filter = "License Files|*.merlic"; openFileDialog1.Title = "Select a Mernok Licnese File"; if (openFileDialog1.ShowDialog() == true) { // Assign the cursor in the Stream to the Form's Cursor property. Console.WriteLine(Path.GetFullPath(openFileDialog1.FileName)); LicenseFilePath = Path.GetFullPath(openFileDialog1.FileName); CardDetailsFile = CardDetailManager.ReadCardDetailFile(LicenseFilePath); VMReturnData.VMCardDetails = CardDetailsFile.FCardDetails; VMReturnData.NewCardUID = CardDetailsFile.FCardDetails.cardUID; } // } if (CardDetailsFile.FCardDetails == null) { WarningMessageF = "Please select a license file."; CardUidPresVis = Visibility.Collapsed; } else { CardUidPresVis = Visibility.Visible; } if (!VMReturnData.CardInField) { if (CardDetailsFile.FCardDetails != null) { WarningMessageI = "Present RFID card with UID: " + VMReturnData.cardInfoRead.UIDtoString(CardDetailsFile.FCardDetails.cardUID); } MessageColour = Brushes.OrangeRed; } else if (CardDetailsFile.FCardDetails != null && CardDetailsFile.FCardDetails.cardUID == VMReturnData.UID) { VMReturnData.VMCardDetails.IssuerUID = CardinFieldUID = VMReturnData.UID; MernokPasswordFile mernokPasswordFile = MernokPasswordManager.ReadMernokPasswordFile(V); bool password = PasswordFinder.FindPasswordinFile(AdminPassword, mernokPasswordFile); if (password) { PassColour = Brushes.GreenYellow; string[] IssuerDetails = /*{ "1", "piet", "1", "2" };*/ PasswordDecriptor.PasswordToDetails(AdminPassword); VMReturnData.VMCardDetails.EngineerName = IssuerDetails[3]; VMReturnData.VMCardDetails.EngineerUID = UInt32.Parse(IssuerDetails[0]); VMReturnData.NextButtonEnabled = true; WarningMessageI = "Password good, click next to continue"; MessageColour = Brushes.White; } else { MessageColour = Brushes.OrangeRed; PassColour = Brushes.OrangeRed; VMReturnData.NextButtonEnabled = false; if (AdminPassword == "") { WarningMessageI = "Enter your password"; } else { WarningMessageI = "Enter correct password"; } } } } else { //View is not visible, do not update //Stop any animations on this vieModel this.View.Visibility = Visibility.Collapsed; AdminPassword = ""; } }
public static bool ResolveInterfacesOnTreeView_recursive(TreeNode tnStartNode, ICirData cdCirData, Dictionary <String, O2TraceBlock_OunceV6> dO2TraceBlock, Dictionary <String, O2TraceBlock_OunceV6> dRawData, //TreeView tvRawData_, String sHardCodedInterfaceKeywork) { var stStackTrace = new StackTrace(); if (stStackTrace.FrameCount > 50) { String sMsg = String.Format( "on ResolveInterfacesOnTreeView_recursive, max StackTrace reached, aborting this leaf:{0}", tnStartNode.Text); DI.log.error(sMsg); return(false); } if (tnStartNode != null) { foreach (TreeNode tnNode in tnStartNode.Nodes) { if (tnNode.Text.IndexOf(sHardCodedInterfaceKeywork) > -1) { if (tnNode.Tag != null) { var fviFindingViewItem = (FindingViewItem)tnNode.Tag; String sSink = AnalysisUtils.getSink(fviFindingViewItem.fFinding, fviFindingViewItem.oadO2AssessmentDataOunceV6); if (cdCirData.dFunctions_bySignature.ContainsKey(sSink)) { ICirFunction cfCirFunction = cdCirData.dFunctions_bySignature[sSink]; ICirClass ccCirClass = cfCirFunction.ParentClass; foreach (ICirClass ccIsSuperClassedBy in ccCirClass.dIsSuperClassedBy.Values) { String sMappedMethodName = cfCirFunction.FunctionSignature.Replace(ccCirClass.Signature, ccIsSuperClassedBy.Signature); List <O2TraceBlock_OunceV6> lotdMatches = analyzer.getO2TraceBlocksThatMatchSignature(sMappedMethodName, dO2TraceBlock); foreach (O2TraceBlock_OunceV6 otbO2TraceBlock in lotdMatches) { TreeNode tnNewNode_forImplementation = O2Forms.newTreeNode(otbO2TraceBlock.sUniqueName, otbO2TraceBlock.sUniqueName, 0, null); tnNode.ForeColor = Color.CadetBlue; tnNewNode_forImplementation.ForeColor = Color.DarkBlue; foreach ( AssessmentAssessmentFileFinding fFinding in otbO2TraceBlock.dSinks.Keys) { var fviFindingViewItem_ForSink = new FindingViewItem(fFinding, fFinding.vuln_name ?? OzasmtUtils_OunceV6. getStringIndexValue (UInt32.Parse (fFinding . vuln_name_id), otbO2TraceBlock.dSinks[fFinding]), null, otbO2TraceBlock. dSinks[fFinding ]); String sUniqueName_ForSink = analyzer.getUniqueSignature(fviFindingViewItem_ForSink.fFinding, TraceType.Known_Sink, fviFindingViewItem_ForSink. oadO2AssessmentDataOunceV6, true); TreeNode tnImplementation_Sink = O2Forms.newTreeNode( sUniqueName_ForSink, sUniqueName_ForSink, 0, fviFindingViewItem_ForSink); tnNewNode_forImplementation.Nodes.Add(tnImplementation_Sink); if (tnImplementation_Sink.Text != "") { if (false == analyzer.addCompatibleTracesToNode_recursive( tnImplementation_Sink, fviFindingViewItem_ForSink, dRawData[tnImplementation_Sink.Text], "Sinks", dRawData)) { // (O2TraceBlock_OunceV6) // tvRawData.Nodes[tnImplementation_Sink.Text].Tag, "Sinks", // tvRawData)) return(false); } } // need to see any posible side effects of this (false check was not there on small projects) } tnNode.Nodes.Add(tnNewNode_forImplementation); } } } } } foreach (TreeNode tnChildNode in tnNode.Nodes) { if (false == ResolveInterfacesOnTreeView_recursive(tnChildNode, cdCirData, dO2TraceBlock, dRawData, //tvRawData, sHardCodedInterfaceKeywork)) { return(false); } } } } return(true); }
private static void OnAxisHomingMethodZCB(IntPtr dataPtr, string str) { axisHomingMethod[2] = UInt32.Parse(str); configUpdated = true; }
protected override void OnDrawItem(DrawItemEventArgs e) { // Make sure we're not trying to draw something that isn't there. if (e.Index >= this.Items.Count || e.Index <= -1) { return; } // Get the item object. object item = this.Items[e.Index]; if (item == null) { return; } // Draw the item. if (IsGameList) { if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) { e.Graphics.FillRectangle(new SolidBrush(Color.LightBlue), e.Bounds); } else { e.Graphics.FillRectangle(new SolidBrush(Color.White), e.Bounds); } TrophyConfNode tc = (TrophyConfNode)item; e.Graphics.DrawImage(tc.GameThumbnail, 0, e.Bounds.Y, 160, 88); string text = tc.TitleName; SizeF stringSize = e.Graphics.MeasureString(text, this.Font); e.Graphics.DrawString(text, this.Font, new SolidBrush(Color.Black), new PointF(163, e.Bounds.Y + (e.Bounds.Height - stringSize.Height) / 2)); } else { TrophyNode t = (TrophyNode)item; if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) { e.Graphics.FillRectangle(new SolidBrush(Color.LightBlue), e.Bounds); } else { if (CurrentGame.TropUsrFile.TrophyInfos[UInt32.Parse(t.ID)].Unlocked == 1) { e.Graphics.FillRectangle(new SolidBrush(Color.LightGreen), e.Bounds); } else { e.Graphics.FillRectangle(new SolidBrush(Color.White), e.Bounds); } } e.Graphics.DrawImage(t.TrophyThumbnail, 0, e.Bounds.Y, 60, 60); string text = item.ToString(); SizeF stringSize = e.Graphics.MeasureString(text, this.Font); e.Graphics.DrawString(text, this.Font, new SolidBrush(Color.Black), new PointF(63, e.Bounds.Y + (e.Bounds.Height - stringSize.Height) / 2)); } }
protected string ParseString(char[] json, ref int index) { string s = ""; char c; EatWhitespace(json, ref index); // " c = json[index++]; bool complete = false; while (!complete) { if (index == json.Length) { break; } c = json[index++]; if (c == '"') { complete = true; break; } else if (c == '\\') { if (index == json.Length) { break; } c = json[index++]; if (c == '"') { s += '"'; } else if (c == '\\') { s += '\\'; } else if (c == '/') { s += '/'; } else if (c == 'b') { s += '\b'; } else if (c == 'f') { s += '\f'; } else if (c == 'n') { s += '\n'; } else if (c == 'r') { s += '\r'; } else if (c == 't') { s += '\t'; } else if (c == 'u') { int remainingLength = json.Length - index; if (remainingLength >= 4) { // fetch the next 4 chars char[] unicodeCharArray = new char[4]; Array.Copy(json, index, unicodeCharArray, 0, 4); // parse the 32 bit hex into an integer codepoint uint codePoint = UInt32.Parse(new string(unicodeCharArray), NumberStyles.HexNumber); // convert the integer codepoint to a unicode char and add to string //s += Char.ConvertFromUtf32((int)codePoint); throw new NotImplementedException(); // skip 4 chars index += 4; } else { break; } } } else { s += c; } } if (!complete) { return(null); } return(s); }
internal static object ConvertTo(this object value, Type toType, Func <object> getConverter, IServiceProvider serviceProvider) { if (value == null) { return(null); } var str = value as string; if (str != null) { //If there's a [TypeConverter], use it object converter = getConverter?.Invoke(); if (null != converter) { var xfTypeConverter = converter as TypeConverter; var xfExtendedTypeConverter = xfTypeConverter as IExtendedTypeConverter; if (xfExtendedTypeConverter != null) { return(value = xfExtendedTypeConverter.ConvertFromInvariantString(str, serviceProvider)); } if (xfTypeConverter != null) { return(value = xfTypeConverter.ConvertFromInvariantString(str)); } var converterType = converter?.GetType(); if (converterType != null) { var convertFromStringInvariant = converterType.GetRuntimeMethod("ConvertFromInvariantString", new[] { typeof(string) }); if (convertFromStringInvariant != null) { return(value = convertFromStringInvariant.Invoke(converter, new object[] { str })); } } } var ignoreCase = (serviceProvider?.GetService(typeof(IConverterOptions)) as IConverterOptions)?.IgnoreCase ?? false; //If the type is nullable, as the value is not null, it's safe to assume we want the built-in conversion if (toType.GetTypeInfo().IsGenericType&& toType.GetGenericTypeDefinition() == typeof(Nullable <>)) { toType = Nullable.GetUnderlyingType(toType); } //Obvious Built-in conversions if (toType.GetTypeInfo().IsEnum) { return(Enum.Parse(toType, str, ignoreCase)); } if (toType == typeof(SByte)) { return(SByte.Parse(str, CultureInfo.InvariantCulture)); } if (toType == typeof(Int16)) { return(Int16.Parse(str, CultureInfo.InvariantCulture)); } if (toType == typeof(Int32)) { return(Int32.Parse(str, CultureInfo.InvariantCulture)); } if (toType == typeof(Int64)) { return(Int64.Parse(str, CultureInfo.InvariantCulture)); } if (toType == typeof(Byte)) { return(Byte.Parse(str, CultureInfo.InvariantCulture)); } if (toType == typeof(UInt16)) { return(UInt16.Parse(str, CultureInfo.InvariantCulture)); } if (toType == typeof(UInt32)) { return(UInt32.Parse(str, CultureInfo.InvariantCulture)); } if (toType == typeof(UInt64)) { return(UInt64.Parse(str, CultureInfo.InvariantCulture)); } if (toType == typeof(Single)) { return(Single.Parse(str, CultureInfo.InvariantCulture)); } if (toType == typeof(Double)) { return(Double.Parse(str, CultureInfo.InvariantCulture)); } if (toType == typeof(Boolean)) { return(Boolean.Parse(str)); } if (toType == typeof(TimeSpan)) { return(TimeSpan.Parse(str, CultureInfo.InvariantCulture)); } if (toType == typeof(DateTime)) { return(DateTime.Parse(str, CultureInfo.InvariantCulture)); } if (toType == typeof(Char)) { char c = '\0'; Char.TryParse(str, out c); return(c); } if (toType == typeof(String) && str.StartsWith("{}", StringComparison.Ordinal)) { return(str.Substring(2)); } if (toType == typeof(String)) { return(value); } if (toType == typeof(Decimal)) { return(Decimal.Parse(str, CultureInfo.InvariantCulture)); } } //if the value is not assignable and there's an implicit conversion, convert if (value != null && !toType.IsAssignableFrom(value.GetType())) { var opImplicit = value.GetType().GetImplicitConversionOperator(fromType: value.GetType(), toType: toType) ?? toType.GetImplicitConversionOperator(fromType: value.GetType(), toType: toType); if (opImplicit != null) { value = opImplicit.Invoke(null, new[] { value }); return(value); } } return(value); }
// minimalistic .rle file reader for Golly files (see http://golly.sourceforge.net) public void Init() { timer = new Stopwatch(); StreamReader sr = new StreamReader("../../data/turing_js_r.rle"); uint state = 0, n = 0, x = 0, y = 0; while (true) { String line = sr.ReadLine(); if (line == null) { break; // end of file } int pos = 0; if (line[pos] == '#') { continue; } /* comment line */ else if (line[pos] == 'x') // header { String[] sub = line.Split(new char[] { '=', ',' }, StringSplitOptions.RemoveEmptyEntries); pw = (UInt32.Parse(sub[1]) + 31) / 32; ph = UInt32.Parse(sub[3]); Console.WriteLine(pw + " " + ph); pattern = new uint[pw * ph]; second = new uint[pw * ph]; } else { while (pos < line.Length) { Char c = line[pos++]; if (state == 0) { if (c < '0' || c > '9') { state = 1; n = Math.Max(n, 1); } else { n = (uint)(n * 10 + (c - '0')); } } if (state == 1) // expect other character { if (c == '$') { y += n; x = 0; } // newline else if (c == 'o') { for (int i = 0; i < n; i++) { BitSet(x++, y); } } else if (c == 'b') { x += n; } state = n = 0; } } } } // swap buffers for (int i = 0; i < pw * ph; i++) { second[i] = pattern[i]; } // //Initialize buffers // for (int i = 0; i < pw * ph; i++) // { // second[i] = 0; // pattern[i] = 0; // } //for(int i = 0; i < 10; i++) // { // second[i] = 1; // pattern[i] = 1; // } patternBuffer = new OpenCLBuffer <uint>(ocl, pattern); secondBuffer = new OpenCLBuffer <uint>(ocl, second); }
protected override object ParseString(string from) { return(UInt32.Parse(StringHelper.RemoveBlanks(from), NumberStyles.Number | NumberStyles.AllowExponent, mCulture)); }
/// <summary>Changes the alpha channel of the <see cref="Color"/>. </summary> /// <param name="color">The <see cref="Color"/>. </param> /// <param name="alpha">The new alpha value. </param> /// <returns>The new <see cref="Color"/>. </returns> public static Color ChangeAlpha(Color color, string alpha) { var value = UInt32.Parse(alpha, NumberStyles.HexNumber); return(ChangeAlpha(color, (byte)(value & 0xff))); }
public void ReadXml(System.Xml.XmlReader reader) { Value = UInt32.Parse(reader.ReadString(), System.Globalization.NumberStyles.HexNumber); }
public void loadAbilityDB(string path) { Output.Write("Loading Abilities.."); // load the CSV into an ArrayList collection ArrayList abilityDB = loadCSV(path, ';'); int linecount = 1; // Create a new List foreach (string[] data in abilityDB) { //Output.WriteLine("Show Colums for Line : " + linecount.ToString() + " Ability ID: " + data[0].ToString() + " GOID " + data[1].ToString() + " Ability Name : " + data[2].ToString()); AbilityItem ability = new AbilityItem(); // we want to skip the first line as it should have the Names if (linecount > 1) { ability.setAbilityID(Convert.ToUInt16(data[0])); ability.setGOID(Convert.ToInt32(data[1])); ability.setAbilityName(data[2]); if (data[3].Length > 0) { ability.setIsCastable(bool.Parse(data[3])); } if (data.Length >= 5) { if (data[4].Length > 0) { CultureInfo ci = (CultureInfo)CultureInfo.CurrentCulture.Clone(); ci.NumberFormat.CurrencyDecimalSeparator = "."; ability.setCastingTime(float.Parse(data[4], NumberStyles.Any, ci)); } } if (data.Length >= 6) { if (data[5].Length > 2) { ability.setCastAnimStart(StringUtils.hexStringToBytes(data[5])); } } if (data.Length >= 7) { if (data[6].Length > 2) { ability.setCastAnimMid(StringUtils.hexStringToBytes((data[6]))); } } if (data.Length >= 8) { if (data[7].Length > 2) { ability.setCastAnimEnd(StringUtils.hexStringToBytes(data[7])); } } if (data.Length >= 9) { if (data[8].Length > 0) { ability.setActivationFX(UInt32.Parse(data[8])); } } if (data.Length >= 10) { if (data[9].Length > 0) { ability.setValueFrom(Int16.Parse(data[9])); } } if (data.Length >= 11) { if (data[10].Length > 0) { ability.setValueTo(UInt16.Parse(data[10])); } } if (data.Length >= 12) { if (data[11].Length > 0) { ability.setIsBuff(bool.Parse(data[11])); } } if (data.Length >= 13) { if (data[12].Length > 0) { CultureInfo ci = (CultureInfo)CultureInfo.CurrentCulture.Clone(); ci.NumberFormat.CurrencyDecimalSeparator = "."; ability.setBuffTime(float.Parse(data[12], NumberStyles.Any, ci)); } } if (data.Length >= 14) { if (data[13].Length > 0) { ability.setAbilityExecutionFX(UInt32.Parse(data[13])); } } AbilityDB.Add(ability); } linecount++; } }
public static uint GetRowIndex(string cellReference) { Match match = RowIndexRegex.Match(cellReference); return(UInt32.Parse(match.Value)); }
/// <summary> /// Returns a parsers for the String value using the given built-in class for parsing. /// </summary> /// <param name="type">is the type to parse the value to</param> /// <returns>value matching the type passed in</returns> public static SimpleTypeParser GetParser(Type type) { Type typeBoxed = TypeHelper.GetBoxedType(type); if (typeBoxed == typeof(string)) { return(value => value); } if (typeBoxed == typeof(char?)) { return(value => value[0]); } if (typeBoxed == typeof(bool?)) { return(value => Boolean.Parse(value)); } if (typeBoxed == typeof(Guid?)) { return(value => new Guid(value)); } // -- Integers if (typeBoxed == typeof(byte?)) { return(delegate(String value) { value = value.Trim(); if (value.StartsWith("0x")) { return Byte.Parse(value.Substring(2), NumberStyles.HexNumber); } return Byte.Parse(value.Trim()); }); } if (typeBoxed == typeof(sbyte?)) { return(value => SByte.Parse(value.Trim())); } if (typeBoxed == typeof(short?)) { return(value => Int16.Parse(value)); } if (typeBoxed == typeof(ushort?)) { return(value => UInt16.Parse(value)); } if (typeBoxed == typeof(int?)) { return(value => Int32.Parse(value)); } if (typeBoxed == typeof(uint?)) { return(value => UInt32.Parse(value)); } if (typeBoxed == typeof(long?)) { return(delegate(String value) { value = value.TrimEnd('l', 'L', ' '); return Int64.Parse(value); }); } if (typeBoxed == typeof(ulong?)) { return(delegate(String value) { value = value.TrimEnd('l', 'L', ' '); return UInt64.Parse(value); }); } // -- Floating Point if (typeBoxed == typeof(float?)) { return(delegate(String value) { value = value.TrimEnd('f', 'F', ' '); return Single.Parse(value); }); } if (typeBoxed == typeof(double?)) { return(delegate(String value) { value = value.TrimEnd('f', 'F', 'd', 'D', ' '); return Double.Parse(value); }); } if (typeBoxed == typeof(decimal?)) { return(delegate(String value) { value = value.TrimEnd('f', 'F', 'd', 'D', 'M', 'm', ' '); return Decimal.Parse(value); }); } var untyped = Nullable.GetUnderlyingType(typeBoxed); if ((untyped != null) && untyped.IsEnum) { return(value => Enum.Parse(untyped, value, true)); } return(null); }
private static void OnAxisHomingV2YCB(IntPtr dataPtr, string str) { axisHomingV2[1] = UInt32.Parse(str); configUpdated = true; }
public Connection() { Port = UInt16.Parse(ConfigManager.Config["port"].ToString()); TimeoutTimer.Interval = UInt32.Parse(ConfigManager.Config["timeout"].ToString()); TimeoutTimer.Elapsed += Reset; }
int GetResponse(byte [] buffer, int max) { int pos = 0; string line = null; bool lineok = false; bool isContinue = false; bool emptyFirstLine = false; do { if (readState == ReadState.None) { lineok = ReadLine(buffer, ref pos, max, ref line); if (!lineok) { return(-1); } if (line == null) { emptyFirstLine = true; continue; } emptyFirstLine = false; readState = ReadState.Status; string [] parts = line.Split(' '); if (parts.Length < 2) { return(-1); } if (String.Compare(parts [0], "HTTP/1.1", true) == 0) { Data.Version = HttpVersion.Version11; sPoint.SetVersion(HttpVersion.Version11); } else { Data.Version = HttpVersion.Version10; sPoint.SetVersion(HttpVersion.Version10); } Data.StatusCode = (int)UInt32.Parse(parts [1]); if (parts.Length >= 3) { Data.StatusDescription = String.Join(" ", parts, 2, parts.Length - 2); } else { Data.StatusDescription = ""; } if (pos >= max) { return(pos); } } emptyFirstLine = false; if (readState == ReadState.Status) { readState = ReadState.Headers; Data.Headers = new WebHeaderCollection(); ArrayList headers = new ArrayList(); bool finished = false; while (!finished) { if (ReadLine(buffer, ref pos, max, ref line) == false) { break; } if (line == null) { // Empty line: end of headers finished = true; continue; } if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) { int count = headers.Count - 1; if (count < 0) { break; } string prev = (string)headers [count] + line; headers [count] = prev; } else { headers.Add(line); } } if (!finished) { return(-1); } foreach (string s in headers) { Data.Headers.SetInternal(s); } if (Data.StatusCode == (int)HttpStatusCode.Continue) { sPoint.SendContinue = true; if (pos >= max) { return(pos); } if (Data.request.ExpectContinue) { Data.request.DoContinueDelegate(Data.StatusCode, Data.Headers); // Prevent double calls when getting the // headers in several packets. Data.request.ExpectContinue = false; } readState = ReadState.None; isContinue = true; } else { readState = ReadState.Content; return(pos); } } } while (emptyFirstLine || isContinue); return(-1); }
public void F3Gate_OnReceived(object sender, HttpDataEventArgs arg) { Log.Info(String.Format("F3 received a request form {0} through {1} method with url: {2}", arg.Request.RemoteEndPoint, arg.Request.HttpMethod, arg.Request.RawUrl)); if (!arg.Request.HasEntityBody) { return; } var stringContent = new Dictionary <string, string>(); var binaryContent = new Dictionary <string, byte[]>(); using (var body = arg.Request.InputStream) { using (new StreamReader(body, arg.Request.ContentEncoding)) { var streamContent = new StreamContent(body); streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse(arg.Request.ContentType); var provider = streamContent.ReadAsMultipartAsync().Result; foreach (var httpContent in provider.Contents) { var name = httpContent.Headers.ContentDisposition.Name.Replace("\"", String.Empty); var fileName = httpContent.Headers.ContentDisposition.FileName; if (string.IsNullOrWhiteSpace(fileName)) { var value = httpContent.ReadAsStringAsync().Result; stringContent.Add(name, value); continue; } var bytesValue = httpContent.ReadAsByteArrayAsync().Result; binaryContent.Add(name, bytesValue); } } } //If debug output all message if (this.IsDebug) { foreach (var key in stringContent.Keys) { Log.Info(String.Format("Key:{0} Value:{1}", key, stringContent[key])); } foreach (var key in binaryContent.Keys) { Log.Info(String.Format("Key:{0} BinaryLength:{1}", key, binaryContent[key].Length)); } } //Switch urls var url = arg.Request.RawUrl; try { if (url.Equals(this.ParkingUrl)) { var trigger = this.OnParking; if (trigger != null) { trigger(this, new ParkingEventArgs( arg.Request, arg.Response, stringContent[this.Config.GetString("PlateNumber")], DateTime.Parse(stringContent[this.Config.GetString("InTime")]), binaryContent[this.Config.GetString("InImage")]) ); } } else if (url.Equals(this.LeavingUrl)) { var trigger = this.OnLeaving; if (trigger != null) { trigger(this, new LeavingEventArgs( arg.Request, arg.Response, stringContent[this.Config.GetString("PlateNumber")], DateTime.Parse(stringContent[this.Config.GetString("OutTime")]), binaryContent[this.Config.GetString("OutImage")], Decimal.Parse(stringContent[this.Config.GetString("CopeMoney")]), Decimal.Parse(stringContent[this.Config.GetString("ActualMoney")]), UInt32.Parse(stringContent[this.Config.GetString("TicketId")]) )); } } else if (url.Equals(this.CouponReceiveUrl)) { var trigger = this.OnCouponNeed; if (trigger != null) { trigger(this, new CouponEventArgs(arg.Request, arg.Response, stringContent[this.Config.GetString("PlateNumber")])); } } else if (url.Equals(this.UpdateUrl)) { var trigger = this.OnSurplusSpaceUpdate; if (trigger != null) { trigger(this, new UpdateSurplusSpaceEventArgs(arg.Request, arg.Response, UInt16.Parse(stringContent[this.Config.GetString("SURPLUSSPACE")]))); } } else if (url.Equals(this.ImageUpdateUrl)) { var trigger = this.OnImageUpdate; if (trigger != null) { trigger(this, new ImageUpdateEventArgs(arg.Request, arg.Response, stringContent[this.Config.GetString("PlateNumber")], stringContent[this.Config.GetString("ImageTime")], binaryContent[this.Config.GetString("Image")], stringContent[this.Config.GetString("ImageType")] )); } } else { arg.Response.OutputStream.Close(); throw new ArgumentException(String.Format("Can not distinguish url {0}", arg.Request.Url)); } } catch (KeyNotFoundException) { arg.Response.OutputStream.Close(); throw new ArgumentException("Request argument deficiency!"); } catch (Exception ex) { arg.Response.OutputStream.Close(); throw new ArgumentException("Can not process this request!", ex); } }
static void Main(string[] args) { Console.Write("Enter number:"); uint n = 0; try { n = UInt32.Parse(Console.ReadLine()); } catch (OverflowException) { Console.WriteLine("Out of range. Aborting program .."); Environment.Exit(0); } Console.WriteLine("Binary representation of n:\n {0}", Convert.ToString(n, 2).PadLeft(32, '0')); Console.Write("Enter p:"); byte p = byte.Parse(Console.ReadLine()); Console.Write("Enter q:"); byte q = byte.Parse(Console.ReadLine()); Console.Write("Enter k:"); byte k = byte.Parse(Console.ReadLine()); if (p < 0 || p > 31 || q < 0 || q > 31 || 31 - (p + k - 1) < 0) { Console.WriteLine("Out of range. Aborting program .."); Environment.Exit(0); } string binary = "00000000000000000000000000000000"; StringBuilder strMaskOne = new StringBuilder(binary); StringBuilder strMaskTwo = new StringBuilder(binary); int begin = (binary.Length - 1 - p); int end = (binary.Length - 1) - (p + k - 1); int beginTwo = (binary.Length - 1 - q); int endTwo = (binary.Length - 1) - (q + k - 1); if (end < beginTwo || endTwo < begin) { Console.WriteLine("Overlapping. Aborting program .."); Environment.Exit(0); } for (int i = begin; i >= end; i--) { strMaskOne[i] = '1'; } for (int i = beginTwo; i >= endTwo; i--) { strMaskTwo[i] = '1'; } uint firstMask = Convert.ToUInt32(strMaskOne.ToString(), 2); uint secondMask = Convert.ToUInt32(strMaskTwo.ToString(), 2); firstMask = n & firstMask; secondMask = n & secondMask; uint result = n & ~(firstMask | secondMask); int shiftage; if (firstMask < secondMask) { shiftage = q - p; result = result | (firstMask << shiftage); result = result | (secondMask >> shiftage); Console.WriteLine("Binary result:\n {0}", Convert.ToString(result, 2).PadLeft(32, '0')); Console.WriteLine("result:\n" + result); } else { shiftage = p - q; result = result | (firstMask >> shiftage); result = result | (secondMask << shiftage); Console.WriteLine("Binary result:\n {0}", Convert.ToString(result, 2).PadLeft(32, '0')); Console.WriteLine("result:\n" + result); } }
public void GetCurrentConnectionIds(out IList <UInt32> currentConnectionIds) { IList <object> outParams = _getCurrentConnectionIdsAction.InvokeAction(null); currentConnectionIds = outParams[0].ToString().Split(',').Select(x => UInt32.Parse(x)).ToList <UInt32>(); }
public void TestParse() { //test Parse(string s) Assert.IsTrue(MyUInt32_1 == UInt32.Parse(MyString1), "Parse problem on \"" + MyString1 + "\""); Assert.IsTrue(MyUInt32_2 == UInt32.Parse(MyString2), "Parse problem on \"" + MyString2 + "\""); Assert.IsTrue(MyUInt32_3 == UInt32.Parse(MyString3), "Parse problem on \"" + MyString3 + "\""); try { UInt32.Parse(null); Assert.Fail("Should raise a System.ArgumentNullException"); } catch (Exception e) { Assert.IsTrue(typeof(ArgumentNullException) == e.GetType(), "Did not get ArgumentNullException type"); } try { UInt32.Parse("not-a-number"); Assert.Fail("Should raise a System.FormatException"); } catch (Exception e) { Assert.IsTrue(typeof(FormatException) == e.GetType(), "Did not get FormatException type"); } try { // TODO: Use this after ToString() is completed. For now, hard code string that generates // exception. //double OverInt = (double)UInt32.MaxValue + 1; //UInt32.Parse(OverInt.ToString()); UInt32.Parse("4294967296"); Assert.Fail("Should raise a System.OverflowException"); } catch (Exception e) { Assert.IsTrue(typeof(OverflowException) == e.GetType(), "Did not get OverflowException type on '" + "4294967296" + "'. Instead, got: '" + e.GetType() + "'"); } //test Parse(string s, NumberStyles style) Assert.IsTrue(42 == UInt32.Parse(" " + NumberFormatInfo.CurrentInfo.CurrencySymbol + "42 ", NumberStyles.Currency)); try { UInt32.Parse("$42", NumberStyles.Integer); Assert.Fail("Should raise a System.FormatException"); } catch (Exception e) { Assert.IsTrue(typeof(FormatException) == e.GetType()); } //test Parse(string s, IFormatProvider provider) Assert.IsTrue(42 == UInt32.Parse(" 42 ", Nfi)); try { UInt32.Parse("%42", Nfi); Assert.Fail("Should raise a System.FormatException"); } catch (Exception e) { Assert.IsTrue(typeof(FormatException) == e.GetType()); } //test Parse(string s, NumberStyles style, IFormatProvider provider) Assert.IsTrue(16 == UInt32.Parse(" 10 ", NumberStyles.HexNumber, Nfi)); try { UInt32.Parse("$42", NumberStyles.Integer, Nfi); Assert.Fail("Should raise a System.FormatException"); } catch (FormatException e) { } try { UInt32.Parse("5", NumberStyles.Any, CultureInfo.InvariantCulture); Assert.Fail("C#42"); } catch (FormatException) { } // Pass a DateTimeFormatInfo, it is unable to format // numbers, but we should not crash UInt32.Parse("123", new DateTimeFormatInfo()); Assert.AreEqual(734561, UInt32.Parse("734561\0"), "C#43"); try { UInt32.Parse("734561\0\0\0 \0"); Assert.Fail("C#44"); } catch (FormatException) {} try { UInt32.Parse("734561\0\0\0 "); Assert.Fail("C#45"); } catch (FormatException) {} Assert.AreEqual(734561, UInt32.Parse("734561\0\0\0"), "C#46"); Assert.AreEqual(0, UInt32.Parse("0+", NumberStyles.Any), "#50"); }
public static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += AppDomain_CurrentDomain_UnhandledException; try { IniConfigSource confFile = new IniConfigSource(configFile); confFile.Reload(); IConfig serviceConfig = confFile.Configs["Service"]; serviceHostName = serviceConfig.GetString("service_host_name"); servicePort = serviceConfig.GetString("service_port"); IConfig osrmConfig = confFile.Configs["OsrmService"]; serverUrl = osrmConfig.GetString("server_url"); IConfig mysqlConfig = confFile.Configs["Mysql"]; mysqlServerHostName = mysqlConfig.GetString("mysql_server_host_name"); mysqlServerPort = mysqlConfig.GetString("mysql_server_port", "3306"); mysqlUser = mysqlConfig.GetString("mysql_user"); mysqlPassword = mysqlConfig.GetString("mysql_password"); mysqlDatabase = mysqlConfig.GetString("mysql_database"); } catch (Exception ex) { logger.Fatal(ex, "Ошибка чтения конфигурационного файла."); return; } logger.Info("Запуск службы правил доставки..."); try { var conStrBuilder = new MySqlConnectionStringBuilder(); conStrBuilder.Server = mysqlServerHostName; conStrBuilder.Port = UInt32.Parse(mysqlServerPort); conStrBuilder.Database = mysqlDatabase; conStrBuilder.UserID = mysqlUser; conStrBuilder.Password = mysqlPassword; conStrBuilder.SslMode = MySqlSslMode.None; QSMain.ConnectionString = conStrBuilder.GetConnectionString(true); var db_config = FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard .Dialect <NHibernate.Spatial.Dialect.MySQL57SpatialDialect>() .ConnectionString(QSMain.ConnectionString); OrmConfig.ConfigureOrm(db_config, new[] { System.Reflection.Assembly.GetAssembly(typeof(Vodovoz.HibernateMapping.OrganizationMap)), System.Reflection.Assembly.GetAssembly(typeof(Bank)), System.Reflection.Assembly.GetAssembly(typeof(QS.Project.Domain.UserBase)) }); OsrmMain.ServerUrl = serverUrl; IDeliveryRepository deliveryRepository = new DeliveryRepository(); var backupDistrictService = new BackupDistrictService(); DeliveryRulesInstanceProvider deliveryRulesInstanceProvider = new DeliveryRulesInstanceProvider(deliveryRepository, backupDistrictService); ServiceHost deliveryRulesHost = new DeliveryRulesServiceHost(deliveryRulesInstanceProvider); ServiceEndpoint webEndPoint = deliveryRulesHost.AddServiceEndpoint( typeof(IDeliveryRulesService), new WebHttpBinding(), $"http://{serviceHostName}:{servicePort}/DeliveryRules" ); WebHttpBehavior httpBehavior = new WebHttpBehavior(); webEndPoint.Behaviors.Add(httpBehavior); #if DEBUG deliveryRulesHost.Description.Behaviors.Add(new PreFilter()); #endif backupDistrictService.StartAutoUpdateTask(); deliveryRulesHost.Open(); logger.Info("Server started."); UnixSignal[] signals = { new UnixSignal(Signum.SIGINT), new UnixSignal(Signum.SIGHUP), new UnixSignal(Signum.SIGTERM) }; UnixSignal.WaitAny(signals); } catch (Exception e) { logger.Fatal(e); } finally { if (Environment.OSVersion.Platform == PlatformID.Unix) { Thread.CurrentThread.Abort(); } Environment.Exit(0); } }
public UInt32 ToUInt32() => UInt32.Parse(rawValue);
public static void SetPropertys(this Component component, PropertyObj[] propertys) { if (component != null && propertys.Length != 0) { for (int i = 0; i < propertys.Length; ++i) { PropertyObj property = propertys[i]; // do not modify compnent's name if (property.m_szValueName == "name") { continue; } Type t = Util.GetTypeByName(property.m_szTypeName); if (t == null) { Debug.LogWarningFormat("GetTypeByName({0}) is null", property.m_szTypeName); continue; } try { System.Object value = property.m_value; if (t.Equals(typeof(System.Single))) { value = Single.Parse(property.m_value.ToString()); } else if (t.Equals(typeof(System.UInt32))) { value = UInt32.Parse(property.m_value.ToString()); } else if (t.Equals(typeof(System.UInt64))) { value = UInt64.Parse(property.m_value.ToString()); } else if (t.Equals(typeof(System.UInt16))) { value = UInt16.Parse(property.m_value.ToString()); } ComponentExtension.SetValue(component, property.m_szValueName, value); // MethodInfo mi = typeof(ComponentExtension).GetMethod("SetValue").MakeGenericMethod(t); // System.Object[] parmas = null; // // if (t.Equals(typeof(System.Single))) { // parmas = new System.Object[] { component, property.m_szValueName, Single.Parse(property.m_value.ToString()) }; // } // else if (t.Equals(typeof(System.UInt32))) { // parmas = new System.Object[] { component, property.m_szValueName, UInt32.Parse(property.m_value.ToString()) }; // } // else if (t.Equals(typeof(System.UInt64))) { // parmas = new System.Object[] { component, property.m_szValueName, UInt64.Parse(property.m_value.ToString()) }; // } // else if (t.Equals(typeof(System.UInt16))) { // parmas = new System.Object[] { component, property.m_szValueName, UInt16.Parse(property.m_value.ToString()) }; // } // else { // parmas = new System.Object[] { component, property.m_szValueName, property.m_value }; // } // mi.Invoke(null, parmas); } catch (Exception ex) { Debug.LogException(ex); Debug.LogErrorFormat("Set Component:{0} property:{1} Failed, Type:{2}", component.name, property.m_szValueName, t.ToString()); //throw (new Exception(string.Format("Set Component:{0} property:{1} Failed, Type:{2}", component.name, property.szName, t.ToString()))); } } } }
private static HashSet <string> ParsePluginsXML(string platform, List <string> in_pluginFiles) { HashSet <string> newDlls = new HashSet <string>(); foreach (string pluginFile in in_pluginFiles) { if (!File.Exists(pluginFile)) { continue; } try { XmlDocument doc = new XmlDocument(); doc.Load(pluginFile); XPathNavigator Navigator = doc.CreateNavigator(); XPathNavigator pluginInfoNode = Navigator.SelectSingleNode("//PluginInfo"); string boolMotion = pluginInfoNode.GetAttribute("Motion", ""); XPathNodeIterator it = Navigator.Select("//Plugin"); if (boolMotion == "true") { newDlls.Add("AkMotion"); } foreach (XPathNavigator node in it) { uint pid = UInt32.Parse(node.GetAttribute("ID", "")); if (pid == 0) { continue; } string dll = string.Empty; if (platform == "Switch") { if (pid == (uint)PluginID.WwiseMeter) { dll = "AkMeter"; } } else if (builtInPluginIDs.Contains(pid)) { continue; } if (string.IsNullOrEmpty(dll)) { dll = node.GetAttribute("DLL", ""); } newDlls.Add(dll); } } catch (Exception ex) { Debug.LogError("Wwise: " + pluginFile + " could not be parsed. " + ex.Message); } } return(newDlls); }
private void cmdSave_Click(object sender, EventArgs e) { string serialText = txtSerial.Text; string accessText = txtAccessKey.Text; string emailText = txtEmail.Text; UInt32 nserial; try { nserial = UInt32.Parse(txtSerial.Text, NumberStyles.None); } catch { // Invalid serial. MessageBox.Show("Invalid Serial Number", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (accessText.Length != 8) { // Invalid access key MessageBox.Show("Invalid Access Key", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } int atIdx = emailText.IndexOf('@'); if (emailText.Length < 3 || atIdx == -1 || atIdx == 0 || atIdx == emailText.Length - 1 || emailText.Length > 64) { // Invalid Email address MessageBox.Show("Invalid E-Mail Address", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } /* Write the data back to the registry. */ RegistryKey k = Registry.CurrentUser.OpenSubKey("Software\\SonicTeam\\PSOV2", true); byte[] key = { 0x4a, 0x43, 0x0a, 0x13, 0x5e, 0x6f, 0x58, 0x5b, 0x46, 0x18, 0x25, 0x51, 0x60, 0x15, 0x7d, 0x64, 0x0b, 0x71, 0x0d, 0x1e, 0x7c, 0x27, 0x43, 0x7e, 0x10, 0x2c, 0x4f, 0x15, 0x31, 0x32, 0x04, 0x40, 0x51, 0x21, 0x4d, 0x63, 0x6b, 0x4a, 0x6e, 0x7e, 0x62, 0x56, 0x49, 0x16, 0x1c, 0x07, 0x1f, 0x01, 0x16, 0x03, 0x5c, 0x72, 0x0b, 0x06, 0x30, 0x0a, 0x72, 0x69, 0x46, 0x7b, 0x04, 0x0e, 0x6d, 0x48 }; string serialStr = nserial.ToString("X"); while (serialStr.Length < 8) { serialStr = "0" + serialStr; } byte[] cookedSerial = Encoding.ASCII.GetBytes(serialStr); byte[] cookedAccess = Encoding.ASCII.GetBytes(accessText); byte[] cookedEmail = Encoding.ASCII.GetBytes(emailText); byte[] serial = new byte[8], access = new byte[8], email = new byte[64]; int i; if (cookedSerial.Length != 8) { // Invalid serial MessageBox.Show("Invalid Serial Number", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (cookedAccess.Length != 8) { // Invalid access key MessageBox.Show("Invalid Access Key", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (cookedEmail.Length < 3 || cookedEmail.Length > 64) { // Invalid Email address MessageBox.Show("Invalid E-Mail Address", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } for (i = 0; i < 8; ++i) { if (cookedSerial[i] < 0x30 || cookedSerial[i] > 0x46 || (cookedSerial[i] > 0x39 && cookedSerial[i] < 0x41)) { MessageBox.Show("Invalid Serial Number", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } serial[i] = (byte)(cookedSerial[i] ^ key[i]); } for (i = 0; i < 8; ++i) { if (cookedAccess[i] < 0x30 || cookedAccess[i] > 0x7a || (cookedAccess[i] > 0x39 && cookedAccess[i] < 0x41) || (cookedAccess[i] > 0x5a && cookedAccess[i] < 0x61)) { MessageBox.Show("Invalid Access Key", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } access[i] = (byte)(cookedAccess[i] ^ key[i]); } for (i = 0; i < emailText.Length && i < 64; ++i) { email[i] = (byte)(cookedEmail[i] ^ key[i]); } /* Fail, Sega. */ for (; i < 64; ++i) { email[i] = key[i]; } k.SetValue("SERIAL", serial); k.SetValue("ACCESS", access); k.SetValue("E-MAIL", email); this.Close(); }
static WeaponProperties ParseWeapon(string str) { WeaponProperties prop = new WeaponProperties(); string[] cell = null; cell = str.Split(','); try { prop.gunType = (GunType)Int32.Parse(cell[(int)WeaponTableIndex.Type]); } catch { return(null); } //min atk try { prop.minAtkBonus = Int32.Parse(cell[(int)WeaponTableIndex.MinAtk]); } catch { return(null); } //max atk try { prop.maxAtkBonus = Int32.Parse(cell[(int)WeaponTableIndex.MaxAtk]); } catch { return(null); } //interval try { prop.atkInterval = float.Parse(cell[(int)WeaponTableIndex.Interval]); } catch { return(null); } //crtl chance try { prop.crtlChanceBonus = float.Parse(cell[(int)WeaponTableIndex.CrtlChance]) / 100.0f; } catch { prop.crtlChanceBonus = 0;; } //crtl rate try { prop.crtlRateBonus = float.Parse(cell[(int)WeaponTableIndex.CtrlRate]) / 100.0f; } catch { prop.crtlRateBonus = 0;; } //ammo try { prop.ammoCapacity = UInt32.Parse(cell[(int)WeaponTableIndex.AmmoCap]); } catch { return(null); } //RCR try { prop.rcrBonus = float.Parse(cell[(int)WeaponTableIndex.RCR]) / 100.0f; } catch { prop.rcrBonus = 0; } //recoil try { prop.recoil = float.Parse(cell[(int)WeaponTableIndex.Recoil]); } catch { prop.recoil = 0; } //beat back try { prop.beatBack = float.Parse(cell[(int)WeaponTableIndex.BeatBack]); } catch { prop.beatBack = 0; } return(prop); }
private static void ParsePrimitive(PropertyInfo prop, object entity, object value) { if (prop.PropertyType == typeof(string)) { prop.SetValue(entity, value.ToString().Trim(), null); } else if (prop.PropertyType == typeof(int) || prop.PropertyType == typeof(int?)) { if (value == null) { prop.SetValue(entity, null, null); } else { prop.SetValue(entity, int.Parse(value.ToString()), null); } } else if (prop.PropertyType == typeof(UInt32) || prop.PropertyType == typeof(UInt32?)) { if (value == null || value == DBNull.Value) { prop.SetValue(entity, null, null); } else { prop.SetValue(entity, UInt32.Parse(value.ToString()), null); } } else if (prop.PropertyType == typeof(DateTime) || prop.PropertyType == typeof(Nullable <DateTime>)) { DateTime date; bool isValid = DateTime.TryParse(value.ToString(), out date); if (isValid) { prop.SetValue(entity, date, null); } else { //Making an assumption here about the format of dates in the source data. isValid = DateTime.TryParseExact(value.ToString(), "yyyy-MM-dd", new CultureInfo("en-US"), DateTimeStyles.AssumeUniversal, out date); if (isValid) { prop.SetValue(entity, date, null); } } } else if (prop.PropertyType == typeof(decimal)) { prop.SetValue(entity, decimal.Parse(value.ToString()), null); } else if (prop.PropertyType == typeof(bool)) { prop.SetValue(entity, bool.Parse(value.ToString()), null); } else if (prop.PropertyType == typeof(double) || prop.PropertyType == typeof(double?)) { double number; bool isValid = double.TryParse(value.ToString(), out number); if (isValid) { prop.SetValue(entity, double.Parse(value.ToString()), null); } } }