Example #1
0
 private bool TryGetTotalLines(StreamReader sr, out LUint totalLines)
 {
     if (!LUint.TryParse(sr.ReadLine(), out totalLines))
     {
         LogHelper.Logln($"The file {infoFilePath} might not be in the format of Nameless song collection.", LogType.Error);
         return(false);
     }
     return(true);
 }
Example #2
0
        public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out TName result)
        {
            if (s == null)
            {
                result = 0;
                return(false);
            }

            var r = TType.TryParse(s, style, NumberFormatInfo.GetInstance(provider), out var res);

            result = res;
            return(r);
        }
Example #3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="lineNo"></param>
        /// <param name="newTimesPlayed"></param>
        /// <returns>Whether the program actually changed times played</returns>
        public async Task <bool> TryChangeTimesPlayed(LUint lineNo, LUint newTimesPlayed)
        {
            using (StreamWriter sw = File.CreateText(infoFilePath + "temp"))
                using (StreamReader sr = File.OpenText(infoFilePath))
                {
                    LUint  totalLines;
                    string line = await sr.ReadLineAsync();

                    if (!LUint.TryParse(line, out totalLines))
                    {
                        LogHelper.Logln($"{infoFilePath} is not encoded as expected.", LogType.Error);
                        sr.Close();
                        await sw.FlushAsync();

                        File.Delete(infoFilePath + "temp");
                        return(false);
                    }
                    if (totalLines == 0)
                    {
                        LogHelper.Logln($"Trying to change {infoFilePath}, which has 0 line of song in it!", LogType.Error);
                        sr.Close();
                        await sw.FlushAsync();

                        File.Delete(infoFilePath + "temp");
                        return(false);
                    }
                    if (totalLines < lineNo)
                    {
                        LogHelper.Logln($"Trying to change line {lineNo} out of {totalLines} in {infoFilePath}!.", LogType.Error);
                        sr.Close();
                        await sw.FlushAsync();

                        File.Delete(infoFilePath + "temp");
                        return(false);
                    }
                    try
                    {
                        await sw.WriteLineAsync(totalLines.ToString());

                        for (int i = 0; i < lineNo; i++)
                        {
                            await sw.WriteLineAsync(await sr.ReadLineAsync());
                        }
                        //Write the changing value
                        string changingString = await sr.ReadLineAsync();

                        await sw.WriteLineAsync(
                            SongCollectionFormatter.ChangeTimesPlayed(
                                changingString, newTimesPlayed));

                        for (; lineNo < totalLines; lineNo++)
                        {
                            await sw.WriteLineAsync(await sr.ReadLineAsync());
                        }
                    }
                    catch (Exception e)
                    {
                        LogHelper.Logln($"Error occured while reading {infoFilePath} and writing {infoFilePath + "temp"}. {e.Message}", LogType.Error);
                        sr.Close();
                        await sw.FlushAsync();

                        File.Delete(infoFilePath + "temp");
                        return(false);
                    }
                }
            try
            {
                File.Delete(infoFilePath);
                File.Move(infoFilePath + "temp", infoFilePath);
            }
            catch (Exception e)
            {
                LogHelper.Logln($"Error while deleting ${infoFilePath} and replacing {infoFilePath} with {infoFilePath + "temp"}. {e.Message}", LogType.Error);
            }
            LogHelper.Logln($"Successfully rewrite times played and flushed all underlying streams.", LogType.Success);
            return(true);
        }
