long.Parse(string)

Here are the examples of the csharp api long.Parse(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1105 Examples 7

19 View Source File : VkTracksService.cs
License : Apache License 2.0
Project Creator : artemshuba

public async Task<bool> ReorderTracks(IAudio track, string beforeTrackId, string afterTrackId)
        {
            return await _vk.Audio.Reorder(long.Parse(track.Id), long.Parse(afterTrackId), long.Parse(beforeTrackId));
        }

19 View Source File : WebAccountDataRepository.cs
License : GNU General Public License v3.0
Project Creator : atomex-me

public void AddData(string data)
        {
            List<BrowserDBData> dbData = JsonConvert.DeserializeObject<List<BrowserDBData>>(data);
            foreach (var dbObj in dbData)
            {
                if (dbObj.type == AvailableDataType.WalletAddress.ToString())
                {
                    _addresses[dbObj.id] =
                        _bsonMapper.ToObject<WalletAddress>(
                            BsonSerializer.Deserialize(Convert.FromBase64String(dbObj.data)));
                }
                else if (dbObj.type == AvailableDataType.Transaction.ToString())
                {
                    string[] parsedId = dbObj.id.Split(Convert.ToChar("/"));
                    string id = parsedId[0];
                    string currency = parsedId[1];

                    BsonDoreplacedent bd = BsonSerializer.Deserialize(Convert.FromBase64String(dbObj.data));
                    _transactions[$"{id}:{currency}"] = (IBlockchainTransaction) _bsonMapper.ToObject(doc: bd,
                        type: _currencies.GetByName(currency).TransactionType);
                }
                else if (dbObj.type == AvailableDataType.Swap.ToString())
                {
                    _swaps[long.Parse(dbObj.id)] =
                        _bsonMapper.ToObject<Swap>(
                            BsonSerializer.Deserialize(Convert.FromBase64String(dbObj.data)));
                }
                else if (dbObj.type == AvailableDataType.Output.ToString())
                {
                    string[] parsedId = dbObj.id.Split(Convert.ToChar("/"));
                    string id = parsedId[0];
                    string currency = parsedId[1];
                    string address = parsedId[2];

                    BsonDoreplacedent bd = BsonSerializer.Deserialize(Convert.FromBase64String(dbObj.data));
                    BitcoinBasedConfig BtcBasedCurrency = _currencies.Get<BitcoinBasedConfig>(currency);
                    ITxOutput output =
                        (ITxOutput) _bsonMapper.ToObject(doc: bd, type: BtcBasedCurrency.OutputType());

                    _outputs[id] = new OutputEnreplacedy {Output = output, Currency = currency, Address = address};
                }
                else if (dbObj.type == AvailableDataType.Order.ToString())
                {
                    _orders[dbObj.id] =
                        _bsonMapper.ToObject<Order>(
                            BsonSerializer.Deserialize(Convert.FromBase64String(dbObj.data)));
                }

                else if (dbObj.type == AvailableDataType.TezosTokenAddress.ToString())
                {
                    _tezosTokensAddresses[dbObj.id] = _bsonMapper.ToObject<WalletAddress>(
                        BsonSerializer.Deserialize(Convert.FromBase64String(dbObj.data)));
                }

                else if (dbObj.type == AvailableDataType.TezosTokenContract.ToString())
                {
                    _tezosTokensContracts[dbObj.id] =
                        _bsonMapper.ToObject<TokenContract>(
                            BsonSerializer.Deserialize(Convert.FromBase64String(dbObj.data)));
                }

                else if (dbObj.type == AvailableDataType.TezosTokenTransfer.ToString())
                {
                    _tezosTokensTransfers[dbObj.id] =
                        _bsonMapper.ToObject<TokenTransfer>(
                            BsonSerializer.Deserialize(Convert.FromBase64String(dbObj.data)));
                }
            }
        }

19 View Source File : HardwareInfo.cs
License : Apache License 2.0
Project Creator : alexyakunin

public static int? GetRamSize()
        {
            try {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {
                    var cmd = Command.Run("wmic", "computersystem", "get", "TotalPhysicalMemory");
                    var stringValue = cmd.StandardOutput.GetLines().SkipEmpty().Last().Trim();
                    return (int) Math.Round(long.Parse(stringValue) / Sizes.GB);
                }
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) {
                    var cmd = Command.Run("cat", "/proc/meminfo");
                    var stringValue = cmd.StandardOutput.GetLines().SkipEmpty()
                        .ToPairs().Single(p => p.Name == "MemTotal")
                        .Value.Split(' ', StringSplitOptions.RemoveEmptyEntries).First();
                    return (int) Math.Round(long.Parse(stringValue) * Sizes.KB / Sizes.GB);
                }
                if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) {
                    var cmd = Command.Run("system_profiler", "SPHardwareDataType");
                    var stringValue = cmd.StandardOutput.GetLines().SkipEmpty()
                        .ToPairs().Single(p => p.Name == "Memory")
                        .Value.Split(' ', StringSplitOptions.RemoveEmptyEntries).First();
                    return (int) Math.Round(double.Parse(stringValue));
                }
                return null;
            }
            catch {
                return null;
            }
        }

19 View Source File : DBCFile.cs
License : MIT License
Project Creator : Aptiv-WLL

private void Parse(string s)
        {
            NS_Lib = new Dictionary<string, int>();
            BS_Lib = new Dictionary<string, int>();
            MsgSendTypes = new Dictionary<int, string>();
            ecus = new Dictionary<string, DBCECU>();
            messages = new Dictionary<string, DBCMessage>();
            attributes = new Dictionary<string, Dictionary<string, List<string>>>();
            signalGroups = new Dictionary<string, List<IDBCSignal>>();

            #region --- Strings for matches ---
            string NS = @"NS_[\t ]*:[\r\t ]*\n(\t[\w]+[\r\t ]*\n)*";
            string BU = @"BU_\s *:(\s +.*)*";
            string BOline = @"BO_\s+\d+\s+\w+:\s*\d+\s+\w+";
            string SGline = @"SG_\s+\w+\s*\w*\s*:\s*\d+\|\[email protected][01][+-]\s+\([\d.-]*,[\d.-]*\)\s+\[.*\|.*\]\s+"".*""(\s+\w+,*\s*)+";
            string BO = BOline + @"\s+(" + SGline + @")*";
            string CM = @"CM_\s+\w+\s+\w+(\s+\w+)*\s+""([^""]*)*""";
            string BA_DEF = @"BA_DEF_\s+.*;";
            string BA_DEF_DEF = @"BA_DEF_DEF_\s+.*;";
            string BA = @"BA_\s+.*;";
            string VAL = @"VAL_\s+.*;";
            //string SIG_GROUP = @"";
            #endregion

            // init some values
            string[] tmp = new string[0];
            int i = -1, DataLength = 0;
            string ECU_Name = "", Msg_Name = "", Snl_name = "", MsgIDHex = "";
            string AttributeName = "", AttributeValue = "";
            try
            {
                #region --- New Symbols ---
                foreach (Match m in Regex.Matches(s, NS))
                {
                    // Remove NS_ and split by whitespace
                    string[] keys = m.Value.Split('\n');

                    // Add to NS lib if not already there
                    for (int ki = 1; ki < keys.Length; ki++)
                        if (!NS_Lib.ContainsKey(keys[ki]) && !string.IsNullOrEmpty(keys[ki]))
                            NS_Lib.Add(keys[ki], NS_Lib.Count);
                }
                #endregion

                #region --- ECUs ---
                foreach (Match m in Regex.Matches(s, BU))
                {
                    // Remove BU_ and split by whitespace
                    tmp = Regex.Split(m.Value.Replace("BU_", ""), @"\s+");

                    // Add to ECU libs
                    foreach (string str in tmp)
                        if (!ecus.ContainsKey(str))
                        {
                            //ECU_Lib.Add(str, ECU_Lib.Count);
                            ecus.Add(str, new DBCECU(tmp[i]));
                        }
                }
                #endregion

                #region --- Messages & Signals ---
                foreach (Match m in Regex.Matches(s, BO))
                {
                    // Deal with Message line: BO_ Tag | Message ID | Message Name | Message Length (bytes) | ECU
                    string messageLine = Regex.Match(m.Value, BOline).Value;

                    //split by whitespace
                    tmp = Regex.Split(messageLine.Replace(":", ""), @"\s+");

                    // Message Attributes
                    ECU_Name = tmp[4];
                    Msg_Name = tmp[2];
                    int midLen = tmp[1].Length > 4 ? 4 : 2;
                    MsgIDHex = "0x" + Convert.ToInt64(tmp[1]).ToString("X3");
                    DataLength = Convert.ToInt32(tmp[3]);


                    //If ECU doesn't exist, create it
                    if (!ecus.ContainsKey(ECU_Name))
                        ecus.Add(ECU_Name, new DBCECU(ECU_Name));

                    // Add a new message
                    var newMessage = new DBCMessage(midLen + DataLength, ecus[ECU_Name], MsgIDHex, Msg_Name);
                    messages.Add(MsgIDHex, newMessage);
                    
                    // Add message to Messages dictionary in current ECU
                    if(!ecus[ECU_Name].Messages.ContainsKey(MsgIDHex)) {
                        ecus[ECU_Name].Messages[MsgIDHex] = (IDBCMessage)newMessage; 
                    }
                    
                    // Deal with signal line:
                    // SG_ Tag | Signal ID | Optional Multiplexer | Start Bit + Length (bits) + Byte Direction | (Factor, Offset) | Physical Range [min,max] | Physical Units | Response ECU
                    foreach (Match sig in Regex.Matches(m.Value, SGline))
                    {
                        int multiplexer = 0; // 1 if there is a multiplexer, 0 if not
                        if (Regex.IsMatch(sig.Value, @"\w+\s+\w+\s+\w+\s*:"))
                            multiplexer = 1;

                        tmp = Regex.Split(Regex.Replace(sig.Value, @"[\(\)\[\]\|""@,:]", " "), @"\s+");

                        Snl_name = tmp[1];

                        // Signal Attributes
                        int startBit = Convert.ToInt32(tmp[2 + multiplexer]);
                        int length = Convert.ToInt32(tmp[3 + multiplexer]);
                        IntDescriptor descriptor = (tmp[4 + multiplexer][1] == '+') ? IntDescriptor.Unsigned : IntDescriptor.Signed;
                        ByteOrder byteOrder;
                        if (tmp[4 + multiplexer][0] == '1')
                            byteOrder = ByteOrder.Intel;
                        else byteOrder = ByteOrder.Motorola;
                        double factor = Convert.ToDouble(tmp[5 + multiplexer], System.Globalization.CultureInfo.InvariantCulture);
                        double offset = Convert.ToDouble(tmp[6 + multiplexer], System.Globalization.CultureInfo.InvariantCulture);
                        double physMin = Convert.ToDouble(tmp[7 + multiplexer], System.Globalization.CultureInfo.InvariantCulture);
                        double physMax = Convert.ToDouble(tmp[8 + multiplexer], System.Globalization.CultureInfo.InvariantCulture);
                        string physUnits = tmp[9 + multiplexer];

                        //If physMin and physMax are both 0, then physMax is as high as the largest bitvalue
                        physMax = (physMin == 0 && physMax == 0) ? (1 << length) : physMax;

                        // These values should be 0 and (2 << length - 1)
                        ulong normMin = (ulong)((physMin - offset) / factor);
                        ulong normMax = (ulong)((physMax - offset) / factor);
                        double res = (physMax - physMin) / (normMax - normMin);
                        if (double.IsInfinity(res) || double.IsNaN(res))
                            res = 1;

                        // Responce ECUs
                        for (i = 10 + multiplexer; i < tmp.Length; i++)
                        {
                            if (!ecus.ContainsKey(tmp[i]))
                                ecus.Add(tmp[i], new DBCECU(tmp[i]));
                            if (!ecus[tmp[i]].RxMessages.ContainsKey(MsgIDHex))
                                ecus[tmp[i]].RxMessages.Add(MsgIDHex, messages[MsgIDHex]);
                        }

                        int old = startBit;

                        // TODO: verify this is needed.
                        // account for motorola being inverse
                        if (byteOrder == ByteOrder.Motorola)
                        {
                            int newStartBit = startBit;
                            for (i = 1; i < length; i++)
                            {
                                if (newStartBit % 8 == 0)
                                    newStartBit += 15;
                                else
                                    newStartBit -= 1;
                            }
                            startBit = newStartBit;
                        }

                        // Add a new signal
                        messages[MsgIDHex].Signals.Add(Snl_name, new DBCSignal(ecus[ECU_Name],
                            messages[MsgIDHex], (uint)startBit, Snl_name, (uint)length, 0, 0,
                            physMax, physMin, normMax, normMin, res, physUnits, descriptor,
                            byteOrder, offset, sig.Value));
                    }
                }




                #endregion

                #region --- Functionality Description (comments) ---
                foreach (Match m in Regex.Matches(s, CM))
                {
                    /*  Note:
                     *  Only existing signals can have comments parsed for them,
                     *  there is no way to generate a new signal or message from
                     *  a comment statement. */

                    if (Regex.IsMatch(m.Value, @"SG_"))
                    {
                        tmp = Regex.Split(m.Value, @"\s+");
                        MsgIDHex = "0x" + Convert.ToInt64(tmp[2]).ToString("X3");
                        if (messages.ContainsKey(MsgIDHex))
                        {
                            Snl_name = tmp[3];
                            if (messages[MsgIDHex].Signals.ContainsKey(Snl_name))
                            {
                                string function = "";
                                for (i = 4; i < tmp.Length; i++)
                                    function += (tmp[i] + " ").Replace("\"", "");
                                ((DBCSignal)messages[MsgIDHex].Signals[Snl_name]).Function = function;
                            }
                        }
                    }
                }
                #endregion

                #region --- Base Attribute Definitions ---
                foreach (Match m in Regex.Matches(s, BA_DEF))
                {
                    string attributeName;
                    string attributeType;
                    string tag = "Definition";
                    List<string> attributeSettings = new List<string>();
                    tmp = Regex.Split(m.Value, @"\s+");

                    if (Regex.IsMatch(m.Value, @"BU_"))
                    {
                        attributeName = tmp[2].Replace("\"", "");
                        attributeType = tmp[3];
                        for (int j = 4; j < tmp.Length; j++)
                            attributeSettings.Add(tmp[j].Replace(";", ""));
                    }
                    else if (Regex.IsMatch(m.Value, @"BO_"))
                    {
                        attributeName = tmp[2].Replace("\"", "");
                        attributeType = tmp[3];
                        for (int j = 4; j < tmp.Length; j++)
                            attributeSettings.Add(tmp[j].Replace(";", ""));

                        // OG code... fix in future
                        switch (attributeName)
                        {
                            case "GenMsgSendType":  //Message send type(cyclic, spontaneous, etc..)
                                string[] values = tmp[tmp.Length - 1].Split(',');
                                for (int k = 0; k < values.Length; k++)
                                {
                                    //k is Enum int value, values[k] is string it represents
                                    MsgSendTypes.Add(k, values[k].Replace("\"", "").Replace(";", ""));
                                }
                                break;
                            case "GenMsgCycleTime":
                                break;
                            case "GenMsgStartDelayTime":
                                break;
                            case "GenMsgDelayTime":
                                break;
                            default:
                                break;
                        }
                    }
                    else if (Regex.IsMatch(m.Value, @"SG_"))
                    {
                        attributeName = tmp[2].Replace("\"", "");
                        attributeType = tmp[3];
                        for (int j = 4; j < tmp.Length; j++)
                            attributeSettings.Add(tmp[j].Replace(";", ""));
                    }
                    else
                    {
                        // extract info
                        attributeName = tmp[1].Replace("\"", "");
                        attributeType = tmp[2];
                        for (int j = 3; j < tmp.Length; j++)
                            attributeSettings.Add(tmp[j].Replace(";", ""));

                        // add to dict
                        if (attributes.ContainsKey(attributeName))
                        {
                            if (attributes[attributeName].ContainsKey(tag))
                                attributes[attributeName][tag].Concat(attributeSettings);
                            else
                                attributes[attributeName].Add(tag, attributeSettings);
                        }
                        else
                        {
                            attributes.Add(attributeName, new Dictionary<string, List<string>>());
                            attributes[attributeName].Add(tag, attributeSettings);
                        }
                    }

                }
                #endregion

                #region --- Base Attribute Definitions Defaults ---
                foreach (Match m in Regex.Matches(s, BA_DEF_DEF))
                {
                    string tag = "Default";
                    tmp = Regex.Split(Regex.Replace(m.Value, @"[;""]", ""), @"\s+");
                    if (tmp.Length < 3)
                        continue;
                    string attr = tmp[1];
                    string val = tmp[2];

                    if (attributes.ContainsKey(attr))
                    {
                        if (attributes[attr].ContainsKey(tag))
                            attributes[attr][tag].Add(val);
                        else
                            attributes[attr].Add(tag, new List<string>() { val });
                    }
                    else
                        attributes.Add(attr, new Dictionary<string, List<string>>() { { tag, new List<string>() { val } } });
                }
                #endregion

                #region --- Base Attributes ---
                foreach (Match m in Regex.Matches(s, BA))
                {
                    string tag = "Setting";
                    string attributeName;
                    string attributeValue;
                    List<string> attributeSettings = new List<string>();

                    //modified regex check to ignore spaces inside of quotes
                    tmp = Regex.Split(m.Value, "(?<=^[^\"]*(?:\"[^\"]*\"[^\"]*)*) (?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");

                    if (Regex.IsMatch(tmp[2], @"BO_"))
                    {
                        MsgIDHex = "0x" + Convert.ToInt64(tmp[3]).ToString("X3");

                        //Handle attributes if MsgID exists
                        if (messages.ContainsKey(MsgIDHex))
                        {
                            attributeName = tmp[1].Replace("\"", "");
                            attributeValue = tmp[4].Replace(";", "");
                            switch (attributeName)
                            {
                                case "GenMsgCycleTime": //Cycle time
                                    messages[MsgIDHex].CycleTime = uint.Parse(attributeValue);
                                    break;
                                case "GenMsgSendType": //Launch type(cyclic, spontaneous, etc.)
                                    messages[MsgIDHex].LaunchType = MsgSendTypes[int.Parse(attributeValue)];
                                    break;
                                case "GenMsgDelayTime":
                                    messages[MsgIDHex].DelayTime = int.Parse(attributeValue);
                                    break;
                            }
                        }
                    }
                    else if (Regex.IsMatch(m.Value, @"SG_"))
                    {
                        MsgIDHex = "0x" + Convert.ToInt64(tmp[3]).ToString("X3");
                        Snl_name = tmp[4];

                        AttributeName = tmp[1].Replace("\"", "");
                        AttributeValue = "";
                        for (i = 5; i < tmp.Length; i++)
                            AttributeValue += (tmp[i] + " ").Replace("\"", "").Replace(";", "");

                        // Check and add
                        if (messages.ContainsKey(MsgIDHex) &&
                            messages[MsgIDHex].Signals.ContainsKey(Snl_name))
                            ((DBCSignal)messages[MsgIDHex].Signals[Snl_name]).Attributes.Add(AttributeName, AttributeValue);
                    }
                    else
                    {
                        if (attributes.ContainsKey(tmp[1]))
                        {
                            if (attributes[tmp[1]].ContainsKey(tag))
                                attributes[tmp[1]][tag].Add(tmp[2]);
                            else
                                attributes[tmp[1]].Add(tag, new List<string>() { tmp[2] });
                        }
                        else
                            attributes.Add(tmp[1], new Dictionary<string, List<string>>() { { tag, new List<string>() { tmp[2] } } });
                        //break;
                    }
                }
                #endregion

                #region --- Specified Signal Values ---

                foreach (Match m in Regex.Matches(s, VAL))
                {
                    tmp = Regex.Split(m.Value, @"\s+");
                    MsgIDHex = "0x" + Convert.ToInt64(tmp[1]).ToString("X3");
                    Snl_name = tmp[2];

                    foreach (Match val in Regex.Matches(m.Value, "\\d+\\s+\".*?\""))
                    {
                        tmp = Regex.Split(val.Value.Replace("\"", " "), @"\s+");

                        long key = long.Parse(tmp[0]);
                        tmp[0] = "";
                        string specifiedValue = string.Join<string>(" ", tmp).Trim();

                        // Check and add
                        if (messages.ContainsKey(MsgIDHex) &&
                            messages[MsgIDHex].Signals.ContainsKey(Snl_name))
                        {
                            if (messages[MsgIDHex].Signals[Snl_name].SpecifiedValues.ContainsKey(key))
                                ((DBCSignal)messages[MsgIDHex].Signals[Snl_name]).SpecifiedValues[key] = specifiedValue;
                            else
                                ((DBCSignal)messages[MsgIDHex].Signals[Snl_name]).SpecifiedValues.Add(key, specifiedValue);
                        }
                    }
                }

                #endregion
            }
            catch (DatabaseLoadingException)
            {
                throw;
            }
            /*catch (Exception e)
            {
                throw new DatabaseLoadingException("Parsing of the given DBC file failed.", e, this, "");
            }*/

            #region old code section for Signal Groups
            /* 
                OG SIG_GROUP_ parsing below

                        #region SIG_GROUP_ (Signal Groupings)
                        case "SIG_GROUP_":

                            // Remove the tag and use space as a delimiter
                            tmp = AcquireValues(str);

                            MsgIDHex = "0x" + Convert.ToInt64(tmp[1]).ToString("X3");
                            ECU_name = MsgID_to_ECUname[MsgIDHex];
                            string Group_name = tmp[2];

                            for (int itm = 5; itm < tmp.Length; itm++)
                            {
                                Snl_name = tmp[itm];
                                if (SignalGroups.ContainsKey(Group_name))
                                    SignalGroups[Group_name].Add(Messages[MsgIDHex].Signals[Snl_name]);
                                else
                                    SignalGroups.Add(Group_name, new List<IDBCSignal>() { Messages[MsgIDHex].Signals[Snl_name] });
                            }

                            break;
                        #endregion
            } 
            */
            #endregion
        }

