Пример #1
0
 public static UInt16 ToUInt16(string s)
 {
     return(UInt16.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture));
 }
Пример #2
0
        public static UndertaleInstruction AssembleOne(string source, IList <UndertaleFunction> funcs, IList <UndertaleVariable> vars, IList <UndertaleString> strg, Dictionary <string, UndertaleVariable> localvars, out string label, UndertaleData data = null, Func <int, UndertaleInstruction.InstanceType?> lookOnStack = null)
        {
            label = null;
            string line = source;
            UndertaleInstruction instr = new UndertaleInstruction();

            string opcode = line;
            int    space  = opcode.IndexOf(' ');

            if (space >= 0)
            {
                opcode = line.Substring(0, space);
                line   = line.Substring(space + 1).Trim();
            }
            else
            {
                line = "";
            }
            string[] types = opcode.Split('.');
            if (types.Length > 3)
            {
                throw new Exception("Too many type parameters");
            }

            instr.Kind = (UndertaleInstruction.Opcode)Enum.Parse(typeof(UndertaleInstruction.Opcode), types[0], true);
            if (types.Length >= 2)
            {
                instr.Type1 = UndertaleInstructionUtil.FromOpcodeParam(types[1]);
            }
            if (types.Length >= 3)
            {
                instr.Type2 = UndertaleInstructionUtil.FromOpcodeParam(types[2]);
            }

            switch (UndertaleInstruction.GetInstructionType(instr.Kind))
            {
            case UndertaleInstruction.InstructionType.SingleTypeInstruction:
                if (instr.Kind == UndertaleInstruction.Opcode.Dup)
                {
                    instr.DupExtra = Byte.Parse(line);
                    line           = "";
                }
                break;

            case UndertaleInstruction.InstructionType.DoubleTypeInstruction:
                break;

            case UndertaleInstruction.InstructionType.ComparisonInstruction:
                instr.ComparisonKind = (UndertaleInstruction.ComparisonType)Enum.Parse(typeof(UndertaleInstruction.ComparisonType), line, true);
                line = "";
                break;

            case UndertaleInstruction.InstructionType.GotoInstruction:
                if (line[0] == '$')
                {
                    instr.JumpOffset = Int32.Parse(line.Substring(1));
                }
                else
                {
                    if (line == "[drop]")
                    {
                        instr.JumpOffsetPopenvExitMagic = true;
                    }
                    else
                    {
                        label = line;
                    }
                }
                line = "";
                break;

            case UndertaleInstruction.InstructionType.PopInstruction:
                if (instr.Type1 == UndertaleInstruction.DataType.Int16)
                {
                    // Special scenario - the swap instruction
                    // TODO: Figure out the proper syntax, see #129
                    instr.SwapExtra = Byte.Parse(line);
                }
                else
                {
                    UndertaleInstruction.InstanceType inst = instr.TypeInst;
                    instr.Destination = ParseVariableReference(line, vars, localvars, ref inst, instr, lookOnStack);
                    instr.TypeInst    = inst;
                }
                line = "";
                break;

            case UndertaleInstruction.InstructionType.PushInstruction:
                switch (instr.Type1)
                {
                case UndertaleInstruction.DataType.Double:
                    instr.Value = Double.Parse(line, CultureInfo.InvariantCulture);
                    break;

                case UndertaleInstruction.DataType.Float:
                    instr.Value = Single.Parse(line, CultureInfo.InvariantCulture);
                    break;

                case UndertaleInstruction.DataType.Int32:
                    int ival;
                    if (Int32.TryParse(line, out ival))
                    {
                        instr.Value = ival;
                    }
                    else
                    {
                        instr.Value = (int)ParseResourceName(line, data);
                    }
                    break;

                case UndertaleInstruction.DataType.Int64:
                    long lval;
                    if (Int64.TryParse(line, out lval))
                    {
                        instr.Value = lval;
                    }
                    else
                    {
                        instr.Value = (long)ParseResourceName(line, data);
                    }
                    break;

                case UndertaleInstruction.DataType.Boolean:
                    instr.Value = Boolean.Parse(line);
                    break;

                case UndertaleInstruction.DataType.Variable:
                    UndertaleInstruction.InstanceType inst2 = instr.TypeInst;
                    instr.Value    = ParseVariableReference(line, vars, localvars, ref inst2, instr, lookOnStack);
                    instr.TypeInst = inst2;
                    break;

                case UndertaleInstruction.DataType.String:
                    instr.Value = ParseStringReference(line, strg);
                    break;

                case UndertaleInstruction.DataType.Int16:
                    short sval;
                    if (Int16.TryParse(line, out sval))
                    {
                        instr.Value = sval;
                    }
                    else
                    {
                        instr.Value = (short)ParseResourceName(line, data);
                    }
                    break;
                }
                line = "";
                break;

            case UndertaleInstruction.InstructionType.CallInstruction:
                Match match = Regex.Match(line, @"^(.*)\(argc=(.*)\)$");
                if (!match.Success)
                {
                    throw new Exception("Call instruction format error");
                }

                UndertaleFunction func = funcs.ByName(match.Groups[1].Value);
                if (func == null)
                {
                    throw new Exception("Function not found: " + match.Groups[1].Value);
                }
                instr.Function = new UndertaleInstruction.Reference <UndertaleFunction>()
                {
                    Target = func
                };
                instr.ArgumentsCount = UInt16.Parse(match.Groups[2].Value);
                line = "";
                break;

            case UndertaleInstruction.InstructionType.BreakInstruction:
                instr.Value = Int16.Parse(line);
                line        = "";
                break;
            }
            if (line != "")
            {
                throw new Exception("Excess parameters");
            }
            return(instr);
        }
Пример #3
0
        public bool IPCOSD(string nvrip, string ipcip, string osd)
        {
            List <OSD> text = JsonConvert.DeserializeObject <List <OSD> >(osd).Take(8).ToList();
            NVRInfo    nvr  = NVRInfos.FirstOrDefault(o => o.Host.DVRIPAddress == nvrip);

            if (nvr == null)
            {
                ErrorMsg = "NVR不存在";
                _log.Error(ErrorMsg);
                return(false);
            }
            int userId = nvr.Host.LUserId;
            IPC ipc    = nvr.IPCs.FirstOrDefault(o => o.ChannelIp == ipcip);

            if (ipc == null)
            {
                ErrorMsg = "IPC不存在";
                _log.Error(ErrorMsg);
                return(false);
            }
            int    channel       = ipc.ChannelIndex;
            UInt32 dwReturn      = 0;
            Int32  nSize         = Marshal.SizeOf(m_struShowStrCfg);
            IntPtr ptrShowStrCfg = Marshal.AllocHGlobal(nSize);

            Marshal.StructureToPtr(m_struShowStrCfg, ptrShowStrCfg, true);

            _log.Debug(userId + "." + channel);
            if (!CHCNetSDK.NET_DVR_GetDVRConfig(userId, CHCNetSDK.NET_DVR_GET_SHOWSTRING_V30, channel, ptrShowStrCfg, (UInt32)nSize, ref dwReturn))
            {
                ErrorMsg = "获取设置信息失败" + CHCNetSDK.NET_DVR_GetLastError();
                _log.Error(ErrorMsg);
                Marshal.FreeHGlobal(ptrShowStrCfg);
                return(false);
            }
            else
            {
                m_struShowStrCfg = (CHCNetSDK.NET_DVR_SHOWSTRING_V30)Marshal.PtrToStructure(ptrShowStrCfg, typeof(CHCNetSDK.NET_DVR_SHOWSTRING_V30));
                Marshal.FreeHGlobal(ptrShowStrCfg);
            }
            int i = 0;

            foreach (OSD txt in text)
            {
                m_struShowStrCfg.struStringInfo[i].wShowString         = (ushort)(txt.Show == true ? 1 : 0);
                m_struShowStrCfg.struStringInfo[i].sString             = txt.Text;
                m_struShowStrCfg.struStringInfo[i].wStringSize         = (ushort)Encoding.UTF8.GetBytes(txt.Text).Length;
                m_struShowStrCfg.struStringInfo[i].wShowStringTopLeftX = UInt16.Parse(txt.X.ToString());
                m_struShowStrCfg.struStringInfo[i].wShowStringTopLeftY = UInt16.Parse(txt.Y.ToString());
                i++;
            }
            nSize         = Marshal.SizeOf(m_struShowStrCfg);
            ptrShowStrCfg = Marshal.AllocHGlobal(nSize);
            Marshal.StructureToPtr(m_struShowStrCfg, ptrShowStrCfg, true);
            if (!CHCNetSDK.NET_DVR_SetDVRConfig(userId, CHCNetSDK.NET_DVR_SET_SHOWSTRING_V30, channel, ptrShowStrCfg, (UInt32)nSize))
            {
                ErrorMsg = "设置信息失败" + CHCNetSDK.NET_DVR_GetLastError();
                _log.Error(ErrorMsg);
                Marshal.FreeHGlobal(ptrShowStrCfg);
                return(false);
            }
            else
            {
                Marshal.FreeHGlobal(ptrShowStrCfg);
                ErrorMsg = "";
                return(true);
            }
        }
Пример #4
0
 /// <summary>
 /// Convert the given value to a string using the given CultureInfo
 /// </summary>
 internal override object FromString(string value, CultureInfo culture)
 {
     return(UInt16.Parse(value, culture));
 }