Example #4
0
        public async Task <bool> TryChangeTimesPlayed(LUint lineNo, OfflineSong offlineSong)
        {
            using (StreamWriter sw = File.CreateText(infoFilePath + "temp"))
                using (StreamReader sr = File.OpenText(infoFilePath))
                {
                    LUint  totalLines;
                    string line = await sr.ReadLineAsync();

                    #region Precautions
                    if (!LUint.TryParse(line, out totalLines))
                    {
                        LogHelper.Logln($"{infoFilePath} is not encoded as expected.", LogType.Error);
                        sr.Close();
                        await sw.FlushAsync();

                        File.Delete(infoFilePath + "temp");
                        return(false);
                    }
                    if (totalLines == 0)
                    {
                        LogHelper.Logln($"Trying to change {infoFilePath}, which has 0 line of song in it!", LogType.Error);
                        sr.Close();
                        await sw.FlushAsync();

                        File.Delete(infoFilePath + "temp");
                        return(false);
                    }
                    if (totalLines < lineNo)
                    {
                        LogHelper.Logln($"Trying to change line {lineNo} out of {totalLines} in {infoFilePath}!.", LogType.Error);
                        sr.Close();
                        await sw.FlushAsync();

                        File.Delete(infoFilePath + "temp");
                        return(false);
                    }
                    #endregion
                    //totalLines is now assigned
                    try
                    {
                        await sw.WriteLineAsync(totalLines.ToString());

                        bool songRearranged = false;
                        for (int i = 0; i < lineNo; i++)
                        {
                            string songLine = await sr.ReadLineAsync();

                            if (!songRearranged)
                            {
                                if (SongCollectionFormatter.GetTimesPlayed(songLine) == offlineSong.timesPlayed)
                                {
                                    int min = Math.Min(SongCollectionFormatter.GetSongTitle(songLine).Length
                                                       , offlineSong.song.Title.Length);
                                    for (int j = 0; j < min; j++)
                                    {
                                        if (offlineSong.song.Title[j] < SongCollectionFormatter.GetSongTitle(songLine)[j] || j == min - 1)
                                        {
                                            songRearranged = true;
                                            await sw.WriteLineAsync(SongCollectionFormatter.SongFormatter(offlineSong));

                                            break;
                                        }
                                        else if (offlineSong.song.Title[j] > SongCollectionFormatter.GetSongTitle(songLine)[j])
                                        {
                                            break;
                                        }
                                    }
                                }
                                else if (SongCollectionFormatter.GetTimesPlayed(songLine) < offlineSong.timesPlayed)
                                {
                                    //We might want to re-arrange it if the song being changed the times played has
                                    //a promotion of rank
                                    songRearranged = true;
                                    await sw.WriteLineAsync(SongCollectionFormatter.SongFormatter(offlineSong));
                                }
                            }
                            await sw.WriteLineAsync(songLine);
                        }
                        await sr.ReadLineAsync(); //Move to next line on the reader since we don't need to use it

                        if (!songRearranged)      //If ranking does not change
                        {
                            await sw.WriteLineAsync(SongCollectionFormatter.SongFormatter(offlineSong));
                        }
                        for (; lineNo < totalLines; lineNo++) //DEBUNK THIS
                        {
                            await sw.WriteLineAsync(await sr.ReadLineAsync());
                        }
                    }
                    catch (Exception e)
                    {
                        LogHelper.Logln($"Error occured while reading {infoFilePath} and writing {infoFilePath + "temp"}. {e.Message}", LogType.Error);
                        sr.Close();
                        await sw.FlushAsync();

                        File.Delete(infoFilePath + "temp");
                        return(false);
                    }
                }
            #region Clean-up
            try
            {
                File.Delete(infoFilePath);
                File.Move(infoFilePath + "temp", infoFilePath);
            }
            catch (Exception e)
            {
                LogHelper.Logln($"Error while deleting ${infoFilePath} and replacing {infoFilePath} with {infoFilePath + "temp"}. {e.Message}", LogType.Error);
            }
            LogHelper.Logln($"Successfully rewrite times played and flushed all underlying streams.", LogType.Success);
            #endregion
            return(true);
        }