19 View Source File : VMMap.cs
License : GNU Lesser General Public License v3.0
Project Creator : Alois-xx

internal void MapDataFromLine(VMMapData lret, string line)
        {
            string[] parts = SplitLine(line);
            if (parts.Length >= 11)
            {
                string name = parts[0];
                if (RowMapper.TryGetValue(parts[0], out Action<long, long, long, VMMapData> mapper))
                {
                    if( parts[1] == "") // Page table data can sometimes be empty
                    {
                        return;
                    }
                    long reserved = long.Parse(parts[1]);
                    long.TryParse(parts[2], out long committed);
                    long.TryParse(parts[10], out long largestBlock);
                    mapper(reserved, committed, largestBlock, lret);
                }
            }
        }

19 View Source File : FunctionCubeHandler.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel

private static void HandleUseCube(GameSession session, PacketReader packet)
    {
        string coord = packet.ReadUnicodeString();
        byte unk = packet.ReadByte();

        string coordHexa = long.Parse(coord.Split('_')[1]).ToString("X2");
        if (coordHexa.Length == 5)
        {
            coordHexa = "0" + coordHexa;
        }
        CoordB coordB = CoordB.From((sbyte) Convert.ToByte(coordHexa[4..], 16),
                                    (sbyte) Convert.ToByte(coordHexa.Substring(2, 2), 16),
                                    (sbyte) Convert.ToByte(coordHexa[..2], 16));

        IFieldObject<Cube> fieldCube = session.FieldManager.State.Cubes.FirstOrDefault(cube => cube.Value.Coord == coordB.ToFloat()).Value;
        if (fieldCube is null)
        {
            return;
        }

        switch (fieldCube.Value.Item.HousingCategory)
        {
            case ItemHousingCategory.Ranching:
            case ItemHousingCategory.Farming:
                int objectId = ItemMetadataStorage.GetObjectId(fieldCube.Value.Item.Id);
                int recipeId = FunctionCubeMetadataStorage.GetRecipeId(objectId);
                GatheringHelper.HandleGathering(session, recipeId, out int numDrops);
                session.FieldManager.BroadcastPacket(FunctionCubePacket.UpdateFunctionCube(coordB, 1, 1));
                if (numDrops > 0)
                {
                    session.Send(FunctionCubePacket.SuccessLifeSkill(session.Player.CharacterId, coordB, 1));
                }
                else
                {
                    session.Send(FunctionCubePacket.FailLikeSkill(session.Player.CharacterId, coordB));
                }
                session.FieldManager.BroadcastPacket(FunctionCubePacket.UpdateFunctionCube(coordB, 2, 1));
                break;
            default:
                Cube cube = fieldCube.Value;
                cube.InUse = !cube.InUse;

                session.FieldManager.BroadcastPacket(FunctionCubePacket.UpdateFunctionCube(coordB, cube.InUse ? 1 : 0, 1));
                session.FieldManager.BroadcastPacket(FunctionCubePacket.UseFurniture(session.Player.CharacterId, coordB, cube.InUse));
                break;
        }
    }

19 View Source File : SocietyMusicViewModel.cs
License : Apache License 2.0
Project Creator : artemshuba

private async Task LoadTracks(string playlistId = null, bool withoutPlaylistOnly = false)
        {
            TaskStarted("tracks");

            try
            {
                var albumId = playlistId != null ? long.Parse(playlistId) : 0;
                var tracks = await _tracksService.GetTracks(userId: -Society.Id, albumId: albumId);
                if (tracks == null)
                    return;

                if (withoutPlaylistOnly)
                    tracks = tracks?.Where(t => t.PlaylistId == 0).ToList();

                Tracks = new ObservableCollection<IAudio>(tracks);
            }
            catch (VkAccessDeniedException)
            {
                TaskError("tracks", Resources.GetStringByKey("Society_TracksDisabled"));
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Unable to load society tracks");
            }
            finally
            {
                TaskFinished("tracks");
            }
        }

19 View Source File : Int64Data.cs
License : GNU Affero General Public License v3.0
Project Creator : aianlinb

public override void FromString(string value) {
			Value = long.Parse(value.TrimEnd('L'));
		}

19 View Source File : ConfigUtility.cs
License : GNU General Public License v3.0
Project Creator : autodotua

public static long GetLong(string key, long defaultValue)
        {
            bool hasValue = configs.TryGetValue(key, out string value);
            return hasValue ? long.Parse(value) : defaultValue;
        }

19 View Source File : SimpleEventListener.cs
License : MIT License
Project Creator : aishang2015

protected override void OnEventWritten(EventWrittenEventArgs eventData)
        {
            if (!eventData.EventName.Equals("EventCounters"))
            {
                return;
            }

            for (int i = 0; i < eventData.Payload.Count; ++i)
            {
                if (eventData.Payload[i] is IDictionary<string, object> eventPayload)
                {
                    var (counterName, counterValue, counterUnit) = GetRelevantMetric(eventPayload);
                    switch (counterName)
                    {
                        case "cpu-usage":
                            _hub.Clients.All.HandleCpuUsage(counterValue);
                            break;
                        case "working-set":
                            _hub.Clients.All.HandleWorkingSet(counterValue);
                            break;

                        case "gc-heap-size":
                            _hub.Clients.All.HandleGCHeapSize(counterValue);
                            break;
                        case "gen-0-gc-count":
                            _hub.Clients.All.HandelGCCount(0, int.Parse(counterValue));
                            break;
                        case "gen-1-gc-count":
                            _hub.Clients.All.HandelGCCount(1, int.Parse(counterValue));
                            break;
                        case "gen-2-gc-count":
                            _hub.Clients.All.HandelGCCount(2, int.Parse(counterValue));
                            break;

                        case "threadpool-thread-count":
                            _hub.Clients.All.HandelThreadPoolThreadCount(counterValue);
                            break;
                        case "monitor-lock-contention-count":
                            _hub.Clients.All.HandelMonitorLockContentionCount(counterValue);
                            break;
                        case "threadpool-queue-length":
                            _hub.Clients.All.ThreadPoolQueueLength(counterValue);
                            break;
                        case "threadpool-completed-items-count":
                            _hub.Clients.All.ThreadPoolCompletedWorkItemCount(counterValue);
                            break;

                        case "gen-0-size":
                            _hub.Clients.All.HandelGcSize(0, long.Parse(counterValue));
                            break;
                        case "gen-1-size":
                            _hub.Clients.All.HandelGcSize(1, long.Parse(counterValue));
                            break;
                        case "gen-2-size":
                            _hub.Clients.All.HandelGcSize(2, long.Parse(counterValue));
                            break;
                        case "loh-size":
                            _hub.Clients.All.HandeLohSize(long.Parse(counterValue));
                            break;
                        case "poh-size":
                            _hub.Clients.All.HandelPohSize(long.Parse(counterValue));
                            break;

                        default:
                            break;
                    }
                }
            }
        }

