示例#1
0
        public static int ReversionType_all        = 3; //完全翻转
        /// <summary>
        ///
        /// </summary>
        /// <param name="shex"></param>
        /// <param name="isReversion">0:bu不翻转,1:分两组翻转,3:4字节的组内再翻转 低高低高 前后两组又是低高类型</param>
        /// <param name="itype"></param>
        /// <param name="cSign"></param>
        /// <returns></returns>
        public static long HexNumberToDenary(string shex, int ReversionType, int itype, char cSign)
        {
            long   ret = 0;
            string hex = shex;

            if (ReversionType == ReversionType_group)
            {
                hex = ReversionTwoGroup(hex);
            }
            else if (ReversionType == ReversionType_groupinner)
            {
                hex = ReversionTwoInner(hex);
            }
            else if (ReversionType == ReversionType_all)
            {
                hex = ReversionAll(hex);
            }

            if (cSign.ToString().ToUpper().Equals("S"))
            {
                switch (itype)
                {
                case 16:
                    ret = Int16.Parse(hex, System.Globalization.NumberStyles.HexNumber);
                    break;

                case 32:
                    ret = Int32.Parse(hex, System.Globalization.NumberStyles.HexNumber);
                    break;

                case 64:
                    ret = Int64.Parse(hex, System.Globalization.NumberStyles.HexNumber);
                    break;

                default:
                    ret = int.Parse(Convert.ToSByte(hex, 16).ToString());    //
                    //ret = int.Parse(hex, System.Globalization.NumberStyles.HexNumber);
                    break;
                }
            }
            else if (cSign.ToString().ToUpper().Equals("U"))
            {
                switch (itype)
                {
                case 16:
                    ret = UInt16.Parse(hex, System.Globalization.NumberStyles.HexNumber);
                    break;

                case 32:
                    ret = UInt32.Parse(hex, System.Globalization.NumberStyles.HexNumber);
                    break;

                case 64:
                    ret = (long)UInt64.Parse(hex, System.Globalization.NumberStyles.HexNumber);
                    break;

                default:
                    ret = (long)HexToDenary(hex);
                    break;
                }
            }
            return(ret);
        }
示例#2
0
        /// <summary>
        /// Gets the list of objects in the bucket filtered by prefix
        /// </summary>
        /// <param name="bucketName">Bucket to list objects from</param>
        /// <param name="prefix">Filters all objects not beginning with a given prefix</param>
        /// <param name="recursive">Set to false to emulate a directory</param>
        /// <param name="marker">marks location in the iterator sequence</param>
        /// <returns>Task with a tuple populated with objects</returns>
        /// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>

        private async Task <Tuple <ListBucketResult, List <Item> > > GetObjectListAsync(string bucketName, string prefix, bool recursive, string marker, CancellationToken cancellationToken = default(CancellationToken))
        {
            var queries = new List <string>();

            if (!recursive)
            {
                queries.Add("delimiter=%2F");
            }
            if (prefix != null)
            {
                queries.Add("prefix=" + Uri.EscapeDataString(prefix));
            }
            if (marker != null)
            {
                queries.Add("marker=" + Uri.EscapeDataString(marker));
            }
            queries.Add("max-keys=1000");
            string query = string.Join("&", queries);

            string path = bucketName;

            if (query.Length > 0)
            {
                path += "?" + query;
            }

            var request = await this.CreateRequest(Method.GET,
                                                   bucketName,
                                                   resourcePath : "?" + query);



            var response = await this.ExecuteTaskAsync(this.NoErrorHandlers, request, cancellationToken);

            var contentBytes = System.Text.Encoding.UTF8.GetBytes(response.Content);
            ListBucketResult listBucketResult = null;

            using (var stream = new MemoryStream(contentBytes))
            {
                listBucketResult = (ListBucketResult)(new XmlSerializer(typeof(ListBucketResult)).Deserialize(stream));
            }

            XDocument root = XDocument.Parse(response.Content);

            var items = (from c in root.Root.Descendants("{http://s3.amazonaws.com/doc/2006-03-01/}Contents")
                         select new Item()
            {
                Key = c.Element("{http://s3.amazonaws.com/doc/2006-03-01/}Key").Value,
                LastModified = c.Element("{http://s3.amazonaws.com/doc/2006-03-01/}LastModified").Value,
                ETag = c.Element("{http://s3.amazonaws.com/doc/2006-03-01/}ETag").Value,
                Size = UInt64.Parse(c.Element("{http://s3.amazonaws.com/doc/2006-03-01/}Size").Value, CultureInfo.CurrentCulture),
                IsDir = false
            });

            var prefixes = (from c in root.Root.Descendants("{http://s3.amazonaws.com/doc/2006-03-01/}CommonPrefixes")
                            select new Item()
            {
                Key = c.Element("{http://s3.amazonaws.com/doc/2006-03-01/}Prefix").Value,
                IsDir = true
            });

            items = items.Concat(prefixes);

            return(new Tuple <ListBucketResult, List <Item> >(listBucketResult, items.ToList()));
        }
示例#3
0
 // ReadUInt64 /////////////////////////////////////
 public UInt64 ReadUInt64()
 { // Reads a 64-bit integer from the stream.
     return(UInt64.Parse(getNextRawItem().ToString()));
 }
示例#4
0
 public static ulong ToUInt64Value(this String str)
 {
     return(UInt64.Parse(str));
 }
        public override ExpressionResult VisitInt(EntityGraphQLParser.IntContext context)
        {
            string s = context.GetText();

            return((ExpressionResult)(s.StartsWith("-") ? Expression.Constant(Int64.Parse(s)) : Expression.Constant(UInt64.Parse(s))));
        }
