### Install SODA.NET NuGet Package Source: https://github.com/cityofsantamonica/soda.net/blob/master/README.md Use the .NET CLI to add the SODA.NET NuGet package to your project. ```console dotnet add package CSM.SodaDotNet ``` -------------------------------- ### Handle Location Data with LocationColumn and HumanAddress Source: https://context7.com/cityofsantamonica/soda.net/llms.txt Utilize LocationColumn and HumanAddress models for geographic data, including coordinates and structured addresses. This example demonstrates reading and creating location data. ```csharp using SODA; using SODA.Models; public class Facility { public string facility_id { get; set; } public string name { get; set; } public LocationColumn location { get; set; } } var client = new SodaClient("data.smgov.net", "YOUR_APP_TOKEN"); var facilities = client.GetResource("abcd-1234"); foreach (var facility in facilities.GetRows(10)) { Console.WriteLine($"Facility: {facility.name}"); if (facility.location != null) { Console.WriteLine($" Latitude: {facility.location.Latitude}"); Console.WriteLine($" Longitude: {facility.location.Longitude}"); if (facility.location.HumanAddress != null) { var addr = facility.location.HumanAddress; Console.WriteLine($" Address: {addr.Address}"); Console.WriteLine($" City: {addr.City}, {addr.State} {addr.Zip}"); } } } // Creating location data for upsert var newFacility = new Facility { facility_id = "FAC-001", name = "Community Center", location = new LocationColumn { Latitude = "34.0195", Longitude = "-118.4912", HumanAddress = new HumanAddress { Address = "1685 Main Street", City = "Santa Monica", State = "CA", Zip = "90401" } } }; ``` -------------------------------- ### GET /catalog Source: https://context7.com/cityofsantamonica/soda.net/llms.txt Retrieves a paginated list of dataset metadata from a Socrata portal's catalog. ```APIDOC ## GET /catalog ### Description Retrieves a paginated list of dataset metadata to discover available datasets on a portal. ### Method GET ### Endpoint /catalog ### Parameters #### Query Parameters - **page** (int) - Required - The page number to retrieve from the catalog. ### Response #### Success Response (200) - **datasets** (IEnumerable) - A collection of metadata objects for datasets found on the requested page. ``` -------------------------------- ### Get Dataset Resource with Dictionary Source: https://github.com/cityofsantamonica/soda.net/blob/master/README.md Get a reference to a dataset resource, specifying Dictionary as the type for the underlying rows. ```csharp //get a reference to the resource itself //the result (a Resouce object) is a generic type //the type parameter represents the underlying rows of the resource var dataset = client.GetResource>("1234-wxyz"); ``` -------------------------------- ### Get Dataset Resource with Custom Class Source: https://github.com/cityofsantamonica/soda.net/blob/master/README.md Get a reference to a dataset resource, using a custom JSON serializable class for the underlying rows. ```csharp //of course, a custom type can be used as long as it is JSON serializable var dataset = client.GetResource("1234-wxyz"); ``` -------------------------------- ### GET /metadata/{fourByFour} Source: https://context7.com/cityofsantamonica/soda.net/llms.txt Fetches detailed metadata about a specific dataset using its unique 4x4 identifier. ```APIDOC ## GET /metadata/{fourByFour} ### Description Retrieves detailed metadata for a specific dataset, including schema, column definitions, and statistics. ### Method GET ### Endpoint /metadata/{fourByFour} ### Parameters #### Path Parameters - **fourByFour** (string) - Required - The Socrata 4x4 identifier of the dataset. ### Response #### Success Response (200) - **metadata** (ResourceMetadata) - Object containing dataset name, description, category, view counts, and column schema information. ``` -------------------------------- ### Handle Operation Results with SodaResult Source: https://context7.com/cityofsantamonica/soda.net/llms.txt Use the SodaResult class to inspect the outcome of write operations, including error details and row counts. This example shows how to check for errors and process success messages. ```csharp using SODA; var client = new SodaClient( "data.example.com", "YOUR_APP_TOKEN", "user@domain.com", "password" ); SodaResult result = client.Upsert(data, "1234-wxyz"); // Check for errors if (result.IsError) { Console.WriteLine($"Operation failed!"); Console.WriteLine($"Error Code: {result.ErrorCode}"); Console.WriteLine($"Message: {result.Message}"); Console.WriteLine($"Data: {result.Data}"); } else { // Success - examine results Console.WriteLine($"Operation successful!"); Console.WriteLine($"Rows Created: {result.RowsCreated}"); Console.WriteLine($"Rows Updated: {result.RowsUpdated}"); Console.WriteLine($"Rows Deleted: {result.RowsDeleted}"); Console.WriteLine($"By Row Identifier: {result.ByRowIdentifier}"); Console.WriteLine($"By SID: {result.BySID}"); Console.WriteLine($"Errors: {result.Errors}"); Console.WriteLine($"Message: {result.Message}"); } ``` -------------------------------- ### Initialize SodaClient Source: https://context7.com/cityofsantamonica/soda.net/llms.txt Create a client instance for interacting with a Socrata portal. Authentication is required for write operations and private data access. ```csharp using SODA; // Anonymous client for read-only access to public data var readOnlyClient = new SodaClient("data.smgov.net", "YOUR_APP_TOKEN"); // Authenticated client for write operations and private data access var authenticatedClient = new SodaClient( host: "data.smgov.net", appToken: "YOUR_APP_TOKEN", username: "user@domain.com", password: "your_password" ); // Optional: Set request timeout (milliseconds) authenticatedClient.RequestTimeout = 30000; // Client without app token (not recommended - lower API quotas) var basicClient = new SodaClient("data.smgov.net"); ``` -------------------------------- ### Initialize SODA.NET Client and Read Metadata Source: https://github.com/cityofsantamonica/soda.net/blob/master/README.md Initialize a new SODA.NET client with your domain and app token. Then, retrieve dataset metadata using its resource identifier. ```csharp //initialize a new client //make sure you register for your own app token (http://dev.socrata.com/register) var client = new SodaClient("data.smgov.net", "REPLACE_WITH_YOUR_APP_TOKEN"); //read metadata of a dataset using the resource identifier (Socrata 4x4) var metadata = client.GetMetadata("1234-wxyz"); Console.WriteLine("{0} has {1} views.", metadata.Name, metadata.ViewsCount); ``` -------------------------------- ### Build SODA.NET with .NET CLI Source: https://github.com/cityofsantamonica/soda.net/blob/master/README.md Clone the SODA.NET repository and build the project using the .NET CLI. ```console git clone git@github.com:CityofSantaMonica/SODA.NET.git SODA.NET cd SODA.NET dotnet build ``` -------------------------------- ### Initialize Client for Write Operations Source: https://github.com/cityofsantamonica/soda.net/blob/master/README.md Initialize a SODA.NET client for write operations, providing authentication credentials. ```csharp //make sure to provide auth credentials! var client = new SodaClient("data.smgov.net", "AppToken", "user@domain.com", "password"); ``` -------------------------------- ### Run Tests with .NET CLI Source: https://github.com/cityofsantamonica/soda.net/blob/master/README.md Execute the project's tests using the .NET CLI. ```console dotnet test ``` -------------------------------- ### Query Dataset with SoQL Source: https://github.com/cityofsantamonica/soda.net/blob/master/README.md Build and execute a SoQL query against a dataset using a fluent query builder syntax. ```csharp //collections of an arbitrary type can be returned //using SoQL and a fluent query building syntax var soql = new SoqlQuery().Select("column1", "column2") .Where("something > nothing") .Group("column3"); var results = dataset.Query(soql); ``` -------------------------------- ### SoqlQuery - Build Queries with Fluent Interface Source: https://context7.com/cityofsantamonica/soda.net/llms.txt The SoqlQuery class provides a fluent interface for constructing Socrata Query Language (SoQL) queries with support for selecting columns, filtering, ordering, grouping, pagination, and full-text search. ```APIDOC ## SoqlQuery - Build Queries with Fluent Interface ### Description The SoqlQuery class provides a fluent interface for constructing Socrata Query Language (SoQL) queries with support for selecting columns, filtering, ordering, grouping, pagination, and full-text search. ### Method POST (for query execution) ### Endpoint `/resource/{dataset_identifier}/query` ### Parameters #### Query Parameters None (Query is built within the request body or as part of the `Query` method call) #### Request Body None (The `SoqlQuery` object is passed directly to the `Query` method) ### Request Example ```csharp var client = new SodaClient("data.smgov.net", "YOUR_APP_TOKEN"); var dataset = client.GetResource>("1234-wxyz"); // Basic query with select and where var basicQuery = new SoqlQuery() .Select("name", "category", "amount") .Where("amount > 1000"); var results = dataset.Query(basicQuery); // Query with column aliases var aliasedQuery = new SoqlQuery() .Select("department_name", "total_budget", "fiscal_year") .As("department", "budget", "year") .Where("total_budget > 500000"); // Parameterized where clause var paramQuery = new SoqlQuery() .Select("*") .Where("category = '{0}' AND year = {1}", "Parks", 2023); // Ordering results var orderedQuery = new SoqlQuery() .Select("name", "created_date") .Order(SoqlOrderDirection.DESC, "created_date") .Limit(100); // Multiple column ordering (default is ASC) var multiOrderQuery = new SoqlQuery() .Select("department", "employee_name", "salary") .Order("department", "salary"); // Grouping with aggregation var groupQuery = new SoqlQuery() .Select("category", "COUNT(*) as count", "SUM(amount) as total") .Group("category") .Having("COUNT(*) > 10") .Order(SoqlOrderDirection.DESC, "total"); // Pagination var pagedQuery = new SoqlQuery() .Select("*") .Limit(50) .Offset(100); // Skip first 100, get next 50 // Full-text search var searchQuery = new SoqlQuery() .FullTextSearch("recreation center") .Select("name", "address", "phone"); // Complex combined query var complexQuery = new SoqlQuery() .Select("department", "project_name", "budget", "start_date") .Where("budget > 100000 AND status = 'Active'") .Order(SoqlOrderDirection.DESC, "budget") .Limit(25) .Offset(0); var complexResults = dataset.Query(complexQuery); ``` ### Response #### Success Response (200) - **IEnumerable** - A collection of rows matching the query, typed according to the generic parameter. #### Response Example ```csharp // Example for basicQuery results foreach (var row in results) { Console.WriteLine($"Name: {row["name"]}, Category: {row["category"]}, Amount: {row["amount"]}"); } ``` ``` -------------------------------- ### Read All or First N Rows from Dataset Source: https://github.com/cityofsantamonica/soda.net/blob/master/README.md Read all rows or the first N rows from a dataset resource. ```csharp //Resource objects read their own data var allRows = dataset.GetRows(); var first10Rows = dataset.GetRows(10); ``` -------------------------------- ### Browse Dataset Catalog Source: https://context7.com/cityofsantamonica/soda.net/llms.txt Retrieve a paginated list of dataset metadata to discover available datasets on a portal. ```csharp using SODA; var client = new SodaClient("data.smgov.net", "YOUR_APP_TOKEN"); // Get the first page of the metadata catalog IEnumerable firstPage = client.GetMetadataPage(1); foreach (ResourceMetadata dataset in firstPage) { Console.WriteLine($"{dataset.Identifier}: {dataset.Name}"); Console.WriteLine($" Category: {dataset.Category}"); Console.WriteLine($" Views: {dataset.ViewsCount}"); } // Iterate through multiple pages for (int page = 1; page <= 5; page++) { var datasets = client.GetMetadataPage(page); Console.WriteLine($"--- Page {page} ---"); foreach (var ds in datasets) { Console.WriteLine($" {ds.Name} ({ds.Identifier})"); } } ``` -------------------------------- ### Build SoQL Queries with Fluent Interface Source: https://context7.com/cityofsantamonica/soda.net/llms.txt Constructs Socrata Query Language (SoQL) queries using a fluent interface. Supports selecting columns, filtering, ordering, grouping, pagination, and full-text search. ```csharp using SODA; var client = new SodaClient("data.smgov.net", "YOUR_APP_TOKEN"); var dataset = client.GetResource>("1234-wxyz"); // Basic query with select and where var basicQuery = new SoqlQuery() .Select("name", "category", "amount") .Where("amount > 1000"); var results = dataset.Query(basicQuery); // Query with column aliases var aliasedQuery = new SoqlQuery() .Select("department_name", "total_budget", "fiscal_year") .As("department", "budget", "year") .Where("total_budget > 500000"); // Parameterized where clause var paramQuery = new SoqlQuery() .Select("*") .Where("category = '{0}' AND year = {1}", "Parks", 2023); // Ordering results var orderedQuery = new SoqlQuery() .Select("name", "created_date") .Order(SoqlOrderDirection.DESC, "created_date") .Limit(100); // Multiple column ordering (default is ASC) var multiOrderQuery = new SoqlQuery() .Select("department", "employee_name", "salary") .Order("department", "salary"); // Grouping with aggregation var groupQuery = new SoqlQuery() .Select("category", "COUNT(*) as count", "SUM(amount) as total") .Group("category") .Having("COUNT(*) > 10") .Order(SoqlOrderDirection.DESC, "total"); // Pagination var pagedQuery = new SoqlQuery() .Select("*") .Limit(50) .Offset(100); // Skip first 100, get next 50 // Full-text search var searchQuery = new SoqlQuery() .FullTextSearch("recreation center") .Select("name", "address", "phone"); // Complex combined query var complexQuery = new SoqlQuery() .Select("department", "project_name", "budget", "start_date") .Where("budget > 100000 AND status = 'Active'") .Order(SoqlOrderDirection.DESC, "budget") .Limit(25) .Offset(0); var complexResults = dataset.Query(complexQuery); ``` -------------------------------- ### Access Dataset as Typed Resource with Soda.net Source: https://context7.com/cityofsantamonica/soda.net/llms.txt Defines a class matching the dataset schema for strongly-typed access. Use this when you know the dataset structure and want compile-time type safety. Handles pagination automatically. ```csharp using SODA; using System.Collections.Generic; // Define a class matching the dataset schema public class CrimeReport { public string incident_number { get; set; } public string crime_type { get; set; } public DateTime? date_reported { get; set; } public string location { get; set; } public string status { get; set; } } var client = new SodaClient("data.smgov.net", "YOUR_APP_TOKEN"); // Get resource with strongly-typed rows Resource crimeDataset = client.GetResource("1234-wxyz"); // Access resource metadata Console.WriteLine($"Dataset: {crimeDataset.Metadata.Name}"); Console.WriteLine($"Host: {crimeDataset.Host}"); Console.WriteLine($"Identifier: {crimeDataset.Identifier}"); // Get all rows (handles pagination automatically) IEnumerable allCrimes = crimeDataset.GetRows(); // Get limited number of rows IEnumerable first100 = crimeDataset.GetRows(100); // Get rows with offset for manual pagination IEnumerable page2 = crimeDataset.GetRows(limit: 50, offset: 50); // Alternative: Use dynamic typing with Dictionary Resource> dynamicDataset = client.GetResource>("1234-wxyz"); foreach (var row in dynamicDataset.GetRows(10)) { Console.WriteLine($"Incident: {row["incident_number"]}"); } ``` -------------------------------- ### Execute Raw SoQL Queries in C# Source: https://context7.com/cityofsantamonica/soda.net/llms.txt Use raw SoQL query strings for complex expressions or subqueries not supported by the fluent interface. ```csharp using SODA; var client = new SodaClient("data.smgov.net", "YOUR_APP_TOKEN"); var dataset = client.GetResource>("1234-wxyz"); // Raw SoQL query string var rawQuery = new SoqlQuery( "SELECT department, SUM(amount) as total " + "WHERE fiscal_year = 2023 " + "GROUP BY department " + "HAVING SUM(amount) > 1000000 " + "ORDER BY total DESC " + "LIMIT 10" ); var results = dataset.Query(rawQuery); foreach (var row in results) { Console.WriteLine($"{row["department"]}: ${row["total"]}"); } ``` -------------------------------- ### Execute Typed SoQL Queries in C# Source: https://context7.com/cityofsantamonica/soda.net/llms.txt Retrieve strongly-typed results from a resource. The library automatically handles pagination unless specific limits are defined. ```csharp using SODA; using System.Collections.Generic; public class BusinessLicense { public string license_number { get; set; } public string business_name { get; set; } public string business_type { get; set; } public string address { get; set; } public DateTime? issue_date { get; set; } public DateTime? expiration_date { get; set; } } public class LicenseSummary { public string business_type { get; set; } public int count { get; set; } } var client = new SodaClient("data.smgov.net", "YOUR_APP_TOKEN"); var licenses = client.GetResource("abcd-1234"); // Query returning the resource's row type var activeQuery = new SoqlQuery() .Where("expiration_date > '2023-01-01'") .Order(SoqlOrderDirection.DESC, "issue_date"); IEnumerable activeLicenses = licenses.Query(activeQuery); // Query returning a different type (for aggregations) var summaryQuery = new SoqlQuery() .Select("business_type", "COUNT(*) as count") .Group("business_type") .Order(SoqlOrderDirection.DESC, "count"); IEnumerable summary = licenses.Query(summaryQuery); foreach (var item in summary) { Console.WriteLine($"{item.business_type}: {item.count} licenses"); } // Direct query via client (specifying resource ID) var directResults = client.Query(activeQuery, "abcd-1234"); ``` -------------------------------- ### Retrieve Dataset Metadata Source: https://context7.com/cityofsantamonica/soda.net/llms.txt Fetch schema, column definitions, and statistics for a specific dataset using its 4x4 identifier. ```csharp using SODA; var client = new SodaClient("data.smgov.net", "YOUR_APP_TOKEN"); // Get metadata for a specific dataset ResourceMetadata metadata = client.GetMetadata("1234-wxyz"); // Access metadata properties Console.WriteLine($"Dataset Name: {metadata.Name}"); Console.WriteLine($"Description: {metadata.Description}"); Console.WriteLine($"Category: {metadata.Category}"); Console.WriteLine($"View Count: {metadata.ViewsCount}"); Console.WriteLine($"Download Count: {metadata.DownloadsCount}"); Console.WriteLine($"Created: {metadata.CreationDate}"); Console.WriteLine($"Last Updated: {metadata.RowsLastUpdated}"); Console.WriteLine($"Row Identifier Field: {metadata.RowIdentifierField}"); // Access column schema information foreach (ResourceColumn column in metadata.Columns) { Console.WriteLine($"Column: {column.Name}"); Console.WriteLine($" Field Name: {column.SodaFieldName}"); Console.WriteLine($" Data Type: {column.DataTypeName}"); Console.WriteLine($" Position: {column.Position}"); } // Access tags and attribution if (metadata.Tags != null) { Console.WriteLine($"Tags: {string.Join(", ", metadata.Tags)}"); } Console.WriteLine($"Attribution: {metadata.Attribution}"); Console.WriteLine($"Attribution Link: {metadata.AttributionLink}"); // Access custom metadata fields if defined by the portal if (metadata.Metadata != null && metadata.Metadata.ContainsKey("custom_fields")) { var customFields = metadata.Metadata["custom_fields"]; // Process custom metadata } ``` -------------------------------- ### GetResource - Access Dataset as Typed Resource Source: https://context7.com/cityofsantamonica/soda.net/llms.txt Creates a Resource object that provides strongly-typed access to dataset rows. The type parameter represents the structure of each row and must be JSON serializable. ```APIDOC ## GetResource - Access Dataset as Typed Resource ### Description Creates a Resource object that provides strongly-typed access to dataset rows. The type parameter represents the structure of each row and must be JSON serializable. ### Method GET (Implicit) ### Endpoint `/resource/{dataset_identifier}` ### Parameters #### Path Parameters - **dataset_identifier** (string) - Required - The unique identifier for the dataset. ### Request Body None ### Request Example ```csharp var client = new SodaClient("data.smgov.net", "YOUR_APP_TOKEN"); Resource crimeDataset = client.GetResource("1234-wxyz"); ``` ### Response #### Success Response (200) - **Resource** - An object representing the dataset with strongly-typed rows. #### Response Example ```csharp // Access resource metadata Console.WriteLine($"Dataset: {crimeDataset.Metadata.Name}"); Console.WriteLine($"Host: {crimeDataset.Host}"); Console.WriteLine($"Identifier: {crimeDataset.Identifier}"); // Get all rows (handles pagination automatically) IEnumerable allCrimes = crimeDataset.GetRows(); // Get limited number of rows IEnumerable first100 = crimeDataset.GetRows(100); // Get rows with offset for manual pagination IEnumerable page2 = crimeDataset.GetRows(limit: 50, offset: 50); // Alternative: Use dynamic typing with Dictionary Resource> dynamicDataset = client.GetResource>("1234-wxyz"); foreach (var row in dynamicDataset.GetRows(10)) { Console.WriteLine($"Incident: {row["incident_number"]}"); } ``` ``` -------------------------------- ### Upsert Data from CSV Source: https://github.com/cityofsantamonica/soda.net/blob/master/README.md Upsert data into a dataset from a CSV string. ```csharp //Upsert some data serialized as CSV string csvData = File.ReadAllText("data.csv"); client.Upsert(csvData, SodaDataFormat.CSV, "1234-wxyz"); ``` -------------------------------- ### Update Resource Metadata Source: https://context7.com/cityofsantamonica/soda.net/llms.txt Update metadata properties like name, description, category, tags, and attribution for a dataset. Requires an existing dataset ID. ```csharp using SODA; var client = new SodaClient( "data.example.com", "YOUR_APP_TOKEN", "user@domain.com", "password" ); // Get existing metadata ResourceMetadata metadata = client.GetMetadata("1234-wxyz"); // Modify metadata properties metadata.Name = "Updated Dataset Name"; metadata.Description = "This dataset contains updated information about..."; metadata.Category = "Finance"; metadata.Tags = new[] { "budget", "fiscal-year-2023", "public" }; metadata.Attribution = "City Finance Department"; metadata.AttributionLink = "https://finance.example.com"; // Save changes SodaResult result = metadata.Update(); if (!result.IsError) { Console.WriteLine($"Metadata updated: {result.Message}"); } else { Console.WriteLine($"Update failed: {result.Message}"); } ``` -------------------------------- ### BatchUpsert - Upsert Large Datasets in Batches Source: https://context7.com/cityofsantamonica/soda.net/llms.txt Processes large collections of data in smaller batches to avoid timeout and memory issues. Returns a result for each batch processed. ```csharp using SODA; using System.Collections.Generic; using System.Linq; public class SalesRecord { public string transaction_id { get; set; } public DateTime sale_date { get; set; } public string product_id { get; set; } public int quantity { get; set; } public decimal amount { get; set; } public string store_id { get; set; } } var client = new SodaClient( "data.example.com", "YOUR_APP_TOKEN", "user@domain.com", "password" ); // Large dataset to upload List salesData = GetLargeSalesDataset(); // 50,000 records // Batch upsert with fixed batch size IEnumerable results = client.BatchUpsert( payload: salesData, batchSize: 1000, resourceId: "1234-wxyz" ); // Process results int totalCreated = 0; int totalUpdated = 0; int batchNumber = 0; foreach (SodaResult result in results) { batchNumber++; if (!result.IsError) { totalCreated += result.RowsCreated; totalUpdated += result.RowsUpdated; Console.WriteLine($"Batch {batchNumber}: {result.RowsCreated} created, {result.RowsUpdated} updated"); } else { Console.WriteLine($"Batch {batchNumber} Error: {result.Message}"); } } Console.WriteLine($"Total: {totalCreated} created, {totalUpdated} updated"); // Batch upsert with break function (custom batch boundaries) // Break batch when store_id changes to keep store data together IEnumerable storeResults = client.BatchUpsert( payload: salesData.OrderBy(s => s.store_id).ToList(), batchSize: 5000, breakFunction: (currentBatch, nextItem) => { if (!currentBatch.Any()) return false; return currentBatch.Last().store_id != nextItem.store_id; }, resourceId: "1234-wxyz" ); // Via Resource object var salesResource = client.GetResource("1234-wxyz"); var resourceResults = salesResource.BatchUpsert(salesData, batchSize: 1000); ``` -------------------------------- ### Retrieve Single Row by ID with Soda.net Source: https://context7.com/cityofsantamonica/soda.net/llms.txt Fetches a single row from a dataset using its row identifier. Ensure you have the correct row identifier for the dataset. ```csharp using SODA; public class ParkingMeter { public string meter_id { get; set; } public string location { get; set; } public decimal rate { get; set; } public string zone { get; set; } } var client = new SodaClient("data.smgov.net", "YOUR_APP_TOKEN"); var meters = client.GetResource("abcd-1234"); // Get a specific row by its identifier ParkingMeter specificMeter = meters.GetRow("row-identifier-value"); Console.WriteLine($"Meter ID: {specificMeter.meter_id}"); Console.WriteLine($"Location: {specificMeter.location}"); Console.WriteLine($"Rate: ${specificMeter.rate}/hr"); ``` -------------------------------- ### Perform Upsert Operations in C# Source: https://context7.com/cityofsantamonica/soda.net/llms.txt Insert or update data in a dataset using objects, CSV, or JSON. Requires authentication and matches rows by the dataset's identifier. ```csharp using SODA; using System.Collections.Generic; using System.IO; public class InventoryItem { public string item_id { get; set; } public string name { get; set; } public int quantity { get; set; } public decimal price { get; set; } public string warehouse { get; set; } } // Create authenticated client var client = new SodaClient( "data.example.com", "YOUR_APP_TOKEN", "user@domain.com", "password" ); // Upsert a collection of objects var items = new List { new InventoryItem { item_id = "SKU001", name = "Widget A", quantity = 100, price = 19.99m, warehouse = "Main" }, new InventoryItem { item_id = "SKU002", name = "Widget B", quantity = 50, price = 29.99m, warehouse = "Main" } }; SodaResult result = client.Upsert(items, "1234-wxyz"); // Check result if (!result.IsError) { Console.WriteLine($"Rows Created: {result.RowsCreated}"); Console.WriteLine($"Rows Updated: {result.RowsUpdated}"); Console.WriteLine($"Message: {result.Message}"); } else { Console.WriteLine($"Error: {result.ErrorCode}"); Console.WriteLine($"Message: {result.Message}"); } // Upsert from CSV file string csvData = File.ReadAllText("inventory.csv"); SodaResult csvResult = client.Upsert(csvData, SodaDataFormat.CSV, "1234-wxyz"); // Upsert from JSON string string jsonData = @"[ {""item_id"": ""SKU003"", ""name"": ""Widget C"", ""quantity"": 75, ""price"": 39.99} ]"; SodaResult jsonResult = client.Upsert(jsonData, SodaDataFormat.JSON, "1234-wxyz"); // Upsert via Resource object var inventory = client.GetResource("1234-wxyz"); SodaResult resourceResult = inventory.Upsert(items); ``` -------------------------------- ### Replace - Replace All Dataset Rows Source: https://context7.com/cityofsantamonica/soda.net/llms.txt Replaces all existing rows in a dataset with new data. Use with caution as this operation deletes all existing data. ```csharp using SODA; using System.Collections.Generic; using System.IO; public class ConfigSetting { public string setting_key { get; set; } public string setting_value { get; set; } public string description { get; set; } public DateTime last_modified { get; set; } } var client = new SodaClient( "data.example.com", "YOUR_APP_TOKEN", "user@domain.com", "password" ); // New configuration to replace existing data var newConfig = new List { new ConfigSetting { setting_key = "max_connections", setting_value = "100", description = "Maximum concurrent connections", last_modified = DateTime.Now }, new ConfigSetting { setting_key = "timeout_seconds", setting_value = "30", description = "Request timeout in seconds", last_modified = DateTime.Now } }; // Replace all existing rows with new data SodaResult result = client.Replace(newConfig, "config-1234"); if (!result.IsError) { Console.WriteLine($"Replaced with {result.RowsCreated} rows"); } // Replace using CSV data string csvData = File.ReadAllText("new_config.csv"); SodaResult csvResult = client.Replace(csvData, SodaDataFormat.CSV, "config-1234"); // Replace using JSON data string jsonData = "[{\"setting_key\": \"debug_mode\", \"setting_value\": \"false\"}]"; SodaResult jsonResult = client.Replace(jsonData, SodaDataFormat.JSON, "config-1234"); // Via Resource object var configResource = client.GetResource("config-1234"); SodaResult resourceResult = configResource.Replace(newConfig); ``` -------------------------------- ### Upsert Collection of Entities Source: https://github.com/cityofsantamonica/soda.net/blob/master/README.md Upsert a collection of serializable entities into a dataset. ```csharp //Upsert a collection of serializable entities IEnumerable payload = GetPayloadData(); client.Upsert(payload, "1234-wxyz"); ``` -------------------------------- ### GetRow - Retrieve Single Row by ID Source: https://context7.com/cityofsantamonica/soda.net/llms.txt Fetches a single row from a dataset using its row identifier. ```APIDOC ## GetRow - Retrieve Single Row by ID ### Description Fetches a single row from a dataset using its row identifier. ### Method GET (Implicit) ### Endpoint `/resource/{dataset_identifier}/{row_identifier}` ### Parameters #### Path Parameters - **dataset_identifier** (string) - Required - The unique identifier for the dataset. - **row_identifier** (string) - Required - The unique identifier for the row within the dataset. ### Request Body None ### Request Example ```csharp var client = new SodaClient("data.smgov.net", "YOUR_APP_TOKEN"); var meters = client.GetResource("abcd-1234"); // Get a specific row by its identifier ParkingMeter specificMeter = meters.GetRow("row-identifier-value"); ``` ### Response #### Success Response (200) - **T** - An object representing the requested row, typed according to the generic parameter. #### Response Example ```csharp Console.WriteLine($"Meter ID: {specificMeter.meter_id}"); Console.WriteLine($"Location: {specificMeter.location}"); Console.WriteLine($"Rate: ${specificMeter.rate}/hr"); ``` ``` -------------------------------- ### DeleteRow - Delete Single Row Source: https://context7.com/cityofsantamonica/soda.net/llms.txt Deletes a single row from a dataset using its row identifier. Requires authentication. ```csharp using SODA; var client = new SodaClient( "data.example.com", "YOUR_APP_TOKEN", "user@domain.com", "password" ); // Delete a row by its identifier SodaResult result = client.DeleteRow( rowId: "row-identifier-value", resourceId: "1234-wxyz" ); if (!result.IsError) { Console.WriteLine($"Deleted {result.RowsDeleted} row(s)"); } else { Console.WriteLine($"Delete failed: {result.Message}"); } // Via Resource object var resource = client.GetResource("1234-wxyz"); SodaResult deleteResult = resource.DeleteRow("row-identifier-value"); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.