19 View Source File : TimeConverter.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public long ToLong()
            => long.Parse(this.ToStringFlat());

19 View Source File : ExternalsPropertyEditor.cs
License : Apache License 2.0
Project Creator : AmpScm

private static bool TryCreateItemFromRow(DataGridViewRow r, out SvnExternalItem item)
        {
            if (r == null)
                throw new ArgumentNullException("r");

            string url = r.Cells[0].Value as string;
            string target = r.Cells[4].Value as string;
            string rev = r.Cells[2].Value as string;
            SvnRevision rr = string.IsNullOrEmpty(rev) ? SvnRevision.None : long.Parse(rev);

            if (url.Contains("://"))
            {
                Uri uri;

                if (!Uri.TryCreate(url, UriKind.Absolute, out uri))
                {
                    item = null;
                    return false;
                }

                url = uri.AbsoluteUri;
            }

            SvnExternalItem ei = new SvnExternalItem(target, url, rr, rr);
            SvnExternalItem p;

            if (!SvnExternalItem.TryParse(ei.ToString(), out p) || !p.Equals(ei))
            {
                item = null;
                return false;
            }
            item = ei;
            return true;
        }

19 View Source File : UserChatHandler.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel

private static PacketWriter GereplacedemLink(string message)
    {
        // '<' signals a message containing an item link
        if (!message.Contains('<'))
        {
            return null;
        }
        PacketWriter itemLinkPacket = null;

        XmlDoreplacedent itemLinkMessages = new();
        itemLinkMessages.LoadXml("<xml>" + message + "</xml>");

        List<Item> items = new();

        foreach (XmlNode itemLinkMessage in itemLinkMessages.SelectNodes("//A"))
        {
            string[] itemLinkMessageSplit = itemLinkMessage.Attributes["HREF"].Value.Split(",");
            string itemLinkType = itemLinkMessageSplit[0].Split(":")[1];
            long itemUid = long.Parse(itemLinkMessageSplit[1]);
            Item item = null;

            if (itemLinkType == "itemTooltip")
            {
                int itemToolTipType = int.Parse(itemLinkMessageSplit[2]);
                if (itemToolTipType == 2) // quest/navigator items
                {
                    if (ItemMetadataStorage.IsValid((int) itemUid))
                    {
                        item = new((int) itemUid, false)
                        {
                            Uid = itemUid
                        };
                    }
                }
                else if (itemToolTipType == 3) // normal item
                {
                    item = DatabaseManager.Items.FindByUid(itemUid);
                }
            }
            if (item != null)
            {
                items.Add(item);
            }
        }
        if (items.Count > 0)
        {
            itemLinkPacket = ItemLinkPacket.SendLinkItem(items);
        }
        return itemLinkPacket;
    }

19 View Source File : PreferencesPage.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus

private void AddParameter(string name, string data, List<Func<bool>> applyChanges, Grid pageContent, int currRow)
        {
            string controlType = data.Substring(0, data.IndexOf(":"));
            string controlParameters = data.Substring(data.IndexOf(":") + 1);

            if (controlType == "CheckBox")
            {
                string parameterName = name;

                bool defaultValue = Convert.ToBoolean(controlParameters);

                if (!GlobalSettings.Settings.AdditionalSettings.TryGetValue(parameterName, out object valueObject))
                {
                    GlobalSettings.Settings.AdditionalSettings.Add(parameterName, defaultValue);
                }
                else
                {
                    if (valueObject is JsonElement element)
                    {
                        defaultValue = element.GetBoolean();
                        GlobalSettings.Settings.AdditionalSettings[parameterName] = defaultValue;
                    }
                    else
                    {
                        defaultValue = (bool)valueObject;
                    }
                }

                CheckBox control = new CheckBox() { Content = parameterName, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left, Margin = new Thickness(0, 0, 0, 10), IsChecked = defaultValue, FontSize = 14 };

                Grid.SetRow(control, currRow);
                Grid.SetColumnSpan(control, 2);
                pageContent.Children.Add(control);

                applyChanges.Add(() =>
                {
                    GlobalSettings.Settings.AdditionalSettings[parameterName] = control.IsChecked == true;
                    return false;
                });
            }
            else
            {
                string parameterName = name;

                TextBlock blk = new TextBlock() { Text = parameterName, Margin = new Thickness(0, 0, 10, 10), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, FontSize = 14 };
                Grid.SetRow(blk, currRow);
                pageContent.Children.Add(blk);

                if (controlType == "ComboBox")
                {
                    int defaultIndex = int.Parse(controlParameters.Substring(0, controlParameters.IndexOf("[")));
                    controlParameters = controlParameters.Substring(controlParameters.IndexOf("["));

                    List<string> items = System.Text.Json.JsonSerializer.Deserialize<List<string>>(controlParameters, Modules.DefaultSerializationOptions);

                    if (!GlobalSettings.Settings.AdditionalSettings.TryGetValue(parameterName, out object valueObject))
                    {
                        GlobalSettings.Settings.AdditionalSettings.Add(parameterName, defaultIndex);
                    }
                    else
                    {
                        if (valueObject is JsonElement element)
                        {
                            defaultIndex = element.GetInt32();
                            GlobalSettings.Settings.AdditionalSettings[parameterName] = defaultIndex;
                        }
                        else
                        {
                            defaultIndex = (int)valueObject;
                        }
                    }

                    ComboBox box = new ComboBox() { Margin = new Thickness(0, 0, 0, 10), Items = items, SelectedIndex = defaultIndex, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, MinWidth = 200, FontSize = 14 };

                    Grid.SetRow(box, currRow);
                    Grid.SetColumn(box, 1);
                    pageContent.Children.Add(box);


                    applyChanges.Add(() =>
                    {
                        GlobalSettings.Settings.AdditionalSettings[parameterName] = box.SelectedIndex;
                        return false;
                    });
                }
                else if (controlType == "TextBox")
                {
                    string defaultValue = controlParameters;

                    if (!GlobalSettings.Settings.AdditionalSettings.TryGetValue(parameterName, out object valueObject))
                    {
                        GlobalSettings.Settings.AdditionalSettings.Add(parameterName, defaultValue);
                    }
                    else
                    {
                        if (valueObject is JsonElement element)
                        {
                            defaultValue = element.GetString();
                            GlobalSettings.Settings.AdditionalSettings[parameterName] = defaultValue;
                        }
                        else
                        {
                            defaultValue = (string)valueObject;
                        }
                    }

                    TextBox box = new TextBox() { Margin = new Thickness(0, 0, 0, 10), Padding = new Thickness(5, 2, 5, 2), Text = defaultValue, VerticalContentAlignment = Avalonia.Layout.VerticalAlignment.Center, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, MinWidth = 200, FontSize = 14, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left };

                    Grid.SetRow(box, currRow);
                    Grid.SetColumn(box, 1);
                    pageContent.Children.Add(box);

                    applyChanges.Add(() =>
                    {
                        GlobalSettings.Settings.AdditionalSettings[parameterName] = box.Text;
                        return false;
                    });
                }
                else if (controlType == "NumericUpDown")
                {
                    double defaultValue = double.Parse(controlParameters.Substring(0, controlParameters.IndexOf("[")));
                    controlParameters = controlParameters.Substring(controlParameters.IndexOf("["));

                    string[] range = System.Text.Json.JsonSerializer.Deserialize<string[]>(controlParameters, Modules.DefaultSerializationOptions);

                    double minRange = double.Parse(range[0], System.Globalization.CultureInfo.InvariantCulture);
                    double maxRange = double.Parse(range[1], System.Globalization.CultureInfo.InvariantCulture);

                    double increment = (maxRange - minRange) * 0.01;

                    if (range.Length > 2)
                    {
                        increment = double.Parse(range[2], System.Globalization.CultureInfo.InvariantCulture);
                    }

                    if (double.IsNaN(increment) || double.IsInfinity(increment))
                    {
                        increment = 1;
                    }

                    string formatString = Extensions.GetFormatString(increment);

                    if (range.Length > 3)
                    {
                        formatString = range[3];
                    }

                    if (!GlobalSettings.Settings.AdditionalSettings.TryGetValue(parameterName, out object valueObject))
                    {
                        GlobalSettings.Settings.AdditionalSettings.Add(parameterName, defaultValue);
                    }
                    else
                    {
                        if (valueObject is JsonElement element)
                        {
                            defaultValue = element.GetDouble();
                            GlobalSettings.Settings.AdditionalSettings[parameterName] = defaultValue;
                        }
                        else
                        {
                            defaultValue = (double)valueObject;
                        }
                    }

                    NumericUpDown nud = new NumericUpDown() { Margin = new Thickness(0, 0, 0, 10), Minimum = minRange, Maximum = maxRange, Increment = increment, Value = defaultValue, FormatString = formatString, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, MinWidth = 200, FontSize = 14, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left };

                    Grid.SetRow(nud, currRow);
                    Grid.SetColumn(nud, 1);
                    pageContent.Children.Add(nud);

                    applyChanges.Add(() =>
                    {
                        GlobalSettings.Settings.AdditionalSettings[parameterName] = nud.Value;
                        return false;
                    });
                }
                else if (controlType == "FileSize")
                {
                    long defaultValue = long.Parse(controlParameters);

                    if (!GlobalSettings.Settings.AdditionalSettings.TryGetValue(parameterName, out object valueObject))
                    {
                        GlobalSettings.Settings.AdditionalSettings.Add(parameterName, defaultValue);
                    }
                    else
                    {
                        if (valueObject is JsonElement element)
                        {
                            defaultValue = element.GetInt64();
                            GlobalSettings.Settings.AdditionalSettings[parameterName] = defaultValue;
                        }
                        else
                        {
                            defaultValue = (long)valueObject;
                        }
                    }

                    FileSizeControl.FileSizeUnit unit;

                    if (defaultValue < 1024)
                    {
                        unit = FileSizeControl.FileSizeUnit.B;
                    }
                    else
                    {
                        double longSize = defaultValue / 1024.0;

                        if (longSize < 1024)
                        {
                            unit = FileSizeControl.FileSizeUnit.kiB;
                        }
                        else
                        {
                            longSize /= 1024.0;

                            if (longSize < 1024)
                            {
                                unit = FileSizeControl.FileSizeUnit.MiB;
                            }
                            else
                            {
                                longSize /= 1024.0;
                                unit = FileSizeControl.FileSizeUnit.GiB;
                            }
                        }
                    }

                    FileSizeControl control = new FileSizeControl() { Margin = new Thickness(0, 0, 0, 10), Value = defaultValue, Unit = unit, MinWidth = 200, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, FontSize = 14, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left };

                    Grid.SetRow(control, currRow);
                    Grid.SetColumn(control, 1);
                    pageContent.Children.Add(control);

                    applyChanges.Add(() =>
                    {
                        GlobalSettings.Settings.AdditionalSettings[parameterName] = control.Value;
                        return false;
                    });
                }
                else if (controlType == "Slider")
                {
                    double defaultValue = double.Parse(controlParameters.Substring(0, controlParameters.IndexOf("[")));
                    controlParameters = controlParameters.Substring(controlParameters.IndexOf("["));

                    string[] range = System.Text.Json.JsonSerializer.Deserialize<string[]>(controlParameters, Modules.DefaultSerializationOptions);

                    double minRange = double.Parse(range[0], System.Globalization.CultureInfo.InvariantCulture);
                    double maxRange = double.Parse(range[1], System.Globalization.CultureInfo.InvariantCulture);

                    double increment = (maxRange - minRange) * 0.01;

                    if (double.IsNaN(increment) || double.IsInfinity(increment))
                    {
                        increment = 1;
                    }

                    if (!GlobalSettings.Settings.AdditionalSettings.TryGetValue(parameterName, out object valueObject))
                    {
                        GlobalSettings.Settings.AdditionalSettings.Add(parameterName, defaultValue);
                    }
                    else
                    {
                        if (valueObject is JsonElement element)
                        {
                            defaultValue = element.GetDouble();
                            GlobalSettings.Settings.AdditionalSettings[parameterName] = defaultValue;
                        }
                        else
                        {
                            defaultValue = (double)valueObject;
                        }
                    }

                    Grid sliderGrid = new Grid();
                    sliderGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                    sliderGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                    Grid.SetRow(sliderGrid, currRow);
                    Grid.SetColumn(sliderGrid, 1);
                    pageContent.Children.Add(sliderGrid);

                    Slider slid = new Slider() { Margin = new Thickness(0, 0, 0, 10), Minimum = minRange, Maximum = maxRange, Value = defaultValue, LargeChange = increment, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, FontSize = 14 };
                    sliderGrid.Children.Add(slid);


                    NumericUpDown valueBlock = null;

                    if (range.Length > 2)
                    {
                        valueBlock = new NumericUpDown() { VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, Margin = new Thickness(5, 0, 0, 10), Value = slid.Value, FormatString = range[2], Minimum = minRange, Maximum = maxRange, Increment = increment, MinWidth = 100, FontSize = 14, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left };
                        Grid.SetColumn(valueBlock, 1);
                        sliderGrid.Children.Add(valueBlock);
                    }
                    else
                    {
                        valueBlock = new NumericUpDown() { VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, Margin = new Thickness(5, 0, 0, 10), Value = slid.Value, FormatString = Extensions.GetFormatString(increment), Minimum = minRange, Maximum = maxRange, Increment = increment, MinWidth = 100, FontSize = 14, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left };
                        Grid.SetColumn(valueBlock, 1);
                        sliderGrid.Children.Add(valueBlock);
                    }

                    slid.PropertyChanged += (s, e) =>
                    {
                        if (e.Property == Slider.ValueProperty)
                        {
                            valueBlock.Value = slid.Value;
                        }
                    };


                    if (valueBlock != null)
                    {
                        valueBlock.ValueChanged += (s, e) =>
                        {
                            slid.Value = valueBlock.Value;
                        };
                    }

                    applyChanges.Add(() =>
                    {
                        GlobalSettings.Settings.AdditionalSettings[parameterName] = valueBlock.Value;
                        return false;
                    });
                }
                else if (controlType == "Font")
                {
                    string[] font = System.Text.Json.JsonSerializer.Deserialize<string[]>(controlParameters, Modules.DefaultSerializationOptions);

                    VectSharp.Font fnt = new VectSharp.Font(new VectSharp.FontFamily(font[0]), double.Parse(font[1], System.Globalization.CultureInfo.InvariantCulture));

                    if (!GlobalSettings.Settings.AdditionalSettings.TryGetValue(parameterName, out object valueObject))
                    {
                        GlobalSettings.Settings.AdditionalSettings.Add(parameterName, fnt);
                    }
                    else
                    {
                        if (valueObject is JsonElement element)
                        {
                            font = element.GetString().Split(',');
                            fnt = new VectSharp.Font(new VectSharp.FontFamily(font[0]), double.Parse(font[1], System.Globalization.CultureInfo.InvariantCulture));
                            GlobalSettings.Settings.AdditionalSettings[parameterName] = fnt;
                        }
                        else
                        {
                            fnt = (VectSharp.Font)valueObject;
                        }
                    }

                    FontButton but = new FontButton(false) { FontSize = 14, Font = fnt, Margin = new Thickness(0, 0, 0, 10), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left };

                    Grid.SetRow(but, currRow);
                    Grid.SetColumn(but, 1);
                    pageContent.Children.Add(but);

                    applyChanges.Add(() =>
                    {
                        GlobalSettings.Settings.AdditionalSettings[parameterName] = but.Font;
                        return false;
                    });
                }
                else if (controlType == "Point")
                {
                    double[] point = System.Text.Json.JsonSerializer.Deserialize<double[]>(controlParameters, Modules.DefaultSerializationOptions);

                    Grid grid = new Grid();
                    grid.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                    grid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                    grid.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                    grid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));

                    VectSharp.Point pt = new VectSharp.Point(point[0], point[1]);

                    if (!GlobalSettings.Settings.AdditionalSettings.TryGetValue(parameterName, out object valueObject))
                    {
                        GlobalSettings.Settings.AdditionalSettings.Add(parameterName, pt);
                    }
                    else
                    {
                        if (valueObject is JsonElement element)
                        {
                            string str = element.GetString();
                            string[] pointStr = str.Split(',');

                            pt = new VectSharp.Point(double.Parse(pointStr[0], System.Globalization.CultureInfo.InvariantCulture), double.Parse(pointStr[1], System.Globalization.CultureInfo.InvariantCulture));

                            GlobalSettings.Settings.AdditionalSettings[parameterName] = pt;
                        }
                        else
                        {
                            pt = (VectSharp.Point)valueObject;
                        }
                    }

                    NumericUpDown nudX = new NumericUpDown() { Margin = new Thickness(5, 0, 0, 10), Increment = 1, Value = pt.X, FormatString = Extensions.GetFormatString(point[0]), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, FontSize = 14, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left, MinWidth = 100 };
                    NumericUpDown nudY = new NumericUpDown() { Margin = new Thickness(5, 0, 0, 10), Increment = 1, Value = pt.Y, FormatString = Extensions.GetFormatString(point[1]), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, FontSize = 14, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left, MinWidth = 100 };

                    TextBlock blkX = new TextBlock() { Text = "X:", VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, Margin = new Thickness(5, 0, 0, 10), FontSize = 14 };
                    TextBlock blkY = new TextBlock() { Text = "Y:", VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, Margin = new Thickness(5, 0, 0, 10), FontSize = 14 };

                    Grid.SetColumn(blkY, 2);

                    Grid.SetColumn(grid, 1);

                    Grid.SetColumn(nudX, 1);
                    Grid.SetColumn(nudY, 3);

                    grid.Children.Add(blkX);
                    grid.Children.Add(nudX);
                    grid.Children.Add(blkY);
                    grid.Children.Add(nudY);

                    Grid.SetRow(grid, currRow);
                    Grid.SetColumn(grid, 1);
                    pageContent.Children.Add(grid);

                    applyChanges.Add(() =>
                    {
                        GlobalSettings.Settings.AdditionalSettings[parameterName] = new VectSharp.Point(nudX.Value, nudY.Value);
                        return false;
                    });
                }
                else if (controlType == "Colour")
                {
                    int[] colour = System.Text.Json.JsonSerializer.Deserialize<int[]>(controlParameters, Modules.DefaultSerializationOptions);

                    VectSharp.Colour col = VectSharp.Colour.FromRgba((byte)colour[0], (byte)colour[1], (byte)colour[2], (byte)colour[3]);

                    if (!GlobalSettings.Settings.AdditionalSettings.TryGetValue(parameterName, out object valueObject))
                    {
                        GlobalSettings.Settings.AdditionalSettings.Add(parameterName, col);
                    }
                    else
                    {
                        if (valueObject is JsonElement element)
                        {
                            col = VectSharp.Colour.FromCSSString(element.GetString()) ?? VectSharp.Colour.FromRgba(0, 0, 0, 0);
                            GlobalSettings.Settings.AdditionalSettings[parameterName] = col;
                        }
                        else
                        {
                            col = (VectSharp.Colour)valueObject;
                        }
                    }

                    ColorButton but = new ColorButton() { Color = col.ToAvalonia(), Margin = new Thickness(0, 0, 0, 10), HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left, FontSize = 14, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };

                    Grid.SetRow(but, currRow);
                    Grid.SetColumn(but, 1);
                    pageContent.Children.Add(but);

                    applyChanges.Add(() =>
                    {
                        GlobalSettings.Settings.AdditionalSettings[parameterName] = but.Color.ToVectSharp();
                        return false;
                    });
                }
                else if (controlType == "Dash")
                {
                    double[] dash = System.Text.Json.JsonSerializer.Deserialize<double[]>(controlParameters, Modules.DefaultSerializationOptions);

                    VectSharp.LineDash lineDash = new VectSharp.LineDash(dash[0], dash[1], dash[2]);

                    if (!GlobalSettings.Settings.AdditionalSettings.TryGetValue(parameterName, out object valueObject))
                    {
                        GlobalSettings.Settings.AdditionalSettings.Add(parameterName, lineDash);
                    }
                    else
                    {
                        if (valueObject is JsonElement element)
                        {
                            string str = element.GetString();
                            string[] dashStr = str.Split(',');

                            lineDash = new VectSharp.LineDash(double.Parse(dashStr[0], System.Globalization.CultureInfo.InvariantCulture), double.Parse(dashStr[1], System.Globalization.CultureInfo.InvariantCulture), double.Parse(dashStr[2], System.Globalization.CultureInfo.InvariantCulture));
                            GlobalSettings.Settings.AdditionalSettings[parameterName] = lineDash;
                        }
                        else
                        {
                            lineDash = (VectSharp.LineDash)valueObject;
                        }
                    }

                    DashControl control = new DashControl() { LineDash = lineDash, Margin = new Thickness(0, 0, 0, 10), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, FontSize = 14 };

                    Grid.SetRow(control, currRow);
                    Grid.SetColumn(control, 1);
                    pageContent.Children.Add(control);

                    applyChanges.Add(() =>
                    {
                        GlobalSettings.Settings.AdditionalSettings[parameterName] = control.LineDash;
                        return false;
                    });
                }
            }
        }