示例#6
0
        private bool UpdateStatus(XContainer status)
        {
            XElement processes  = status.Descendants("RegisteredProcesses").Single();
            UInt64   newEpoch   = UInt64.Parse(processes.Attribute("epoch").Value);
            UInt64   newVersion = UInt64.Parse(processes.Attribute("version").Value);

            XElement workers   = processes.Descendants("ProcessGroup").Where(pg => pg.Attribute("name").Value == "Worker").Single();
            int      newTarget = int.Parse(workers.Attribute("targetNumberOfProcesses").Value);

            Debug.Assert(newEpoch >= epoch);
            if (newEpoch > epoch)
            {
                epoch = newEpoch;
                targetNumberOfWorkers = newTarget;
                version = 0;
            }
            else
            {
                Debug.Assert(newTarget == targetNumberOfWorkers);
            }

            Debug.Assert(newVersion >= version);
            if (newVersion > version)
            {
                version = newVersion;
            }

            List <KeyValuePair <string, IPEndPoint> > newPeer = new List <KeyValuePair <string, IPEndPoint> >();

            foreach (var processElement in workers.Descendants("Process"))
            {
                string   id       = processElement.Attribute("identifier").Value;
                XElement details  = processElement.Descendants("ProcessDetails").Single();
                XElement server   = details.Descendants("ServerSocket").Single();
                string   hostName = server.Attribute("hostname").Value;
                int      port     = int.Parse(server.Attribute("port").Value);

                IPAddress[]             choices = Dns.GetHostAddresses(hostName);
                IEnumerable <IPAddress> ipv4    = choices.Where(a => a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
                IPAddress remoteAddress         = ipv4.First();

                newPeer.Add(new KeyValuePair <string, IPEndPoint>(id, new IPEndPoint(remoteAddress, port)));
            }

            if (newPeer.Count == targetNumberOfWorkers)
            {
                Logging.Info("Got status response with all " + targetNumberOfWorkers + " workers");
                IEnumerable <KeyValuePair <string, IPEndPoint> > sorted = newPeer.OrderBy(x => x.Key);

                knownWorkers = sorted.Select(x => x.Value).ToArray();
                selfIndex    = sorted.
                               Select((x, i) => new KeyValuePair <string, int>(x.Key, i)).
                               Where(x => x.Key == procIdentifier).
                               Single().
                               Value;

                Logging.Info("Self index is " + selfIndex);

                return(true);
            }
            else
            {
                Logging.Info("Got status response with " + newPeer.Count + " workers; need to wait for " + targetNumberOfWorkers);
                return(false);
            }
        }
示例#7
0
 public static ulong ToUInt64(string value)
 {
     return(UInt64.Parse(value));
 }
        public static ExtendedGroupMembersData GroupMembersData(Dictionary <string, object> dict)
        {
            ExtendedGroupMembersData member = new ExtendedGroupMembersData();

            if (dict == null)
            {
                return(member);
            }

            if (dict.ContainsKey("AcceptNotices") && dict["AcceptNotices"] != null)
            {
                member.AcceptNotices = bool.Parse(dict["AcceptNotices"].ToString());
            }

            if (dict.ContainsKey("AccessToken") && dict["AccessToken"] != null)
            {
                member.AccessToken = Sanitize(dict["AccessToken"].ToString());
            }
            else
            {
                member.AccessToken = string.Empty;
            }

            if (dict.ContainsKey("AgentID") && dict["AgentID"] != null)
            {
                member.AgentID = Sanitize(dict["AgentID"].ToString());
            }
            else
            {
                member.AgentID = UUID.Zero.ToString();
            }

            if (dict.ContainsKey("AgentPowers") && dict["AgentPowers"] != null)
            {
                member.AgentPowers = UInt64.Parse(dict["AgentPowers"].ToString());
            }

            if (dict.ContainsKey("Contribution") && dict["Contribution"] != null)
            {
                member.Contribution = Int32.Parse(dict["Contribution"].ToString());
            }

            if (dict.ContainsKey("IsOwner") && dict["IsOwner"] != null)
            {
                member.IsOwner = bool.Parse(dict["IsOwner"].ToString());
            }

            if (dict.ContainsKey("ListInProfile") && dict["ListInProfile"] != null)
            {
                member.ListInProfile = bool.Parse(dict["ListInProfile"].ToString());
            }

            if (dict.ContainsKey("OnlineStatus") && dict["OnlineStatus"] != null)
            {
                member.OnlineStatus = Sanitize(dict["OnlineStatus"].ToString());
            }
            else
            {
                member.OnlineStatus = string.Empty;
            }

            if (dict.ContainsKey("Title") && dict["Title"] != null)
            {
                member.Title = Sanitize(dict["Title"].ToString());
            }
            else
            {
                member.Title = string.Empty;
            }

            return(member);
        }
        public static ExtendedGroupMembershipData GroupMembershipData(Dictionary <string, object> dict)
        {
            if (dict == null)
            {
                return(null);
            }

            ExtendedGroupMembershipData membership = new ExtendedGroupMembershipData();

            if (dict.ContainsKey("AcceptNotices") && dict["AcceptNotices"] != null)
            {
                membership.AcceptNotices = bool.Parse(dict["AcceptNotices"].ToString());
            }

            if (dict.ContainsKey("AccessToken") && dict["AccessToken"] != null)
            {
                membership.AccessToken = dict["AccessToken"].ToString();
            }
            else
            {
                membership.AccessToken = string.Empty;
            }

            if (dict.ContainsKey("Active") && dict["Active"] != null)
            {
                membership.Active = bool.Parse(dict["Active"].ToString());
            }

            if (dict.ContainsKey("ActiveRole") && dict["ActiveRole"] != null)
            {
                membership.ActiveRole = UUID.Parse(dict["ActiveRole"].ToString());
            }

            if (dict.ContainsKey("AllowPublish") && dict["AllowPublish"] != null)
            {
                membership.AllowPublish = bool.Parse(dict["AllowPublish"].ToString());
            }

            if (dict.ContainsKey("Charter") && dict["Charter"] != null)
            {
                membership.Charter = dict["Charter"].ToString();
            }
            else
            {
                membership.Charter = string.Empty;
            }

            if (dict.ContainsKey("Contribution") && dict["Contribution"] != null)
            {
                membership.Contribution = Int32.Parse(dict["Contribution"].ToString());
            }

            if (dict.ContainsKey("FounderID") && dict["FounderID"] != null)
            {
                membership.FounderID = UUID.Parse(dict["FounderID"].ToString());
            }

            if (dict.ContainsKey("GroupID") && dict["GroupID"] != null)
            {
                membership.GroupID = UUID.Parse(dict["GroupID"].ToString());
            }

            if (dict.ContainsKey("GroupName") && dict["GroupName"] != null)
            {
                membership.GroupName = dict["GroupName"].ToString();
            }
            else
            {
                membership.GroupName = string.Empty;
            }

            if (dict.ContainsKey("GroupPicture") && dict["GroupPicture"] != null)
            {
                membership.GroupPicture = UUID.Parse(dict["GroupPicture"].ToString());
            }

            if (dict.ContainsKey("GroupPowers") && dict["GroupPowers"] != null)
            {
                membership.GroupPowers = UInt64.Parse(dict["GroupPowers"].ToString());
            }

            if (dict.ContainsKey("GroupTitle") && dict["GroupTitle"] != null)
            {
                membership.GroupTitle = dict["GroupTitle"].ToString();
            }
            else
            {
                membership.GroupTitle = string.Empty;
            }

            if (dict.ContainsKey("ListInProfile") && dict["ListInProfile"] != null)
            {
                membership.ListInProfile = bool.Parse(dict["ListInProfile"].ToString());
            }

            if (dict.ContainsKey("MaturePublish") && dict["MaturePublish"] != null)
            {
                membership.MaturePublish = bool.Parse(dict["MaturePublish"].ToString());
            }

            if (dict.ContainsKey("MembershipFee") && dict["MembershipFee"] != null)
            {
                membership.MembershipFee = Int32.Parse(dict["MembershipFee"].ToString());
            }

            if (dict.ContainsKey("OpenEnrollment") && dict["OpenEnrollment"] != null)
            {
                membership.OpenEnrollment = bool.Parse(dict["OpenEnrollment"].ToString());
            }

            if (dict.ContainsKey("ShowInList") && dict["ShowInList"] != null)
            {
                membership.ShowInList = bool.Parse(dict["ShowInList"].ToString());
            }

            return(membership);
        }
示例#10
0
        private bool Validate(InputBoxResultType validationType)
        {
            bool result = false;

            switch (validationType)
            {
            case InputBoxResultType.Boolean:
                try
                {
                    Boolean.Parse(this.txtInput.Text);
                    result = true;
                }
                catch
                {
                    // just eat it
                }
                break;

            case InputBoxResultType.Byte:
                try
                {
                    Byte.Parse(this.txtInput.Text);
                    result = true;
                }
                catch
                {
                    // just eat it
                }
                break;

            case InputBoxResultType.Char:
                try
                {
                    Char.Parse(this.txtInput.Text);
                    result = true;
                }
                catch
                {
                    // just eat it
                }
                break;

            case InputBoxResultType.Date:
                try
                {
                    DateTime.Parse(this.dateTimePicker1.Text);
                    result = true;
                }
                catch
                {
                    // just eat it
                }
                break;

            case InputBoxResultType.Decimal:
                try
                {
                    Decimal.Parse(this.txtInput.Text);
                    result = true;
                }
                catch
                {
                    // just eat it
                }
                break;

            case InputBoxResultType.Double:
                try
                {
                    Double.Parse(this.txtInput.Text);
                    result = true;
                }
                catch
                {
                    // just eat it
                }
                break;

            case InputBoxResultType.Float:
                try
                {
                    Single.Parse(this.txtInput.Text);
                    result = true;
                }
                catch
                {
                    // just eat it
                }
                break;

            case InputBoxResultType.Int16:
                try
                {
                    Int16.Parse(this.txtInput.Text);
                    result = true;
                }
                catch
                {
                    // just eat it
                }
                break;

            case InputBoxResultType.Int32:
                try
                {
                    Int32.Parse(this.txtInput.Text);
                    result = true;
                }
                catch
                {
                    // just eat it
                }
                break;

            case InputBoxResultType.Int64:
                try
                {
                    Int64.Parse(this.txtInput.Text);
                    result = true;
                }
                catch
                {
                    // just eat it
                }
                break;

            case InputBoxResultType.UInt16:
                try
                {
                    UInt16.Parse(this.txtInput.Text);
                    result = true;
                }
                catch
                {
                    // just eat it
                }
                break;

            case InputBoxResultType.UInt32:
                try
                {
                    UInt32.Parse(this.txtInput.Text);
                    result = true;
                }
                catch
                {
                    // just eat it
                }
                break;

            case InputBoxResultType.UInt64:
                try
                {
                    UInt64.Parse(this.txtInput.Text);
                    result = true;
                }
                catch
                {
                    // just eat it
                }
                break;
            }

            return(result);
        }
        static ulong GetSteam3DepotManifest(uint depotId, uint appId, string branch)
        {
            KeyValue depots     = GetSteam3AppSection(appId, EAppInfoSection.Depots);
            KeyValue depotChild = depots[depotId.ToString()];

            if (depotChild == KeyValue.Invalid)
            {
                return(INVALID_MANIFEST_ID);
            }

            // Shared depots can either provide manifests, or leave you relying on their parent app.
            // It seems that with the latter, "sharedinstall" will exist (and equals 2 in the one existance I know of).
            // Rather than relay on the unknown sharedinstall key, just look for manifests. Test cases: 111710, 346680.
            if (depotChild["manifests"] == KeyValue.Invalid && depotChild["depotfromapp"] != KeyValue.Invalid)
            {
                uint otherAppId = depotChild["depotfromapp"].AsUnsignedInteger();
                if (otherAppId == appId)
                {
                    // This shouldn't ever happen, but ya never know with Valve. Don't infinite loop.
                    Console.WriteLine("App {0}, Depot {1} has depotfromapp of {2}!",
                                      appId, depotId, otherAppId);
                    return(INVALID_MANIFEST_ID);
                }

                steam3.RequestAppInfo(otherAppId);

                return(GetSteam3DepotManifest(depotId, otherAppId, branch));
            }

            var manifests           = depotChild["manifests"];
            var manifests_encrypted = depotChild["encryptedmanifests"];

            if (manifests.Children.Count == 0 && manifests_encrypted.Children.Count == 0)
            {
                return(INVALID_MANIFEST_ID);
            }

            var node = manifests[branch];

            if (branch != "Public" && node == KeyValue.Invalid)
            {
                var node_encrypted = manifests_encrypted[branch];
                if (node_encrypted != KeyValue.Invalid)
                {
                    string password = Config.BetaPassword;
                    if (password == null)
                    {
                        Console.Write("Please enter the password for branch {0}: ", branch);
                        Config.BetaPassword = password = Console.ReadLine();
                    }

                    var encrypted_v1 = node_encrypted["encrypted_gid"];
                    var encrypted_v2 = node_encrypted["encrypted_gid_2"];

                    if (encrypted_v1 != KeyValue.Invalid)
                    {
                        byte[] input          = Util.DecodeHexString(encrypted_v1.Value);
                        byte[] manifest_bytes = CryptoHelper.VerifyAndDecryptPassword(input, password);

                        if (manifest_bytes == null)
                        {
                            Console.WriteLine("Password was invalid for branch {0}", branch);
                            return(INVALID_MANIFEST_ID);
                        }

                        return(BitConverter.ToUInt64(manifest_bytes, 0));
                    }
                    else if (encrypted_v2 != KeyValue.Invalid)
                    {
                        // Submit the password to Steam now to get encryption keys
                        steam3.CheckAppBetaPassword(appId, Config.BetaPassword);

                        if (!steam3.AppBetaPasswords.ContainsKey(branch))
                        {
                            Console.WriteLine("Password was invalid for branch {0}", branch);
                            return(INVALID_MANIFEST_ID);
                        }

                        byte[] input = Util.DecodeHexString(encrypted_v2.Value);
                        byte[] manifest_bytes;
                        try
                        {
                            manifest_bytes = CryptoHelper.SymmetricDecryptECB(input, steam3.AppBetaPasswords[branch]);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Failed to decrypt branch {0}: {1}", branch, e.Message);
                            return(INVALID_MANIFEST_ID);
                        }

                        return(BitConverter.ToUInt64(manifest_bytes, 0));
                    }
                    else
                    {
                        Console.WriteLine("Unhandled depot encryption for depotId {0}", depotId);
                        return(INVALID_MANIFEST_ID);
                    }
                }

                return(INVALID_MANIFEST_ID);
            }

            if (node.Value == null)
            {
                return(INVALID_MANIFEST_ID);
            }

            return(UInt64.Parse(node.Value));
        }
示例#12
0
        private static object DeserializeScalar(EventReader reader, Type type, DeserializationContext context)
        {
            Scalar scalar = reader.Expect <Scalar>();

            object result;

            type = GetType(scalar.Tag, type, context.Options.Mappings);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                default:
                    if (type == typeof(object))
                    {
                        // Default to string
                        result = scalar.Value;
                    }
                    else
                    {
                        TypeConverter converter = TypeDescriptor.GetConverter(type);
                        if (converter != null && converter.CanConvertFrom(typeof(string)))
                        {
                            result = converter.ConvertFromInvariantString(scalar.Value);
                        }
                        else
                        {
                            result = Convert.ChangeType(scalar.Value, type, CultureInfo.InvariantCulture);
                        }
                    }
                    break;
                }
            }

            AddAnchoredObject(scalar, result, context.Anchors);

            return(result);
        }
