Example #1
0
        internal static void Initialize()
        {
            if (Initialized)
            {
                return;
            }
            Trace.AutoFlush = true;
            var logDir  = Path.Combine(Config.Instance.DataDir, "Logs");
            var logFile = Path.Combine(logDir, "hdt_log.txt");

            if (!Directory.Exists(logDir))
            {
                Directory.CreateDirectory(logDir);
            }
            else
            {
                try
                {
                    var fileInfo = new FileInfo(logFile);
                    if (fileInfo.Exists)
                    {
                        using (var fs = new FileStream(logFile, FileMode.Open, FileAccess.Read, FileShare.None))
                        {
                            //can access log file => no other instance of same installation running
                        }
                        File.Move(logFile, logFile.Replace(".txt", "_" + DateTime.Now.ToUnixTime() + ".txt"));
                        //keep logs from the last 2 days plus 25 before that
                        foreach (var file in
                                 new DirectoryInfo(logDir).GetFiles("hdt_log*")
                                 .Where(x => x.LastWriteTime < DateTime.Now.AddDays(-MaxLogFileAge))
                                 .OrderByDescending(x => x.LastWriteTime)
                                 .Skip(KeepOldLogs))
                        {
                            try
                            {
                                File.Delete(file.FullName);
                            }
                            catch
                            {
                            }
                        }
                    }
                    else
                    {
                        File.Create(logFile).Dispose();
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("Another instance of Hearthstone Deck Tracker is already running.",
                                    "Error starting Hearthstone Deck Tracker", MessageBoxButton.OK, MessageBoxImage.Error);
                    Application.Current.Shutdown();
                    return;
                }
            }
            try
            {
                Trace.Listeners.Add(new TextWriterTraceListener(new StreamWriter(logFile, false)));
            }
            catch (Exception ex)
            {
                ErrorManager.AddError("Can not access log file.", ex.ToString());
            }
            Initialized = true;
            foreach (var line in LogQueue)
            {
                Trace.WriteLine(line);
            }
        }
        public void WriteStreamMulti(TextWriter writer, IEnumerable <T> records, int maxRecords)
        {
            if (writer == null)
            {
                throw new ArgumentNullException(nameof(writer), "The writer of the Stream can be null");
            }

            if (records == null)
            {
                throw new ArgumentNullException(nameof(records), "The records can be null. Try with an empty array.");
            }

            ResetFields();

            writer.NewLine = NewLineForWrite;

            if (!string.IsNullOrEmpty(HeaderText))
            {
                if (HeaderText.EndsWith(NewLineForWrite))
                {
                    writer.Write(HeaderText);
                }
                else
                {
                    writer.WriteLine(HeaderText);
                }
            }

            var max = records is IList?Math.Min(((IList)records).Count, maxRecords) : maxRecords;

            if (MustNotifyProgress) // Avoid object creation
            {
                OnProgress(new ProgressEventArgs(0, max));
            }

            var recIndex = 0;

            var    first       = true;
            string currentLine = null;

            foreach (var rec in records)
            {
                if (recIndex == maxRecords)
                {
                    break;
                }

                LineNumber++;
                try
                {
                    if (rec == null)
                    {
                        throw new BadUsageException($"The record at index {recIndex} is null.");
                    }

                    if (first)
                    {
                        first = false;
                        if (RecordInfo.RecordType.IsInstanceOfType(rec) == false)
                        {
                            throw new BadUsageException($"This engine works with record of type {RecordInfo.RecordType.Name} and you use records of type {rec.GetType().Name}");
                        }
                    }

                    var skip = false;

                    if (MustNotifyProgress) // Avoid object creation
                    {
                        OnProgress(new ProgressEventArgs(recIndex + 1, max));
                    }

                    if (MustNotifyWrite)
                    {
                        skip = OnBeforeWriteRecord(rec, LineNumber);
                    }

                    if (skip == false)
                    {
                        currentLine = RecordInfo.Operations.RecordToString(rec);
                        if (MustNotifyWrite)
                        {
                            currentLine = OnAfterWriteRecord(currentLine, rec);
                        }
                        writer.WriteLine(currentLine);
                    }
                }
                catch (Exception ex)
                {
                    switch (ErrorManager.ErrorMode)
                    {
                    case ErrorMode.ThrowException: throw;

                    case ErrorMode.IgnoreAndContinue: break;

                    case ErrorMode.SaveAndContinue:
                        var err = new ErrorInfo
                        {
                            LineNumber    = LineNumber,
                            ExceptionInfo = ex,
                            Text          = currentLine
                        };
                        ErrorManager.AddError(err);
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                }
                recIndex++;
            }

            TotalRecords = recIndex;

            if (string.IsNullOrEmpty(FooterText))
            {
                return;
            }
            if (FooterText.EndsWith(NewLineForWrite))
            {
                writer.Write(FooterText);
            }
            else
            {
                writer.WriteLine(FooterText);
            }
        }
        public static async Task SyncCollection()
        {
            if (!Config.Instance.SyncCollection || !HSReplayNetOAuth.IsFullyAuthenticated)
            {
                return;
            }
            var collection = await CollectionHelper.GetCollection();

            if (collection == null)
            {
                return;
            }
            var hash    = collection.GetHashCode();
            var hi      = collection.AccountHi;
            var lo      = collection.AccountLo;
            var account = hi + "-" + lo;

            if (Account.Instance.CollectionState.TryGetValue(account, out var state) && state.Hash == hash)
            {
                Log.Debug("Collection ready up-to-date");
                state.Date = DateTime.Now;
                Account.Save();
                CollectionAlreadyUpToDate?.Invoke();
                return;
            }
            await CollectionSyncLimiter.Run(async() =>
            {
                if (!HSReplayNetOAuth.AccountData?.BlizzardAccounts?.Any(x => x.AccountHi == hi && x.AccountLo == lo) ?? true)
                {
                    var response = await HSReplayNetOAuth.ClaimBlizzardAccount(hi, lo, collection.BattleTag);
                    var success  = response == HSReplayNetOAuth.ClaimBlizzardAccountResponse.Success;
                    BlizzardAccountClaimed?.Invoke(success);
                    if (success)
                    {
                        HSReplayNetOAuth.UpdateAccountData().Forget();
                    }
                    else if (response == HSReplayNetOAuth.ClaimBlizzardAccountResponse.TokenAlreadyClaimed)
                    {
                        ErrorManager.AddError("HSReplay.net error",
                                              $"Your blizzard account ({collection.BattleTag}, {account}) is already attached to another"
                                              + " HSReplay.net Account. Please contact us at [email protected]"
                                              + " if this is not correct.");
                        return;
                    }
                    else
                    {
                        ErrorManager.AddError("HSReplay.net error",
                                              $"Could not attach your Blizzard account ({collection.BattleTag}, {account}) to"
                                              + $" HSReplay.net Account ({HSReplayNetOAuth.AccountData?.Username})."
                                              + " Please try again later or contact us at [email protected] if this persists.");
                        return;
                    }
                }
                if (await HSReplayNetOAuth.UpdateCollection(collection))
                {
                    Account.Instance.CollectionState[account] = new Account.SyncState(hash);
                    Account.Save();
                    Log.Debug("Collection synced");
                    CollectionUploaded?.Invoke();
                }
                else
                {
                    ErrorManager.AddError("HSReplay.net error",
                                          "Could not update your collection. Please try again later.\n"
                                          + "If this problem persists please try logging out and back in"
                                          + " under 'options > hsreplay.net > my account'");
                    CollectionUploadError?.Invoke();
                }
            }, () =>
            {
                Log.Debug("Waiting for rate limit...");
                CollectionUploadThrottled?.Invoke();
            });
        }
        private IList ReadStreamAsList(TextReader reader, int maxRecords, DataTable dt)
        {
            if (reader == null)
            {
                throw new ArgumentNullException(nameof(reader), "The reader of the Stream canĀ“t be null");
            }

            HeaderText = string.Empty;
            FooterText = string.Empty;

            IList result;

            using (var recordReader = new TextReaderWrapper(reader))
            {
                ResetFields();


                if (_objectEngine)
                {
                    result = new ArrayList();
                }
                else
                {
                    result = new List <T>();
                }

                var currentRecord = 0;

                var streamInfo = new StreamInfoProvider(reader);
                using (var freader = new ForwardReader(recordReader, RecordInfo.IgnoreLast))
                {
                    freader.DiscardForward = true;

                    string currentLine, completeLine;

                    LineNumber = 1;

                    completeLine = freader.ReadNextLine();
                    currentLine  = completeLine;

                    if (MustNotifyProgress) // Avoid object creation
                    {
                        OnProgress(new ProgressEventArgs(0, -1, streamInfo.Position, streamInfo.TotalBytes));
                    }

                    if (RecordInfo.IgnoreFirst > 0)
                    {
                        for (var i = 0; i < RecordInfo.IgnoreFirst && currentLine != null; i++)
                        {
                            HeaderText += currentLine + Environment.NewLine;
                            currentLine = freader.ReadNextLine();
                            LineNumber++;
                        }
                    }

                    var byPass = false;

                    if (maxRecords < 0)
                    {
                        maxRecords = int.MaxValue;
                    }

                    var line = new LineInfo(currentLine)
                    {
                        mReader = freader
                    };

                    var values = new object[RecordInfo.FieldCount];

                    while (currentLine != null &&
                           currentRecord < maxRecords)
                    {
                        completeLine = currentLine;

                        try
                        {
                            TotalRecords++;
                            currentRecord++;

                            line.ReLoad(currentLine);

                            var skip = false;

                            var record = (T)RecordInfo.Operations.CreateRecordHandler();

                            if (MustNotifyProgress) // Avoid object creation
                            {
                                OnProgress(new ProgressEventArgs(currentRecord,
                                                                 -1,
                                                                 streamInfo.Position,
                                                                 streamInfo.TotalBytes));
                            }

                            Events.BeforeReadEventArgs <T> e = null;
                            if (MustNotifyRead)
                            {
                                e    = new BeforeReadEventArgs <T>(this, record, currentLine, LineNumber);
                                skip = OnBeforeReadRecord(e);
                                if (e.RecordLineChanged)
                                {
                                    line.ReLoad(e.RecordLine);
                                }
                            }


                            if (skip == false)
                            {
                                if (RecordInfo.Operations.StringToRecord(record, line, values))
                                {
                                    if (MustNotifyRead) // Avoid object creation
                                    {
                                        skip = OnAfterReadRecord(currentLine, record, e.RecordLineChanged, LineNumber);
                                    }

                                    if (skip == false)
                                    {
                                        if (dt == null)
                                        {
                                            result.Add(record);
                                        }
                                        else
                                        {
                                            dt.Rows.Add(RecordInfo.Operations.RecordToValues(record));
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            switch (ErrorManager.ErrorMode)
                            {
                            case ErrorMode.ThrowException:
                                byPass = true;
                                throw;

                            case ErrorMode.IgnoreAndContinue:
                                break;

                            case ErrorMode.SaveAndContinue:
                                var err = new ErrorInfo
                                {
                                    LineNumber    = freader.LineNumber,
                                    ExceptionInfo = ex,
                                    Text          = completeLine
                                };

                                ErrorManager.AddError(err);
                                break;
                            }
                        }
                        finally
                        {
                            if (byPass == false)
                            {
                                currentLine = freader.ReadNextLine();
                                LineNumber++;
                            }
                        }
                    }

                    if (RecordInfo.IgnoreLast > 0)
                    {
                        FooterText = freader.RemainingText;
                    }
                }
            }
            return(result);
        }