19 View Source File : MyPageBase.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

protected long GetLongArg(string name, long def = -1)
        {
            var value = GetArgValue(name);
            if (string.IsNullOrEmpty(value) || value == "undefined" || value == "null")
            {
                return def;
            }
            return long.Parse(value);
        }

19 View Source File : FriendMusicViewModel.cs
License : Apache License 2.0
Project Creator : artemshuba

private async Task LoadTracks(string playlistId = null, bool withoutPlaylistOnly = false)
        {
            TaskStarted("tracks");

            try
            {
                var albumId = playlistId != null ? long.Parse(playlistId) : 0;
                var tracks = await _tracksService.GetTracks(userId: Friend.Id, albumId: albumId);
                if (tracks == null)
                    return;

                if (withoutPlaylistOnly)
                    tracks = tracks?.Where(t => t.PlaylistId == 0).ToList();

                Tracks = new ObservableCollection<IAudio>(tracks);
            }
            catch (VkAccessDeniedException)
            {
                TaskError("tracks", Resources.GetStringByKey("Friend_TracksDisabled"));
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Unable to load friend tracks");
            }
            finally
            {
                TaskFinished("tracks");
            }
        }

19 View Source File : CourtSystem.cs
License : GNU General Public License v3.0
Project Creator : Albo1125

private static void LoadCourtCasesFromXMLFile(string File)
        {
            try
            {
                XDoreplacedent xdoc = XDoreplacedent.Load(File);
                char[] trim = new char[] { '\'', '\"', ' ' };
                List<CourtCase> AllCourtCases = xdoc.Descendants("CourtCase").Select(x => new CourtCase()
                {
                    SuspectName = ((string)x.Element("SuspectName").Value).Trim(trim),
                    SuspectDOB = DateTime.FromBinary(long.Parse(x.Element("SuspectDOB").Value)),
                    Crime = ((string)x.Element("Crime").Value).Trim(trim),
                    CrimeDate = DateTime.FromBinary(long.Parse(x.Element("CrimeDate").Value)),
                    GuiltyChance = int.Parse(x.Element("GuiltyChance") != null ?  ((string)x.Element("GuiltyChance").Value).Trim(trim) : "100"),
                    CourtVerdict = ((string)x.Element("CourtVerdict").Value).Trim(trim),
                    ResultsPublishTime = DateTime.FromBinary(long.Parse(x.Element("ResultsPublishTime").Value)),
                    ResultsPublished = bool.Parse(((string)x.Element("Published").Value).Trim(trim)),
                    ResultsPublishedNotificationShown = bool.Parse(((string)x.Element("ResultsPublishedNotificationShown").Value).Trim(trim))

                }).ToList<CourtCase>();

                foreach (CourtCase courtcase in AllCourtCases)
                {
                    courtcase.AddToCourtsMenuAndLists();
                }

            }
            catch (System.Threading.ThreadAbortException e) { }
            catch (Exception e)
            {
                Game.LogTrivial("LSPDFR+ encountered an exception reading \'" + File + "\'. It was: " + e.ToString());
                Game.DisplayNotification("~r~LSPDFR+: Error reading CourtCases.xml. Setting default values.");
            }
            finally
            {
                LoadingXMLFileCases = false;
            }


        }

19 View Source File : Check.cs
License : MIT License
Project Creator : arttonoyan

public static long? AsNullableInt64(object obj)
        {
            if (obj == null || obj == DBNull.Value)
                return null;

            return long.Parse(obj.ToString());
        }

19 View Source File : PerformanceAppender.cs
License : MIT License
Project Creator : Abc-Arbitrage

public void PrintTimeTaken()
        {
            var totalTimeCsv = "total-time.csv";
            if (File.Exists(totalTimeCsv))
                File.Delete(totalTimeCsv);

            using (var fileStream = new StreamWriter(File.OpenWrite(totalTimeCsv)))
            {
                for (int i = 0; i < _count; i++)
                {
                    var messageReceived = _messages[i];
                    var timestampString = Encoding.Default.GetString(messageReceived.StartTimestampInChars, 0, messageReceived.MessageLength);
                    var startTime = long.Parse(timestampString);
                    fileStream.WriteLine(ToMicroseconds(messageReceived.EndTimestamp - startTime));
                }
            }
        }

19 View Source File : TranslatorController.cs
License : MIT License
Project Creator : Autodesk-Forge

private Dictionary<string, object> GetProperties(long id, dynamic properties)
    {
      Dictionary<string, object> returnProps = new Dictionary<string, object>();
      foreach (KeyValuePair<string, dynamic> objectProps in new DynamicDictionaryItems(properties.data.collection))
      {
        if (objectProps.Value.objectid != id) continue;
        string name = objectProps.Value.name;
        long elementId = long.Parse(Regex.Match(name, @"\d+").Value);
        returnProps.Add("ID", elementId);
        returnProps.Add("Name", name.Replace("[" + elementId.ToString() + "]", string.Empty));
        foreach (KeyValuePair<string, dynamic> objectPropsGroup in new DynamicDictionaryItems(objectProps.Value.properties))
        {
          if (objectPropsGroup.Key.StartsWith("__")) continue;
          foreach (KeyValuePair<string, dynamic> objectProp in new DynamicDictionaryItems(objectPropsGroup.Value))
          {
            if (!returnProps.ContainsKey(objectProp.Key))
              returnProps.Add(objectProp.Key, objectProp.Value);
            else
              Debug.Write(objectProp.Key);
          }
        }
      }
      return returnProps;
    }

19 View Source File : ServiceBusQueueClient.cs
License : MIT License
Project Creator : allantargino

private async Task<long> GetQueueMessages(string serviceBusUrl, string queueName, ServiceBusToken token)
        {
            var apiVersion = "2017-04";
            var queueEndpoint = $"{serviceBusUrl}{queueName}/?api-version={apiVersion}";

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", token.Value);
                var xmlResponse = await client.RestGet(queueEndpoint);

                var messageCount = new Regex(@"<MessageCount>(.+?)<\/MessageCount>").Match(xmlResponse).Groups[1].Value;
                return long.Parse(messageCount);
            }
        }

19 View Source File : StorageQueueClient.cs
License : MIT License
Project Creator : allantargino

public async Task<long> GetMessageCountAsync(string queueName)
        {
            if (string.IsNullOrWhiteSpace(queueName)) throw new ArgumentException("queueName is empty");

            _queue = await GetQueueAsync(queueName);
            int? count = 0;
            try
            {
                await _queue.FetchAttributesAsync();
                count = _queue.ApproximateMessageCount;

                if (count > 0)
                {
                    List<CloudQueueMessage> messages = (List<CloudQueueMessage>)await _queue.PeekMessagesAsync(count.Value);

                    if (messages.Count < 32)
                        count = messages.Count;
                }
                Console.WriteLine($"The queue {queueName} has  {count} message(s)!");
            }
            catch (Exception ex) {
                throw new Exception($"Error getting message count: {ex.Message} ");
            }

            if (count != null)
                return long.Parse(count.ToString());

            return 0;
        }

19 View Source File : UnixEpochDateTimeConverter.cs
License : MIT License
Project Creator : actions

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            long unixVal = reader.Value is string ? long.Parse((string) reader.Value) : (long)reader.Value;

            return unixVal.FromUnixEpochTime();
        }

19 View Source File : AzureBlobFileStorage.cs
License : Apache License 2.0
Project Creator : aloneguid

private static IEnumerable<IOEntry> ConvertBatch(XElement blobs)
      {
         foreach(XElement blobPrefix in blobs.Elements("BlobPrefix"))
         {
            string name = blobPrefix.Element("Name").Value;
            yield return new IOEntry(name + IOPath.PathSeparatorString);
         }

         foreach(XElement blob in blobs.Elements("Blob"))
         {
            string name = blob.Element("Name").Value;
            var file = new IOEntry(name);

            foreach(XElement xp in blob.Element("Properties").Elements())
            {
               string pname = xp.Name.ToString();
               string pvalue = xp.Value;

               if(!string.IsNullOrEmpty(pvalue))
               {
                  if(pname == "Last-Modified")
                  {
                     file.LastModificationTime = DateTimeOffset.Parse(pvalue);
                  }
                  else if(pname == "Content-Length")
                  {
                     file.Size = long.Parse(pvalue);
                  }
                  else if(pname == "Content-MD5")
                  {
                     file.MD5 = pvalue;
                  }
                  else
                  {
                     file.Properties[pname] = pvalue;
                  }
               }
            }

            yield return file;
         }
      }