Example #5
0
        /// <summary>
        /// Please make sure the infoFilePath exists
        /// </summary>
        /// <param name="song"></param>
        /// <returns></returns>
        public async Task <bool> TryAddSongAsync(OfflineSong song)
        {
            bool songAdded;

            using (StreamReader sr = File.OpenText(infoFilePath))
                using (StreamWriter sw = File.CreateText(infoFilePath + "temp"))
                {
                    LUint  totalLines;
                    string line = await sr.ReadLineAsync();

                    if (!LUint.TryParse(line, out totalLines))
                    {
                        LogHelper.Logln($"{infoFilePath} is not encoded as expected.", LogType.Error);
                        sr.Close();
                        await sw.FlushAsync();

                        sw.Close();
                        File.Delete(infoFilePath + "temp");
                        return(false);
                    }
                    if (totalLines == 0)
                    {
                        await sw.WriteLineAsync('1');

                        await sw.WriteLineAsync(SongCollectionFormatter.SongFormatter(song));

                        sr.Close();
                        await sw.FlushAsync();

                        sw.Close();
                        File.Delete(infoFilePath);
                        File.Move(infoFilePath + "temp", infoFilePath);
                        return(true);
                    }
#if DEBUG
                    LogHelper.Logln($"Total lines = {totalLines}", LogType.Warning);
#endif
                    await sw.WriteLineAsync((totalLines + 1).ToString());

                    //We are now done with getting and writing the number of totalLines of the new file
                    songAdded = false;
                    for (int i = 0; i < totalLines; i++)
                    {
                        string songLine = await sr.ReadLineAsync();

                        if (!songAdded)
                        {
#if DEBUG
                            LogHelper.Logln("!songAdded; i = " + i);
#endif
                            LUint songLineTimesPlayed = SongCollectionFormatter.GetTimesPlayed(songLine);
                            if (songLineTimesPlayed == song.timesPlayed)
                            {
                                //2»aaaaaaa...
                                //1»abcde»... //songLine
                                //1»bcdefeee»... //song.song
                                string songTitle = SongCollectionFormatter.GetSongTitle(songLine);
                                int    minLength = Math.Min(song.song.Title.Length, songTitle.Length); //5, 8 => 5
                                for (int j = 0; j < minLength; j++)
                                {
                                    if (song.song.Title[j] < songTitle[j])
                                    //if the adding song is less than the existed one alphabetically
                                    {
                                        await sw.WriteLineAsync(SongCollectionFormatter.SongFormatter(song));

                                        songAdded = true;
                                        break;
                                    }
                                    else if (j == minLength - 1)
                                    //If the adding song is a modification of the existed one
                                    {
                                        if (song.song.Title.Length != songTitle.Length) //the original or the new one might be a remix
                                        {
                                            //It does not matter anymore if the new title is an inserted of an old one
                                            await sw.WriteLineAsync(SongCollectionFormatter.SongFormatter(song));

                                            songAdded = true;
                                            break;
                                        }
                                        else //same title, exit
                                        {
                                            string songDuration = SongCollectionFormatter.GetDuration(songLine);
                                            //Check duration of both
                                            if (songDuration == song.song.Duration)
                                            {
                                                //Same song
                                                sr.Close();
                                                await sw.FlushAsync();

                                                sw.Close();
                                                File.Delete(infoFilePath + "temp");
                                                return(true);
                                            }
                                            //The else case is automatically handled
                                        }
                                    }
                                    else if (song.song.Title[j] > songTitle[j])
                                    {
                                        break;
                                    }
                                }
                            }
                            else if (songLineTimesPlayed < song.timesPlayed)
                            {
                                await sw.WriteLineAsync(SongCollectionFormatter.SongFormatter(song));

                                songAdded = true;
                            }
                        }
                        await sw.WriteLineAsync(songLine);
                    }
                    if (!songAdded)
                    {
                        //When you have eliminated the impossible, whatever remains, however improbable, must be the truth.
                        //- Sherlock Holmes/Sir Arthur Conan Doyle
                        await sw.WriteLineAsync(SongCollectionFormatter.SongFormatter(song));

                        songAdded = true;
                    }
                }
            #region Clean-up (works perfectly)
#if DEBUG
            LogHelper.Logln("Flushed sr and sw.", LogType.Success);
#endif
            try
            {
#if DEBUG
                if (songAdded)
                {
                    LogHelper.Logln("Since songAdded, delete old file, replace new file", LogType.Success);
#endif
                File.Delete(infoFilePath);
                File.Move(infoFilePath + "temp", infoFilePath);
#if DEBUG
            }
            else
            {
                LogHelper.Logln("Since !songAdded, delete new file.", LogType.Success);
                File.Delete(infoFilePath + "temp");
            }
#endif
            }
            catch (Exception e)
            {
                LogHelper.Logln($"Error while deleting ${infoFilePath} and replacing {infoFilePath} with {infoFilePath + "temp"}. {e.Message}", LogType.Error);
            }
#if DEBUG
            LogHelper.Logln("TryAddSongAsync algorithm got to the bottom of before returning.", LogType.Success);
#endif
            #endregion
            return(songAdded);
        }
Example #6
0
        public static object Parse(Type enumType, string value, bool ignoreCase)
        {
            if (enumType == null)
            {
                throw new ArgumentNullException("enumType");
            }

            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            if (!enumType.IsEnum)
            {
                throw new ArgumentException("enumType is not an Enum type.", "enumType");
            }

            value = value.Trim();
            if (value.Length == 0)
            {
                throw new ArgumentException("An empty string is not considered a valid value.");
            }

            MonoEnumInfo info;

            MonoEnumInfo.GetInfo(enumType, out info);

            // is 'value' a named constant?
            int loc = FindName(info.name_hash, info.names, value, ignoreCase);

            if (loc >= 0)
            {
                return(info.values.GetValue(loc));
            }

            TypeCode typeCode = ((Enum)info.values.GetValue(0)).GetTypeCode();

            // is 'value' a list of named constants?
            if (value.IndexOf(',') != -1)
            {
                string [] names  = value.Split(split_char);
                ulong     retVal = 0;
                for (int i = 0; i < names.Length; ++i)
                {
                    loc = FindName(info.name_hash, info.names, names [i].Trim(), ignoreCase);
                    if (loc < 0)
                    {
                        throw new ArgumentException("The requested value was not found.");
                    }
                    retVal |= GetValue(info.values.GetValue(loc), typeCode);
                }
                return(ToObject(enumType, retVal));
            }

            // is 'value' a number?
#if !NET_2_0
            try {
                return(ToObject(enumType, Convert.ChangeType(value, typeCode)));
            } catch (FormatException) {
                throw new ArgumentException(String.Format("The requested value '{0}' was not found.", value));
            }
#else
            switch (typeCode)
            {
            case TypeCode.SByte:
                sbyte sb;
                if (SByte.TryParse(value, out sb))
                {
                    return(ToObject(enumType, sb));
                }
                break;

            case TypeCode.Byte:
                byte b;
                if (Byte.TryParse(value, out b))
                {
                    return(ToObject(enumType, b));
                }
                break;

            case TypeCode.Int16:
                short i16;
                if (Int16.TryParse(value, out i16))
                {
                    return(ToObject(enumType, i16));
                }
                break;

            case TypeCode.UInt16:
                ushort u16;
                if (UInt16.TryParse(value, out u16))
                {
                    return(ToObject(enumType, u16));
                }
                break;

            case TypeCode.Int32:
                int i32;
                if (Int32.TryParse(value, out i32))
                {
                    return(ToObject(enumType, i32));
                }
                break;

            case TypeCode.UInt32:
                uint u32;
                if (UInt32.TryParse(value, out u32))
                {
                    return(ToObject(enumType, u32));
                }
                break;

            case TypeCode.Int64:
                long i64;
                if (Int64.TryParse(value, out i64))
                {
                    return(ToObject(enumType, i64));
                }
                break;

            case TypeCode.UInt64:
                ulong u64;
                if (UInt64.TryParse(value, out u64))
                {
                    return(ToObject(enumType, u64));
                }
                break;

            default:
                break;
            }
            throw new ArgumentException(String.Format("The requested value '{0}' was not found.", value));
#endif
        }
