Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

Poniżej znajduje się kod klasy FiscalPrinterService oraz komunikaty, które wyświetlają…

  1. User

    Poniżej znajduje się kod klasy FiscalPrinterService oraz komunikaty, które wyświetlają się w Visual Studio 2022. Zrefaktoryzuj kod, aby komunikaty przestały być wyświetlane.

    using FiscalPrinterApi.Extensions; using FiscalPrinterApi.Models; using NLog; using System; using System.Collections.Concurrent; using System.Net.Sockets; using System.Runtime.CompilerServices; using System.Text;

    [assembly: InternalsVisibleTo("FiscalPrinterApi.Test")]

    namespace FiscalPrinterApi.Services;

    /// /// Service for interacting with the fiscal printer. /// public class FiscalPrinterService : IFiscalPrinterService { private readonly ConcurrentDictionary<string, SemaphoreSlim> _printerSemaphores = new(); private IFiscalPrinterService? _sendCommandMock; private readonly static ConcurrentDictionary<string, ParagonAsyncStatusResponse> _tasks = new(); private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); private static readonly string[] RtcGetCommand = { "rtcget" }; private static readonly string[] VatGetCommand = { "vatget" }; private static readonly string[] HdrGetCommand = { "hdrget" }; private static readonly string[] FtrInfoGetCommand = { "ftrinfoget" }; private static readonly string[] PcCfgGetCommand = { "pccfgget", "pi1" }; private static readonly string[] TcpIpCfgGetCommand = { "tcpipcfgget" }; private static readonly string[] SdevCommand = { "sdev" }; private static readonly string[] SprnCommand = { "sprn" }; private static readonly string[] ScntCommand = { "scnt" }; private static readonly string[] StotCommand = { "stot" };

    /// <summary>
    /// Sets the mock implementation for the SendCommand method.
    /// </summary>
    /// <param name="mock">The mock implementation of the IFiscalPrinterService interface.</param>
    public void SetSendCommandMock(IFiscalPrinterService mock)
    {
        _sendCommandMock = mock;
    }
    
    private SemaphoreSlim GetPrinterSemaphore(string ip, int port)
    {
        string key = $"{ip}:{port}";
        return _printerSemaphores.GetOrAdd(key, _ => new SemaphoreSlim(1, 1));
    }
    
    /// <inheritdoc />
    public async Task<ParagonResponse> PrintFiscalDocument(ParagonRequest request, string ip, int port, bool bulkMode)
    {
        Logger.Info("Printing fiscal document for IP: {0}, Port: {1}", ip, port);
        var semaphore = GetPrinterSemaphore(ip, port);
        await semaphore.WaitAsync();
    
        ParagonResponse response = new();
        try
        {
            Logger.Debug("Initializing transaction.");
            await SendCommandToFiscalPrinter(["trinit", bulkMode ? "bm1" : "bm0"], ip, port);
    
            foreach (var line in request.Lines)
            {
                Logger.Debug("Sending line item: {0}", line.Na);
                await SendCommandToFiscalPrinter(["trline", $"na{line.Na}", $"il{line.Il}", $"vt{line.Vt}", $"pr{line.Pr}"], ip, port);
            }
    
            foreach (var extraLine in request.ExtraLines)
            {
                Logger.Debug("Sending extra line: {0}", extraLine.Id);
                await SendCommandToFiscalPrinter(["trftrln", $"id{extraLine.Id}", $"na{extraLine.Na}", $"sw{(extraLine.Sw ? 1 : 0)}", $"sh{(extraLine.Sh ? 1 : 0)}"], ip, port);
            }
    
            if (request.TaxIdInfo != null)
            {
                Logger.Debug("Sending tax ID info.");
                await SendCommandToFiscalPrinter(["trnipset", $"ni{request.TaxIdInfo.Ni}", $"dw{(request.TaxIdInfo.Dw ? 1 : 0)}", $"ds{request.TaxIdInfo.Ds}"], ip, port);
            }
    
            foreach (var payment in request.Payments)
            {
                Logger.Debug("Sending payment: {0}", payment.Ty);
                await SendCommandToFiscalPrinter(["trpayment", $"ty{(int)payment.Ty}", $"wa{payment.Wa}", $"na{payment.Na}", $"re{(payment.Re ? 1 : 0)}"], ip, port);
            }
    
            if (request.Summary != null)
            {
                Logger.Debug("Ending transaction.");
                await SendCommandToFiscalPrinter(["trend", $"to{request.Summary.To}", $"fp{request.Summary.Fp}"], ip, port);
            }
    
            response.Ok = true;
            response.Message = "Transaction completed successfully.";
            Logger.Info("Fiscal document printed successfully.");
        }
        catch (Exception ex)
        {
            response.Ok = false;
            response.Error = ex.Message;
            Logger.Error(ex, "Error printing fiscal document.");
        }
        finally
        {
            semaphore.Release();
        }
    
        return response;
    }
    
    /// <inheritdoc />
    public async Task<string> PrintFiscalDocumentAsync(ParagonRequest request, string ip, int port, bool bulkMode, string resultsUrl, string resultsUrlMethod)
    {
        Logger.Info("Starting async fiscal document print.");
        var operationId = Guid.NewGuid().ToString();
        _tasks[operationId] = new ParagonAsyncStatusResponse { Status = "Pending" };
    
        try
        {
            ParagonResponse response = await PrintFiscalDocument(request, ip, port, bulkMode);
            _tasks[operationId] = new ParagonAsyncStatusResponse { Status = "Completed", Response = response };
    
            if (!string.IsNullOrEmpty(resultsUrl))
            {
                Logger.Debug("Notifying results URL.");
                await NotifyResultsUrl(resultsUrl, resultsUrlMethod, _tasks[operationId]);
            }
        }
        catch (Exception ex)
        {
            _tasks[operationId] = new ParagonAsyncStatusResponse { Status = "Failed", Error = ex.Message };
            Logger.Error(ex, "Async fiscal document print failed.");
        }
    
        return operationId;
    }
    
    /// <inheritdoc />
    public ParagonAsyncStatusResponse? GetTaskStatusAsync(string taskId)
    {
        Logger.Info("Getting task status for TaskId: {0}", taskId);
        if (_tasks.TryGetValue(taskId, out var status))
        {
            return status;
        }
    
        Logger.Warn("Task status not found for TaskId: {0}", taskId);
        return null;
    }
    
    /// <inheritdoc />
    public async Task<PrinterStatusResponse> GetPrinterStatusAsync(string ip, int port)
    {
        Logger.Info("Getting printer status for IP: {0}, Port: {1}", ip, port);
        var semaphore = GetPrinterSemaphore(ip, port);
        await semaphore.WaitAsync();
    
        try
        {
            var printerStatusResults = await GetPrinterStatusResultsAsync(ip, port);
            Logger.Info("Printer status retrieved successfully.");
    
            return new PrinterStatusResponse
            {
                ok = true,
                buildversion = "5.3",
                schemaversion = "5.2",
                error = string.Empty,
                code = -1,
                results = printerStatusResults
            };
        }
        catch (Exception ex)
        {
            Logger.Error(ex, "Error getting printer status.");
            return new PrinterStatusResponse
            {
                ok = false,
                error = ex.Message,
                code = (int)PrinterErrorCodes.GeneralError
            };
        }
        finally
        {
            semaphore.Release();
        }
    }
    
    /// <inheritdoc />
    public async Task<ReportDobowyResponse> GenerateDailyReport(string ip, int port, bool fullDebug)
    {
        Logger.Info("Generating daily report for IP: {0}, Port: {1}", ip, port);
        var semaphore = GetPrinterSemaphore(ip, port);
        await semaphore.WaitAsync();
    
        try
        {
            var dailyReportCommand = BuildDailyReportCommand(fullDebug);
            var response = await SendCommandToFiscalPrinter(dailyReportCommand, ip, port);
            Logger.Info("Daily report generated successfully.");
    
            return new ReportDobowyResponse
            {
                Ok = true,
                Code = -1,
                Error = string.Empty,
                Results = []
            };
        }
        catch (Exception ex)
        {
            Logger.Error(ex, "Error generating daily report.");
            return new ReportDobowyResponse
            {
                Ok = false,
                Code = (int)PrinterErrorCodes.GeneralError,
                Error = ex.Message,
                Results = []
            };
        }
        finally
        {
            semaphore.Release();
        }
    }
    
    /// <inheritdoc />
    public virtual async Task<string> SendCommandToFiscalPrinter(string[] commands, string ip, int port)
    {
        Logger.Debug("Sending command to fiscal printer.");
        if (_sendCommandMock != null)
            return await _sendCommandMock.SendCommandToFiscalPrinter(commands, ip, port);
    
        if (ip == null)
        {
            throw new InvalidOperationException("The fiscal printer host is not configured. Please set the host before sending commands.");
        }
    
        using TcpClient client = new(ip, port);
        using NetworkStream stream = client.GetStream();
        var fullCommand = FullCommandCrced(commands);
        return await SendCommandToStream(fullCommand, stream);
    }
    
    /// <inheritdoc />
    public async Task PrintSaleConfirmationAsync(FirstDataStartResponse response, string ip, int port)
    {
        if (response == null)
        {
            Logger.Error("Response cannot be null.");
            throw new ArgumentNullException(nameof(response));
        }
    
        Logger.Info($"Printing sale confirmation for transaction {response.AcceptorTransactionIdentifier} on printer at {ip}:{port}");
    
        var semaphore = GetPrinterSemaphore(ip, port);
        await semaphore.WaitAsync();
    
        try
        {
            var printRules = response.MaskingRulesPrintouts?.ToMaskingRulesPrintoutsDecoder(MaskingRulesPrintoutsDecoder.PrintType.CardholderCopy);
            var isDCC = response.DCCExchangeRate.HasValue;
            var isApproved = response.IsApproved;
            var expiryDate = (printRules?.PrintB4 == true || printRules?.PrintB5 == true) ? response.MaskedExpiryDateOfCard : response.UnmaskedExpiryDateOfCard;
            var cardNumber = printRules?.PrintB3 == true ? response.MaskedCardNumber?.Trim() : response.UnmaskedCardNumber?.Trim();
    
            if (cardNumber is not null && expiryDate is not null)
            {
                await PrintFormHeader(isApproved, response, ip, port);
                await PrintTransactionDetails(isDCC, response, cardNumber, expiryDate, ip, port);
                await PrintAdditionalInfo(response, ip, port);
                await PrintFormFooter(ip, port);
    
                Logger.Info($"Sale confirmation printed successfully for transaction {response.AcceptorTransactionIdentifier}");
            }
            else
            {
                Logger.Error("Failed to retrieve card number or expiry date.");
            }
        }
        catch (Exception ex)
        {
            Logger.Error(ex, $"Error printing sale confirmation for transaction {response.AcceptorTransactionIdentifier}");
            throw;
        }
        finally
        {
            semaphore.Release();
        }
    }
    
    private async Task PrintFormHeader(bool isApproved, FirstDataStartResponse response, string ip, int port)
    {
        await SendCommandToFiscalPrinter(["formstart", "fn22", $"fh{(isApproved ? 1 : 7)}"], ip, port);
    
        if (!string.IsNullOrWhiteSpace(response.AcceptorTransactionIdentifier))
            await SendCommandToFiscalPrinter(["formline", "fn22", "fl1", $"s1{response.AcceptorTransactionIdentifier.LimitTakeRight(15)}"], ip, port);
    
        if (response.TransactionNumber > 0)
            await SendCommandToFiscalPrinter(["formline", "fn22", "fl2", $"s1{response.TransactionNumber}"], ip, port);
    
        await SendCommandToFiscalPrinter(["formline", "fn22", "fl4", $"s1{response.TID}\\r{response.MID}"], ip, port);
    
        if (!string.IsNullOrWhiteSpace(response.CardAcceptorName))
            await SendCommandToFiscalPrinter(["formline", "fn22", "fl6", $"s1{response.CardAcceptorName.LimitTakeLeft(35)}"], ip, port);
    }
    
    private async Task PrintTransactionDetails(bool isDCC, FirstDataStartResponse response, string cardNumber, string expiryDate, string ip, int port)
    {
        await SendCommandToFiscalPrinter(["formline", "fn22", "fl8", $"s1{cardNumber}"], ip, port);
    
        if (!string.IsNullOrWhiteSpace(expiryDate))
            await SendCommandToFiscalPrinter(["formline", "fn22", "fl9", $"s1{response.CardName}\\r{expiryDate[..2]}\\r{expiryDate[3..5]}"], ip, port);
    
        if (!isDCC)
        {
            await SendCommandToFiscalPrinter(["formline", "fn22", "fl31", $"s1{response.TransactionCurrencyCode}\\r{response.TransactionAmountFormatted}"], ip, port);
            await SendCommandToFiscalPrinter(["formline", "fn22", "fl35", $"s1{response.TransactionCurrencyCode}\\r{response.TransactionAmountFormatted}"], ip, port);
        }
        else
        {
            await SendCommandToFiscalPrinter(["formline", "fn22", "fl83", $"s1{response.TransactionCurrencyCode}\\r{response.DCCSaleAmountFormatted}"], ip, port);
            await SendCommandToFiscalPrinter(["formline", "fn22", "fl87", $"s1{response.TransactionCurrencyCode}\\r{response.DCCSurchargeFeeFormatted}"], ip, port);
            await SendCommandToFiscalPrinter(["formline", "fn22", "fl88", $"s1{response.TransactionAmountFormatted}"], ip, port);
        }
    }
    
    private async Task PrintAdditionalInfo(FirstDataStartResponse response, string ip, int port)
    {
        if (string.IsNullOrWhiteSpace(response.TextForTransactionDenialFromHost))
        {
            await SendCommandToFiscalPrinter(["formline", "fn22", "fl70"], ip, port);
            foreach (var cmd in CreateMessageCmdParams(response.TextForPrintoutCDCVM ?? ""))
            {
                await SendCommandToFiscalPrinter(cmd, ip, port);
            }
        }
        else
        {
            await SendCommandToFiscalPrinter(["formline", "fn22", "fl69"], ip, port);
            foreach (var cmd in CreateMessageCmdParams(response.TextForTransactionDenialFromHost))
            {
                await SendCommandToFiscalPrinter(cmd, ip, port);
            }
        }
    
        await PrintAuthorizationCode(response, ip, port);
        await PrintEMVData(response, ip, port);
        await PrintInstallmentInfo(response, ip, port);
    }
    
    private async Task PrintAuthorizationCode(FirstDataStartResponse response, string ip, int port)
    {
        if (!string.IsNullOrWhiteSpace(response.OTCValue))
            await SendCommandToFiscalPrinter(["formline", "fn22", "fl17", $"s1{response.OTCValue.LimitTakeRight(16)}"], ip, port);
        else if (!string.IsNullOrWhiteSpace(response.AuthorizationCode))
            await SendCommandToFiscalPrinter(["formline", "fn22", "fl17", $"s1{response.AuthorizationCode.LimitTakeRight(16)}"], ip, port);
    }
    
    private async Task PrintEMVData(FirstDataStartResponse response, string ip, int port)
    {
        if (!string.IsNullOrWhiteSpace(response.AID))
            await SendCommandToFiscalPrinter(["formline", "fn22", "fl36", $"s1{response.AID}"], ip, port);
    
        if (!string.IsNullOrWhiteSpace(response.ApplicationTransactionCounter))
            await SendCommandToFiscalPrinter(["formline", "fn22", "fl40", $"s1{response.ApplicationTransactionCounter}"], ip, port);
    
        if (!string.IsNullOrWhiteSpace(response.ApplicationCryptogram))
            await SendCommandToFiscalPrinter(["formline", "fn22", "fl37", $"s1{response.ApplicationCryptogram}"], ip, port);
    }
    
    private async Task PrintInstallmentInfo(FirstDataStartResponse response, string ip, int port)
    {
        if (!string.IsNullOrWhiteSpace(response.TextPrintoutInstallment))
        {
            foreach (var cmd in CreateMessageCmdParams(response.TextPrintoutInstallment))
            {
                await SendCommandToFiscalPrinter(cmd, ip, port);
            }
        }
    
        if (!string.IsNullOrWhiteSpace(response.AdditionalTextFromIssuerInstallment))
        {
            foreach (var cmd in CreateMessageCmdParams(response.AdditionalTextFromIssuerInstallment))
            {
                await SendCommandToFiscalPrinter(cmd, ip, port);
            }
        }
    }
    
    private async Task PrintFormFooter(string ip, int port)
    {
        await SendCommandToFiscalPrinter(["formend", "fn22"], ip, port);
    }
    
    private static IEnumerable<string[]> CreateMessageCmdParams(string message)
    {
        foreach (var line in message.SplitToLinesWordWrap(34))
        {
            yield return ["formline", "fn22", "fl130", $"s1{line}\r "];
        }
    }
    
    /// <summary>
    /// Sends a command to the fiscal printer over the specified network stream.
    /// </summary>
    /// <param name="command">The command to send.</param>
    /// <param name="stream">The network stream to use.</param>
    /// <returns>A task that represents the asynchronous operation. The task result contains the response from the printer.</returns>
    internal async Task<string> SendCommandToStream(string command, NetworkStream stream)
    {
        Logger.Debug("Sending command to stream.");
        byte[] data = Encoding.UTF8.GetBytes(command);
        await stream.WriteAsync(data.AsMemory(0, data.Length));
    
        StringBuilder responseBuilder = new();
        byte[] buffer = new byte[1024];
        int bytesRead;
    
        try
        {
            stream.ReadTimeout = 5000; // 5 seconds timeout
            while ((bytesRead = await stream.ReadAsync(new Memory<byte>(buffer))) > 0)
            {
                responseBuilder.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead));
                if (responseBuilder.ToString().EndsWith('\u0003'))
                {
                    break;
                }
            }
    
            string response = responseBuilder.ToString();
            int errorCode = ParseErrorCode(response);
    
            if (frameErrorMessages.TryGetValue(errorCode, out string? frameErrorMessage) && frameErrorMessage != null)
            {
                throw new Exception(frameErrorMessage);
            }
            else if (commandErrorMessages.TryGetValue(errorCode, out string? commandErrorMessage) && commandErrorMessage != null)
            {
                throw new Exception(commandErrorMessage);
            }
    
            return response;
        }
        catch (Exception ex)
        {
            Logger.Error(ex, "Error communicating with printer.");
            throw new Exception($"Error communicating with printer: {ex.Message}");
        }
        finally
        {
            stream.Close();
        }
    }
    
    // Error Dictionaries
    private readonly Dictionary<int, string> frameErrorMessages = new()
     {
         { 1, "PROTO_ERR_CMD_UNKNOWN: Nierozpoznana komenda" },
         { 2, "PROTO_ERR_CMD_MANDATORY_FIELDS: Brak obowiązkowego pola" },
         { 3, "PROTO_ERR_DATA_CONVERSION: Błąd konwersji pola (np.: przesłana została wartość z przecinkiem w polu którego wartość przesyła się w częściach setnych np.: 12,34 zamiast 1234, lub przekroczony zakres danych)" },
         { 4, "PROTO_ERR_TOKEN_INVALID: Błędny token" },
         { 5, "PROTO_ERR_CRC_INVALID: Zła suma kontrolna" },
         { 6, "PROTO_ERR_FLD_INVALID: Puste pole (kolejno dwa tabulatory)" },
         { 7, "PROTO_ERR_CMD_LENGTH: Niewłaściwa długość nazwy rozkazu" },
         { 8, "PROTO_ERR_TOKEN_LENGTH: Niewłaściwa długość tokena" },
         { 9, "PROTO_ERR_CRC_LENGTH: Niewłaściwa długość sumy kontrolnej" },
         { 10, "PROTO_ERR_DATA_LENGTH: Niewłaściwa długość pola danych" },
         { 11, "PROTO_ERR_INPUT_BUFFER_OVERRUN: Zapełniony bufor odbiorczy" },
         { 12, "PROTO_ERR_CMD_IMMEDIATE_FORBIDDEN: Nie można wykonać rozkazu w trybie natychmiastowym" },
         { 13, "PROTO_ERR_TOKEN_NOT_FOUND: Nie znaleziono rozkazu o podanym tokenie" },
         { 14, "PROTO_ERR_INPUT_QUEUE_FULL: Zapełniona kolejka wejściowa" },
         { 15, "PROTO_ERR_SYNTAX: Błąd budowy ramki" }
     };
    
    private readonly Dictionary<int, string> commandErrorMessages = new()
    {
         { 10, "ERR_CANCEL: Błąd nietypowy - rezygnacja, przerwanie funkcji" },
         { 50, "ERR_UNKN: Błąd wykonywania operacji przez kasę" },
         { 51, "ERR_ASSERT_FM: Błąd wykonywania operacji przez kasę" },
         { 52, "ERR_ASSERT_DB: Błąd wykonywania operacji przez kasę" },
         { 53, "ERR_ASSERT_SALE: Błąd wykonywania operacji przez kasę" },
         { 54, "ERR_ASSERT_UI: Błąd wykonywania operacji przez kasę" },
         { 55, "ERR_ASSERT_CFG: Błąd wykonywania operacji przez kasę" },
         { 323, "ERR_OPER_BLOCKED: Funkcja zablokowana w konfiguracji" },
         { 360, "ERR_SERVICE_SWITCH_FOUND: Znaleziono zworę serwisową" },
         { 361, "ERR_SERVICE_SWITCH_NOT_FOUND: Nie znaleziono zwory serwisowej" },
         { 362, "ERR_SERVICE_KEY_DATA: Błąd weryfikacji danych klucza" },
         { 363, "ERR_SERVICE_KEY_TIMEOUT: Upłynął czas na odpowiedź od klucza" },
         { 382, "ERR_RD_ZERO: Próba wykonania raportu zerowego" },
         { 383, "ERR_RD_NOT_PRINTED: Brak raportu dobowego" },
         { 384, "ERR_FM_NO_REC: Brak rekordu w pamięci" },
         { 400, "ERR_WRONG_VALUE: Błędna wartość" },
         { 460, "ERR_CLOCK_RTC_FSK: Błąd zegara w trybie fiskalnym" },
         { 461, "ERR_CLOCK_RTC_NFSK: Błąd zegara w trybie niefiskalnym" },
         { 480, "ERR_AUTH_AUTHORIZED: Drukarka już autoryzowana, bezterminowo" },
         { 481, "ERR_AUTH_NOT_STARTED: Nie rozpoczęto jeszcze autoryzacji" },
         { 482, "ERR_AUTH_WAS_ADDED: Kod już wprowadzony" },
         { 483, "ERR_AUTH_DAY_CNT: Próba wprowadzenia błędnych wartości" },
         { 484, "ERR_AUTH_BLOCKED: Minął czas pracy kasy, sprzedaż zablokowana" },
         { 485, "ERR_AUTH_BAD_CODE: Błędny kod autoryzacji" },
         { 486, "ERR_AUTH_TOO_MANY_WRONG_CODES: Blokada autoryzacji. Wprowadź kod z klawiatury" },
         { 500, "ERR_STAT_MIN_OVF: Przepełnienie statystyki minimalnej" },
         { 501, "ERR_STAT_MAX_OVF: Przepełnienie statystyki maksymalnej" },
         { 502, "ERR_CASH_IN_MAX_OVF: Przepełnienie stanu kasy" },
         { 503, "ERR_CASH_OUT_BELOW_0: Wartość stanu kasy po wypłacie staje się ujemna (przyjmuje się stan zerowy kasy)" },
         { 700, "ERR_INVALID_IP_ADDR: Błędny adres IP" },
         { 701, "ERR_INVALID_TONE_NUMBER: Błąd numeru tonu" },
         { 702, "ERR_ILLEGAL_DRAWER_IMPULSE_LEN: Błąd długości impulsu szuflady" },
         { 703, "ERR_ILLEGAL_VAT_RATE: Błąd stawki VAT" },
         { 704, "ERR_INVALID_LOGOUT_TIME: Błąd czasu wylogowania" },
         { 705, "ERR_INVALID_SLEEP_TIME: Błąd czasu uśpienia" },
         { 706, "ERR_INVALID_TURNOFF_TIME: Błąd czasu wyłączenia" },
         { 713, "ERR_CONFIG_SET: Błędne parametry konfiguracji" },
         { 714, "ERR_ILLEGAL_DSP_CONTRAST: Błędna wartość kontrastu wyświetlacza" },
         { 715, "ERR_ILLEGAL_DSP_LUMIN: Błędna wartość podświetlenia wyświetlacza" },
         { 716, "ERR_ILLEGAL_DSP_OFF_DELAY: Błędna wartość czasu zaniku podświetlenia" },
         { 717, "ERR_LINE_TOO_LONG: Zbyt długa linia nagłówka albo stopki" },
         { 718, "ERR_ILLEGAL_COMM_CFG: Błędna konfiguracja komunikacji" },
         { 719, "ERR_ILLEGAL_PROTOCOL_CFG: Błędna konfiguracja protokołu komunikacji" },
         { 720, "ERR_ILLEGAL_PORT: Błędny identyfikator portu" },
         { 721, "ERR_ILLEGAL_INFO_TXT_NUM: Błędny numer tekstu reklamowego" },
         { 722, "ERR_ILLEGAL_TIME_DIFF: Podany czas wychodzi poza wymagany zakres" },
         { 723, "ERR_ILLEGAL_TIME: Podana data/czas niepoprawne" },
         { 724, "ERR_ILLEGAL_HOUR_DIFF: Inna godzina w różnicach czasowych 0<=>23" },
         { 726, "ERR_ILLEGAL_DSP_LINE_CONTENT: Błędna zawartość tekstu w linii wyświetlacza" },
         { 727, "ERR_ILLEGAL_DSP_SCROLL_VALUE: Błędna wartość dla przewijania na wyświetlaczu" },
         { 728, "ERR_ILLEGAL_PORT_CFG: Błędna konfiguracja portu" },
         { 738, "ERR_ETH_CONFIG: Nieprawidłowa konfiguracja Ethernetu" },
         { 739, "ERR_ILLEGAL_DSP_ID: Nieprawidłowy typ wyświetlacza" },
         { 740, "ERR_ILLEGAL_DSP_ID_FOR_OFF_DELAY: Dla tego typu wyświetlacza nie można ustawić czasu zaniku podświetlenia" },
         { 820, "ERR_TEST: Negatywny wynik testu" },
         { 821, "ERR_TEST_NO_CONF: Brak testowanej opcji w konfiguracji" },
         { 857, "ERR_DF_DB_NO_MEM: Brak pamięci na inicjalizację bazy drukarkowej" },
         { 1000, "ERR_FATAL_FM: Błąd fatalny modułu fiskalnego" },
         { 1001, "ERR_FM_NCONN: Wypięta pamięć fiskalna" },
         { 1002, "ERR_FM_WRITE: Błąd zapisu" },
         { 1003, "ERR_FM_UNKN: Błąd nie ujęty w specyfikacji bios" },
         { 1004, "ERR_FM_CHKSUM_CNT: Błędne sumy kontrolne" },
         { 1005, "ERR_FM_CTRL_BLK_0: Błąd w pierwszym bloku kontrolnym" },
         { 1006, "ERR_FM_CTRL_BLK_1: Błąd w drugim bloku kontrolnym" },
         { 1007, "ERR_FM_BAD_REC_ID: Błędny id rekordu" },
         { 1008, "ERR_FM_DATA_ADDR_INIT: Błąd inicjalizacji adresu startowego" },
         { 1009, "ERR_FM_DATA_ADDR_INITED: Adres startowy zainicjalizowany" },
         { 1010, "ERR_FM_NU_PRESENT: Numer unikatowy już zapisany" },
         { 1011, "ERR_FM_NU_NO_PRESENT_FSK: Brak numeru w trybie fiskalnym" },
         { 1012, "ERR_FM_NU_WRITE: Błąd zapisu numeru unikatowego" },
         { 1013, "ERR_FM_NU_FULL: Przepełnienie numerów unikatowych" },
         { 1014, "ERR_FM_NU_LANG: Błędny język w numerze unikatowym" },
         { 1015, "ERR_FM_TIN_CNT: Więcej niż jeden NIP" },
         { 1016, "ERR_FM_READ_ONLY_NFSK: Drukarka w trybie do odczytu bez rekordu fiskalizacji" },
         { 1017, "ERR_FM_CLR_RAM_CNT: Przekroczono liczbę zerowań RAM" },
         { 1018, "ERR_FM_REP_DAY_CNT: Przekroczono liczbę raportów dobowych" },
         { 1019, "ERR_FM_VERIFY_NU: Błąd weryfikacji numeru unikatowego" },
         { 1020, "ERR_FM_VERIFY_STAT: Błąd weryfikacji statystyk z RD." },
         { 1021, "ERR_FM_VERIFY_NVR_READ: Błąd odczytu danych z NVR do weryfikacji FM" },
         { 1022, "ERR_FM_VERIFY_NVR_WRITE: Błąd zapisu danych z NVR do weryfikacji FM" },
         { 1023, "ERR_FM_CTRL_BLK_2: Pamięć fiskalna jest mała 1Mb zamiast 2Mb" },
         { 1024, "ERR_FM_DATA_ADDR_NO_INITED: Nie zainicjalizowany obszar danych w pamięci fiskalnej" },
         { 1025, "ERR_FM_NU_FORMAT: Błędny format numeru unikatowego" },
         { 1026, "ERR_FM_REC_BAD_CNT: Za dużo błędnych bloków w FM" },
         { 1027, "ERR_FM_NO_BADBLK_MARKER: Błąd oznaczenia błędnego bloku" },
         { 1028, "ERR_FM_REC_EMPTY: Rekord w pamięci fiskalnej nie istnieje - obszar pusty" },
         { 1029, "ERR_FM_REC_DATE: Rekord w pamięci fiskalnej z datą późniejszą od poprzedniego" },
         { 1950, "ERR_TR_TOT_OVR: Przekroczony zakres totalizerów paragonu" },
         { 1951, "ERR_TR_PF_OVR: Wpłata formą płatności przekracza max. wpłatę" },
         { 1952, "ERR_TR_PF_SUM_OVR: Suma form płatności przekracza max. wpłatę" },
         { 1953, "ERR_PAYMENT_OVR: Formy płatności pokrywają już do zapłaty" },
         { 1954, "ERR_TR_CHANGE_OVR: Wpłata reszty przekracza max. wpłatę" },
         { 1955, "ERR_TR_CHANGE_SUM_OVR: Suma form płatności przekracza max. wpłatę" },
         { 1956, "ERR_TR_TOTAL_OVR: Przekroczony zakres totalizerów" },
         { 1957, "ERR_TR_FISC_OVR: Przekroczony maksymalny zakres paragonu" },
         { 1958, "ERR_TR_PACK_OVR: Przekroczony zakres wartości opakowań" },
         { 1959, "ERR_TR_PACK_STORNO_OVR: Przekroczony zakres wartości opakowań przy stornowaniu" },
         { 1961, "ERR_TR_PF_REST_TOO_BIG: Wpłata reszty zbyt duża" },
         { 1962, "ERR_TR_PF_ZERO: Wpłata formą płatności wartości 0" },
         { 1980, "ERR_TR_DISCNT_BASE_OVR: Przekroczony zakres kwoty bazowej rabatu/narzutu" },
         { 1981, "ERR_TR_DISCNT_AFTER_OVR: Przekroczony zakres kwoty po rabacie/narzucie" },
         { 1982, "ERR_TR_DISCNT_CALC: Błąd obliczania rabatu/narzutu" },
         { 1983, "ERR_TR_DISCNT_BASE_NEGATIVE_OR_ZERO: Wartość bazowa ujemna lub równa 0" },
         { 1984, "ERR_TR_DISCNT_ZERO: Wartość rabatu/narzutu równa 0" },
         { 1985, "ERR_TR_DISCNT_AFTER_NEGATIVE_OR_ZERO: Wartość po rabacie ujemna lub równa 0" },
         { 1990, "ERR_TR_STORNO_NOT_ALLOWED: Niedozwolone stornowanie towaru. Błędny stan transakcji" },
         { 1991, "ERR_TR_DISCNT_NOT_ALLOWED: Niedozwolony rabat/narzut. Błędny stan transakcji" },
         { 2000, "ERR_TR_FLD_VAT: Błąd pola VAT" },
         { 2002, "ERR_NO_HDR: Brak nagłówka" },
         { 2003, "ERR_HDR: Zaprogramowany nagłówek" },
         { 2004, "ERR_NO_VAT: Brak aktywnych stawek VAT" },
         { 2005, "ERR_NO_TRNS_MODE: Brak trybu transakcji" },
         { 2006, "ERR_TR_FLD_PRICE: Błąd pola cena (cena <= 0)" },
         { 2007, "ERR_TR_FLD_QUANT: Błąd pola ilość (ilość <= 0)" },
         { 2008, "ERR_TR_FLD_TOTAL: Błąd kwoty total" },
         { 2009, "ERR_TR_FLD_TOTAL_ZERO: Błąd kwoty total, równa zero" },
         { 2010, "ERR_TOT_OVR: Przekroczony zakres totalizerów dobowych" },
         { 2021, "ERR_RTC_WAS_SET: Próba ponownego ustawienia zegara" },
         { 2022, "ERR_RTC_DIFF: Zbyt duża różnica dat" },
         { 2023, "ERR_RTC_HOUR: Różnica większa niż godzina w trybie użytkownika w trybie fiskalnym" },
         { 2024, "ERR_RTC_BAD_FORMAT: Zły format daty (np. 13 miesiąc)" },
         { 2025, "ERR_RTC_FM_DATE: Data wcześniejsza od ostatniego zapisu do modułu" },
         { 2026, "ERR_RTC: Błąd zegara" },
         { 2027, "ERR_VAT_CHNG_CNT: Przekroczono maksymalną liczbę zmian stawek VAT" },
         { 2028, "ERR_VAT_SAME: Próba zdefiniowania identycznych stawek VAT" },
         { 2029, "ERR_VAT_VAL: Błędne wartości stawek VAT" },
         { 2030, "ERR_VAT_NO_ACTIVE: Próba zdefiniowania stawek VAT wszystkich nieaktywnych" },
         { 2031, "ERR_FLD_TIN: Błąd pola NIP" },
         { 2032, "ERR_FM_ID: Błąd numeru unikatowego pamięci fiskalnej" },
         { 2033, "ERR_FISC_MODE: Urządzenie w trybie fiskalnym" },
         { 2034, "ERR_NO_FISC_MODE: Urządzenie w trybie niefiskalnym" },
         { 2035, "ERR_TOT_NOT_ZERO: Niezerowe totalizery" },
         { 2036, "ERR_READ_ONLY: Urządzenie w stanie tylko do odczytu" },
         { 2037, "ERR_NO_READ_ONLY: Urządzenie nie jest w stanie tylko do odczytu" },
         { 2038, "ERR_TRNS_MODE: Urządzenie w trybie transakcji" },
         { 2039, "ERR_TOT_ZERO: Zerowe totalizery" },
         { 2040, "ERR_CURR_CALC: Błąd obliczeń walut, przepełnienie przy mnożeniu lub dzieleniu" },
         { 2041, "ERR_TR_END_VAL_0: Próba zakończenia pozytywnego paragonu wartością 0" },
         { 2042, "ERR_REP_PER_DATE_FORMAT_FROM: Błędy formatu daty początkowej raportu okresowego" },
         { 2043, "ERR_REP_PER_DATE_FORMAT_TO: Błędy formatu daty końcowej raportu okresowego" },
         { 2044, "ERR_REP_PER_CURR_MONTH: Próba wykonania raportu miesięcznego w danym miesiącu" },
         { 2045, "ERR_REP_PER_DATE_START_GT_CURR: Data początkowa późniejsza od bieżącej daty" },
         { 2046, "ERR_REP_PER_DATE_END_GT_FISK: Data końcowa wcześniejsza od daty fiskalizacji" },
         { 2047, "ERR_REP_PER_NUM_ZERO: Numer początkowy lub końcowy równy zero" },
         { 2048, "ERR_REP_PER_NUM_FROM_GT_END: Numer początkowy większy od numeru końcowego" },
         { 2049, "ERR_REP_PER_NUM_TOO_BIG: Numer raportu zbyt duży" },
         { 2050, "ERR_REP_PER_DATE_END_GT_START: Data początkowa późniejsza od daty końcowej" },
         { 2051, "ERR_REP_TXT_NO_MEM: Brak pamięci w buforze tekstów" },
         { 2052, "ERR_TR_NO_MEM: Brak pamięci w buforze transakcji" },
         { 2054, "ERR_TR_END_PAYMENT: Formy płatności nie pokrywają kwoty do zapłaty lub reszty" },
         { 2055, "ERR_LINE: Błędna linia" },
         { 2056, "ERR_EMPTY_TXT: Tekst pusty" },
         { 2057, "ERR_SIZE: Przekroczony rozmiar" },
         { 2058, "ERR_LINE_CNT: Błędna liczba linii" },
         { 2060, "ERR_TR_BAD_STATE: Błędny stan transakcji" },
         { 2062, "ERR_PRN_START: Jest wydrukowana część jakiegoś dokumentu" },
         { 2063, "ERR_PAR: Błąd parametru" },
         { 2064, "ERR_FTR_NO_HDR: Brak rozpoczęcia wydruku lub transakcji" },
         { 2067, "ERR_PRN_CFG_SET: Błąd ustawień konfiguracyjnych wydruków/drukarki" },
         { 2070, "ERR_WRONG_MAINTENANCE_TIME: Data przeglądu wcześniejsza od systemowej" },
         { 2101, "ERR_DF_DB_OVR: Zapełnienie bazy danych" },
         { 2102, "ERR_DF_DB_VAT_INACTIVE: Stawka VAT nieaktywna" },
         { 2103, "ERR_DF_DB_VAT_INVALID: Nieprawidłowa stawka VAT" },
         { 2104, "ERR_DF_DB_NAME: Błąd nazwy" },
         { 2105, "ERR_DF_DB_NAME_VAT: Błąd przypisania stawki" },
         { 2106, "ERR_DF_DB_LOCKED: Zablokowany" },
         { 2107, "ERR_DF_DB_NAME_NOT_FOUND: Nie znaleziono w bazie drukarkowej" },
         { 2108, "ERR_DF_DB_NOT_OVR: Baza nie jest zapełniona" },
         { 2501, "ERR_FORM_ID: Błędny identyfikator raportu" },
         { 2502, "ERR_FORM_LINE_NO: Błędny identyfikator linii raportu" },
         { 2503, "ERR_FORM_HDR_NO: Błędny identyfikator nagłówka raportu" },
         { 2504, "ERR_FORM_PAR_CNT: Zbyt mało parametrów raportu" },
         { 2505, "ERR_FORM_NOT_STARTED: Raport nie rozpoczęty" },
         { 2506, "ERR_FORM_STARTED: Raport rozpoczęty" },
         { 2507, "ERR_FORM_CMD: Błędny identyfikator komendy" },
         { 2521, "ERR_DB_REP_PLU_ACTIVE: Raport już rozpoczęty" },
         { 2522, "ERR_DB_REP_PLU_NOT_ACTIVE: Raport nie rozpoczęty" },
         { 2523, "ERR_DB_REP_PLU_VAT_ID: Błędna stawka VAT" },
         { 2532, "ERR_FV_COPY_CNT: Błędna liczba kopii faktur" },
         { 2600, "ERR_DISCNT_TYPE: Błędny typ rabatu/narzutu" },
         { 2601, "ERR_TR_DISCNT_VALUE: Wartość rabatu/narzutu spoza zakresu" },
         { 2701, "ERR_VAT_ID: Błąd identyfikatora stawki podatkowej" },
         { 2702, "ERR_FTRLN_ID: Błędny identyfikator dodatkowej stopki" },
         { 2703, "ERR_FTRLN_CNT: Przekroczona liczba dodatkowych stopek" },
         { 2704, "ERR_ACC_LOW: Zbyt słaby akumulator" },
         { 2705, "ERR_PF_TYPE: Błędny identyfikator typu formy płatności" },
         { 2801, "ERR_DISCNT_VERIFY: Błąd weryfikacji wartości rabatu/narzutu" },
         { 2802, "ERR_LNTOT_VERIFY: Błąd weryfikacji wartości linii sprzedaży" },
         { 2803, "ERR_PACKTOT_VERIFY: Błąd weryfikacji wartości opakowania" },
         { 2804, "ERR_CURRTOT_VERIFY: Błąd weryfikacji wartości formy płatności" },
         { 2805, "ERR_ENDTOT_VERIFY: Błąd weryfikacji wartości fiskalnej" },
         { 2806, "ERR_ENDPACKPLUS_VERIFY: Błąd weryfikacji wartości opakowań dodatnich" },
         { 2807, "ERR_ENDPACKMINUS_VERIFY: Błąd weryfikacji wartości opakowań ujemnych" },
         { 2808, "ERR_ENDPAYMENT_VERIFY: Błąd weryfikacji wartości wpłaconych form płatności" },
         { 2809, "ERR_ENDCHANGE_VERIFY: Błąd weryfikacji wartości reszty" },
         { 2851, "ERR_STORNO_QNT: Błąd stornowania, błędna ilość" },
         { 2852, "ERR_STORNO_AMT: Błąd stornowania, błędna wartość" },
         { 2900, "ERR_EC_NOT_ENOUGH_SPACE: Stan kopii elektronicznej nie pozwala na wydrukowanie tego dokumentu. Brak nośnika lub operacja na nośniku trwa" },
         { 2901, "ERR_EC_EDM_NOT_READY: Pamięć podręczna kopii elektronicznej zawiera zbyt dużą ilość danych. Brak pliku na nośniku." },
         { 2903, "ERR_EC_DATA_PENDING: Nieprawidłowy wynik testu." },
         { 2911, "ERR_EC_EDM_FILE_NOT_FOUND: Nie można zmienić 2 raz waluty ewidencyjnej po RD." },
         { 2913, "ERR_EC_TEST_FAILED: Próba ustawienia już ustawionej waluty." },
         { 3051, "ERR_CURRENCY_ALREADY_CHANGED: Błędna nazwa waluty." },
         { 3052, "ERR_CURRENCY_SAME: Automatyczna zmiana waluty." },
         { 3053, "ERR_CURRENCY_INVALID_NAME: Błędna wartość przelicznika kursu." },
         { 3054, "ERR_CURRENCY_SHOULD_CHANGE: Przekroczono maksymalną liczbę zmian walut." },
         { 3055, "ERR_CURRENCY_RATE: Błąd zmiany waluty." },
         { 3056, "ERR_CURRENCY_CHNG_CNT: Błędna liczba walut w bazie." },
     };
    
    private static int ParseErrorCode(string response)
    {
        // Find the position of the sequence "\u0002ERR\t"
        int startIndex = response.IndexOf("\u0002ERR\t");
        if (startIndex == -1)
        {
            // Return -1 if the sequence is not found
            return -1;
        }
    
        // Move to the character after "\u0002ERR\t"
        startIndex += "\u0002ERR\t".Length;
    
        // Find the position of the next tab character after the number
        int endIndex = response.IndexOf('\t', startIndex);
        if (endIndex == -1)
        {
            // If no tab is found, assume the number goes to the end of the string
            endIndex = response.Length;
        }
    
        // Extract the number substring
        string numberString = response[startIndex..endIndex].Trim();
    
        // Try to parse the number as an integer
        if (int.TryParse(numberString, out int errorCode))
        {
            return errorCode;
        }
    
        // Return -1 if parsing fails
        return -1;
    }
    
    private async static Task NotifyResultsUrl(string resultsUrl, string resultsUrlMethod, ParagonAsyncStatusResponse response)
    {
        using var httpClient = new HttpClient();
    
        var content = new StringContent(System.Text.Json.JsonSerializer.Serialize(response), Encoding.UTF8, "application/json");
    
        switch (resultsUrlMethod?.ToUpper())
        {
            case "POST":
                await httpClient.PostAsync(resultsUrl, content);
                break;
            case "PUT":
                await httpClient.PutAsync(resultsUrl, content);
                break;
            case "GET":
                await httpClient.GetAsync(resultsUrl);
                break;
        }
    }
    
    private async Task<PrinterStatusResults> GetPrinterStatusResultsAsync(string ip, int port)
    {
        return new PrinterStatusResults()
        {
            rtcget = ParseRtcGet(await SendCommandToFiscalPrinter(RtcGetCommand, ip, port)),
            vatget = ParseVatGet(await SendCommandToFiscalPrinter(VatGetCommand, ip, port)),
            hdrget = ParseHdrGet(await SendCommandToFiscalPrinter(HdrGetCommand, ip, port)),
            ftrinfoget = ParseFtrInfoGet(await SendCommandToFiscalPrinter(FtrInfoGetCommand, ip, port)),
            pccfgget = ParsePcCfgGet(await SendCommandToFiscalPrinter(PcCfgGetCommand, ip, port)),
            tcpipcfgget = ParseTcpIpCfgGet(await SendCommandToFiscalPrinter(TcpIpCfgGetCommand, ip, port)),
            sdev = ParseSdev(await SendCommandToFiscalPrinter(SdevCommand, ip, port)),
            sprn = ParseSprn(await SendCommandToFiscalPrinter(SprnCommand, ip, port)),
            scnt = ParseScnt(await SendCommandToFiscalPrinter(ScntCommand, ip, port)),
            stot = ParseStot(await SendCommandToFiscalPrinter(StotCommand, ip, port))
        };
    }
    
    private string[] BuildDailyReportCommand(bool fullDebug)
    {
        var currentDate = DateTime.Now.ToString("yyyy-MM-dd");
        var command = new List<string> { "dailyrep", $"da{currentDate}" };
    
        if (fullDebug)
        {
            command.Add("fulldebug");
        }
    
        return command.ToArray();
    }
    
    private RtcGet ParseRtcGet(string response)
    {
        var parts = response.Split('\u0009');
    
        if (parts.Length < 3)
        {
            return new RtcGet();
        }
    
        return new RtcGet
        {
            da = GetSubstringOrEmpty(parts[1], 2),
            tm = GetSubstringOrEmpty(parts[2], 2),
        };
    }
    
    private VatGet ParseVatGet(string response)
    {
        var parts = response.Split('\u0009');
    
        if (parts.Length < 8)
        {
            return new VatGet();
        }
    
        return new VatGet
        {
            va = GetSubstringOrEmpty(parts[1], 2),
            vb = GetSubstringOrEmpty(parts[2], 2),
            vc = GetSubstringOrEmpty(parts[3], 2),
            vd = GetSubstringOrEmpty(parts[4], 2),
            ve = GetSubstringOrEmpty(parts[5], 2),
            vf = GetSubstringOrEmpty(parts[6], 2),
            vg = GetSubstringOrEmpty(parts[7], 2)
        };
    }
    
    private List<HdrGet> ParseHdrGet(string response)
    {
        var parts = response.Split('\u0009');
    
        if (parts.Length < 2)
        {
            return new List<HdrGet>();
        }
    
        return new List<HdrGet>
        {
            new HdrGet { tx = GetSubstringOrEmpty(parts[1], 2) }
        };
    }
    
    private List<FtrInfoGet> ParseFtrInfoGet(string response)
    {
        var parts = response.Split('\u0009');
    
        if (parts.Length < 2)
        {
            return new List<FtrInfoGet>();
        }
    
        return new List<FtrInfoGet>
        {
            new FtrInfoGet { tx = GetSubstringOrEmpty(parts[1], 2) }
        };
    }
    
    private List<PcCfgGet> ParsePcCfgGet(string response)
    {
        var parts = response.Split('\u0009');
    
        if (parts.Length < 5)
        {
            return new List<PcCfgGet>();
        }
    
        return new List<PcCfgGet>
        {
            new PcCfgGet { cp = GetSubstringOrEmpty(parts[4], 2) },
            new PcCfgGet { id = GetSubstringOrEmpty(parts[1], 2) },
            new PcCfgGet { no = GetSubstringOrEmpty(parts[2], 2) },
            new PcCfgGet { pr = GetSubstringOrEmpty(parts[3], 2) }
        };
    }
    
    
    private List<TcpIpCfgGet> ParseTcpIpCfgGet(string response)
    {
        var parts = response.Split('\u0009');
    
        if (parts.Length < 9)
        {
            return new List<TcpIpCfgGet>();
        }
    
        return new List<TcpIpCfgGet>
        {
            new TcpIpCfgGet { da = GetSubstringOrEmpty(parts[7], 2) },
            new TcpIpCfgGet { dh = GetSubstringOrEmpty(parts[8], 2) },
            new TcpIpCfgGet { dp = GetSubstringOrEmpty(parts[6], 2) },
            new TcpIpCfgGet { ge = GetSubstringOrEmpty(parts[5], 2) },
            new TcpIpCfgGet { id = GetSubstringOrEmpty(parts[1], 2) },
            new TcpIpCfgGet { ip = GetSubstringOrEmpty(parts[3], 2) },
            new TcpIpCfgGet { ma = GetSubstringOrEmpty(parts[4], 2) },
            new TcpIpCfgGet { no = GetSubstringOrEmpty(parts[2], 2) }
        };
    }
    
    private List<Sdev> ParseSdev(string response)
    {
        var parts = response.Split('\u0009');
    
        if (parts.Length < 6)
        {
            return new List<Sdev>();
        }
    
        return new List<Sdev>
        {
            new Sdev { cp = GetSubstringOrEmpty(parts[2], 2) },
            new Sdev { ds = GetSubstringOrEmpty(parts[1], 2) },
            new Sdev { pe = GetSubstringOrEmpty(parts[4], 2) },
            new Sdev { qe = GetSubstringOrEmpty(parts[3], 2) },
            new Sdev { tl = GetSubstringOrEmpty(parts[5], 2) }
        };
    }
    
    private List<Sprn> ParseSprn(string response)
    {
        var parts = response.Split('\u0009');
    
        if (parts.Length < 2)
        {
            return new List<Sprn>();
        }
    
        return new List<Sprn>
        {
            new Sprn { pr = GetSubstringOrEmpty(parts[1], 2) }
        };
    }
    
    private List<Scnt> ParseScnt(string response)
    {
        var parts = response.Split('\u0009');
    
        if (parts.Length < 9)
        {
            return new List<Scnt>();
        }
    
        return new List<Scnt>
        {
            new Scnt { bc = GetSubstringOrEmpty(parts[6], 2) },
            new Scnt { bn = GetSubstringOrEmpty(parts[3], 2) },
            new Scnt { bt = GetSubstringOrEmpty(parts[7], 2) },
            new Scnt { fc = GetSubstringOrEmpty(parts[8], 2) },
            new Scnt { fn = GetSubstringOrEmpty(parts[4], 2) },
            new Scnt { hn = GetSubstringOrEmpty(parts[2], 2) },
            new Scnt { nu = GetSubstringOrEmpty(parts[5], 2) },
            new Scnt { rd = GetSubstringOrEmpty(parts[1], 2) }
        };
    }
    
    private string GetSubstringOrEmpty(string input, int startIndex)
    {
        return startIndex >= input.Length ? string.Empty : input[startIndex..];
    }
    
    private List<Stot> ParseStot(string response)
    {
        var parts = response.Split('\u0009');
    
        if (parts.Length < 32)
        {
            return new List<Stot>();
        }
    
        return new List<Stot>
        {
            new Stot { bc = GetTotalizerValue(parts, "bc") },
            new Stot { cc = GetTotalizerValue(parts, "cc") },
            new Stot { cn = GetTotalizerValue(parts, "cn") },
            new Stot { cn = GetTotalizerValue(parts, "ct") },
            new Stot { de = GetDateTimeOrDefault(parts, 30, "yyyy-MM-dd;HH:mm") },
            new Stot { ds = GetDateTimeOrDefault(parts, 28, "yyyy-MM-dd;HH:mm") },
            new Stot { fa = GetTotalizerValue(parts, "fa") },
            new Stot { fb = GetTotalizerValue(parts, "fb") },
            new Stot { fc = GetTotalizerValue(parts, "fc") },
            new Stot { fd = GetTotalizerValue(parts, "fd") },
            new Stot { fe = GetTotalizerValue(parts, "fe") },
            new Stot { ff = GetTotalizerValue(parts, "ff") },
            new Stot { fg = GetTotalizerValue(parts, "fg") },
            new Stot { fl = GetTotalizerValue(parts, "fl") },
            new Stot { fn = GetTotalizerValue(parts, "fn") },
            new Stot { ft = GetTotalizerValue(parts, "ft") },
            new Stot { ie = GetDateTimeOrDefault(parts, 31, "yyyy-MM-ddTHH:mm:sszzz") },
            new Stot { @is = GetDateTimeOrDefault(parts, 29, "yyyy-MM-ddTHH:mm:sszzz") },
            new Stot { le = GetTotalizerValue(parts, "le") },
            new Stot { nf = GetTotalizerValue(parts, "nf") },
            new Stot { no = GetTotalizerValue(parts, "no") },
            new Stot { oe = GetTotalizerValue(parts, "oe") },
            new Stot { pa = GetTotalizerValue(parts, "pa") },
            new Stot { pb = GetTotalizerValue(parts, "pb") },
            new Stot { pc = GetTotalizerValue(parts, "pc") },
            new Stot { pd = GetTotalizerValue(parts, "pd") },
            new Stot { pe = GetTotalizerValue(parts, "pe") },
            new Stot { pf = GetTotalizerValue(parts, "pf") },
            new Stot { pg = GetTotalizerValue(parts, "pg") },
            new Stot { pn = GetTotalizerValue(parts, "pn") },
            new Stot { tf = GetTotalizerValue(parts, "tf") },
            new Stot { va = GetTotalizerValue(parts, "va") },
            new Stot { vb = GetTotalizerValue(parts, "vb") },
            new Stot { vc = GetTotalizerValue(parts, "vc") },
            new Stot { vd = GetTotalizerValue(parts, "vd") },
            new Stot { ve = GetTotalizerValue(parts, "ve") },
            new Stot { vf = GetTotalizerValue(parts, "vf") },
            new Stot { vg = GetTotalizerValue(parts, "vg") }
        };
    }
    
    private static string GetTotalizerValue(string[] parts, string totalizerName)
    {
        return parts.Where(part => part.StartsWith(totalizerName))
            .Select(part => part[2..])
            .FirstOrDefault() ?? "0";
    }
    
    private static string GetDateTimeOrDefault(string[] parts, int index, string format)
    {
        return parts.Length > index ? parts[index].Substring(2) : new DateTimeOffset(2000, 1, 1, 1, 0, 0, TimeSpan.FromHours(1)).ToString(format);
    }
    
    /// <summary>
    /// Constructs a full command with CRC.
    /// </summary>
    /// <param name="command">The command parts.</param>
    /// <returns>The full command with CRC.</returns>
    private string FullCommandCrced(string[] command)
    {
        const char Separator = '\u0009'; // Tab character
        const char StartMarker = '\u0002'; // Start of Text (STX)
        const char EndMarker = '\u0003'; // End of Text (ETX)
    
        var joinedString = string.Join(Separator, command) + Separator;
        var crc = CalculateCrc(joinedString);
    
        return $"{StartMarker}{joinedString}#{crc}{EndMarker}";
    }
    
    private string CalculateCrc(string input)
    {
        byte[] crc16htab =
        {
                0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
                0x81, 0x91, 0xa1, 0xb1, 0xc1, 0xd1, 0xe1, 0xf1,
                0x12, 0x02, 0x32, 0x22, 0x52, 0x42, 0x72, 0x62,
                0x93, 0x83, 0xb3, 0xa3, 0xd3, 0xc3, 0xf3, 0xe3,
                0x24, 0x34, 0x04, 0x14, 0x64, 0x74, 0x44, 0x54,
                0xa5, 0xb5, 0x85, 0x95, 0xe5, 0xf5, 0xc5, 0xd5,
                0x36, 0x26, 0x16, 0x06, 0x76, 0x66, 0x56, 0x46,
                0xb7, 0xa7, 0x97, 0x87, 0xf7, 0xe7, 0xd7, 0xc7,
                0x48, 0x58, 0x68, 0x78, 0x08, 0x18, 0x28, 0x38,
                0xc9, 0xd9, 0xe9, 0xf9, 0x89, 0x99, 0xa9, 0xb9,
                0x5a, 0x4a, 0x7a, 0x6a, 0x1a, 0x0a, 0x3a, 0x2a,
                0xdb, 0xcb, 0xfb, 0xeb, 0x9b, 0x8b, 0xbb, 0xab,
                0x6c, 0x7c, 0x4c, 0x5c, 0x2c, 0x3c, 0x0c, 0x1c,
                0xed, 0xfd, 0xcd, 0xdd, 0xad, 0xbd, 0x8d, 0x9d,
                0x7e, 0x6e, 0x5e, 0x4e, 0x3e, 0x2e, 0x1e, 0x0e,
                0xff, 0xef, 0xdf, 0xcf, 0xbf, 0xaf, 0x9f, 0x8f,
                0x91, 0x81, 0xb1, 0xa1, 0xd1, 0xc1, 0xf1, 0xe1,
                0x10, 0x00, 0x30, 0x20, 0x50, 0x40, 0x70, 0x60,
                0x83, 0x93, 0xa3, 0xb3, 0xc3, 0xd3, 0xe3, 0xf3,
                0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
                0xb5, 0xa5, 0x95, 0x85, 0xf5, 0xe5, 0xd5, 0xc5,
                0x34, 0x24, 0x14, 0x04, 0x74, 0x64, 0x54, 0x44,
                0xa7, 0xb7, 0x87, 0x97, 0xe7, 0xf7, 0xc7, 0xd7,
                0x26, 0x36, 0x06, 0x16, 0x66, 0x76, 0x46, 0x56,
                0xd9, 0xc9, 0xf9, 0xe9, 0x99, 0x89, 0xb9, 0xa9,
                0x58, 0x48, 0x78, 0x68, 0x18, 0x08, 0x38, 0x28,
                0xcb, 0xdb, 0xeb, 0xfb, 0x8b, 0x9b, 0xab, 0xbb,
                0x4a, 0x5a, 0x6a, 0x7a, 0x0a, 0x1a, 0x2a, 0x3a,
                0xfd, 0xed, 0xdd, 0xcd, 0xbd, 0xad, 0x9d, 0x8d,
                0x7c, 0x6c, 0x5c, 0x4c, 0x3c, 0x2c, 0x1c, 0x0c,
                0xef, 0xff, 0xcf, 0xdf, 0xaf, 0xbf, 0x8f, 0x9f,
                0x6e, 0x7e, 0x4e, 0x5e, 0x2e, 0x3e, 0x0e, 0x1e
            };
    
        byte[] crc16ltab =
        {
                0x00, 0x21, 0x42, 0x63, 0x84, 0xa5, 0xc6, 0xe7,
                0x08, 0x29, 0x4a, 0x6b, 0x8c, 0xad, 0xce, 0xef,
                0x31, 0x10, 0x73, 0x52, 0xb5, 0x94, 0xf7, 0xd6,
                0x39, 0x18, 0x7b, 0x5a, 0xbd, 0x9c, 0xff, 0xde,
                0x62, 0x43, 0x20, 0x01, 0xe6, 0xc7, 0xa4, 0x85,
                0x6a, 0x4b, 0x28, 0x09, 0xee, 0xcf, 0xac, 0x8d,
                0x53, 0x72, 0x11, 0x30, 0xd7, 0xf6, 0x95, 0xb4,
                0x5b, 0x7a, 0x19, 0x38, 0xdf, 0xfe, 0x9d, 0xbc,
                0xc4, 0xe5, 0x86, 0xa7, 0x40, 0x61, 0x02, 0x23,
                0xcc, 0xed, 0x8e, 0xaf, 0x48, 0x69, 0x0a, 0x2b,
                0xf5, 0xd4, 0xb7, 0x96, 0x71, 0x50, 0x33, 0x12,
                0xfd, 0xdc, 0xbf, 0x9e, 0x79, 0x58, 0x3b, 0x1a,
                0xa6, 0x87, 0xe4, 0xc5, 0x22, 0x03, 0x60, 0x41,
                0xae, 0x8f, 0xec, 0xcd, 0x2a, 0x0b, 0x68, 0x49,
                0x97, 0xb6, 0xd5, 0xf4, 0x13, 0x32, 0x51, 0x70,
                0x9f, 0xbe, 0xdd, 0xfc, 0x1b, 0x3a, 0x59, 0x78,
                0x88, 0xa9, 0xca, 0xeb, 0x0c, 0x2d, 0x4e, 0x6f,
                0x80, 0xa1, 0xc2, 0xe3, 0x04, 0x25, 0x46, 0x67,
                0xb9, 0x98, 0xfb, 0xda, 0x3d, 0x1c, 0x7f, 0x5e,
                0xb1, 0x90, 0xf3, 0xd2, 0x35, 0x14, 0x77, 0x56,
                0xea, 0xcb, 0xa8, 0x89, 0x6e, 0x4f, 0x2c, 0x0d,
                0xe2, 0xc3, 0xa0, 0x81, 0x66, 0x47, 0x24, 0x05,
                0xdb, 0xfa, 0x99, 0xb8, 0x5f, 0x7e, 0x1d, 0x3c,
                0xd3, 0xf2, 0x91, 0xb0, 0x57, 0x76, 0x15, 0x34,
                0x4c, 0x6d, 0x0e, 0x2f, 0xc8, 0xe9, 0x8a, 0xab,
                0x44, 0x65, 0x06, 0x27, 0xc0, 0xe1, 0x82, 0xa3,
                0x7d, 0x5c, 0x3f, 0x1e, 0xf9, 0xd8, 0xbb, 0x9a,
                0x75, 0x54, 0x37, 0x16, 0xf1, 0xd0, 0xb3, 0x92,
                0x2e, 0x0f, 0x6c, 0x4d, 0xaa, 0x8b, 0xe8, 0xc9,
                0x26, 0x07, 0x64, 0x45, 0xa2, 0x83, 0xe0, 0xc1,
                0x1f, 0x3e, 0x5d, 0x7c, 0x9b, 0xba, 0xd9, 0xf8,
                0x17, 0x36, 0x55, 0x74, 0x93, 0xb2, 0xd1, 0xf0
            };
    
        byte hi = 0, lo = 0, index;
        string s = input;
    
        foreach (var ch in s)
        {
            index = (byte)(hi ^ (byte)ch);
            hi = (byte)(lo ^ crc16htab[index]);
            lo = crc16ltab[index];
        }
    
        return ((hi << 8) | lo).ToString("X");
    }
    
    private enum PrinterErrorCodes
    {
        GeneralError = 1
    }
    

    }

    Severity Code Description Project File Line Suppression State Message (active) IDE0057 Substring can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 1002 Message (active) CA1822 Members that do not access instance data or call instance methods can be marked as static. After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. This can give you a measurable performance gain for performance-sensitive code. FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 941 Message (active) CA1822 Members that do not access instance data or call instance methods can be marked as static. After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. This can give you a measurable performance gain for performance-sensitive code. FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 936 Message (active) CA1822 Members that do not access instance data or call instance methods can be marked as static. After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. This can give you a measurable performance gain for performance-sensitive code. FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 1022 Message (active) CA1822 Members that do not access instance data or call instance methods can be marked as static. After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. This can give you a measurable performance gain for performance-sensitive code. FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 759 Message (active) IDE0300 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 23 Message (active) IDE0300 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 24 Message (active) IDE0300 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 25 Message (active) IDE0300 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 26 Message (active) IDE0300 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 27 Message (active) IDE0300 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 28 Message (active) IDE0300 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 29 Message (active) IDE0300 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 30 Message (active) IDE0300 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 31 Message (active) IDE0300 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 32 Message (active) IDE0305 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 769 Message (active) IDE0028 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 815 Message (active) IDE0028 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 818 Message (active) IDE0028 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 830 Message (active) IDE0028 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 833 Message (active) IDE0028 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 845 Message (active) IDE0028 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 848 Message (active) IDE0028 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 864 Message (active) IDE0028 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 867 Message (active) IDE0028 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 886 Message (active) IDE0028 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 889 Message (active) IDE0028 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 905 Message (active) IDE0028 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 908 Message (active) IDE0028 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 920 Message (active) IDE0028 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 923 Message (active) IDE0028 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 947 Message (active) IDE0028 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 950 Message (active) IDE0300 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 1025 Message (active) IDE0300 Collection initialization can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 1061 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 820 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 835 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 850 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 851 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 852 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 853 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 869 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 870 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 871 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 872 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 873 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 874 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 875 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 876 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 891 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 892 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 893 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 894 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 895 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 910 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 925 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 926 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 927 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 928 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 929 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 930 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 931 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 932 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 952 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 953 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 954 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 955 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 956 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 957 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 958 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 959 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 960 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 961 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 962 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 963 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 964 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 965 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 966 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 967 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 968 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 969 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 970 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 971 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 972 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 973 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 974 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 975 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 976 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 977 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 978 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 979 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 980 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 981 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 982 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 983 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 984 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 985 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 986 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 987 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 988 Message (active) IDE0090 'new' expression can be simplified FiscalPrinterApi C:\Users\adala\OneDrive\Dokumenty\Posnet\Posnet\PosnetAPI\Services\FiscalPrinterService.cs 989

  2. Assistant

    Aby usunąć komunikaty wyświetlane w Visual Studio 2022, należy zrefaktoryzować kod klasy FiscalPrinterService, stosując się do sugestii narzędzia analizującego kod. Poniżej przedstawiam konkretne kroki, które należy wykonać:

    1. Uproszczenie metody Substring (IDE0057):

      Problem na linii 1002:

      Metoda Substring może być uproszczona przez użycie indeksowania zakresowego wprowadzonego w C# 8.0.

      Oryginalny kod:

      private string GetSubstringOrEmpty(string input, int startIndex)
      {
          return startIndex >= input.Length ? string.Empty : input.Substring(startIndex, input.Length - startIndex);
      }
      

      Zrefaktoryzowany kod:

      private static string GetSubstringOrEmpty(string input, int startIndex)
      {
          return startIndex >= input.Length ? string.Empty : input[startIndex..];
      }
      

      Dodatkowo, metoda nie korzysta z żadnych danych instancyjnych, więc można ją oznaczyć jako static (CA1822).

    2. Oznaczenie metod jako static (CA1822):

      Metody, które nie korzystają z danych instancyjnych klasy, powinny być oznaczone jako static. Dotyczy to metod na liniach 759, 936, 941 i 1022.

      Przykład na linii 936:

      Oryginalny kod:

      private RtcGet ParseRtcGet(string response)
      {
          // ...
      }
      

      Zrefaktoryzowany kod:

      private static RtcGet ParseRtcGet(string response)
      {
          // ...
      }
      

      Powtórz ten krok dla wszystkich wskazanych metod.

    3. Uproszczenie inicjalizacji kolekcji (IDE0300, IDE0305, IDE0028, IDE0090):

      W wielu miejscach możesz uprościć inicjalizację kolekcji, korzystając z niejawnego typowania (var) i docelowego typu (target-typed new).

      Przykład na liniach 23-32:

      Oryginalny kod:

      private static readonly string[] RtcGetCommand = new string[] { "rtcget" };
      // Powtarza się dla innych tablic
      

      Zrefaktoryzowany kod:

      private static readonly string[] RtcGetCommand = { "rtcget" };
      

      Lub jeśli deklaracja typu jest oczywista:

      private static readonly string[] RtcGetCommand = new[] { "rtcget" };
      

      Przykład dla słowników na liniach 769 i 1025:

      Oryginalny kod:

      private readonly Dictionary<int, string> frameErrorMessages = new Dictionary<int, string>()
      {
          { 1, "PROTO_ERR_CMD_UNKNOWN: Nierozpoznana komenda" },
          // ...
      };
      

      Zrefaktoryzowany kod:

      private readonly Dictionary<int, string> frameErrorMessages = new()
      {
          { 1, "PROTO_ERR_CMD_UNKNOWN: Nierozpoznana komenda" },
          // ...
      };
      
    4. Uproszczenie wyrażeń new (IDE0090):

      Kiedy typ jest oczywisty z kontekstu, możesz pominąć jego jawne określanie w wyrażeniu new.

      Przykład na linii 820:

      Oryginalny kod:

      return new List<PcCfgGet>
      {
          new PcCfgGet { cp = ..., id = ..., no = ..., pr = ... }
      };
      

      Zrefaktoryzowany kod:

      return new()
      {
          new PcCfgGet { cp = ..., id = ..., no = ..., pr = ... }
      };
      

      Powtórz ten krok dla wszystkich wskazanych linii z komunikatem IDE0090.

    5. Korzystanie z niejawnego typowania (var) tam, gdzie to możliwe:

      Jeśli typ zmiennej jest oczywisty z prawej strony przypisania, możesz użyć var.

      Przykład:

      Oryginalny kod:

      List<string> messages = new List<string>();
      

      Zrefaktoryzowany kod:

      var messages = new List<string>();
      

      Uwagi dodatkowe:

      • Upewnij się, że wszelkie zmiany nie wpływają na logikę programu ani nie wprowadzają błędów.
      • Po dokonaniu refaktoryzacji przetestuj kod, aby upewnić się, że działa poprawnie.

    Podsumowanie:

    Zrefaktoryzowanie kodu zgodnie z powyższymi wskazówkami usunie komunikaty wyświetlane w Visual Studio 2022 i poprawi czytelność oraz nowoczesność kodu. Stosowanie się do standardów kodowania oraz wykorzystanie nowszych funkcji języka C# sprawi, że kod będzie bardziej zwięzły i zgodny z najlepszymi praktykami.