• NeonSDK
  • NeonKUBE
Search Results for

    Show / Hide Table of Contents
    • Neon
      • Build
    • Neon.Blazor
      • BlazorHelper
      • BodyOutlet
      • ClientRenderContext
      • DOMRectReadOnly
      • EventHandlers
      • FileDownloader
      • HtmlElement
      • IRenderContext
      • IntersectionChangedEventArgs
      • IntersectionObserver
      • IntersectionObserverContext
      • MobileDetector
      • NeonBlazorExtensions
      • ServerRenderContext
      • SwipeDirection
      • SwipeHandler
    • Neon.Blazor.Analyzers
      • SvgGenerator
      • SvgGenerator.Svg
    • Neon.BuildInfo
      • ThisAssembly
      • ThisAssembly.Git
      • ThisAssembly.Git.BaseVersion
      • ThisAssembly.Git.SemVer
    • Neon.CSharp
      • CSharpHelper
      • CompilerErrorException
      • MetadataReferences
    • Neon.Cassandra
      • KeyspaceStatus
      • RowSetExtensions
      • SchemaManager
      • SchemaManagerException
      • SchemaStatus
      • SessionExtensions
    • Neon.Collections
      • ArgDictionary
      • Bits
      • IObjectDictionary
      • NiceDictionary<TKey, TValue>
      • ObjectDictionary
    • Neon.Common
      • AppDomainExtensions
      • Block
      • BlockArray
      • ByteEncoding
      • ByteUnits
      • CommandLine
      • CommandLine.OptionDefinition
      • CommandLine.Redactor
      • CpuArchitecture
      • Credentials
      • DateTimeExtensions
      • EnumExtensions
      • EnvironmentParser
      • EnvironmentParser.Parser<T>
      • EnvironmentParser.Validator<T>
      • EnvironmentParser.VariableSource
      • ExceptionExtensions
      • ExecuteException
      • ExecuteResponse
      • GlobPattern
      • HexDumpOption
      • HttpClientExtensions
      • HttpResponseMessageExtensions
      • IEnumerableExtensions
      • ILabeled
      • IOExtensions
      • IServiceContainer
      • IStaticDirectoryExtensions
      • LabelSelector
      • LabelSelectorOptions
      • LabelSelector<TItem>
      • NeonAssemblyExtensions
      • NeonExtendedHelper
      • NeonHelper
      • NetFramework
      • NewtonsoftExtensions
      • NotReadyException
      • ProcessExtensions
      • ProgramEntrypoint
      • ProgramEntrypointAsync
      • ProgramExitException
      • ProgramRunner
      • RandomExtensions
      • ReflectionExtensions
      • SemanticVersion
      • ServiceContainer
      • StaticZipOptions
      • StringBuilderExtensions
      • StringExtensions
      • Stub
      • Stub.Value
      • TaskExtensions
      • TimeSpanExtensions
      • ToolException
      • TriState
      • WeakEventController
      • WindowsEdition
      • WindowsFeatureStatus
      • YamlDotNetExtensions
    • Neon.Cryptography
      • AesCipher
      • CryptoExtensions
      • CryptoHelper
      • NeonVault
      • Wildcard
    • Neon.Csv
      • CsvReader
      • CsvTableReader
      • CsvTableWriter
      • CsvWriter
    • Neon.Data
      • DateTimeJsonConverter
      • DateTimeOffsetJsonConverter
      • IEnhancedJsonConverter
      • IGeneratedServiceClient
      • IPersistableType
      • IPersistableType<T>
      • IRoundtripData
      • IntegerEnumConverter<TEnum>
      • NotifyPropertyChanged
      • RoundtripDataFactory
      • RoundtripDataHelper
      • TimeSpanJsonConverter
      • VersionJsonConverter
    • Neon.Deployment
      • AwsCli
      • DeploymentException
      • DeploymentHelper
      • DownloadManifest
      • DownloadPart
      • DownloadProgressDelegate
      • DownloadProgressType
      • GitHub
      • GitHubActionsApi
      • GitHubPackage
      • GitHubPackageApi
      • GitHubPackageType
      • GitHubPackageVersion
      • GitHubPackageVisibility
      • GitHubReleaseApi
      • GitHubRepoPath
      • GitHubTagApi
      • IProfileClient
      • IProfileRequest
      • IProfileResponse
      • MaintainerProfile
      • NotifyClient
      • OnePassword
      • OnePasswordException
      • ProfileException
      • ProfileHandlerResult
      • ProfileRequest
      • ProfileResponse
      • ProfileServer
      • ProfileStatus
      • XenServer
    • Neon.Deployment.CodeSigning
      • AzureProfile
      • CodeSigner
      • UsbTokenProfile
    • Neon.Diagnostics
      • AssertException
      • ConfigExtensions
      • ConsoleJsonLogExporter
      • ConsoleJsonLogExporterOptions
      • ConsoleTextLogExporter
      • ConsoleTextLogExporterOptions
      • ExceptionInfo
      • FileLogExporter
      • FileLogExporterFormat
      • FileLogExporterOptions
      • LogAsTraceProcessor
      • LogAsTraceProcessorOptions
      • LogAttributeNames
      • LogAttributes
      • LogEvent
      • LogEventInterceptor
      • LoggerExtensions
      • NullLogger
      • TelemetryHub
      • TelemetrySpanEventNames
      • TelemetrySpanExtensions
    • Neon.Docker
      • DockerClient
      • DockerNetwork
      • DockerNetworkContainer
      • DockerNetworkIpam
      • DockerNode
      • DockerNodeManagerStatus
      • DockerResponse
      • DockerSettings
      • DockerVolume
      • NetworkCreateResponse
      • ServiceBindOptions
      • ServiceConfig
      • ServiceContainerSpec
      • ServiceCredentialSpec
      • ServiceDetails
      • ServiceDiscreteResourceSpec
      • ServiceDnsConfig
      • ServiceEndpoint
      • ServiceEndpointMode
      • ServiceEndpointPortConfig
      • ServiceEndpointSpec
      • ServiceFile
      • ServiceGenericResources
      • ServiceGlobalSchedulingMode
      • ServiceHealthCheck
      • ServiceIsolationMode
      • ServiceListResponse
      • ServiceLogDriver
      • ServiceMode
      • ServiceMount
      • ServiceMountBindPropagation
      • ServiceMountConsistency
      • ServiceMountType
      • ServiceNamedResourceSpec
      • ServiceNetwork
      • ServicePlacement
      • ServicePlacementPreferences
      • ServicePlacementSpreadSettings
      • ServicePlatform
      • ServicePortMode
      • ServicePortProtocol
      • ServicePrivileges
      • ServiceReplicatedSchedulingMode
      • ServiceResourceSettings
      • ServiceResources
      • ServiceRestartCondition
      • ServiceRestartPolicy
      • ServiceRollbackConfig
      • ServiceRollbackFailureAction
      • ServiceRollbackOrder
      • ServiceSELinuxContext
      • ServiceSchedulingMode
      • ServiceSecret
      • ServiceSpec
      • ServiceTaskTemplate
      • ServiceTmpfsOptions
      • ServiceUpdateConfig
      • ServiceUpdateFailureAction
      • ServiceUpdateOrder
      • ServiceUpdateState
      • ServiceUpdateStatus
      • ServiceVersion
      • ServiceVirtualIP
      • ServiceVolumeDriverConfig
      • ServiceVolumeOptions
      • VolumeListResponse
    • Neon.GitHub
      • GitExtensions
      • GitHubCredentials
      • GitHubRepo
      • LocalRepoApi
      • NoLocalRepositoryException
      • RemoteRepoApi
      • RemoteRepoBranchApi
      • RemoteRepoIssueApi
      • RemoteRepoIssueCommentApi
      • RemoteRepoPath
      • RemoteRepoReleaseApi
      • RemoteRepoTagApi
    • Neon.HyperV
      • HyperVClient
      • HyperVDriverType
      • HyperVException
      • NetAdapter
      • VirtualDrive
      • VirtualIPAddress
      • VirtualMachine
      • VirtualMachineNetworkAdapter
      • VirtualMachineState
      • VirtualNat
      • VirtualSwitch
      • VirtualSwitchType
    • Neon.IO
      • BlockStream
      • FixedLengthStream
      • IStaticDirectory
      • IStaticFile
      • LineEnding
      • LinuxPath
      • LinuxPermissions
      • PreprocessReader
      • RelayStream
      • StaticDirectoryBase
      • StaticFileBase
      • SubStream
      • TempFile
      • TempFolder
    • Neon.JsonConverters
      • JsonDateTimeConverter
      • JsonGenericConverter<T>
      • JsonNullableDateTimeConverter
    • Neon.ModelGen
      • ActionResult<T>
      • ApiVersion
      • ApiVersionAttribute
      • BodyStreamAttribute
      • ControllerValidationAttribute
      • DataModelAttribute
      • EnumMember
      • FromBodyAttribute
      • FromHeaderAttribute
      • FromQueryAttribute
      • FromRouteAttribute
      • GeneratedClientAttribute
      • GeneratedMethodAttribute
      • GeneratedParamAttribute
      • HashSourceAttribute
      • HttpAttribute
      • HttpDeleteAttribute
      • HttpGetAttribute
      • HttpHeadAttribute
      • HttpOptionsAttribute
      • HttpPatchAttribute
      • HttpPostAttribute
      • HttpPutAttribute
      • IActionResult
      • ModelGenerator
      • ModelGeneratorOutput
      • ModelGeneratorSettings
      • NoCodeGenAttribute
      • NoControllerValidationAttribute
      • PassAs
      • PersistableAttribute
      • PersistableKeyAttribute
      • RouteAttribute
      • ServiceModelAttribute
      • TargetAttribute
      • UxFrameworks
    • Neon.Net
      • HttpApiException
      • HttpException
      • JsonClient
      • JsonClientPayload
      • JsonResponse
      • Jwt
      • LocalHostSection
      • NetConst
      • NetHelper
      • NetworkCidr
      • NetworkConfiguration
      • NetworkException
      • NetworkPorts
      • Pinger
      • ReachableHost
      • ReachableHostMode
      • StreamDocument
    • Neon.Postgres
      • ConnectionExtensions
      • DatabaseStatus
      • PreparedCommand
      • ReaderAsyncEnumerator
      • ReaderEnumerator
      • ReaderExtensions
      • SchemaManager
      • SchemaManagerException
      • SchemaStatus
    • Neon.Retry
      • ExponentialRetryPolicy
      • IRetryPolicy
      • LinearRetryPolicy
      • NoRetryPolicy
      • RetryPolicy
      • RetryPolicyBase
      • RetryTransientArgs
      • TransientDetector
      • TransientException
    • Neon.Roslyn
      • DisplayFormat
      • DocumentationComment
      • DocumentationItem
      • MetadataLoadContext
      • RoslynAssembly
      • RoslynConstructorInfo
      • RoslynCustomAttributeData
      • RoslynExtensions
      • RoslynFieldInfo
      • RoslynMethodInfo
      • RoslynParameterInfo
      • RoslynPropertyInfo
      • RoslynType
      • SharedUtilities
    • Neon.Roslyn.Xunit
      • AdditionalSourceText
      • CompilationOptions
      • CompilationOptionsProvider
      • TestCompilation
      • TestCompilationAssertions
      • TestCompilationBuilder
      • TestCompilationBuilderExtensions
      • TestCompilationExtensions
    • Neon.SSH
      • CommandBundle
      • CommandFile
      • CommandResponse
      • HostFolders
      • IBashCommandFormatter
      • ILinuxSshProxy
      • LinuxDiskInfo
      • LinuxDiskPartition
      • LinuxSshProxy
      • LinuxSshProxy<TMetadata>
      • NamespaceDoc
      • RemoteCommandException
      • RunOptions
      • SshCredentials
      • SshExtensions
      • SshProxyException
    • Neon.Service
      • LogMetricsProcessor
      • MetricsMode
      • MetricsOptions
      • NeonService
      • NeonServiceOptions
      • NeonServiceStatus
      • OtelConfigExtensions
      • OtlpCollectorChecker
      • ProcessTerminator
      • ServiceApiContact
      • ServiceApiInfo
      • ServiceApiLicense
      • ServiceDependencies
      • ServiceDescription
      • ServiceEndpoint
      • ServiceEndpointProtocol
      • ServiceEndpoints
      • ServiceMap
    • Neon.SignalR
      • DependencyInjectionExtensions
      • DnsCache
      • GroupAction
      • GroupCommand
      • IDnsCache
      • Invocation
      • NatsHubLifetimeManager<THub>
      • ProxyConfig
      • ServiceCollectionExtensions
      • ServiceDiscovey
      • SignalrProxyMiddleware
      • SignalrProxyMiddlewareExtensions
      • TracerProviderBuilderExtensions
    • Neon.Tailwind
      • ClickOffEventHandler
      • ComponentEventArgs<TSender>
      • ComponentEventArgs<TSender, TEventArgs>
      • DisclosureState
      • EventHandlerComponentBase<TComponent>
      • HeadlessButton
      • HeadlessDialog
      • HeadlessDialogPanel
      • HeadlessDisclosure
      • HeadlessDisclosureButton
      • HeadlessDisclosurePanel
      • HeadlessListboxButton<TValue>
      • HeadlessListboxLabel<TValue>
      • HeadlessListboxOption<TValue>
      • HeadlessListboxOptions<TValue>
      • HeadlessListbox<TValue>
      • HeadlessMenu
      • HeadlessMenuButton
      • HeadlessMenuItem
      • HeadlessMenuItems
      • HeadlessSwitch
      • HeadlessSwitchGroup
      • HeadlessSwitchLabel
      • IPortalBinder
      • KeyDownEventHandler
      • KeyboardKey
      • ListboxFocus
      • ListboxState
      • MenuFocus
      • MenuState
      • Portal
      • PortalBinder
      • PortalContent
      • SearchAssistant
      • TailwindExtensions
      • Transition
      • TransitionGroup
      • TransitionState
    • Neon.Tasks
      • Async
      • AsyncAutoResetEvent
      • AsyncManualResetEvent
      • AsyncMutex
      • AsyncPeriodicTask
      • AsyncReaderWriterLock
      • AsyncReentrantMutex
      • AsyncTimer
      • IAsyncFuture
      • IAsyncFuture<T>
      • NonDisposableTask
      • NonDisposableTask<T>
      • SyncContext
      • SyncContextMode
    • Neon.Temporal
      • ActivityHelper
      • ActivityLogEnricher
      • TemporalEnricherTagNames
      • WorkflowLogEnricher
    • Neon.Time
      • GatedTimer
      • GoDuration
      • PolledTimer
      • RecurringTimer
      • RecurringTimerType
      • SysTime
      • TimeOfDay
    • Neon.WSL
      • Wsl2Proxy
    • Neon.Web
      • AesProtector
      • DataProtectionExtensions
      • NeonController
      • NeonControllerBase
      • RoundTripJsonInputFormatter
      • RoundTripJsonOutputFormatter
      • TracerProviderBuilderExtensions
      • WebHelper
    • Neon.WinTTY
      • ConsoleTTY
    • Neon.Windows
      • MEMORYSTATUSEX
      • PowerShellException
      • Win32
    • Neon.XenServer
      • IXenClient
      • XenClient
      • XenClient.MachineOperations
      • XenClient.StorageOperations
      • XenClient.TemplateOperations
      • XenException
      • XenHostInfo
      • XenObject
      • XenResponse
      • XenStorageRepository
      • XenTempIso
      • XenTemplate
      • XenVirtualDisk
      • XenVirtualMachine
      • XenVmPowerState
    • Neon.Xunit
      • AnsiblePlayResults
      • AnsiblePlayer
      • AnsibleTaskResult
      • AspNetFixture
      • BasicFixture
      • CodeFixture
      • CollectionComparer<T>
      • ComposedFixture
      • ContainerFixture
      • ContainerLimits
      • DockerComposeFixture
      • DockerFixture
      • DockerFixture.ConfigInfo
      • DockerFixture.ContainerInfo
      • DockerFixture.NetworkInfo
      • DockerFixture.SecretInfo
      • DockerFixture.ServiceInfo
      • DockerFixture.StackDefinition
      • DockerFixture.StackInfo
      • DockerFixture.StackService
      • EnvironmentFixture
      • HostsFixture
      • ITestFixture
      • IncompatibleServiceException
      • MaintainerFactAttribute
      • MaintainerTheoryAttribute
      • MockHttpServer
      • MockHttpServerExtensions
      • NatsFixture
      • NatsStreamingFixture
      • NeonServiceFixture<TService>
      • PlatformFactAttribute
      • RepeatAttribute
      • TargetPlatforms
      • TestArea
      • TestCollection
      • TestContext
      • TestFixture
      • TestFixtureStatus
      • TestHelper
      • TestHttpClient
      • TestOutputWriter
      • TestTrait
      • XunitExtensions
    • Neon.Xunit.YugaByte
      • YugaByteFixture
    • Neon.YugaByte
      • YugaByteHelper

    Class PreparedCommand

    Simplifies prepared Postgres command usage by combining the prepared command and its usage into a single type. It's also often useful to create derived custom types from this that handle the parameter definitions and subsitutions and perhaps precompute result column indexes to help abstract these details from the calling program.

    Inheritance
    object
    PreparedCommand
    Namespace: Neon.Postgres
    Assembly: Neon.Postgres.dll
    Syntax
    public class PreparedCommand
    Remarks

    You can use this class directly in your code like:

    var parameters = new Dictionary<string, NpgsqlDbType>()> 
        {
            { "name", NpgsqlDbType.Text }
        };
    

    var preparedCommand = new PreparedCommand(connection, "SELECT Name, Age, Email FROM People WHERE Name = @name", parameters);

    foreach (var name in new string[] { "jack", "jill", "john", "jane" }) { var queryCommand = preparedCommand.Clone();

    queryCommand.Parameters["name"].Value = name;
    
    foreach (var row in queryCommand.ExecuteReader().ToEnumerable())
    {
        Console.WriteLine($"Name: {row.GetString("Name")} Age: {row.GetInt32("Age"} Email: {row.GetString("Email")}");
    }
    

    }

    In this example, we first created the prepared command that performs a query passing a person's name as the parameter. Note that we had to create a dictionary defining the parameter name and type. The below, we looped for perform four queries by cloning the prepared command, setting the parameter values and then executing the command.

    Note how we used methods like row.GetString("Name") to access individual columns. This works and is convenient but will be somewhat inefficient because the method will need to map the column name into the corresponding column index. We could have specified column indexes here, but that's starting to be fragile and could break if we inserted or removed result columns. Even using names can be fragile since column names can be altered over time.

    We recommend writing custom classes that inherit from PreparedCommand to help abstract these things efficiently and without needing to use ORM frameworks like Entity Framework, NHibernate, and Dapper which tend to be inefficient and somewhat cumbersome to setup. Here's an example of a class that wraps a prepared statement to implement the query from the example above:

    public class QueryPeopleByName : PreparedCommand
    {
        private const string query = "SELECT Name, Age, Email FROM People WHERE Name = @name";
    
    public const int NameIndex  = 0;
    public const int AgeIndex   = 1;
    public const int EmailIndex = 2;
    
    private static readonly Dictionary<string, NpgsqlDbType> paramDefinitions =
        new Dictionary<string, NpgsqlDbType>()
        {
            { "name", NpgsqlDbType.Text }
        };
    
    public QueryPeopleByName(NpgsqlConnection connection)
        : base(connection, query, paramDefinitions)
    {
        var queryCommand = queryPeopleByName.Clone();
    
        queryCommand.Parameters["name"] = name;
    
        return qiery
    }
    
    public ReaderEnumerator GetPeople(string name)
    {
        var queryCommand = queryPeopleByName.Clone();
    
        queryCommand.Parameters["name"].Value = name;
    
        return queryCommand.ExecuteReader().ToEnumerable()
    }
    

    }

    ...

    var queryPeopleByName = new QueryPeopleByName(connection);

    foreach (var name in new string[] { "jack", "jill", "john", "jane" }) { foreach (var row in queryCommand.ExecuteReader().ToEnumerable()) { Console.WriteLine($"Name: {row.GetString(QueryPeopleByName.NameIndex)} Age: {row.GetInt32(QueryPeopleByName.AgeIndex} Email: {row.GetString(QueryPeopleByName.EmailIndex)}"); } }

    The example above abstracted the query SQL, the parameter subsitution, as well as the result column indexes to make this a little less fragile and easier to modify when necessary. You can extend this coding pattern by having your class handle conversion of the query result to nice .NET model objects:

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Email { get; set; }
    }
    

    public class QueryPeopleByName : PreparedCommand { private const string query = "SELECT Name, Age, Email FROM People WHERE Name = @name";

    private const int NameIndex  = 0;
    private const int AgeIndex   = 1;
    private const int EmailIndex = 2;
    
    private static readonly Dictionary<string, NpgsqlDbType> paramDefinitions =
        new Dictionary<string, NpgsqlDbType>()
        {
            { "name", NpgsqlDbType.Text }
        };
    
    public QueryPeopleByName(NpgsqlConnection connection)
        : base(connection, query, paramDefinitions)
    {
        var queryCommand = queryPeopleByName.Clone();
    
        queryCommand.Parameters["name"] = name;
    
        return qiery
    }
    
    public IEnumerable<Person> GetPeople(string name)
    {
        var queryCommand = queryPeopleByName.Clone();
    
        queryCommand.Parameters["name"] = name;
    
        foreach (var row in queryCommand.ExecuteReader().ToEnumerable())
        {
            yield return new Person()
            {
                Name  = row.GetString(NameIndex),
                Age   = row.GetInt32(RowIndex),
                Email = row.GetString(EmailIndex);
            };
        }
    }
    

    }

    ...

    var queryPeopleByName = new QueryPeopleByName(connection);

    foreach (var name in new string[] { "jack", "jill", "john", "jane" }) { foreach (var person in queryCommand.GetProple(name)) { Console.WriteLine($"Name: {person.Name} Age: {person.Age} Email: {person.Email}"); } }

    This final example abstracted the parameter name and type as well as converted the query result to compile-time Person object instances. These patterns can provide a nice way to get some of the advantages of an ORM without extra runtime overhead.

    Constructors

    PreparedCommand(NpgsqlConnection, string, Dictionary<string, NpgsqlDbType>, bool)

    Constructor.

    Declaration
    public PreparedCommand(NpgsqlConnection connection, string sqlText, Dictionary<string, NpgsqlDbType> paramDefinitions = null, bool prepareNow = false)
    Parameters
    Type Name Description
    NpgsqlConnection connection

    The open Postgres connection.

    string sqlText

    The command SQL.

    Dictionary<string, NpgsqlDbType> paramDefinitions

    Optional parameter name and type definitions.

    note

    Not all possible parameter types are supported by the common ones are at this time.

    bool prepareNow

    Optionally specifies that the command is to be prepared immediately rather than waiting for it's first execution (the default).

    Properties

    CommandText

    Returns the command text.

    Declaration
    public string CommandText { get; }
    Property Value
    Type Description
    string

    CommandTimeout

    The command timeout in seconds. This defaults to 30 seconds.

    Declaration
    public int CommandTimeout { get; set; }
    Property Value
    Type Description
    int

    Parameters

    Returns the command parameters.

    note

    The collection returned should be considered tob read-only and must not be modified.

    Declaration
    public NpgsqlParameterCollection Parameters { get; }
    Property Value
    Type Description
    NpgsqlParameterCollection

    Methods

    Clone(NpgsqlTransaction)

    Prepares the underlying command if it hasn't already been prepared and then creates a clone of the command that can be executed after parameter values are set when necessary.

    Declaration
    public NpgsqlCommand Clone(NpgsqlTransaction transaction = null)
    Parameters
    Type Name Description
    NpgsqlTransaction transaction

    Optional transaction.

    Returns
    Type Description
    NpgsqlCommand
    In this article
    Back to top © Copyright 2005-2023 by NEONFORGE LLC