Пример #5
0
 public void UpdateObject()
 {
     foreach (KeyValuePair <string, Control> kvp in _bindings)
     {
         if (!_fieldInfo.ContainsKey(kvp.Key))
         {
             throw new Exception("Invalid binding key");
         }
         else
         {
             try {
                 FieldInfoWrapper field  = _fieldInfo[kvp.Key];
                 eNumberFormat    format = _fieldFormat[kvp.Key];
                 if (kvp.Value is TextBox)
                 {
                     object       value       = kvp.Value.Text;
                     NumberStyles numberStyle = format == eNumberFormat.Decimal ? NumberStyles.Integer : NumberStyles.HexNumber;
                     if (field.FieldType != typeof(string))
                     {
                         value = ((string)value).Trim().Replace("$", "").Replace("0x", "");
                         if (string.IsNullOrWhiteSpace((string)value))
                         {
                             value = "0";
                         }
                     }
                     if (field.FieldType == typeof(UInt32))
                     {
                         value = (object)UInt32.Parse((string)value, numberStyle);
                     }
                     else if (field.FieldType == typeof(Int32))
                     {
                         value = (object)Int32.Parse((string)value, numberStyle);
                     }
                     else if (field.FieldType == typeof(Byte))
                     {
                         value = (object)Byte.Parse((string)value, numberStyle);
                     }
                     else if (field.FieldType == typeof(UInt16))
                     {
                         value = (object)UInt16.Parse((string)value, numberStyle);
                     }
                     else if (field.FieldType == typeof(UInt64))
                     {
                         value = (object)UInt64.Parse((string)value, numberStyle);
                     }
                     else if (field.FieldType == typeof(Int64))
                     {
                         value = (object)Int64.Parse((string)value, numberStyle);
                     }
                     field.SetValue(Entity, value);
                 }
                 else if (kvp.Value is ctrlPathSelection)
                 {
                     field.SetValue(Entity, ((ctrlPathSelection)kvp.Value).Text);
                 }
                 else if (kvp.Value is CheckBox)
                 {
                     if (field.FieldType == typeof(bool))
                     {
                         field.SetValue(Entity, ((CheckBox)kvp.Value).Checked);
                     }
                     else if (field.FieldType == typeof(byte))
                     {
                         field.SetValue(Entity, ((CheckBox)kvp.Value).Checked ? (byte)1 : (byte)0);
                     }
                 }
                 else if (kvp.Value is ctrlRiskyOption)
                 {
                     if (field.FieldType == typeof(bool))
                     {
                         field.SetValue(Entity, ((ctrlRiskyOption)kvp.Value).Checked);
                     }
                     else if (field.FieldType == typeof(byte))
                     {
                         field.SetValue(Entity, ((ctrlRiskyOption)kvp.Value).Checked ? (byte)1 : (byte)0);
                     }
                 }
                 else if (kvp.Value is RadioButton)
                 {
                     field.SetValue(Entity, ((RadioButton)kvp.Value).Checked);
                 }
                 else if (kvp.Value is Panel)
                 {
                     field.SetValue(Entity, kvp.Value.Controls.OfType <RadioButton>().FirstOrDefault(r => r.Checked).Tag);
                 }
                 else if (kvp.Value is ctrlTrackbar)
                 {
                     if (field.FieldType == typeof(Int32))
                     {
                         field.SetValue(Entity, (Int32)((ctrlTrackbar)kvp.Value).Value);
                     }
                     else
                     {
                         field.SetValue(Entity, (UInt32)((ctrlTrackbar)kvp.Value).Value);
                     }
                 }
                 else if (kvp.Value is ctrlHorizontalTrackbar)
                 {
                     field.SetValue(Entity, (Int32)((ctrlHorizontalTrackbar)kvp.Value).Value);
                 }
                 else if (kvp.Value is TrackBar)
                 {
                     if (field.FieldType == typeof(Int32))
                     {
                         field.SetValue(Entity, ((TrackBar)kvp.Value).Value);
                     }
                     else
                     {
                         field.SetValue(Entity, (UInt32)((TrackBar)kvp.Value).Value);
                     }
                 }
                 else if (kvp.Value is MesenNumericUpDown)
                 {
                     if (field.FieldType == typeof(UInt32))
                     {
                         field.SetValue(Entity, (UInt32)((MesenNumericUpDown)kvp.Value).Value);
                     }
                     else if (field.FieldType == typeof(Int32))
                     {
                         field.SetValue(Entity, (Int32)((MesenNumericUpDown)kvp.Value).Value);
                     }
                     else
                     {
                         field.SetValue(Entity, (double)((MesenNumericUpDown)kvp.Value).Value);
                     }
                 }
                 else if (kvp.Value is ComboBox)
                 {
                     if (field.FieldType.IsSubclassOf(typeof(Enum)))
                     {
                         Enum enumValue = ((ComboBox)kvp.Value).GetEnumValue(field.FieldType);
                         if (enumValue != null)
                         {
                             field.SetValue(Entity, enumValue);
                         }
                     }
                     else if (field.FieldType == typeof(UInt32))
                     {
                         UInt32 numericValue;
                         string item = Regex.Replace(((ComboBox)kvp.Value).SelectedItem.ToString(), "[^0-9]", "");
                         if (UInt32.TryParse(item, out numericValue))
                         {
                             field.SetValue(Entity, numericValue);
                         }
                     }
                     else if (field.FieldType == typeof(string))
                     {
                         field.SetValue(Entity, ((ComboBox)kvp.Value).SelectedItem);
                     }
                 }
             } catch {
                 //Ignore exceptions caused by bad user input
             }
         }
     }
 }