19 View Source File : DataTimeUtil.cs
License : MIT License
Project Creator : aishang2015

public static DateTime ConvertStringToDateTime(string timeStamp)
        {
            var intStamp = long.Parse(timeStamp);
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = intStamp * 10000000;
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }

19 View Source File : Backup.cs
License : MIT License
Project Creator : ANF-Studios

public static void ListBackups(
            in HandleEventType eventType,
            in string userBackupDirectory,
            in string systemBackupDirectory = null,
            in int range = 3
        )
        {
            // The value that defines the location of the desired format
            // in the index of dateTimeObject.GetGetDateTimeFormats();.
            // It strictly looks like: 01-Jan-20 12:00 PM.
            const uint formatIndex = 12;

            DirectoryInfo userDirInfo = new DirectoryInfo(userBackupDirectory);
            DirectoryInfo systemDirInfo = systemBackupDirectory is null
                                            ? null
                                            : new DirectoryInfo(systemBackupDirectory);

            if (!userDirInfo.Exists)
            {
                Console.WriteLine("No backups found...");
                return;
            }
            //if (!systemDirInfo.Exists)
            //{
            // Will be implemented when system backups are supported.
            //}

            FileInfo[] userDirFileInfo = userDirInfo.GetFiles();
            FileInfo[] systemDirFileInfo = systemDirInfo?.GetFiles();

            FileInfo[] reversedUserList = userDirFileInfo.Reverse().ToArray();
            FileInfo[] reversedSystemList = systemDirFileInfo?.Reverse().ToArray();

            long temp; // For long.TryParse(..., out temp);
            string separator = "-----------------------------------------"; // Default separator.
            string spaces = string.Empty; // The number of spaces between `Filename` and `|`.

            //var now = DateTime.Now;
            //for (int i = 0; i < now.GetDateTimeFormats().Length; ++i)
            //    Console.WriteLine(i + " " + now.GetDateTimeFormats()[i]);

            if (userDirFileInfo.Length > 0)
            {
                separator = string.Empty;
                for (int i = 0; i < (userDirFileInfo[0].Name + " | " + DateTime.FromFileTime(long.Parse(userDirFileInfo[0].Name)).GetDateTimeFormats()[formatIndex]).Length; ++i)
                    separator += '-';

                for (int i = 0; i < userDirFileInfo[0].Name.Length - "Filename".Length; ++i)
                    spaces += " ";
            }

            switch (eventType)
            {
                case HandleEventType.ListAllBackups:
                    Console.WriteLine("User Backups:");
                    Console.WriteLine("Filename" + spaces + " | Date of creation");
                    Console.WriteLine(separator);

                    foreach (FileInfo backupFile in userDirFileInfo)
                        Console.WriteLine(
                            backupFile.Name
                                + " | "
                                + (
                                    long.TryParse(
                                        backupFile.Name,
                                        out temp
                                    )
                                        ? DateTime.FromFileTime(temp).GetDateTimeFormats()[formatIndex]
                                        : "<Parsing error>"
                                  )
                        );

                    Console.WriteLine(separator + Console.Out.NewLine);

                    Console.WriteLine("System Backups:");
                    Console.WriteLine("Filename | Date of creation");
                    Console.WriteLine(separator);

                    /*
                    if (systemDirFileInfo is not null)
                    {
                        foreach (FileInfo backupFile in systemDirFileInfo)
                            Console.WriteLine(
                                backupFile.Name
                                    + " | "
                                    + (
                                        long.TryParse(
                                            backupFile.Name,
                                            out temp
                                        )
                                            ? DateTime.FromFileTime(temp).GetDateTimeFormats()[formatIndex]
                                            : "<Parsing error>"
                                      )
                            );
                    }
                    else*/
                    Console.WriteLine("System backups not yet supported by the API.");
                    Console.WriteLine(separator);
                    break;

                case HandleEventType.ListBackups:
                case HandleEventType.ListLatestBackups:
                    if (range < BackupOptions.BackupListOptions.MinimumRange
                            || range > BackupOptions.BackupListOptions.MaximumRange)
                        Console.WriteLine($"Range cannot be greater than "
                                            + BackupOptions.BackupListOptions.MaximumRange
                                            + " or less than "
                                            + BackupOptions.BackupListOptions.MinimumRange
                                            + $" (current: {range})");
                    else
                    {
                        Console.WriteLine("User Backups:");
                        Console.WriteLine("Filename" + spaces + " | Date of creation");
                        Console.WriteLine(separator);

                        for (int i = 0; i < range; ++i)
                        {
                            try
                            {
                                Console.WriteLine(
                                    reversedUserList[i].Name
                                        + " | "
                                        + (
                                            long.TryParse(
                                                reversedUserList[i].Name,
                                                out temp
                                            )
                                                ? DateTime.FromFileTime(temp).GetDateTimeFormats()[formatIndex]
                                                : "<Parsing error>"
                                          )
                                );
                            }
                            catch (IndexOutOfRangeException) { break; }
                        }

                        Console.WriteLine(separator + Console.Out.NewLine);

                        Console.WriteLine("System Backups:");
                        Console.WriteLine("Filename | Date of creation");
                        Console.WriteLine(separator);

                        /*
                        if (reversedSystemList is not null)
                            for (int i = 0; i < range; ++i)
                            {
                                try
                                {
                                    Console.WriteLine(
                                        reversedSystemList[i].Name
                                            + " | "
                                            + (
                                                long.TryParse(
                                                    reversedSystemList[i].Name,
                                                    out temp
                                                )
                                                    ? DateTime.FromFileTime(temp).GetDateTimeFormats()[formatIndex]
                                                    : "<Parsing error>"
                                              )
                                    );
                                }
                                catch (IndexOutOfRangeException) { break; }
                            }
                        else*/
                        Console.WriteLine("System backups not yet supported by the API.");

                        Console.WriteLine(separator);
                    }
                    break;

                default:
                    throw new ArgumentException(
                        $"{nameof(HandleEventType)} cannot be set to {nameof(eventType)}.",
                        nameof(eventType)
                    );
            }
        }

19 View Source File : ExternalsPropertyEditor.cs
License : Apache License 2.0
Project Creator : AmpScm

private void SelectRevision(DataGridViewRow row)
        {
            IAnkhServiceProvider context = Context;
            if (context != null)
            {
                string selectedUriString = row.Cells[0].Value as string;

                Uri selectedUri;
                if (!string.IsNullOrEmpty(selectedUriString)
                    && Uri.TryCreate(selectedUriString, UriKind.Absolute, out selectedUri)
                    )
                {
                    Uri repoRoot = string.Equals(_lastUsedUriString, selectedUriString) ? _lastRepositoryRoot : null;
                    if (repoRoot == null)
                    {
                        if (context.GetService<IProgressRunner>().RunModal(
                            PropertyEditStrings.RetrievingRepositoryRoot,
                            delegate(object sender, ProgressWorkerArgs a)
                            {
                                repoRoot = a.Client.GetRepositoryRoot(selectedUri);

                            }).Succeeded)
                        {
                            //cache the last used repo uri string and the fetched repository root uri
                            _lastRepositoryRoot = repoRoot;
                            _lastUsedUriString = selectedUriString;
                        }
                    }
                    if (repoRoot != null)
                    {
                        try
                        {
                            // set the current revision value as the initial selection
                            string rev = row.Cells[2].Value as string;
                            SvnRevision rr = string.IsNullOrEmpty(rev) ? SvnRevision.None : long.Parse(rev);
                            SvnUriTarget svnTarget = new SvnUriTarget(selectedUri, rr);
                            Ankh.Scc.SvnOrigin origin = new Ankh.Scc.SvnOrigin(svnTarget, repoRoot);
                            using (Ankh.UI.SvnLog.LogViewerDialog dlg = new Ankh.UI.SvnLog.LogViewerDialog(origin))
                            {
                                if (dlg.ShowDialog(Context) == DialogResult.OK)
                                {
                                    Ankh.Scc.ISvnLogItem li = EnumTools.GetSingle(dlg.SelectedItems);
                                    rev = li == null ? null : li.Revision.ToString();
                                    //set the revision cell value to the selection revision
                                    row.Cells[2].Value = rev ?? string.Empty;
                                }
                            }
                        }
                        catch
                        {
                            // clear cache in case of error
                            _lastUsedUriString = null;
                            _lastRepositoryRoot = null;
                        }
                    }
                }
            }
        }

19 View Source File : MoveFieldHandler.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel

private static void HandleHomePortal(GameSession session, IFieldObject<Portal> fieldPortal)
    {
        IFieldObject<Cube> srcCube = session.FieldManager.State.Cubes.Values
            .FirstOrDefault(x => x.Value.PortalSettings is not null
                                && x.Value.PortalSettings.PortalObjectId == fieldPortal.ObjectId);
        if (srcCube is null)
        {
            return;
        }

        string destinationTarget = srcCube.Value.PortalSettings.DestinationTarget;
        if (string.IsNullOrEmpty(destinationTarget))
        {
            return;
        }

        switch (srcCube.Value.PortalSettings.Destination)
        {
            case UGCPortalDestination.PortalInHome:
                IFieldObject<Cube> destinationCube = session.FieldManager.State.Cubes.Values
                    .FirstOrDefault(x => x.Value.PortalSettings is not null
                                        && x.Value.PortalSettings.PortalName == destinationTarget);
                if (destinationCube is null)
                {
                    return;
                }
                session.FieldPlayer.Coord = destinationCube.Coord;
                CoordF coordF = destinationCube.Coord;
                coordF.Z += 25; // Without this the player falls through the ground.
                session.Send(UserMoveByPortalPacket.Move(session.FieldPlayer, coordF, session.FieldPlayer.Rotation));
                break;
            case UGCPortalDestination.SelectedMap:
                session.Player.Warp(int.Parse(destinationTarget));
                break;
            case UGCPortalDestination.FriendHome:
                long friendAccountId = long.Parse(destinationTarget);
                Home home = GameServer.HomeManager.GetHomeById(friendAccountId);
                if (home is null)
                {
                    return;
                }
                session.Player.WarpGameToGame((int) Map.PrivateResidence, instanceId: home.InstanceId);
                break;
        }
    }

19 View Source File : FileSelector.cs
License : Apache License 2.0
Project Creator : Appdynamics

private static SelectionCriterion _ParseCriterion(String s)
        {
            if (s == null) return null;

            // inject spaces after open paren and before close paren, etc
            s = NormalizeCriteriaExpression(s);

            // no spaces in the criteria is shorthand for filename glob
            if (s.IndexOf(" ") == -1)
                s = "name = " + s;

            // split the expression into tokens
            string[] tokens = s.Trim().Split(' ', '\t');

            if (tokens.Length < 3) throw new ArgumentException(s);

            SelectionCriterion current = null;

            LogicalConjunction pendingConjunction = LogicalConjunction.NONE;

            ParseState state;
            var stateStack = new System.Collections.Generic.Stack<ParseState>();
            var critStack = new System.Collections.Generic.Stack<SelectionCriterion>();
            stateStack.Push(ParseState.Start);

            for (int i = 0; i < tokens.Length; i++)
            {
                string tok1 = tokens[i].ToLower(CultureInfo.InvariantCulture);
                switch (tok1)
                {
                    case "and":
                    case "xor":
                    case "or":
                        state = stateStack.Peek();
                        if (state != ParseState.CriterionDone)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        if (tokens.Length <= i + 3)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        pendingConjunction = (LogicalConjunction)Enum.Parse(typeof(LogicalConjunction), tokens[i].ToUpper(CultureInfo.InvariantCulture), true);
                        current = new CompoundCriterion { Left = current, Right = null, Conjunction = pendingConjunction };
                        stateStack.Push(state);
                        stateStack.Push(ParseState.ConjunctionPending);
                        critStack.Push(current);
                        break;

                    case "(":
                        state = stateStack.Peek();
                        if (state != ParseState.Start && state != ParseState.ConjunctionPending && state != ParseState.OpenParen)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        if (tokens.Length <= i + 4)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        stateStack.Push(ParseState.OpenParen);
                        break;

                    case ")":
                        state = stateStack.Pop();
                        if (stateStack.Peek() != ParseState.OpenParen)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        stateStack.Pop();
                        stateStack.Push(ParseState.CriterionDone);
                        break;

                    case "atime":
                    case "ctime":
                    case "mtime":
                        if (tokens.Length <= i + 2)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        DateTime t;
                        try
                        {
                            t = DateTime.ParseExact(tokens[i + 2], "yyyy-MM-dd-HH:mm:ss", null);
                        }
                        catch (FormatException)
                        {
                            try
                            {
                                t = DateTime.ParseExact(tokens[i + 2], "yyyy/MM/dd-HH:mm:ss", null);
                            }
                            catch (FormatException)
                            {
                                try
                                {
                                    t = DateTime.ParseExact(tokens[i + 2], "yyyy/MM/dd", null);
                                }
                                catch (FormatException)
                                {
                                    try
                                    {
                                        t = DateTime.ParseExact(tokens[i + 2], "MM/dd/yyyy", null);
                                    }
                                    catch (FormatException)
                                    {
                                        t = DateTime.ParseExact(tokens[i + 2], "yyyy-MM-dd", null);
                                    }
                                }
                            }
                        }
                        t= DateTime.SpecifyKind(t, DateTimeKind.Local).ToUniversalTime();
                        current = new TimeCriterion
                        {
                            Which = (WhichTime)Enum.Parse(typeof(WhichTime), tokens[i], true),
                            Operator = (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1]),
                            Time = t
                        };
                        i += 2;
                        stateStack.Push(ParseState.CriterionDone);
                        break;


                    case "length":
                    case "size":
                        if (tokens.Length <= i + 2)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        Int64 sz = 0;
                        string v = tokens[i + 2];
                        if (v.EndsWith("K", StringComparison.OrdinalIgnoreCase))
                            sz = Int64.Parse(v.Substring(0, v.Length - 1)) * 1024;
                        else if (v.EndsWith("KB", StringComparison.OrdinalIgnoreCase))
                            sz = Int64.Parse(v.Substring(0, v.Length - 2)) * 1024;
                        else if (v.EndsWith("M", StringComparison.OrdinalIgnoreCase))
                            sz = Int64.Parse(v.Substring(0, v.Length - 1)) * 1024 * 1024;
                        else if (v.EndsWith("MB", StringComparison.OrdinalIgnoreCase))
                            sz = Int64.Parse(v.Substring(0, v.Length - 2)) * 1024 * 1024;
                        else if (v.EndsWith("G", StringComparison.OrdinalIgnoreCase))
                            sz = Int64.Parse(v.Substring(0, v.Length - 1)) * 1024 * 1024 * 1024;
                        else if (v.EndsWith("GB", StringComparison.OrdinalIgnoreCase))
                            sz = Int64.Parse(v.Substring(0, v.Length - 2)) * 1024 * 1024 * 1024;
                        else sz = Int64.Parse(tokens[i + 2]);

                        current = new SizeCriterion
                        {
                            Size = sz,
                            Operator = (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1])
                        };
                        i += 2;
                        stateStack.Push(ParseState.CriterionDone);
                        break;

                    case "filename":
                    case "name":
                        {
                            if (tokens.Length <= i + 2)
                                throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                            ComparisonOperator c =
                                (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1]);

                            if (c != ComparisonOperator.NotEqualTo && c != ComparisonOperator.EqualTo)
                                throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                            string m = tokens[i + 2];

                            // handle single-quoted filespecs (used to include
                            // spaces in filename patterns)
                            if (m.StartsWith("'") && m.EndsWith("'"))
                            {
                                // trim off leading and trailing single quotes and
                                // revert the control characters to spaces.
                                m = m.Substring(1, m.Length - 2)
                                    .Replace("\u0006", " ");
                            }

                            // if (m.StartsWith("'"))
                            //     m = m.Replace("\u0006", " ");

                            current = new NameCriterion
                            {
                                MatchingFileSpec = m,
                                Operator = c
                            };
                            i += 2;
                            stateStack.Push(ParseState.CriterionDone);
                        }
                        break;