示例#13
0
        /// <summary>
        /// Converts String represenation to appropriate object of specified <see cref="Alachisoft.NosDB.Common.DataStructures.ColumnDataType"/>
        /// </summary>
        /// <param name="stringValue">String representation of object</param>
        /// <param name="dataType"><see cref="Alachisoft.NosDB.Common.DataStructures.ColumnDataType"/> of object</param>
        /// <returns></returns>
        public static object ToObject(string stringValue, ColumnDataType dataType)
        {
            switch (dataType)
            {
            case ColumnDataType.Bool:
                return(bool.Parse(stringValue));

                break;

            case ColumnDataType.Byte:
                return(byte.Parse(stringValue));

                break;

            case ColumnDataType.Char:
                return(char.Parse(stringValue));

                break;

            case ColumnDataType.DateTime:
                return(DateTime.ParseExact(stringValue, "dd/MM/yyyy/HH/mm/ss/ffff/zzzz", System.Globalization.CultureInfo.InvariantCulture));

                break;

            case ColumnDataType.Decimal:
                return(decimal.Parse(stringValue));

            case ColumnDataType.Double:
                return(double.Parse(stringValue));

                break;

            case ColumnDataType.Float:
                return(float.Parse(stringValue));

                break;

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

                break;

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

                break;

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

                break;

            case ColumnDataType.SByte:
                return(sbyte.Parse(stringValue));

            case ColumnDataType.String:
                return(stringValue);

                break;

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

                break;

            case ColumnDataType.UInt32:
                return(UInt32.Parse(stringValue));

                break;

            case ColumnDataType.UInt64:
                return(UInt64.Parse(stringValue));

                break;

            default:
                throw new InvalidCastException();
            }
        }