Example #7
0
        static bool Parse <TEnum> (Type enumType, string value, bool ignoreCase, out TEnum result)
        {
            result = default(TEnum);

            MonoEnumInfo info;

            MonoEnumInfo.GetInfo(enumType, out info);

            // is 'value' a named constant?
            int loc = FindName(info.name_hash, info.names, value, ignoreCase);

            if (loc >= 0)
            {
                result = (TEnum)info.values.GetValue(loc);
                return(true);
            }

            TypeCode typeCode = ((Enum)info.values.GetValue(0)).GetTypeCode();

            // is 'value' a list of named constants?
            if (value.IndexOf(',') != -1)
            {
                if (split_char == null)
                {
                    split_char = new [] { ',' }
                }
                ;
                string [] names  = value.Split(split_char);
                ulong     retVal = 0;
                for (int i = 0; i < names.Length; ++i)
                {
                    loc = FindName(info.name_hash, info.names, names [i].Trim(), ignoreCase);
                    if (loc < 0)
                    {
                        return(false);
                    }

                    retVal |= GetValue(info.values.GetValue(loc), typeCode);
                }
                result = (TEnum)ToObject(enumType, retVal);
                return(true);
            }

            // is 'value' a number?
            switch (typeCode)
            {
            case TypeCode.SByte:
                sbyte sb;
                if (!SByte.TryParse(value, out sb))
                {
                    return(false);
                }
                result = (TEnum)ToObject(enumType, sb);
                break;

            case TypeCode.Byte:
                byte b;
                if (!Byte.TryParse(value, out b))
                {
                    return(false);
                }
                result = (TEnum)ToObject(enumType, b);
                break;

            case TypeCode.Int16:
                short i16;
                if (!Int16.TryParse(value, out i16))
                {
                    return(false);
                }
                result = (TEnum)ToObject(enumType, i16);
                break;

            case TypeCode.UInt16:
                ushort u16;
                if (!UInt16.TryParse(value, out u16))
                {
                    return(false);
                }
                result = (TEnum)ToObject(enumType, u16);
                break;

            case TypeCode.Int32:
                int i32;
                if (!Int32.TryParse(value, out i32))
                {
                    return(false);
                }
                result = (TEnum)ToObject(enumType, i32);
                break;

            case TypeCode.UInt32:
                uint u32;
                if (!UInt32.TryParse(value, out u32))
                {
                    return(false);
                }
                result = (TEnum)ToObject(enumType, u32);
                break;

            case TypeCode.Int64:
                long i64;
                if (!Int64.TryParse(value, out i64))
                {
                    return(false);
                }
                result = (TEnum)ToObject(enumType, i64);
                break;

            case TypeCode.UInt64:
                ulong u64;
                if (!UInt64.TryParse(value, out u64))
                {
                    return(false);
                }
                result = (TEnum)ToObject(enumType, u64);
                break;

            default:
                break;
            }

            return(true);
        }
Example #8
0
        /// <summary>
        /// String to UInt32(字符串 转换成 无符号、数值、整数)
        /// </summary>
        /// <remarks>
        ///  2014-06-23 16:31 Created By iceStone
        /// </remarks>
        /// <param name="s">String</param>
        /// <param name="def">Default</param>
        /// <returns>Byte</returns>
        public static uint ToUInt32(this string s, uint def = default(uint))
        {
            uint result;

            return(UInt32.TryParse(s, out result) ? result : def);
        }