#if !SILVERLIGHT
                    case "attrs":
                    case "attributes":
#endif
                    case "type":
                        {
                            if (tokens.Length <= i + 2)
                                throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                            ComparisonOperator c =
                                (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1]);

                            if (c != ComparisonOperator.NotEqualTo && c != ComparisonOperator.EqualTo)
                                throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

#if SILVERLIGHT
                            current = (SelectionCriterion) new TypeCriterion
                                    {
                                        AttributeString = tokens[i + 2],
                                        Operator = c
                                    };
#else
                            current = (tok1 == "type")
                                ? (SelectionCriterion) new TypeCriterion
                                    {
                                        AttributeString = tokens[i + 2],
                                        Operator = c
                                    }
                                : (SelectionCriterion) new AttributesCriterion
                                    {
                                        AttributeString = tokens[i + 2],
                                        Operator = c
                                    };
#endif
                            i += 2;
                            stateStack.Push(ParseState.CriterionDone);
                        }
                        break;

                    case "":
                        // NOP
                        stateStack.Push(ParseState.Whitespace);
                        break;

                    default:
                        throw new ArgumentException("'" + tokens[i] + "'");
                }

                state = stateStack.Peek();
                if (state == ParseState.CriterionDone)
                {
                    stateStack.Pop();
                    if (stateStack.Peek() == ParseState.ConjunctionPending)
                    {
                        while (stateStack.Peek() == ParseState.ConjunctionPending)
                        {
                            var cc = critStack.Pop() as CompoundCriterion;
                            cc.Right = current;
                            current = cc; // mark the parent as current (walk up the tree)
                            stateStack.Pop();   // the conjunction is no longer pending

                            state = stateStack.Pop();
                            if (state != ParseState.CriterionDone)
                                throw new ArgumentException("??");
                        }
                    }
                    else stateStack.Push(ParseState.CriterionDone);  // not sure?
                }

                if (state == ParseState.Whitespace)
                    stateStack.Pop();
            }

            return current;
        }

19 View Source File : MockOpenInvoicePayment.cs
License : MIT License
Project Creator : Adyen

public static PaymentRequest CreateOpenInvoicePaymentRequest()
        {

            DateTime dateOfBirth = DateTime.Parse("1970-07-10");

            PaymentRequest paymentRequest = MockPaymentData.CreateFullPaymentRequest();

            // Set Shopper Data
            paymentRequest.ShopperEmail = "[email protected]";
            paymentRequest.DateOfBirth = dateOfBirth;
            paymentRequest.TelephoneNumber = "0612345678";
            paymentRequest.ShopperReference = "4";

            // Set Shopper Info
            Name shopperName = new Name
            {
                FirstName = "Testperson-nl",
                LastName = "Approved",
                Gender = GenderEnum.MALE
            };
            paymentRequest.ShopperName = shopperName;

            // Set Billing and Delivery address
            Address address = new Address
            {
                City = "Gravenhage",
                Country = "NL",
                HouseNumberOrName = "1",
                PostalCode = "2521VA",
                StateOrProvince = "Zuid-Holland",
                Street = "Neherkade"
            };
            paymentRequest.DeliveryAddress = address;
            paymentRequest.BillingAddress = address;

            // Use OpenInvoice Provider (klarna, ratepay)
            paymentRequest.SelectedBrand = "klarna";

            long itemAmount = long.Parse("9000");
            long itemVatAmount = long.Parse("1000");
            long itemVatPercentage = long.Parse("1000");

            List<InvoiceLine> invoiceLines = new List<InvoiceLine>();

            // invoiceLine1
            InvoiceLine invoiceLine = new InvoiceLine
            {
                CurrencyCode = ("EUR"),
                Description = ("Test product"),
                VatAmount = (itemVatAmount),
                ItemAmount = (itemAmount),
                ItemVatPercentage = (itemVatPercentage),
                VatCategory = (VatCategory.None),
                NumberOfItems = (1),
                ItemId = ("1234")
            };

            // invoiceLine2
            // invoiceLine1
            InvoiceLine invoiceLine2 = new InvoiceLine
            {
                CurrencyCode = ("EUR"),
                Description = ("Test product2"),
                VatAmount = (itemVatAmount),
                ItemAmount = (itemAmount),
                ItemVatPercentage = (itemVatPercentage),
                VatCategory = (VatCategory.None),
                NumberOfItems = (1),
                ItemId = ("456")
            };
            
            invoiceLines.Add(invoiceLine);
            invoiceLines.Add(invoiceLine2);

            paymentRequest.InvoiceLines(invoiceLines);

            return paymentRequest;
        }

19 View Source File : FtpClient.cs
License : MIT License
Project Creator : ARKlab

private FtpEntry _parseMatch(GroupCollection matchGroups, ListStyle style, string path)
        {
            string dirMatch = (style == ListStyle.Unix ? "d" : "<dir>");

            FtpEntry result = new FtpEntry();
            result.IsDirectory = matchGroups["dir"].Value.Equals(dirMatch, StringComparison.InvariantCultureIgnoreCase);
            result.Name = matchGroups["name"].Value.GetFtpPath();
            result.FullPath = path.GetFtpPath(result.Name);

            if (matchGroups["modify"].Value.Length > 0)
                result.Modified = matchGroups["modify"].Value.GetFtpDate(DateTimeStyles.replacedumeLocal);

            if (!result.IsDirectory)
                result.Size = long.Parse(matchGroups["size"].Value);

            return result;
        }

19 View Source File : PacketStructureResolver.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel

public static PacketStructureResolver Parse(string input)
    {
        string[] args = input.Split(" ", StringSplitOptions.RemoveEmptyEntries);

        // Parse opCode: 81 0081 0x81 0x0081
        ushort opCode;
        string firstArg = args[0];
        if (firstArg.ToLower().StartsWith("0x"))
        {
            opCode = Convert.ToUInt16(firstArg, 16);
        }
        else
        {
            if (firstArg.Length == 2)
            {
                opCode = firstArg.ToByte();
            }
            else if (firstArg.Length == 4)
            {
                // Reverse bytes
                byte[] bytes = firstArg.ToByteArray();
                Array.Reverse(bytes);

                opCode = BitConverter.ToUInt16(bytes);
            }
            else
            {
                Logger.Info("Invalid opcode.");
                return null;
            }
        }

        PacketStructureResolver resolver = new(opCode);
        DirectoryInfo dir = Directory.CreateDirectory($"{Paths.SOLUTION_DIR}/MapleServer2/PacketStructures");

        string filePath = $"{dir.FullName}/{resolver.OpCode:X4} - {resolver.PacketName}.txt";
        if (!File.Exists(filePath))
        {
            StreamWriter writer = File.CreateText(filePath);
            writer.WriteLine("# Generated by MapleServer2 PacketStructureResolver");
            IEnumerable<char> enumerable = opCode.ToString("D4").Reverse();
            writer.WriteLine($"PacketWriter pWriter = PacketWriter.Of(SendOp.{resolver.PacketName});");
            writer.Close();
            return resolver;
        }

        string[] fileLines = File.ReadAllLines(filePath);
        foreach (string line in fileLines)
        {
            if (string.IsNullOrEmpty(line) || line.StartsWith("#") || line.StartsWith("PacketWriter"))
            {
                continue;
            }

            string[] packetLine = line.Split("(");
            string type = packetLine[0][13..];
            string valuereplacedtring = packetLine[1].Split(")")[0];
            valuereplacedtring = string.IsNullOrEmpty(valuereplacedtring) ? "0" : valuereplacedtring;
            try
            {
                switch (type)
                {
                    case "Byte":
                        resolver.Packet.WriteByte(byte.Parse(valuereplacedtring));
                        break;
                    case "Short":
                        resolver.Packet.WriteShort(short.Parse(valuereplacedtring));
                        break;
                    case "Int":
                        resolver.Packet.WriteInt(int.Parse(valuereplacedtring));
                        break;
                    case "Long":
                        resolver.Packet.WriteLong(long.Parse(valuereplacedtring));
                        break;
                    case "Float":
                        resolver.Packet.WriteFloat(float.Parse(valuereplacedtring));
                        break;
                    case "UnicodeString":
                        resolver.Packet.WriteUnicodeString(valuereplacedtring.Replace("\"", ""));
                        break;
                    case "String":
                        resolver.Packet.WriteString(valuereplacedtring.Replace("\"", ""));
                        break;
                    default:
                        Logger.Info($"Unknown type: {type}");
                        break;
                }
            }
            catch
            {
                Logger.Info($"Couldn't parse value on function: {line}");
                return null;
            }
        }
        return resolver;
    }

19 View Source File : GlobalSettings.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus

internal static void SetSetting(string settingName, string settingValue)
        {
            switch (settingName)
            {
                case "AutosaveInterval":
                    if (string.IsNullOrEmpty(settingValue))
                    {
                        GlobalSettings.Settings.AutosaveInterval = new TimeSpan(0, 10, 0);
                    }
                    else
                    {
                        GlobalSettings.Settings.AutosaveInterval = TimeSpan.Parse(settingValue);
                    }
                    break;
                case "DragInterval":
                    if (string.IsNullOrEmpty(settingValue))
                    {
                        GlobalSettings.Settings.DragInterval = 250;
                    }
                    else
                    {
                        GlobalSettings.Settings.DragInterval = int.Parse(settingValue);
                    }
                    break;
                case "KeepRecentFilesFor":
                    if (string.IsNullOrEmpty(settingValue))
                    {
                        GlobalSettings.Settings.KeepRecentFilesFor = 30;
                    }
                    else
                    {
                        GlobalSettings.Settings.KeepRecentFilesFor = int.Parse(settingValue);
                    }
                    break;
                case "DrawTreeWhenOpened":
                    if (string.IsNullOrEmpty(settingValue))
                    {
                        GlobalSettings.Settings.DrawTreeWhenOpened = true;
                    }
                    else
                    {
                        GlobalSettings.Settings.DrawTreeWhenOpened = Convert.ToBoolean(settingValue);
                    }
                    break;
                case "ShowLegacyUpDownArrows":
                    if (string.IsNullOrEmpty(settingValue))
                    {
                        GlobalSettings.Settings.ShowLegacyUpDownArrows = false;
                    }
                    else
                    {
                        GlobalSettings.Settings.ShowLegacyUpDownArrows = Convert.ToBoolean(settingValue);
                    }
                    break;
                case "SelectionColour":
                    if (string.IsNullOrEmpty(settingValue))
                    {
                        GlobalSettings.Settings.SelectionColour = Colour.FromRgb(35, 127, 255);
                    }
                    else
                    {
                        GlobalSettings.Settings.SelectionColour = Colour.FromCSSString(settingValue) ?? Colour.FromRgb(35, 127, 255);
                    }
                    break;
                case "BackgroundColour":
                    if (string.IsNullOrEmpty(settingValue))
                    {
                        GlobalSettings.Settings.BackgroundColour = Colour.FromRgb(240, 244, 250);
                    }
                    else
                    {
                        GlobalSettings.Settings.BackgroundColour = Colour.FromCSSString(settingValue) ?? Colour.FromRgb(240, 244, 250);
                    }
                    break;
                case "ModuleRepositoryBaseUri":
                    if (string.IsNullOrEmpty(settingValue))
                    {
                        GlobalSettings.Settings.ModuleRepositoryBaseUri = GlobalSettings.DefaultModuleRepository;
                    }
                    else
                    {
                        GlobalSettings.Settings.ModuleRepositoryBaseUri = settingValue;
                    }
                    break;
                case "UpdateCheckMode":
                    if (string.IsNullOrEmpty(settingValue))
                    {
                        GlobalSettings.Settings.UpdateCheckMode = GlobalSettings.UpdateCheckModes.ProgramAndAllModules;
                    }
                    else
                    {
                        GlobalSettings.Settings.UpdateCheckMode = (GlobalSettings.UpdateCheckModes)Enum.Parse(typeof(GlobalSettings.UpdateCheckModes), settingValue);
                    }
                    break;
                case "InterfaceStyle":
                    if (string.IsNullOrEmpty(settingValue))
                    {
                        GlobalSettings.Settings.InterfaceStyle = Modules.IsMac ? InterfaceStyles.MacOSStyle : InterfaceStyles.WindowsStyle;
                    }
                    else
                    {
                        GlobalSettings.Settings.InterfaceStyle = (GlobalSettings.InterfaceStyles)Enum.Parse(typeof(GlobalSettings.InterfaceStyles), settingValue);
                    }
                    break;
                case "RibbonStyle":
                    if (string.IsNullOrEmpty(settingValue))
                    {
                        GlobalSettings.Settings.RibbonStyle = Modules.IsWindows ? RibbonStyles.Colourful : RibbonStyles.Grey;
                    }
                    else
                    {
                        GlobalSettings.Settings.RibbonStyle = (GlobalSettings.RibbonStyles)Enum.Parse(typeof(GlobalSettings.RibbonStyles), settingValue);
                    }
                    break;
                default:
                    {
                        bool found = false;

                        foreach (KeyValuePair<string, string> kvp in GlobalSettings.Settings.AdditionalSettingsList)
                        {
                            string name = kvp.Key;
                            string data = kvp.Value;

                            if (name == settingName)
                            {
                                string controlType = data.Substring(0, data.IndexOf(":"));
                                string controlParameters = data.Substring(data.IndexOf(":") + 1);

                                if (controlType == "CheckBox")
                                {
                                    bool defaultValue = Convert.ToBoolean(controlParameters);

                                    if (string.IsNullOrEmpty(settingValue))
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = defaultValue;
                                    }
                                    else
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = Convert.ToBoolean(settingValue);
                                    }
                                }
                                else if (controlType == "ComboBox")
                                {
                                    int defaultIndex = int.Parse(controlParameters.Substring(0, controlParameters.IndexOf("[")));
                                    controlParameters = controlParameters.Substring(controlParameters.IndexOf("["));

                                    List<string> items = System.Text.Json.JsonSerializer.Deserialize<List<string>>(controlParameters, Modules.DefaultSerializationOptions);

                                    if (string.IsNullOrEmpty(settingValue))
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = defaultIndex;
                                    }
                                    else
                                    {
                                        int index = items.IndexOf(settingValue);
                                        if (index < 0)
                                        {
                                            index = defaultIndex;
                                        }

                                        GlobalSettings.Settings.AdditionalSettings[name] = index;
                                    }
                                }
                                else if (controlType == "TextBox")
                                {
                                    string defaultValue = controlParameters;

                                    if (string.IsNullOrEmpty(settingValue))
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = defaultValue;
                                    }
                                    else
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = settingValue;
                                    }
                                }
                                else if (controlType == "NumericUpDown")
                                {
                                    double defaultValue = double.Parse(controlParameters.Substring(0, controlParameters.IndexOf("[")));

                                    if (string.IsNullOrEmpty(settingValue))
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = defaultValue;
                                    }
                                    else
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = double.Parse(settingValue, System.Globalization.CultureInfo.InvariantCulture);
                                    }
                                }
                                else if (controlType == "FileSize")
                                {
                                    long defaultValue = long.Parse(controlParameters);

                                    if (string.IsNullOrEmpty(settingValue))
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = defaultValue;
                                    }
                                    else
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = long.Parse(settingValue, System.Globalization.CultureInfo.InvariantCulture);
                                    }
                                }
                                else if (controlType == "Slider")
                                {
                                    double defaultValue = double.Parse(controlParameters.Substring(0, controlParameters.IndexOf("[")));
                                    if (string.IsNullOrEmpty(settingValue))
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = defaultValue;
                                    }
                                    else
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = double.Parse(settingValue, System.Globalization.CultureInfo.InvariantCulture);
                                    }
                                }
                                else if (controlType == "Font")
                                {
                                    string[] font = System.Text.Json.JsonSerializer.Deserialize<string[]>(controlParameters, Modules.DefaultSerializationOptions);

                                    VectSharp.Font fnt = new VectSharp.Font(new VectSharp.FontFamily(font[0]), double.Parse(font[1], System.Globalization.CultureInfo.InvariantCulture));

                                    if (string.IsNullOrEmpty(settingValue))
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = fnt;
                                    }
                                    else
                                    {
                                        string[] splitSettingValue = settingValue.Split(',');
                                        VectSharp.Font newFont = new VectSharp.Font(new VectSharp.FontFamily(splitSettingValue[0]), double.Parse(splitSettingValue[1], System.Globalization.CultureInfo.InvariantCulture));

                                        GlobalSettings.Settings.AdditionalSettings[name] = double.Parse(settingValue, System.Globalization.CultureInfo.InvariantCulture);
                                    }
                                }
                                else if (controlType == "Point")
                                {
                                    double[] point = System.Text.Json.JsonSerializer.Deserialize<double[]>(controlParameters, Modules.DefaultSerializationOptions);
                                    VectSharp.Point pt = new VectSharp.Point(point[0], point[1]);

                                    if (string.IsNullOrEmpty(settingValue))
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = pt;
                                    }
                                    else
                                    {
                                        string[] splitSettingValue = settingValue.Split(',');
                                        VectSharp.Point newPoint = new VectSharp.Point(double.Parse(splitSettingValue[0], System.Globalization.CultureInfo.InvariantCulture), double.Parse(splitSettingValue[1], System.Globalization.CultureInfo.InvariantCulture));

                                        GlobalSettings.Settings.AdditionalSettings[name] = newPoint;
                                    }
                                }
                                else if (controlType == "Colour")
                                {
                                    int[] colour = System.Text.Json.JsonSerializer.Deserialize<int[]>(controlParameters, Modules.DefaultSerializationOptions);

                                    VectSharp.Colour col = VectSharp.Colour.FromRgba((byte)colour[0], (byte)colour[1], (byte)colour[2], (byte)colour[3]);

                                    if (string.IsNullOrEmpty(settingValue))
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = col;
                                    }
                                    else
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = Colour.FromCSSString(settingValue) ?? col;
                                    }
                                }
                                else if (controlType == "Dash")
                                {
                                    double[] dash = System.Text.Json.JsonSerializer.Deserialize<double[]>(controlParameters, Modules.DefaultSerializationOptions);

                                    VectSharp.LineDash lineDash = new VectSharp.LineDash(dash[0], dash[1], dash[2]);

                                    if (string.IsNullOrEmpty(settingValue))
                                    {
                                        GlobalSettings.Settings.AdditionalSettings[name] = lineDash;
                                    }
                                    else
                                    {
                                        string[] splitSettingValue = settingValue.Split(',');
                                        VectSharp.LineDash newDash = new VectSharp.LineDash(double.Parse(splitSettingValue[0], System.Globalization.CultureInfo.InvariantCulture), double.Parse(splitSettingValue[1], System.Globalization.CultureInfo.InvariantCulture), double.Parse(splitSettingValue[2], System.Globalization.CultureInfo.InvariantCulture));

                                        GlobalSettings.Settings.AdditionalSettings[name] = newDash;
                                    }
                                }

                                found = true;
                                break;
                            }
                        }

                        if (!found)
                        {
                            throw new ArgumentException("There is no global setting named \"" + settingName + "\"!");
                        }
                    }
                    break;
            }
        }

19 View Source File : CallIncidentCmd.cs
License : Apache License 2.0
Project Creator : AantCoder

public ModelStatus Execute(ref PlayerServer player, Chat chat, List<string> argsM)
        {
            Loger.Log("IncidentLod CallIncidentCmd Execute 1");
            var ownLogin = player.Public.Login;
            
            //базовая проверка аргументов
            if (argsM.Count < 2)
                return _chatManager.PostCommandPrivatPostActivChat(ChatCmdResult.IncorrectSubCmd, ownLogin, chat,
                    "OC_Incidents_CallIncidents_Err1");

            //собираем данные
            var type = CallIncident.ParseIncidentTypes(argsM[0]); 

            PlayerServer targetPlayer = Repository.GetPlayerByLogin(argsM[1]);
            if (targetPlayer == null)
            {
                return _chatManager.PostCommandPrivatPostActivChat(ChatCmdResult.UserNotFound, ownLogin, chat, "User " + argsM[1] + " not found");
            }

            long serverId = 0;
            if (argsM.Count > 2)
            {
                serverId = Int64.Parse(argsM[2]);
            }

            int mult = 1;
            if (argsM.Count > 3)
            {
                mult = Int32.Parse(argsM[3]);
            }

            //  walk, random, air
            IncidentArrivalModes? arrivalMode = null;
            if (argsM.Count > 4)
            {
                arrivalMode = CallIncident.ParseArrivalMode(argsM[4]);
            }

            string faction = null;
            if (argsM.Count > 5)
            {
                faction = CallIncident.ParseFaction(argsM[5]);
            }

            Loger.Log("IncidentLod CallIncidentCmd Execute 2");
            var error = CallIncident.CreateIncident(player, targetPlayer, serverId, type, mult, arrivalMode, faction);
            if (error != null)
            {
                Loger.Log("IncidentLod CallIncidentCmd Execute error: " + error);
                return _chatManager.PostCommandPrivatPostActivChat(ChatCmdResult.IncorrectSubCmd, ownLogin, chat, error);
            }

            //var msg = argsM[0] + " lvl " + mult + " for user " + targetPlayer.Public.Login + " from " + ownLogin;
            //_chatManager.AddSystemPostToPublicChat(msg);

            Loger.Log("IncidentLod CallIncidentCmd Execute 3");

            return new ModelStatus() { Status = 0 };
        }

19 View Source File : VkTracksService.cs
License : Apache License 2.0
Project Creator : artemshuba

public async Task<bool> AddTracksToPlaylist(List<AudioVk> tracks, string playlistId)
        {
            return await _vk.Audio.MoveToAlbum(long.Parse(playlistId), tracks.Select(t => long.Parse(t.Id)).ToList());
        }

19 View Source File : UpdateChecker.cs
License : GNU General Public License v3.0
Project Creator : Albo1125

public static void InitialiseUpdateCheckingProcess()
        {
            Game.LogTrivial("Albo1125.Common " + replacedembly.GetExecutingreplacedembly().GetName().Version.ToString() + ", developed by Albo1125. Starting update checks.");
            Directory.CreateDirectory("Albo1125.Common/UpdateInfo");
            if (!File.Exists("Albo1125.Common/CommonVariables.xml"))
            {
                new XDoreplacedent(
                        new XElement("CommonVariables")
                    )
                    .Save("Albo1125.Common/CommonVariables.xml");
            }
            try
            {
                XDoreplacedent CommonVariablesDoc = XDoreplacedent.Load("Albo1125.Common/CommonVariables.xml");
                if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT") == null) { CommonVariablesDoc.Root.Add(new XElement("NextUpdateCheckDT")); }
                if (!string.IsNullOrWhiteSpace((string)CommonVariablesDoc.Root.Element("NextUpdateCheckDT")))
                {

                    try
                    {
                        if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value == replacedembly.GetExecutingreplacedembly().GetName().Version.ToString())
                        {
                            Game.LogTrivial("Albo1125.Common update checking has been disabled. Skipping checks.");
                            Game.LogTrivial("Albo1125.Common note: please do not request support for old versions.");
                            return;
                        }
                        DateTime UpdateCheckDT = DateTime.FromBinary(long.Parse(CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value));
                        if (DateTime.Now < UpdateCheckDT)
                        {

                            Game.LogTrivial("Albo1125.Common " + replacedembly.GetExecutingreplacedembly().GetName().Version.ToString() + ", developed by Albo1125. Not checking for updates until " + UpdateCheckDT.ToString());
                            return;
                        }
                    }
                    catch (Exception e) { Game.LogTrivial(e.ToString()); Game.LogTrivial("Albo1125.Common handled exception. #1"); }

                }

                
                DateTime NextUpdateCheckDT = DateTime.Now.AddDays(1);
                if (CommonVariablesDoc.Root.Element("NextUpdateCheckDT") == null) { CommonVariablesDoc.Root.Add(new XElement("NextUpdateCheckDT")); }
                CommonVariablesDoc.Root.Element("NextUpdateCheckDT").Value = NextUpdateCheckDT.ToBinary().ToString();
                CommonVariablesDoc.Save("Albo1125.Common/CommonVariables.xml");
                CommonVariablesDoc = null;
                GameFiber.StartNew(delegate
                {


                    GetUpdateNodes();
                    foreach (UpdateEntry entry in AllUpdateEntries.ToArray())
                    {
                        CheckForModificationUpdates(entry.Name, new Version(FileVersionInfo.GetVersionInfo(entry.Path).FileVersion), entry.FileID, entry.DownloadLink);
                    }
                    if (PluginsDownloadLink.Count > 0) { DisplayUpdates(); }
                    Game.LogTrivial("Albo1125.Common " + replacedembly.GetExecutingreplacedembly().GetName().Version.ToString() + ", developed by Albo1125. Update checks complete.");
                });
            }
            catch (System.Xml.XmlException e)
            {
                Game.LogTrivial(e.ToString());
                Game.DisplayNotification("Error while processing XML files. To fix this, please delete the following folder and its contents: Grand Theft Auto V/Albo1125.Common");
                Albo1125.Common.CommonLibrary.ExtensionMethods.DisplayPopupTextBoxWithConfirmation("Albo1125.Common", "Error while processing XML files. To fix this, please delete the following folder and its contents: Grand Theft Auto V/Albo1125.Common", false);
                throw e;
            }

            



        }

19 View Source File : MyMusicViewModel.cs
License : Apache License 2.0
Project Creator : artemshuba

private async Task LoadTracks(string playlistId = null, bool withoutPlaylistOnly = false)
        {
            TaskStarted("tracks");

            try
            {
                var albumId = playlistId != null ? long.Parse(playlistId) : 0;
                var tracks = await _tracksService.GetTracks(albumId: albumId);
                if (tracks == null)
                    return;

                if (withoutPlaylistOnly)
                    tracks = tracks?.Where(t => t.PlaylistId == 0).ToList();

                if (Tracks != null)
                    Tracks.CollectionChanged -= Tracks_CollectionChanged;

                Tracks = new ObservableCollection<IAudio>(tracks);
                Tracks.CollectionChanged += Tracks_CollectionChanged;
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Unable to load tracks");
            }
            finally
            {
                TaskFinished("tracks");
            }

            if (!Tracks.IsNullOrEmpty() && AudioService.Instance.CurrentPlaylist.Items.Count == 0)
            {
                AudioService.Instance.SetCurrentPlaylist(new AudioPlaylist(Tracks));
            }
        }

19 View Source File : ApiControlerEx.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

protected long GetLongArg(string name, long def = -1)
        {
            var value = GetArgValue(name);
            if (string.IsNullOrEmpty(value) || value == "undefined" || value == "null") return def;
            return long.Parse(value);
        }

19 View Source File : Check.cs
License : MIT License
Project Creator : arttonoyan

public static long AsInt64(object obj)
        {
            if (obj == null || obj == DBNull.Value)
                return 0;

            return long.Parse(obj.ToString());
        }

