/// <summary> /// Creates a <see cref="LogTarget"/> instance for sending log entries to an <see cref="LogTargetKind.Organization"/>. /// </summary> public static LogTarget ForOrganization(string organizationId) { GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)); return(new LogTarget(LogTargetKind.Organization, null, organizationId)); }
private ImageAnnotatorSettings(ImageAnnotatorSettings existing) : base(existing) { GaxPreconditions.CheckNotNull(existing, nameof(existing)); BatchAnnotateImagesSettings = existing.BatchAnnotateImagesSettings?.Clone(); }
/// <summary> /// Gets the default expiration period for tables created in this dataset. /// Tables will (by default) be automatically deleted this long after they are created, /// unless otherwise specified, such as by <see cref="Table.ExpirationTime"/>. /// </summary> /// <param name="dataset">The dataset for which to set the expiration for. /// Must not be null.</param> public static TimeSpan?GetDefaultTableExpiration(this Dataset dataset) => GaxPreconditions.CheckNotNull(dataset, nameof(dataset)).DefaultTableExpirationMs.HasValue ? TimeSpan.FromMilliseconds(dataset.DefaultTableExpirationMs.Value) : (TimeSpan?)null;
private ApiMetadata(string name) { GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)); Name = name; _typeRegistryProvider = new Lazy <TypeRegistry>(() => TypeRegistry.FromFiles(ProtobufDescriptors)); }
/// <summary> /// Constructs a new instance of the <see cref="ProjectName"/> resource name class /// from its component parts. /// </summary> /// <param name="projectId">The project ID. Must not be <c>null</c>.</param> public ProjectName(string projectId) { ProjectId = GaxPreconditions.CheckNotNull(projectId, nameof(projectId)); }
/// <summary> /// Constructs a new instance from the given sequence of responses. This constructor /// is only present to facilitate testing; application code will normally obtain instances /// of this class by calling <see cref="DatastoreDb.RunQueryLazily(Query, ReadOptions.Types.ReadConsistency?, CallSettings)"/>. /// </summary> /// <remarks> /// The sequence of responses will be returned directly from <see cref="AsResponses"/>, and /// used to lazily construct the other sequences returned by this class. It should not /// contain any null references. /// </remarks> /// <param name="responses">The responses to return.</param> public LazyDatastoreQuery(IEnumerable <RunQueryResponse> responses) { _responses = GaxPreconditions.CheckNotNull(responses, nameof(responses)); }
/// <param name="client">The logging client that will push logs to the Stackdriver Logging API.</param> public GrpcLogConsumer(LoggingServiceV2Client client) { _client = GaxPreconditions.CheckNotNull(client, nameof(client)); }
private TimestampBound(TimestampBoundMode mode, DateTime timestamp) { GaxPreconditions.CheckArgument(timestamp.Kind == DateTimeKind.Utc, nameof(timestamp), "Timestamps must be expressed in UTC"); Mode = mode; Timestamp = timestamp; }
internal ReliableStreamReader(IAsyncEnumerator <PartialResultSet> resultStream, Logger logger) { _resultStream = GaxPreconditions.CheckNotNull(resultStream, nameof(resultStream)); _logger = GaxPreconditions.CheckNotNull(logger, nameof(logger)); }
/// <summary> /// Creates an instance from a Protobuf <see cref="LatLng"/> representation. /// Later modifications to the Protobuf representation will not affect the returned object. /// </summary> /// <param name="proto">A Protobuf location representation.</param> /// <returns>A new <see cref="GeoPoint"/> value.</returns> public static GeoPoint FromProto(LatLng proto) { GaxPreconditions.CheckNotNull(proto, nameof(proto)); return(new GeoPoint(proto.Latitude, proto.Longitude)); }
/// <summary> /// Creates a SpannerConnection with a datasource contained in connectionString. /// </summary> /// <param name="connectionStringBuilder"> /// A SpannerConnectionStringBuilder containing a formatted connection string. Must not be null. /// </param> public SpannerConnection(SpannerConnectionStringBuilder connectionStringBuilder) { GaxPreconditions.CheckNotNull(connectionStringBuilder, nameof(connectionStringBuilder)); TrySetNewConnectionInfo(connectionStringBuilder); }
/// <summary> /// Creates a new value using the provided latitude and longitude values. /// </summary> /// <param name="latitude">The latitude of the point in degrees, between -90 and 90 inclusive.</param> /// <param name="longitude">The longitude of the point in degrees, between -180 and 180 inclusive.</param> public GeoPoint(double latitude, double longitude) { _latitude = GaxPreconditions.CheckArgumentRange(latitude, nameof(latitude), -90d, 90d); _longitude = GaxPreconditions.CheckArgumentRange(longitude, nameof(longitude), -180d, 180d); }
internal SigningState(RequestTemplate template, Options options, IBlobSigner blobSigner, IClock clock) { GaxPreconditions.CheckArgument( template.QueryParameters.Count == 0, nameof(template.QueryParameters), $"When using {nameof(SigningVersion.V2)} custom query parematers are not included as part of the signature so none should be specified."); (_host, _urlResourcePath) = options.UrlStyle switch { UrlStyle.PathStyle => (StorageHost, $"/{template.Bucket}"), UrlStyle.VirtualHostedStyle => ($"{template.Bucket}.{StorageHost}", string.Empty), _ => throw new ArgumentOutOfRangeException( nameof(options.UrlStyle), $"When using {nameof(SigningVersion.V2)} only {nameof(UrlStyle.PathStyle)} or {nameof(UrlStyle.VirtualHostedStyle)} can be specified.") }; _scheme = options.Scheme; options = options.ToExpiration(clock); string expiryUnixSeconds = ((int)(options.Expiration.Value - UnixEpoch).TotalSeconds).ToString(CultureInfo.InvariantCulture); string signingResourcePath = $"/{template.Bucket}"; if (template.ObjectName != null) { string escaped = Uri.EscapeDataString(template.ObjectName); _urlResourcePath += $"/{escaped}"; signingResourcePath += $"/{escaped}"; } var extensionHeaders = GetExtensionHeaders(template.RequestHeaders, template.ContentHeaders); var effectiveHttpMethod = template.HttpMethod; if (effectiveHttpMethod == ResumableHttpMethod) { extensionHeaders["x-goog-resumable"] = new StringBuilder("start"); effectiveHttpMethod = HttpMethod.Post; } var contentMD5 = GetFirstHeaderValue(template.ContentHeaders, "Content-MD5"); var contentType = GetFirstHeaderValue(template.ContentHeaders, "Content-Type"); var signatureLines = new List <string> { effectiveHttpMethod.ToString(), contentMD5, contentType, expiryUnixSeconds }; signatureLines.AddRange(extensionHeaders.Select( header => $"{header.Key}:{string.Join(", ", header.Value)}")); signatureLines.Add(signingResourcePath); _blobToSign = Encoding.UTF8.GetBytes(string.Join("\n", signatureLines)); _queryParameters = new List <string> { $"GoogleAccessId={blobSigner.Id}" }; if (expiryUnixSeconds != null) { _queryParameters.Add($"Expires={expiryUnixSeconds}"); } }
private void AddMutations <T>(IEnumerable <T> values, Func <T, Mutation> conversion, string paramName) { GaxPreconditions.CheckNotNull(values, paramName); _mutations.AddRange(values.Select(conversion)); }
/// <summary> /// Adds an additional descending ordering by the specified path. /// </summary> /// <remarks> /// <para> /// Unlike LINQ's OrderBy method, this call adds additional subordinate orderings to any /// additionally specified. So <c>query.OrderBy("foo").OrderByDescending("bar")</c> is similar /// to a LINQ <c>query.OrderBy(x => x.Foo).ThenByDescending(x => x.Bar)</c>. /// </para> /// <para> /// This method cannot be called after a start/end cursor has been specified with /// <see cref="StartAt"/>, <see cref="StartAfter(object[])"/>, <see cref="EndAt(object[])"/> or <see cref="EndBefore(object[])"/>. /// </para> /// </remarks> /// <param name="fieldPath">The field path to order by. Must not be null.</param> /// <returns>A new query based on the current one, but with the additional specified ordering applied.</returns> public Query OrderByDescending(FieldPath fieldPath) => OrderBy(GaxPreconditions.CheckNotNull(fieldPath, nameof(fieldPath)), Direction.Descending);
/// <summary> /// Creates a new instance of this type with the specified emulator detection value. /// </summary> /// <param name="emulatorDetection">Determines how and whether to detect the emulator.</param> /// <returns>The new instance</returns> public ClientCreationSettings WithEmulatorDetection(EmulatorDetection emulatorDetection) { GaxPreconditions.CheckEnumValue(emulatorDetection, nameof(emulatorDetection)); return(new ClientCreationSettings(ClientCount, PublisherServiceApiSettings, Credentials, ServiceEndpoint, emulatorDetection)); }
private Query OrderBy(string fieldPath, Direction direction) { GaxPreconditions.CheckNotNullOrEmpty(fieldPath, nameof(fieldPath)); return(OrderBy(FieldPath.FromDotSeparatedString(fieldPath), direction)); }
internal void Validate() { // Fairly arbitrary upper limit. GaxPreconditions.CheckArgumentRange(ClientCount ?? 1, nameof(ClientCount), 1, 256); }
internal Span(SimpleManagedTracer tracer, TraceSpan traceSpan) { _tracer = GaxPreconditions.CheckNotNull(tracer, nameof(tracer)); TraceSpan = GaxPreconditions.CheckNotNull(traceSpan, nameof(traceSpan)); }
/// <summary> /// Constructs a <see cref="RecognitionAudio"/> by loading data from the given file path. /// </summary> /// <param name="path">The file path to load RecognitionAudio data from. Must not be null.</param> /// <returns>The newly created RecognitionAudio.</returns> public static RecognitionAudio FromFile(string path) { GaxPreconditions.CheckNotNull(path, nameof(path)); return(FromBytes(File.ReadAllBytes(path))); }
public EphemeralTransaction(SpannerConnection connection, Logger logger) { GaxPreconditions.CheckNotNull(connection, nameof(connection)); _connection = connection; Logger = logger ?? Logger.DefaultLogger; }
/// <summary> /// Constructs a <see cref="RecognitionAudio"/> by downloading data from the given URI. /// </summary> /// <param name="uri">The URI to fetch. Must not be null.</param> /// <param name="httpClient">The <see cref="HttpClient"/> to use to fetch the image, or /// <c>null</c> to use a default client.</param> /// <returns>The newly created RecognitionAudio.</returns> public static RecognitionAudio FetchFromUri(Uri uri, HttpClient httpClient = null) { GaxPreconditions.CheckNotNull(uri, nameof(uri)); return(Task.Run(() => FetchFromUriAsync(uri, httpClient)).ResultWithUnwrappedExceptions()); }
/// <summary> /// Constructs a new instance of the <see cref="InstanceName"/> resource name class /// from its component parts. /// </summary> /// <param name="projectId">The project ID. Must not be <c>null</c>.</param> /// <param name="instanceId">The instance ID. Must not be <c>null</c>.</param> public InstanceName(string projectId, string instanceId) { ProjectId = GaxPreconditions.CheckNotNull(projectId, nameof(projectId)); InstanceId = GaxPreconditions.CheckNotNull(instanceId, nameof(instanceId)); }
/// <summary> /// Initializes the <see cref="HttpLogEntryLabelProvider"/> base class. /// </summary> /// <param name="httpContextAccessor">The <see cref="IHttpContextAccessor"/> instance with the <see cref="HttpContext"/>.</param> protected HttpLogEntryLabelProvider(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = GaxPreconditions.CheckNotNull(httpContextAccessor, nameof(httpContextAccessor)); }
/// <summary> /// Creates a <see cref="ImageAnnotatorClient"/> which uses the specified channel for remote operations. /// </summary> /// <param name="channel">The <see cref="Channel"/> for remote operations. Must not be null.</param> /// <param name="settings">Optional <see cref="ImageAnnotatorSettings"/>.</param> /// <returns>The created <see cref="ImageAnnotatorClient"/>.</returns> public static ImageAnnotatorClient Create(Channel channel, ImageAnnotatorSettings settings = null) { GaxPreconditions.CheckNotNull(channel, nameof(channel)); ImageAnnotator.ImageAnnotatorClient grpcClient = new ImageAnnotator.ImageAnnotatorClient(channel); return(new ImageAnnotatorClientImpl(grpcClient, settings)); }
/// <inheritdoc/> public override void ActivateOptions() { base.ActivateOptions(); // Initialise services if not already initialised for testing _client = _client ?? LoggingServiceV2Client.Create(); _scheduler = _scheduler ?? SystemScheduler.Instance; _clock = _clock ?? SystemClock.Instance; // Validate configuration GaxPreconditions.CheckState(!string.IsNullOrEmpty(ResourceType), $"{nameof(ResourceType)} must be set."); GaxPreconditions.CheckState(!string.IsNullOrEmpty(ProjectId), $"{nameof(ProjectId)} must be set."); GaxPreconditions.CheckState(!string.IsNullOrEmpty(LogId), $"{nameof(LogId)} must be set."); GaxPreconditions.CheckState(MaxUploadBatchSize > 0, $"{nameof(MaxUploadBatchSize)} must be > 0"); GaxPreconditions.CheckEnumValue <LocalQueueType>(LocalQueueType, nameof(LocalQueueType)); switch (LocalQueueType) { case LocalQueueType.Memory: GaxPreconditions.CheckState(MaxMemoryCount > 0 || MaxMemorySize > 0, $"Either {nameof(MaxMemoryCount)} or {nameof(MaxFileSize)} must be configured to be > 0"); break; case LocalQueueType.Disk: GaxPreconditions.CheckState(!string.IsNullOrEmpty(File), $"{nameof(File)} must be set."); GaxPreconditions.CheckState(MaxFileSize > 0, $"{nameof(MaxFileSize)} must be > 0"); GaxPreconditions.CheckState(MaxSizeRollBackups > 0, $"{nameof(MaxSizeRollBackups)} must be > 0"); break; default: throw new InvalidOperationException("Inconceivable!"); } GaxPreconditions.CheckState(ServerErrorBackoffDelaySeconds >= 1, $"{nameof(ServerErrorBackoffDelaySeconds)} must be >= 1 second."); GaxPreconditions.CheckState(ServerErrorBackoffMultiplier > 1.1999999, $"{nameof(ServerErrorBackoffMultiplier)} must be >= 1.2"); GaxPreconditions.CheckState(ServerErrorBackoffMaxDelaySeconds >= 20, $"{nameof(ServerErrorBackoffMaxDelaySeconds)} must be >= 20 seconds."); // Configure the logger from the given configuration _logName = new LogName(ProjectId, LogId).ToString(); _resource = new MonitoredResource { Type = ResourceType }; switch (LocalQueueType) { case LocalQueueType.Memory: _logQ = new MemoryLogQueue(MaxMemorySize, MaxMemoryCount); break; case LocalQueueType.Disk: throw new NotImplementedException("File-base local queues not implemented."); default: throw new InvalidOperationException("Inconceivable!"); } _initIdTask = Task.Run(_logQ.GetPreviousExecutionIdAsync); var labels = new Dictionary <string, string>(); foreach (var customLabel in _customLabels) { labels.Add(customLabel.Key, customLabel.Value); } var logsLostWarningEntry = new LogEntry { TextPayload = s_logsLostWarningMessage, Severity = LogSeverity.Warning, LogName = _logName, Resource = _resource, Labels = { labels }, }; var serverErrorBackoffSettings = new BackoffSettings( delay: TimeSpan.FromSeconds(ServerErrorBackoffDelaySeconds), delayMultiplier: ServerErrorBackoffMultiplier, maxDelay: TimeSpan.FromSeconds(ServerErrorBackoffMaxDelaySeconds) ); _logUploader = new LogUploader( _client, _scheduler, _clock, _logQ, logsLostWarningEntry, MaxUploadBatchSize, serverErrorBackoffSettings); }
/// <summary> /// <see cref="ILoggerProvider"/> for Stackdriver Logging. /// </summary> /// <param name="consumer">The consumer to push logs to. Cannot be null.</param> /// <param name="projectId">The Google Cloud Platform project ID. Cannot be null.</param> /// <param name="logLevel">The minimum log level.</param> internal GoogleLoggerProvider(IConsumer <LogEntry> consumer, string projectId, LogLevel logLevel) { _consumer = GaxPreconditions.CheckNotNull(consumer, nameof(consumer)); _projectId = GaxPreconditions.CheckNotNull(projectId, nameof(projectId)); _logLevel = GaxPreconditions.CheckEnumValue(logLevel, nameof(logLevel)); }
// TODO: Choices... // - Use an enum instead of strings? // - Rename the "op" parameter? (operator is a keyword, but we could make it @operator maybe) // - Rename "Where" to "AddFilter"? // - Reimplement as individual methods, two per filter operator (accepting string or FieldPath), // e.g. WhereEqual, WhereLess than etc /// <summary> /// Add a filter for the given field path. /// </summary> /// <remarks> /// This call adds additional filters to any previously-specified ones. /// </remarks> /// <param name="fieldPath">The dot-separated field path to filter on. Must not be null or empty.</param> /// <param name="op">The filter operator. Must not be null.</param> /// <param name="value">The value to compare in the filter.</param> /// <returns>A new query based on the current one, but with the additional specified filter applied.</returns> public Query Where(string fieldPath, QueryOperator op, object value) { GaxPreconditions.CheckNotNullOrEmpty(fieldPath, nameof(fieldPath)); return(Where(FieldPath.FromDotSeparatedString(fieldPath), op, value)); }
/// <summary> /// Sets the default expiration period for tables created in this dataset. /// Tables will (by default) be automatically deleted this long after they are created, /// unless otherwise specified, such as by <see cref="Table.ExpirationTime"/>. /// </summary> /// <param name="dataset">The dataset for which to set the expiration for. /// Must not be null.</param> /// <param name="expiration">The new expiration to be set.</param> /// <returns>The same dataset on which the change was made. To facilitate method chaining.</returns> public static Dataset SetDefaultTableExpiration(this Dataset dataset, TimeSpan?expiration) { GaxPreconditions.CheckNotNull(dataset, nameof(dataset)); dataset.DefaultTableExpirationMs = (long?)expiration?.TotalMilliseconds; return(dataset); }
/// <summary> /// Creates a <see cref="LogTarget"/> instance for sending log entries to a <see cref="LogTargetKind.Project"/>. /// </summary> public static LogTarget ForProject(string projectId) { GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)); return(new LogTarget(LogTargetKind.Project, projectId, null)); }