Jak odczytywać BarCodes z obiektów rysunkowych systemu
Migracja z API Cloudmersive Barcode do IronBarcode
To najprostsza migracja w historii BarCode'ów .NET. Usuń klienta HTTP. Dodaj pakiet NuGet. Usuń zarządzanie kluczami API. Reszta to po prostu wyszukiwanie i zamiana.
SDK .NET od Cloudmersive to wygenerowany klient API REST — cienka otoczka wokół wywołań HttpClient. Każdy fragment kodu specyficznego dla Cloudmersive w aplikacji to albo konfiguracja dla tego klienta, albo wywołania za pośrednictwem tego klienta, albo obsługa błędów w przypadku niepowodzenia żądań sieciowych. Żadna z tych infrastruktur nie jest potrzebna w przypadku IronBarcode, który przetwarza kody kreskowe lokalnie, bez zależności od sieci.
Szybki start: trzy kroki
Krok 1: Zamień pakiety
dotnet remove package Cloudmersive.APIClient.NET.Barcode
dotnet add package BarCode
dotnet remove package Cloudmersive.APIClient.NET.Barcode
dotnet add package BarCode
Krok 2: Zastąp przestrzenie nazw
// Remove these
using Cloudmersive.APIClient.NET.Barcode.Api;
using Cloudmersive.APIClient.NET.Barcode.Client;
// Add this
using IronBarCode;
// Remove these
using Cloudmersive.APIClient.NET.Barcode.Api;
using Cloudmersive.APIClient.NET.Barcode.Client;
// Add this
using IronBarCode;
Imports IronBarCode
Krok 3: Zastąp "Konfiguracja klucza API" przez "Klucz licencyjny"
// Remove this
Configuration.Default.ApiKey.Add("Apikey", "YOUR-CLOUDMERSIVE-API-KEY");
// Replace with this — set once at application startup
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY";
// Remove this
Configuration.Default.ApiKey.Add("Apikey", "YOUR-CLOUDMERSIVE-API-KEY");
// Replace with this — set once at application startup
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY";
' Remove this
Configuration.Default.ApiKey.Add("Apikey", "YOUR-CLOUDMERSIVE-API-KEY")
' Replace with this — set once at application startup
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY"
W aplikacji ASP.NET Core klucz licencyjny umieszcza się w Program.cs przed builder.Build():
using IronBarCode;
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY";
var builder = WebApplication.CreateBuilder(args);
// ... rest of startup
using IronBarCode;
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY";
var builder = WebApplication.CreateBuilder(args);
// ... rest of startup
Imports IronBarCode
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY"
Dim builder = WebApplication.CreateBuilder(args)
' ... rest of startup
Koszt: ile wydawałeś dotychczas a ile wydasz
Przed migracją warto obliczyć, ile faktycznie kosztuje integracja z Cloudmersive. Rachunek jest prosty:
| Twoja dzienna liczba słów | Miesięczne zlecenia | Poziom Cloudmersive | IronBarcode (jednorazowe zlecenie) |
|---|---|---|---|
| 100/dzień | ~3 000 | Podstawowy $19.99/miesiąc | $749 |
| 1000/dzień | ~30 000 | Biznesowy Premier $99.99/miesiąc | $749 |
| 5 000/dzień | ~150 000 | Średni Biznes $499.99/miesiąc | $749 |
| 10 000/dzień | ~300 000 | Enterprise (niestandardowy) | $749 |
| 25 000/dzień | ~750 000 | Enterprise (niestandardowy) | 1499 USD (Plus 3 programistów) |
Jeśli płacisz więcej niż ~$63/miesiąc dla Cloudmersive, Lite licencja IronBarcode opłaca się w ciągu pierwszego roku. Po osiągnięciu progu rentowności IronBarcode jest licencją wieczystą bez odnowień i opłat za żądanie.
Przykłady migracji kodu
Generowanie kodów QR
Najpopularniejsze mapy wywołań generacji Cloudmersive odpowiadają bezpośrednio IronBarcode:
Przed (Cloudmersive):
using Cloudmersive.APIClient.NET.Barcode.Api;
using Cloudmersive.APIClient.NET.Barcode.Client;
Configuration.Default.ApiKey.Add("Apikey", "YOUR-CLOUDMERSIVE-API-KEY");
var apiInstance = new GenerateBarcodeApi();
byte[] result = apiInstance.GenerateBarcodeQRCode("https://example.com");
File.WriteAllBytes("qr.png", result);
using Cloudmersive.APIClient.NET.Barcode.Api;
using Cloudmersive.APIClient.NET.Barcode.Client;
Configuration.Default.ApiKey.Add("Apikey", "YOUR-CLOUDMERSIVE-API-KEY");
var apiInstance = new GenerateBarcodeApi();
byte[] result = apiInstance.GenerateBarcodeQRCode("https://example.com");
File.WriteAllBytes("qr.png", result);
Imports Cloudmersive.APIClient.NET.Barcode.Api
Imports Cloudmersive.APIClient.NET.Barcode.Client
Configuration.Default.ApiKey.Add("Apikey", "YOUR-CLOUDMERSIVE-API-KEY")
Dim apiInstance As New GenerateBarcodeApi()
Dim result As Byte() = apiInstance.GenerateBarcodeQRCode("https://example.com")
File.WriteAllBytes("qr.png", result)
Po (IronBarcode):
using IronBarCode;
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY";
byte[] result = QRCodeWriter.CreateQrCode("https://example.com", 500)
.ToPngBinaryData();
File.WriteAllBytes("qr.png", result);
// Or save directly
QRCodeWriter.CreateQrCode("https://example.com", 500)
.SaveAsPng("qr.png");
using IronBarCode;
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY";
byte[] result = QRCodeWriter.CreateQrCode("https://example.com", 500)
.ToPngBinaryData();
File.WriteAllBytes("qr.png", result);
// Or save directly
QRCodeWriter.CreateQrCode("https://example.com", 500)
.SaveAsPng("qr.png");
Imports IronBarCode
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY"
Dim result As Byte() = QRCodeWriter.CreateQrCode("https://example.com", 500).ToPngBinaryData()
File.WriteAllBytes("qr.png", result)
' Or save directly
QRCodeWriter.CreateQrCode("https://example.com", 500).SaveAsPng("qr.png")
Generowanie kodu 128
Przed (Cloudmersive):
using Cloudmersive.APIClient.NET.Barcode.Api;
using Cloudmersive.APIClient.NET.Barcode.Client;
Configuration.Default.ApiKey.Add("Apikey", "YOUR-CLOUDMERSIVE-API-KEY");
var apiInstance = new GenerateBarcodeApi();
byte[] result = apiInstance.GenerateBarcodeCode128("SHIP-2024031500428");
File.WriteAllBytes("barcode.png", result);
using Cloudmersive.APIClient.NET.Barcode.Api;
using Cloudmersive.APIClient.NET.Barcode.Client;
Configuration.Default.ApiKey.Add("Apikey", "YOUR-CLOUDMERSIVE-API-KEY");
var apiInstance = new GenerateBarcodeApi();
byte[] result = apiInstance.GenerateBarcodeCode128("SHIP-2024031500428");
File.WriteAllBytes("barcode.png", result);
Imports Cloudmersive.APIClient.NET.Barcode.Api
Imports Cloudmersive.APIClient.NET.Barcode.Client
Configuration.Default.ApiKey.Add("Apikey", "YOUR-CLOUDMERSIVE-API-KEY")
Dim apiInstance As New GenerateBarcodeApi()
Dim result As Byte() = apiInstance.GenerateBarcodeCode128("SHIP-2024031500428")
File.WriteAllBytes("barcode.png", result)
Po (IronBarcode):
using IronBarCode;
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY";
BarcodeWriter.CreateBarcode("SHIP-2024031500428", BarcodeEncoding.Code128)
.SaveAsPng("barcode.png");
// Or get bytes directly
byte[] result = BarcodeWriter.CreateBarcode("SHIP-2024031500428", BarcodeEncoding.Code128)
.ToPngBinaryData();
using IronBarCode;
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY";
BarcodeWriter.CreateBarcode("SHIP-2024031500428", BarcodeEncoding.Code128)
.SaveAsPng("barcode.png");
// Or get bytes directly
byte[] result = BarcodeWriter.CreateBarcode("SHIP-2024031500428", BarcodeEncoding.Code128)
.ToPngBinaryData();
Imports IronBarCode
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY"
BarcodeWriter.CreateBarcode("SHIP-2024031500428", BarcodeEncoding.Code128) _
.SaveAsPng("barcode.png")
' Or get bytes directly
Dim result As Byte() = BarcodeWriter.CreateBarcode("SHIP-2024031500428", BarcodeEncoding.Code128) _
.ToPngBinaryData()
Odczytywanie BarCode
Przed (Cloudmersive):
using Cloudmersive.APIClient.NET.Barcode.Api;
using Cloudmersive.APIClient.NET.Barcode.Client;
Configuration.Default.ApiKey.Add("Apikey", "YOUR-CLOUDMERSIVE-API-KEY");
var scanApi = new BarcodeScanApi();
using (var stream = File.OpenRead("barcode.png"))
{
var result = scanApi.BarcodeScanImage(stream);
if (result.Successful == true)
{
Console.WriteLine($"Value: {result.RawText}");
Console.WriteLine($"Type: {result.BarcodeType}");
}
}
using Cloudmersive.APIClient.NET.Barcode.Api;
using Cloudmersive.APIClient.NET.Barcode.Client;
Configuration.Default.ApiKey.Add("Apikey", "YOUR-CLOUDMERSIVE-API-KEY");
var scanApi = new BarcodeScanApi();
using (var stream = File.OpenRead("barcode.png"))
{
var result = scanApi.BarcodeScanImage(stream);
if (result.Successful == true)
{
Console.WriteLine($"Value: {result.RawText}");
Console.WriteLine($"Type: {result.BarcodeType}");
}
}
Imports Cloudmersive.APIClient.NET.Barcode.Api
Imports Cloudmersive.APIClient.NET.Barcode.Client
Configuration.Default.ApiKey.Add("Apikey", "YOUR-CLOUDMERSIVE-API-KEY")
Dim scanApi As New BarcodeScanApi()
Using stream = File.OpenRead("barcode.png")
Dim result = scanApi.BarcodeScanImage(stream)
If result.Successful = True Then
Console.WriteLine($"Value: {result.RawText}")
Console.WriteLine($"Type: {result.BarcodeType}")
End If
End Using
Po (IronBarcode):
using IronBarCode;
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY";
var results = BarcodeReader.Read("barcode.png");
var result = results.First();
Console.WriteLine($"Value: {result.Value}");
Console.WriteLine($"Type: {result.Format}");
using IronBarCode;
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY";
var results = BarcodeReader.Read("barcode.png");
var result = results.First();
Console.WriteLine($"Value: {result.Value}");
Console.WriteLine($"Type: {result.Format}");
Imports IronBarCode
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY"
Dim results = BarcodeReader.Read("barcode.png")
Dim result = results.First()
Console.WriteLine($"Value: {result.Value}")
Console.WriteLine($"Type: {result.Format}")
Asynchroniczne odczytywanie BarCodes
Jeśli Twoja integracja z Cloudmersive wykorzystuje asynchroniczny interfejs API:
Przed (Cloudmersive):
using Cloudmersive.APIClient.NET.Barcode.Api;
using Cloudmersive.APIClient.NET.Barcode.Client;
Configuration.Default.ApiKey.Add("Apikey", "YOUR-CLOUDMERSIVE-API-KEY");
var scanApi = new BarcodeScanApi();
using (var stream = File.OpenRead("barcode.png"))
{
var result = await scanApi.BarcodeScanImageAsync(stream);
return result.Successful == true ? result.RawText : null;
}
using Cloudmersive.APIClient.NET.Barcode.Api;
using Cloudmersive.APIClient.NET.Barcode.Client;
Configuration.Default.ApiKey.Add("Apikey", "YOUR-CLOUDMERSIVE-API-KEY");
var scanApi = new BarcodeScanApi();
using (var stream = File.OpenRead("barcode.png"))
{
var result = await scanApi.BarcodeScanImageAsync(stream);
return result.Successful == true ? result.RawText : null;
}
Imports Cloudmersive.APIClient.NET.Barcode.Api
Imports Cloudmersive.APIClient.NET.Barcode.Client
Configuration.Default.ApiKey.Add("Apikey", "YOUR-CLOUDMERSIVE-API-KEY")
Dim scanApi As New BarcodeScanApi()
Using stream = File.OpenRead("barcode.png")
Dim result = Await scanApi.BarcodeScanImageAsync(stream)
Return If(result.Successful = True, result.RawText, Nothing)
End Using
Po (IronBarcode):
using IronBarCode;
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY";
// IronBarcode is synchronous; wrap in Task.Run to free the calling thread for CPU-bound work
var results = await Task.Run(() => BarcodeReader.Read("barcode.png"));
return results.FirstOrDefault()?.Value;
using IronBarCode;
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY";
// IronBarcode is synchronous; wrap in Task.Run to free the calling thread for CPU-bound work
var results = await Task.Run(() => BarcodeReader.Read("barcode.png"));
return results.FirstOrDefault()?.Value;
Imports IronBarCode
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY"
' IronBarcode is synchronous; wrap in Task.Run to free the calling thread for CPU-bound work
Dim results = Await Task.Run(Function() BarcodeReader.Read("barcode.png"))
Return results.FirstOrDefault()?.Value
Odczytywanie BarCodes z plików PDF
Cloudmersive nie obsługuje natywnie plików PDF. Jeśli istniejący kod wyodrębnia obrazy z plików PDF przed skanowaniem, zastąp cały ten proces pojedynczym wywołaniem IronBarcode:
Przed (Cloudmersive — wymaga oddzielnego wyodrębnienia pliku PDF):
// Requires a separate PDF library to extract pages as images,
// then one Cloudmersive API call per extracted page image.
var scanApi = new BarcodeScanApi();
foreach (var pageImagePath in ExtractPdfPages("document.pdf"))
{
using var stream = File.OpenRead(pageImagePath);
var result = await scanApi.BarcodeScanImageAsync(stream);
if (result.Successful == true)
{
Console.WriteLine($"Found: {result.RawText}");
}
}
// Requires a separate PDF library to extract pages as images,
// then one Cloudmersive API call per extracted page image.
var scanApi = new BarcodeScanApi();
foreach (var pageImagePath in ExtractPdfPages("document.pdf"))
{
using var stream = File.OpenRead(pageImagePath);
var result = await scanApi.BarcodeScanImageAsync(stream);
if (result.Successful == true)
{
Console.WriteLine($"Found: {result.RawText}");
}
}
Imports System.IO
Imports Cloudmersive.APIClient.NET.BarcodeScan
' Requires a separate PDF library to extract pages as images,
' then one Cloudmersive API call per extracted page image.
Dim scanApi As New BarcodeScanApi()
For Each pageImagePath In ExtractPdfPages("document.pdf")
Using stream As FileStream = File.OpenRead(pageImagePath)
Dim result = Await scanApi.BarcodeScanImageAsync(stream)
If result.Successful = True Then
Console.WriteLine($"Found: {result.RawText}")
End If
End Using
Next
Po (IronBarcode):
using IronBarCode;
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY";
// One call — all pages, all barcodes, no image extraction step
var results = BarcodeReader.Read("document.pdf");
foreach (var result in results)
{
Console.WriteLine($"Page {result.PageNumber}: {result.Value}");
}
using IronBarCode;
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY";
// One call — all pages, all barcodes, no image extraction step
var results = BarcodeReader.Read("document.pdf");
foreach (var result in results)
{
Console.WriteLine($"Page {result.PageNumber}: {result.Value}");
}
Imports IronBarCode
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY"
' One call — all pages, all barcodes, no image extraction step
Dim results = BarcodeReader.Read("document.pdf")
For Each result In results
Console.WriteLine($"Page {result.PageNumber}: {result.Value}")
Next
Wykrywanie wielu BarCodes
Jeśli masz kod, który skanuje dokumenty z wieloma BARCODE'ami:
Przed (Cloudmersive — wymagane wielokrotne wywołania):
// Cloudmersive returns one barcode per scan — multiple calls for multiple barcodes
var scanApi = new BarcodeScanApi();
var barcodeValues = new List<string>();
foreach (var croppedRegion in CropBarcodeRegions("invoice.png"))
{
using var stream = new MemoryStream(croppedRegion);
var result = await scanApi.BarcodeScanImageAsync(stream);
if (result.Successful == true)
barcodeValues.Add(result.RawText);
}
// Cloudmersive returns one barcode per scan — multiple calls for multiple barcodes
var scanApi = new BarcodeScanApi();
var barcodeValues = new List<string>();
foreach (var croppedRegion in CropBarcodeRegions("invoice.png"))
{
using var stream = new MemoryStream(croppedRegion);
var result = await scanApi.BarcodeScanImageAsync(stream);
if (result.Successful == true)
barcodeValues.Add(result.RawText);
}
Imports System.IO
Imports System.Collections.Generic
Imports System.Threading.Tasks
' Cloudmersive returns one barcode per scan — multiple calls for multiple barcodes
Dim scanApi As New BarcodeScanApi()
Dim barcodeValues As New List(Of String)()
For Each croppedRegion In CropBarcodeRegions("invoice.png")
Using stream As New MemoryStream(croppedRegion)
Dim result = Await scanApi.BarcodeScanImageAsync(stream)
If result.Successful = True Then
barcodeValues.Add(result.RawText)
End If
End Using
Next
Po (IronBarcode):
using IronBarCode;
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY";
var options = new BarcodeReaderOptions
{
Speed = ReadingSpeed.Balanced,
ExpectMultipleBarcodes = true,
};
// One call — returns all barcodes in the image
var results = BarcodeReader.Read("invoice.png", options);
var barcodeValues = results.Select(r => r.Value).ToList();
using IronBarCode;
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY";
var options = new BarcodeReaderOptions
{
Speed = ReadingSpeed.Balanced,
ExpectMultipleBarcodes = true,
};
// One call — returns all barcodes in the image
var results = BarcodeReader.Read("invoice.png", options);
var barcodeValues = results.Select(r => r.Value).ToList();
Imports IronBarCode
IronBarCode.License.LicenseKey = "YOUR-LICENSE-KEY"
Dim options As New BarcodeReaderOptions With {
.Speed = ReadingSpeed.Balanced,
.ExpectMultipleBarcodes = True
}
' One call — returns all barcodes in the image
Dim results = BarcodeReader.Read("invoice.png", options)
Dim barcodeValues = results.Select(Function(r) r.Value).ToList()
Usuwanie infrastruktury, która nie jest już potrzebna
Jest to etap migracji, w którym usuwa się więcej kodu niż się pisze.
Usuń obsługę wyjątków HTTP
Operacje Cloudmersive mogą zakończyć się niepowodzeniem z powodu błędów sieciowych, odpowiedzi HTTP 4xx/5xx oraz wyjątków związanych z przekroczeniem limitu czasu. Zazwyczaj powoduje to powstanie infrastruktury try/catch, której IronBarcode nie potrzebuje:
// Remove all of this
try
{
var result = await scanApi.BarcodeScanImageAsync(stream);
// ...
}
catch (ApiException ex) when (ex.ErrorCode == 429)
{
// Rate limited — wait and retry
await Task.Delay(TimeSpan.FromSeconds(2));
// retry logic...
}
catch (ApiException ex) when (ex.ErrorCode == 503)
{
// Service unavailable — Cloudmersive is down
_logger.LogError("Cloudmersive unavailable: {Message}", ex.Message);
throw;
}
catch (HttpRequestException ex)
{
// Network error
_logger.LogError("Network failure: {Message}", ex.Message);
throw;
}
catch (TaskCanceledException)
{
// Timeout
_logger.LogError("Cloudmersive request timed out");
throw;
}
// Remove all of this
try
{
var result = await scanApi.BarcodeScanImageAsync(stream);
// ...
}
catch (ApiException ex) when (ex.ErrorCode == 429)
{
// Rate limited — wait and retry
await Task.Delay(TimeSpan.FromSeconds(2));
// retry logic...
}
catch (ApiException ex) when (ex.ErrorCode == 503)
{
// Service unavailable — Cloudmersive is down
_logger.LogError("Cloudmersive unavailable: {Message}", ex.Message);
throw;
}
catch (HttpRequestException ex)
{
// Network error
_logger.LogError("Network failure: {Message}", ex.Message);
throw;
}
catch (TaskCanceledException)
{
// Timeout
_logger.LogError("Cloudmersive request timed out");
throw;
}
Imports System
Imports System.Threading.Tasks
' Remove all of this
Try
Dim result = Await scanApi.BarcodeScanImageAsync(stream)
' ...
Catch ex As ApiException When ex.ErrorCode = 429
' Rate limited — wait and retry
Await Task.Delay(TimeSpan.FromSeconds(2))
' retry logic...
Catch ex As ApiException When ex.ErrorCode = 503
' Service unavailable — Cloudmersive is down
_logger.LogError("Cloudmersive unavailable: {Message}", ex.Message)
Throw
Catch ex As HttpRequestException
' Network error
_logger.LogError("Network failure: {Message}", ex.Message)
Throw
Catch ex As TaskCanceledException
' Timeout
_logger.LogError("Cloudmersive request timed out")
Throw
End Try
IronBarcode nie generuje wyjątków sieciowych. Rzuca BarcodeException, jeśli kod kreskowy nie może być zdekodowany z danych wejściowych, co jest problemem z zawartością, a nie z infrastrukturą. Uproszczona obsługa błędów:
using IronBarCode;
var results = BarcodeReader.Read("barcode.png");
if (!results.Any())
{
_logger.LogWarning("No barcode detected in image");
}
using IronBarCode;
var results = BarcodeReader.Read("barcode.png");
if (!results.Any())
{
_logger.LogWarning("No barcode detected in image");
}
Imports IronBarCode
Dim results = BarcodeReader.Read("barcode.png")
If Not results.Any() Then
_logger.LogWarning("No barcode detected in image")
End If
Usuń logikę ponownej próby
Jeśli Twoja integracja z Cloudmersive zawiera zasady ponownych prób — Polly, niestandardowe pętle ponownych prób lub wykładniczy backoff — usuń je całkowicie:
// Remove retry infrastructure
// var retryPolicy = Policy
// .Handle<ApiException>()
// .WaitAndRetryAsync(3, retryAttempt =>
// TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
// IronBarcode — no retry needed
var results = BarcodeReader.Read("barcode.png");
// Remove retry infrastructure
// var retryPolicy = Policy
// .Handle<ApiException>()
// .WaitAndRetryAsync(3, retryAttempt =>
// TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
// IronBarcode — no retry needed
var results = BarcodeReader.Read("barcode.png");
' Remove retry infrastructure
' Dim retryPolicy = Policy _
' .Handle(Of ApiException)() _
' .WaitAndRetryAsync(3, Function(retryAttempt) _
' TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)))
' IronBarcode — no retry needed
Dim results = BarcodeReader.Read("barcode.png")
Usuń śledzenie limitów szybkości
Jeśli Twój kod śledzi liczbę wywołań API, aby nie przekroczyć miesięcznego limitu Cloudmersive:
// Remove quota tracking
// private static int _monthlyCallCount = 0;
// private const int MonthlyLimit = 30000;
//
// if (Interlocked.Increment(ref _monthlyCallCount) > MonthlyLimit)
// throw new InvalidOperationException("Monthly Cloudmersive quota exceeded");
// IronBarcode — no quota
var results = BarcodeReader.Read("barcode.png");
// Remove quota tracking
// private static int _monthlyCallCount = 0;
// private const int MonthlyLimit = 30000;
//
// if (Interlocked.Increment(ref _monthlyCallCount) > MonthlyLimit)
// throw new InvalidOperationException("Monthly Cloudmersive quota exceeded");
// IronBarcode — no quota
var results = BarcodeReader.Read("barcode.png");
' Remove quota tracking
' Private Shared _monthlyCallCount As Integer = 0
' Private Const MonthlyLimit As Integer = 30000
'
' If Interlocked.Increment(_monthlyCallCount) > MonthlyLimit Then
' Throw New InvalidOperationException("Monthly Cloudmersive quota exceeded")
' IronBarcode — no quota
Dim results = BarcodeReader.Read("barcode.png")
Usuń konfigurację limitu czasu sieciowego
Klienci Cloudmersive często uwzględniają konfigurację limitu czasu. Usuń to:
// Remove timeout configuration
// Configuration.Default.Timeout = 30000; // 30 second timeout
// Configuration.Default.ConnectionTimeout = 5000;
// IronBarcode has no network timeout — no network
// Remove timeout configuration
// Configuration.Default.Timeout = 30000; // 30 second timeout
// Configuration.Default.ConnectionTimeout = 5000;
// IronBarcode has no network timeout — no network
' Remove timeout configuration
' Configuration.Default.Timeout = 30000 ' 30 second timeout
' Configuration.Default.ConnectionTimeout = 5000
' IronBarcode has no network timeout — no network
Usuń rotację kluczy API
Jeśli Twoja aplikacja zmienia klucze API zgodnie z harmonogramem lub przechowuje je w systemie zarządzania sekretami:
// Simplify this pattern
// private string GetCloudmersiveApiKey() =>
// _secretManager.GetSecret("cloudmersive-api-key-current");
//
// Configuration.Default.ApiKey["Apikey"] = GetCloudmersiveApiKey();
// IronBarcode — set once at startup
IronBarCode.License.LicenseKey = _configuration["IronBarcode:LicenseKey"];
// or literal: "YOUR-LICENSE-KEY"
// Simplify this pattern
// private string GetCloudmersiveApiKey() =>
// _secretManager.GetSecret("cloudmersive-api-key-current");
//
// Configuration.Default.ApiKey["Apikey"] = GetCloudmersiveApiKey();
// IronBarcode — set once at startup
IronBarCode.License.LicenseKey = _configuration["IronBarcode:LicenseKey"];
// or literal: "YOUR-LICENSE-KEY"
' Simplify this pattern
' Private Function GetCloudmersiveApiKey() As String
' Return _secretManager.GetSecret("cloudmersive-api-key-current")
' End Function
'
' Configuration.Default.ApiKey("Apikey") = GetCloudmersiveApiKey()
' IronBarcode — set once at startup
IronBarCode.License.LicenseKey = _configuration("IronBarcode:LicenseKey")
' or literal: "YOUR-LICENSE-KEY"
Typowe problemy związane z migracją
Cloudmersive zwrócił byte[] dla generacji
Metody generowania w Cloudmersive zwracają bezpośrednio byte[]. IronBarcode zwraca obiekt GeneratedBarcode, który daje więcej opcji:
// Cloudmersive returned byte[] directly
byte[] cloudmersiveResult = apiInstance.GenerateBarcodeQRCode("data");
// IronBarcode — call ToPngBinaryData() for the equivalent byte[]
byte[] ironBarcodeResult = BarcodeWriter.CreateBarcode("data", BarcodeEncoding.QRCode)
.ToPngBinaryData();
// Or save directly (often simpler)
BarcodeWriter.CreateBarcode("data", BarcodeEncoding.QRCode)
.SaveAsPng("output.png");
// Or get other formats
byte[] jpegBytes = BarcodeWriter.CreateBarcode("data", BarcodeEncoding.QRCode)
.ToJpegBinaryData();
// Cloudmersive returned byte[] directly
byte[] cloudmersiveResult = apiInstance.GenerateBarcodeQRCode("data");
// IronBarcode — call ToPngBinaryData() for the equivalent byte[]
byte[] ironBarcodeResult = BarcodeWriter.CreateBarcode("data", BarcodeEncoding.QRCode)
.ToPngBinaryData();
// Or save directly (often simpler)
BarcodeWriter.CreateBarcode("data", BarcodeEncoding.QRCode)
.SaveAsPng("output.png");
// Or get other formats
byte[] jpegBytes = BarcodeWriter.CreateBarcode("data", BarcodeEncoding.QRCode)
.ToJpegBinaryData();
Imports Cloudmersive.APIClient
Imports IronBarCode
' Cloudmersive returned byte() directly
Dim cloudmersiveResult As Byte() = apiInstance.GenerateBarcodeQRCode("data")
' IronBarcode — call ToPngBinaryData() for the equivalent byte()
Dim ironBarcodeResult As Byte() = BarcodeWriter.CreateBarcode("data", BarcodeEncoding.QRCode) _
.ToPngBinaryData()
' Or save directly (often simpler)
BarcodeWriter.CreateBarcode("data", BarcodeEncoding.QRCode) _
.SaveAsPng("output.png")
' Or get other formats
Dim jpegBytes As Byte() = BarcodeWriter.CreateBarcode("data", BarcodeEncoding.QRCode) _
.ToJpegBinaryData()
Cloudmersive Reading zwróciło model odpowiedzi JSON
Wynik skanowania Cloudmersive to model odpowiedzi z właściwościami takimi jak Successful, RawText i BarcodeType. IronBarcode zwraca obiekty wyników typu:
// Cloudmersive result model
if (cloudmersiveResult.Successful == true)
{
string value = cloudmersiveResult.RawText;
string type = cloudmersiveResult.BarcodeType;
}
// IronBarcode result — use .Value and .Format directly
var results = BarcodeReader.Read("barcode.png");
if (results.Any())
{
string value = results.First().Value;
string format = results.First().Format.ToString();
}
// Cloudmersive result model
if (cloudmersiveResult.Successful == true)
{
string value = cloudmersiveResult.RawText;
string type = cloudmersiveResult.BarcodeType;
}
// IronBarcode result — use .Value and .Format directly
var results = BarcodeReader.Read("barcode.png");
if (results.Any())
{
string value = results.First().Value;
string format = results.First().Format.ToString();
}
' Cloudmersive result model
If cloudmersiveResult.Successful = True Then
Dim value As String = cloudmersiveResult.RawText
Dim type As String = cloudmersiveResult.BarcodeType
End If
' IronBarcode result — use .Value and .Format directly
Dim results = BarcodeReader.Read("barcode.png")
If results.Any() Then
Dim value As String = results.First().Value
Dim format As String = results.First().Format.ToString()
End If
Wiele typów instancji API Cloudmersive
Cloudmersive rozdziela generowanie i skanowanie na instancje GenerateBarcodeApi i BarcodeScanApi. IronBarcode wykorzystuje klasy statyczne — nie są potrzebne żadne instancje:
// Cloudmersive — two separate API instances
var generateApi = new GenerateBarcodeApi();
var scanApi = new BarcodeScanApi();
// IronBarcode — static, no instances
// BarcodeWriter for generation
// BarcodeReader for reading
// QRCodeWriter for QR codes specifically
// Cloudmersive — two separate API instances
var generateApi = new GenerateBarcodeApi();
var scanApi = new BarcodeScanApi();
// IronBarcode — static, no instances
// BarcodeWriter for generation
// BarcodeReader for reading
// QRCodeWriter for QR codes specifically
' Cloudmersive — two separate API instances
Dim generateApi As New GenerateBarcodeApi()
Dim scanApi As New BarcodeScanApi()
' IronBarcode — static, no instances
' BarcodeWriter for generation
' BarcodeReader for reading
' QRCodeWriter for QR codes specifically
Lista kontrolna migracji
Przeprowadź te wyszukiwania w swoim kodzie przed i po migracji, aby sprawdzić, czy wychwyciłeś wszystkie odniesienia do Cloudmersive:
# Find all Cloudmersive references
grep -r "Cloudmersive" --include="*.cs" .
grep -r "GenerateBarcodeApi" --include="*.cs" .
grep -r "BarcodeScanApi" --include="*.cs" .
grep -r "Configuration.Default.ApiKey" --include="*.cs" .
grep -r '"Apikey"' --include="*.cs" .
grep -r "GenerateBarcodeQRCode" --include="*.cs" .
grep -r "GenerateBarcodeCode128" --include="*.cs" .
grep -r "BarcodeScanImage" --include="*.cs" .
grep -r "cloudmersive" --include="*.csproj" .
grep -r "cloudmersive" --include="*.json" .
# Find all Cloudmersive references
grep -r "Cloudmersive" --include="*.cs" .
grep -r "GenerateBarcodeApi" --include="*.cs" .
grep -r "BarcodeScanApi" --include="*.cs" .
grep -r "Configuration.Default.ApiKey" --include="*.cs" .
grep -r '"Apikey"' --include="*.cs" .
grep -r "GenerateBarcodeQRCode" --include="*.cs" .
grep -r "GenerateBarcodeCode128" --include="*.cs" .
grep -r "BarcodeScanImage" --include="*.cs" .
grep -r "cloudmersive" --include="*.csproj" .
grep -r "cloudmersive" --include="*.json" .
Po migracji wszystkie wyszukiwania powinny zwracać zero wyników. Następnie sprawdź, czy IronBarcode jest poprawnie przywołany:
grep -r "IronBarCode" --include="*.cs" .
grep -r "BarcodeReader" --include="*.cs" .
grep -r "BarcodeWriter" --include="*.cs" .
grep -r "IronBarCode" --include="*.cs" .
grep -r "BarcodeReader" --include="*.cs" .
grep -r "BarcodeWriter" --include="*.cs" .
Lista kontrolna konfiguracji
- Usuń
Cloudmersive.APIClient.NET.Barcodeze wszystkich plików.csproj - Usuń klucz API Cloudmersive z
appsettings.json, zmiennych środowiskowych i magazynów sekretów - Dodaj pakiet NuGet IronBarcode
- Dodaj inicjalizację
IronBarCode.License.LicenseKeyprzy starcie aplikacji - Usuń zasady ponownych prób i mechanizmy zabezpieczające dla wywołań Cloudmersive
- Usuń kod śledzenia limitów częstotliwości
- Usuń konfigurację limitu czasu sieciowego
Lista kontrolna do testowania
Po zakończeniu migracji:
- Sprawdź, czy generowanie kodów QR daje poprawny wynik, który można zeskanować
- Weryfikacja generowania kodów Code128 i innych kodów kreskowych liniowych
- Sprawdź odczyt BARCODE-ów z popularnych formatów obrazów (PNG, JPEG, BMP)
- Sprawdź odczyt plików PDF, jeśli przetwarzasz dokumenty w formacie PDF
- W razie potrzeby przetestuj wykrywanie wielu BarCodes
- Upewnij się, że w ruchu sieciowym nie pojawiają się żadne wywołania API Cloudmersive
- Sprawdź, czy aplikacja działa poprawnie bez połączenia z Internetem
Co zyskujesz po migracji
Oprócz oszczędności kosztów migracja eliminuje całą gamę problemów operacyjnych:
Koniec z przetwarzaniem kodów kreskowych zależnym od sieci. Twój proces przetwarzania dokumentów działa niezależnie od dostępności Cloudmersive, jakości połączenia internetowego czy skoków opóźnień sieciowych.
Koniec z zarządzaniem limitami. Skoki w ilości dokumentów pod koniec miesiąca nie powodują niespodziewanych przekroczeń limitów ani błędów przetwarzania.
Żadne dane nie opuszczają już Twojej sieci. Obrazy BARCODE zawierające poufne informacje o klientach, dane finansowe lub informacje dotyczące zdrowia pozostają w Twojej infrastrukturze.
Prostszy kod. Zniknęła infrastruktura ponownych prób, obsługa limitów czasu i zarządzanie wyjątkami HTTP, które są wymagane w produkcyjnych integracjach Cloudmersive. Zastępuje to bezpośrednie wywołanie metody.
Migracja ma charakter mechaniczny. Korzyści mają charakter strukturalny — eliminują zależność od zewnętrznej usługi sieciowej z procesu, który jej nie wymaga.
Często Zadawane Pytania
Dlaczego warto przejść z Cloudmersive BarCode API na IronBarcode?
Typowe powody to uproszczenie licencjonowania (eliminacja złożoności związanej z SDK i kluczem uruchomieniowym), zniesienie limitów przepustowości, uzyskanie natywnej obsługi plików PDF, usprawnienie wdrażania w środowisku Docker/CI/CD oraz ograniczenie powtarzalnego kodu API w kodzie produkcyjnym.
Jak zastąpić wywołania API Cloudmersive za pomocą IronBarcode?
Zastąp standardowe fragmenty kodu dotyczące tworzenia instancji i licencjonowania wyrażeniem IronBarCode.License.LicenseKey = "key". Zastąp wywołania czytnika wyrażeniem BarcodeReader.Read(path), a wywołania zapisu wyrażeniem BarcodeWriter.CreateBarcode(data, encoding). Metody statyczne nie wymagają zarządzania instancjami.
Jak bardzo zmienia się kod podczas migracji z Cloudmersive BarCode API do IronBarcode?
Większość migracji skutkuje zmniejszeniem liczby linii kodu. Usuwane są standardowe fragmenty dotyczące licencji, konstruktory instancji oraz jawna konfiguracja formatów. Podstawowe operacje odczytu/zapisu są mapowane na krótsze odpowiedniki w IronBarcode z bardziej przejrzystymi obiektami wynikowymi.
Czy podczas migracji muszę mieć zainstalowane zarówno Cloudmersive BarCode API, jak i IronBarcode?
Nie. Większość migracji polega na bezpośredniej wymianie, a nie na równoległym działaniu. Należy migrować po jednej klasie usługowej na raz, zastąpić odwołanie do NuGet oraz zaktualizować wzorce instancjonowania i wywoływania API przed przejściem do kolejnej klasy.
Jaka jest nazwa pakietu NuGet dla IronBarcode?
Pakiet nosi nazwę „IronBarcode” (z wielkimi literami B i C). Zainstaluj go za pomocą polecenia „Install-Package IronBarcode” lub „dotnet add package IronBarcode”. Dyrektywa using w kodzie to „using IronBarcode;”.
W jaki sposób IronBarcode upraszcza wdrażanie Docker w porównaniu z Cloudmersive BarCode API?
IronBarcode to pakiet NuGet bez zewnętrznych plików SDK ani konfiguracji licencji. W Dockerze należy ustawić zmienną środowiskową IRONBARCODE_LICENSE_KEY, a pakiet zajmie się weryfikacją licencji podczas uruchamiania.
Czy IronBarcode automatycznie wykrywa wszystkie formaty kodów kreskowych po migracji z Cloudmersive?
Tak. IronBarcode automatycznie wykrywa symbole we wszystkich obsługiwanych formatach. Wyraźne wyliczenie typów kodów kreskowych nie jest wymagane. Jeśli format jest już znany, a wydajność ma znaczenie, BarcodeReaderOptions pozwala ograniczyć obszar wyszukiwania w celu optymalizacji.
Czy IronBarcode może odczytywać BarCodes z plików PDF bez oddzielnej biblioteki?
Tak. BarCodeReader.Read("document.pdf") przetwarza pliki PDF natywnie. Wyniki obejmują PageNumber, Format, Value i Confidence dla każdego znalezionego kodu kreskowego. Nie jest wymagany żaden zewnętrzny etap renderowania pliku PDF.
W jaki sposób IronBarcode obsługuje równoległe przetwarzanie kodów kreskowych?
Metody statyczne IronBarcode są bezstanowe i bezpieczne dla wątków. Użyj Parallel.ForEach bezpośrednio na listach plików bez zarządzania instancjami dla poszczególnych wątków. BarcodeReaderOptions.MaxParallelThreads kontroluje wewnętrzny limit wątków.
Jakie właściwości wyników ulegają zmianie podczas migracji z Cloudmersive BarCode API do IronBarcode?
Typowe zmiany nazw: BarcodeValue staje się Value, BarcodeType staje się Format. Wyniki IronBarcode zawierają również Confidence i PageNumber. Funkcja wyszukiwania i zamiany w całym rozwiązaniu obsługuje zmiany nazw w istniejącym kodzie przetwarzania wyników.
Jak skonfigurować licencjonowanie IronBarcode w potoku CI/CD?
Zapisz IronBarcode_LICENSE_KEY jako sekret potoku i przypisz IronBarCode.License.LicenseKey w kodzie uruchamiającym aplikację. Jeden sekret obejmuje wszystkie środowiska, w tym środowisko programistyczne, testowe, przejściowe i produkcyjne.
Czy IronBarcode obsługuje generowanie kodów QR z niestandardowym stylem?
Tak. Funkcja QRCodeWriter.CreateQrCode() obsługuje niestandardowe kolory za pomocą ChangeBarCodeColor(), osadzanie logo za pomocą AddBrandLogo(), konfigurowalne poziomy korekcji błędów oraz wiele formatów wyjściowych, w tym PNG, JPG, PDF i strumień.