19 View Source File : ConfigLoader.cs
License : MIT License
Project Creator : alexis-

public static long GetRulesTimestampFromFileName(string fileName)
    {
      return String.IsNullOrWhiteSpace(fileName)
        ? -1
        : Int64.Parse(RuleFileNameRegex.Match(fileName).Groups[1].Value);
    }

19 View Source File : HttpHandler.cs
License : MIT License
Project Creator : Ashesh3

public bool CompleteSignup(string alias, string preplacedword,
            Action<string> updateStatus,
            ref long steamId, ref int gamesNotAdded,
            IEnumerable<Models.GameInfo> addThisGames,
            Models.ProfileConfig profileConfig)
        {
            Logger.Trace("Creating account: compliting signup...");

            if (!CheckAlias(alias, updateStatus))
                return false;
            if (!CheckPreplacedword(preplacedword, alias, updateStatus))
                return false;

            SetConfig(Defaults.Web.STEAM_CREATE_ACCOUNT_URI, Method.POST);
            _request.AddParameter("accountname", alias);
            _request.AddParameter("preplacedword", preplacedword);
            _request.AddParameter("creation_sessionid", _sessionId);
            _request.AddParameter("count", "1");
            _request.AddParameter("lt", "0");

            var response = _client.Execute(_request);

            dynamic jsonResponse = JsonConvert.DeserializeObject(response.Content);
            if (jsonResponse.bSuccess == "true")
            {
                Logger.Debug("Creating account: Account created");
                updateStatus?.Invoke("Account created");
                //disable guard
                Logger.Debug("Creating account: Disabling guard");
                _client.FollowRedirects = false;
                SetConfig("https://store.steampowered.com/twofactor/manage", Method.POST);
                _request.AddParameter("action", "none");
                _request.AddParameter("sessionid", _sessionId);
                _request.AddParameter("none_authenticator_check", "on");
                var response1 = _client.Execute(_request);
                var sessionId = "";

                var cookies = _cookieJar.GetCookies(new Uri("https://store.steampowered.com/"));
                foreach (Cookie cookie in cookies)
                {
                    _cookieJar.Add(new Uri("https://steamcommunity.com"), cookie);

                    if (cookie.Name.ToLower() == "sessionid")
                    {
                        sessionId = cookie?.Value ?? "";
                    }
                }

                if (string.IsNullOrEmpty(sessionId))
                {
                    Logger.Warn($"SessionID cookie not found for: {alias}");
                    updateStatus?.Invoke("Account seems created but SessionID cookie not found. Cannot disable guard, add game(s), set profile.");
                    return true;
                }

                SetConfig("https://store.steampowered.com/twofactor/manage_action", Method.POST);
                _request.AddParameter("action", "actuallynone");
                _request.AddParameter("sessionid", sessionId);
                var response11 = _client.Execute(_request);
                _client.FollowRedirects = true;

                var _steamIdRegex = SteamProfileRegex.Match(response1?.Content ?? "");
                if (!_steamIdRegex.Success)
                    _steamIdRegex = SteamProfileRegex.Match(response11?.Content ?? "");

                if (_steamIdRegex.Success)
                {
                    Logger.Trace($"Creating account: SteamID64 found ({_steamIdRegex.Groups[1].Value}).");
                    steamId = long.Parse(_steamIdRegex.Groups[1].Value);
                }

                gamesNotAdded = 0;
                foreach (var game in addThisGames)
                {
                    if (game == null)
                        continue;

                    var addSuccess = false;

                    try
                    {
                        Logger.Debug($"Creating account: Adding game({game.SubId}:{game.Name})");
                        updateStatus($"Adding game: {game.Name}");

                        SetConfig("https://store.steampowered.com/checkout/addfreelicense", Method.POST);
                        _request.AddParameter("action", "add_to_cart");
                        _request.AddParameter("subid", game.SubId);
                        _request.AddParameter("sessionid", sessionId);
                        var responce111 = _client.Execute(_request);
                        _client.FollowRedirects = true;

                        addSuccess = Regex.IsMatch(responce111?.Content ?? "", $"steam://subscriptioninstall/{game.SubId}", RegexOptions.IgnoreCase);
                    }
                    catch { }

                    if (!addSuccess)
                    {
                        gamesNotAdded++;
                        Logger.Warn($"Creating account: Adding game({game.SubId}:{game.Name}) failed!");
                    }

                    if (game != addThisGames.Last())
                        Thread.Sleep(500);
                }

                if ((profileConfig?.Enabled ?? false) && steamId > 0)
                {
                    Logger.Debug("Updating profile info...");
                    updateStatus("Updating profile info...");

                    var profCli = new RestClient("https://steamcommunity.com")
                    {
                        CookieContainer = _cookieJar
                    };
                    var profReq = new RestRequest($"/profiles/{steamId}/edit", Method.POST);
                    profReq.AddHeader("Referer", $"https://steamcommunity.com/profiles/{steamId}/edit?welcomed=1");
                    profReq.AddParameter("sessionID", sessionId);
                    profReq.AddParameter("type", "profileSave");
                    profReq.AddParameter("personaName", profileConfig.Name);
                    profReq.AddParameter("real_name", profileConfig.RealName);
                    profReq.AddParameter("country", profileConfig.Country);
                    profReq.AddParameter("state", profileConfig.State);
                    profReq.AddParameter("city", profileConfig.City);
                    if (profileConfig.Url)
                        profReq.AddParameter("customURL", alias);
                    profReq.AddParameter("summary", profileConfig.Bio);

                    var profRes = profCli.Execute(profReq);

                    if (System.IO.File.Exists(profileConfig?.Image ?? ""))
                    {
                        var imageInfo = new FileInfo(profileConfig.Image);
                        if (imageInfo.Length <= MainForm.PHOTO_MAX_SIZE)
                        {
                            Logger.Debug("Uploading image...");
                            updateStatus("Uploading image...");

                            var photoReq = new RestRequest("/actions/FileUploader", Method.POST, DataFormat.Json)
                            {
                                JsonSerializer = new RestSharp.Serializers.Newtonsoft.Json.NewtonsoftJsonSerializer()
                            };

                            photoReq.AddParameter("MAX_FILE_SIZE", $"{MainForm.PHOTO_MAX_SIZE}");
                            photoReq.AddParameter("type", "player_avatar_image");
                            photoReq.AddParameter("sId", $"{steamId}");
                            photoReq.AddParameter("sessionid", $"{sessionId}");
                            photoReq.AddParameter("doSub", "1");
                            photoReq.AddParameter("json", "1");
                            photoReq.AddFile("avatar", imageInfo.FullName);

                            var resp = profCli.Execute<Models.Steam.UploadProfileImage>(photoReq);
                            var imgUploadOk = resp?.Data?.Success ?? false;
                            if (imgUploadOk)
                                Logger.Debug("Uploading image done!");
                            else
                                Logger.Debug("Something went wrong with uloading image");
                        }
                    }

                    Logger.Debug("Updating profile info done!");
                }

                Logger.Debug("Creating account: done!");
                return true;
            }
            Logger.Debug($"Creating account: {jsonResponse.details}");
            updateStatus?.Invoke((jsonResponse.details as object)?.ToString() ?? "Accounts seems to be created but something broken...");
            return false;
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 499116344

private static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                throw new Exception("参数数量错误:账号 密码。");
            }
            var user = new QQUser(long.Parse(args[0]), args[1]); // 虽然已经太迟了,但是还是把密码去掉了... 起码总比在这里好啊!(塞口球
            var socketServer = new SocketServiceImpl(user);
            var transponder = new Transponder();
            var sendService = new SendMessageServiceImpl(socketServer, user);

            var manage = new MessageManage(socketServer, user, transponder);

            var robot = new TestRobot(sendService, transponder, user);

            manage.Init();
            Console.ReadKey();
        }

19 View Source File : StringReader.cs
License : MIT License
Project Creator : AtomicBlom

public long ReadLong()
		{
			var start = Cursor;
			while (CanRead() && IsAllowedNumber(Peek()))
			{
				Skip();
			}

			var number = String.Substring(start, Cursor - start);
			if (number.Length == 0)
			{
				throw CommandSyntaxException.BuiltInExceptions.ReaderExpectedLong().CreateWithContext(this);
			}

			try
			{
				return long.Parse(number);
			}
			catch (FormatException)
			{
				Cursor = start;
				throw CommandSyntaxException.BuiltInExceptions.ReaderInvalidLong().CreateWithContext(this, number);
			}
		}

19 View Source File : FunctionExtensions.cs
License : MIT License
Project Creator : alfa-laboratory

public static object parseLong(string str)
        {
            try
            {
                return long.Parse(str);
            }
            catch (FormatException ex)
            {
                Log.Logger().LogWarning($"Parsing string to long return an error {ex.Message}.");
                return str;
            }
        }

19 View Source File : DefaultParamValueProcessors.cs
License : MIT License
Project Creator : aillieo

public long Load(string serializedValue)
        {
            return long.Parse(serializedValue);
        }

19 View Source File : RedisReader.cs
License : MIT License
Project Creator : 2881099

public long ReadInt(bool checkType = true)
        {
            if (checkType)
                ExpectType(RedisMessage.Int);

            string line = ReadLine();
            return Int64.Parse(line.ToString());
        }

19 View Source File : OCIncident.cs
License : Apache License 2.0
Project Creator : AantCoder

public static string GetCostOnGameByCommand(string command, bool onliCheck, out string error)
        {
            Loger.Log("IncidentLod OCIncident.GetCostOnGameByCommand 1 command:" + command);
            //разбираем аргументы в кавычках '. Удвоенная кавычка указывает на её символ.
            string cmd;
            List<string> args;
            ChatUtils.ParceCommand(command, out cmd, out args);

            if (args.Count < 3)
            {
                error = "OC_Incidents_OCIncident_WrongArg".Translate().ToString();
                Loger.Log("IncidentLod OCIncident.GetCostOnGameByCommand error:" + error);
                return null;
            }

            // /call raid '111' 1 10 air tribe

            //проверка, что денег хватает
            int cost = OCIncident.CalculateRaidCost(args[0].ToLower(), Int64.Parse(args[2])
                , args.Count > 3 ? Int32.Parse(args[3]) : 1
                , args.Count > 4 ? args[4].ToLower() : null
                , args.Count > 5 ? args[5].ToLower() : null);
            int gold = -1;

            Map map = null;
            if (cost > 0)
            {
                gold = GameUtils.FindThings(ThingDefOf.Gold, 0, false);
            }

            if (cost < 0 || gold < 0 || gold < cost)
            {
                error = cost < 0 || gold < 0
                    ? "OC_Incidents_OCIncident_WealthErr".Translate().ToString() + $" cost={cost} gold={gold}"
                    : "OC_Incidents_OCIncident_GoldErr".Translate(gold, cost, cost - gold).ToString();
                Loger.Log("IncidentLod OCIncident.GetCostOnGameByCommand error:" + error);
                return null;
            }

            if (onliCheck)
            {
                error = null;
                return "OC_Incidents_OCIncident_NotEnoughGold".Translate(cost);
            }

            Loger.Log("IncidentLod OCIncident.GetCostOnGameByCommand 2");

            //отнимаем нужное кол-во денег(золото или серебро... или что-нибудь ещё)
            GameUtils.FindThings(ThingDefOf.Gold, cost, false);

            Loger.Log("IncidentLod OCIncident.GetCostOnGameByCommand 3");
            //принудительное сохранение
            if (!SessionClientController.Data.BackgroundSaveGameOff)
                SessionClientController.SaveGameNow(true);
            Loger.Log("IncidentLod ChatController.AfterStartIncident 4");

            error = null;
            return "OC_Incidents_OCIncident_GoldPay".Translate(cost);
        }

19 View Source File : CertExtensions.cs
License : MIT License
Project Creator : ActiveLogin

private static DateTime ParseUnixTimestampMillis(string milliseconds)
        {
            return DateTimeFromUnixTimestampMilliseconds(long.Parse(milliseconds));
        }

19 View Source File : TechLogItem.cs
License : MIT License
Project Creator : akpaevj

private long? GetLongOrNull(string propertyName)
        {
            if (AllProperties.TryGetValue(propertyName, out var value))
                return long.Parse(value);
            else
                return null;
        }

19 View Source File : AnalogyFilePlotting.cs
License : MIT License
Project Creator : Analogy-LogViewer

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        private void ProcessLine(string line)
        {
            try
            {
                var items = line.Split(seperators);
                if (CustomXAxis)
                {
                    switch (_xAxisType)
                    {
                        case replacedogyCustomXAxisPlot.Numerical:
                            var x = double.Parse(items[0]);
                            for (int i = 1; i < items.Length; i++)
                            {
                                var str = items[i];
                                double val = double.Parse(str);
                                string series = headers[i];
                                var data = new replacedogyPlottingPointData(series, val, x);
                                OnNewPointData?.Invoke(this, data);
                            }
                            break;
                        case replacedogyCustomXAxisPlot.DateTimeUnixMillisecond:
                            DateTime timeMili = DateTimeOffset.FromUnixTimeMilliseconds(long.Parse(items[0])).DateTime;
                            for (int i = 1; i < items.Length; i++)
                            {
                                var str = items[i];
                                double val = double.Parse(str);
                                string series = headers[i];
                                var data = new replacedogyPlottingPointData(series, val, timeMili);
                                OnNewPointData?.Invoke(this, data);
                            }
                            break;
                        case replacedogyCustomXAxisPlot.DateTimeUnixSecond:
                            DateTime timeSecond = DateTimeOffset.FromUnixTimeSeconds(long.Parse(items[0])).DateTime;
                            for (int i = 1; i < items.Length; i++)
                            {
                                var str = items[i];
                                double val = double.Parse(str);
                                string series = headers[i];
                                var data = new replacedogyPlottingPointData(series, val, timeSecond);
                                OnNewPointData?.Invoke(this, data);
                            }
                            break;
                        default:
                            throw new ArgumentOutOfRangeException();
                    }
                }
                else
                {
                    for (int i = 0; i < items.Length; i++)
                    {
                        var str = items[i];
                        double val = double.Parse(str);
                        string series = headers[i];
                        var data = new replacedogyPlottingPointData(series, val, processed);
                        OnNewPointData?.Invoke(this, data);
                    }
                }
                processed++;
            }
            catch (Exception e)
            {
                replacedogyLogManager.Instance.LogError(e.ToString(), nameof(replacedogyFilePlotting));
            }

        }

See More Examples