Пример #6
0
        public bool ParseFaceValues()
        {
            Regex           rx        = new Regex(@"(\d+)");
            MatchCollection rxMatches = rx.Matches(FaceString);

            if (rxMatches.Count == 147)
            {
                for (int i = 0; i < 49; i++)
                {
                    FaceValue _faceValue = new FaceValue(UInt16.Parse(rxMatches[i].Value), UInt16.Parse(rxMatches[i + 49].Value), UInt16.Parse(rxMatches[i + 98].Value));
                    _originalFaceValues.Add(_faceValue);
                    _faceValues.Add(_faceValue);
                }
                return(true);
            }
            else
            {
                MessageBox.Show(String.Format("Unable to process face values for mercenary. Count mismatch - expected a total of 147 values. Got {0}.", rxMatches.Count), "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                return(false);
            }
        }
Пример #7
0
        bool INodeDeserializer.Deserialize(EventReader reader, Type expectedType, Func <EventReader, Type, object> nestedObjectDeserializer, out object value)
        {
            var scalar = reader.Allow <Scalar>();

            if (scalar == null)
            {
                value = null;
                return(false);
            }

            if (expectedType.IsEnum)
            {
                value = Enum.Parse(expectedType, scalar.Value);
            }
            else
            {
                TypeCode typeCode = Type.GetTypeCode(expectedType);
                switch (typeCode)
                {
                case TypeCode.Boolean:
                    value = bool.Parse(scalar.Value);
                    break;

                case TypeCode.Byte:
                    value = Byte.Parse(scalar.Value, numberFormat);
                    break;

                case TypeCode.Int16:
                    value = Int16.Parse(scalar.Value, numberFormat);
                    break;

                case TypeCode.Int32:
                    value = Int32.Parse(scalar.Value, numberFormat);
                    break;

                case TypeCode.Int64:
                    value = Int64.Parse(scalar.Value, numberFormat);
                    break;

                case TypeCode.SByte:
                    value = SByte.Parse(scalar.Value, numberFormat);
                    break;

                case TypeCode.UInt16:
                    value = UInt16.Parse(scalar.Value, numberFormat);
                    break;

                case TypeCode.UInt32:
                    value = UInt32.Parse(scalar.Value, numberFormat);
                    break;

                case TypeCode.UInt64:
                    value = UInt64.Parse(scalar.Value, numberFormat);
                    break;

                case TypeCode.Single:
                    value = Single.Parse(scalar.Value, numberFormat);
                    break;

                case TypeCode.Double:
                    value = Double.Parse(scalar.Value, numberFormat);
                    break;

                case TypeCode.Decimal:
                    value = Decimal.Parse(scalar.Value, numberFormat);
                    break;

                case TypeCode.String:
                    value = scalar.Value;
                    break;

                case TypeCode.Char:
                    value = scalar.Value[0];
                    break;

                case TypeCode.DateTime:
                    // TODO: This is probably incorrect. Use the correct regular expression.
                    value = DateTime.Parse(scalar.Value, CultureInfo.InvariantCulture);
                    break;

                default:
                    if (expectedType == typeof(object))
                    {
                        // Default to string
                        value = scalar.Value;
                    }
                    else
                    {
                        value = TypeConverter.ChangeType(scalar.Value, expectedType);
                    }
                    break;
                }
            }
            return(true);
        }
Пример #8
0
        public static IEnumerable <Instruction> PushConvertedValue(this ValueNode node, ILContext context,
                                                                   TypeReference targetTypeRef, TypeReference typeConverter, IEnumerable <Instruction> pushServiceProvider,
                                                                   bool boxValueTypes, bool unboxValueTypes)
        {
            var module = context.Body.Method.Module;
            var str    = (string)node.Value;
            //If the TypeConverter has a ProvideCompiledAttribute that can be resolved, shortcut this
            Type compiledConverterType;

            if (typeConverter?.GetCustomAttribute(module, ("Microsoft.Maui.Controls", "Microsoft.Maui.Controls.Xaml", "ProvideCompiledAttribute"))?.ConstructorArguments?.First().Value is string compiledConverterName && (compiledConverterType = Type.GetType(compiledConverterName)) != null)
            {
                var compiledConverter = Activator.CreateInstance(compiledConverterType);
                var converter         = typeof(ICompiledTypeConverter).GetMethods().FirstOrDefault(md => md.Name == "ConvertFromString");
                IEnumerable <Instruction> instructions;
                try
                {
                    instructions = (IEnumerable <Instruction>)converter.Invoke(compiledConverter, new object[] {
                        node.Value as string, context, node as BaseNode
                    });
                }
                catch (System.Reflection.TargetInvocationException tie) when(tie.InnerException is XamlParseException)
                {
                    throw tie.InnerException;
                }
                catch (System.Reflection.TargetInvocationException tie) when(tie.InnerException is BuildException)
                {
                    throw tie.InnerException;
                }
                foreach (var i in instructions)
                {
                    yield return(i);
                }
                if (targetTypeRef.IsValueType && boxValueTypes)
                {
                    yield return(Instruction.Create(OpCodes.Box, module.ImportReference(targetTypeRef)));
                }
                yield break;
            }

            //If there's a [TypeConverter], use it
            if (typeConverter != null)
            {
                var isExtendedConverter  = typeConverter.ImplementsInterface(module.ImportReference(("Microsoft.Maui.Controls", "Microsoft.Maui.Controls", "IExtendedTypeConverter")));
                var typeConverterCtorRef = module.ImportCtorReference(typeConverter, paramCount: 0);
                var convertFromInvariantStringDefinition = isExtendedConverter
                                        ? module.ImportReference(("Microsoft.Maui.Controls", "Microsoft.Maui.Controls", "IExtendedTypeConverter"))
                                                           .ResolveCached()
                                                           .Methods.FirstOrDefault(md => md.Name == "ConvertFromInvariantString" && md.Parameters.Count == 2)
                                        : typeConverter.ResolveCached()
                                                           .AllMethods()
                                                           .FirstOrDefault(md => md.methodDef.Name == "ConvertFromInvariantString" && md.methodDef.Parameters.Count == 1).methodDef;
                var convertFromInvariantStringReference = module.ImportReference(convertFromInvariantStringDefinition);

                yield return(Create(Newobj, typeConverterCtorRef));

                yield return(Create(Ldstr, node.Value as string));

                if (isExtendedConverter)
                {
                    foreach (var instruction in pushServiceProvider)
                    {
                        yield return(instruction);
                    }
                }

                yield return(Instruction.Create(OpCodes.Callvirt, convertFromInvariantStringReference));

                if (targetTypeRef.IsValueType && unboxValueTypes)
                {
                    yield return(Instruction.Create(OpCodes.Unbox_Any, module.ImportReference(targetTypeRef)));
                }

                //ConvertFrom returns an object, no need to Box
                yield break;
            }
            var             originalTypeRef = targetTypeRef;
            var             isNullable      = false;
            MethodReference nullableCtor    = null;

            if (targetTypeRef.ResolveCached().FullName == "System.Nullable`1")
            {
                var nullableTypeRef = targetTypeRef;
                targetTypeRef = ((GenericInstanceType)targetTypeRef).GenericArguments[0];
                isNullable    = true;
                nullableCtor  = originalTypeRef.GetMethods(md => md.IsConstructor && md.Parameters.Count == 1, module).Single().Item1;
                nullableCtor  = nullableCtor.ResolveGenericParameters(nullableTypeRef, module);
            }

            var implicitOperator = module.TypeSystem.String.GetImplicitOperatorTo(targetTypeRef, module);

            //Obvious Built-in conversions
            if (targetTypeRef.ResolveCached().BaseType != null && targetTypeRef.ResolveCached().BaseType.FullName == "System.Enum")
            {
                yield return(PushParsedEnum(targetTypeRef, str, node));
            }
            else if (targetTypeRef.FullName == "System.Char")
            {
                yield return(Instruction.Create(OpCodes.Ldc_I4, unchecked ((int)TryFormat(Char.Parse, node, str))));
            }
            else if (targetTypeRef.FullName == "System.SByte")
            {
                yield return(Instruction.Create(OpCodes.Ldc_I4, unchecked ((int)TryFormat(s => SByte.Parse(s, CultureInfo.InvariantCulture), node, str))));
            }
            else if (targetTypeRef.FullName == "System.Int16")
            {
                yield return(Instruction.Create(OpCodes.Ldc_I4, unchecked ((int)TryFormat(s => Int16.Parse(s, CultureInfo.InvariantCulture), node, str))));
            }
            else if (targetTypeRef.FullName == "System.Int32")
            {
                yield return(Instruction.Create(OpCodes.Ldc_I4, TryFormat(s => Int32.Parse(s, CultureInfo.InvariantCulture), node, str)));
            }
            else if (targetTypeRef.FullName == "System.Int64")
            {
                yield return(Instruction.Create(OpCodes.Ldc_I8, TryFormat(s => Int64.Parse(s, CultureInfo.InvariantCulture), node, str)));
            }
            else if (targetTypeRef.FullName == "System.Byte")
            {
                yield return(Instruction.Create(OpCodes.Ldc_I4, unchecked ((int)TryFormat(s => Byte.Parse(s, CultureInfo.InvariantCulture), node, str))));
            }
            else if (targetTypeRef.FullName == "System.UInt16")
            {
                yield return(Instruction.Create(OpCodes.Ldc_I4, unchecked ((int)TryFormat(s => UInt16.Parse(s, CultureInfo.InvariantCulture), node, str))));
            }
            else if (targetTypeRef.FullName == "System.UInt32")
            {
                yield return(Instruction.Create(OpCodes.Ldc_I4, unchecked ((int)TryFormat(s => UInt32.Parse(s, CultureInfo.InvariantCulture), node, str))));
            }
            else if (targetTypeRef.FullName == "System.UInt64")
            {
                yield return(Instruction.Create(OpCodes.Ldc_I8, unchecked ((long)TryFormat(s => UInt64.Parse(s, CultureInfo.InvariantCulture), node, str))));
            }
            else if (targetTypeRef.FullName == "System.Single")
            {
                yield return(Instruction.Create(OpCodes.Ldc_R4, TryFormat(s => Single.Parse(str, CultureInfo.InvariantCulture), node, str)));
            }
            else if (targetTypeRef.FullName == "System.Double")
            {
                yield return(Instruction.Create(OpCodes.Ldc_R8, TryFormat(s => Double.Parse(str, CultureInfo.InvariantCulture), node, str)));
            }
            else if (targetTypeRef.FullName == "System.Boolean")
            {
                if (TryFormat(Boolean.Parse, node, str))
                {
                    yield return(Instruction.Create(OpCodes.Ldc_I4_1));
                }
                else
                {
                    yield return(Instruction.Create(OpCodes.Ldc_I4_0));
                }
            }
            else if (targetTypeRef.FullName == "System.TimeSpan")
            {
                var ts    = TryFormat(s => TimeSpan.Parse(s, CultureInfo.InvariantCulture), node, str);
                var ticks = ts.Ticks;
                yield return(Instruction.Create(OpCodes.Ldc_I8, ticks));

                yield return(Instruction.Create(OpCodes.Newobj, module.ImportCtorReference(("mscorlib", "System", "TimeSpan"), parameterTypes: new[] { ("mscorlib", "System", "Int64") })));
Пример #9
0
        // TODO: Refactor
        public bool Load(string FilePath, string Version, List <String> Lines, MSGParser FOObj, Dictionary <String, ItemProtoCustomField> CustomFields)
        {
            ItemProto Prot = null;
            bool      CompatibilityMode = false;
            bool      DuplicateFound    = false;

            List <int> ProcessedPids = new List <int>();

            foreach (ItemProto LProt in _loadedProtos)
            {
                ProcessedPids.Add(LProt.ProtoId);
            }

            bool IsCar    = false; // Compatibility
            bool IsNoOpen = false; // Compatibility

            int j = Lines.Count;

            for (int i = 0; i < j; i++)// String Line in Lines)
            {
                String Line = Lines[i];
                if (Line == "[Proto]" || i == Lines.Count - 1)
                {
                    if (Prot != null)
                    {
                        if (FOObj != null)
                        {
                            Prot.Name        = FOObj.GetMSGValue(Prot.ProtoId * 100);
                            Prot.Description = FOObj.GetMSGValue(Prot.ProtoId * 100 + 1);
                        }
                        //Prot.FileName = Path.GetFileName(FilePath);
                        Prot.FileName = FilePath;
                        if (CompatibilityMode)
                        {
                            ConvertStuff(ref Prot, IsCar, IsNoOpen);
                            CompatibilityMode = false;
                        }
                        IsCar    = false;
                        IsNoOpen = false;

                        if (ProcessedPids.Contains(Prot.ProtoId))
                        {
                            DuplicateFound = true;
                            Utils.Log("An object with the ProtoId " + Prot.ProtoId + " was already loaded. Overwriting proto.");
                            for (ushort u = 0; u < _loadedProtos.Count; u++)
                            {
                                if (_loadedProtos[u].ProtoId == Prot.ProtoId)
                                {
                                    _loadedProtos[u] = Prot;
                                }
                            }
                        }
                        else
                        {
                            if (Prot.ProtoId != 0)
                            {
                                _loadedProtos.Add(Prot);
                            }
                        }

                        ProcessedPids.Add(Prot.ProtoId);
                    }
                    Prot = new ItemProto();
                    continue;
                }

                if (string.IsNullOrEmpty(Lines[i]) || (Lines[i].Length > 0 && Lines[i][0] == '#'))
                {
                    continue;
                }

                if (FOObj != null && Prot != null)
                {
                    Prot.Name        = FOObj.GetMSGValue(Prot.ProtoId * 100);
                    Prot.Description = FOObj.GetMSGValue(Prot.ProtoId * 100 + 1);
                }

                String[] Parts = Line.Split('=');
                if (Parts.Length != 2)
                {
                    continue;
                }
                _fieldName  = Parts[0].Trim();
                _fieldValue = Parts[1].TrimStart(' ', '\t');

                if (Prot == null)
                {
                    continue;
                }

                if (_fieldName == "Pid")
                {
                    Prot.ProtoId = ushort.Parse(_fieldValue); CompatibilityMode = true;
                }
                if (_fieldName == "MiscEx.IsCar")
                {
                    IsCar = true;
                }
                if (_fieldName == "Container.IsNoOpen")
                {
                    IsNoOpen = true;
                }

                if (Prot != null)
                {
                    ParseData(ref Prot, CompatibilityMode, true);
                }

                if (CustomFields == null)
                {
                    continue;
                }
                foreach (KeyValuePair <String, ItemProtoCustomField> kvp in CustomFields)
                {
                    if (_fieldName == kvp.Key || _fieldName.Replace('.', '_') == kvp.Key)
                    {
                        try
                        {
                            ItemProtoCustomField NewCustom = new ItemProtoCustomField(kvp.Key,
                                                                                      (Utils.DataType)
                                                                                      kvp.Value.Type);
                            if (NewCustom.Type == (Byte)Utils.DataType.BOOL)
                            {
                                NewCustom.Value = (_fieldValue == "1");
                            }
                            else if (NewCustom.Type == (Byte)Utils.DataType.SBYTE)
                            {
                                NewCustom.Value = SByte.Parse(_fieldValue);
                            }
                            else if (NewCustom.Type == (Byte)Utils.DataType.INT)
                            {
                                NewCustom.Value = Int32.Parse(_fieldValue);
                            }
                            else if (NewCustom.Type == (Byte)Utils.DataType.INT16)
                            {
                                NewCustom.Value = Int16.Parse(_fieldValue);
                            }
                            else if (NewCustom.Type == (Byte)Utils.DataType.UINT)
                            {
                                NewCustom.Value = UInt32.Parse(_fieldValue);
                            }
                            else if (NewCustom.Type == (Byte)Utils.DataType.UINT16)
                            {
                                NewCustom.Value = UInt16.Parse(_fieldValue);
                            }
                            Prot.CustomFields.Add(kvp.Key, NewCustom);
                        }
                        catch (OverflowException ex)
                        {
                            Utils.Log(ex.Message + " in ProtoId " + Prot.ProtoId + " ,field " + _fieldName +
                                      " value: " + _fieldValue);
                        }
                    }
                }
            }
            return(DuplicateFound);
        }
Пример #10
0
        public IBrush MakeBrush(Player player, CommandReader cmd)
        {
            if (player == null)
            {
                throw new ArgumentNullException("player");
            }
            if (cmd == null)
            {
                throw new ArgumentNullException("cmd");
            }

            List <Block> blocks              = new List <Block>();
            List <int>   blockRatios         = new List <int>();
            bool         scaleSpecified      = false,
                         turbulenceSpecified = false,
                         seedSpecified       = false;
            int scale      = 100,
                turbulence = 100;
            UInt16 seed    = CloudyBrush.NextSeed();

            while (true)
            {
                int    offset       = cmd.Offset;
                string rawNextParam = cmd.Next();
                if (rawNextParam == null)
                {
                    break;
                }

                if (rawNextParam.EndsWith("%"))
                {
                    string numPart = rawNextParam.Substring(0, rawNextParam.Length - 1);
                    int    tempScale;
                    if (!Int32.TryParse(numPart, out tempScale))
                    {
                        player.Message(
                            "Cloudy brush: To specify scale, write a number followed by a percentage (e.g. 100%).");
                        return(null);
                    }
                    if (scaleSpecified)
                    {
                        player.Message("Cloudy brush: Scale has been specified twice.");
                        return(null);
                    }
                    if (scale < 1 || tempScale > CloudyBrush.MaxScale)
                    {
                        player.Message("Cloudy brush: Invalid scale ({0}). Must be between 1 and {1}",
                                       scale,
                                       CloudyBrush.MaxScale);
                        return(null);
                    }
                    scale          = tempScale;
                    scaleSpecified = true;
                    continue;
                }
                else if (rawNextParam.EndsWith("T", StringComparison.OrdinalIgnoreCase))
                {
                    string numPart = rawNextParam.Substring(0, rawNextParam.Length - 1);
                    int    tempTurbulence;
                    if (Int32.TryParse(numPart, out tempTurbulence))
                    {
                        if (turbulenceSpecified)
                        {
                            player.Message("Cloudy brush: Turbulence has been specified twice.");
                            return(null);
                        }
                        if (turbulence < 1 || tempTurbulence > CloudyBrush.MaxTurbulence)
                        {
                            player.Message("Cloudy brush: Invalid turbulence ({0}). Must be between 1 and {1}",
                                           turbulence,
                                           CloudyBrush.MaxTurbulence);
                            return(null);
                        }
                        turbulence          = tempTurbulence;
                        turbulenceSpecified = true;
                        continue;
                    }
                }
                else if (rawNextParam.EndsWith("S", StringComparison.OrdinalIgnoreCase))
                {
                    string numPart = rawNextParam.Substring(0, rawNextParam.Length - 1);
                    try {
                        seed = UInt16.Parse(numPart, NumberStyles.HexNumber);
                        if (seedSpecified)
                        {
                            player.Message("Cloudy brush: Seed has been specified twice.");
                            return(null);
                        }
                        seedSpecified = true;
                        continue;
                    } catch {
                        seed = CloudyBrush.NextSeed();
                    }
                }

                cmd.Offset = offset;
                int   ratio;
                Block block;
                if (!cmd.NextBlockWithParam(player, true, out block, out ratio))
                {
                    return(null);
                }
                if (ratio < 1 || ratio > CloudyBrush.MaxRatio)
                {
                    player.Message("{0} brush: Invalid block ratio ({1}). Must be between 1 and {2}.",
                                   Name, ratio, CloudyBrush.MaxRatio);
                    return(null);
                }
                blocks.Add(block);
                blockRatios.Add(ratio);
            }

            CloudyBrush madeBrush;

            switch (blocks.Count)
            {
            case 0:
                player.Message("{0} brush: Please specify at least one block type.", Name);
                return(null);

            case 1:
                madeBrush = new CloudyBrush(blocks[0], blockRatios[0]);
                break;

            default:
                madeBrush = new CloudyBrush(blocks.ToArray(), blockRatios.ToArray());
                break;
            }

            madeBrush.Frequency  /= (scale / 100f);
            madeBrush.Turbulence *= (turbulence / 100f);
            madeBrush.Seed        = seed;

            return(madeBrush);
        }
        private UInt16 ObterSerie()
        {
            string parte = Chave.Substring(22, 3);

            return(UInt16.Parse(parte));
        }
Пример #12
0
        /// <summary>Initializes the extension</summary>
        /// <param name="parameters">Initialization parameters: This class expects following parameters:
        /// <list type="table"><listheader><term>Parameter</term><description>Description</description></listheader>
        /// <item><term><c>PropertyName</c></term><description>Name of property to add attribute to. Required.</description></item>
        /// <item><term><c>TypeName</c></term><description>Name of type property <c>PropertyName</c> is property of. Required.</description></item>
        /// <item><term><c>Name</c></term><description>Name of the attribute</description></item>
        /// <item><term><c>p-&lt;number></c></term><description>Positional attribute constructor parameter. Optional. See remarks.</description></item>
        /// <item><term><c>p-&lt;string></c></term><description>Named attribute parameter. Optional. See remarks.</description></item>
        /// </list></param>
        /// <remarks>
        /// Positional and named parameters of constructor have name in form p-&lt;number or name> and value in form "&lt;TypeName> &lt;value>".
        /// TypeName can be one of supported attribute parameter types (<see cref="String"/>, <see cref="Byte"/>, <see cref="SByte"/>, <see cref="Int16"/>, <see cref="UInt16"/>, <see cref="Int32"/>, <see cref="UInt32"/>, <see cref="Int64"/>, <see cref="UInt64"/>, <see cref="Decimnal"/>, <see cref="Single"/>, <see cref="Double"/>, <see cref="Boolean"/>, <see cref="DateTime"/>, <see cref="Char"/>, <see cref="Type"/>).
        /// If it is not one of them it's treated a name of enumeration type. For supported types value is parsed in invariant culture to that type using appropriate <c>Parse</c> method.
        /// With exception of <see cref="String"/> which is used directly and <see cref="Type"/> where value part is treated as type name.
        /// For enumerations value part is treated as name of enumeration memner of enumeration specified in type part.
        /// <para>
        /// Positional parameters are added as constuctor parameters in order of their position numbers. Missing position numbers are ignored. Skipped optional parameters are not supported.
        /// Named parameters are added at the end of parameters list as named parameters.
        /// </para></remarks>
        /// <exception cref="KeyNotFoundException">A required parameter is not present in the <paramref name="parameters"/> dictionary.</exception>
        /// <exception cref="FormatException">Value of numeric type cannot be parsed.</exception>
        /// <exception cref="OverflowException">Value of numeric type is out of range of given numberic type.</exception>
        public void Initialize(System.Collections.Generic.IDictionary <string, string> parameters)
        {
            propertyName  = parameters["PropertyName"];
            typeName      = parameters["TypeName"];
            attributeName = parameters["Name"];
            //Params in arguments name p-Name or p-Number
            //Content typename-space-value (typename cannot contain space)
            List <CodeAttributeArgument>            namedParams = new List <CodeAttributeArgument>();
            Dictionary <int, CodeAttributeArgument> posParams   = new Dictionary <int, CodeAttributeArgument>();

            foreach (var item in parameters)
            {
                if (item.Key.StartsWith("p-"))
                {
                    string         pName = item.Key.Substring(2);
                    CodeExpression pValue;
                    int            pnum;
                    string         TypeName  = item.Value.Substring(0, item.Value.IndexOf(' '));
                    string         valuePart = item.Value.Substring(item.Value.IndexOf(' ') + 1);
                    switch (TypeName)
                    {
                    case "System.String": pValue = new CodePrimitiveExpression(valuePart); break;

                    case "System.Byte": pValue = new CodePrimitiveExpression(byte.Parse(valuePart, System.Globalization.CultureInfo.InvariantCulture)); break;

                    case "System.SByte": pValue = new CodePrimitiveExpression(SByte.Parse(valuePart, System.Globalization.CultureInfo.InvariantCulture)); break;

                    case "System.Int16": pValue = new CodePrimitiveExpression(Int16.Parse(valuePart, System.Globalization.CultureInfo.InvariantCulture)); break;

                    case "System.UInt16": pValue = new CodePrimitiveExpression(UInt16.Parse(valuePart, System.Globalization.CultureInfo.InvariantCulture)); break;

                    case "System.Int32": pValue = new CodePrimitiveExpression(Int32.Parse(valuePart, System.Globalization.CultureInfo.InvariantCulture)); break;

                    case "System.UInt32": pValue = new CodePrimitiveExpression(UInt32.Parse(valuePart, System.Globalization.CultureInfo.InvariantCulture)); break;

                    case "System.Int64": pValue = new CodePrimitiveExpression(Int64.Parse(valuePart, System.Globalization.CultureInfo.InvariantCulture)); break;

                    case "System.UInt64": pValue = new CodePrimitiveExpression(UInt64.Parse(valuePart, System.Globalization.CultureInfo.InvariantCulture)); break;

                    case "System.Decimal": pValue = new CodePrimitiveExpression(Decimal.Parse(valuePart, System.Globalization.CultureInfo.InvariantCulture)); break;

                    case "System.Single": pValue = new CodePrimitiveExpression(Single.Parse(valuePart, System.Globalization.CultureInfo.InvariantCulture)); break;

                    case "System.Double": pValue = new CodePrimitiveExpression(Double.Parse(valuePart, System.Globalization.CultureInfo.InvariantCulture)); break;

                    case "System.Boolean": pValue = new CodePrimitiveExpression(bool.Parse(valuePart)); break;

                    case "System.DateTime": pValue = new CodePrimitiveExpression((DateTime) new XAttribute("x", valuePart)); break;

                    case "System.Char": pValue = new CodePrimitiveExpression(valuePart[0]); break;

                    case "System.Type": pValue = new CodeTypeOfExpression(valuePart); break;

                    default:    //Enum
                        pValue = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(TypeName), valuePart); break;
                    }

                    if (int.TryParse(pName, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out pnum))
                    {
                        posParams.Add(pnum, new CodeAttributeArgument(pValue));
                    }
                    else
                    {
                        namedParams.Add(new CodeAttributeArgument(pName, pValue));
                    }
                }
            }
            attrParams.AddRange(from itm in posParams orderby itm.Key select itm.Value);
            attrParams.AddRange(namedParams);
        }
Пример #13
0
 protected void cmdAddNode_Click(object sender, EventArgs e)
 {
     using (BladeDirectorServices services = new BladeDirectorServices(getCurrentServerURL(this)))
     {
         services.svc.addNode(txtNewNodeIP.Text, txtNewISCSI.Text, txtNewIloIP.Text, UInt16.Parse(txtNewPort.Text), "TODO.the.key.here", "name of " + txtNewNodeIP.Text);
     }
     Response.Redirect(Request.RawUrl);
 }
Пример #14
0
        public virtual object ConvertStringToValue(string parameter, Type parameterType)
        {
            if (parameterType == null)
            {
                throw new ArgumentNullException("parameterType");
            }

            if (!CanConvert(parameterType))
            {
                throw new NotSupportedException(String.Format("Conversion from the argument parameterType '{0}' is not supported", parameterType));
            }

            if (parameterType.IsEnum)
            {
                return(Enum.Parse(parameterType, parameter, true));
            }

            switch (Type.GetTypeCode(parameterType))
            {
            case TypeCode.String:
                return(parameter);

            case TypeCode.Char:
                return(parameter != null?Char.Parse(parameter) : default(char));

            case TypeCode.SByte:
                return(parameter != null?SByte.Parse(parameter, CultureInfo.InvariantCulture) : default(sbyte));

            case TypeCode.Byte:
                return(parameter != null?Byte.Parse(parameter, CultureInfo.InvariantCulture) : default(byte));

            case TypeCode.Int16:
                return(parameter != null?Int16.Parse(parameter, CultureInfo.InvariantCulture) : default(short));

            case TypeCode.Int32:
                return(parameter != null?Int32.Parse(parameter, CultureInfo.InvariantCulture) : default(int));

            case TypeCode.Int64:
                return(parameter != null?Int64.Parse(parameter, CultureInfo.InvariantCulture) : default(long));

            case TypeCode.UInt16:
                return(parameter != null?UInt16.Parse(parameter, CultureInfo.InvariantCulture) : default(ushort));

            case TypeCode.UInt32:
                return(parameter != null?UInt32.Parse(parameter, CultureInfo.InvariantCulture) : default(uint));

            case TypeCode.UInt64:
                return(parameter != null?UInt64.Parse(parameter, CultureInfo.InvariantCulture) : default(ulong));

            case TypeCode.DateTime:
                return(parameter != null?DateTime.Parse(parameter, CultureInfo.InvariantCulture) : default(DateTime));

            case TypeCode.Boolean:
                return(parameter != null?Boolean.Parse(parameter) : default(bool));

            case TypeCode.Single:
                return(parameter != null?Single.Parse(parameter, CultureInfo.InvariantCulture) : default(float));

            case TypeCode.Double:
                return(parameter != null?Double.Parse(parameter, CultureInfo.InvariantCulture) : default(double));

            case TypeCode.Decimal:
                return(parameter != null?Decimal.Parse(parameter, CultureInfo.InvariantCulture) : default(decimal));

            case TypeCode.Object:
                if (parameterType == typeof(TimeSpan))
                {
                    return(TimeSpan.Parse(parameter));
                }
                if (parameterType == typeof(DateTimeOffset))
                {
                    return(DateTimeOffset.Parse(parameter, CultureInfo.InvariantCulture));
                }
                if (parameterType == typeof(Guid))
                {
                    return(new Guid(parameter));
                }
                break;
            }
            throw new NotSupportedException(String.Format("Cannot convert parameter string '{0}' to parameter type '{1}'", parameter, parameterType));
        }
 protected override object ParseString(string from)
 {
     return(UInt16.Parse(StringHelper.RemoveBlanks(from), NumberStyles.Number, mCulture));
 }
Пример #16
0
 public override object FromStringValue(string xml)
 {
     return(UInt16.Parse(xml));
 }
Пример #17
0
        private void RunMission(bool queuedMission = false)
        {
            StartMission.Enabled   = false;
            client.Device          = RBiOS.Checked ? "iPhone9,3" : "XT890";
            client.OperatingSystem = RBiOS.Checked ? "ios10.2.1" : RBAndroid.Checked ? "android4.4.2" : "amazon";
            client.Login();
            //if (Verbose)
            client.UpdateCurrentParty();
            var mission = missionSelect.SelectedItem as Mission;

            //client.DoMission(mission, CBFriends.Checked, null, null, null, CBTrophies.Checked, CBChallenge.Checked, CBLoot.Checked, CBUnits.Checked, CBExplore.Checked, LBLevel.Text, 3000);
            RunMissionCount = 0;
            var TotalErrors = 0;
            var runTotal    = RepeatMission.Text.Replace(" ", "") ?? "1";

            while (RunMissionCount < Int32.Parse(runTotal) && TotalErrors < 3)
            {
                if (queuedMission && QueuedMissions.Count > 0)
                {
                    mission = QueuedMissions.FirstOrDefault();
                    QueuedMissions.Remove(mission);
                    queuedMissions.Items.RemoveAt(queuedMissions.Items.IndexOf(mission.Name));
                }
                try
                {
                    var iterationInfo = $"Doing run ... {mission.Name} {(++RunMissionCount).ToString()}/{runTotal} With party: {client.MyCurrentParty.CurrentPartyNames}";
                    Logger.Out(iterationInfo);
                    var missionResult = client.DoMission(mission, CBFriends.Checked, null, null, null, CBTrophies.Checked, CBChallenge.Checked, CBLoot.Checked, CBUnits.Checked, CBExplore.Checked, LBLevel.Text, 1500);

                    client.ArenaOrbs = UInt16.Parse(missionResult[GameObject.UserTeamInfo][0][Variable.ColosseumOrb].ToString());
                    client.RaidOrbs  = UInt16.Parse(missionResult[GameObject.UserTeamInfo][0][Variable.RaidOrb].ToString());
                    var currentEnergy = Int32.Parse(missionResult[GameObject.UserTeamInfo][0][Variable.Energy].ToString());

                    Thread.Sleep(1500);
                    if (StopForArena && client.ArenaOrbs > 0)// && (RunMissionCount % 20 == 0))
                    {
                        client.ClearArena();
                    }
                    if (StopForRaid && client.RaidOrbs > 0)//&& (RunMissionCount % 20 == 0))
                    {
                        client.ClearRaid(raidMissionSelect.SelectedItem as Mission, RaidParty);
                    }

                    if (Verbose && RunMissionCount % 10 == 0)
                    {
                        client.UpdateCurrentParty(missionResult);

                        client.MyCurrentParty.MyPartyUnits.ForEach(x =>
                        {
                            if (x.TMR == 100 || (x.TMR > 0 && x.TMR > x.LastTMR))
                            {
                                Logger.Out(x.Name + " Gained " + (x.TMR - x.LastTMR) + " points.");
                            }
                        });
                    }

                    if (Verbose && currentEnergy > 195)
                    {
                        Logger.Out("Warning: Excess Energy " + client.TotalEnergy);
                    }

                    if (ChangeParty >= 0 && ChangeParty < 5 && client.MyCurrentParty.MyPartyId != ChangeParty)
                    {
                        client.SetParty(ChangeParty);
                    }

                    // Get fresh data every x runs
                    if (RunMissionCount > 1 && RunMissionCount % 100 == 0)
                    {
                        client.UpdateGetUserInfo();
                    }
                }
                catch (Exception ex)
                {
                    Logger.Out(ex.Message);
                    Console.WriteLine(ex.InnerException);
                    TotalErrors++;
                }
            }
            StartMission.Enabled = true;

            Logger.Out("Run Complete!");
        }
Пример #18
0
        /// <summary>
        /// Converts a string into a type specified.
        /// </summary>
        /// <param name="s"></param>
        /// <param name="type"></param>
        /// <param name="formatProvider"></param>
        /// <returns></returns>
        public static object Parse(string s, Type type, IFormatProvider formatProvider)
        {
            if (type == typeof(string))
            {
                return(s);
            }
            if (String.IsNullOrEmpty(s))
            {
                return(null);
            }

            switch (Type.GetTypeCode(type))
            {
            case TypeCode.Boolean:
                return(Boolean.Parse(s));

            case TypeCode.Char:
                return(Char.Parse(s));

            case TypeCode.SByte:
                return(SByte.Parse(s, formatProvider));

            case TypeCode.Byte:
                return(Byte.Parse(s, formatProvider));

            case TypeCode.Int16:
                return(Int16.Parse(s, formatProvider));

            case TypeCode.UInt16:
                return(UInt16.Parse(s, formatProvider));

            case TypeCode.Int32:
                return(Int32.Parse(s, formatProvider));

            case TypeCode.UInt32:
                return(UInt32.Parse(s, formatProvider));

            case TypeCode.Int64:
                return(Int64.Parse(s, formatProvider));

            case TypeCode.UInt64:
                return(UInt64.Parse(s, formatProvider));

            case TypeCode.Single:
                return(Single.Parse(s, formatProvider));

            case TypeCode.Double:
                return(Double.Parse(s, formatProvider));

            case TypeCode.Decimal:
                return(Decimal.Parse(s, formatProvider));

            case TypeCode.DateTime:
                return(DateTime.Parse(s, formatProvider));

            case TypeCode.String:
                return(s);
            }

            throw new NotSupportedException("Not supported type.");
        }
Пример #19
0
        private void buttonApply_Click(object sender, EventArgs e)
        {
            int x = (int)(numericUpDownX.Value - XStart);
            int y;

            if (mParam.GetDatamapDimension(mDatamapPosition) > 0)
            {
                y = (int)(numericUpDownY.Value - YStart);
            }
            else
            {
                y = 0;
            }
            mParam.SetDatamapValue(mDatamapPosition, (UInt16)(x / XSize), (UInt16)(y / YSize), UInt16.Parse(textBoxContent.Text));
        }
Пример #20
0
 public object ConvertBack(object Value, Type TargetType, object Parameter, CultureInfo Culture)
 {
     return((ushort)(50 / UInt16.Parse((string)Value)));
 }
Пример #21
0
 /// <summary>
 /// Convert the given value to a string using the given formatInfo
 /// </summary>
 internal override object FromString(string value, NumberFormatInfo formatInfo)
 {
     return(UInt16.Parse(value, NumberStyles.Integer, formatInfo));
 }
Пример #22
0
        private void setFieldValue()
        {
            int    moduleid    = (int)ReadDword();
            int    fielddef    = (int)ReadDword();
            IntPtr instanceptr = (IntPtr)ReadQword();
            string value       = ReadUTF8String();

            object   instance = null;
            GCHandle instanceGCH;

            try
            {
                instanceGCH = GCHandle.Alloc(null);

                if (instanceptr != IntPtr.Zero)
                {
                    Marshal.WriteIntPtr((IntPtr)instanceGCH, instanceptr);
                    instance = instanceGCH.Target;
                }


                if ((moduleid >= 0) && (moduleid < ModuleList.Count))
                {
                    Module m = ModuleList[moduleid];

                    FieldInfo mb = m.ResolveField(fielddef);
                    TypeCode  tc = Type.GetTypeCode(mb.FieldType);



                    switch (tc)
                    {
                    case TypeCode.Boolean:
                        mb.SetValue(instance, Boolean.Parse(value));
                        break;

                    case TypeCode.Char:
                        mb.SetValue(instance, Char.Parse(value));
                        break;

                    case TypeCode.SByte:
                        mb.SetValue(instance, SByte.Parse(value));
                        break;

                    case TypeCode.Byte:
                        mb.SetValue(instance, Byte.Parse(value));
                        break;

                    case TypeCode.Int16:
                        mb.SetValue(instance, Int16.Parse(value));
                        break;

                    case TypeCode.UInt16:
                        mb.SetValue(instance, UInt16.Parse(value));
                        break;

                    case TypeCode.Int32:
                        mb.SetValue(instance, Int32.Parse(value));
                        break;

                    case TypeCode.UInt32:
                        mb.SetValue(instance, UInt32.Parse(value));
                        break;

                    case TypeCode.Int64:
                        mb.SetValue(instance, Int32.Parse(value));
                        break;

                    case TypeCode.UInt64:
                        mb.SetValue(instance, UInt32.Parse(value));
                        break;

                    case TypeCode.Single:
                        mb.SetValue(instance, Single.Parse(value));
                        break;

                    case TypeCode.Double:
                        mb.SetValue(instance, Double.Parse(value));
                        break;

                    case TypeCode.Decimal:
                        mb.SetValue(instance, Decimal.Parse(value));
                        break;

                    case TypeCode.DateTime:
                        mb.SetValue(instance, DateTime.Parse(value));
                        break;

                    case TypeCode.String:
                        mb.SetValue(instance, value);
                        break;
                    }
                }

                if (instanceptr != IntPtr.Zero)
                {
                    instance    = null;
                    instanceGCH = GCHandle.FromIntPtr(IntPtr.Zero);
                    Marshal.WriteIntPtr((IntPtr)instanceGCH, IntPtr.Zero);
                    instanceGCH.Free();
                }
            }
            catch
            {
            }
        }
Пример #23
0
        protected override Boolean PatchFile(String fileName)
        {
            List <PatchResource> patchResources = new List <PatchResource>();

            foreach (PatchResourceSet set in _resourceSets)
            {
                if (EvaluatePatchResourceSet(set, fileName))
                {
                    // HACK: This just adds them together into a massive list. If the same name is mentioned it'll be overwritten several times
                    // fortunately it isnt' very expensive as only the last "final" one counts, but could do with filtering at this stage maybe?

                    patchResources.AddRange(set.Resources);
                }
                else
                {
                    Package.Log.Add(LogSeverity.Info, "Expression evaluation non-one: " + set.Condition.ExpressionString + ", did not process " + set.Resources.Count + " resources");
                }
            }

            if (patchResources.Count == 0)
            {
                Package.Log.Add(LogSeverity.Warning, "No resources to patch: " + fileName);
                return(false);
            }

            try {
                // for now, use lazy-load under all circumstances. In future analyse the Resources list to see if it's necessary or not
                // but the performance impact is minimal and it's the safest option, so keep it as it is
                using (ResourceSource source = ResourceSource.Open(fileName, false, ResourceSourceLoadMode.LazyLoadData)) {
                    List <String> tempFiles = new List <String>();

                    foreach (PatchResource res in patchResources)
                    {
                        if (res.Source.StartsWith("comp:", StringComparison.OrdinalIgnoreCase))
                        {
                            CompositedImage comp = new CompositedImage(res.Source, Package.RootDirectory);

                            DirectoryInfo packageTempDirectory = new DirectoryInfo(P.Combine(Package.RootDirectory.FullName, "Temp"));
                            if (!packageTempDirectory.Exists)
                            {
                                packageTempDirectory.Create();
                            }

                            // I think not using the *.bmp extension messes up Bitmap import
                            String tempFileName = PackageUtility.GetUnusedFileName(P.Combine(packageTempDirectory.FullName, P.GetFileName(Path) + res.Name) + ".bmp");

                            comp.Save(tempFileName, System.Drawing.Imaging.ImageFormat.Bmp);

                            res.File = tempFileName;
                            tempFiles.Add(tempFileName);
                        }
                        else
                        {
                            res.File = res.Source;
                        }

                        if (!File.Exists(res.File))
                        {
                            Package.Log.Add(LogSeverity.Error, "Data File not found: " + res.File);
                            continue;
                        }

                        ResourceTypeIdentifier typeId = ResourceTypeIdentifier.CreateFromString(res.Type, true);
                        ResourceIdentifier     nameId = ResourceIdentifier.CreateFromString(res.Name);
                        UInt16 langId = String.IsNullOrEmpty(res.Lang) ? UInt16.MaxValue : UInt16.Parse(res.Lang, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture);


                        if (langId == UInt16.MaxValue)                                // if the lang="" attribute was not specified

                        {
                            ResourceName name = source.GetName(typeId, nameId);

                            if (name == null)                              // if the specified name does not exist

                            {
                                if (res.Add)
                                {
                                    UInt16 sysLang = (UInt16)CultureInfo.InvariantCulture.LCID;

                                    ResourceData data = ResourceData.FromFileToAdd(res.File, sysLang, source);
                                    source.Add(typeId, nameId, sysLang, data);
                                }
                                else
                                {
                                    // Error

                                    String sourcePath = source.Name;

                                    Anolis.Core.Source.FileResourceSource frs = source as Anolis.Core.Source.FileResourceSource;
                                    if (frs != null)
                                    {
                                        sourcePath = frs.FileInfo.FullName;
                                    }

                                    Package.Log.Add(LogSeverity.Warning, "Resource name not found: " + sourcePath + '\\' + typeId.ToString() + '\\' + nameId.FriendlyName);
                                }
                            }
                            else
                            {
                                foreach (ResourceLang lang in name.Langs)
                                {
                                    ResourceData data = ResourceData.FromFileToUpdate(res.File, lang);
                                    lang.SwapData(data);
                                }
                            }
                        }
                        else                             // if the lang="" attribute was specified

                        {
                            ResourceLang lang = source.GetLang(typeId, nameId, langId);
                            if (lang == null)
                            {
                                ResourceData data = ResourceData.FromFileToAdd(res.File, langId, source);
                                source.Add(typeId, nameId, langId, data);
                            }
                            else
                            {
                                ResourceData data = ResourceData.FromFileToUpdate(res.File, lang);
                                lang.SwapData(data);
                            }
                        }
                    }                    //foreach

                    // note that Win32ResourceSource now recomptues the PE checksum by itself
                    source.CommitChanges();

                    foreach (String tempFile in tempFiles)
                    {
                        File.Delete(tempFile);
                    }

                    return(true);
                }                //using source
            } catch (AnolisException aex) {
                Package.Log.Add(LogSeverity.Error, "Patch Exception: " + aex.Message);

                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }

                throw;
            }
        }
Пример #24
0
        /// <summary>
        /// Set value
        /// </summary>
        /// <param name="_class"></param>
        public void SetVal(_ClassBind _class)
        {
            string classType = $"{_class.Namespace + (_class.Namespace == "" ? "" : ".")}{_class.Class}";
            IType  type      = Init.appdomain.LoadedTypes[classType];
            Type   t         = type.ReflectionType;//获取实际属性
            //这里获取适配器类型接口,不直接获取Mono适配器了,因为不同的类型适配器不一样
            var clrInstance = this.gameObject.GetComponents <CrossBindingAdaptorType>()
                              .Last(clr => clr.ILInstance.Type == type as ILType);

            //绑定数据
            if (_class.RequireBindFields)
            {
                _class.BoundData = false;
                var fields = _class.Fields.ToArray();

                foreach (_ClassField field in fields)
                {
                    object obj = new object();

                    try
                    {
                        if (field.fieldType == _ClassField.FieldType.Number)
                        {
                            var fieldType = t.GetField(field.fieldName,
                                                       BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance |
                                                       BindingFlags.Static).FieldType;
                            if (fieldType == null)
                            {
                                fieldType = t.GetProperty(field.fieldName,
                                                          BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance |
                                                          BindingFlags.Static).PropertyType;
                            }

                            if (fieldType.FullName == typeof(SByte).FullName)
                            {
                                obj = SByte.Parse(field.value);
                                _class.BoundData = true;
                            }
                            else if (fieldType.FullName == typeof(Byte).FullName)
                            {
                                obj = Byte.Parse(field.value);
                                _class.BoundData = true;
                            }
                            else if (fieldType.FullName == typeof(Int16).FullName)
                            {
                                obj = Int16.Parse(field.value);
                                _class.BoundData = true;
                            }
                            else if (fieldType.FullName == typeof(UInt16).FullName)
                            {
                                obj = UInt16.Parse(field.value);
                                _class.BoundData = true;
                            }
                            else if (fieldType.FullName == typeof(Int32).FullName)
                            {
                                obj = Int32.Parse(field.value);
                                _class.BoundData = true;
                            }
                            else if (fieldType.FullName == typeof(UInt32).FullName)
                            {
                                obj = UInt32.Parse(field.value);
                                _class.BoundData = true;
                            }
                            else if (fieldType.FullName == typeof(Int64).FullName)
                            {
                                obj = Int64.Parse(field.value);
                                _class.BoundData = true;
                            }
                            else if (fieldType.FullName == typeof(UInt64).FullName)
                            {
                                obj = UInt64.Parse(field.value);
                                _class.BoundData = true;
                            }
                            else if (fieldType.FullName == typeof(Single).FullName)
                            {
                                obj = Single.Parse(field.value);
                                _class.BoundData = true;
                            }
                            else if (fieldType.FullName == typeof(Decimal).FullName)
                            {
                                obj = Decimal.Parse(field.value);
                                _class.BoundData = true;
                            }
                            else if (fieldType.FullName == typeof(Double).FullName)
                            {
                                obj = Double.Parse(field.value);
                                _class.BoundData = true;
                            }
                        }

                        else if (field.fieldType == _ClassField.FieldType.String)
                        {
                            obj = field.value;
                            _class.BoundData = true;
                        }
                        else if (field.fieldType == _ClassField.FieldType.Bool)
                        {
                            field.value      = field.value.ToLower();
                            obj              = field.value == "true";
                            _class.BoundData = true;
                        }

                        if (field.fieldType == _ClassField.FieldType.GameObject)
                        {
                            GameObject go = field.gameObject;
                            if (go == null)
                            {
                                try
                                {
                                    go = field.value == "${this}"
                                        ? this.gameObject
                                        : GameObject.Find(field.value);
                                    if (go == null) //找父物体
                                    {
                                        go = FindSubGameObject(field);
                                        if (go == null) //如果父物体还不存在
                                        {
                                            continue;
                                        }
                                    }
                                }
                                catch (Exception ex) //找父物体(如果抛出空异常)
                                {
                                    go = FindSubGameObject(field);
                                    if (go == null) //如果父物体还不存在
                                    {
                                        continue;
                                    }
                                }
                            }

                            obj = go;
                            _class.BoundData = true;
                        }
                        else if (field.fieldType == _ClassField.FieldType.UnityComponent)
                        {
                            GameObject go = field.gameObject;
                            if (go == null)
                            {
                                try
                                {
                                    if (field.value.Contains("."))
                                    {
                                        field.value =
                                            field.value.Remove(field.value.IndexOf(".", StringComparison.Ordinal));
                                    }

                                    go = field.value == "${this}"
                                        ? this.gameObject
                                        : GameObject.Find(field.value);
                                    if (go == null) //找父物体
                                    {
                                        go = FindSubGameObject(field);
                                        if (go == null) //如果父物体还不存在
                                        {
                                            continue;
                                        }
                                    }
                                }
                                catch (Exception ex) //找父物体(如果抛出空异常)
                                {
                                    go = FindSubGameObject(field);
                                    if (go == null) //如果父物体还不存在
                                    {
                                        continue;
                                    }
                                }
                            }

                            var tp = t.GetField(field.fieldName,
                                                BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance |
                                                BindingFlags.Static);
                            if (tp != null)
                            {
                                string tName = tp.FieldType.Name;
                                if (tp.FieldType.Assembly.ToString().Contains("ILRuntime")) //如果在热更中
                                {
                                    var components = go.GetComponents <CrossBindingAdaptorType>();
                                    foreach (var c in components)
                                    {
                                        if (c.ILInstance.Type.Name == tName)
                                        {
                                            obj = c.ILInstance;
                                            _class.BoundData = true;
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    var component = go.GetComponents <Component>().ToList()
                                                    .Find(c => c.GetType().ToString().Contains(tName));
                                    if (component != null)
                                    {
                                        obj = component;
                                        _class.BoundData = true;
                                    }
                                }
                            }
                            else
                            {
                                var pi = t.GetProperty(field.fieldName,
                                                       BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance |
                                                       BindingFlags.Static);
                                if (pi != null)
                                {
                                    string tName = pi.PropertyType.Name;
                                    if (pi.PropertyType.Assembly.ToString().Contains("ILRuntime")) //如果在热更中
                                    {
                                        var components = go.GetComponents <CrossBindingAdaptorType>();
                                        foreach (var c in components)
                                        {
                                            if (c.ILInstance.Type.Name == tName)
                                            {
                                                obj = c.ILInstance;
                                                _class.BoundData = true;
                                                break;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        var component = go.GetComponents <Component>().ToList()
                                                        .Find(c => c.GetType().ToString().Contains(tName));
                                        if (component != null)
                                        {
                                            obj = component;
                                            _class.BoundData = true;
                                        }
                                    }
                                }
                                else
                                {
                                    Log.PrintError(
                                        $"自动绑定{this.name}出错:{classType}.{field.fieldName}赋值出错:{field.fieldName}不存在");
                                }
                            }
                        }
                        else if (field.fieldType == _ClassField.FieldType.HotUpdateResource)
                        {
                            obj = Assets.LoadAsset(field.value, typeof(UnityEngine.Object)).asset;
                            _class.BoundData = true;
                        }
                    }
                    catch (Exception except)
                    {
                        Log.PrintError(
                            $"自动绑定{this.name}出错:{classType}.{field.fieldName}获取值{field.value}出错:{except.Message},已跳过");
                    }

                    //如果有数据再绑定
                    if (_class.BoundData)
                    {
                        var fi = t.GetField(field.fieldName,
                                            BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance |
                                            BindingFlags.Static);
                        if (fi != null)
                        {
                            try
                            {
                                fi.SetValue(clrInstance.ILInstance, obj);
                            }
                            catch (Exception e)
                            {
                                Log.PrintError(
                                    $"自动绑定{this.name}出错:{classType}.{field.fieldName}赋值出错:{e.Message},已跳过");
                            }
                        }
                        else
                        {
                            //没FieldInfo尝试PropertyInfo
                            var pi = t.GetProperty(field.fieldName,
                                                   BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance |
                                                   BindingFlags.Static);
                            if (pi != null)
                            {
                                pi.SetValue(clrInstance.ILInstance, obj);
                            }
                            else
                            {
                                Log.PrintError($"自动绑定{this.name}出错:{classType}不存在{field.fieldName},已跳过");
                            }
                        }
                    }
                }
            }
        }
Пример #25
0
        private void save()
        {
            string OT_Name = TB_OTName.Text;

            //string RIV_Name = TB_Rival.Text;

            sav[TrainerCard + 0x04 + savshift] = (byte)(CB_Game.SelectedIndex + 0x18);
            sav[TrainerCard + 0x05 + savshift] = (byte)CB_Gender.SelectedIndex;

            uint TID   = Util.ToUInt32(MT_TID.Text);
            uint SID   = Util.ToUInt32(MT_SID.Text);
            uint money = Util.ToUInt32(MT_Money.Text);

            string saying1 = TB_Saying1.Text;
            string saying2 = TB_Saying2.Text;
            string saying3 = TB_Saying3.Text;
            string saying4 = TB_Saying4.Text;
            string saying5 = TB_Saying5.Text;

            uint _region   = Util.ToUInt32(CB_Region.SelectedValue.ToString());
            uint _country  = Util.ToUInt32(CB_Country.SelectedValue.ToString());
            uint _3dsreg   = Util.ToUInt32(CB_3DSReg.SelectedValue.ToString());
            uint _language = Util.ToUInt32(CB_Language.SelectedValue.ToString());

            Array.Copy(BitConverter.GetBytes(TID), 0, sav, TrainerCard + 0x0 + savshift, 2);
            Array.Copy(BitConverter.GetBytes(SID), 0, sav, TrainerCard + 0x2 + savshift, 2);
            Array.Copy(BitConverter.GetBytes(money), 0, sav, Trainer2 + 0x8 + savshift, 4);
            Array.Copy(BitConverter.GetBytes(_region), 0, sav, TrainerCard + 0x26 + savshift, 1);
            Array.Copy(BitConverter.GetBytes(_country), 0, sav, TrainerCard + 0x27 + savshift, 1);
            Array.Copy(BitConverter.GetBytes(_3dsreg), 0, sav, TrainerCard + 0x2C + savshift, 1);
            Array.Copy(BitConverter.GetBytes(_language), 0, sav, TrainerCard + 0x2D + savshift, 1);

            byte[] OT = Encoding.Unicode.GetBytes(OT_Name);
            Array.Resize(ref OT, 0x1A);
            Array.Copy(OT, 0, sav, TrainerCard + 0x48 + savshift, 0x1A);
            //byte[] Rival = Encoding.Unicode.GetBytes(RIV_Name);
            //Array.Resize(ref Rival, 0x1A);
            //Array.Copy(Rival, 0, sav, 0x9610 + savshift, 0x1A);

            byte[] s1 = Encoding.Unicode.GetBytes(saying1);
            Array.Resize(ref s1, 0x22);
            Array.Copy(s1, 0, sav, TrainerCard + 0x7C + savshift, 0x22);
            byte[] s2 = Encoding.Unicode.GetBytes(saying2);
            Array.Resize(ref s2, 0x22);
            Array.Copy(s2, 0, sav, TrainerCard + 0x9E + savshift, 0x22);
            byte[] s3 = Encoding.Unicode.GetBytes(saying3);
            Array.Resize(ref s3, 0x22);
            Array.Copy(s3, 0, sav, TrainerCard + 0xC0 + savshift, 0x22);
            byte[] s4 = Encoding.Unicode.GetBytes(saying4);
            Array.Resize(ref s4, 0x22);
            Array.Copy(s4, 0, sav, TrainerCard + 0xE2 + savshift, 0x22);
            byte[] s5 = Encoding.Unicode.GetBytes(saying5);
            Array.Resize(ref s5, 0x22);
            Array.Copy(s5, 0, sav, TrainerCard + 0x104 + savshift, 0x22);

            // New stuff.
            // Copy Maison Data in
            MaskedTextBox[] tba = new MaskedTextBox[] {
                TB_MCSN, TB_MCSS, TB_MBSN, TB_MBSS,
                TB_MCDN, TB_MCDS, TB_MBDN, TB_MBDS,
                TB_MCTN, TB_MCTS, TB_MBTN, TB_MBTS,
                TB_MCRN, TB_MCRS, TB_MBRN, TB_MBRS,
                TB_MCMN, TB_MCMS, TB_MBMN, TB_MBMS,
            };
            for (int i = 0; i < tba.Length; i++)
            {
                byte[] streak = BitConverter.GetBytes(Util.ToUInt32(tba[i].Text));
                Array.Resize(ref streak, 2);
                Array.Copy(streak, 0, sav, Maison + 2 * i + savshift, 2);
            }

            // Copy Position
            byte[] m = BitConverter.GetBytes(Int16.Parse(TB_CoordM.Text)); Array.Resize(ref m, 2); Array.Copy(m, 0, sav, savshift + Trainer1 + 0x02, 2);
            byte[] x = BitConverter.GetBytes(Single.Parse(TB_CoordX.Text)); Array.Resize(ref x, 4); Array.Copy(x, 0, sav, savshift + Trainer1 + 0x10, 4);
            byte[] z = BitConverter.GetBytes(Single.Parse(TB_CoordZ.Text)); Array.Resize(ref z, 4); Array.Copy(z, 0, sav, savshift + Trainer1 + 0x14, 4);
            byte[] y = BitConverter.GetBytes(Single.Parse(TB_CoordY.Text)); Array.Resize(ref y, 4); Array.Copy(y, 0, sav, savshift + Trainer1 + 0x18, 4);

            byte[] bp = BitConverter.GetBytes(Util.ToUInt32(TB_BP.Text)); Array.Resize(ref bp, 2); Array.Copy(bp, 0, sav, savshift + 0x963C - 0xC * Convert.ToInt16(m_parent.savegame_oras), 2);
            byte[] pm = BitConverter.GetBytes(Util.ToUInt32(TB_PM.Text)); Array.Resize(ref pm, 4); Array.Copy(pm, 0, sav, savshift + psssatoffset + 0xFC, 4); Array.Copy(pm, 0, sav, savshift + psssatoffset + 0x100, 4);
            sav[0x694D + savshift] = Byte.Parse(TB_Style.Text);

            // Copy Badges
            badgeval = 0;
            CheckBox[] cba = { cb1, cb2, cb3, cb4, cb5, cb6, cb7, cb8, };
            for (int i = 0; i < 8; i++)
            {
                badgeval |= (byte)(Convert.ToByte(cba[i].Checked) << i);
            }
            sav[0x960C + savshift] = badgeval;

            // Save PlayTime
            byte[] h = BitConverter.GetBytes(UInt16.Parse(MT_Hours.Text)); Array.Resize(ref h, 2); Array.Copy(h, 0, sav, savshift + 0x6C00, 2);
            sav[0x6C02 + savshift] = (byte)(UInt16.Parse(MT_Minutes.Text) % 60);
            sav[0x6C03 + savshift] = (byte)(UInt16.Parse(MT_Seconds.Text) % 60);

            // Sprite
            sav[TrainerCard + 0x07] = Byte.Parse(MT_Sprite.Text);

            sav[TrainerCard + 0x31] = (byte)(Byte.Parse(MT_HairColor.Text) + (Byte.Parse(MT_Hat.Text) << 3));

            sav[TrainerCard + 0x30 + savshift] = Byte.Parse(MT_14030.Text);
            //sav[TrainerCard + 0x31 + savshift] = Byte.Parse(MT_14031.Text);
            sav[TrainerCard + 0x32 + savshift] = Byte.Parse(MT_14032.Text);
            sav[TrainerCard + 0x33 + savshift] = Byte.Parse(MT_14033.Text);
            sav[TrainerCard + 0x34 + savshift] = Byte.Parse(MT_14034.Text);
            sav[TrainerCard + 0x35 + savshift] = Byte.Parse(MT_14035.Text);
            sav[TrainerCard + 0x36 + savshift] = Byte.Parse(MT_14036.Text);
            sav[TrainerCard + 0x37 + savshift] = Byte.Parse(MT_14037.Text);
            sav[TrainerCard + 0x38 + savshift] = Byte.Parse(MT_14038.Text);
            sav[TrainerCard + 0x39 + savshift] = Byte.Parse(MT_14039.Text);
            sav[TrainerCard + 0x3A + savshift] = Byte.Parse(MT_1403A.Text);
            sav[TrainerCard + 0x3B + savshift] = Byte.Parse(MT_1403B.Text);
            sav[TrainerCard + 0x3C + savshift] = Byte.Parse(MT_1403C.Text);
            sav[TrainerCard + 0x3D + savshift] = Byte.Parse(MT_1403D.Text);
            sav[TrainerCard + 0x3E + savshift] = Byte.Parse(MT_1403E.Text);
            sav[TrainerCard + 0x3F + savshift] = Byte.Parse(MT_1403F.Text);
        }
Пример #26
0
        static MacErrorList()
        {
            string name     = RFID_Explorer.Properties.Settings.Default.macErrorsFileName;
            string fileName = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), name);

            if (!File.Exists(fileName))
            {
                throw new Exception(String.Format("A critial configuration file ({0}) is missing.", fileName));
            }

            Dictionary <uint, MacError> errorList = new Dictionary <uint, MacError>();

            XmlReaderSettings settings = new XmlReaderSettings();

            settings.CheckCharacters              = true;
            settings.CloseInput                   = true;
            settings.ConformanceLevel             = ConformanceLevel.Document;
            settings.IgnoreComments               = true;
            settings.IgnoreProcessingInstructions = true;
            settings.IgnoreWhitespace             = true;


            try
            {
                //clark not sure. 2011.10.24. In 64-bit win7, the application will crash.
                FileStream tmpStream = File.OpenRead(fileName);

                using (XmlReader xmlReader = XmlReader.Create(tmpStream, settings))
                {
                    xmlReader.MoveToContent();

                    while (!xmlReader.IsStartElement())
                    {
                        xmlReader.Read();
                    }

                    if (xmlReader.Name != "MacErrors")
                    {
                        throw new Exception("The \"MacErrors\" element is missing.");
                    }

                    xmlReader.ReadToFollowing("error");
                    do
                    {
                        string id = xmlReader.GetAttribute("id");
                        if (id.StartsWith("0x"))
                        {
                            id = id.Substring(2);
                        }
                        UInt16 errorCode = UInt16.Parse(id, System.Globalization.NumberStyles.HexNumber);
                        string errorName = xmlReader.GetAttribute("name");
                        string errorDesc = xmlReader.ReadElementContentAsString();

                        errorList.Add(errorCode, new MacError(errorCode, errorName, errorDesc));
                    } while (xmlReader.IsStartElement("error"));
                }
            }
            catch (Exception ex)
            {
            }

            Errors = errorList;
        }
Пример #27
0
    public bool runTest()
    {
        Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer);
        int    iCountErrors    = 0;
        int    iCountTestcases = 0;
        String strLoc          = "Loc_000oo";
        String strValue        = String.Empty;

        try
        {
            UInt16 i16a, i16b, i16ret;
            strLoc = "Loc_09utg";
            i16a   = UInt16.Parse("0");
            i16b   = UInt16.Parse("0");
            i16ret = Math.Max(i16a, i16b);
            iCountTestcases++;
            if (i16ret != UInt16.Parse("0"))
            {
                iCountErrors++;
                printerr("Error_20xxu");
            }
            strLoc = "Loc_209uc";
            i16a   = UInt16.Parse("1");
            i16b   = UInt16.Parse("0");
            i16ret = Math.Max(i16a, i16b);
            iCountTestcases++;
            if (i16ret != UInt16.Parse("1"))
            {
                iCountErrors++;
                printerr("Error_230uc! Expected==0 , value==" + i16ret.ToString());
            }
            strLoc = "Loc_209cc";
            i16a   = UInt16.Parse("0");
            i16b   = UInt16.Parse("1");
            i16ret = Math.Max(i16a, i16b);
            iCountTestcases++;
            if (i16ret != UInt16.Parse("1"))
            {
                iCountErrors++;
                printerr("Error_948nc! Expected==1 , value==" + i16ret.ToString());
            }
            strLoc = "Loc_20uxw";
            i16a   = UInt16.MaxValue;
            i16b   = UInt16.MinValue;
            i16ret = Math.Max(i16a, i16b);
            iCountTestcases++;
            if (i16ret != UInt16.MaxValue)
            {
                iCountErrors++;
                printerr("Error_2908x! expected==" + UInt16.MaxValue.ToString() + " , value==" + i16ret.ToString());
            }
            strLoc = "Loc_6745x";
            i16a   = UInt16.Parse("10");
            i16b   = UInt16.Parse("9");
            i16ret = Math.Max(i16a, i16b);
            iCountTestcases++;
            if (i16ret != UInt16.Parse("10"))
            {
                iCountErrors++;
                printerr("Error_298xz! Expected==10 , value==" + i16ret.ToString());
            }
            strLoc = "Loc_298yx";
            i16a   = UInt16.Parse("9");
            i16b   = UInt16.Parse("10");
            i16ret = Math.Max(i16a, i16b);
            iCountTestcases++;
            if (i16ret != UInt16.Parse("10"))
            {
                iCountErrors++;
                printerr("Error_298di! Expeceted==10 , value==" + i16ret.ToString());
            }
            strLoc = "Loc_90uxf";
            i16a   = UInt16.MaxValue;
            i16b   = UInt16.MaxValue;
            i16ret = Math.Max(i16a, i16b);
            iCountTestcases++;
            if (i16ret != UInt16.MaxValue)
            {
                iCountErrors++;
                printerr("Error_298xq! Expected==" + UInt16.MaxValue.ToString() + " , value==" + i16ret.ToString());
            }
        } catch (Exception exc_general) {
            ++iCountErrors;
            Console.WriteLine(s_strTFAbbrev + " : Error Err_8888yyy!  strLoc==" + strLoc + ", exc_general==" + exc_general.ToString());
        }
        if (iCountErrors == 0)
        {
            Console.WriteLine("paSs. " + s_strTFName + " ,iCountTestcases==" + iCountTestcases.ToString());
            return(true);
        }
        else
        {
            Console.WriteLine("FAiL! " + s_strTFName + " ,iCountErrors==" + iCountErrors.ToString() + " , BugNums?: " + s_strActiveBugNums);
            return(false);
        }
    }
Пример #28
0
        public static IEnumerable <Instruction> PushConvertedValue(this ValueNode node, ILContext context,
                                                                   TypeReference targetTypeRef, TypeReference typeConverter, IEnumerable <Instruction> pushServiceProvider,
                                                                   bool boxValueTypes, bool unboxValueTypes)
        {
            var module = context.Body.Method.Module;
            var str    = (string)node.Value;

            //If the TypeConverter has a ProvideCompiledAttribute that can be resolved, shortcut this
            var  compiledConverterName = typeConverter?.GetCustomAttribute(module.Import(typeof(ProvideCompiledAttribute)))?.ConstructorArguments?.First().Value as string;
            Type compiledConverterType;

            if (compiledConverterName != null && (compiledConverterType = Type.GetType(compiledConverterName)) != null)
            {
                var compiledConverter = Activator.CreateInstance(compiledConverterType);
                var converter         = typeof(ICompiledTypeConverter).GetMethods().FirstOrDefault(md => md.Name == "ConvertFromString");
                var instructions      = (IEnumerable <Instruction>)converter.Invoke(compiledConverter, new object[] {
                    node.Value as string, context.Body.Method.Module, node as BaseNode
                });
                foreach (var i in instructions)
                {
                    yield return(i);
                }
                if (targetTypeRef.IsValueType && boxValueTypes)
                {
                    yield return(Instruction.Create(OpCodes.Box, module.Import(targetTypeRef)));
                }
                yield break;
            }

            //If there's a [TypeConverter], use it
            if (typeConverter != null)
            {
                var isExtendedConverter  = typeConverter.ImplementsInterface(module.Import(typeof(IExtendedTypeConverter)));
                var typeConverterCtor    = typeConverter.Resolve().Methods.Single(md => md.IsConstructor && md.Parameters.Count == 0);
                var typeConverterCtorRef = module.Import(typeConverterCtor);
                var convertFromInvariantStringDefinition = isExtendedConverter
                                        ? module.Import(typeof(IExtendedTypeConverter))
                                                           .Resolve()
                                                           .Methods.FirstOrDefault(md => md.Name == "ConvertFromInvariantString" && md.Parameters.Count == 2)
                                        : typeConverter.Resolve()
                                                           .AllMethods()
                                                           .FirstOrDefault(md => md.Name == "ConvertFromInvariantString" && md.Parameters.Count == 1);
                var convertFromInvariantStringReference = module.Import(convertFromInvariantStringDefinition);

                yield return(Instruction.Create(OpCodes.Newobj, typeConverterCtorRef));

                yield return(Instruction.Create(OpCodes.Ldstr, node.Value as string));

                if (isExtendedConverter)
                {
                    foreach (var instruction in pushServiceProvider)
                    {
                        yield return(instruction);
                    }
                }

                yield return(Instruction.Create(OpCodes.Callvirt, convertFromInvariantStringReference));

                if (targetTypeRef.IsValueType && unboxValueTypes)
                {
                    yield return(Instruction.Create(OpCodes.Unbox_Any, module.Import(targetTypeRef)));
                }

                //ConvertFrom returns an object, no need to Box
                yield break;
            }
            var             originalTypeRef = targetTypeRef;
            var             isNullable      = false;
            MethodReference nullableCtor    = null;

            if (targetTypeRef.Resolve().FullName == "System.Nullable`1")
            {
                var nullableTypeRef = targetTypeRef;
                targetTypeRef = ((GenericInstanceType)targetTypeRef).GenericArguments[0];
                isNullable    = true;
                nullableCtor  = originalTypeRef.GetMethods(md => md.IsConstructor && md.Parameters.Count == 1, module).Single().Item1;
                nullableCtor  = nullableCtor.ResolveGenericParameters(nullableTypeRef, module);
            }

            var implicitOperator = module.TypeSystem.String.GetImplicitOperatorTo(targetTypeRef, module);

            //Obvious Built-in conversions
            if (targetTypeRef.Resolve().BaseType != null && targetTypeRef.Resolve().BaseType.FullName == "System.Enum")
            {
                yield return(PushParsedEnum(targetTypeRef, str, node));
            }
            else if (targetTypeRef.FullName == "System.Char")
            {
                yield return(Instruction.Create(OpCodes.Ldc_I4, Char.Parse(str)));
            }
            else if (targetTypeRef.FullName == "System.SByte")
            {
                yield return(Instruction.Create(OpCodes.Ldc_I4, SByte.Parse(str, CultureInfo.InvariantCulture)));
            }
            else if (targetTypeRef.FullName == "System.Int16")
            {
                yield return(Instruction.Create(OpCodes.Ldc_I4, Int16.Parse(str, CultureInfo.InvariantCulture)));
            }
            else if (targetTypeRef.FullName == "System.Int32")
            {
                yield return(Instruction.Create(OpCodes.Ldc_I4, Int32.Parse(str, CultureInfo.InvariantCulture)));
            }
            else if (targetTypeRef.FullName == "System.Int64")
            {
                yield return(Instruction.Create(OpCodes.Ldc_I8, Int64.Parse(str, CultureInfo.InvariantCulture)));
            }
            else if (targetTypeRef.FullName == "System.Byte")
            {
                yield return(Instruction.Create(OpCodes.Ldc_I4, Byte.Parse(str, CultureInfo.InvariantCulture)));
            }
            else if (targetTypeRef.FullName == "System.UInt16")
            {
                yield return(Instruction.Create(OpCodes.Ldc_I4, UInt16.Parse(str, CultureInfo.InvariantCulture)));
            }
            else if (targetTypeRef.FullName == "System.UInt32")
            {
                yield return(Instruction.Create(OpCodes.Ldc_I4, UInt32.Parse(str, CultureInfo.InvariantCulture)));
            }
            else if (targetTypeRef.FullName == "System.UInt64")
            {
                yield return(Instruction.Create(OpCodes.Ldc_I8, UInt64.Parse(str, CultureInfo.InvariantCulture)));
            }
            else if (targetTypeRef.FullName == "System.Single")
            {
                yield return(Instruction.Create(OpCodes.Ldc_R4, Single.Parse(str, CultureInfo.InvariantCulture)));
            }
            else if (targetTypeRef.FullName == "System.Double")
            {
                yield return(Instruction.Create(OpCodes.Ldc_R8, Double.Parse(str, CultureInfo.InvariantCulture)));
            }
            else if (targetTypeRef.FullName == "System.Boolean")
            {
                if (Boolean.Parse(str))
                {
                    yield return(Instruction.Create(OpCodes.Ldc_I4_1));
                }
                else
                {
                    yield return(Instruction.Create(OpCodes.Ldc_I4_0));
                }
            }
            else if (targetTypeRef.FullName == "System.TimeSpan")
            {
                var ts           = TimeSpan.Parse(str, CultureInfo.InvariantCulture);
                var ticks        = ts.Ticks;
                var timeSpanCtor =
                    module.Import(typeof(TimeSpan))
                    .Resolve()
                    .Methods.FirstOrDefault(md => md.IsConstructor && md.Parameters.Count == 1);
                var timeSpanCtorRef = module.Import(timeSpanCtor);

                yield return(Instruction.Create(OpCodes.Ldc_I8, ticks));

                yield return(Instruction.Create(OpCodes.Newobj, timeSpanCtorRef));
            }
            else if (targetTypeRef.FullName == "System.DateTime")
            {
                var dt           = DateTime.Parse(str, CultureInfo.InvariantCulture);
                var ticks        = dt.Ticks;
                var dateTimeCtor =
                    module.Import(typeof(DateTime))
                    .Resolve()
                    .Methods.FirstOrDefault(md => md.IsConstructor && md.Parameters.Count == 1);
                var dateTimeCtorRef = module.Import(dateTimeCtor);

                yield return(Instruction.Create(OpCodes.Ldc_I8, ticks));

                yield return(Instruction.Create(OpCodes.Newobj, dateTimeCtorRef));
            }
            else if (targetTypeRef.FullName == "System.String" && str.StartsWith("{}", StringComparison.Ordinal))
            {
                yield return(Instruction.Create(OpCodes.Ldstr, str.Substring(2)));
            }
            else if (targetTypeRef.FullName == "System.String")
            {
                yield return(Instruction.Create(OpCodes.Ldstr, str));
            }
            else if (targetTypeRef.FullName == "System.Object")
            {
                yield return(Instruction.Create(OpCodes.Ldstr, str));
            }
            else if (targetTypeRef.FullName == "System.Decimal")
            {
                decimal outdecimal;
                if (decimal.TryParse(str, NumberStyles.Number, CultureInfo.InvariantCulture, out outdecimal))
                {
                    var vardef = new VariableDefinition(context.Body.Method.Module.Import(typeof(decimal)));
                    context.Body.Variables.Add(vardef);
                    //Use an extra temp var so we can push the value to the stack, just like other cases
                    //					IL_0003:  ldstr "adecimal"
                    //					IL_0008:  ldc.i4.s 0x6f
                    //					IL_000a:  call class [mscorlib]System.Globalization.CultureInfo class [mscorlib]System.Globalization.CultureInfo::get_InvariantCulture()
                    //					IL_000f:  ldloca.s 0
                    //					IL_0011:  call bool valuetype [mscorlib]System.Decimal::TryParse(string, valuetype [mscorlib]System.Globalization.NumberStyles, class [mscorlib]System.IFormatProvider, [out] valuetype [mscorlib]System.Decimal&)
                    //					IL_0016:  pop
                    yield return(Instruction.Create(OpCodes.Ldstr, str));

                    yield return(Instruction.Create(OpCodes.Ldc_I4, 0x6f));                    //NumberStyles.Number

                    var getInvariantInfo =
                        context.Body.Method.Module.Import(typeof(CultureInfo))
                        .Resolve()
                        .Properties.FirstOrDefault(pd => pd.Name == "InvariantCulture")
                        .GetMethod;
                    var getInvariant = context.Body.Method.Module.Import(getInvariantInfo);
                    yield return(Instruction.Create(OpCodes.Call, getInvariant));

                    yield return(Instruction.Create(OpCodes.Ldloca, vardef));

                    var tryParseInfo =
                        context.Body.Method.Module.Import(typeof(decimal))
                        .Resolve()
                        .Methods.FirstOrDefault(md => md.Name == "TryParse" && md.Parameters.Count == 4);
                    var tryParse = context.Body.Method.Module.Import(tryParseInfo);
                    yield return(Instruction.Create(OpCodes.Call, tryParse));

                    yield return(Instruction.Create(OpCodes.Pop));

                    yield return(Instruction.Create(OpCodes.Ldloc, vardef));
                }
                else
                {
                    yield return(Instruction.Create(OpCodes.Ldc_I4_0));

                    var decimalctorinfo =
                        context.Body.Method.Module.Import(typeof(decimal))
                        .Resolve()
                        .Methods.FirstOrDefault(
                            md => md.IsConstructor && md.Parameters.Count == 1 && md.Parameters[0].ParameterType.FullName == "System.Int32");
                    var decimalctor = context.Body.Method.Module.Import(decimalctorinfo);
                    yield return(Instruction.Create(OpCodes.Newobj, decimalctor));
                }
            }
            else if (implicitOperator != null)
            {
                yield return(Instruction.Create(OpCodes.Ldstr, node.Value as string));

                yield return(Instruction.Create(OpCodes.Call, module.Import(implicitOperator)));
            }
            else
            {
                yield return(Instruction.Create(OpCodes.Ldnull));
            }

            if (isNullable)
            {
                yield return(Instruction.Create(OpCodes.Newobj, module.Import(nullableCtor)));
            }
            if (originalTypeRef.IsValueType && boxValueTypes)
            {
                yield return(Instruction.Create(OpCodes.Box, module.Import(originalTypeRef)));
            }
        }
        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();
                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 }));
                    }
                }

                //NOTE: only change here
                //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, true));
                }
                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);
                }
            }

            var nativeValueConverterService = DependencyService.Get <INativeValueConverterService> ();

            object nativeValue = null;

            if (nativeValueConverterService != null && nativeValueConverterService.ConvertTo(value, toType, out nativeValue))
            {
                return(nativeValue);
            }

            return(value);
        }
        /// <summary>
        /// Returns parameter accoring type
        /// </summary>
        /// <param name="stringValue">String parameter representation</param>
        /// <param name="isNull">Is parameter null</param>
        /// <param name="type">Type of parameter <see href="http://msdn.microsoft.com/en-us/library/system.data.sqldbtype.aspx"></see></param>
        /// <returns>Parameter value</returns>
        public static object GetValue(string stringValue, bool isNull, DbType type)
        {
            if ((isNull) || (String.IsNullOrEmpty(stringValue)))
            {
                return(DBNull.Value);
            }

            switch (type)
            {
            case DbType.AnsiString:
            case DbType.AnsiStringFixedLength:
            case DbType.StringFixedLength:
            case DbType.String:
            case DbType.Xml:
            case DbType.VarNumeric:
                return(stringValue);

            case DbType.Boolean:
                return(Boolean.Parse(stringValue));

            case DbType.Byte:
                return(Byte.Parse(stringValue));

            case DbType.SByte:
                return(SByte.Parse(stringValue));

            case DbType.Decimal:
            case DbType.Currency:
                return(Decimal.Parse(stringValue));

            case DbType.Date:
            case DbType.DateTime:
            case DbType.DateTime2:
                return(DateTime.Parse(stringValue));

            case DbType.DateTimeOffset:
                return(DateTimeOffset.Parse(stringValue));

            case DbType.Double:
                return(Double.Parse(stringValue));

            case DbType.Guid:
                return(Guid.Parse(stringValue));

            case DbType.Int16:
                return(Int16.Parse(stringValue));

            case DbType.Int32:
                return(Int32.Parse(stringValue));

            case DbType.Int64:
                return(Int64.Parse(stringValue));

            case DbType.UInt16:
                return(UInt16.Parse(stringValue));

            case DbType.UInt32:
                return(UInt16.Parse(stringValue));

            case DbType.UInt64:
                return(UInt16.Parse(stringValue));

            case DbType.Single:
                return(Single.Parse(stringValue));

            default:
                return(stringValue);
            }
        }