示例#14
0
        private void btnDetailsApply_Click(object sender, EventArgs e)
        {
            if (DoingSomeJob.Working)
            {
                MessageBox.Show("Please wait... Still working in background!", "UO:KR Uop Dumper", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            DoingSomeJob.Working = true;

            if (this.pnUopfile.Enabled)
            {
                try
                {
                    UOPFile uppeCurrent = (UOPFile)this.gbSelectedData.Tag;

                    byte[] bHeader1 = Utility.StringToByteArray(this.txt_pnlUopFile_Header1.Text, Utility.HashStringStyle.HexWithSeparator, 24);
                    byte[] bHeader2 = Utility.StringToByteArray(this.txt_pnlUopFile_Header2.Text, Utility.HashStringStyle.HexWithSeparator, 12);
                    uint   uCount   = Decimal.ToUInt32(this.num_pnlUopFile_Files.Value);

                    if ((bHeader1 == null) || (bHeader1 == null))
                    {
                        throw new Exception();
                    }
                    else
                    {
                        uppeCurrent.m_Header.m_variousData = bHeader1;
                        uppeCurrent.m_Header.m_totalIndex  = uCount;
                        uppeCurrent.m_Header.m_Unknown     = bHeader2;
                    }
                }
                catch
                {
                    MessageBox.Show("Error while parsing the data!", "UO:KR Uop Dumper - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                SetPanel(ShowPanels.RootNode, this.gbSelectedData.Tag);
            }
            else if (this.pnUopDatafile.Enabled)
            {
                try
                {
                    UOPIndexBlockHeader uppeCurrent = (UOPIndexBlockHeader)this.gbSelectedData.Tag;

                    ulong ulOffset = UInt64.Parse(this.txt_pnUopDatafile_Offset.Text, System.Globalization.NumberStyles.AllowHexSpecifier);
                    uint  uCount   = Decimal.ToUInt32(this.nud_pnUopDatafile_Files.Value);

                    uppeCurrent.m_Files           = uCount;
                    uppeCurrent.m_OffsetNextIndex = ulOffset;
                }
                catch
                {
                    MessageBox.Show("Error while parsing the data!", "UO:KR Uop Dumper - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                SetPanel(ShowPanels.DataNode, this.gbSelectedData.Tag);
            }
            else if (this.pnUopHeaderAndData.Enabled)
            {
                try
                {
                    UOPPairData uppeCurrent = (UOPPairData)this.gbSelectedData.Tag;

                    // Header block
                    ulong  ulOffset = UInt64.Parse(this.txt_pnUopHeaderAndData_Offset.Text, System.Globalization.NumberStyles.AllowHexSpecifier);
                    uint   uiUnk1 = UInt32.Parse(this.txt_pnUopHeaderAndData_Unk1.Text, System.Globalization.NumberStyles.AllowHexSpecifier);
                    uint   uiUnk2 = UInt32.Parse(this.txt_pnUopHeaderAndData_Unk2.Text, System.Globalization.NumberStyles.AllowHexSpecifier);
                    uint   uiUnk3 = UInt32.Parse(this.txt_pnUopHeaderAndData_Unk3.Text, System.Globalization.NumberStyles.AllowHexSpecifier);
                    string sNewFile = null; bool bUncompressed = false;
                    if (this.txt_pnUopHeaderAndData_Data.Tag != null)
                    {
                        sNewFile      = (string)(((System.Collections.Hashtable) this.txt_pnUopHeaderAndData_Data.Tag)["file"]);
                        bUncompressed = (bool)(((System.Collections.Hashtable) this.txt_pnUopHeaderAndData_Data.Tag)["uncompressed"]);
                    }
                    ulong ulUnkData = UInt64.Parse(this.txt_pnUopHeaderAndData_DataUnk1.Text, System.Globalization.NumberStyles.AllowHexSpecifier);

                    if (sNewFile != null)
                    {
                        if (UopManager.getIstance().Replace(sNewFile, uppeCurrent, bUncompressed) != UopManager.UopPatchError.Okay)
                        {
                            throw new Exception();
                        }
                    }

                    uppeCurrent.First.m_OffsetOfDataBlock = ulOffset;
                    uppeCurrent.First.m_Unknown1          = uiUnk1;
                    uppeCurrent.First.m_Unknown2          = uiUnk2;
                    uppeCurrent.First.m_Unknown3          = uiUnk2;
                }
                catch
                {
                    MessageBox.Show("Error while parsing the data!", "UO:KR Uop Dumper - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                SetPanel(ShowPanels.SingleHeader, this.gbSelectedData.Tag);
            }
            else
            {
                SetPanel(ShowPanels.Nothing, null);
            }

            DoingSomeJob.Working = false;
        }
示例#15
0
    void Start()
    {
#if !UNITY_ANDROID
        if (CombineMeshes)
        {
            CombineMeshes = false;
            AvatarLogger.Log("Combine Meshes Currently Only Supported On Android");
        }
#endif

#if !UNITY_5_5_OR_NEWER
        if (CombineMeshes)
        {
            CombineMeshes = false;
            AvatarLogger.LogWarning("Unity Version too old to use Combined Mesh Shader, required 5.5.0+");
        }
#endif

        try
        {
            oculusUserIDInternal = UInt64.Parse(oculusUserID);
        }
        catch (Exception)
        {
            oculusUserIDInternal = 0;

            AvatarLogger.LogWarning("Invalid Oculus User ID Format");
        }

        AvatarLogger.Log("Starting OvrAvatar " + gameObject.name);
        AvatarLogger.Log(AvatarLogger.Tab + "LOD: " + LevelOfDetail.ToString());
        AvatarLogger.Log(AvatarLogger.Tab + "Combine Meshes: " + CombineMeshes);
        AvatarLogger.Log(AvatarLogger.Tab + "Force Mobile Textures: " + ForceMobileTextureFormat);
        AvatarLogger.Log(AvatarLogger.Tab + "Oculus User ID: " + oculusUserIDInternal);

        Capabilities = 0;
        if (EnableBody)
        {
            Capabilities |= ovrAvatarCapabilities.Body;
        }
        if (EnableHands)
        {
            Capabilities |= ovrAvatarCapabilities.Hands;
        }
        if (EnableBase && EnableBody)
        {
            Capabilities |= ovrAvatarCapabilities.Base;
        }
        if (EnableExpressive)
        {
            Capabilities |= ovrAvatarCapabilities.Expressive;
        }

#if !UNITY_ANDROID
        Capabilities |= ovrAvatarCapabilities.BodyTilt;
#endif

        ShowLeftController(StartWithControllers);
        ShowRightController(StartWithControllers);
        OvrAvatarSDKManager.Instance.RequestAvatarSpecification(
            oculusUserIDInternal,
            this.AvatarSpecificationCallback,
            CombineMeshes,
            LevelOfDetail,
            ForceMobileTextureFormat,
            LookAndFeelVersion,
            FallbackLookAndFeelVersion,
            EnableExpressive);

        WaitingForCombinedMesh = CombineMeshes;
        if (Driver != null)
        {
            Driver.Mode = UseSDKPackets ? OvrAvatarDriver.PacketMode.SDK : OvrAvatarDriver.PacketMode.Unity;
        }
    }
示例#16
0
    /*
     * <GuildResp>
     *  <Arg>UINT8</Arg>   -- id
     *  <Arg>UINT16</Arg>  --errCode
     *  <Arg>LUA_TABLE</Arg>
     * </GuildResp>
     */

    public void GuildResp(byte id, UInt16 errCode, LuaTable respInfo)
    {
        if (errCode != 0)
        {
            HandleErrorCode(errCode);
        }

        switch (id)
        {
        case MSG_GET_GUILDS:
            //应lua_table:({1=数量, 2={1={1=公会dbid,2=名称,3=等级,4=人数}, ...}})
            if (errCode == 0)
            {
                int tongNum = int.Parse((string)respInfo["1"]);

                m_listTongUIData.Clear();
                m_listTongData.Clear();

                for (int i = 0; i < tongNum; ++i)
                {
                    TongData temp = new TongData();

                    //uint.Parse((string)((LuaTable)((LuaTable)respInfo["2"])[i.ToString()])["1"]);
                    temp.dbid      = uint.Parse((string)((LuaTable)((LuaTable)respInfo["2"])[(i + 1).ToString()])["1"]);
                    temp.name      = (string)((LuaTable)((LuaTable)respInfo["2"])[(i + 1).ToString()])["2"];
                    temp.level     = int.Parse((string)((LuaTable)((LuaTable)respInfo["2"])[(i + 1).ToString()])["3"]);
                    temp.peopleNum = int.Parse((string)((LuaTable)((LuaTable)respInfo["2"])[(i + 1).ToString()])["4"]);

                    TongUIViewManager.TongData td = new TongUIViewManager.TongData();
                    td.level = temp.level.ToString();
                    td.name  = temp.name;
                    td.num   = temp.peopleNum.ToString();

                    m_listTongUIData.Add(td);
                    m_listTongData.Add(temp);
                }

                TongUIViewManager.Instance.SetTongList(m_listTongUIData);
                TongUIViewManager.Instance.ShowTongList();
            }
            break;

        case MSG_GET_GUILDS_COUNT:
            Debug.Log("获取公会数量返回");
            if (errCode == 0)
            {
                m_iTongNum = int.Parse((string)respInfo["1"]);

                GuildReq(MSG_GET_GUILDS, 1, (uint)m_iTongNum);

                Debug.Log("获取公会数量  " + m_iTongNum);
            }
            break;

        case MSG_CREATE_GUILD:
            if (errCode == 0)
            {
                //创建公会成功
                //le:({1=公会名, 2=公会人数, 3=公会职位})

                //m_strTongName = (string)respInfo["1"];
                //m_strTongPeopleNum = ((int)respInfo["2"]).ToString();

                GuildReq(MSG_GET_GUILD_INFO);
                Debug.Log("创建公会成功");
            }
            else
            {
                Debug.Log("创建公会失败 errCode = " + errCode);
            }
            break;

        case MSG_GET_GUILD_INFO:
            if (errCode == 0 && (string)respInfo["1"] != "")
            {
                //切换到公会详细界面
                m_strTongName = (string)respInfo["1"];
                GuildReq(MSG_GET_GUILD_DETAILED_INFO);
                IsShowMyTong = true;
                IsShowDragon = false;
                IsShowSkill  = false;

                Debug.Log("获取公会信息成功 " + errCode + " " + (string)respInfo["1"]);
            }
            //else if (errCode == ERROR_GET_GUILD_DETAILED_INFO_NO_GUILD)
            else
            {
                GuildReq(MSG_GET_GUILDS_COUNT);
                //切换到公会列表

                Debug.Log("获取公会信息失败 " + errCode);
            }
            break;

        case MSG_SET_GUILD_ANNOUNCEMENT:
            if (errCode == 0)
            {
                //修改公告成功
                GuildReq(MSG_GET_GUILD_ANNOUNCEMENT);
            }
            break;

        case MSG_GET_GUILD_ANNOUNCEMENT:
            if (errCode == 0)
            {
                m_strTongNotice = (string)respInfo["1"];

                TongUIViewManager.Instance.SetTongNotice(m_strTongNotice);
                //获取公告成功
            }
            break;

        case MSG_APPLY_TO_JOIN:
            if (errCode == 0)
            {
                //申请加入公会成功
                Debug.Log("尝试申请加入公会成功");
            }
            else
            {
                Debug.Log("尝试申请加入?崾О圻" + errCode);
            }
            break;

        case MSG_APPLY_TO_JOIN_NOTIFY:
            break;

        case MSG_GET_GUILD_DETAILED_INFO:
            if (errCode == 0)
            {
                //获取公会详细信息成功
                m_strTongNotice      = (string)respInfo["1"];
                m_strTongMoney       = (string)respInfo["2"];
                m_strTongLevel       = (string)respInfo["3"];
                m_strTongPeopleNum   = (string)respInfo["4"];
                m_strTongBossName    = (string)respInfo["5"];
                m_iCurrenDragonPower = int.Parse((string)respInfo["6"]);

                foreach (var item in GuildSkillData.dataMap)
                {
                    if (!m_dictSkillIDToLevel.ContainsKey(item.Value.type))
                    {
                        Debug.Log(item.Value.type.ToString() + " " + (LuaTable)respInfo["7"]);
                        m_dictSkillIDToLevel.Add(item.Value.type, int.Parse((string)((LuaTable)respInfo["7"])[item.Value.type.ToString()]));
                    }
                }

                TongUIViewManager.Instance.SetTitle(string.Concat(m_strTongName, "   Lv ", m_strTongLevel));
                TongUIViewManager.Instance.SetTongMoney("公会资金:" + m_strTongMoney);
                TongUIViewManager.Instance.SetTongNum("公会人数:" + m_strTongPeopleNum + "/" + GuildLevelData.dataMap[int.Parse(m_strTongLevel)].memberCount);
                TongUIViewManager.Instance.SetTongName("会长:" + m_strTongBossName);
                TongUIViewManager.Instance.SetTongNotice(m_strTongNotice);

                if (IsShowMyTong)
                {
                    TongUIViewManager.Instance.ShowMyTong();
                }
                else if (IsShowDragon)
                {
                    foreach (var item in GuildDragonData.dataMap)
                    {
                        if (item.Value.guild_level.ToString() == m_strTongLevel)
                        {
                            int diamond = item.Value.diamond_recharge_cost;
                            int gold    = item.Value.gold_recharge_cost;
                            TongUIViewManager.Instance.ShowDragonPower("88", m_iCurrenDragonPower, item.Value.dragon_limit, gold, diamond, diamond);
                            break;
                        }
                    }
                }
                else if (IsShowSkill)
                {
                    m_listTongSkillUIData.Clear();

                    foreach (var item in GuildSkillData.dataMap)
                    {
                        TongUIViewManager.TongSkillData data = new TongUIViewManager.TongSkillData();
                        data.cost    = item.Value.money.ToString();
                        data.effect1 = item.Value.add.ToString();
                        data.effect2 = item.Value.add.ToString();
                        //data.name = item.Value.type.ToString();

                        switch (item.Value.type)
                        {
                        case 1:
                            data.name = LanguageData.GetContent(48405);         // "攻击技能";
                            break;

                        case 2:
                            data.name = LanguageData.GetContent(48405);         // "防守技能";
                            break;

                        case 3:
                            data.name = LanguageData.GetContent(48405);         // "生命技能";
                            break;
                        }
                        data.starNum = m_dictSkillIDToLevel[item.Value.type];

                        m_listTongSkillUIData.Add(data);

                        m_listTongSkillType.Add(item.Value.type);
                    }

                    TongUIViewManager.Instance.SetSkillList(m_listTongSkillUIData);
                    TongUIViewManager.Instance.ShowSkillList();
                }
                else
                {
                    TongManager.Instance.GuildReq(TongManager.MSG_GET_GUILD_MEMBERS, 1,
                                                  uint.Parse(TongManager.Instance.m_strTongPeopleNum));
                }

                Debug.Log("获取公会详细信息成功");
            }
            else
            {
                Debug.Log("获取公会详细信息失败 " + errCode);
            }
            break;

        case MSG_GET_GUILD_MESSAGES_COUNT:
            if (errCode == 0)
            {
                int count = int.Parse((string)(respInfo["1"]));
                Debug.Log("获取公会请求信息数量成功 " + count);

                GuildReq(MSG_GET_GUILD_MESSAGES, 1, (uint)count, "1");
            }
            else
            {
                Debug.Log("获取公会请求信息数量失败 " + errCode);
            }
            break;

        case MSG_GET_GUILD_MESSAGES:
            if (errCode == 0)
            {
                m_listTongApplicantData.Clear();
                m_listTongApplicantUIData.Clear();

                int count = int.Parse((string)(respInfo["1"]));

                for (int i = 0; i < count; ++i)
                {
                    TongApplicantData data = new TongApplicantData();

                    data.dbid  = UInt64.Parse((string)((LuaTable)((LuaTable)respInfo["2"])[(i + 1).ToString()])["1"]);
                    data.name  = (string)((LuaTable)((LuaTable)respInfo["2"])[(i + 1).ToString()])["2"];
                    data.job   = int.Parse((string)((LuaTable)((LuaTable)respInfo["2"])[(i + 1).ToString()])["3"]);
                    data.level = int.Parse((string)((LuaTable)((LuaTable)respInfo["2"])[(i + 1).ToString()])["4"]);
                    data.power = int.Parse((string)((LuaTable)((LuaTable)respInfo["2"])[(i + 1).ToString()])["5"]);

                    m_listTongApplicantData.Add(data);

                    TongUIViewManager.ApplicantData uidata = new TongUIViewManager.ApplicantData();

                    uidata.name         = data.name;
                    uidata.level        = data.level.ToString();
                    uidata.power        = data.power.ToString();
                    uidata.vocationIcon = IconData.GetHeadImgByVocation(data.job);

                    m_listTongApplicantUIData.Add(uidata);
                }

                TongUIViewManager.Instance.SetApplicantList(m_listTongApplicantUIData);
                TongUIViewManager.Instance.ShowMyTongApplicantList();

                Debug.Log("获取公会请求列表成功 " + count);
            }
            else
            {
                Debug.Log("获取公会请求列表失败 " + errCode);
            }
            break;

        case MSG_ANSWER_APPLY:
            if (errCode == 0)
            {
                TongManager.Instance.GuildReq(TongManager.MSG_GET_GUILD_MESSAGES_COUNT, 1);
            }
            else
            {
                Debug.Log("回应申请失败 " + errCode);
            }
            break;

        case MSG_INVITE:
            if (errCode == 0)
            {
            }
            break;

        case MSG_INVITED:
            if (errCode == 0)
            {
            }
            break;

        case MSG_ANSWER_INVITE:
            if (errCode == 0)
            {
            }
            break;

        case MSG_APPLY_TO_JOIN_RESULT:
            if (errCode == 0)
            {
                //申请回应

                int result = int.Parse((string)respInfo["1"]);

                string tongName = (string)respInfo["2"];

                if (result == 0)
                {
                    MogoGlobleUIManager.Instance.Info(tongName + " JoinReq Success");
                    Debug.Log("申请成功");
                    GuildReq(MSG_GET_GUILD_INFO);
                }
                else
                {
                    MogoGlobleUIManager.Instance.Info(tongName + " JoinReq Fail");
                }
            }
            break;

        case MSG_QUIT:
            if (errCode == 0)
            {
            }
            break;

        case MSG_PROMOTE:
            if (errCode == 0)
            {
                Debug.Log("提升职位成功");
                TongManager.Instance.GuildReq(TongManager.MSG_GET_GUILD_DETAILED_INFO);
                TongManager.Instance.IsShowMyTong = false;
                TongManager.Instance.IsShowDragon = false;
                TongManager.Instance.IsShowSkill  = false;
                TongUIViewManager.Instance.ShowMemberControlPanel(false);
            }
            else
            {
                Debug.Log("提升职位失败 " + errCode);
            }
            break;

        case MSG_DEMOTE:
            if (errCode == 0)
            {
                Debug.Log("减低职位成功");
                TongManager.Instance.GuildReq(TongManager.MSG_GET_GUILD_DETAILED_INFO);
                TongManager.Instance.IsShowMyTong = false;
                TongManager.Instance.IsShowDragon = false;
                TongManager.Instance.IsShowSkill  = false;
                TongUIViewManager.Instance.ShowMemberControlPanel(false);
            }
            else
            {
                Debug.Log("减低职位失败 " + errCode);
            }
            break;

        case MSG_EXPEL:
            if (errCode == 0)
            {
                Debug.Log("开除成功");
                TongManager.Instance.GuildReq(TongManager.MSG_GET_GUILD_DETAILED_INFO);
                TongManager.Instance.IsShowMyTong = false;
                TongManager.Instance.IsShowDragon = false;
                TongManager.Instance.IsShowSkill  = false;
                TongUIViewManager.Instance.ShowMemberControlPanel(false);
            }
            else
            {
                Debug.Log("开除失败 " + errCode);
            }
            break;

        case MSG_DEMISE:
            if (errCode == 0)
            {
                Debug.Log("转让成功");
                TongManager.Instance.GuildReq(TongManager.MSG_GET_GUILD_DETAILED_INFO);
                TongManager.Instance.IsShowMyTong = false;
                TongManager.Instance.IsShowDragon = false;
                TongManager.Instance.IsShowSkill  = false;
                TongUIViewManager.Instance.ShowMemberControlPanel(false);
            }
            else
            {
                Debug.Log("转让失败 " + errCode);
            }
            break;

        case MSG_DISMISS:
            if (errCode == 0)
            {
            }
            break;

        case MSG_THAW:
            if (errCode == 0)
            {
            }
            break;

        case MSG_RECHARGE:
            if (errCode == 0)
            {
            }
            break;

        case MSG_GET_GUILD_MEMBERS:
            if (errCode == 0)
            {
                Debug.Log("获取公会成员列表成功");

                m_listTongMemberData.Clear();
                m_listTongMemberUIData.Clear();

                int count = respInfo.Count;

                for (int i = 0; i < count; ++i)
                {
                    TongUIViewManager.MemberData uidata = new TongUIViewManager.MemberData();
                    TongMemberData data = new TongMemberData();

                    data.dbid       = uint.Parse((string)((LuaTable)(respInfo[(i + 1).ToString()]))["1"]);
                    data.name       = (string)((LuaTable)(respInfo[(i + 1).ToString()]))["2"];
                    data.level      = int.Parse((string)((LuaTable)(respInfo[(i + 1).ToString()]))["3"]);
                    data.jobId      = int.Parse((string)((LuaTable)(respInfo[(i + 1).ToString()]))["4"]);
                    data.power      = int.Parse((string)((LuaTable)(respInfo[(i + 1).ToString()]))["5"]);
                    data.contribute = int.Parse((string)((LuaTable)(respInfo[(i + 1).ToString()]))["6"]);
                    data.date       = int.Parse((string)((LuaTable)(respInfo[(i + 1).ToString()]))["7"]);

                    m_listTongMemberData.Add(data);

                    uidata.name         = data.name;
                    uidata.level        = data.level.ToString();
                    uidata.contribution = data.contribute.ToString();
                    uidata.power        = data.power.ToString();
                    uidata.date         = Utils.GetTime(data.date).ToString("yyyy-MM-dd");

                    switch (data.jobId)
                    {
                    case 1:
                        uidata.position = LanguageData.GetContent(48400);         // "公会长";
                        break;

                    case 2:
                        uidata.position = LanguageData.GetContent(48401);         // "副会长1";
                        break;

                    case 3:
                        uidata.position = LanguageData.GetContent(48402);         // "副会长2";
                        break;

                    case 4:
                        uidata.position = LanguageData.GetContent(48403);         // "副会长3";
                        break;

                    default:
                        uidata.position = LanguageData.GetContent(48404);         // "普通成员";
                        break;
                    }

                    m_listTongMemberUIData.Add(uidata);

                    TongUIViewManager.Instance.SetMemberList(m_listTongMemberUIData);
                    TongUIViewManager.Instance.ShowMyTongMemberList();
                }
            }
            else
            {
                Debug.Log("获取公会成员列表失败 " + errCode);
            }
            break;

        case MSG_GET_DRAGON:
            if (errCode == 0)
            {
            }
            break;

        case MSG_UPGRADE_GUILD_SKILL:
            if (errCode == 0)
            {
            }
            break;

        case MSG_GET_RECOMMEND_LIST:
            if (errCode == 0)
            {
                Debug.Log("获取推荐列表成功");

                m_listTongPresenterUIData.Clear();
                m_listTongPresenterData.Clear();

                for (int i = 0; i < respInfo.Count; ++i)
                {
                    TongPresenterData data = new TongPresenterData();

                    data.dbid  = UInt64.Parse((string)((LuaTable)respInfo[(i + 1).ToString()])["1"]);
                    data.name  = (string)((LuaTable)respInfo[(i + 1).ToString()])["2"];
                    data.level = int.Parse((string)((LuaTable)respInfo[(i + 1).ToString()])["3"]);
                    data.power = int.Parse((string)((LuaTable)respInfo[(i + 1).ToString()])["4"]);

                    TongUIViewManager.PresenterData uidata = new TongUIViewManager.PresenterData();

                    uidata.level = data.level.ToString();
                    uidata.name  = data.name;
                    uidata.power = data.power.ToString();

                    m_listTongPresenterData.Add(data);
                    m_listTongPresenterUIData.Add(uidata);
                }

                TongUIViewManager.Instance.SetRecommendList(m_listTongPresenterUIData);
            }
            else
            {
                Debug.Log("获取推荐列表失败 " + errCode);
            }
            break;

        default:
            MogoGlobleUIManager.Instance.Info("回调消息id未定义 --!");
            break;
        }
    }
示例#17
0
        public static Expression Convert(Type type, string value)
        {
            if (type == typeof(double))
            {
                return(Expression.Constant(Double.Parse(value), type));
            }
            if (type == typeof(Int32))
            {
                return(Expression.Constant(Int32.Parse(value), type));
            }
            if (type == typeof(string))
            {
                return(Expression.Constant(value, type));
            }
            if (type == typeof(DateTime))
            {
                return(Expression.Constant(DateTime.Parse(value), type));
            }
            if (type == typeof(Int16))
            {
                return(Expression.Constant(Int16.Parse(value), type));
            }
            if (type == typeof(Int64))
            {
                return(Expression.Constant(Int64.Parse(value), type));
            }
            if (type == typeof(UInt16))
            {
                return(Expression.Constant(UInt16.Parse(value), type));
            }
            if (type == typeof(UInt32))
            {
                return(Expression.Constant(UInt32.Parse(value), type));
            }
            if (type == typeof(UInt64))
            {
                return(Expression.Constant(UInt64.Parse(value), type));
            }
            if (type == typeof(Single))
            {
                return(Expression.Constant(Single.Parse(value), type));
            }
            if (type == typeof(bool))
            {
                return(Expression.Constant(bool.Parse(value), type));
            }
            if (type == typeof(byte))
            {
                return(Expression.Constant(byte.Parse(value), type));
            }
            if (type == typeof(sbyte))
            {
                return(Expression.Constant(sbyte.Parse(value), type));
            }
            if (type == typeof(Char))
            {
                return(Expression.Constant(Char.Parse(value), type));
            }
            if (type == typeof(TimeSpan))
            {
                return(Expression.Constant(TimeSpan.Parse(value), type));
            }
            if (type == typeof(DateTimeOffset))
            {
                return(Expression.Constant(DateTimeOffset.Parse(value), type));
            }
            if (type == typeof(decimal))
            {
                return(Expression.Constant(decimal.Parse(value), type));
            }
            if (type == typeof(Guid))
            {
                return(Expression.Constant(Guid.Parse(value), type));
            }
            if (type == typeof(double?))
            {
                return(value.ToLower() != "null"
                    ? Expression.Constant(Double.Parse(value), type)
                    : Expression.Constant(null, type));
            }
            if (type == typeof(Int32?))
            {
                return(value.ToLower() != "null"
                    ? Expression.Constant(Int32.Parse(value), type)
                    : Expression.Constant(null, type));
            }
            if (type == typeof(DateTime?))
            {
                return(value.ToLower() != "null"
                    ? Expression.Constant(DateTime.Parse(value), type)
                    : Expression.Constant(null, type));
            }
            if (type == typeof(Int16?))
            {
                return(value.ToLower() != "null"
                    ? Expression.Constant(Int16.Parse(value), type)
                    : Expression.Constant(null, type));
            }
            if (type == typeof(Int64?))
            {
                return(value.ToLower() != "null"
                    ? Expression.Constant(Int64.Parse(value), type)
                    : Expression.Constant(null, type));
            }
            if (type == typeof(UInt16?))
            {
                return(value.ToLower() != "null"
                    ? Expression.Constant(UInt16.Parse(value), type)
                    : Expression.Constant(null, type));
            }
            if (type == typeof(UInt32?))
            {
                return(value.ToLower() != "null"
                    ? Expression.Constant(UInt32.Parse(value), type)
                    : Expression.Constant(null, type));
            }
            if (type == typeof(UInt64?))
            {
                return(value.ToLower() != "null"
                    ? Expression.Constant(UInt64.Parse(value), type)
                    : Expression.Constant(null, type));
            }
            if (type == typeof(Single?))
            {
                return(value.ToLower() != "null"
                    ? Expression.Constant(Single.Parse(value), type)
                    : Expression.Constant(null, type));
            }
            if (type == typeof(bool?))
            {
                return(value.ToLower() != "null"
                    ? Expression.Constant(bool.Parse(value), type)
                    : Expression.Constant(null, type));
            }
            if (type == typeof(byte?))
            {
                return(value.ToLower() != "null"
                    ? Expression.Constant(byte.Parse(value), type)
                    : Expression.Constant(null, type));
            }
            if (type == typeof(sbyte?))
            {
                return(value.ToLower() != "null"
                    ? Expression.Constant(sbyte.Parse(value), type)
                    : Expression.Constant(null, type));
            }
            if (type == typeof(Char?))
            {
                return(value.ToLower() != "null"
                    ? Expression.Constant(Char.Parse(value), type)
                    : Expression.Constant(null, type));
            }
            if (type == typeof(TimeSpan?))
            {
                return(value.ToLower() != "null"
                    ? Expression.Constant(TimeSpan.Parse(value), type)
                    : Expression.Constant(null, type));
            }
            if (type == typeof(DateTimeOffset?))
            {
                return(value.ToLower() != "null"
                    ? Expression.Constant(DateTimeOffset.Parse(value), type)
                    : Expression.Constant(null, type));
            }
            if (type == typeof(decimal?))
            {
                return(value.ToLower() != "null"
                    ? Expression.Constant(decimal.Parse(value), type)
                    : Expression.Constant(null, type));
            }
            if (type == typeof(Guid?))
            {
                return(value.ToLower() != "null"
                    ? Expression.Constant(Guid.Parse(value), type)
                    : Expression.Constant(null, type));
            }
            if (type.IsEnum)
            {
                return(Expression.Constant(Enum.Parse(type, value), type));
            }

            var constructor = type.GetConstructor(new[] { typeof(string) });

            if (constructor == null)
            {
                throw new ArgumentException("constructor error.");
            }
            return(Expression.New(constructor, Expression.Constant(value, typeof(string))));
        }
示例#18
0
        /////////////////////////
        protected int _StringToBytes(int nType, string Value, ref byte[] bValue)
        {
            int i, j, nLen;

            try
            {
                if (nType == 1)
                {
                    bValue = BitConverter.GetBytes(Int16.Parse(Value));
                }
                else if (nType == 2)
                {
                    bValue = BitConverter.GetBytes(UInt16.Parse(Value));
                }
                else if (nType == 3)
                {
                    bValue = BitConverter.GetBytes(Int32.Parse(Value));
                }
                else if (nType == 4)
                {
                    bValue = BitConverter.GetBytes(UInt32.Parse(Value));
                }
                else if (nType == 5)
                {
                    bValue = BitConverter.GetBytes(Int64.Parse(Value));
                }
                else if (nType == 6)
                {
                    bValue = BitConverter.GetBytes(UInt64.Parse(Value));
                }
                else if (nType == 7)
                {
                    bValue = BitConverter.GetBytes(Byte.Parse(Value));
                }
                else if (nType == 8)
                {
                    bValue = BitConverter.GetBytes(SByte.Parse(Value));
                }
                else if (nType == 9)
                {
                    bValue = new byte[Value.Length / 2];
                    nLen   = (Value.Length / 2) * 2;
                    for (i = j = 0; i < nLen; i += 2, j++)
                    {
                        bValue[j] = Convert.ToByte(Value.Substring(i, 2));
                    }
                }
                else if (nType == 10)
                {
                    bValue = new byte[Value.Length / 2];
                    nLen   = (Value.Length / 2) * 2;
                    for (i = j = 0; i < nLen; i += 2, j++)
                    {
                        bValue[j] = (Byte)Convert.ToSByte(Value.Substring(i, 2));
                    }
                }
                else if (nType == 11)
                {
                    bValue = System.Text.Encoding.Default.GetBytes(Value);
                }
                else if (nType == 12)
                {
                    bValue = BitConverter.GetBytes(Single.Parse(Value));
                }
                else if (nType == 13)
                {
                    bValue = BitConverter.GetBytes(Double.Parse(Value));
                }
                else if (nType == 14)
                {
                    Decimal pDecimal = Convert.ToDecimal(Value);
                    byte[]  bDecimal;
                    int[]   nValue = Decimal.GetBits(pDecimal);
                    bValue = new byte[nValue.Length * 4];
                    for (i = 0; i < nValue.Length; i++)
                    {
                        bDecimal = BitConverter.GetBytes(nValue[i]);
                        for (j = 0; j < 4; j++)
                        {
                            bValue[i * 4 + j] = bDecimal[j];
                        }
                    }
                }
                else if (nType == 15)
                {
                    DateTime cDateTime = Convert.ToDateTime(Value);
                    Int64    nValue    = cDateTime.ToBinary();
                    bValue = BitConverter.GetBytes(nValue);
                }
                else if (nType == 16)
                {
                    bValue = BitConverter.GetBytes(Boolean.Parse(Value));
                }
            }
            catch (Exception e)
            {
                m_sErrorInfo = e.Message;
                return(-2);
            }
            return(0);
        }
示例#19
0
    public Boolean runTest()
    {
        Console.WriteLine(s_strTFPath + " " + s_strTFName + " ,for " + s_strComponentBeingTested + "  ,Source ver " + s_strDtTmVer);
        XenoUInt64 xeno = new XenoUInt64();
        UInt64     i    = 0;

        try
        {
            NumberFormatInfo nfi = NumberFormatInfo.CurrentInfo;
            m_strLoc = "Loc_normalTests";
            String testStr = "";
            UInt64 testUI;
            while (xeno.HasMoreValues())
            {
                i = xeno.GetNextValue();
                iCountTestcases++;
                testStr = i.ToString("d");
                testUI  = UInt64.Parse(testStr, NumberStyles.Any, nfi);
                if (testUI != i)
                {
                    Console.WriteLine("Fail! " + testUI + " != " + i);
                    iCountErrors++;
                }
                iCountTestcases++;
                testUI = UInt64.Parse(testStr.PadLeft(1000, ' '), NumberStyles.Any, nfi);
                if (testUI != i)
                {
                    Console.WriteLine("Fail! (pad left)" + testUI + " != " + i);
                    iCountErrors++;
                }
                iCountTestcases++;
                testUI = UInt64.Parse(testStr.PadRight(1000, ' '), NumberStyles.Any, nfi);
                if (testUI != i)
                {
                    Console.WriteLine("Fail! (pad right)" + testUI + " != " + i);
                    iCountErrors++;
                }
                iCountTestcases++;
                testUI = UInt64.Parse(testStr.PadRight(1000, ' ').PadLeft(1000, ' '), NumberStyles.Any, nfi);
                if (testUI != i)
                {
                    Console.WriteLine("Fail! (pad right+left) " + testUI + " != " + i);
                    iCountErrors++;
                }
                try {
                    iCountTestcases++;
                    testStr = i.ToString("E");
                    testUI  = UInt64.Parse(testStr, NumberStyles.AllowCurrencySymbol, nfi);
                    iCountErrors++;
                    Console.WriteLine("Failed! NumberStyle.AllowCurrencySymbol::No exception Thrown! String = '" + testStr + "'");
                }
                catch (FormatException) {}
                catch (Exception e) {
                    iCountErrors++;
                    Console.WriteLine("Failed! Wrong exception: '" + e + "'");
                }
            }
            try {
                iCountTestcases++;
                testStr = i.ToString("E", nfi);
                testUI  = UInt64.Parse(testStr, NumberStyles.AllowLeadingSign);
                iCountErrors++;
                Console.WriteLine("Failed! No exception Thrown! String = '" + testStr + "'");
            }
            catch (FormatException) {}
            catch (Exception e) {
                iCountErrors++;
                Console.WriteLine("Failed! Wrong exception: '" + e + "'");
            }
            try {
                iCountTestcases++;
                UInt64 UI = UInt64.Parse(null, NumberStyles.Any, nfi);
                iCountErrors++;
                Console.WriteLine("Failed! No exception Thrown! String = '" + testStr + "'");
            }
            catch (ArgumentNullException) {}
            catch (Exception e) {
                iCountErrors++;
                Console.WriteLine("Failed! Wrong exception: '" + e + "'");
            }
        }
        catch (Exception exc_general)
        {
            ++iCountErrors;
            Console.WriteLine("Error Err_8888yyy (" + s_strTFAbbrev + ")!  Unexpected exception thrown sometime after m_strLoc==" + m_strLoc + " ,exc_general==" + exc_general);
        }
        Console.Write(Environment.NewLine);
        Console.WriteLine("Total Tests Ran: " + iCountTestcases + " Failed Tests: " + iCountErrors);
        if (iCountErrors == 0)
        {
            Console.WriteLine("paSs.   " + s_strTFPath + " " + s_strTFName + "  ,iCountTestcases==" + iCountTestcases);
            return(true);
        }
        else
        {
            Console.WriteLine("FAiL!   " + s_strTFPath + " " + s_strTFName + "  ,iCountErrors==" + iCountErrors + " ,BugNums?: " + s_strActiveBugNums);
            return(false);
        }
    }
示例#20
0
 public static object GetUnderlyingValue(System.Linq.Expressions.Expression e)
 {
     if (e.Type == typeof(Boolean))
     {
         return(Boolean.Parse(e.ToString()));
     }
     else if (e.Type == typeof(DateTime))
     {
         return(DateTime.Parse(e.ToString()));
     }
     else if (e.Type == typeof(Decimal))
     {
         return(Decimal.Parse(e.ToString()));
     }
     else if (e.Type == typeof(Double))
     {
         return(Double.Parse(e.ToString()));
     }
     else if (e.Type == typeof(Single))
     {
         return(Single.Parse(e.ToString()));
     }
     else if (e.Type == typeof(Byte))
     {
         return(Byte.Parse(e.ToString()));
     }
     else if (e.Type == typeof(SByte))
     {
         return(SByte.Parse(e.ToString()));
     }
     else if (e.Type == typeof(Int16))
     {
         return(Int16.Parse(e.ToString()));
     }
     else if (e.Type == typeof(Int32))
     {
         return(Int32.Parse(e.ToString()));
     }
     else if (e.Type == typeof(Int64))
     {
         return(Int64.Parse(e.ToString()));
     }
     else if (e.Type == typeof(UInt16))
     {
         return(UInt16.Parse(e.ToString()));
     }
     else if (e.Type == typeof(UInt32))
     {
         return(UInt32.Parse(e.ToString()));
     }
     else if (e.Type == typeof(UInt64))
     {
         return(UInt64.Parse(e.ToString()));
     }
     else if (e.Type == typeof(String))
     {
         return(e.ToString());
     }
     else
     {
         return(string.Empty);
     }
 }
示例#21
0
        public List <ExtendedGroupMembersData> GetGroupMembers(string RequestingAgentID, UUID GroupID)
        {
            List <ExtendedGroupMembersData> members = new List <ExtendedGroupMembersData>();

            GroupData group = m_Database.RetrieveGroup(GroupID);

            if (group == null)
            {
                return(members);
            }

            // Unfortunately this doesn't quite work on legacy group data because of a bug
            // that's also being fixed here on CreateGroup. The OwnerRoleID sent to the DB was wrong.
            // See how to find the ownerRoleID a few lines below.
            UUID ownerRoleID = new UUID(group.Data["OwnerRoleID"]);

            RoleData[] roles = m_Database.RetrieveRoles(GroupID);
            if (roles == null)
            {
                // something wrong with this group
                return(members);
            }
            List <RoleData> rolesList = new List <RoleData>(roles);

            // Let's find the "real" ownerRoleID
            RoleData ownerRole = rolesList.Find(r => r.Data["Powers"] == ((long)OwnerPowers).ToString());

            if (ownerRole != null)
            {
                ownerRoleID = ownerRole.RoleID;
            }

            // Check visibility?
            // When we don't want to check visibility, we pass it "all" as the requestingAgentID
            bool checkVisibility = !RequestingAgentID.Equals(UUID.Zero.ToString());

            if (checkVisibility)
            {
                // Is the requester a member of the group?
                bool isInGroup = false;
                if (m_Database.RetrieveMember(GroupID, RequestingAgentID) != null)
                {
                    isInGroup = true;
                }

                if (!isInGroup) // reduce the roles to the visible ones
                {
                    rolesList = rolesList.FindAll(r => (UInt64.Parse(r.Data["Powers"]) & (ulong)GroupPowers.MemberVisible) != 0);
                }
            }

            MembershipData[] datas = m_Database.RetrieveMembers(GroupID);
            if (datas == null || (datas != null && datas.Length == 0))
            {
                return(members);
            }

            // OK, we have everything we need

            foreach (MembershipData d in datas)
            {
                RoleMembershipData[]      rolememberships     = m_Database.RetrieveMemberRoles(GroupID, d.PrincipalID);
                List <RoleMembershipData> rolemembershipsList = new List <RoleMembershipData>(rolememberships);

                ExtendedGroupMembersData m = new ExtendedGroupMembersData();

                // What's this person's current role in the group?
                UUID     selectedRole = new UUID(d.Data["SelectedRoleID"]);
                RoleData selected     = rolesList.Find(r => r.RoleID == selectedRole);

                if (selected != null)
                {
                    m.Title       = selected.Data["Title"];
                    m.AgentPowers = UInt64.Parse(selected.Data["Powers"]);
                }

                m.AgentID       = d.PrincipalID;
                m.AcceptNotices = d.Data["AcceptNotices"] == "1" ? true : false;
                m.Contribution  = Int32.Parse(d.Data["Contribution"]);
                m.ListInProfile = d.Data["ListInProfile"] == "1" ? true : false;

                // Is this person an owner of the group?
                m.IsOwner = (rolemembershipsList.Find(r => r.RoleID == ownerRoleID) != null) ? true : false;

                members.Add(m);
            }

            return(members);
        }
示例#22
0
        public bool LoadHistoryFromDisk(string PathToLoad)
        {
            bool result = false;

            if (!string.IsNullOrEmpty(PathToLoad))
            {
                if (File.Exists(PathToLoad))
                {
                    this.history.Clear();
                    using (StreamReader sr = new StreamReader(PathToLoad, Encoding.UTF8))
                    {
                        GameInfo info  = (GameInfo)DeserializeObject(sr.ReadLine());
                        BitBoard board = new BitBoard();
                        this.history.Add(info, new List <BitBoard>());
                        int amount = 0;
                        if (int.TryParse(sr.ReadLine(), out amount))
                        {
                            for (int step = 0; step < amount; ++step)
                            {
                                board.WhiteKing           = UInt64.Parse(sr.ReadLine());
                                board.WhiteQueens         = UInt64.Parse(sr.ReadLine());
                                board.WhiteRooks          = UInt64.Parse(sr.ReadLine());
                                board.WhiteBishops        = UInt64.Parse(sr.ReadLine());
                                board.WhiteKnights        = UInt64.Parse(sr.ReadLine());
                                board.WhitePawns          = UInt64.Parse(sr.ReadLine());
                                board.EnPassantWhite      = UInt64.Parse(sr.ReadLine());
                                board.BlackKing           = UInt64.Parse(sr.ReadLine());
                                board.BlackQueens         = UInt64.Parse(sr.ReadLine());
                                board.BlackRooks          = UInt64.Parse(sr.ReadLine());
                                board.Blackbishops        = UInt64.Parse(sr.ReadLine());
                                board.BlackKnights        = UInt64.Parse(sr.ReadLine());
                                board.BlackPawns          = UInt64.Parse(sr.ReadLine());
                                board.EnPassantBlack      = UInt64.Parse(sr.ReadLine());
                                board.BalckKingMoved      = sr.ReadLine() == "1" ? true : false;
                                board.WhiteKingMoved      = sr.ReadLine() == "1" ? true : false;
                                board.BlackLeftRookMoved  = sr.ReadLine() == "1" ? true : false;
                                board.BlackRightRookMoved = sr.ReadLine() == "1" ? true : false;
                                board.WhiteLeftRookMoved  = sr.ReadLine() == "1" ? true : false;
                                board.WhiteRightRookMoved = sr.ReadLine() == "1" ? true : false;
                                this.history[info].Add(BitBoard.CopyFigureValues(board));
                            }
                            this.activeColor = int.Parse(sr.ReadLine());
                            //Current state
                            board.WhiteKing           = UInt64.Parse(sr.ReadLine());
                            board.WhiteQueens         = UInt64.Parse(sr.ReadLine());
                            board.WhiteRooks          = UInt64.Parse(sr.ReadLine());
                            board.WhiteBishops        = UInt64.Parse(sr.ReadLine());
                            board.WhiteKnights        = UInt64.Parse(sr.ReadLine());
                            board.WhitePawns          = UInt64.Parse(sr.ReadLine());
                            board.EnPassantWhite      = UInt64.Parse(sr.ReadLine());
                            board.BlackKing           = UInt64.Parse(sr.ReadLine());
                            board.BlackQueens         = UInt64.Parse(sr.ReadLine());
                            board.BlackRooks          = UInt64.Parse(sr.ReadLine());
                            board.Blackbishops        = UInt64.Parse(sr.ReadLine());
                            board.BlackKnights        = UInt64.Parse(sr.ReadLine());
                            board.BlackPawns          = UInt64.Parse(sr.ReadLine());
                            board.EnPassantBlack      = UInt64.Parse(sr.ReadLine());
                            board.BalckKingMoved      = sr.ReadLine() == "1" ? true : false;
                            board.WhiteKingMoved      = sr.ReadLine() == "1" ? true : false;
                            board.BlackLeftRookMoved  = sr.ReadLine() == "1" ? true : false;
                            board.BlackRightRookMoved = sr.ReadLine() == "1" ? true : false;
                            board.WhiteLeftRookMoved  = sr.ReadLine() == "1" ? true : false;
                            board.WhiteRightRookMoved = sr.ReadLine() == "1" ? true : false;
                            this.history[info].Add(BitBoard.CopyFigureValues(board));

                            result = true;
                        }
                        else
                        {
                            throw new Exception("Invalid save file");
                        }
                    }
                }
            }
            return(result);
        }
示例#23
0
 public static ulong ToUInt64Value(this String str, NumberStyles ns)
 {
     return(UInt64.Parse(str, ns));
 }
示例#24
0
        private bool parseHeader(byte[] data, out RequestParameters requestParams)
        {
            requestParams = new RequestParameters();
            var ret = false;

            // Look for the end of the header.
            var headerBuilder = new StringBuilder();

            headerBuilder.Append(Encoding.UTF8.GetString(data));
            var header = headerBuilder.ToString();

            var ind = header.IndexOf("\r\n\r\n");

            if (ind != -1)
            {
                ret = true;
                requestParams.payloadOffset = (ulong)ind + 4;
                header = header.Substring(0, ind);
                var headerLines = header.Split('\n');
                // Remove the '\r'
                for (int i = 0; i < headerLines.Length; ++i)
                {
                    headerLines[i] = headerLines[i].Substring(0, headerLines[i].Length - 1);

                    const string CONTENT_LENGTH_HEADER = "Content-Length: ";
                    const string CONTENT_TYPE_HEADER   = "Content-Type: ";

                    if (i == 0)
                    {
                        // Get the method and the endpoint.
                        var lineParts = headerLines[i].Split();
                        requestParams.method   = lineParts[0];
                        requestParams.endPoint = lineParts[1];
                    }
                    else if (headerLines[i].StartsWith(CONTENT_LENGTH_HEADER))
                    {
                        requestParams.payloadLength =
                            UInt64.Parse(headerLines[i].Substring(CONTENT_LENGTH_HEADER.Length));
                    }
                    else if (headerLines[i].StartsWith(CONTENT_TYPE_HEADER))
                    {
                        var d = getHeaderLineDict(headerLines[i].Substring(CONTENT_TYPE_HEADER.Length));
                        if (d.ContainsKey("multipart/form-data"))
                        {
                            requestParams.boundary = d["boundary"];
                        }
                        else
                        {
                            throw new HttpServerException("Not a \"multipart/form-data\" content");
                        }
                    }
                    Debug.WriteLine("header: " + headerLines[i]);
                }
            }
            else
            {
                ret = false;
            }

            return(ret);
        }
示例#25
0
        internal static object ConvertTo(this object value, Type toType, Func <object> getConverter,
                                         IServiceProvider serviceProvider, out Exception exception)
        {
            exception = null;
            if (value == null)
            {
                return(null);
            }

            if (value is string str)
            {
                //If there's a [TypeConverter], use it
                object converter;
                try
                {                 //minforetriver can fail
                    converter = getConverter?.Invoke();
                }
                catch (Exception e)
                {
                    exception = e;
                    return(null);
                }
                try
                {
                    if (converter is IExtendedTypeConverter xfExtendedTypeConverter)
                    {
                        return(xfExtendedTypeConverter.ConvertFromInvariantString(str, serviceProvider));
                    }
                    if (converter is TypeConverter xfTypeConverter)
                    {
                        return(xfTypeConverter.ConvertFromInvariantString(str));
                    }
                }
                catch (Exception e)
                {
                    exception = e as XamlParseException ?? new XamlParseException($"Type converter failed: {e.Message}", serviceProvider, e);
                    return(null);
                }
                var converterType = converter?.GetType();
                if (converterType != null)
                {
                    var convertFromStringInvariant = converterType.GetRuntimeMethod("ConvertFromInvariantString",
                                                                                    new[] { typeof(string) });
                    if (convertFromStringInvariant != null)
                    {
                        try
                        {
                            return(convertFromStringInvariant.Invoke(converter, new object[] { str }));
                        }
                        catch (Exception e)
                        {
                            exception = new XamlParseException("Type conversion failed", serviceProvider, e);
                            return(null);
                        }
                    }
                }
                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
                try
                {
                    if (toType.GetTypeInfo().IsEnum)
                    {
                        return(Enum.Parse(toType, str, ignoreCase));
                    }
                    if (toType == typeof(SByte))
                    {
                        return(SByte.Parse(str, CultureInfo.InvariantCulture));
                    }
                    if (toType == typeof(Int16))
                    {
                        return(Int16.Parse(str, CultureInfo.InvariantCulture));
                    }
                    if (toType == typeof(Int32))
                    {
                        return(Int32.Parse(str, CultureInfo.InvariantCulture));
                    }
                    if (toType == typeof(Int64))
                    {
                        return(Int64.Parse(str, CultureInfo.InvariantCulture));
                    }
                    if (toType == typeof(Byte))
                    {
                        return(Byte.Parse(str, CultureInfo.InvariantCulture));
                    }
                    if (toType == typeof(UInt16))
                    {
                        return(UInt16.Parse(str, CultureInfo.InvariantCulture));
                    }
                    if (toType == typeof(UInt32))
                    {
                        return(UInt32.Parse(str, CultureInfo.InvariantCulture));
                    }
                    if (toType == typeof(UInt64))
                    {
                        return(UInt64.Parse(str, CultureInfo.InvariantCulture));
                    }
                    if (toType == typeof(Single))
                    {
                        return(Single.Parse(str, CultureInfo.InvariantCulture));
                    }
                    if (toType == typeof(Double))
                    {
                        return(Double.Parse(str, CultureInfo.InvariantCulture));
                    }
                    if (toType == typeof(Boolean))
                    {
                        return(Boolean.Parse(str));
                    }
                    if (toType == typeof(TimeSpan))
                    {
                        return(TimeSpan.Parse(str, CultureInfo.InvariantCulture));
                    }
                    if (toType == typeof(DateTime))
                    {
                        return(DateTime.Parse(str, CultureInfo.InvariantCulture));
                    }
                    if (toType == typeof(Char))
                    {
                        Char.TryParse(str, out var 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));
                    }
                }
                catch (FormatException fe)
                {
                    exception = fe;
                    return(null);
                }
            }

            //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);
        }
示例#26
0
            public Take1()
            {
                var lines = File.ReadAllText(filename).Trim().Split(new string[] { "\r\n" }, StringSplitOptions.None);

                nums = lines.Select(x => UInt64.Parse(x)).ToList();
            }
示例#27
0
        // TODO: write a generic method for each Primitive type, in order to avoid boxing to object.
        internal static Object TranscodeStringToPrimitiveObject(string s, L3TypeManager typeManager)
        {
            TypeCode tc = (TypeCode)typeManager.TypeIndex;

#if DEBUG
            if ((int)tc < (int)TypeCode.Boolean)
            {
                throw new ArgumentException(ErrorMessages.GetText(9));                //"data is not a Primitive type");
            }
#endif
            switch (tc)
            {
            case TypeCode.Boolean:
                return(Boolean.Parse(s));

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

            case TypeCode.Char:
#if SILVERLIGHT || PORTABLE
                return(s[0]);
#else
                return(Char.Parse(s));
#endif
            case TypeCode.DateTime:
                return(Tools.DateTimeFromTicksAndKind(ulong.Parse(s)));

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

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

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

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

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

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

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

            case TypeCode.String:
                return(s);

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

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

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

            default:
                throw new Exception();
            }
        }
示例#28
0
        public List <urlInfo> GetIndexList(string url, int pg, List <urlInfo> list)
        {
            HttpHelper http = new HttpHelper();

            http.DefaultHeadInfo.timeout           = 100000;
            http.DefaultHeadInfo.cookie_collection = new System.Net.CookieContainer();
            Uri uri = new Uri(url + pg);

            http.DefaultHeadInfo.cookie_collection.Add(uri, new System.Net.Cookie("t", "5b5f39b0ce4c5797e6f2e5a5abfdeeb0"));
            http.DefaultHeadInfo.cookie_collection.Add(uri, new System.Net.Cookie("_tb_token_", "vE0SSZDAO7Fe"));
            http.DefaultHeadInfo.cookie_collection.Add(uri, new System.Net.Cookie("cookie2", "fd45fc19ff278287a315b52e19b91ca6"));
            http.DefaultHeadInfo.header.Add("Accept-Encoding", " gzip, deflate, sdch, br");
            var page = http.Get(url + pg);
            int a    = 0;

            if (page.StatusCode != System.Net.HttpStatusCode.OK)
            {
                if (a > 5)
                {
                    return(null);
                }
                System.Threading.Thread.Sleep(2000);
                page = http.Get(url + pg);
            }
            HtmlDocument hd = new HtmlDocument();

            hd.LoadHtml(page.Html.Replace("\\", ""));
            var nodes = hd.DocumentNode.SelectNodes("//div[@class='J_TItems']//div[@class='item4line1']");

            if (nodes == null)
            {
                nodes = hd.DocumentNode.SelectNodes("//div[@class='J_TItems']//div[@class='item5line1']");
                if (nodes == null)
                {
                    return(null);
                }
            }
            for (int i = 0; i < nodes.Count - 2; i++)
            {
                var node_line = nodes[i].SelectNodes("./dl");
                for (int j = 0; j < node_line.Count; j++)
                {
                    var uf = new urlInfo();
                    uf.dataId     = UInt64.Parse(node_line[j].Attributes["data-id"].Value);
                    uf.name       = node_line[j].SelectSingleNode("./dd[@class='detail']/a").InnerText;
                    uf.detailUrl  = "http:" + node_line[j].SelectSingleNode("./dd[@class='detail']/a").Attributes["href"].Value;
                    uf.indexPrice = double.Parse(node_line[j].SelectSingleNode("./dd[@class='detail']/div[@class='attribute']/div[@class='cprice-area']//span[2]").InnerText);
                    try
                    {
                        uf.totalSales   = int.Parse(node_line[j].SelectSingleNode("./dd[@class='detail']/div[@class='attribute']/div[@class='sale-area']//span[1]").InnerText);
                        uf.indexComment = uint.Parse(Regex.Match(node_line[j].SelectSingleNode("./dd[@class='rates']/div[@class='title']").InnerText, @"\d+").Value);
                    }
                    catch { }
                    list.Add(uf);
                }
            }
            if (first)
            {
                var pgStr   = hd.DocumentNode.SelectSingleNode("//div[@class='filter clearfix J_TFilter']/p/b[@class='ui-page-s-len']").InnerText.Split('/')[1];
                int pgNodes = int.Parse(pgStr);
                if (pgStr != null)
                {
                    Console.WriteLine("共有 {0} 页", pgNodes);
                    first = false;
                    for (int un = 2; un <= pgNodes; un++)
                    {
                        System.Threading.Thread.Sleep(1000);
                        GetIndexList(url, un, list);
                        Console.WriteLine("第{0}页", un);
                    }
                }
            }
            return(list);
        }
        public static string HexParaBinario(string hexValue, int tamanho)
        {
            var number = UInt64.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);

            return(IntParaBinario(number.ToString(), tamanho));
        }
示例#30
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);
        }