diff --git a/.github/workflows/cleanrepo-orphaned-articles.yml b/.github/workflows/cleanrepo-orphaned-articles.yml index 88318c251aa3f..554689691bb16 100644 --- a/.github/workflows/cleanrepo-orphaned-articles.yml +++ b/.github/workflows/cleanrepo-orphaned-articles.yml @@ -35,7 +35,7 @@ jobs: # Create the PR for the work done by the "clean repo" tool - name: create-pull-request - uses: peter-evans/create-pull-request@v7 + uses: peter-evans/create-pull-request@84ae59a2cdc2258d6fa0732dd66352dddae2a412 #v7.0.9 with: branch: cleanrepo-orphaned-articles title: "Monthly chores: Delete orphaned articles" diff --git a/.github/workflows/cleanrepo-orphaned-images.yml b/.github/workflows/cleanrepo-orphaned-images.yml index 46a9fc4bfd5e6..e04b327055037 100644 --- a/.github/workflows/cleanrepo-orphaned-images.yml +++ b/.github/workflows/cleanrepo-orphaned-images.yml @@ -35,7 +35,7 @@ jobs: # Create the PR for the work done by the "clean repo" tool - name: create-pull-request - uses: peter-evans/create-pull-request@v7 + uses: peter-evans/create-pull-request@84ae59a2cdc2258d6fa0732dd66352dddae2a412 #v7.0.9 with: branch: cleanrepo-orphaned-images title: "Monthly chores: Delete orphaned images" diff --git a/.github/workflows/cleanrepo-orphaned-includes.yml b/.github/workflows/cleanrepo-orphaned-includes.yml index 7e21ec58afe4c..31d8689d8a526 100644 --- a/.github/workflows/cleanrepo-orphaned-includes.yml +++ b/.github/workflows/cleanrepo-orphaned-includes.yml @@ -35,7 +35,7 @@ jobs: # Create the PR for the work done by the "clean repo" tool - name: create-pull-request - uses: peter-evans/create-pull-request@v7 + uses: peter-evans/create-pull-request@84ae59a2cdc2258d6fa0732dd66352dddae2a412 #v7.0.9 with: branch: cleanrepo-orphaned-includes title: "Monthly chores: Delete orphaned include files" diff --git a/.github/workflows/cleanrepo-orphaned-snippets.yml b/.github/workflows/cleanrepo-orphaned-snippets.yml index 7d31980ec1a4e..bb642c6dc2009 100644 --- a/.github/workflows/cleanrepo-orphaned-snippets.yml +++ b/.github/workflows/cleanrepo-orphaned-snippets.yml @@ -35,7 +35,7 @@ jobs: # Create the PR for the work done by the "clean repo" tool - name: create-pull-request - uses: peter-evans/create-pull-request@v7 + uses: peter-evans/create-pull-request@84ae59a2cdc2258d6fa0732dd66352dddae2a412 #v7.0.9 with: branch: cleanrepo-orphaned-snippets title: "Monthly chores: Delete orphaned snippets" diff --git a/.github/workflows/cleanrepo-redirect-hops.yml b/.github/workflows/cleanrepo-redirect-hops.yml index aa71d5ffa2612..931fe9ea87e61 100644 --- a/.github/workflows/cleanrepo-redirect-hops.yml +++ b/.github/workflows/cleanrepo-redirect-hops.yml @@ -35,7 +35,7 @@ jobs: # Create the PR for the work done by the "clean repo" tool - name: create-pull-request - uses: peter-evans/create-pull-request@v7 + uses: peter-evans/create-pull-request@84ae59a2cdc2258d6fa0732dd66352dddae2a412 #v7.0.9 with: branch: cleanrepo-remove-hops title: "Monthly chores: Remove redirect hops" diff --git a/.github/workflows/cleanrepo-relative-links.yml b/.github/workflows/cleanrepo-relative-links.yml index 54db1f46fe089..24526537863a4 100644 --- a/.github/workflows/cleanrepo-relative-links.yml +++ b/.github/workflows/cleanrepo-relative-links.yml @@ -35,7 +35,7 @@ jobs: # Create the PR for the work done by the "clean repo" tool - name: create-pull-request - uses: peter-evans/create-pull-request@v7 + uses: peter-evans/create-pull-request@84ae59a2cdc2258d6fa0732dd66352dddae2a412 #v7.0.9 with: branch: cleanrepo-relative-links title: "Monthly chores: Use relative links" diff --git a/.github/workflows/cleanrepo-replace-redirects.yml b/.github/workflows/cleanrepo-replace-redirects.yml index 9b4341241694d..ff26a53c4fa52 100644 --- a/.github/workflows/cleanrepo-replace-redirects.yml +++ b/.github/workflows/cleanrepo-replace-redirects.yml @@ -35,7 +35,7 @@ jobs: # Create the PR for the work done by the "clean repo" tool - name: create-pull-request - uses: peter-evans/create-pull-request@v7 + uses: peter-evans/create-pull-request@84ae59a2cdc2258d6fa0732dd66352dddae2a412 #v7.0.9 with: branch: cleanrepo-replace-redirects title: "Monthly chores: Replace redirect targets" diff --git a/.github/workflows/dependabot-bot.yml b/.github/workflows/dependabot-bot.yml index 0379eab8ace36..83f33ee238bbd 100644 --- a/.github/workflows/dependabot-bot.yml +++ b/.github/workflows/dependabot-bot.yml @@ -54,7 +54,7 @@ jobs: dependabot-yml-path: ".github/dependabot.yml" - name: Create pull request if: github.event_name == 'workflow_dispatch' || github.repository_owner == 'dotnet' - uses: peter-evans/create-pull-request@v7 + uses: peter-evans/create-pull-request@84ae59a2cdc2258d6fa0732dd66352dddae2a412 #v7.0.9 with: branch: create-dependabotconfig-pull-request/patch title: "Update dependabot.yml - automatically." diff --git a/docs/ai/conceptual/data-ingestion.md b/docs/ai/conceptual/data-ingestion.md new file mode 100644 index 0000000000000..430efb4600ae3 --- /dev/null +++ b/docs/ai/conceptual/data-ingestion.md @@ -0,0 +1,159 @@ +--- +title: Data ingestion +description: Introduction to data ingestion +author: luisquintanilla +ms.author: luquinta +ms.date: 12/02/2025 +ms.topic: concept-article +ai-usage: ai-assisted +--- + +# Data ingestion + +Data ingestion is the process of collecting, reading, and preparing data from different sources such as files, databases, APIs, or cloud services so it can be used in downstream applications. In practice, this process follows the Extract-Transform-Load (ETL) workflow: + +- **Extract** data from its original source, whether that is a PDF, Word document, audio file, or web API. +- **Transform** the data by cleaning, chunking, enriching, or converting formats. +- **Load** the data into a destination like a database, vector store, or AI model for retrieval and analysis. + +For AI and machine learning scenarios, especially Retrieval-Augmented Generation (RAG), data ingestion is not just about converting data from one format to another. It is about making data usable for intelligent applications. This means representing documents in a way that preserves their structure and meaning, splitting them into manageable chunks, enriching them with metadata or embeddings, and storing them so they can be retrieved quickly and accurately. + +## Why data ingestion matters for AI applications + +Imagine you're building a RAG-powered chatbot to help employees find information across your company's vast collection of documents. These documents might include PDFs, Word files, PowerPoint presentations, and web pages scattered across different systems. + +Your chatbot needs to understand and search through thousands of documents to provide accurate, contextual answers. But raw documents aren't suitable for AI systems. You need to transform them into a format that preserves meaning while making them searchable and retrievable. + +This is where data ingestion becomes critical. You need to extract text from different file formats, break large documents into smaller chunks that fit within AI model limits, enrich the content with metadata, generate embeddings for semantic search, and store everything in a way that enables fast retrieval. Each step requires careful consideration of how to preserve the original meaning and context. + +## The Microsoft.Extensions.DataIngestion library + +The [📦 Microsoft.Extensions.DataIngestion package](https://www.nuget.org/packages/Microsoft.Extensions.DataIngestion) provides foundational .NET building blocks for data ingestion. It enables developers to read, process, and prepare documents for AI and machine learning workflows, especially Retrieval-Augmented Generation (RAG) scenarios. + +With these building blocks, you can create robust, flexible, and intelligent data ingestion pipelines tailored for your application needs: + +- **Unified document representation:** Represent any file type (for example, PDF, Image, or Microsoft Word) in a consistent format that works well with large language models. +- **Flexible data ingestion:** Read documents from both cloud services and local sources using multiple built-in readers, making it easy to bring in data from wherever it lives. +- **Built-in AI enhancements:** Automatically enrich content with summaries, sentiment analysis, keyword extraction, and classification, preparing your data for intelligent workflows. +- **Customizable chunking strategies:** Split documents into chunks using token-based, section-based, or semantic-aware approaches, so you can optimize for your retrieval and analysis needs. +- **Production-ready storage:** Store processed chunks in popular vector databases and document stores, with support for embedding generation, making your pipelines ready for real-world scenarios. +- **End-to-end pipeline composition:** Chain together readers, processors, chunkers, and writers with the API, reducing boilerplate and making it easy to build, customize, and extend complete workflows. +- **Performance and scalability:** Designed for scalable data processing, these components can handle large volumes of data efficiently, making them suitable for enterprise-grade applications. + +All of these components are open and extensible by design. You can add custom logic and new connectors, and extend the system to support emerging AI scenarios. By standardizing how documents are represented, processed, and stored, .NET developers can build reliable, scalable, and maintainable data pipelines without "reinventing the wheel" for every project. + +### Built on stable foundations + +![Data Ingestion Architecture Diagram](../media/data-ingestion/dataingestion.png) + +These data ingestion building blocks are built on top of proven and extensible components in the .NET ecosystem, ensuring reliability, interoperability, and seamless integration with existing AI workflows: + +- **Microsoft.ML.Tokenizers:** Tokenizers provide the foundation for chunking documents based on tokens. This enables precise splitting of content, which is essential for preparing data for large language models and optimizing retrieval strategies. +- **Microsoft.Extensions.AI:** This set of libraries powers enrichment transformations using large language models. It enables features like summarization, sentiment analysis, keyword extraction, and embedding generation, making it easy to enhance your data with intelligent insights. +- **Microsoft.Extensions.VectorData:** This set of libraries offers a consistent interface for storing processed chunks in a wide variety of vector stores, including Qdrant, Azure SQL, CosmosDB, MongoDB, ElasticSearch, and many more. This ensures your data pipelines are ready for production and can scale across different storage backends. + +In addition to familiar patterns and tools, these abstractions build on already extensible components. Plug-in capability and interoperability are paramount, so as the rest of the .NET AI ecosystem grows, the capabilities of the data ingestion components grow as well. This approach empowers developers to easily integrate new connectors, enrichments, and storage options, keeping their pipelines future-ready and adaptable to evolving AI scenarios. + +## Data ingestion building blocks + +The [Microsoft.Extensions.DataIngestion](https://www.nuget.org/packages/Microsoft.Extensions.DataIngestion) library is built around several key components that work together to create a complete data processing pipeline. This section explores each component and how they fit together. + +### Documents and document readers + +At the foundation of the library is the type, which provides a unified way to represent any file format without losing important information. `IngestionDocument` is Markdown-centric because large language models work best with Markdown formatting. + +The abstraction handles loading documents from various sources, whether local files or streams. A few readers are available: + +- **[MarkItDown](https://www.nuget.org/packages/Microsoft.Extensions.DataIngestion.MarkItDown)** +- **[Markdig](https://www.nuget.org/packages/Microsoft.Extensions.DataIngestion.Markdig/)** + +More readers (including **LlamaParse** and **Azure Document Intelligence**) will be added in the future. + +This design means you can work with documents from different sources using the same consistent API, making your code more maintainable and flexible. + +### Document processing + +Document processors apply transformations at the document level to enhance and prepare content. The library provides the class as a built-in processor that uses large language models to generate descriptive alternative text for images within documents. + +### Chunks and chunking strategies + +Once you have a document loaded, you typically need to break it down into smaller pieces called chunks. Chunks represent subsections of a document that can be efficiently processed, stored, and retrieved by AI systems. This chunking process is essential for retrieval-augmented generation scenarios where you need to find the most relevant pieces of information quickly. + +The library provides several chunking strategies to fit different use cases: + +- **Header-based chunking** to split on headers. +- **Section-based chunking** to split on sections (for example, pages). +- **Semantic-aware chunking** to preserve complete thoughts. + +These chunking strategies build on the Microsoft.ML.Tokenizers library to intelligently split text into appropriately sized pieces that work well with large language models. The right chunking strategy depends on your document types and how you plan to retrieve information. + +```csharp +Tokenizer tokenizer = TiktokenTokenizer.CreateForModel("gpt-4"); +IngestionChunkerOptions options = new(tokenizer) +{ + MaxTokensPerChunk = 2000, + OverlapTokens = 0 +}; +IngestionChunker chunker = new HeaderChunker(options); +``` + +### Chunk processing and enrichment + +After documents are split into chunks, you can apply processors to enhance and enrich the content. Chunk processors work on individual pieces and can perform: + +- **Content enrichment** including automatic summaries (`SummaryEnricher`), sentiment analysis (`SentimentEnricher`), and keyword extraction (`KeywordEnricher`). +- **Classification** for automated content categorization based on predefined categories (`ClassificationEnricher`). + +These processors use [Microsoft.Extensions.AI.Abstractions](https://www.nuget.org/packages/Microsoft.Extensions.AI.Abstractions) to leverage large language models for intelligent content transformation, making your chunks more useful for downstream AI applications. + +### Document writer and storage + + stores processed chunks into a data store for later retrieval. Using Microsoft.Extensions.AI and [Microsoft.Extensions.VectorData.Abstractions](https://www.nuget.org/packages/Microsoft.Extensions.VectorData.Abstractions), the library provides the class that supports storing chunks in any vector store supported by Microsoft.Extensions.VectorData. + +Vectore stores include popular options like [Qdrant](https://www.nuget.org/packages/Microsoft.SemanticKernel.Connectors.Qdrant), [SQL Server](https://www.nuget.org/packages/Microsoft.SemanticKernel.Connectors.SqlServer), [CosmosDB](https://www.nuget.org/packages/Microsoft.SemanticKernel.Connectors.CosmosNoSQL), [MongoDB](https://www.nuget.org/packages/Microsoft.SemanticKernel.Connectors.MongoDB), [ElasticSearch](https://www.nuget.org/packages/Elastic.SemanticKernel.Connectors.Elasticsearch), and many more. The writer can also automatically generate embeddings for your chunks using Microsoft.Extensions.AI, readying them for semantic search and retrieval scenarios. + +```csharp +OpenAIClient openAIClient = new( + new ApiKeyCredential(Environment.GetEnvironmentVariable("GITHUB_TOKEN")!), + new OpenAIClientOptions { Endpoint = new Uri("https://models.github.ai/inference") }); + +IEmbeddingGenerator> embeddingGenerator = + openAIClient.GetEmbeddingClient("text-embedding-3-small").AsIEmbeddingGenerator(); + +using SqliteVectorStore vectorStore = new( + "Data Source=vectors.db;Pooling=false", + new() + { + EmbeddingGenerator = embeddingGenerator + }); + +// The writer requires the embedding dimension count to be specified. +// For OpenAI's `text-embedding-3-small`, the dimension count is 1536. +using VectorStoreWriter writer = new(vectorStore, dimensionCount: 1536); +``` + +### Document processing pipeline + +The API allows you to chain together the various data ingestion components into a complete workflow. You can combine: + +- **Readers** to load documents from various sources. +- **Processors** to transform and enrich document content. +- **Chunkers** to break documents into manageable pieces. +- **Writers** to store the final results in your chosen data store. + +This pipeline approach reduces boilerplate code and makes it easy to build, test, and maintain complex data ingestion workflows. + +```csharp +using IngestionPipeline pipeline = new(reader, chunker, writer, loggerFactory: loggerFactory) +{ + DocumentProcessors = { imageAlternativeTextEnricher }, + ChunkProcessors = { summaryEnricher } +}; + +await foreach (var result in pipeline.ProcessAsync(new DirectoryInfo("."), searchPattern: "*.md")) +{ + Console.WriteLine($"Completed processing '{result.DocumentId}'. Succeeded: '{result.Succeeded}'."); +} +``` + +A single document ingestion failure shouldn't fail the whole pipeline. That's why implements partial success by returning `IAsyncEnumerable`. The caller is responsible for handling any failures (for example, by retrying failed documents or stopping on first error). diff --git a/docs/ai/media/data-ingestion/dataingestion.png b/docs/ai/media/data-ingestion/dataingestion.png new file mode 100644 index 0000000000000..fd750ccc581e8 Binary files /dev/null and b/docs/ai/media/data-ingestion/dataingestion.png differ diff --git a/docs/ai/toc.yml b/docs/ai/toc.yml index b49af499ac0ef..80d10744a9d41 100644 --- a/docs/ai/toc.yml +++ b/docs/ai/toc.yml @@ -44,6 +44,8 @@ items: href: conceptual/embeddings.md - name: Vector databases href: conceptual/vector-databases.md + - name: Data ingestion + href: conceptual/data-ingestion.md - name: Prompt engineering href: conceptual/prompt-engineering-dotnet.md - name: Chain-of-thought prompting diff --git a/docs/azure/includes/dotnet-all.md b/docs/azure/includes/dotnet-all.md index 6f5ff3c96eaf1..4af77a486805f 100644 --- a/docs/azure/includes/dotnet-all.md +++ b/docs/azure/includes/dotnet-all.md @@ -1,6 +1,6 @@ | Name | Package | Docs | Source | | ---- | ------- | ---- | ------ | -| AI Agents Persistent | NuGet [1.1.0](https://www.nuget.org/packages/Azure.AI.Agents.Persistent/1.1.0)
NuGet [1.2.0-beta.7](https://www.nuget.org/packages/Azure.AI.Agents.Persistent/1.2.0-beta.7) | [docs](/dotnet/api/overview/azure/AI.Agents.Persistent-readme) | GitHub [1.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Agents.Persistent_1.1.0/sdk/ai/Azure.AI.Agents.Persistent/)
GitHub [1.2.0-beta.7](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Agents.Persistent_1.2.0-beta.7/sdk/ai/Azure.AI.Agents.Persistent/) | +| AI Agents Persistent | NuGet [1.1.0](https://www.nuget.org/packages/Azure.AI.Agents.Persistent/1.1.0)
NuGet [1.2.0-beta.8](https://www.nuget.org/packages/Azure.AI.Agents.Persistent/1.2.0-beta.8) | [docs](/dotnet/api/overview/azure/AI.Agents.Persistent-readme) | GitHub [1.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Agents.Persistent_1.1.0/sdk/ai/Azure.AI.Agents.Persistent/)
GitHub [1.2.0-beta.8](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Agents.Persistent_1.2.0-beta.8/sdk/ai/Azure.AI.Agents.Persistent/) | | AI Foundry | NuGet [1.1.0](https://www.nuget.org/packages/Azure.AI.Projects/1.1.0)
NuGet [1.2.0-beta.4](https://www.nuget.org/packages/Azure.AI.Projects/1.2.0-beta.4) | [docs](/dotnet/api/overview/azure/AI.Projects-readme) | GitHub [1.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Projects_1.1.0/sdk/ai/Azure.AI.Projects/)
GitHub [1.2.0-beta.4](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Projects_1.2.0-beta.4/sdk/ai/Azure.AI.Projects/) | | AI Model Inference | NuGet [1.0.0-beta.5](https://www.nuget.org/packages/Azure.AI.Inference/1.0.0-beta.5) | [docs](/dotnet/api/overview/azure/AI.Inference-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.5](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Inference_1.0.0-beta.5/sdk/ai/Azure.AI.Inference/) | | Anomaly Detector | NuGet [3.0.0-preview.7](https://www.nuget.org/packages/Azure.AI.AnomalyDetector/3.0.0-preview.7) | [docs](/dotnet/api/overview/azure/AI.AnomalyDetector-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [3.0.0-preview.7](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.AnomalyDetector_3.0.0-preview.7/sdk/anomalydetector/Azure.AI.AnomalyDetector/) | @@ -83,7 +83,7 @@ | Personalizer | NuGet [2.0.0-beta.2](https://www.nuget.org/packages/Azure.AI.Personalizer/2.0.0-beta.2) | [docs](/dotnet/api/overview/azure/AI.Personalizer-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [2.0.0-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Personalizer_2.0.0-beta.2/sdk/personalizer/Azure.AI.Personalizer/) | | Playwright | NuGet [1.0.0](https://www.nuget.org/packages/Azure.Developer.Playwright/1.0.0) | [docs](/dotnet/api/overview/azure/Developer.Playwright-readme) | GitHub [1.0.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Developer.Playwright_1.0.0/sdk/loadtestservice/Azure.Developer.Playwright/) | | Playwright NUnit | NuGet [1.0.0](https://www.nuget.org/packages/Azure.Developer.Playwright.NUnit/1.0.0) | [docs](/dotnet/api/overview/azure/Developer.Playwright.NUnit-readme) | GitHub [1.0.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Developer.Playwright.NUnit_1.0.0/sdk/loadtestservice/Azure.Developer.Playwright.NUnit/) | -| Provisioning | NuGet [1.3.0](https://www.nuget.org/packages/Azure.Provisioning/1.3.0)
NuGet [1.4.0-beta.2](https://www.nuget.org/packages/Azure.Provisioning/1.4.0-beta.2) | [docs](/dotnet/api/overview/azure/Provisioning-readme) | GitHub [1.3.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Provisioning_1.3.0/sdk/provisioning/Azure.Provisioning/)
GitHub [1.4.0-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Provisioning_1.4.0-beta.2/sdk/provisioning/Azure.Provisioning/) | +| Provisioning | NuGet [1.3.0](https://www.nuget.org/packages/Azure.Provisioning/1.3.0)
NuGet [1.4.0-beta.3](https://www.nuget.org/packages/Azure.Provisioning/1.4.0-beta.3) | [docs](/dotnet/api/overview/azure/Provisioning-readme) | GitHub [1.3.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Provisioning_1.3.0/sdk/provisioning/Azure.Provisioning/)
GitHub [1.4.0-beta.3](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Provisioning_1.4.0-beta.3/sdk/provisioning/Azure.Provisioning/) | | Provisioning - Resources | NuGet [0.2.0](https://www.nuget.org/packages/Azure.Provisioning.Resources/0.2.0) | [docs](/dotnet/api/overview/azure/Provisioning.Resources-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [0.2.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Provisioning.Resources_0.2.0/sdk/provisioning/Azure.Provisioning.Resources/) | | Purview Account | NuGet [1.0.0-beta.1](https://www.nuget.org/packages/Azure.Analytics.Purview.Account/1.0.0-beta.1) | [docs](/dotnet/api/overview/azure/Analytics.Purview.Account-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Analytics.Purview.Account_1.0.0-beta.1/sdk/purview/Azure.Analytics.Purview.Account/) | | Purview Administration | NuGet [1.0.0-beta.1](https://www.nuget.org/packages/Azure.Analytics.Purview.Administration/1.0.0-beta.1) | [docs](/dotnet/api/overview/azure/Analytics.Purview.Administration-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Analytics.Purview.Administration_1.0.0-beta.1/sdk/purview/Azure.Analytics.Purview.Administration/) | @@ -152,7 +152,7 @@ | Provisioning - Container Service | NuGet [1.0.0-beta.4](https://www.nuget.org/packages/Azure.Provisioning.ContainerService/1.0.0-beta.4) | [docs](/dotnet/api/overview/azure/Provisioning.ContainerService-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.4](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Provisioning.ContainerService_1.0.0-beta.4/sdk/provisioning/Azure.Provisioning.ContainerService/) | | Provisioning - CosmosDB | NuGet [1.0.0](https://www.nuget.org/packages/Azure.Provisioning.CosmosDB/1.0.0)
NuGet [1.1.0-beta.1](https://www.nuget.org/packages/Azure.Provisioning.CosmosDB/1.1.0-beta.1) | [docs](/dotnet/api/overview/azure/Provisioning.CosmosDB-readme) | GitHub [1.0.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Provisioning.CosmosDB_1.0.0/sdk/provisioning/Azure.Provisioning.CosmosDB/)
GitHub [1.1.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Provisioning.CosmosDB_1.1.0-beta.1/sdk/provisioning/Azure.Provisioning.CosmosDB/) | | Provisioning - Deployment | NuGet [1.0.0-beta.2](https://www.nuget.org/packages/Azure.Provisioning.Deployment/1.0.0-beta.2) | [docs](/dotnet/api/overview/azure/Provisioning.Deployment-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Provisioning.Deployment_1.0.0-beta.2/sdk/provisioning/Azure.Provisioning.Deployment/) | -| Provisioning - Dns | NuGet [1.0.0-beta.1](https://www.nuget.org/packages/Azure.Provisioning.Dns/1.0.0-beta.1) | [docs](/dotnet/api/overview/azure/Provisioning.Dns-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Provisioning.Dns_1.0.0-beta.1/sdk/provisioning/Azure.Provisioning.Dns/) | +| Provisioning - Dns | NuGet [1.0.0-beta.2](https://www.nuget.org/packages/Azure.Provisioning.Dns/1.0.0-beta.2) | [docs](/dotnet/api/overview/azure/Provisioning.Dns-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Provisioning.Dns_1.0.0-beta.2/sdk/provisioning/Azure.Provisioning.Dns/) | | Provisioning - Event Grid | NuGet [1.1.0](https://www.nuget.org/packages/Azure.Provisioning.EventGrid/1.1.0) | [docs](/dotnet/api/overview/azure/Provisioning.EventGrid-readme) | GitHub [1.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Provisioning.EventGrid_1.1.0/sdk/provisioning/Azure.Provisioning.EventGrid/) | | Provisioning - Event Hubs | NuGet [1.1.0](https://www.nuget.org/packages/Azure.Provisioning.EventHubs/1.1.0) | [docs](/dotnet/api/overview/azure/Provisioning.EventHubs-readme) | GitHub [1.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Provisioning.EventHubs_1.1.0/sdk/provisioning/Azure.Provisioning.EventHubs/) | | Provisioning - Frontdoor | NuGet [1.0.0-beta.1](https://www.nuget.org/packages/Azure.Provisioning.FrontDoor/1.0.0-beta.1) | [docs](/dotnet/api/overview/azure/Provisioning.FrontDoor-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Provisioning.FrontDoor_1.0.0-beta.1/sdk/provisioning/Azure.Provisioning.FrontDoor/) | @@ -206,6 +206,7 @@ | Resource Management - Compute Fleet | NuGet [1.0.0](https://www.nuget.org/packages/Azure.ResourceManager.ComputeFleet/1.0.0) | [docs](/dotnet/api/overview/azure/ResourceManager.ComputeFleet-readme) | GitHub [1.0.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.ComputeFleet_1.0.0/sdk/computefleet/Azure.ResourceManager.ComputeFleet/) | | Resource Management - Compute Schedule | NuGet [1.1.0](https://www.nuget.org/packages/Azure.ResourceManager.ComputeSchedule/1.1.0)
NuGet [1.2.0-beta.1](https://www.nuget.org/packages/Azure.ResourceManager.ComputeSchedule/1.2.0-beta.1) | [docs](/dotnet/api/overview/azure/ResourceManager.ComputeSchedule-readme) | GitHub [1.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.ComputeSchedule_1.1.0/sdk/computeschedule/Azure.ResourceManager.ComputeSchedule/)
GitHub [1.2.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.ComputeSchedule_1.2.0-beta.1/sdk/computeschedule/Azure.ResourceManager.ComputeSchedule/) | | Resource Management - Compute.Recommender | NuGet [1.0.0-beta.2](https://www.nuget.org/packages/Azure.ResourceManager.Compute.Recommender/1.0.0-beta.2) | [docs](/dotnet/api/overview/azure/ResourceManager.Compute.Recommender-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.Compute.Recommender_1.0.0-beta.2/sdk/computerecommender/Azure.ResourceManager.Compute.Recommender/) | +| Resource Management - Computelimit | NuGet [1.0.0-beta.1](https://www.nuget.org/packages/Azure.ResourceManager.ComputeLimit/1.0.0-beta.1) | [docs](/dotnet/api/overview/azure/ResourceManager.ComputeLimit-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.ComputeLimit_1.0.0-beta.1/sdk/computelimit/Azure.ResourceManager.ComputeLimit/) | | Resource Management - Confidential Ledger | NuGet [1.0.1](https://www.nuget.org/packages/Azure.ResourceManager.ConfidentialLedger/1.0.1)
NuGet [1.1.0-beta.6](https://www.nuget.org/packages/Azure.ResourceManager.ConfidentialLedger/1.1.0-beta.6) | [docs](/dotnet/api/overview/azure/ResourceManager.ConfidentialLedger-readme) | GitHub [1.0.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.ConfidentialLedger_1.0.1/sdk/confidentialledger/Azure.ResourceManager.ConfidentialLedger/)
GitHub [1.1.0-beta.6](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.ConfidentialLedger_1.1.0-beta.6/sdk/confidentialledger/Azure.ResourceManager.ConfidentialLedger/) | | Resource Management - Confluent | NuGet [1.2.1](https://www.nuget.org/packages/Azure.ResourceManager.Confluent/1.2.1) | [docs](/dotnet/api/overview/azure/ResourceManager.Confluent-readme) | GitHub [1.2.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.Confluent_1.2.1/sdk/confluent/Azure.ResourceManager.Confluent/) | | Resource Management - Connected VMware vSphere | NuGet [1.1.1](https://www.nuget.org/packages/Azure.ResourceManager.ConnectedVMwarevSphere/1.1.1) | [docs](/dotnet/api/overview/azure/ResourceManager.ConnectedVMwarevSphere-readme) | GitHub [1.1.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.ConnectedVMwarevSphere_1.1.1/sdk/connectedvmwarevsphere/Azure.ResourceManager.ConnectedVMwarevSphere/) | diff --git a/docs/azure/includes/dotnet-new.md b/docs/azure/includes/dotnet-new.md index a1ba3a3eb6ed6..ecc061a53d6ad 100644 --- a/docs/azure/includes/dotnet-new.md +++ b/docs/azure/includes/dotnet-new.md @@ -1,6 +1,6 @@ | Name | Package | Docs | Source | | ---- | ------- | ---- | ------ | -| AI Agents Persistent | NuGet [1.1.0](https://www.nuget.org/packages/Azure.AI.Agents.Persistent/1.1.0)
NuGet [1.2.0-beta.7](https://www.nuget.org/packages/Azure.AI.Agents.Persistent/1.2.0-beta.7) | [docs](/dotnet/api/overview/azure/AI.Agents.Persistent-readme) | GitHub [1.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Agents.Persistent_1.1.0/sdk/ai/Azure.AI.Agents.Persistent/)
GitHub [1.2.0-beta.7](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Agents.Persistent_1.2.0-beta.7/sdk/ai/Azure.AI.Agents.Persistent/) | +| AI Agents Persistent | NuGet [1.1.0](https://www.nuget.org/packages/Azure.AI.Agents.Persistent/1.1.0)
NuGet [1.2.0-beta.8](https://www.nuget.org/packages/Azure.AI.Agents.Persistent/1.2.0-beta.8) | [docs](/dotnet/api/overview/azure/AI.Agents.Persistent-readme) | GitHub [1.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Agents.Persistent_1.1.0/sdk/ai/Azure.AI.Agents.Persistent/)
GitHub [1.2.0-beta.8](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Agents.Persistent_1.2.0-beta.8/sdk/ai/Azure.AI.Agents.Persistent/) | | AI Foundry | NuGet [1.1.0](https://www.nuget.org/packages/Azure.AI.Projects/1.1.0)
NuGet [1.2.0-beta.4](https://www.nuget.org/packages/Azure.AI.Projects/1.2.0-beta.4) | [docs](/dotnet/api/overview/azure/AI.Projects-readme) | GitHub [1.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Projects_1.1.0/sdk/ai/Azure.AI.Projects/)
GitHub [1.2.0-beta.4](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Projects_1.2.0-beta.4/sdk/ai/Azure.AI.Projects/) | | AI Model Inference | NuGet [1.0.0-beta.5](https://www.nuget.org/packages/Azure.AI.Inference/1.0.0-beta.5) | [docs](/dotnet/api/overview/azure/AI.Inference-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.5](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Inference_1.0.0-beta.5/sdk/ai/Azure.AI.Inference/) | | Anomaly Detector | NuGet [3.0.0-preview.7](https://www.nuget.org/packages/Azure.AI.AnomalyDetector/3.0.0-preview.7) | [docs](/dotnet/api/overview/azure/AI.AnomalyDetector-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [3.0.0-preview.7](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.AnomalyDetector_3.0.0-preview.7/sdk/anomalydetector/Azure.AI.AnomalyDetector/) | @@ -90,7 +90,7 @@ | Playwright | NuGet [1.0.0](https://www.nuget.org/packages/Azure.Developer.Playwright/1.0.0) | [docs](/dotnet/api/overview/azure/Developer.Playwright-readme) | GitHub [1.0.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Developer.Playwright_1.0.0/sdk/loadtestservice/Azure.Developer.Playwright/) | | Playwright NUnit | NuGet [1.0.0](https://www.nuget.org/packages/Azure.Developer.Playwright.NUnit/1.0.0) | [docs](/dotnet/api/overview/azure/Developer.Playwright.NUnit-readme) | GitHub [1.0.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Developer.Playwright.NUnit_1.0.0/sdk/loadtestservice/Azure.Developer.Playwright.NUnit/) | | Programmable Connectivity | NuGet [1.0.0-beta.1](https://www.nuget.org/packages/Azure.Communication.ProgrammableConnectivity/1.0.0-beta.1) | | GitHub [1.0.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Communication.ProgrammableConnectivity_1.0.0-beta.1/sdk/communication/Azure.Communication.ProgrammableConnectivity/) | -| Provisioning | NuGet [1.3.0](https://www.nuget.org/packages/Azure.Provisioning/1.3.0)
NuGet [1.4.0-beta.2](https://www.nuget.org/packages/Azure.Provisioning/1.4.0-beta.2) | [docs](/dotnet/api/overview/azure/Provisioning-readme) | GitHub [1.3.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Provisioning_1.3.0/sdk/provisioning/Azure.Provisioning/)
GitHub [1.4.0-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Provisioning_1.4.0-beta.2/sdk/provisioning/Azure.Provisioning/) | +| Provisioning | NuGet [1.3.0](https://www.nuget.org/packages/Azure.Provisioning/1.3.0)
NuGet [1.4.0-beta.3](https://www.nuget.org/packages/Azure.Provisioning/1.4.0-beta.3) | [docs](/dotnet/api/overview/azure/Provisioning-readme) | GitHub [1.3.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Provisioning_1.3.0/sdk/provisioning/Azure.Provisioning/)
GitHub [1.4.0-beta.3](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Provisioning_1.4.0-beta.3/sdk/provisioning/Azure.Provisioning/) | | Provisioning - Resources | NuGet [0.2.0](https://www.nuget.org/packages/Azure.Provisioning.Resources/0.2.0) | [docs](/dotnet/api/overview/azure/Provisioning.Resources-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [0.2.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Provisioning.Resources_0.2.0/sdk/provisioning/Azure.Provisioning.Resources/) | | Purview Account | NuGet [1.0.0-beta.1](https://www.nuget.org/packages/Azure.Analytics.Purview.Account/1.0.0-beta.1) | [docs](/dotnet/api/overview/azure/Analytics.Purview.Account-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Analytics.Purview.Account_1.0.0-beta.1/sdk/purview/Azure.Analytics.Purview.Account/) | | Purview Administration | NuGet [1.0.0-beta.1](https://www.nuget.org/packages/Azure.Analytics.Purview.Administration/1.0.0-beta.1) | [docs](/dotnet/api/overview/azure/Analytics.Purview.Administration-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Analytics.Purview.Administration_1.0.0-beta.1/sdk/purview/Azure.Analytics.Purview.Administration/) | @@ -162,7 +162,7 @@ | Provisioning - Container Service | NuGet [1.0.0-beta.4](https://www.nuget.org/packages/Azure.Provisioning.ContainerService/1.0.0-beta.4) | [docs](/dotnet/api/overview/azure/Provisioning.ContainerService-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.4](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Provisioning.ContainerService_1.0.0-beta.4/sdk/provisioning/Azure.Provisioning.ContainerService/) | | Provisioning - CosmosDB | NuGet [1.0.0](https://www.nuget.org/packages/Azure.Provisioning.CosmosDB/1.0.0)
NuGet [1.1.0-beta.1](https://www.nuget.org/packages/Azure.Provisioning.CosmosDB/1.1.0-beta.1) | [docs](/dotnet/api/overview/azure/Provisioning.CosmosDB-readme) | GitHub [1.0.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Provisioning.CosmosDB_1.0.0/sdk/provisioning/Azure.Provisioning.CosmosDB/)
GitHub [1.1.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Provisioning.CosmosDB_1.1.0-beta.1/sdk/provisioning/Azure.Provisioning.CosmosDB/) | | Provisioning - Deployment | NuGet [1.0.0-beta.2](https://www.nuget.org/packages/Azure.Provisioning.Deployment/1.0.0-beta.2) | [docs](/dotnet/api/overview/azure/Provisioning.Deployment-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Provisioning.Deployment_1.0.0-beta.2/sdk/provisioning/Azure.Provisioning.Deployment/) | -| Provisioning - Dns | NuGet [1.0.0-beta.1](https://www.nuget.org/packages/Azure.Provisioning.Dns/1.0.0-beta.1) | [docs](/dotnet/api/overview/azure/Provisioning.Dns-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Provisioning.Dns_1.0.0-beta.1/sdk/provisioning/Azure.Provisioning.Dns/) | +| Provisioning - Dns | NuGet [1.0.0-beta.2](https://www.nuget.org/packages/Azure.Provisioning.Dns/1.0.0-beta.2) | [docs](/dotnet/api/overview/azure/Provisioning.Dns-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Provisioning.Dns_1.0.0-beta.2/sdk/provisioning/Azure.Provisioning.Dns/) | | Provisioning - Event Grid | NuGet [1.1.0](https://www.nuget.org/packages/Azure.Provisioning.EventGrid/1.1.0) | [docs](/dotnet/api/overview/azure/Provisioning.EventGrid-readme) | GitHub [1.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Provisioning.EventGrid_1.1.0/sdk/provisioning/Azure.Provisioning.EventGrid/) | | Provisioning - Event Hubs | NuGet [1.1.0](https://www.nuget.org/packages/Azure.Provisioning.EventHubs/1.1.0) | [docs](/dotnet/api/overview/azure/Provisioning.EventHubs-readme) | GitHub [1.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Provisioning.EventHubs_1.1.0/sdk/provisioning/Azure.Provisioning.EventHubs/) | | Provisioning - Frontdoor | NuGet [1.0.0-beta.1](https://www.nuget.org/packages/Azure.Provisioning.FrontDoor/1.0.0-beta.1) | [docs](/dotnet/api/overview/azure/Provisioning.FrontDoor-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Provisioning.FrontDoor_1.0.0-beta.1/sdk/provisioning/Azure.Provisioning.FrontDoor/) | @@ -218,6 +218,7 @@ | Resource Management - Compute Fleet | NuGet [1.0.0](https://www.nuget.org/packages/Azure.ResourceManager.ComputeFleet/1.0.0) | [docs](/dotnet/api/overview/azure/ResourceManager.ComputeFleet-readme) | GitHub [1.0.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.ComputeFleet_1.0.0/sdk/computefleet/Azure.ResourceManager.ComputeFleet/) | | Resource Management - Compute Schedule | NuGet [1.1.0](https://www.nuget.org/packages/Azure.ResourceManager.ComputeSchedule/1.1.0)
NuGet [1.2.0-beta.1](https://www.nuget.org/packages/Azure.ResourceManager.ComputeSchedule/1.2.0-beta.1) | [docs](/dotnet/api/overview/azure/ResourceManager.ComputeSchedule-readme) | GitHub [1.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.ComputeSchedule_1.1.0/sdk/computeschedule/Azure.ResourceManager.ComputeSchedule/)
GitHub [1.2.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.ComputeSchedule_1.2.0-beta.1/sdk/computeschedule/Azure.ResourceManager.ComputeSchedule/) | | Resource Management - Compute.Recommender | NuGet [1.0.0-beta.2](https://www.nuget.org/packages/Azure.ResourceManager.Compute.Recommender/1.0.0-beta.2) | [docs](/dotnet/api/overview/azure/ResourceManager.Compute.Recommender-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.Compute.Recommender_1.0.0-beta.2/sdk/computerecommender/Azure.ResourceManager.Compute.Recommender/) | +| Resource Management - Computelimit | NuGet [1.0.0-beta.1](https://www.nuget.org/packages/Azure.ResourceManager.ComputeLimit/1.0.0-beta.1) | [docs](/dotnet/api/overview/azure/ResourceManager.ComputeLimit-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.ComputeLimit_1.0.0-beta.1/sdk/computelimit/Azure.ResourceManager.ComputeLimit/) | | Resource Management - Confidential Ledger | NuGet [1.0.1](https://www.nuget.org/packages/Azure.ResourceManager.ConfidentialLedger/1.0.1)
NuGet [1.1.0-beta.6](https://www.nuget.org/packages/Azure.ResourceManager.ConfidentialLedger/1.1.0-beta.6) | [docs](/dotnet/api/overview/azure/ResourceManager.ConfidentialLedger-readme) | GitHub [1.0.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.ConfidentialLedger_1.0.1/sdk/confidentialledger/Azure.ResourceManager.ConfidentialLedger/)
GitHub [1.1.0-beta.6](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.ConfidentialLedger_1.1.0-beta.6/sdk/confidentialledger/Azure.ResourceManager.ConfidentialLedger/) | | Resource Management - Confluent | NuGet [1.2.1](https://www.nuget.org/packages/Azure.ResourceManager.Confluent/1.2.1) | [docs](/dotnet/api/overview/azure/ResourceManager.Confluent-readme) | GitHub [1.2.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.Confluent_1.2.1/sdk/confluent/Azure.ResourceManager.Confluent/) | | Resource Management - Connected VMware vSphere | NuGet [1.1.1](https://www.nuget.org/packages/Azure.ResourceManager.ConnectedVMwarevSphere/1.1.1) | [docs](/dotnet/api/overview/azure/ResourceManager.ConnectedVMwarevSphere-readme) | GitHub [1.1.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.ConnectedVMwarevSphere_1.1.1/sdk/connectedvmwarevsphere/Azure.ResourceManager.ConnectedVMwarevSphere/) | diff --git a/docs/core/additional-tools/dotnet-svcutil.xmlserializer-guide.md b/docs/core/additional-tools/dotnet-svcutil.xmlserializer-guide.md index e19e91f241945..3e45ab437f9ef 100644 --- a/docs/core/additional-tools/dotnet-svcutil.xmlserializer-guide.md +++ b/docs/core/additional-tools/dotnet-svcutil.xmlserializer-guide.md @@ -92,4 +92,4 @@ To use `dotnet-svcutil.xmlserializer` in a .NET Core console application: 6. Build the application by running `dotnet build`. If everything succeeds, an assembly named *MyWCFClient.XmlSerializers.dll* is generated in the output folder. If the tool failed to generate the assembly, you'll see warnings in the build output. -7. Start the WCF service by, for example, running `http://localhost:2561/Service1.svc` in the browser. Then start the client application, and it will automatically load and use the pre-generated serializers at run time. +7. Start the WCF service by, for example, running `http://localhost:2561/Service1.svc` in the browser. Then start the client application, and it will automatically load and use the pre-generated serializers at runtime. diff --git a/docs/core/additional-tools/xml-serializer-generator.md b/docs/core/additional-tools/xml-serializer-generator.md index 07a525f4869ff..7af4183e01201 100644 --- a/docs/core/additional-tools/xml-serializer-generator.md +++ b/docs/core/additional-tools/xml-serializer-generator.md @@ -83,7 +83,7 @@ The following instructions show you how to use XML Serializer Generator in a .NE dotnet run ``` - The app automatically loads and uses the pre-generated serializers at run time. + The app automatically loads and uses the pre-generated serializers at runtime. > [!TIP] > [`dotnet run`](../tools/dotnet-run.md) calls [`dotnet build`](../tools/dotnet-build.md) to ensure that the build targets have been built, and then calls `dotnet ` to run the target application. diff --git a/docs/core/compatibility/10.0.md b/docs/core/compatibility/10.0.md index 994060f75659e..1b3c5e71df340 100644 --- a/docs/core/compatibility/10.0.md +++ b/docs/core/compatibility/10.0.md @@ -26,7 +26,7 @@ If you're migrating an app to .NET 10, the breaking changes listed here might af | [IncludeOpenAPIAnalyzers property and MVC API analyzers are deprecated](aspnet-core/10/openapi-analyzers-deprecated.md) | Source incompatible | | [IPNetwork and ForwardedHeadersOptions.KnownNetworks are obsolete](aspnet-core/10/ipnetwork-knownnetworks-obsolete.md) | Source incompatible | | [Microsoft.Extensions.ApiDescription.Client package deprecated](aspnet-core/10/apidescription-client-deprecated.md) | Source incompatible | -| [Razor run-time compilation is obsolete](aspnet-core/10/razor-runtime-compilation-obsolete.md) | Source incompatible | +| [Razor runtime compilation is obsolete](aspnet-core/10/razor-runtime-compilation-obsolete.md) | Source incompatible | | [WebHostBuilder, IWebHost, and WebHost are obsolete](aspnet-core/10/webhostbuilder-deprecated.md) | Source incompatible | ## Containers diff --git a/docs/core/compatibility/aspnet-core/10/razor-runtime-compilation-obsolete.md b/docs/core/compatibility/aspnet-core/10/razor-runtime-compilation-obsolete.md index 80c409579cf26..a7e5fd65126cc 100644 --- a/docs/core/compatibility/aspnet-core/10/razor-runtime-compilation-obsolete.md +++ b/docs/core/compatibility/aspnet-core/10/razor-runtime-compilation-obsolete.md @@ -1,12 +1,12 @@ --- -title: "Breaking change: Razor run-time compilation is obsolete" -description: Learn about the breaking change in ASP.NET Core 10.0 where Razor run-time compilation APIs have been marked obsolete. +title: "Breaking change: Razor runtime compilation is obsolete" +description: Learn about the breaking change in ASP.NET Core 10.0 where Razor runtime compilation APIs have been marked obsolete. ms.date: 08/08/2025 --- -# Razor run-time compilation is obsolete +# Razor runtime compilation is obsolete -Razor run-time compilation is obsolete and is not recommended for production scenarios. For production scenarios, use the default build-time compilation. For development scenarios, use [Hot Reload](/aspnet/core/test/hot-reload) instead. +Razor runtime compilation is obsolete and is not recommended for production scenarios. For production scenarios, use the default build-time compilation. For development scenarios, use [Hot Reload](/aspnet/core/test/hot-reload) instead. ## Version introduced @@ -14,13 +14,13 @@ Razor run-time compilation is obsolete and is not recommended for production sce ## Previous behavior -Previously, you could use [Razor run-time compilation](/aspnet/core/mvc/views/view-compilation) to recompile `.cshtml` files while the application was running. This meant you didn't need to restart the application for changes to take effect. +Previously, you could use [Razor runtime compilation](/aspnet/core/mvc/views/view-compilation) to recompile `.cshtml` files while the application was running. This meant you didn't need to restart the application for changes to take effect. ## New behavior Starting in .NET 10, use of the [affected APIs](#affected-apis) produces a compiler warning with diagnostic ID `ASPDEPR003`: -> warning ASPDEPR003: Razor run-time compilation is obsolete and is not recommended for production scenarios. For production scenarios, use the default build time compilation. For development scenarios, use Hot Reload instead. For more information, visit . +> warning ASPDEPR003: Razor runtime compilation is obsolete and is not recommended for production scenarios. For production scenarios, use the default build time compilation. For development scenarios, use Hot Reload instead. For more information, visit . ## Type of breaking change @@ -28,7 +28,7 @@ This change can affect [source compatibility](../../categories.md#source-compati ## Reason for change -Razor run-time compilation has been replaced by [Hot Reload](/aspnet/core/test/hot-reload), which has been the recommended approach for a few years now. This change makes it clearer that Razor run-time compilation doesn't get support for new features and should no longer be used. +Razor runtime compilation has been replaced by [Hot Reload](/aspnet/core/test/hot-reload), which has been the recommended approach for a few years now. This change makes it clearer that Razor runtime compilation doesn't get support for new features and should no longer be used. ## Recommended action diff --git a/docs/core/compatibility/aspnet-core/5.0/kestrel-configuration-changes-at-run-time-detected-by-default.md b/docs/core/compatibility/aspnet-core/5.0/kestrel-configuration-changes-at-run-time-detected-by-default.md index 3af172cbe60bf..494f773811e20 100644 --- a/docs/core/compatibility/aspnet-core/5.0/kestrel-configuration-changes-at-run-time-detected-by-default.md +++ b/docs/core/compatibility/aspnet-core/5.0/kestrel-configuration-changes-at-run-time-detected-by-default.md @@ -1,12 +1,12 @@ --- -title: "Breaking change: Kestrel: Configuration changes at run time detected by default" -description: "Learn about the breaking change in ASP.NET Core 5.0 titled Kestrel: Configuration changes at run time detected by default" +title: "Breaking change: Kestrel: Configuration changes at runtime detected by default" +description: "Learn about the breaking change in ASP.NET Core 5.0 titled Kestrel: Configuration changes at runtime detected by default" ms.author: scaddie ms.date: 10/01/2020 --- -# Kestrel: Configuration changes at run time detected by default +# Kestrel: Configuration changes at runtime detected by default -Kestrel now reacts to changes made to the `Kestrel` section of the project's `IConfiguration` instance (for example, *appsettings.json*) at run time. To learn more about how to configure Kestrel using *appsettings.json*, see the *appsettings.json* example in [Endpoint configuration](/aspnet/core/fundamentals/servers/kestrel#endpoint-configuration). +Kestrel now reacts to changes made to the `Kestrel` section of the project's `IConfiguration` instance (for example, *appsettings.json*) at runtime. To learn more about how to configure Kestrel using *appsettings.json*, see the *appsettings.json* example in [Endpoint configuration](/aspnet/core/fundamentals/servers/kestrel#endpoint-configuration). Kestrel will bind, unbind, and rebind endpoints as necessary to react to these configuration changes. @@ -18,9 +18,9 @@ For discussion, see issue [dotnet/aspnetcore#22807](https://github.com/dotnet/as ## Old behavior -Before ASP.NET Core 5.0 Preview 6, Kestrel didn't support changing configuration at run time. +Before ASP.NET Core 5.0 Preview 6, Kestrel didn't support changing configuration at runtime. -In ASP.NET Core 5.0 Preview 6, you could opt in to the now-default behavior of reacting to configuration changes at run time. Opting in required binding Kestrel's configuration manually: +In ASP.NET Core 5.0 Preview 6, you could opt in to the now-default behavior of reacting to configuration changes at runtime. Opting in required binding Kestrel's configuration manually: ```csharp using Microsoft.AspNetCore.Hosting; @@ -48,17 +48,17 @@ public class Program ## New behavior -Kestrel reacts to configuration changes at run time by default. To support that change, calls `KestrelServerOptions.Configure(IConfiguration, bool)` with `reloadOnChange: true` by default. +Kestrel reacts to configuration changes at runtime by default. To support that change, calls `KestrelServerOptions.Configure(IConfiguration, bool)` with `reloadOnChange: true` by default. ## Reason for change -The change was made to support endpoint reconfiguration at run time without completely restarting the server. Unlike with a full server restart, unchanged endpoints aren't unbound even temporarily. +The change was made to support endpoint reconfiguration at runtime without completely restarting the server. Unlike with a full server restart, unchanged endpoints aren't unbound even temporarily. ## Recommended action -* For most scenarios in which Kestrel's default configuration section doesn't change at run time, this change has no impact and no action is needed. -* For scenarios in which Kestrel's default configuration section does change at run time and Kestrel should react to it, this is now the default behavior. -* For scenarios in which Kestrel's default configuration section changes at run time and Kestrel shouldn't react to it, you can opt out as follows: +* For most scenarios in which Kestrel's default configuration section doesn't change at runtime, this change has no impact and no action is needed. +* For scenarios in which Kestrel's default configuration section does change at runtime and Kestrel should react to it, this is now the default behavior. +* For scenarios in which Kestrel's default configuration section changes at runtime and Kestrel shouldn't react to it, you can opt out as follows: ```csharp using Microsoft.AspNetCore.Hosting; diff --git a/docs/core/compatibility/aspnet-core/5.0/localization-members-removed.md b/docs/core/compatibility/aspnet-core/5.0/localization-members-removed.md index 6e4f615ab5f43..de117630a5b42 100644 --- a/docs/core/compatibility/aspnet-core/5.0/localization-members-removed.md +++ b/docs/core/compatibility/aspnet-core/5.0/localization-members-removed.md @@ -24,7 +24,7 @@ The `ResourceManagerWithCultureStringLocalizer` class and the `ResourceManagerSt ## Reason for change -The `ResourceManagerWithCultureStringLocalizer` class and `ResourceManagerStringLocalizer.WithCulture` method were often sources of confusion for users of localization. The confusion was especially high when creating a custom implementation. This class and method give consumers the impression that an `IStringLocalizer` instance is expected to be "per-language, per-resource". In reality, the instance should only be "per-resource". At run time, the property determines the language to be used. +The `ResourceManagerWithCultureStringLocalizer` class and `ResourceManagerStringLocalizer.WithCulture` method were often sources of confusion for users of localization. The confusion was especially high when creating a custom implementation. This class and method give consumers the impression that an `IStringLocalizer` instance is expected to be "per-language, per-resource". In reality, the instance should only be "per-resource". At runtime, the property determines the language to be used. ## Recommended action diff --git a/docs/core/compatibility/aspnet-core/6.0/assemblies-removed-from-shared-framework.md b/docs/core/compatibility/aspnet-core/6.0/assemblies-removed-from-shared-framework.md index b21b0e3f53024..58cf58fe97ef5 100644 --- a/docs/core/compatibility/aspnet-core/6.0/assemblies-removed-from-shared-framework.md +++ b/docs/core/compatibility/aspnet-core/6.0/assemblies-removed-from-shared-framework.md @@ -27,7 +27,7 @@ Applications could use APIs provided by these libraries by referencing the [Micr ## New behavior -If you use APIs from the affected assemblies without having a [PackageReference](../../../project-sdk/msbuild-props.md#packagereference) in your project file, you might see run-time errors. For example, an application that uses reflection to access APIs from one of these assemblies without adding an explicit reference to the package will have run-time errors. The `PackageReference` ensures that the assemblies are present as part of the application output. +If you use APIs from the affected assemblies without having a [PackageReference](../../../project-sdk/msbuild-props.md#packagereference) in your project file, you might see runtime errors. For example, an application that uses reflection to access APIs from one of these assemblies without adding an explicit reference to the package will have runtime errors. The `PackageReference` ensures that the assemblies are present as part of the application output. For discussion, see . diff --git a/docs/core/compatibility/aspnet-core/6.0/preservecompilationcontext-not-set-by-default.md b/docs/core/compatibility/aspnet-core/6.0/preservecompilationcontext-not-set-by-default.md index c9412da6a68b7..3bc4cd7dd396f 100644 --- a/docs/core/compatibility/aspnet-core/6.0/preservecompilationcontext-not-set-by-default.md +++ b/docs/core/compatibility/aspnet-core/6.0/preservecompilationcontext-not-set-by-default.md @@ -6,7 +6,7 @@ ms.date: 04/22/2021 --- # PreserveCompilationContext not configured by default -[`PreserveCompilationContext`](../../../project-sdk/msbuild-props.md#preservecompilationcontext) is an MSBuild property that causes .NET Core projects to emit additional content to the application's dependency (.deps) file about how the app was compiled. This is primarily used to support run-time compilation scenarios. +[`PreserveCompilationContext`](../../../project-sdk/msbuild-props.md#preservecompilationcontext) is an MSBuild property that causes .NET Core projects to emit additional content to the application's dependency (.deps) file about how the app was compiled. This is primarily used to support runtime compilation scenarios. Prior to .NET 6, `PreserveCompilationContext` was set to `true` for all apps that target the Razor (Microsoft.NET.Sdk.Razor) and Web (Microsoft.NET.Sdk.Web) SDKs. Starting in .NET 6, this property is no longer configured by default. However, packages such as Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation configure this property as required. diff --git a/docs/core/compatibility/aspnet-core/9.0/middleware-constructors.md b/docs/core/compatibility/aspnet-core/9.0/middleware-constructors.md index 00e9668c4c760..29d159b4759eb 100644 --- a/docs/core/compatibility/aspnet-core/9.0/middleware-constructors.md +++ b/docs/core/compatibility/aspnet-core/9.0/middleware-constructors.md @@ -1,12 +1,12 @@ --- title: "Breaking change: Middleware types with multiple constructors" -description: Learn about the breaking change in ASP.NET Core 9 where having multiple constructors in a middleware type can cause an exception at run time. +description: Learn about the breaking change in ASP.NET Core 9 where having multiple constructors in a middleware type can cause an exception at runtime. ms.date: 11/6/2024 --- # Middleware types with multiple constructors -Previously, when a middleware type with multiple satisfiable constructors was instantiated from the dependency injection container, the one with the most parameters was used. Now that only happens if the dependency injection container implements . If it doesn't, an exception is thrown at run time. +Previously, when a middleware type with multiple satisfiable constructors was instantiated from the dependency injection container, the one with the most parameters was used. Now that only happens if the dependency injection container implements . If it doesn't, an exception is thrown at runtime. ## Version introduced diff --git a/docs/core/compatibility/code-analysis/5.0/ca1416-platform-compatibility-analyzer.md b/docs/core/compatibility/code-analysis/5.0/ca1416-platform-compatibility-analyzer.md index 95bace275ac29..96357a1409c88 100644 --- a/docs/core/compatibility/code-analysis/5.0/ca1416-platform-compatibility-analyzer.md +++ b/docs/core/compatibility/code-analysis/5.0/ca1416-platform-compatibility-analyzer.md @@ -13,7 +13,7 @@ Starting in .NET 5, the .NET SDK includes [.NET source code analyzers](../../../ Rule [CA1416](/visualstudio/code-quality/ca1416), the platform compatibility analyzer, works hand-in-hand with some other features that are new in .NET 5. .NET 5 introduces the and , which let you specify the platforms that an API *is* or *isn't* supported on. In the absence of these attributes, an API is assumed to be supported on all platforms. These attributes have been applied to platform-specific APIs in the core .NET libraries. -In projects that target platforms for which APIs that they use aren't available, rule [CA1416](/visualstudio/code-quality/ca1416) flags any platform-specific API call where the platform context isn't verified. Most of the APIs that are now decorated with the and attributes throw exceptions when they're invoked on an unsupported operating system. Now that these APIs are marked as platform-specific, rule [CA1416](/visualstudio/code-quality/ca1416) helps you prevent run-time exceptions by adding OS checks to your call sites. +In projects that target platforms for which APIs that they use aren't available, rule [CA1416](/visualstudio/code-quality/ca1416) flags any platform-specific API call where the platform context isn't verified. Most of the APIs that are now decorated with the and attributes throw exceptions when they're invoked on an unsupported operating system. Now that these APIs are marked as platform-specific, rule [CA1416](/visualstudio/code-quality/ca1416) helps you prevent runtime exceptions by adding OS checks to your call sites. ## Examples @@ -65,7 +65,7 @@ public void PlayCMajor() } ``` -Or, if you don't want the overhead of an additional `if` statement at run time, call instead: +Or, if you don't want the overhead of an additional `if` statement at runtime, call instead: ```csharp public void PlayCMajor() diff --git a/docs/core/compatibility/code-analysis/5.0/ca2247-ctor-arg-should-be-taskcreationoptions.md b/docs/core/compatibility/code-analysis/5.0/ca2247-ctor-arg-should-be-taskcreationoptions.md index b8ffef3f4c6a1..10c9e5d9d63ce 100644 --- a/docs/core/compatibility/code-analysis/5.0/ca2247-ctor-arg-should-be-taskcreationoptions.md +++ b/docs/core/compatibility/code-analysis/5.0/ca2247-ctor-arg-should-be-taskcreationoptions.md @@ -11,7 +11,7 @@ ms.date: 09/03/2020 Starting in .NET 5, the .NET SDK includes [.NET source code analyzers](../../../../fundamentals/code-analysis/overview.md). Several of these rules are enabled, by default, including [CA2247](/visualstudio/code-quality/ca2247). If your project contains code that violates this rule and is configured to treat warnings as errors, this change could break your build. -Rule CA2247 finds calls to the constructor that pass an argument of type . The type has a constructor that accepts a value, and another constructor that accepts an . If you accidentally pass a value instead of a value, the constructor with the parameter is called at run time. Your code will compile and run but won't have the intended behavior. +Rule CA2247 finds calls to the constructor that pass an argument of type . The type has a constructor that accepts a value, and another constructor that accepts an . If you accidentally pass a value instead of a value, the constructor with the parameter is called at runtime. Your code will compile and run but won't have the intended behavior. ## Version introduced diff --git a/docs/core/compatibility/configuration/7.0/diagnostics-config-section.md b/docs/core/compatibility/configuration/7.0/diagnostics-config-section.md index 7ceb90015a75f..4c38326af8625 100644 --- a/docs/core/compatibility/configuration/7.0/diagnostics-config-section.md +++ b/docs/core/compatibility/configuration/7.0/diagnostics-config-section.md @@ -7,7 +7,7 @@ ms.date: 11/03/2022 For applications that have an *app.config* file, the `` entry is no longer allowed to contain a `
` entry. If present, you must remove the entry. -Having a `
` entry throws the following run-time exception when the configuration system is first used: +Having a `
` entry throws the following runtime exception when the configuration system is first used: > **ConfigurationErrorsException: Section or group name 'system.diagnostics' is already defined. Updates to this may only occur at the configuration level where it is defined.** diff --git a/docs/core/compatibility/core-libraries/10.0/asyncenumerable.md b/docs/core/compatibility/core-libraries/10.0/asyncenumerable.md index 26b07ddf819ff..131f9aa712292 100644 --- a/docs/core/compatibility/core-libraries/10.0/asyncenumerable.md +++ b/docs/core/compatibility/core-libraries/10.0/asyncenumerable.md @@ -54,7 +54,7 @@ If `System.Linq.Async` is consumed indirectly via another package, avoid ambigui ``` - Use this configuration only if you're certain no dependencies require System.Linq.Async at run time. + Use this configuration only if you're certain no dependencies require System.Linq.Async at runtime. Most consuming code should be compatible without changes, but some call sites might need updates to refer to newer names and signatures. For example, a `Select` call like `e.Select(i => i * 2)` will work the same before and after. However, the call `e.SelectAwait(async (int i, CancellationToken ct) => i * 2)` will need to be changed to use `Select` instead of `SelectAwait`, as in `e.Select(async (int i, CancellationToken ct) => i * 2)`. diff --git a/docs/core/compatibility/core-libraries/10.0/csharp-overload-resolution.md b/docs/core/compatibility/core-libraries/10.0/csharp-overload-resolution.md index 96c44ab072dba..4d9f8612ed823 100644 --- a/docs/core/compatibility/core-libraries/10.0/csharp-overload-resolution.md +++ b/docs/core/compatibility/core-libraries/10.0/csharp-overload-resolution.md @@ -14,7 +14,7 @@ In C# 13 and earlier, an extension method taking a `ReadOnlySpan` or `Span ## New behavior -In C# 14 and later, methods with `ReadOnlySpan` or `Span` parameters can participate in type inference or be used as extension methods in more scenarios. This makes span-based methods like the ones from the `System.MemoryExtensions` class bind in more scenarios, including inside Expression lambdas where they will cause run-time exceptions when compiled with interpretation. +In C# 14 and later, methods with `ReadOnlySpan` or `Span` parameters can participate in type inference or be used as extension methods in more scenarios. This makes span-based methods like the ones from the `System.MemoryExtensions` class bind in more scenarios, including inside Expression lambdas where they will cause runtime exceptions when compiled with interpretation. ## Version introduced diff --git a/docs/core/compatibility/core-libraries/10.0/defaultvalueattribute-dynamically-accessed-members.md b/docs/core/compatibility/core-libraries/10.0/defaultvalueattribute-dynamically-accessed-members.md index 76ecf80f614c8..813956551696b 100644 --- a/docs/core/compatibility/core-libraries/10.0/defaultvalueattribute-dynamically-accessed-members.md +++ b/docs/core/compatibility/core-libraries/10.0/defaultvalueattribute-dynamically-accessed-members.md @@ -7,7 +7,7 @@ ai-usage: ai-assisted # `DynamicallyAccessedMembers` annotation removed from `DefaultValueAttribute` ctor -The constructor is no longer annotated with . This constructor is not supported with trimming and throws an exception if reached at run time in a trimmed app. +The constructor is no longer annotated with . This constructor is not supported with trimming and throws an exception if reached at runtime in a trimmed app. ## Version introduced @@ -15,11 +15,11 @@ The constructor accepted `null` for the `stem` parameter without any compile-time or run-time warnings or errors. +Previously, the constructor accepted `null` for the `stem` parameter without any compile-time or runtime warnings or errors. ```csharp // Allowed in previous versions. @@ -29,7 +29,7 @@ The constructor yields a compile-time warning. And, if `null` is passed in, a run-time is thrown. +Starting in .NET 10, passing a `null` or possibly-null value to the `stem` argument in the constructor yields a compile-time warning. And, if `null` is passed in, a runtime is thrown. The property is now annotated to indicate that the value won't be null if `IsSuccessful` is `true`. diff --git a/docs/core/compatibility/core-libraries/5.0/code-access-security-apis-obsolete.md b/docs/core/compatibility/core-libraries/5.0/code-access-security-apis-obsolete.md index 83006fb85b0ff..53d2d554f68a6 100644 --- a/docs/core/compatibility/core-libraries/5.0/code-access-security-apis-obsolete.md +++ b/docs/core/compatibility/core-libraries/5.0/code-access-security-apis-obsolete.md @@ -32,18 +32,18 @@ public void DoSomething() } ``` -Additionally, programmatic calls to expansive APIs (`Assert`) always succeed, while programmatic calls to restrictive APIs (`Deny`, `PermitOnly`) always throw an exception at run time. ( is an exception to this rule. See the [Recommended action](#cas-action) section below.) +Additionally, programmatic calls to expansive APIs (`Assert`) always succeed, while programmatic calls to restrictive APIs (`Deny`, `PermitOnly`) always throw an exception at runtime. ( is an exception to this rule. See the [Recommended action](#cas-action) section below.) ```csharp public void DoAssert() { - // The line below has no effect at run time. + // The line below has no effect at runtime. new SocketPermission(PermissionState.Unrestricted).Assert(); } public void DoDeny() { - // The line below throws PlatformNotSupportedException at run time. + // The line below throws PlatformNotSupportedException at runtime. new SocketPermission(PermissionState.Unrestricted).Deny(); } ``` @@ -59,13 +59,13 @@ public void DoSomething() } ``` -This is a compile-time only change. There is no run-time change from previous versions of .NET Core. Methods that perform no operation in .NET Core 2.x - 3.x will continue to perform no operation at run time in .NET 5 and later. Methods that throw in .NET Core 2.x - 3.x will continue to throw a at run time in .NET 5 and later. +This is a compile-time only change. There is no runtime change from previous versions of .NET Core. Methods that perform no operation in .NET Core 2.x - 3.x will continue to perform no operation at runtime in .NET 5 and later. Methods that throw in .NET Core 2.x - 3.x will continue to throw a at runtime in .NET 5 and later. ## Reason for change [Code access security (CAS)](/previous-versions/dotnet/framework/code-access-security/code-access-security) is an unsupported legacy technology. The infrastructure to enable CAS exists only in .NET Framework 2.x - 4.x, but is deprecated and not receiving servicing or security fixes. -Due to CAS's deprecation, the [supporting infrastructure was not brought forward to .NET Core](../../../porting/net-framework-tech-unavailable.md) or .NET 5+. However, the APIs were brought forward so that apps could cross-compile against .NET Framework and .NET Core. This led to "fail open" scenarios, where some CAS-related APIs exist and are callable but perform no action at run time. This can lead to security issues for components that expect the runtime to honor CAS-related attributes or programmatic API calls. To better communicate that the runtime doesn't respect these attributes or APIs, we have obsoleted the majority of them in .NET 5.0. +Due to CAS's deprecation, the [supporting infrastructure was not brought forward to .NET Core](../../../porting/net-framework-tech-unavailable.md) or .NET 5+. However, the APIs were brought forward so that apps could cross-compile against .NET Framework and .NET Core. This led to "fail open" scenarios, where some CAS-related APIs exist and are callable but perform no action at runtime. This can lead to security issues for components that expect the runtime to honor CAS-related attributes or programmatic API calls. To better communicate that the runtime doesn't respect these attributes or APIs, we have obsoleted the majority of them in .NET 5.0. ## Version introduced @@ -105,7 +105,7 @@ Due to CAS's deprecation, the [supporting infrastructure was not brought forward } ``` -- If you're demanding any permission (except ), remove the demand. All demands will succeed at run time. +- If you're demanding any permission (except ), remove the demand. All demands will succeed at runtime. ```csharp // REMOVE the attribute below; it will always succeed. diff --git a/docs/core/compatibility/core-libraries/5.0/global-assembly-cache-apis-obsolete.md b/docs/core/compatibility/core-libraries/5.0/global-assembly-cache-apis-obsolete.md index 906c70344249e..f3cce640a9063 100644 --- a/docs/core/compatibility/core-libraries/5.0/global-assembly-cache-apis-obsolete.md +++ b/docs/core/compatibility/core-libraries/5.0/global-assembly-cache-apis-obsolete.md @@ -25,7 +25,7 @@ Assembly asm = typeof(object).Assembly; Console.WriteLine(asm.GlobalAssemblyCache); ``` -In .NET 5 and later versions, the property continues to always return `false`. However, the property getter is also marked as obsolete to indicate to callers that they should stop accessing the property. Libraries and apps should not use the API to make determinations about run-time behavior, as it always returns `false` in .NET Core and .NET 5 and later versions. +In .NET 5 and later versions, the property continues to always return `false`. However, the property getter is also marked as obsolete to indicate to callers that they should stop accessing the property. Libraries and apps should not use the API to make determinations about runtime behavior, as it always returns `false` in .NET Core and .NET 5 and later versions. ```csharp Assembly asm = typeof(object).Assembly; @@ -33,7 +33,7 @@ Assembly asm = typeof(object).Assembly; Console.WriteLine(asm.GlobalAssemblyCache); ``` -This is a compile-time only change. There is no run-time change from previous versions of .NET Core. +This is a compile-time only change. There is no runtime change from previous versions of .NET Core. ## Reason for change @@ -45,7 +45,7 @@ The global assembly cache (GAC) does not exist as a concept in .NET Core and .NE ## Recommended action -- If your application queries the property, consider removing the call. If you use the value to choose between an "assembly in the GAC"-flow vs. an "assembly not in the GAC"-flow at run time, reconsider whether the flow still makes sense for a .NET Core or .NET 5+ application. +- If your application queries the property, consider removing the call. If you use the value to choose between an "assembly in the GAC"-flow vs. an "assembly not in the GAC"-flow at runtime, reconsider whether the flow still makes sense for a .NET Core or .NET 5+ application. - If you must continue to use the obsolete APIs, you can suppress the `SYSLIB0005` warning in code. diff --git a/docs/core/compatibility/core-libraries/5.0/os-platform-attributes-renamed.md b/docs/core/compatibility/core-libraries/5.0/os-platform-attributes-renamed.md index 86c6fdab81757..29abb40c478e0 100644 --- a/docs/core/compatibility/core-libraries/5.0/os-platform-attributes-renamed.md +++ b/docs/core/compatibility/core-libraries/5.0/os-platform-attributes-renamed.md @@ -38,7 +38,7 @@ For .NET 5 RC1, an additional feature was added to the platform compatibility an ## Recommended action -When you retarget your project from .NET 5 Preview 8 to .NET 5 RC1, you might encounter build or run-time errors due to these changes. For example, the renaming of `MinimumOSPlatformAttribute` is likely to produce errors, because the attribute is applied to platform-specific assemblies at build time, and old build artifacts will still reference the old API name. +When you retarget your project from .NET 5 Preview 8 to .NET 5 RC1, you might encounter build or runtime errors due to these changes. For example, the renaming of `MinimumOSPlatformAttribute` is likely to produce errors, because the attribute is applied to platform-specific assemblies at build time, and old build artifacts will still reference the old API name. Example build-time errors: @@ -46,7 +46,7 @@ Example build-time errors: - **error CS0246: The type or namespace name 'RemovedInOSPlatformAttribute' could not be found (are you missing a using directive or an assembly reference?)** - **error CS0246: The type or namespace name 'ObsoletedInOSPlatformAttribute' could not be found (are you missing a using directive or an assembly reference?)** -Example run-time error: +Example runtime error: **Unhandled exception. System.TypeLoadException: Could not load type 'System.Runtime.Versioning.MinimumOSPlatformAttribute' from assembly 'System.Runtime, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.** diff --git a/docs/core/compatibility/core-libraries/5.0/platformabstractions-package-removed.md b/docs/core/compatibility/core-libraries/5.0/platformabstractions-package-removed.md index 129436318f570..663acec131bca 100644 --- a/docs/core/compatibility/core-libraries/5.0/platformabstractions-package-removed.md +++ b/docs/core/compatibility/core-libraries/5.0/platformabstractions-package-removed.md @@ -36,7 +36,7 @@ The scenarios enabled by the and | > [!NOTE] - > Most use cases for `RuntimeEnvironment.OperatingSystem` and `RuntimeEnvironment.OperatingSystemVersion` are for display purposes, for example, displaying to a user, logging, and telemetry. It's not recommended to make run-time decisions based on an operating system (OS) version. now [returns the correct version](environment-osversion-returns-correct-version.md) for Windows and macOS operating systems. However, for most Unix distributions, what is considered to be the "OS version" is not as straightforward. For example, it could be the Linux kernel version, or it could be the distro version. For most Unix platforms, and return the version that's returned by `uname`. To get the Linux distro name and version information, the recommended approach is to read the */etc/os-release* file. + > Most use cases for `RuntimeEnvironment.OperatingSystem` and `RuntimeEnvironment.OperatingSystemVersion` are for display purposes, for example, displaying to a user, logging, and telemetry. It's not recommended to make runtime decisions based on an operating system (OS) version. now [returns the correct version](environment-osversion-returns-correct-version.md) for Windows and macOS operating systems. However, for most Unix distributions, what is considered to be the "OS version" is not as straightforward. For example, it could be the Linux kernel version, or it could be the distro version. For most Unix platforms, and return the version that's returned by `uname`. To get the Linux distro name and version information, the recommended approach is to read the */etc/os-release* file. ## Affected APIs diff --git a/docs/core/compatibility/core-libraries/5.0/remoting-apis-obsolete.md b/docs/core/compatibility/core-libraries/5.0/remoting-apis-obsolete.md index 97ed715c52371..efba349addf74 100644 --- a/docs/core/compatibility/core-libraries/5.0/remoting-apis-obsolete.md +++ b/docs/core/compatibility/core-libraries/5.0/remoting-apis-obsolete.md @@ -16,9 +16,9 @@ The following remoting APIs are marked obsolete. | | 5.0 RC1 | | | 5.0 RC1 | -In .NET Framework 2.x - 4.x, the and methods control the lifetime of instances involved with .NET remoting. In .NET Core 2.x- 3.x, these methods always throw a at run time. +In .NET Framework 2.x - 4.x, the and methods control the lifetime of instances involved with .NET remoting. In .NET Core 2.x- 3.x, these methods always throw a at runtime. -In .NET 5 and later versions, the and methods are marked obsolete as warning, but continue to throw a at run time. +In .NET 5 and later versions, the and methods are marked obsolete as warning, but continue to throw a at runtime. ```csharp // MemoryStream, like all Stream instances, subclasses MarshalByRefObject. @@ -27,7 +27,7 @@ MemoryStream stream = new MemoryStream(); obj.InitializeLifetimeService(); ``` -This is a compile-time only change. There is no run-time change from previous versions of .NET Core. +This is a compile-time only change. There is no runtime change from previous versions of .NET Core. ## Reason for change @@ -65,7 +65,7 @@ To help steer developers away from these APIs, we are obsoleting selected remoti ``` - Suppressing `SYSLIB0010` disables only the remoting API obsoletion warnings. It does not disable any other warnings. Additionally, it doesn't change the hardcoded run-time behavior of always throwing . + Suppressing `SYSLIB0010` disables only the remoting API obsoletion warnings. It does not disable any other warnings. Additionally, it doesn't change the hardcoded runtime behavior of always throwing . ## Affected APIs diff --git a/docs/core/compatibility/core-libraries/5.0/thread-abort-obsolete.md b/docs/core/compatibility/core-libraries/5.0/thread-abort-obsolete.md index 8117a9932a1cf..31112ffc9094b 100644 --- a/docs/core/compatibility/core-libraries/5.0/thread-abort-obsolete.md +++ b/docs/core/compatibility/core-libraries/5.0/thread-abort-obsolete.md @@ -9,7 +9,7 @@ The APIs ar ## Change description -Previously, calls to did not produce compile-time warnings, however, the method did throw a at run time. +Previously, calls to did not produce compile-time warnings, however, the method did throw a at runtime. Starting in .NET 5, is marked obsolete as warning. Calling this method produces compiler warning `SYSLIB0006`. The implementation of the method is unchanged, and it continues to throw a . diff --git a/docs/core/compatibility/core-libraries/6.0/parameter-name-changes.md b/docs/core/compatibility/core-libraries/6.0/parameter-name-changes.md index 1477ead907fdc..f488b6440485a 100644 --- a/docs/core/compatibility/core-libraries/6.0/parameter-name-changes.md +++ b/docs/core/compatibility/core-libraries/6.0/parameter-name-changes.md @@ -61,7 +61,7 @@ The following table shows the APIs and parameter names that changed. In addition If you encounter a compiler error due to a parameter name change, update the parameter name accordingly. -If you use run-time reflection to inspect methods and took a dependency on the parameter names, update the code to use the new parameter names. +If you use runtime reflection to inspect methods and took a dependency on the parameter names, update the code to use the new parameter names. ## Affected APIs diff --git a/docs/core/compatibility/core-libraries/6.0/securitycontext-obsolete.md b/docs/core/compatibility/core-libraries/6.0/securitycontext-obsolete.md index 7e0b6b1d49d2d..d49b6d234b425 100644 --- a/docs/core/compatibility/core-libraries/6.0/securitycontext-obsolete.md +++ b/docs/core/compatibility/core-libraries/6.0/securitycontext-obsolete.md @@ -12,7 +12,7 @@ ms.date: 08/16/2021 ## Old behavior -Prior to .NET 6, the type was not marked obsolete, however, all of its public members throw a at run time. +Prior to .NET 6, the type was not marked obsolete, however, all of its public members throw a at runtime. ## New behavior @@ -28,7 +28,7 @@ This change can affect [source compatibility](../../categories.md#source-compati ## Reason for change -All of the public members of throw a at run time. The is part of [Code access security (CAS)](/previous-versions/dotnet/framework/code-access-security/code-access-security), which is an unsupported legacy technology. +All of the public members of throw a at runtime. The is part of [Code access security (CAS)](/previous-versions/dotnet/framework/code-access-security/code-access-security), which is an unsupported legacy technology. ## Recommended action diff --git a/docs/core/compatibility/core-libraries/6.0/stringbuilder-append-evaluation-order.md b/docs/core/compatibility/core-libraries/6.0/stringbuilder-append-evaluation-order.md index 7a20d37860424..894cf61bfc1ae 100644 --- a/docs/core/compatibility/core-libraries/6.0/stringbuilder-append-evaluation-order.md +++ b/docs/core/compatibility/core-libraries/6.0/stringbuilder-append-evaluation-order.md @@ -1,6 +1,6 @@ --- title: "Breaking change: New StringBuilder.Append overloads" -description: Learn about the .NET 6 breaking change where new overloads were added to StringBuilder.Append and StringBuilder.AppendLine that may result in different run-time behavior. +description: Learn about the .NET 6 breaking change where new overloads were added to StringBuilder.Append and StringBuilder.AppendLine that may result in different runtime behavior. ms.date: 10/14/2021 --- # StringBuilder.Append overloads and evaluation order @@ -43,7 +43,7 @@ stringBuilder.Append(ref handler); This means `a` is evaluated and appended to the builder, and then `b` is evaluated and appended to the builder. -If, for example, either `a` or `b` is itself the builder, as shown in the following code, the new evaluation order can result in different behavior at run time. +If, for example, either `a` or `b` is itself the builder, as shown in the following code, the new evaluation order can result in different behavior at runtime. ```csharp stringBuilder.Append($"{a} {stringBuilder}"); diff --git a/docs/core/compatibility/core-libraries/6.0/strong-name-signing-exceptions.md b/docs/core/compatibility/core-libraries/6.0/strong-name-signing-exceptions.md index 7f5183a6d27e9..7a10a26703cd0 100644 --- a/docs/core/compatibility/core-libraries/6.0/strong-name-signing-exceptions.md +++ b/docs/core/compatibility/core-libraries/6.0/strong-name-signing-exceptions.md @@ -5,7 +5,7 @@ ms.date: 05/31/2022 --- # Strong-name APIs throw PlatformNotSupportedException -A few [APIs](#affected-apis) that aren't supported in .NET/.NET Core but didn't do anything when accessed have been changed to now throw a at run time. Previously, using these APIs would eventually result in a run-time exception further along; the exception is now thrown when the type is instantiated or first accessed. +A few [APIs](#affected-apis) that aren't supported in .NET/.NET Core but didn't do anything when accessed have been changed to now throw a at runtime. Previously, using these APIs would eventually result in a runtime exception further along; the exception is now thrown when the type is instantiated or first accessed. ## Previous behavior @@ -13,7 +13,7 @@ In previous versions, calling at run time. +Starting in .NET 6, each of the three affected APIs throws a at runtime. ## Version introduced @@ -25,7 +25,7 @@ This change can affect [binary compatibility](../../categories.md#binary-compati ## Reason for change -Previously, an application that called the API compiled and ran, but as soon as the instance was used in any code path, it threw a run-time exception. To make it more explicit that this scenario is unsupported, the exception-throwing logic was moved into the instance constructor. In case no instances are created, the exception is also thrown in public entry points that return this type, that is, . +Previously, an application that called the API compiled and ran, but as soon as the instance was used in any code path, it threw a runtime exception. To make it more explicit that this scenario is unsupported, the exception-throwing logic was moved into the instance constructor. In case no instances are created, the exception is also thrown in public entry points that return this type, that is, . ## Recommended action diff --git a/docs/core/compatibility/core-libraries/6.0/system-drawing-common-windows-only.md b/docs/core/compatibility/core-libraries/6.0/system-drawing-common-windows-only.md index ea99586d1e010..38753d3cbf471 100644 --- a/docs/core/compatibility/core-libraries/6.0/system-drawing-common-windows-only.md +++ b/docs/core/compatibility/core-libraries/6.0/system-drawing-common-windows-only.md @@ -11,11 +11,11 @@ On non-Windows operating systems, unless you set a runtime configuration switch, ## Old behavior -Prior to .NET 6, using the System.Drawing.Common package did not produce any compile-time warnings, and no run-time exceptions were thrown. +Prior to .NET 6, using the System.Drawing.Common package did not produce any compile-time warnings, and no runtime exceptions were thrown. ## New behavior -Starting in .NET 6, the platform analyzer emits compile-time warnings when referencing code is compiled for non-Windows operating systems. In addition, the following run-time exception is thrown unless you set a configuration option: +Starting in .NET 6, the platform analyzer emits compile-time warnings when referencing code is compiled for non-Windows operating systems. In addition, the following runtime exception is thrown unless you set a configuration option: ``` System.TypeInitializationException : The type initializer for 'Gdip' threw an exception. diff --git a/docs/core/compatibility/core-libraries/7.0/compressionlevel-validation.md b/docs/core/compatibility/core-libraries/7.0/compressionlevel-validation.md index 9bb15a08760ac..dad8b1818e1c6 100644 --- a/docs/core/compatibility/core-libraries/7.0/compressionlevel-validation.md +++ b/docs/core/compatibility/core-libraries/7.0/compressionlevel-validation.md @@ -20,7 +20,7 @@ The only valid values for the para - - -If you pass any other value, an is thrown at run time. +If you pass any other value, an is thrown at runtime. ## Version introduced diff --git a/docs/core/compatibility/core-libraries/7.0/system-drawing.md b/docs/core/compatibility/core-libraries/7.0/system-drawing.md index 90110cf4b7665..df107388bfb08 100644 --- a/docs/core/compatibility/core-libraries/7.0/system-drawing.md +++ b/docs/core/compatibility/core-libraries/7.0/system-drawing.md @@ -5,11 +5,11 @@ ms.date: 05/18/2023 --- # System.Drawing.Common config switch removed -The [System.Drawing.Common](https://www.nuget.org/packages/System.Drawing.Common/) NuGet package has been attributed as a Windows-specific library since .NET 6 and using it resulted in compile-time warnings and run-time exceptions. The runtime configuration switch to re-enable usage of the package on non-Windows operating systems has been removed in .NET 7. +The [System.Drawing.Common](https://www.nuget.org/packages/System.Drawing.Common/) NuGet package has been attributed as a Windows-specific library since .NET 6 and using it resulted in compile-time warnings and runtime exceptions. The runtime configuration switch to re-enable usage of the package on non-Windows operating systems has been removed in .NET 7. ## Old behavior -Prior to .NET 6, using the System.Drawing.Common package did not produce any compile-time warnings, and no run-time exceptions were thrown. In .NET 6, you could set the `System.Drawing.EnableUnixSupport` runtime configuration setting to re-enable non-Windows support. +Prior to .NET 6, using the System.Drawing.Common package did not produce any compile-time warnings, and no runtime exceptions were thrown. In .NET 6, you could set the `System.Drawing.EnableUnixSupport` runtime configuration setting to re-enable non-Windows support. ## New behavior diff --git a/docs/core/compatibility/core-libraries/8.0/runtimeidentifier.md b/docs/core/compatibility/core-libraries/8.0/runtimeidentifier.md index 1f733519a6bcd..42ff05c01e8b9 100644 --- a/docs/core/compatibility/core-libraries/8.0/runtimeidentifier.md +++ b/docs/core/compatibility/core-libraries/8.0/runtimeidentifier.md @@ -5,7 +5,7 @@ ms.date: 09/06/2023 --- # RuntimeIdentifier returns platform for which the runtime was built - returns the platform for which the runtime was built, rather than a value computed at run time. + returns the platform for which the runtime was built, rather than a value computed at runtime. ## Previous behavior @@ -25,7 +25,7 @@ This change is a [behavioral change](../../categories.md#behavioral-change). ## Reason for change -This change is in line with a .NET 8 change to [RID-specific asset resolution](../../deployment/8.0/rid-asset-list.md) and the move away from a distro-aware runtime. is an opaque value that should represent the platform on which the host or runtime considers itself to be running. In .NET 8, that corresponds to the platform for which the host or runtime is built, rather than an RID computed at run time. +This change is in line with a .NET 8 change to [RID-specific asset resolution](../../deployment/8.0/rid-asset-list.md) and the move away from a distro-aware runtime. is an opaque value that should represent the platform on which the host or runtime considers itself to be running. In .NET 8, that corresponds to the platform for which the host or runtime is built, rather than an RID computed at runtime. ## Recommended action diff --git a/docs/core/compatibility/core-libraries/9.0/biginteger-limit.md b/docs/core/compatibility/core-libraries/9.0/biginteger-limit.md index d75dce2716608..0b5eff70f17d4 100644 --- a/docs/core/compatibility/core-libraries/9.0/biginteger-limit.md +++ b/docs/core/compatibility/core-libraries/9.0/biginteger-limit.md @@ -16,7 +16,7 @@ Previously, you could assign a value with a length up to `Array.MaxLength * 32` ## New behavior -Starting in .NET 9, has a maximum length of `(2^31) - 1` (approximately 2.14 billion) bits. If you attempt to assign a larger value, an is thrown at run time. For example, the following code throws an exception: +Starting in .NET 9, has a maximum length of `(2^31) - 1` (approximately 2.14 billion) bits. If you attempt to assign a larger value, an is thrown at runtime. For example, the following code throws an exception: ```csharp BigInteger bigInt = new BigInteger(-1) << int.MaxValue; diff --git a/docs/core/compatibility/core-libraries/9.0/string-trim.md b/docs/core/compatibility/core-libraries/9.0/string-trim.md index 7a8c75eca7c58..8bb1ecc81c47c 100644 --- a/docs/core/compatibility/core-libraries/9.0/string-trim.md +++ b/docs/core/compatibility/core-libraries/9.0/string-trim.md @@ -47,7 +47,7 @@ Callers of who explicitl As for , unlike with , this method already has an [overload](xref:System.String.Split(System.String,System.StringSplitOptions)) that's both preferred over an extension method accepting a single string parameter and the newly added `ReadOnlySpan` overload. For this reason, the new overload of was preserved. > [!NOTE] -> You should rebuild any assembly built against .NET 9 Preview 6, .NET 9 Preview 7, .NET 9 RC1, or .NET 9 RC2 to ensure that any calls to the removed method are removed. Failure to do so might result in a at run time. +> You should rebuild any assembly built against .NET 9 Preview 6, .NET 9 Preview 7, .NET 9 RC1, or .NET 9 RC2 to ensure that any calls to the removed method are removed. Failure to do so might result in a at runtime. ## Version introduced diff --git a/docs/core/compatibility/cryptography/5.0/cryptography-apis-not-supported-on-blazor-webassembly.md b/docs/core/compatibility/cryptography/5.0/cryptography-apis-not-supported-on-blazor-webassembly.md index 73e800a222a47..5e6372ba6ac26 100644 --- a/docs/core/compatibility/cryptography/5.0/cryptography-apis-not-supported-on-blazor-webassembly.md +++ b/docs/core/compatibility/cryptography/5.0/cryptography-apis-not-supported-on-blazor-webassembly.md @@ -5,7 +5,7 @@ ms.date: 09/16/2020 --- # System.Security.Cryptography APIs not supported on Blazor WebAssembly - APIs throw a at run time when run on a browser. + APIs throw a at runtime when run on a browser. ## Change description diff --git a/docs/core/compatibility/cryptography/5.0/instantiating-default-implementations-of-cryptographic-abstractions-not-supported.md b/docs/core/compatibility/cryptography/5.0/instantiating-default-implementations-of-cryptographic-abstractions-not-supported.md index b91e3a0f5addd..8ec6785eceebe 100644 --- a/docs/core/compatibility/cryptography/5.0/instantiating-default-implementations-of-cryptographic-abstractions-not-supported.md +++ b/docs/core/compatibility/cryptography/5.0/instantiating-default-implementations-of-cryptographic-abstractions-not-supported.md @@ -35,7 +35,7 @@ In .NET Core 2.0 - 3.1, abstract cryptographic primitive factories such as are marked obsolete and produce a compile-time warning with ID `SYSLIB0007`. At run time, these methods continue to throw a . +In .NET 5 and later versions, abstract cryptographic primitive factories such as are marked obsolete and produce a compile-time warning with ID `SYSLIB0007`. At runtime, these methods continue to throw a . ```csharp // Throws PlatformNotSupportedException. @@ -43,7 +43,7 @@ In .NET 5 and later versions, abstract cryptographic primitive factories such as HashAlgorithm alg = HashAlgorithm.Create(); ``` -This is a compile-time only change. There is no run-time change from previous versions of .NET Core. +This is a compile-time only change. There is no runtime change from previous versions of .NET Core. > [!NOTE] > @@ -108,7 +108,7 @@ Best practice dictates that libraries that consume cryptographic primitives (suc ``` > [!NOTE] - > Suppressing `SYSLIB0007` disables only the obsoletion warnings for the cryptography APIs listed here. It does not disable any other warnings. Additionally, even if you suppress the warning, these obsoleted APIs will still throw a at run time. + > Suppressing `SYSLIB0007` disables only the obsoletion warnings for the cryptography APIs listed here. It does not disable any other warnings. Additionally, even if you suppress the warning, these obsoleted APIs will still throw a at runtime. ## Affected APIs diff --git a/docs/core/compatibility/cryptography/8.0/aesgcm-auth-tag-size.md b/docs/core/compatibility/cryptography/8.0/aesgcm-auth-tag-size.md index 0ca61fa8f960f..261612d9e3c47 100644 --- a/docs/core/compatibility/cryptography/8.0/aesgcm-auth-tag-size.md +++ b/docs/core/compatibility/cryptography/8.0/aesgcm-auth-tag-size.md @@ -15,7 +15,7 @@ In addition, the and support 16-byte authentication tags only. If you use a smaller tag size on macOS, an is thrown at run time. +On macOS, and support 16-byte authentication tags only. If you use a smaller tag size on macOS, an is thrown at runtime. The property returns a value of 16 as the supported tag size. diff --git a/docs/core/compatibility/cryptography/8.0/rsa-encrypt-decrypt-value-obsolete.md b/docs/core/compatibility/cryptography/8.0/rsa-encrypt-decrypt-value-obsolete.md index 8e26027e2ae86..e281f2136cce1 100644 --- a/docs/core/compatibility/cryptography/8.0/rsa-encrypt-decrypt-value-obsolete.md +++ b/docs/core/compatibility/cryptography/8.0/rsa-encrypt-decrypt-value-obsolete.md @@ -16,7 +16,7 @@ All references to these methods will result in a [SYSLIB0048](../../../../fundam ## Previous behavior -Previously, code could call the [affected methods](#affected-apis) without any compilation warnings. However, they threw a at run time. +Previously, code could call the [affected methods](#affected-apis) without any compilation warnings. However, they threw a at runtime. ## New behavior diff --git a/docs/core/compatibility/deployment/7.0/deprecated-trimmer-default-action.md b/docs/core/compatibility/deployment/7.0/deprecated-trimmer-default-action.md index 581bad2c32667..e1e231a703f94 100644 --- a/docs/core/compatibility/deployment/7.0/deprecated-trimmer-default-action.md +++ b/docs/core/compatibility/deployment/7.0/deprecated-trimmer-default-action.md @@ -9,11 +9,11 @@ The value of the `TrimmerDefaultAction` property is now ignored by the publish p ## Previous behavior -Previously, only assemblies that were opted-in with `true` in the library project file were trimmed with the action specified by the `TrimmerDefaultAction`. In .NET 6, the default value for that property was `copy`. While apps with trim warnings were more likely to work with this default, run-time behavior could still be affected. In addition, the `copy` action caused apps to be larger than if the entire app was trimmed. +Previously, only assemblies that were opted-in with `true` in the library project file were trimmed with the action specified by the `TrimmerDefaultAction`. In .NET 6, the default value for that property was `copy`. While apps with trim warnings were more likely to work with this default, runtime behavior could still be affected. In addition, the `copy` action caused apps to be larger than if the entire app was trimmed. ## New behavior -Starting in .NET 7, the property `TrimmerDefaultAction` is ignored and publishing behaves as if it was set to `link` all the time. This means all assemblies are fully trimmed, whether they opt in or not. As a result, applications with trim warnings may see changes in behavior or run-time exceptions. For more information and instructions for restoring the previous behavior, see [All assemblies trimmed by default](./trim-all-assemblies.md). +Starting in .NET 7, the property `TrimmerDefaultAction` is ignored and publishing behaves as if it was set to `link` all the time. This means all assemblies are fully trimmed, whether they opt in or not. As a result, applications with trim warnings may see changes in behavior or runtime exceptions. For more information and instructions for restoring the previous behavior, see [All assemblies trimmed by default](./trim-all-assemblies.md). ## Version introduced diff --git a/docs/core/compatibility/deployment/8.0/rid-asset-list.md b/docs/core/compatibility/deployment/8.0/rid-asset-list.md index a16452f2fdbeb..9e4c9000900c2 100644 --- a/docs/core/compatibility/deployment/8.0/rid-asset-list.md +++ b/docs/core/compatibility/deployment/8.0/rid-asset-list.md @@ -7,14 +7,14 @@ ms.date: 06/07/2023 When running an application with [runtime identifier (RID)](../../../rid-catalog.md) specific assets, the host determines what assets are relevant for the platform on which it's running. This applies to both the application itself and the resolution logic used by . -Previously, the host tried to compute the RID at run time and then read the RID graph to determine which RID-specific assets matched or were compatible with the computed RID. Now, the default behavior doesn't compute the RID or use the RID graph. Instead, the host relies on a known list of RIDs based on how the runtime itself was built. +Previously, the host tried to compute the RID at runtime and then read the RID graph to determine which RID-specific assets matched or were compatible with the computed RID. Now, the default behavior doesn't compute the RID or use the RID graph. Instead, the host relies on a known list of RIDs based on how the runtime itself was built. ## Previous behavior Previously, the process for selecting RID-specific assets was: 1. Read the RID graph from the *.deps.json* file of the root framework (Microsoft.NetCore.App). -1. Compute the current RID at run time and try to find an entry for it in the RID graph. If it doesn't exist, check for a fallback RID (built into the host at compile time). +1. Compute the current RID at runtime and try to find an entry for it in the RID graph. If it doesn't exist, check for a fallback RID (built into the host at compile time). 1. Starting from the entry found in the RID graph, look for assets matching that RID. 1. Continue down the list of RIDs in the RID graph entry until an asset match is found or the list ends. diff --git a/docs/core/compatibility/extensions/7.0/contentrootpath-hosted-app.md b/docs/core/compatibility/extensions/7.0/contentrootpath-hosted-app.md index 242d2e23a6764..d2a0b4caaae7a 100644 --- a/docs/core/compatibility/extensions/7.0/contentrootpath-hosted-app.md +++ b/docs/core/compatibility/extensions/7.0/contentrootpath-hosted-app.md @@ -9,7 +9,7 @@ The . diff --git a/docs/core/compatibility/globalization/5.0/icu-globalization-api.md b/docs/core/compatibility/globalization/5.0/icu-globalization-api.md index da1544a6165d1..69480cd3612e2 100644 --- a/docs/core/compatibility/globalization/5.0/icu-globalization-api.md +++ b/docs/core/compatibility/globalization/5.0/icu-globalization-api.md @@ -69,7 +69,7 @@ This change was introduced to unify .NET's globalization behavior across all sup ## Recommended action -No action is required on the part of the developer. However, if you wish to continue using NLS globalization APIs, you can set a [run-time switch](../../../runtime-config/globalization.md#nls) to revert to that behavior. For more information about the available switches, see the [.NET globalization and ICU](../../../../core/extensions/globalization-icu.md) article. +No action is required on the part of the developer. However, if you wish to continue using NLS globalization APIs, you can set a [runtime switch](../../../runtime-config/globalization.md#nls) to revert to that behavior. For more information about the available switches, see the [.NET globalization and ICU](../../../../core/extensions/globalization-icu.md) article. ## Affected APIs diff --git a/docs/core/compatibility/globalization/7.0/icu-globalization-api.md b/docs/core/compatibility/globalization/7.0/icu-globalization-api.md index df2d2c806b431..629b7fd7bc36c 100644 --- a/docs/core/compatibility/globalization/7.0/icu-globalization-api.md +++ b/docs/core/compatibility/globalization/7.0/icu-globalization-api.md @@ -45,7 +45,7 @@ string text = string.Format("{0:C}", 100); If you're using .NET 7 on Windows Server 2019 or Windows 10 client versions 1703, 1709, 1803, or 1809, we recommend testing your app or service before shipping it to ensure the behavior is as expected and doesn't break any users. -If you wish to continue using NLS globalization APIs, you can set a [run-time switch](../../../runtime-config/globalization.md#nls) to revert to that behavior. For more information about the available switches, see the [.NET globalization and ICU](../../../../core/extensions/globalization-icu.md) article. +If you wish to continue using NLS globalization APIs, you can set a [runtime switch](../../../runtime-config/globalization.md#nls) to revert to that behavior. For more information about the available switches, see the [.NET globalization and ICU](../../../../core/extensions/globalization-icu.md) article. ## Affected APIs diff --git a/docs/core/compatibility/includes/binary-source-behavioral.md b/docs/core/compatibility/includes/binary-source-behavioral.md index 984a5b50ff59c..107d596c10639 100644 --- a/docs/core/compatibility/includes/binary-source-behavioral.md +++ b/docs/core/compatibility/includes/binary-source-behavioral.md @@ -4,4 +4,4 @@ This article categorizes each breaking change as *binary incompatible* or *sourc - **Source incompatible** - When recompiled using the new SDK or component or to target the new runtime, existing source code may require source changes to compile successfully. -- **Behavioral change** - Existing code and binaries may behave differently at run time. If the new behavior is undesirable, existing code would need to be updated and recompiled. +- **Behavioral change** - Existing code and binaries may behave differently at runtime. If the new behavior is undesirable, existing code would need to be updated and recompiled. diff --git a/docs/core/compatibility/includes/binary-source-compat.md b/docs/core/compatibility/includes/binary-source-compat.md index c112122fc6a36..1b0dbbef1cdb9 100644 --- a/docs/core/compatibility/includes/binary-source-compat.md +++ b/docs/core/compatibility/includes/binary-source-compat.md @@ -1,4 +1,4 @@ This article indicates whether each breaking change is *binary compatible* or *source compatible*: -- **Binary compatible** - Existing binaries will load and execute successfully without recompilation, and the run-time behavior won't change. +- **Binary compatible** - Existing binaries will load and execute successfully without recompilation, and the runtime behavior won't change. - **Source compatible** - Source code will compile successfully without changes when targeting the new runtime or using the new SDK or component. diff --git a/docs/core/compatibility/interop/8.0/idispatchimplattribute-removed.md b/docs/core/compatibility/interop/8.0/idispatchimplattribute-removed.md index d2d8f99b4975c..fbe4cb1d2098e 100644 --- a/docs/core/compatibility/interop/8.0/idispatchimplattribute-removed.md +++ b/docs/core/compatibility/interop/8.0/idispatchimplattribute-removed.md @@ -5,11 +5,11 @@ ms.date: 08/22/2023 --- # IDispatchImplAttribute API is removed -The implementation has officially been removed from .NET. This type was only discoverable at run time and its removal has no impact on visible API surface area. However, if an assembly targeting .NET Framework uses this type and is loaded in .NET 8 or a later version, the runtime will throw a . +The implementation has officially been removed from .NET. This type was only discoverable at runtime and its removal has no impact on visible API surface area. However, if an assembly targeting .NET Framework uses this type and is loaded in .NET 8 or a later version, the runtime will throw a . ## Previous behavior -The type could be found at run time, but none of the documented semantics of the deprecated attribute applied. +The type could be found at runtime, but none of the documented semantics of the deprecated attribute applied. ## New behavior diff --git a/docs/core/compatibility/reflection/10/ireflect-damt-annotations.md b/docs/core/compatibility/reflection/10/ireflect-damt-annotations.md index b55b4f6ceef02..c12bded0cf327 100644 --- a/docs/core/compatibility/reflection/10/ireflect-damt-annotations.md +++ b/docs/core/compatibility/reflection/10/ireflect-damt-annotations.md @@ -29,7 +29,7 @@ This change is a [behavioral change](../../categories.md#behavioral-change) and ## Reason for change -The change was introduced to improve the accuracy of annotations in APIs and to address issues caused by the overly permissive annotation. This ensures better compatibility with trimming and reflection scenarios, reduces run-time warnings, and prevents unsafe reflection calls. +The change was introduced to improve the accuracy of annotations in APIs and to address issues caused by the overly permissive annotation. This ensures better compatibility with trimming and reflection scenarios, reduces runtime warnings, and prevents unsafe reflection calls. ## Recommended action @@ -53,7 +53,7 @@ If you implement or derive from serialization is obsolete in .NET 8 and later versions. Any use of is deemed insecure and throws an exception at run time. Since MSBuild custom derived build events use , your build would crash if you used these events in your build. The new build error provides a more graceful failure. + serialization is obsolete in .NET 8 and later versions. Any use of is deemed insecure and throws an exception at runtime. Since MSBuild custom derived build events use , your build would crash if you used these events in your build. The new build error provides a more graceful failure. ## Recommended action diff --git a/docs/core/compatibility/serialization/10/property-name-validation.md b/docs/core/compatibility/serialization/10/property-name-validation.md index 204500dd2c68c..d740bafe1cb05 100644 --- a/docs/core/compatibility/serialization/10/property-name-validation.md +++ b/docs/core/compatibility/serialization/10/property-name-validation.md @@ -51,7 +51,7 @@ This change is a [behavioral change](../../categories.md#behavioral-change). ## Reason for change -This change provides early prevention of invalid serialization contracts. By validating property names upfront, the serializer prevents scenarios where duplicate properties would be emitted, resulting in invalid JSON that cannot round-trip correctly. This helps developers identify and fix configuration issues during development rather than discovering them at run time during deserialization. +This change provides early prevention of invalid serialization contracts. By validating property names upfront, the serializer prevents scenarios where duplicate properties would be emitted, resulting in invalid JSON that cannot round-trip correctly. This helps developers identify and fix configuration issues during development rather than discovering them at runtime during deserialization. For more information, see: diff --git a/docs/core/compatibility/serialization/6.0/iasyncenumerable-serialization.md b/docs/core/compatibility/serialization/6.0/iasyncenumerable-serialization.md index 4662892d9e35c..50f8cab4a21ce 100644 --- a/docs/core/compatibility/serialization/6.0/iasyncenumerable-serialization.md +++ b/docs/core/compatibility/serialization/6.0/iasyncenumerable-serialization.md @@ -22,7 +22,7 @@ Asynchronous serialization methods now enumerate any that accept pre-generated type information via or . These overloads provide a performance optimization over pre-existing overloads that take instances and perform run-time reflection. All of these parameter types are reference types for which you can pass `null`. The following example shows the method-signature patterns for both approaches: +The `System.Text.Json` source generator feature added new overloads to that accept pre-generated type information via or . These overloads provide a performance optimization over pre-existing overloads that take instances and perform runtime reflection. All of these parameter types are reference types for which you can pass `null`. The following example shows the method-signature patterns for both approaches: Pre-existing reflection/`JsonSerializerOptions`-based overloads: diff --git a/docs/core/compatibility/serialization/7.0/binaryformatter-apis-produce-errors.md b/docs/core/compatibility/serialization/7.0/binaryformatter-apis-produce-errors.md index 7e6f23ef3d374..eae2792dbb7bd 100644 --- a/docs/core/compatibility/serialization/7.0/binaryformatter-apis-produce-errors.md +++ b/docs/core/compatibility/serialization/7.0/binaryformatter-apis-produce-errors.md @@ -63,18 +63,18 @@ If you must suppress the errors, you can do so by following the guidelines in th ### `` property -The `1 | The affected APIs are obsolete as warning. Compilation will succeed unless you have "warnings as errors" enabled for your application or you've suppressed the `SYSLIB0011` warning code. | The affected APIs are obsolete as error, and calls from your code to those APIs will fail at compile time unless the error is suppressed. | (Same as for `false`.) | -| Blazor and MAUI apps2 | Calls to `BinaryFormatter` will fail at run time. | Calls to `BinaryFormatter` will fail at run time. | Calls to `BinaryFormatter` will fail at run time. | +| Blazor and MAUI apps2 | Calls to `BinaryFormatter` will fail at runtime. | Calls to `BinaryFormatter` will fail at runtime. | Calls to `BinaryFormatter` will fail at runtime. | | ASP.NET app | The affected APIs are obsolete as warning. Compilation will succeed unless you have "warnings as errors" enabled for your application or you've suppressed the `SYSLIB0011` warning code. The runtime will *allow* calls to `BinaryFormatter`, regardless of whether the call originates from your code or from a dependency that you consume. | The affected APIs are obsolete as error, and calls from your code to those APIs will fail at compile time unless the error is suppressed. The runtime will *forbid* calls to `BinaryFormatter`, regardless of whether the call originates from your code or from a dependency that you consume. | (Same as for `false`.) | | Desktop apps and all other app types | The affected APIs are obsolete as warning. Compilation will succeed unless you have "warnings as errors" enabled for your application or you've suppressed the `SYSLIB0011` warning code. The runtime will *allow* calls to `BinaryFormatter`, regardless of whether the call originates from your code or from a dependency that you consume. | The affected APIs are obsolete as error, and calls from your code to those APIs will fail at compile time unless the error is suppressed. The runtime will *forbid* calls to `BinaryFormatter`, regardless of whether the call originates from your code or from a dependency that you consume. | The affected APIs are obsolete as error, and calls from your code to those APIs will fail at compile time unless the error is suppressed. The runtime will *allow* calls to `BinaryFormatter`, regardless of whether the call originates from your code or from a dependency that you consume. | -1Runtime policy is controlled by the app host. Calls into `BinaryFormatter` might still fail at run time even if `` is set to `true` within your library's project file. Libraries can't override the app host's runtime policy. +1Runtime policy is controlled by the app host. Calls into `BinaryFormatter` might still fail at runtime even if `` is set to `true` within your library's project file. Libraries can't override the app host's runtime policy. -2The Blazor and MAUI runtimes forbid calls to `BinaryFormatter`. Regardless of any value you set for ``, the calls will fail at run time. Don't call these APIs from Blazor or MAUI applications or from libraries intended to be consumed by Blazor or MAUI apps. +2The Blazor and MAUI runtimes forbid calls to `BinaryFormatter`. Regardless of any value you set for ``, the calls will fail at runtime. Don't call these APIs from Blazor or MAUI applications or from libraries intended to be consumed by Blazor or MAUI apps. ## Affected APIs diff --git a/docs/core/compatibility/serialization/7.0/serializationformat-binary.md b/docs/core/compatibility/serialization/7.0/serializationformat-binary.md index 9096bb6db085a..e76ada3d759a0 100644 --- a/docs/core/compatibility/serialization/7.0/serializationformat-binary.md +++ b/docs/core/compatibility/serialization/7.0/serializationformat-binary.md @@ -7,7 +7,7 @@ ms.date: 03/18/2022 is obsolete for and . Binary serialization relies on , which is insecure. If you use in your code, obsoletion warning [SYSLIB0038](../../../../fundamentals/syslib-diagnostics/syslib0038.md) will be generated at compile time. -In addition, an is thrown at run time if you: +In addition, an is thrown at runtime if you: - Set or to . - Call one of the deserialization constructors for or with binary data. diff --git a/docs/core/compatibility/serialization/8.0/binaryformatter-disabled.md b/docs/core/compatibility/serialization/8.0/binaryformatter-disabled.md index e8d34470deb16..92b654083fef0 100644 --- a/docs/core/compatibility/serialization/8.0/binaryformatter-disabled.md +++ b/docs/core/compatibility/serialization/8.0/binaryformatter-disabled.md @@ -1,11 +1,11 @@ --- title: "Breaking change: BinaryFormatter disabled across most project types" -description: Learn about the .NET 8 breaking change in serialization where serialize and deserialize methods on BinaryFormatter now throw an exception at run time. +description: Learn about the .NET 8 breaking change in serialization where serialize and deserialize methods on BinaryFormatter now throw an exception at runtime. ms.date: 05/01/2023 --- # BinaryFormatter disabled across most project types -The and methods now throw a at run time across nearly all project types, including console applications. +The and methods now throw a at runtime across nearly all project types, including console applications. ## Previous behavior @@ -13,7 +13,7 @@ In .NET 7, the at run time across all project types except Windows Forms and WPF. The APIs continue to remain obsolete (as error) across all project types, including Windows Forms and WPF. +Starting in .NET 8, the affected methods throw a at runtime across all project types except Windows Forms and WPF. The APIs continue to remain obsolete (as error) across all project types, including Windows Forms and WPF. ## Version introduced @@ -25,7 +25,7 @@ This change is a [behavioral change](../../categories.md#behavioral-change). ## Reason for change -This run-time change is the next stage of the [BinaryFormatter obsoletion plan](https://github.com/dotnet/designs/blob/main/accepted/2020/better-obsoletion/binaryformatter-obsoletion.md), in which will eventually be removed from .NET. +This runtime change is the next stage of the [BinaryFormatter obsoletion plan](https://github.com/dotnet/designs/blob/main/accepted/2020/better-obsoletion/binaryformatter-obsoletion.md), in which will eventually be removed from .NET. ## Recommended action diff --git a/docs/core/compatibility/serialization/8.0/metadata-resolving.md b/docs/core/compatibility/serialization/8.0/metadata-resolving.md index 431ccf30c9de9..7a9b989aec6db 100644 --- a/docs/core/compatibility/serialization/8.0/metadata-resolving.md +++ b/docs/core/compatibility/serialization/8.0/metadata-resolving.md @@ -32,7 +32,7 @@ public class NestedValue ## New behavior -Starting in .NET 8, the same code from the [Previous behavior](#previous-behavior) section throws an at run time. +Starting in .NET 8, the same code from the [Previous behavior](#previous-behavior) section throws an at runtime. > System.InvalidOperationException: The type 'System.ReadOnlySpan`1[System.Byte]' of property 'Span' on type 'NestedValue' is invalid for serialization or deserialization because it is a pointer type, is a ref struct, or contains generic parameters that have not been replaced by specific types. diff --git a/docs/core/compatibility/serialization/9.0/binaryformatter-removal.md b/docs/core/compatibility/serialization/9.0/binaryformatter-removal.md index 8e67636a126f7..edd576871680a 100644 --- a/docs/core/compatibility/serialization/9.0/binaryformatter-removal.md +++ b/docs/core/compatibility/serialization/9.0/binaryformatter-removal.md @@ -5,7 +5,7 @@ ms.date: 08/06/2024 --- # In-box BinaryFormatter implementation removed and always throws -The "in box" implementation now throws exceptions at run time in all cases. This is the final stage of the [BinaryFormatter obsoletion plan](https://github.com/dotnet/designs/blob/main/accepted/2020/better-obsoletion/binaryformatter-obsoletion.md). +The "in box" implementation now throws exceptions at runtime in all cases. This is the final stage of the [BinaryFormatter obsoletion plan](https://github.com/dotnet/designs/blob/main/accepted/2020/better-obsoletion/binaryformatter-obsoletion.md). ## Previous behavior diff --git a/docs/core/compatibility/wcf-client/8.0/configurationname-apis.md b/docs/core/compatibility/wcf-client/8.0/configurationname-apis.md index 3a7b5ca5eaa5a..b5212bb0364ee 100644 --- a/docs/core/compatibility/wcf-client/8.0/configurationname-apis.md +++ b/docs/core/compatibility/wcf-client/8.0/configurationname-apis.md @@ -16,7 +16,7 @@ WCF Client 8.0 GA ## Previous behavior -The removed APIs were previously suppressed from IntelliSense suggestions, however, projects that used them compiled successfully. Using any of the removed APIs resulted in a at run time. +The removed APIs were previously suppressed from IntelliSense suggestions, however, projects that used them compiled successfully. Using any of the removed APIs resulted in a at runtime. ## New behavior @@ -28,7 +28,7 @@ This change can affect [source compatibility](../../categories.md#source-compati ## Reason for change -The [affected APIs](#affected-apis) were never implemented on .NET, and any calls to these APIs previously resulted in a run-time exception. Thus the decision was made to remove them completely. +The [affected APIs](#affected-apis) were never implemented on .NET, and any calls to these APIs previously resulted in a runtime exception. Thus the decision was made to remove them completely. ## Recommended action diff --git a/docs/core/compatibility/windows-forms/6.0/application-bootstrap.md b/docs/core/compatibility/windows-forms/6.0/application-bootstrap.md index 435b47a22dde0..e37327ea21057 100644 --- a/docs/core/compatibility/windows-forms/6.0/application-bootstrap.md +++ b/docs/core/compatibility/windows-forms/6.0/application-bootstrap.md @@ -69,7 +69,7 @@ static class Program - [ApplicationUseCompatibleTextRendering](../../../project-sdk/msbuild-props-desktop.md#applicationusecompatibletextrendering) - [ApplicationVisualStyles](../../../project-sdk/msbuild-props-desktop.md#applicationvisualstyles) -If you don't explicitly configure any properties, the following code is executed at run time: +If you don't explicitly configure any properties, the following code is executed at runtime: ```csharp static class Program diff --git a/docs/core/compatibility/windows-forms/8.0/forms-scale-size-to-dpi.md b/docs/core/compatibility/windows-forms/8.0/forms-scale-size-to-dpi.md index 54c024f22121a..30cbcfff53fe5 100644 --- a/docs/core/compatibility/windows-forms/8.0/forms-scale-size-to-dpi.md +++ b/docs/core/compatibility/windows-forms/8.0/forms-scale-size-to-dpi.md @@ -21,7 +21,7 @@ You can also opt in to this behavior in .NET 7. To opt in, set the `System.Windo Starting in .NET 8, top-level forms scale their and values according to the DPI of the monitor when running in mode. The behavior of your app might change in the following ways: -- Run-time dependencies might be impacted when the minimum and maximum size of the form change. +- Runtime dependencies might be impacted when the minimum and maximum size of the form change. - New and events might be raised. - The scaled form size now has new constraint values for the minimum and maximum sizes. diff --git a/docs/core/compatibility/wpf/10.0/dynamicresource-crash.md b/docs/core/compatibility/wpf/10.0/dynamicresource-crash.md index 5daaefbbca21c..6dfcd423f415f 100644 --- a/docs/core/compatibility/wpf/10.0/dynamicresource-crash.md +++ b/docs/core/compatibility/wpf/10.0/dynamicresource-crash.md @@ -8,7 +8,7 @@ ms.custom: https://github.com/dotnet/docs/issues/46089 # Incorrect usage of DynamicResource causes application crash -Applications that use `DynamicResource` incorrectly now crash at run time. +Applications that use `DynamicResource` incorrectly now crash at runtime. ## Version introduced diff --git a/docs/core/compatibility/xml/7.0/xmlsecureresolver-obsolete.md b/docs/core/compatibility/xml/7.0/xmlsecureresolver-obsolete.md index 0ee147c3f4491..f92d7d7f3d580 100644 --- a/docs/core/compatibility/xml/7.0/xmlsecureresolver-obsolete.md +++ b/docs/core/compatibility/xml/7.0/xmlsecureresolver-obsolete.md @@ -1,11 +1,11 @@ --- title: ".NET 7 breaking change: XmlSecureResolver is obsolete" -description: Learn about the .NET 7 breaking change in XML/XSLT where XmlSecureResolver was obsoleted and XmlSecureResolver.GetEntity unconditionally throws a run-time exception. +description: Learn about the .NET 7 breaking change in XML/XSLT where XmlSecureResolver was obsoleted and XmlSecureResolver.GetEntity unconditionally throws a runtime exception. ms.date: 09/08/2022 --- # XmlSecureResolver is obsolete -The method unconditionally throws an at run time. If your application utilizes and you attempt to resolve an XML resource through it, resolution will fail with an exception. +The method unconditionally throws an at runtime. If your application utilizes and you attempt to resolve an XML resource through it, resolution will fail with an exception. Additionally, the entire type is obsolete. All references to this type will result in a [SYSLIB0047](../../../../fundamentals/syslib-diagnostics/syslib0047.md) warning at build time. If you've enabled warnings as errors, this will cause a build break if your application references . @@ -17,7 +17,7 @@ XmlResolver resolver = new XmlSecureResolver( resolver: new XmlUrlResolver(), securityUrl: "https://www.example.com/"); -// Call to XmlSecureResolver.GetEntity below throws XmlException at run time. +// Call to XmlSecureResolver.GetEntity below throws XmlException at runtime. object entity = resolver.GetEntity( absoluteUri: new Uri("https://www.example.com/some-entity"), role: null, diff --git a/docs/core/containers/publish-configuration.md b/docs/core/containers/publish-configuration.md index 235f339c4eb41..b1c2756e44769 100644 --- a/docs/core/containers/publish-configuration.md +++ b/docs/core/containers/publish-configuration.md @@ -304,7 +304,7 @@ The `ContainerDefaultArgs` configuration has a single `Include` property, which ### `ContainerEnvironmentVariable` -The container environment variable node allows you to add environment variables to the container. Environment variables are accessible to the app running in the container immediately, and are often used to change the run-time behavior of the running app. +The container environment variable node allows you to add environment variables to the container. Environment variables are accessible to the app running in the container immediately, and are often used to change the runtime behavior of the running app. The `ContainerEnvironmentVariable` node has two attributes: diff --git a/docs/core/dependency-loading/overview.md b/docs/core/dependency-loading/overview.md index 7ab6b7410c4ec..ef16e9377b911 100644 --- a/docs/core/dependency-loading/overview.md +++ b/docs/core/dependency-loading/overview.md @@ -11,7 +11,7 @@ Every .NET application has dependencies. Even the simple `hello world` app has d Understanding the default assembly loading logic in .NET can help you troubleshoot typical deployment issues. -In some applications, dependencies are dynamically determined at run time. In these situations, it's critical to understand how managed assemblies and unmanaged dependencies are loaded. +In some applications, dependencies are dynamically determined at runtime. In these situations, it's critical to understand how managed assemblies and unmanaged dependencies are loaded. ## AssemblyLoadContext diff --git a/docs/core/deploying/index.md b/docs/core/deploying/index.md index 67f07c4cded14..63264e3d26523 100644 --- a/docs/core/deploying/index.md +++ b/docs/core/deploying/index.md @@ -311,7 +311,7 @@ Single-file apps are always OS and architecture specific. You need to publish fo **Disadvantages** - **Larger file size**: The single file includes all dependencies, making it larger than individual files. -- **Slower startup**: Files must be extracted at run time, which can impact startup performance. +- **Slower startup**: Files must be extracted at runtime, which can impact startup performance. - **Platform-specific**: Must publish separate files for each target platform. Single-file deployment can be combined with other optimizations like [trimming](trimming/trim-self-contained.md) and [ReadyToRun compilation](#readytorun-deployment) for further optimization. @@ -355,7 +355,7 @@ Native AOT deployment compiles your app directly to native code, eliminating the **Advantages** -- **Fast startup**: No JIT compilation needed at run time, leading to faster application startup. +- **Fast startup**: No JIT compilation needed at runtime, leading to faster application startup. - **Reduced memory usage**: Lower memory footprint compared to traditional .NET applications. - **No runtime dependency**: The application runs without requiring .NET runtime installation. - **Smaller deployment size**: Often smaller than **self-contained deployment** with the full runtime. diff --git a/docs/core/deploying/native-aot/fixing-warnings.md b/docs/core/deploying/native-aot/fixing-warnings.md index 32d6bfaabe5a6..410587a3a14c0 100644 --- a/docs/core/deploying/native-aot/fixing-warnings.md +++ b/docs/core/deploying/native-aot/fixing-warnings.md @@ -7,11 +7,11 @@ ms.date: 09/06/2022 --- # Introduction to AOT warnings -When publishing your application as Native AOT, the build process produces all the native code and data structures required to support the application at run time. This is different from non-native deployments, which execute the application from formats that describe the application in abstract terms (a program for a virtual machine) and create native representations on demand at run time. +When publishing your application as Native AOT, the build process produces all the native code and data structures required to support the application at runtime. This is different from non-native deployments, which execute the application from formats that describe the application in abstract terms (a program for a virtual machine) and create native representations on demand at runtime. The abstract representations of program parts don't have a one-to-one mapping to native representation. For example, the abstract description of the generic `List.Add` method maps to potentially infinite native method bodies that need to be specialized for the given `T` (for example, `List.Add` and `List.Add`). -Because the relationship of abstract code to native code is not one-to-one, the build process needs to create a complete list of native code bodies and data structures at build time. It can be difficult to create this list at build time for some of the .NET APIs. If the API is used in a way that wasn't anticipated at build time, an exception will be thrown at run time. +Because the relationship of abstract code to native code is not one-to-one, the build process needs to create a complete list of native code bodies and data structures at build time. It can be difficult to create this list at build time for some of the .NET APIs. If the API is used in a way that wasn't anticipated at build time, an exception will be thrown at runtime. To prevent changes in behavior when deploying as Native AOT, the .NET SDK provides static analysis of AOT compatibility through "AOT warnings." AOT warnings are produced when the build finds code that may not be compatible with AOT. Code that's not AOT-compatible may produce behavioral changes or even crashes in an application after it's been built as Native AOT. Ideally, all applications that use Native AOT should have no AOT warnings. If there are any AOT warnings, ensure there are no behavior changes by thoroughly testing your app after building as Native AOT. @@ -38,15 +38,15 @@ In this case, Native AOT build issues the following warning on the `MakeGenericT AOT analysis warning IL3050: Program.
$(String[]): Using member 'System.Type.MakeGenericType(Type[])' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. The native code for this instantiation might not be available at runtime. ``` -At run time, the application will indeed throw an exception from the `MakeGenericType` call. +At runtime, the application will indeed throw an exception from the `MakeGenericType` call. ## React to AOT warnings -The AOT warnings are meant to bring predictability to Native AOT builds. A majority of AOT warnings are about possible run-time exception in situations when native code wasn't generated to support the scenario. The broadest category is `RequiresDynamicCodeAttribute`. +The AOT warnings are meant to bring predictability to Native AOT builds. A majority of AOT warnings are about possible runtime exception in situations when native code wasn't generated to support the scenario. The broadest category is `RequiresDynamicCodeAttribute`. ### RequiresDynamicCode - is simple and broad: it's an attribute that means the member has been annotated as being incompatible with AOT. This annotation means that the member might use reflection or another mechanism to create new native code at run time. This attribute is used when code is fundamentally not AOT compatible, or the native dependency is too complex to statically predict at build time. This would often be true for methods that use the `Type.MakeGenericType` API, reflection emit, or other run-time code generation technologies. The following code shows an example. + is simple and broad: it's an attribute that means the member has been annotated as being incompatible with AOT. This annotation means that the member might use reflection or another mechanism to create new native code at runtime. This attribute is used when code is fundamentally not AOT compatible, or the native dependency is too complex to statically predict at build time. This would often be true for methods that use the `Type.MakeGenericType` API, reflection emit, or other runtime code generation technologies. The following code shows an example. ```csharp [RequiresDynamicCode("Use 'MethodFriendlyToAot' instead")] @@ -62,7 +62,7 @@ void TestMethod() There aren't many workarounds for `RequiresDynamicCode`. The best fix is to avoid calling the method at all when building as Native AOT and use something else that's AOT compatible. If you're writing a library and it's not in your control whether or not to call the method, you can also add `RequiresDynamicCode` to your own method. This will annotate your method as not AOT compatible. Adding `RequiresDynamicCode` silences all AOT warnings in the annotated method but will produce a warning whenever someone else calls it. For this reason, it's mostly useful to library authors to "bubble up" the warning to a public API. -If you can somehow determine that the call is safe, and all native code will be available at run time, you can also suppress the warning using . For example: +If you can somehow determine that the call is safe, and all native code will be available at runtime, you can also suppress the warning using . For example: ```csharp [RequiresDynamicCode("Use 'MethodFriendlyToAot' instead")] diff --git a/docs/core/deploying/native-aot/index.md b/docs/core/deploying/native-aot/index.md index bb07bd14be2d8..f706d08e17e07 100644 --- a/docs/core/deploying/native-aot/index.md +++ b/docs/core/deploying/native-aot/index.md @@ -128,19 +128,19 @@ The debug file is necessary for running the app under the [debugger or inspectin Native AOT apps have the following limitations: - No dynamic loading, for example, `Assembly.LoadFile`. -- No run-time code generation, for example, `System.Reflection.Emit`. +- No runtime code generation, for example, `System.Reflection.Emit`. - No C++/CLI. - Windows: No built-in COM. - Requires trimming, which has [limitations](../trimming/incompatibilities.md). - Implies compilation into a single file, which has known [incompatibilities](../single-file/overview.md#api-incompatibility). - Apps include required runtime libraries (just like [self-contained apps](../index.md#self-contained-deployment), increasing their size as compared to framework-dependent apps). -- always use their interpreted form, which is slower than run-time generated compiled code. +- always use their interpreted form, which is slower than runtime generated compiled code. - Generic parameters substituted with struct type arguments have specialized code generated for each instantiation. In the dynamic runtime, many instantiations are generated on-demand. In Native AOT, all instantiations are pre-generated. This can have significant impact to the disk size of the application. Generic virtual methods and generic instance methods will also have an instantiation for every implementing or overriding type. - Not all the runtime libraries are fully annotated to be Native AOT compatible. That is, some warnings in the runtime libraries aren't actionable by end developers. - [Diagnostic support for debugging and profiling](./diagnostics.md) with some limitations. - Support for some ASP.NET Core features. For more information, see [ASP.NET Core support for Native AOT](/aspnet/core/fundamentals/native-aot/). -The publish process analyzes the entire project and its dependencies for possible limitations. Warnings are issued for each limitation the published app might encounter at run time. +The publish process analyzes the entire project and its dependencies for possible limitations. Warnings are issued for each limitation the published app might encounter at runtime. ## Platform/architecture restrictions diff --git a/docs/core/deploying/native-aot/interop.md b/docs/core/deploying/native-aot/interop.md index 665287e9cba91..632a699a33e14 100644 --- a/docs/core/deploying/native-aot/interop.md +++ b/docs/core/deploying/native-aot/interop.md @@ -13,7 +13,7 @@ While native code interop works similarly in Native AOT and non-AOT deployments, ## Direct P/Invoke calls -The P/Invoke calls in AOT-compiled binaries are bound lazily at run time by default, for better compatibility. You can configure the AOT compiler to generate direct calls for selected P/Invoke methods that are bound during startup by the dynamic loader that comes with the operating system. The unmanaged libraries and entry points referenced via direct calls must always be available at run time, otherwise the native binary fails to start. +The P/Invoke calls in AOT-compiled binaries are bound lazily at runtime by default, for better compatibility. You can configure the AOT compiler to generate direct calls for selected P/Invoke methods that are bound during startup by the dynamic loader that comes with the operating system. The unmanaged libraries and entry points referenced via direct calls must always be available at runtime, otherwise the native binary fails to start. The benefits of direct P/Invoke calls are: diff --git a/docs/core/deploying/native-aot/intrinsic-requiresdynamiccode-apis.md b/docs/core/deploying/native-aot/intrinsic-requiresdynamiccode-apis.md index 17a7517ba214b..d60dac24c2c54 100644 --- a/docs/core/deploying/native-aot/intrinsic-requiresdynamiccode-apis.md +++ b/docs/core/deploying/native-aot/intrinsic-requiresdynamiccode-apis.md @@ -10,7 +10,7 @@ ms.date: 09/09/2024 Under normal circumstances, calling APIs annotated with in an app published with native AOT triggers warning [IL3050 (Avoid calling members annotated with 'RequiresDynamicCodeAttribute' when publishing as native AOT)](warnings/il3050.md). APIs that trigger the warning might not behave correctly after AOT compilation. -Some APIs annotated RequiresDynamicCode can still be used without triggering the warning when called in a specific pattern. When used as part of a pattern, the call to the API can be statically analyzed by the compiler, does not generate a warning, and behaves as expected at run time. +Some APIs annotated RequiresDynamicCode can still be used without triggering the warning when called in a specific pattern. When used as part of a pattern, the call to the API can be statically analyzed by the compiler, does not generate a warning, and behaves as expected at runtime. ## Enum.GetValues(Type) Method diff --git a/docs/core/deploying/native-aot/security.md b/docs/core/deploying/native-aot/security.md index 683c907345d91..261b6b33718ab 100644 --- a/docs/core/deploying/native-aot/security.md +++ b/docs/core/deploying/native-aot/security.md @@ -10,13 +10,13 @@ ms.date: 09/11/2024 .NET offers many facilities to help address security concerns when building apps. Native AOT deployment builds on top of these facilities and provides several that can help harden your apps. -## No run-time code generation +## No runtime code generation -Since native AOT generates all code at the time of publishing the app, no new executable code needs to be generated at run time. This allows running your apps in environments that disallow creation of new executable code pages at run time. All the code that the CPU executes can be digitally signed. +Since native AOT generates all code at the time of publishing the app, no new executable code needs to be generated at runtime. This allows running your apps in environments that disallow creation of new executable code pages at runtime. All the code that the CPU executes can be digitally signed. ## Restricted reflection surface -When apps are published with native AOT, the compiler analyzes the usage of reflection within the app. Only the program elements that were deemed to be targets of reflection are available for reflection at run time. Places within the program that attempt to do unconstrained reflection are flagged using [trimming warnings](../trimming/fixing-warnings.md). Program elements that weren't intended to be targets of reflection cannot be reflected on. This restriction can prevent a class of issues where a malicious actor gets in control of what the program reflects on and invokes unintended code. This restriction includes approaches that use `Assembly.LoadFrom` or `Reflection.Emit` - neither of those work with native AOT, and their use is flagged with a warning at build time. +When apps are published with native AOT, the compiler analyzes the usage of reflection within the app. Only the program elements that were deemed to be targets of reflection are available for reflection at runtime. Places within the program that attempt to do unconstrained reflection are flagged using [trimming warnings](../trimming/fixing-warnings.md). Program elements that weren't intended to be targets of reflection cannot be reflected on. This restriction can prevent a class of issues where a malicious actor gets in control of what the program reflects on and invokes unintended code. This restriction includes approaches that use `Assembly.LoadFrom` or `Reflection.Emit` - neither of those work with native AOT, and their use is flagged with a warning at build time. ## Control Flow Guard diff --git a/docs/core/deploying/native-aot/warnings/il3050.md b/docs/core/deploying/native-aot/warnings/il3050.md index b5d5213ca37ba..9c160b590e534 100644 --- a/docs/core/deploying/native-aot/warnings/il3050.md +++ b/docs/core/deploying/native-aot/warnings/il3050.md @@ -1,6 +1,6 @@ --- title: "IL3050: Avoid calling members annotated with 'RequiresDynamicCodeAttribute' when publishing as Native AOT" -description: "Learn about warning IL3050: Members annotated with 'RequiresDynamicCodeAttribute' require code generation at run time" +description: "Learn about warning IL3050: Members annotated with 'RequiresDynamicCodeAttribute' require code generation at runtime" ms.date: 09/01/2022 ms.author: michals author: MichalStrehovsky @@ -11,11 +11,11 @@ f1_keywords: ## Cause -When you publish an app as Native AOT (by setting the `PublishAot` property to `true` in a project), calling members annotated with the `RequiresDynamicCodeAttribute` attribute might result in exceptions at run time. Members annotated with this attribute might require ability to dynamically create new code at run time, and Native AOT publishing model doesn't provide a way to generate native code at run time. +When you publish an app as Native AOT (by setting the `PublishAot` property to `true` in a project), calling members annotated with the `RequiresDynamicCodeAttribute` attribute might result in exceptions at runtime. Members annotated with this attribute might require ability to dynamically create new code at runtime, and Native AOT publishing model doesn't provide a way to generate native code at runtime. ## Rule description - indicates that the member references code that might require code generation at run time. + indicates that the member references code that might require code generation at runtime. ## Example diff --git a/docs/core/deploying/native-aot/warnings/il3052.md b/docs/core/deploying/native-aot/warnings/il3052.md index d2cb35c12c1a8..bbe7644dcc20c 100644 --- a/docs/core/deploying/native-aot/warnings/il3052.md +++ b/docs/core/deploying/native-aot/warnings/il3052.md @@ -13,7 +13,7 @@ f1_keywords: Built-in COM is not supported with Native AOT compilation. Use [COM wrappers](../../../../standard/native-interop/com-wrappers.md) instead. -When the unsupported code path is reached at run time, an exception will be thrown. +When the unsupported code path is reached at runtime, an exception will be thrown. ## Example diff --git a/docs/core/deploying/native-aot/warnings/il3053.md b/docs/core/deploying/native-aot/warnings/il3053.md index b74f857de5c78..f701459c4c5ba 100644 --- a/docs/core/deploying/native-aot/warnings/il3053.md +++ b/docs/core/deploying/native-aot/warnings/il3053.md @@ -1,6 +1,6 @@ --- title: "IL3053: Assembly produced AOT warnings" -description: "Learn about warning IL3053: Assembly contains code that is not compatible with Native AOT and may not work correctly at run time." +description: "Learn about warning IL3053: Assembly contains code that is not compatible with Native AOT and may not work correctly at runtime." ms.date: 09/01/2022 ms.author: michals author: MichalStrehovsky diff --git a/docs/core/deploying/native-aot/warnings/il3054.md b/docs/core/deploying/native-aot/warnings/il3054.md index 78ecf1a3b5e05..022d34b16a7a3 100644 --- a/docs/core/deploying/native-aot/warnings/il3054.md +++ b/docs/core/deploying/native-aot/warnings/il3054.md @@ -15,9 +15,9 @@ Methods on generic types and generic methods that are instantiated over differen It is possible to form a cycle between generic instantiations in a way that the number of native code bodies required to support the application becomes unbounded. Because Native AOT deployments require generating all native method bodies at the time of publishing the application, this would require compiling an infinite number of methods. -When the AOT compilation process detects such unbounded growth, it cuts off the growth by generating a throwing method. If the application goes beyond the cutoff point at run time, an exception is thrown. +When the AOT compilation process detects such unbounded growth, it cuts off the growth by generating a throwing method. If the application goes beyond the cutoff point at runtime, an exception is thrown. -Even though it's unlikely the throwing method body will be reached at run time, it's advisable to remove the generic recursion by restructuring the code. Generic recursion negatively affects compilation speed and the size of the output executable. +Even though it's unlikely the throwing method body will be reached at runtime, it's advisable to remove the generic recursion by restructuring the code. Generic recursion negatively affects compilation speed and the size of the output executable. In .NET, generic code instantiated over reference type is shared across all reference typed instantiations (for example, the code to support `List` and `List` is the same). However, additional native data structures are needed to express the "generic context" (the thing that gets substituted for `T`). It is possible to form generic recursion within these data structures as well. For example, this can happen if the generic context for `Foo` needs to refer to `Foo>` that in turn needs `Foo>>`. @@ -45,7 +45,7 @@ static int CauseGenericRecursion(int i) => 1 + CauseGenericRecursion { } ``` -The behavior of the program at run time for input "100": +The behavior of the program at runtime for input "100": ``` Unhandled Exception: System.TypeLoadException: Could not load type 'Program' from assembly 'repro, Version=7.0.0.0, Culture=neutral, PublicKeyToken=null'. diff --git a/docs/core/deploying/native-aot/warnings/il3055.md b/docs/core/deploying/native-aot/warnings/il3055.md index 43437c16d1eb7..584cd44b8e424 100644 --- a/docs/core/deploying/native-aot/warnings/il3055.md +++ b/docs/core/deploying/native-aot/warnings/il3055.md @@ -11,7 +11,7 @@ f1_keywords: ## Cause -P/Invoke marshalling code needs to be generated ahead of time. If marshalling code for a delegate wasn't pregenerated, P/Invoke marshalling will fail with an exception at run time. +P/Invoke marshalling code needs to be generated ahead of time. If marshalling code for a delegate wasn't pregenerated, P/Invoke marshalling will fail with an exception at runtime. Marshalling code is generated for delegate types that either: @@ -19,7 +19,7 @@ Marshalling code is generated for delegate types that either: - Appear as fields of types passed to native code via P/Invoke. - Are decorated with . -If a concrete type can't be inferred from the P/Invoke signature, marshalling code might not be available at run time and the P/Invoke will throw an exception. +If a concrete type can't be inferred from the P/Invoke signature, marshalling code might not be available at runtime and the P/Invoke will throw an exception. Replace or in the P/Invoke signature with a concrete delegate type. diff --git a/docs/core/deploying/ready-to-run.md b/docs/core/deploying/ready-to-run.md index c0e4f653f53b8..9554d7c95988c 100644 --- a/docs/core/deploying/ready-to-run.md +++ b/docs/core/deploying/ready-to-run.md @@ -39,7 +39,7 @@ There are two ways to publish your app as ReadyToRun: ## Impact of using the ReadyToRun feature -Ahead-of-time compilation has complex performance impact on application performance, which can be difficult to predict. In general, the size of an assembly will grow to between two to three times larger. This increase in the physical size of the file may reduce the performance of loading the assembly from disk, and increase working set of the process. However, in return the number of methods compiled at run time is typically reduced substantially. The result is that most applications that have large amounts of code receive large performance benefits from enabling ReadyToRun. Applications that have small amounts of code will likely not experience a significant improvement from enabling ReadyToRun, as the .NET runtime libraries have already been precompiled with ReadyToRun. +Ahead-of-time compilation has complex performance impact on application performance, which can be difficult to predict. In general, the size of an assembly will grow to between two to three times larger. This increase in the physical size of the file may reduce the performance of loading the assembly from disk, and increase working set of the process. However, in return the number of methods compiled at runtime is typically reduced substantially. The result is that most applications that have large amounts of code receive large performance benefits from enabling ReadyToRun. Applications that have small amounts of code will likely not experience a significant improvement from enabling ReadyToRun, as the .NET runtime libraries have already been precompiled with ReadyToRun. The startup improvement discussed here applies not only to application startup, but also to the first use of any code in the application. For instance, ReadyToRun can be used to reduce the response latency of the first use of Web API in an ASP.NET application. diff --git a/docs/core/deploying/trimming/incompatibilities.md b/docs/core/deploying/trimming/incompatibilities.md index fcd1c079771b9..d9ce7733f233b 100644 --- a/docs/core/deploying/trimming/incompatibilities.md +++ b/docs/core/deploying/trimming/incompatibilities.md @@ -43,11 +43,11 @@ The following sections list known incompatibilities with trimming on Windows. Alternative: [COM Wrappers](../../../standard/native-interop/com-wrappers.md) -Automatic [COM marshalling](../../../standard/native-interop/cominterop.md) has been built in to .NET since .NET Framework 1.0. It uses run-time code analysis to automatically convert between native COM objects and managed .NET objects. Unfortunately, trimming analysis can't always predict what .NET code needs to be preserved for automatic COM marshalling. However, if [COM Wrappers](../../../standard/native-interop/com-wrappers.md) are used instead, trimming analysis can guarantee that all used code will be correctly preserved. +Automatic [COM marshalling](../../../standard/native-interop/cominterop.md) has been built in to .NET since .NET Framework 1.0. It uses runtime code analysis to automatically convert between native COM objects and managed .NET objects. Unfortunately, trimming analysis can't always predict what .NET code needs to be preserved for automatic COM marshalling. However, if [COM Wrappers](../../../standard/native-interop/com-wrappers.md) are used instead, trimming analysis can guarantee that all used code will be correctly preserved. ### WPF -The Windows Presentation Foundation (WPF) framework makes substantial use of reflection and some features are heavily reliant on run-time code inspection. It's not possible for trimming analysis to preserve all necessary code for WPF applications. Unfortunately, almost no WPF apps are runnable after trimming, so trimming support for WPF is currently disabled in the .NET SDK. See [WPF is not trim-compatible](https://github.com/dotnet/wpf/issues/3811) issue for progress on enabling trimming for WPF. +The Windows Presentation Foundation (WPF) framework makes substantial use of reflection and some features are heavily reliant on runtime code inspection. It's not possible for trimming analysis to preserve all necessary code for WPF applications. Unfortunately, almost no WPF apps are runnable after trimming, so trimming support for WPF is currently disabled in the .NET SDK. See [WPF is not trim-compatible](https://github.com/dotnet/wpf/issues/3811) issue for progress on enabling trimming for WPF. ### Windows Forms diff --git a/docs/core/deploying/trimming/intrinsic-requiresunreferencedcode-apis.md b/docs/core/deploying/trimming/intrinsic-requiresunreferencedcode-apis.md index 4a2512a86934b..aa903fe9a2055 100644 --- a/docs/core/deploying/trimming/intrinsic-requiresunreferencedcode-apis.md +++ b/docs/core/deploying/trimming/intrinsic-requiresunreferencedcode-apis.md @@ -10,7 +10,7 @@ ms.date: 09/13/2024 Under normal circumstances, calling APIs annotated with in an app published with trimming triggers warning [IL2026 (Members attributed with RequiresUnreferencedCode may break when trimming)](trim-warnings/il2026.md). APIs that trigger the warning might not behave correctly in a trimmed deployment. -Some APIs annotated `[RequiresUnreferencedCode]` can still be used without triggering the warning if they're called in a specific pattern. When used as part of a pattern, the call to the API can be statically analyzed by the compiler, does not generate a warning, and behaves as expected at run time. +Some APIs annotated `[RequiresUnreferencedCode]` can still be used without triggering the warning if they're called in a specific pattern. When used as part of a pattern, the call to the API can be statically analyzed by the compiler, does not generate a warning, and behaves as expected at runtime. ## MethodInfo.MakeGenericMethod(Type[]) method diff --git a/docs/core/deploying/trimming/prepare-libraries-for-trimming.md b/docs/core/deploying/trimming/prepare-libraries-for-trimming.md index 8185473604f72..f8a04347230a4 100644 --- a/docs/core/deploying/trimming/prepare-libraries-for-trimming.md +++ b/docs/core/deploying/trimming/prepare-libraries-for-trimming.md @@ -144,14 +144,14 @@ In this case, the trim analysis keeps public methods of , and It's better to resolve warnings by expressing the intent of your code using `[RequiresUnreferencedCode]` and `DynamicallyAccessedMembers` when possible. However, in some cases, you might be interested in enabling trimming of a library that uses patterns that can't be expressed with those attributes, or without refactoring existing code. This section describes some advanced ways to resolve trim analysis warnings. > [!WARNING] -> These techniques might change the behavior or your code or result in run time exceptions if used incorrectly. +> These techniques might change the behavior or your code or result in runtime exceptions if used incorrectly. ### UnconditionalSuppressMessage Consider code that: * The intent can't be expressed with the annotations. -* Generates a warning but doesn't represent a real issue at run time. +* Generates a warning but doesn't represent a real issue at runtime. The warnings can be suppressed by . This is similar to `SuppressMessageAttribute`, but it's persisted in IL and respected during trim analysis. @@ -181,7 +181,7 @@ The [`[DynamicDependency]`](xref:System.Diagnostics.CodeAnalysis.DynamicDependen :::code language="csharp" source="~/docs/core/deploying/trimming/snippets/MyLibrary/Class1.cs" id="snippet_AD4" highlight="1"::: -Without `DynamicDependency`, trimming might remove `Helper` from `MyAssembly` or remove `MyAssembly` completely if it's not referenced elsewhere, producing a warning that indicates a possible failure at run time. The attribute ensures that `Helper` is kept. +Without `DynamicDependency`, trimming might remove `Helper` from `MyAssembly` or remove `MyAssembly` completely if it's not referenced elsewhere, producing a warning that indicates a possible failure at runtime. The attribute ensures that `Helper` is kept. The attribute specifies the members to keep via a `string` or via `DynamicallyAccessedMemberTypes`. The type and assembly are either implicit in the attribute context, or explicitly specified in the attribute (by `Type`, or by `string`s for the type and assembly name). diff --git a/docs/core/deploying/trimming/trim-self-contained.md b/docs/core/deploying/trimming/trim-self-contained.md index 29588dce3e9bc..7af38701597a7 100644 --- a/docs/core/deploying/trimming/trim-self-contained.md +++ b/docs/core/deploying/trimming/trim-self-contained.md @@ -11,7 +11,7 @@ The [framework-dependent deployment model](../index.md#framework-dependent-deplo The trim-self-contained deployment model is a specialized version of the self-contained deployment model that is optimized to reduce deployment size. Minimizing deployment size is a critical requirement for some client-side scenarios like Blazor applications. Depending on the complexity of the application, only a subset of the framework assemblies are referenced, and a subset of the code within each assembly is required to run the application. The unused parts of the libraries are unnecessary and can be trimmed from the packaged application. -However, there is a risk that the build-time analysis of the application can cause failures at run time, due to not being able to reliably analyze various problematic code patterns (largely centered on reflection use). To mitigate these problems, warnings are produced whenever the trimmer cannot fully analyze a code pattern. For information on what the trim warnings mean and how to resolve them, see [Fix trim warnings](fixing-warnings.md). To understand how trimming works and why certain patterns cause warnings, see [Understanding trim analysis](trimming-concepts.md). +However, there is a risk that the build-time analysis of the application can cause failures at runtime, due to not being able to reliably analyze various problematic code patterns (largely centered on reflection use). To mitigate these problems, warnings are produced whenever the trimmer cannot fully analyze a code pattern. For information on what the trim warnings mean and how to resolve them, see [Fix trim warnings](fixing-warnings.md). To understand how trimming works and why certain patterns cause warnings, see [Understanding trim analysis](trimming-concepts.md). > [!NOTE] > diff --git a/docs/core/deploying/trimming/trim-warnings/il2026.md b/docs/core/deploying/trimming/trim-warnings/il2026.md index d05d8febcfada..883562a80218a 100644 --- a/docs/core/deploying/trimming/trim-warnings/il2026.md +++ b/docs/core/deploying/trimming/trim-warnings/il2026.md @@ -41,7 +41,7 @@ Common examples include: - is marked as `RequiresUnreferencedCode` because the Assembly being loaded may access members that have been trimmed away. The trimmer removes all members from the framework except the ones directly used by the -application, so it is likely that loading new Assemblies at run time will try to access +application, so it is likely that loading new Assemblies at runtime will try to access missing members. - is marked as `RequiresUnreferencedCode` diff --git a/docs/core/diagnostics/diagnosticsource-diagnosticlistener.md b/docs/core/diagnostics/diagnosticsource-diagnosticlistener.md index e3caaf1d7477b..10d26f6cd83e3 100644 --- a/docs/core/diagnostics/diagnosticsource-diagnosticlistener.md +++ b/docs/core/diagnostics/diagnosticsource-diagnosticlistener.md @@ -8,7 +8,7 @@ ms.date: 05/12/2022 **This article applies to: ✔️** .NET Core 3.1 and later versions **✔️** .NET Framework 4.5 and later versions is a module that allows code to be instrumented for production-time -logging of rich data payloads for consumption within the process that was instrumented. At run time, consumers can dynamically discover +logging of rich data payloads for consumption within the process that was instrumented. At runtime, consumers can dynamically discover data sources and subscribe to the ones of interest. was designed to allow in-process tools to access rich data. When using , the consumer is assumed to be within the same process and as a result, non-serializable types (for example, `HttpResponseMessage` or `HttpContext`) can be passed, @@ -84,7 +84,7 @@ Combining everything you have: The first step in receiving events is to discover which `DiagnosticListeners` you are interested in. `DiagnosticListener` supports a way of discovering `DiagnosticListeners` that are -active in the system at run time. The API to accomplish this is the property. +active in the system at runtime. The API to accomplish this is the property. Implement an `Observer` class that inherits from the `IObservable` interface, which is the 'callback' version of the `IEnumerable` interface. You can learn more about it at the [Reactive Extensions](https://github.com/dotnet/reactive) site. An `IObserver` has three callbacks, `OnNext`, `OnComplete`, diff --git a/docs/core/diagnostics/dotnet-counters.md b/docs/core/diagnostics/dotnet-counters.md index 6a4e25f44e9df..8023184fb9318 100644 --- a/docs/core/diagnostics/dotnet-counters.md +++ b/docs/core/diagnostics/dotnet-counters.md @@ -424,4 +424,4 @@ However, when you want to gain a finer control over the lifetime of the app bein > ``` > [!IMPORTANT] - > Launching your app with `dotnet run` can be problematic because the dotnet CLI might spawn many child processes that aren't your app and they can connect to `dotnet-counters` before your app, leaving your app to be suspended at run time. It's recommended you directly use a self-contained version of the app or use `dotnet exec` to launch the application. + > Launching your app with `dotnet run` can be problematic because the dotnet CLI might spawn many child processes that aren't your app and they can connect to `dotnet-counters` before your app, leaving your app to be suspended at runtime. It's recommended you directly use a self-contained version of the app or use `dotnet exec` to launch the application. diff --git a/docs/core/diagnostics/dotnet-trace.md b/docs/core/diagnostics/dotnet-trace.md index b2f6512906ca9..52764a2578666 100644 --- a/docs/core/diagnostics/dotnet-trace.md +++ b/docs/core/diagnostics/dotnet-trace.md @@ -464,7 +464,7 @@ However, when you want to gain a finer control over the lifetime of the app bein > ``` > [!IMPORTANT] - > Launching your app with `dotnet run` can be problematic because the dotnet CLI may spawn many child processes that are not your app and they can connect to `dotnet-trace` before your app, leaving your app to be suspended at run time. It is recommended you directly use a self-contained version of the app or use `dotnet exec` to launch the application. + > Launching your app with `dotnet run` can be problematic because the dotnet CLI may spawn many child processes that are not your app and they can connect to `dotnet-trace` before your app, leaving your app to be suspended at runtime. It is recommended you directly use a self-contained version of the app or use `dotnet exec` to launch the application. ## View the trace captured from dotnet-trace diff --git a/docs/core/diagnostics/specialized-diagnostics-overview.md b/docs/core/diagnostics/specialized-diagnostics-overview.md index f6942465cec7e..16abe55f46313 100644 --- a/docs/core/diagnostics/specialized-diagnostics-overview.md +++ b/docs/core/diagnostics/specialized-diagnostics-overview.md @@ -37,7 +37,7 @@ The .NET runtime exposes a service endpoint that allows other processes to send ## DiagnosticSource & DiagnosticListener -[DiagnosticSource](./diagnosticsource-diagnosticlistener.md) is a module that allows code to be instrumented for production-time logging of rich data payloads for consumption within the process that was instrumented. At run time, consumers can dynamically discover data sources and subscribe to the ones of interest. was designed to allow in-process tools to access rich data, such as by [OpenTelemetry instrumentation libraries](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/blob/main/src/OpenTelemetry.Instrumentation.AspNetCore/README.md). DiagnosticSource data can also be egressed via EventPipe, which enables rich diagnostic data to be collected by dedicated tools. +[DiagnosticSource](./diagnosticsource-diagnosticlistener.md) is a module that allows code to be instrumented for production-time logging of rich data payloads for consumption within the process that was instrumented. At runtime, consumers can dynamically discover data sources and subscribe to the ones of interest. was designed to allow in-process tools to access rich data, such as by [OpenTelemetry instrumentation libraries](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/blob/main/src/OpenTelemetry.Instrumentation.AspNetCore/README.md). DiagnosticSource data can also be egressed via EventPipe, which enables rich diagnostic data to be collected by dedicated tools. ## Collect diagnostics in containers diff --git a/docs/core/diagnostics/trace-perfcollect-lttng.md b/docs/core/diagnostics/trace-perfcollect-lttng.md index 15c996661f1c3..328e6c413f4cb 100644 --- a/docs/core/diagnostics/trace-perfcollect-lttng.md +++ b/docs/core/diagnostics/trace-perfcollect-lttng.md @@ -41,7 +41,7 @@ Follow these steps to prepare your machine to collect a performance trace with ` This will install the following prerequisites on your machine: 1. `perf`: the Linux Performance Events subsystem and companion user-mode collection/viewer application. `perf` is part of the Linux kernel source, but is not usually installed by default. - 1. `LTTng`: Used to capture event data emitted at run time by CoreCLR. This data is then used to analyze the behavior of various runtime components such as the GC, JIT, and thread pool. + 1. `LTTng`: Used to capture event data emitted at runtime by CoreCLR. This data is then used to analyze the behavior of various runtime components such as the GC, JIT, and thread pool. Recent versions of .NET Core and the Linux perf tool support automatic resolution of method names for framework code. diff --git a/docs/core/extensions/best-practices-for-developing-world-ready-apps.md b/docs/core/extensions/best-practices-for-developing-world-ready-apps.md index ef9988e8c963b..29b453b16192e 100644 --- a/docs/core/extensions/best-practices-for-developing-world-ready-apps.md +++ b/docs/core/extensions/best-practices-for-developing-world-ready-apps.md @@ -55,7 +55,7 @@ This section describes the best practices to follow when developing world-ready 1. Do not put non-localizable resources into the resource-only DLLs. This confuses translators. -1. Do not use composite strings that are built at run time from concatenated phrases. Composite strings are difficult to localize because they often assume an English grammatical order that does not apply to all languages. +1. Do not use composite strings that are built at runtime from concatenated phrases. Composite strings are difficult to localize because they often assume an English grammatical order that does not apply to all languages. 1. Avoid ambiguous constructs such as "Empty Folder" where the strings can be translated differently depending on the grammatical roles of the string components. For example, "empty" can be either a verb or an adjective, which can lead to different translations in languages such as Italian or French. diff --git a/docs/core/extensions/configuration-providers.md b/docs/core/extensions/configuration-providers.md index f6f31d284a5b2..bb0c5cd5f5cff 100644 --- a/docs/core/extensions/configuration-providers.md +++ b/docs/core/extensions/configuration-providers.md @@ -72,7 +72,7 @@ The application writes the following sample output: ### XML configuration provider -The class loads configuration from an XML file at run time. Install the [`Microsoft.Extensions.Configuration.Xml`](https://www.nuget.org/packages/Microsoft.Extensions.Configuration.Xml) NuGet package. +The class loads configuration from an XML file at runtime. Install the [`Microsoft.Extensions.Configuration.Xml`](https://www.nuget.org/packages/Microsoft.Extensions.Configuration.Xml) NuGet package. The following code demonstrates the configuration of XML files using the XML configuration provider. @@ -127,7 +127,7 @@ The previous configuration file loads the following keys with `value`: ### INI configuration provider -The class loads configuration from an INI file at run time. Install the [`Microsoft.Extensions.Configuration.Ini`](https://www.nuget.org/packages/Microsoft.Extensions.Configuration.Ini) NuGet package. +The class loads configuration from an INI file at runtime. Install the [`Microsoft.Extensions.Configuration.Ini`](https://www.nuget.org/packages/Microsoft.Extensions.Configuration.Ini) NuGet package. The following code clears all the configuration providers and adds the `IniConfigurationProvider` with two INI files as the source: diff --git a/docs/core/extensions/create-resource-files.md b/docs/core/extensions/create-resource-files.md index 1d489f0b103de..28cf5e2baf6d8 100644 --- a/docs/core/extensions/create-resource-files.md +++ b/docs/core/extensions/create-resource-files.md @@ -191,7 +191,7 @@ You can use the diff --git a/docs/core/extensions/dependency-injection-guidelines.md b/docs/core/extensions/dependency-injection-guidelines.md index b813f82b612ff..a97a195bf5e6d 100644 --- a/docs/core/extensions/dependency-injection-guidelines.md +++ b/docs/core/extensions/dependency-injection-guidelines.md @@ -150,7 +150,7 @@ The factory method of a singleton service, such as the second argument to [AddSi - Avoid static access to services. For example, avoid capturing [IApplicationBuilder.ApplicationServices](xref:Microsoft.AspNetCore.Builder.IApplicationBuilder.ApplicationServices) as a static field or property for use elsewhere. - Keep [DI factories](#async-di-factories-can-cause-deadlocks) fast and synchronous. - Avoid using the [*service locator pattern*](#scoped-service-as-singleton). For example, don't invoke to obtain a service instance when you can use DI instead. -- Another service locator variation to avoid is injecting a factory that resolves dependencies at run time. Both of these practices mix [Inversion of Control](/dotnet/standard/modern-web-apps-azure-architecture/architectural-principles#dependency-inversion) strategies. +- Another service locator variation to avoid is injecting a factory that resolves dependencies at runtime. Both of these practices mix [Inversion of Control](/dotnet/standard/modern-web-apps-azure-architecture/architectural-principles#dependency-inversion) strategies. - Avoid calls to when configuring services. Calling `BuildServiceProvider` typically happens when the developer wants to resolve a service when registering another service. Instead, use an overload that includes the `IServiceProvider` for this reason. - [Disposable transient services are captured](#disposable-transient-services-captured-by-container) by the container for disposal. This can turn into a memory leak if resolved from the top-level container. - Enable scope validation to make sure the app doesn't have singletons that capture scoped services. For more information, see [Scope validation](dependency-injection.md#scope-validation). diff --git a/docs/core/extensions/dependency-injection-usage.md b/docs/core/extensions/dependency-injection-usage.md index 57b90f8d723c3..c19c5749c8396 100644 --- a/docs/core/extensions/dependency-injection-usage.md +++ b/docs/core/extensions/dependency-injection-usage.md @@ -113,7 +113,7 @@ The app: ## Conclusion -In this sample app, you created several interfaces and corresponding implementations. Each of these services is uniquely identified and paired with a . The sample app demonstrates registering service implementations against an interface, and how to register pure classes without backing interfaces. The sample app then demonstrates how dependencies defined as constructor parameters are resolved at run time. +In this sample app, you created several interfaces and corresponding implementations. Each of these services is uniquely identified and paired with a . The sample app demonstrates registering service implementations against an interface, and how to register pure classes without backing interfaces. The sample app then demonstrates how dependencies defined as constructor parameters are resolved at runtime. When you run the app, it displays output similar to the following: diff --git a/docs/core/extensions/globalization.md b/docs/core/extensions/globalization.md index 2375f31553502..90fef8e31f3a2 100644 --- a/docs/core/extensions/globalization.md +++ b/docs/core/extensions/globalization.md @@ -118,7 +118,7 @@ The following example is similar to the previous example. However, instead of ca ### Avoid string concatenation -If at all possible, avoid using composite strings that are built at run time from concatenated phrases. Composite strings are difficult to localize, because they often assume a grammatical order in the app's original language that does not apply to other localized languages. +If at all possible, avoid using composite strings that are built at runtime from concatenated phrases. Composite strings are difficult to localize, because they often assume a grammatical order in the app's original language that does not apply to other localized languages. ## Handle dates and times @@ -141,7 +141,7 @@ The following example displays sunrise and sunset data twice for October 11, 201 ### Persist dates and times -You should never persist date and time data in a format that can vary by culture. This is a common programming error that results in either corrupted data or a run-time exception. The following example serializes two dates, January 9, 2013 and August 18, 2013, as strings by using the formatting conventions of the English (United States) culture. When the data is retrieved and parsed by using the conventions of the English (United States) culture, it is successfully restored. However, when it is retrieved and parsed by using the conventions of the English (United Kingdom) culture, the first date is wrongly interpreted as September 1, and the second fails to parse because the Gregorian calendar does not have an eighteenth month. +You should never persist date and time data in a format that can vary by culture. This is a common programming error that results in either corrupted data or a runtime exception. The following example serializes two dates, January 9, 2013 and August 18, 2013, as strings by using the formatting conventions of the English (United States) culture. When the data is retrieved and parsed by using the conventions of the English (United States) culture, it is successfully restored. However, when it is retrieved and parsed by using the conventions of the English (United Kingdom) culture, the first date is wrongly interpreted as September 1, and the second fails to parse because the Gregorian calendar does not have an eighteenth month. [!code-csharp[Conceptual.Globalization#3](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/dates2.cs#3)] [!code-vb[Conceptual.Globalization#3](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.globalization/vb/dates2.vb#3)] @@ -265,7 +265,7 @@ The following example displays the average temperature per month in Paris, Franc ### Persist numeric values -You should never persist numeric data in a culture-specific format. This is a common programming error that results in either corrupted data or a run-time exception. The following example generates ten random floating-point numbers, and then serializes them as strings by using the formatting conventions of the English (United States) culture. When the data is retrieved and parsed by using the conventions of the English (United States) culture, it is successfully restored. However, when it is retrieved and parsed by using the conventions of the French (France) culture, none of the numbers can be parsed because the cultures use different decimal separators. +You should never persist numeric data in a culture-specific format. This is a common programming error that results in either corrupted data or a runtime exception. The following example generates ten random floating-point numbers, and then serializes them as strings by using the formatting conventions of the English (United States) culture. When the data is retrieved and parsed by using the conventions of the English (United States) culture, it is successfully restored. However, when it is retrieved and parsed by using the conventions of the French (France) culture, none of the numbers can be parsed because the cultures use different decimal separators. [!code-csharp[Conceptual.Globalization#6](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/numbers2.cs#6)] [!code-vb[Conceptual.Globalization#6](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.globalization/vb/numbers2.vb#6)] diff --git a/docs/core/extensions/httpclient-factory-keyed-di.md b/docs/core/extensions/httpclient-factory-keyed-di.md index eb508cc0d29ea..84793b989fa67 100644 --- a/docs/core/extensions/httpclient-factory-keyed-di.md +++ b/docs/core/extensions/httpclient-factory-keyed-di.md @@ -10,7 +10,7 @@ ms.date: 01/27/2025 In this article, you learn how to integrate `IHttpClientFactory` with Keyed Services. -[_Keyed Services_](dependency-injection.md#keyed-services) (also called _Keyed DI_) is a dependency injection (DI) feature that allows you to conveniently operate with multiple implementations of a single service. Upon registration, you can associate different _service keys_ with the specific implementations. At run time, this key is used in lookup in combination with a service type, which means you can retrieve a specific implementation by passing the matching key. For more information on Keyed Services, and DI in general, see [.NET dependency injection][di]. +[_Keyed Services_](dependency-injection.md#keyed-services) (also called _Keyed DI_) is a dependency injection (DI) feature that allows you to conveniently operate with multiple implementations of a single service. Upon registration, you can associate different _service keys_ with the specific implementations. At runtime, this key is used in lookup in combination with a service type, which means you can retrieve a specific implementation by passing the matching key. For more information on Keyed Services, and DI in general, see [.NET dependency injection][di]. For an overview on how to use `IHttpClientFactory` in your .NET application, see [IHttpClientFactory with .NET][hcf]. diff --git a/docs/core/extensions/httpclient-latency-extensions.md b/docs/core/extensions/httpclient-latency-extensions.md index 7d15c9107e347..b4501d99ddcf1 100644 --- a/docs/core/extensions/httpclient-latency-extensions.md +++ b/docs/core/extensions/httpclient-latency-extensions.md @@ -136,4 +136,4 @@ For example: HTTP client latency telemetry runs on all supported targets (.NET 9, .NET 8, .NET Standard 2.0, and .NET Framework 4.6.2). Core timing checkpoints are always collected. The GC pause metric (Http.GCPauseTime) is emitted only when running on .NET 8 or .NET 9. -The implementation detects platform capabilities at run time and enables what is supported without additional configuration. +The implementation detects platform capabilities at runtime and enables what is supported without additional configuration. diff --git a/docs/core/extensions/log-buffering.md b/docs/core/extensions/log-buffering.md index e69f0943d434f..73db6079c24dc 100644 --- a/docs/core/extensions/log-buffering.md +++ b/docs/core/extensions/log-buffering.md @@ -171,7 +171,7 @@ For each log record, the algorithm checks: ### Change buffer filtering rules in a running app -Both [global buffering](#global-buffering) and [per-request buffering](#per-request-buffering) support run-time configuration updates via the interface. If you're using a configuration provider that supports reloads—such as the [File Configuration Provider](configuration-providers.md#file-configuration-provider)—you can update filtering rules at run time without restarting the application. +Both [global buffering](#global-buffering) and [per-request buffering](#per-request-buffering) support runtime configuration updates via the interface. If you're using a configuration provider that supports reloads—such as the [File Configuration Provider](configuration-providers.md#file-configuration-provider)—you can update filtering rules at runtime without restarting the application. For example, you can start your application with the following _appsettings.json_, which enables log buffering for logs with the level and category starting with `PerRequestLogBufferingFileBased.`: @@ -187,7 +187,7 @@ The new rules are applied automatically. For example, with the preceding configu Log buffering offers a trade-off between memory usage and log storage costs. Buffering logs in memory allows you to: -1. Selectively emit logs based on run-time conditions. +1. Selectively emit logs based on runtime conditions. 1. Drop unnecessary logs without writing them to storage. However, be mindful of the memory consumption, especially in high-throughput applications. Configure appropriate buffer size limits to prevent excessive memory usage. diff --git a/docs/core/extensions/logger-message-generator.md b/docs/core/extensions/logger-message-generator.md index 914133275c5e4..b87034f8342e6 100644 --- a/docs/core/extensions/logger-message-generator.md +++ b/docs/core/extensions/logger-message-generator.md @@ -9,7 +9,7 @@ ai-usage: ai-assisted .NET 6 introduces the `LoggerMessageAttribute` type. This attribute is part of the `Microsoft.Extensions.Logging` namespace, and when used, it source-generates performant logging APIs. The source-generation logging support is designed to deliver a highly usable and highly performant logging solution for modern .NET applications. The auto-generated source code relies on the interface in conjunction with functionality. -The source generator is triggered when `LoggerMessageAttribute` is used on `partial` logging methods. When triggered, it's either able to autogenerate the implementation of the `partial` methods it's decorating, or produce compile-time diagnostics with hints about proper usage. The compile-time logging solution is considerably faster at run time than existing logging approaches. It achieves this by eliminating boxing, temporary allocations, and copies to the maximum extent possible. +The source generator is triggered when `LoggerMessageAttribute` is used on `partial` logging methods. When triggered, it's either able to autogenerate the implementation of the `partial` methods it's decorating, or produce compile-time diagnostics with hints about proper usage. The compile-time logging solution is considerably faster at runtime than existing logging approaches. It achieves this by eliminating boxing, temporary allocations, and copies to the maximum extent possible. ## Basic usage diff --git a/docs/core/extensions/options-validation-generator.md b/docs/core/extensions/options-validation-generator.md index 7adcf3d56ccb6..f2378af9017c4 100644 --- a/docs/core/extensions/options-validation-generator.md +++ b/docs/core/extensions/options-validation-generator.md @@ -8,7 +8,7 @@ ms.date: 12/18/2023 # Compile-time options validation source generation -In the [options pattern](options.md), various methods for validating options are presented. These methods include using data annotation attributes or employing a custom validator. Data annotation attributes are validated at run time and can incur performance costs. This article demonstrates how to utilize the options validation source generator to produce optimized validation code at compile time. +In the [options pattern](options.md), various methods for validating options are presented. These methods include using data annotation attributes or employing a custom validator. Data annotation attributes are validated at runtime and can incur performance costs. This article demonstrates how to utilize the options validation source generator to produce optimized validation code at compile time. ## Automatic IValidateOptions implementation generation diff --git a/docs/core/extensions/options.md b/docs/core/extensions/options.md index e0138465e3310..d5adb6e42af68 100644 --- a/docs/core/extensions/options.md +++ b/docs/core/extensions/options.md @@ -330,7 +330,7 @@ builder.Services }, "VerbosityLevel must be > than Scale."); ``` -The validation occurs at run time, but you can configure it to occur at startup by instead chaining a call to `ValidateOnStart`: +The validation occurs at runtime, but you can configure it to occur at startup by instead chaining a call to `ValidateOnStart`: ```csharp builder.Services diff --git a/docs/core/extensions/resources.md b/docs/core/extensions/resources.md index 70da39ecf5c69..3b8f5b3dc0f7f 100644 --- a/docs/core/extensions/resources.md +++ b/docs/core/extensions/resources.md @@ -37,7 +37,7 @@ For more information, see the [Packaging and Deploying Resources](package-and-de ## Retrieve resources -At run time, an app loads the appropriate localized resources on a per-thread basis, based on the culture specified by the property. This property value is derived as follows: +At runtime, an app loads the appropriate localized resources on a per-thread basis, based on the culture specified by the property. This property value is derived as follows: - By directly assigning a object that represents the localized culture to the property. @@ -49,7 +49,7 @@ For more information about how the current UI culture is set, see the class. Although the class is most commonly used for retrieving resources, the namespace contains additional types that you can use to retrieve resources. These include: -- The class, which enables you to enumerate resources embedded in an assembly or stored in a standalone binary .resources file. It is useful when you don't know the precise names of the resources that are available at run time. +- The class, which enables you to enumerate resources embedded in an assembly or stored in a standalone binary .resources file. It is useful when you don't know the precise names of the resources that are available at runtime. - The class, which enables you to retrieve resources from an XML (.resx) file. diff --git a/docs/core/extensions/retrieve-resources.md b/docs/core/extensions/retrieve-resources.md index 9dfd4cee99cb4..4487f91148885 100644 --- a/docs/core/extensions/retrieve-resources.md +++ b/docs/core/extensions/retrieve-resources.md @@ -2,10 +2,10 @@ title: "Retrieve resources in .NET apps" description: Retrieve resources in .NET apps. Package resources for the default (neutral) culture with the main assembly and create a satellite assembly for each culture. ms.date: 03/13/2023 -dev_langs: +dev_langs: - "csharp" - "vb" -helpviewer_keywords: +helpviewer_keywords: - "deploying applications [.NET Framework], resources" - "resource files, deploying" - "resource files, packaging" @@ -29,7 +29,7 @@ When you work with localized resources in .NET apps, you should ideally package ## Retrieve resources from assemblies -The class provides access to resources at run time. You use the method to retrieve string resources and the or method to retrieve non-string resources. Each method has two overloads: +The class provides access to resources at runtime. You use the method to retrieve string resources and the or method to retrieve non-string resources. Each method has two overloads: - An overload whose single parameter is a string that contains the name of the resource. The method attempts to retrieve that resource for the current culture. For more information, see the , , and methods. diff --git a/docs/core/extensions/work-with-resx-files-programmatically.md b/docs/core/extensions/work-with-resx-files-programmatically.md index 077e9316d37b1..eeb5043dd9b7c 100644 --- a/docs/core/extensions/work-with-resx-files-programmatically.md +++ b/docs/core/extensions/work-with-resx-files-programmatically.md @@ -68,7 +68,7 @@ You cannot embed a .resx file in a runtime executable or compile it into a satel ## Convert .resx files to binary .resources files - Converting .resx files to embedded binary resource (*.resources*) files has significant advantages. Although .resx files are easy to read and maintain during application development, they are rarely included with finished applications. If they are distributed with an application, they exist as separate files apart from the application executable and its accompanying libraries. In contrast, *.resources* files are embedded in the application executable or its accompanying assemblies. In addition, for localized applications, relying on .resx files at run time places the responsibility for handling resource fallback on the developer. In contrast, if a set of satellite assemblies that contain embedded .resources files has been created, the common language runtime handles the resource fallback process. + Converting .resx files to embedded binary resource (*.resources*) files has significant advantages. Although .resx files are easy to read and maintain during application development, they are rarely included with finished applications. If they are distributed with an application, they exist as separate files apart from the application executable and its accompanying libraries. In contrast, *.resources* files are embedded in the application executable or its accompanying assemblies. In addition, for localized applications, relying on .resx files at runtime places the responsibility for handling resource fallback on the developer. In contrast, if a set of satellite assemblies that contain embedded .resources files has been created, the common language runtime handles the resource fallback process. To convert a *.resx* file to a *.resources* file, you use [Resource File Generator (*resgen.exe*)](../../framework/tools/resgen-exe-resource-file-generator.md), which has the following basic syntax: diff --git a/docs/core/porting/framework-overview.md b/docs/core/porting/framework-overview.md index dbfdd8026f804..6c1d7cc33617f 100644 --- a/docs/core/porting/framework-overview.md +++ b/docs/core/porting/framework-overview.md @@ -182,7 +182,7 @@ For more information, see the [`try-convert` GitHub repository](https://github.c ### Platform compatibility analyzer -The [Platform compatibility analyzer](../../standard/analyzers/platform-compat-analyzer.md) analyzes whether or not you're using an API that throws a at run time. Although finding one of these APIs is unlikely if you're moving from .NET Framework 4.7.2 or higher, it's good to check. For more information about APIs that throw exceptions on .NET, see [APIs that always throw exceptions on .NET Core](../compatibility/unsupported-apis.md). +The [Platform compatibility analyzer](../../standard/analyzers/platform-compat-analyzer.md) analyzes whether or not you're using an API that throws a at runtime. Although finding one of these APIs is unlikely if you're moving from .NET Framework 4.7.2 or higher, it's good to check. For more information about APIs that throw exceptions on .NET, see [APIs that always throw exceptions on .NET Core](../compatibility/unsupported-apis.md). For more information, see [Platform compatibility analyzer](../../standard/analyzers/platform-compat-analyzer.md). diff --git a/docs/core/project-sdk/msbuild-props.md b/docs/core/project-sdk/msbuild-props.md index 1a049f6c169a6..622396efac6c6 100644 --- a/docs/core/project-sdk/msbuild-props.md +++ b/docs/core/project-sdk/msbuild-props.md @@ -478,9 +478,9 @@ This property is useful if you run `dotnet publish` on a solution file, as it al ### PreserveCompilationContext -The `PreserveCompilationContext` property allows a built or published application to compile more code at run time using the same settings that were used at build time. The assemblies referenced at build time will be copied into the *ref* subdirectory of the output directory. The names of the reference assemblies are stored in the application's *.deps.json* file along with the options passed to the compiler. You can retrieve this information using the and properties. +The `PreserveCompilationContext` property allows a built or published application to compile more code at runtime using the same settings that were used at build time. The assemblies referenced at build time will be copied into the *ref* subdirectory of the output directory. The names of the reference assemblies are stored in the application's *.deps.json* file along with the options passed to the compiler. You can retrieve this information using the and properties. -This functionality is mostly used internally by ASP.NET Core MVC and Razor pages to support run-time compilation of Razor files. +This functionality is mostly used internally by ASP.NET Core MVC and Razor pages to support runtime compilation of Razor files. ```xml @@ -525,7 +525,7 @@ This property is an enablement flag for several other properties that control wh ### PublishReferencesDocumentationFiles -When this property is `true`, XML documentation files for the project's references are copied to the publish directory, instead of just run-time assets like DLL files. This property defaults to `true`. +When this property is `true`, XML documentation files for the project's references are copied to the publish directory, instead of just runtime assets like DLL files. This property defaults to `true`. ### PublishRelease diff --git a/docs/core/resilience/http-resilience.md b/docs/core/resilience/http-resilience.md index c08eefe8baa18..fccdc07486c47 100644 --- a/docs/core/resilience/http-resilience.md +++ b/docs/core/resilience/http-resilience.md @@ -209,7 +209,7 @@ There are many options available for each of the resilience strategies. For more ### Dynamic reload -Polly supports dynamic reloading of the configured resilience strategies. This means that you can change the configuration of the resilience strategies at run time. To enable dynamic reload, use the appropriate `AddResilienceHandler` overload that exposes the `ResilienceHandlerContext`. Given the context, call `EnableReloads` of the corresponding resilience strategy options: +Polly supports dynamic reloading of the configured resilience strategies. This means that you can change the configuration of the resilience strategies at runtime. To enable dynamic reload, use the appropriate `AddResilienceHandler` overload that exposes the `ResilienceHandlerContext`. Given the context, call `EnableReloads` of the corresponding resilience strategy options: :::code language="csharp" source="snippets/http-resilience/Program.CustomHandler.cs" id="advanced"::: diff --git a/docs/core/rid-catalog.md b/docs/core/rid-catalog.md index dcd84c686cf70..213cf97cf127b 100644 --- a/docs/core/rid-catalog.md +++ b/docs/core/rid-catalog.md @@ -86,7 +86,7 @@ To be able to use RIDs, you have to know which RIDs exist. For the latest and co RIDs that are considered 'portable'—that is, aren't tied to a specific version or OS distribution—are the recommended choice. This means that portable RIDs should be used for both [building a platform-specific application](./deploying/index.md#native-dependencies) and [creating a NuGet package with RID-specific assets](/nuget/create-packages/supporting-multiple-target-frameworks#architecture-specific-folders). -Starting with .NET 8, the default behavior of the .NET SDK and runtime is to only consider non-version-specific and non-distro-specific RIDs. When restoring and building, the SDK [uses a smaller portable RID graph](./compatibility/sdk/8.0/rid-graph.md). The [returns the platform for which the runtime was built](./compatibility/core-libraries/8.0/runtimeidentifier.md). At run time, .NET finds [RID-specific assets using a known set of portable RIDs](./compatibility/deployment/8.0/rid-asset-list.md). When building an application with RID-specific assets that may be ignored at runtime, the SDK will emit a warning: [NETSDK1206](./tools/sdk-errors/netsdk1206.md). +Starting with .NET 8, the default behavior of the .NET SDK and runtime is to only consider non-version-specific and non-distro-specific RIDs. When restoring and building, the SDK [uses a smaller portable RID graph](./compatibility/sdk/8.0/rid-graph.md). The [returns the platform for which the runtime was built](./compatibility/core-libraries/8.0/runtimeidentifier.md). At runtime, .NET finds [RID-specific assets using a known set of portable RIDs](./compatibility/deployment/8.0/rid-asset-list.md). When building an application with RID-specific assets that may be ignored at runtime, the SDK will emit a warning: [NETSDK1206](./tools/sdk-errors/netsdk1206.md). ### Loading assets for a specific OS version or distribution diff --git a/docs/core/runtime-config/compilation.md b/docs/core/runtime-config/compilation.md index 38188d5e4373f..e2563279d68e8 100644 --- a/docs/core/runtime-config/compilation.md +++ b/docs/core/runtime-config/compilation.md @@ -1,6 +1,6 @@ --- title: Compilation config settings -description: Learn about run-time settings that configure how the JIT compiler works for .NET apps. +description: Learn about runtime settings that configure how the JIT compiler works for .NET apps. ms.date: 10/29/2021 --- # Runtime configuration options for compilation diff --git a/docs/core/runtime-config/debugging-profiling.md b/docs/core/runtime-config/debugging-profiling.md index 7a477b3d20ab7..8cf36fbd94f48 100644 --- a/docs/core/runtime-config/debugging-profiling.md +++ b/docs/core/runtime-config/debugging-profiling.md @@ -1,6 +1,6 @@ --- title: Debugging profiling config settings -description: Learn about run-time settings that configure debugging and profiling for .NET apps. +description: Learn about runtime settings that configure debugging and profiling for .NET apps. ms.date: 11/27/2019 --- # Runtime configuration options for debugging and profiling diff --git a/docs/core/runtime-config/garbage-collector.md b/docs/core/runtime-config/garbage-collector.md index 525c0f3f2ddc3..467d893387a69 100644 --- a/docs/core/runtime-config/garbage-collector.md +++ b/docs/core/runtime-config/garbage-collector.md @@ -1,6 +1,6 @@ --- title: Garbage collector config settings -description: Learn about run-time settings for configuring how the garbage collector manages memory for .NET apps. +description: Learn about runtime settings for configuring how the garbage collector manages memory for .NET apps. ms.date: 08/09/2024 --- # Runtime configuration options for garbage collection @@ -11,7 +11,7 @@ Settings are arranged into groups on this page. The settings within each group a > [!NOTE] > -> - These configurations are only read by the runtime when the GC is initialized (usually this means during the process startup time). If you change an environment variable when a process is already running, the change won't be reflected in that process. Settings that can be changed through APIs at run time, such as [latency level](../../standard/garbage-collection/latency.md), are omitted from this page. +> - These configurations are only read by the runtime when the GC is initialized (usually this means during the process startup time). If you change an environment variable when a process is already running, the change won't be reflected in that process. Settings that can be changed through APIs at runtime, such as [latency level](../../standard/garbage-collection/latency.md), are omitted from this page. > - Because GC is per process, it rarely ever makes sense to set these configurations at the machine level. For example, you wouldn't want every .NET process on a machine to use server GC or the same heap hard limit. > - For number values, use decimal notation for settings in the *runtimeconfig.json* or *runtimeconfig.template.json* file and hexadecimal notation for environment variable settings. For hexadecimal values, you can specify them with or without the "0x" prefix. > - If you're using the environment variables, .NET 6 and later versions standardize on the prefix `DOTNET_` instead of `COMPlus_`. However, the `COMPlus_` prefix continues to work. If you're using a previous version of the .NET runtime, you should still use the `COMPlus_` prefix, for example, `COMPlus_gcServer`. @@ -244,7 +244,7 @@ To use a standalone garbage collector instead of the default GC implementation, - Specifies the threshold size, in bytes, that causes objects to go on the large object heap (LOH). - The default threshold is 85,000 bytes. - The value you specify must be larger than the default threshold. -- The value might be capped by the runtime to the maximum possible size for the current configuration. You can inspect the value in use at run time through the API. +- The value might be capped by the runtime to the maximum possible size for the current configuration. You can inspect the value in use at runtime through the API. | | Setting name | Values | Version introduced | | - | - | - | - | diff --git a/docs/core/runtime-config/globalization.md b/docs/core/runtime-config/globalization.md index 82d40f2458b0c..5c68452d360f9 100644 --- a/docs/core/runtime-config/globalization.md +++ b/docs/core/runtime-config/globalization.md @@ -1,6 +1,6 @@ --- title: Globalization config settings -description: Learn about run-time settings that configure globalization aspects of a .NET Core app, for example, how it parses Japanese dates. +description: Learn about runtime settings that configure globalization aspects of a .NET Core app, for example, how it parses Japanese dates. ms.date: 05/18/2020 --- # Runtime configuration options for globalization diff --git a/docs/core/runtime-config/networking.md b/docs/core/runtime-config/networking.md index e42488b144b57..0b20557a3b562 100644 --- a/docs/core/runtime-config/networking.md +++ b/docs/core/runtime-config/networking.md @@ -1,6 +1,6 @@ --- title: Networking config settings -description: Learn about run-time settings that configure networking for .NET apps. +description: Learn about runtime settings that configure networking for .NET apps. ms.date: 11/27/2019 --- # Runtime configuration options for networking diff --git a/docs/core/testing/microsoft-testing-platform-intro.md b/docs/core/testing/microsoft-testing-platform-intro.md index 21f5e558f600a..cf7cf7939dbd4 100644 --- a/docs/core/testing/microsoft-testing-platform-intro.md +++ b/docs/core/testing/microsoft-testing-platform-intro.md @@ -175,16 +175,35 @@ To run a test, navigate to **Test Explorer**, select the test (or tests) to run. ### [Continuous integration (CI)](#tab/continuous-integration) -There's no special pipeline task, or any extra tooling to run `Testing.Platform` tests. There's also no other tooling required to run multiple tests projects through a single command. +- To run a single test project in CI, add one step for each test executable that you wish to run, such as the following on Azure DevOps: -To run a test project in CI add one step for each test executable that you wish to run, such as this on Azure DevOps: + ```yml + - task: CmdLine@2 + displayName: "Run Contoso.MyTests" + inputs: + script: '.\Contoso.MyTests\bin\Debug\net8.0\Contoso.MyTests.exe' + ``` -```yml -- task: CmdLine@2 - displayName: "Run Contoso.MyTests" - inputs: - script: '.\Contoso.MyTests\bin\Debug\net8.0\Contoso.MyTests.exe' -``` +- Run the `dotnet test` command manually, similar to the typical local workflow: + + ```yml + - task: CmdLine@2 + displayName: "Run tests" + inputs: + script: 'dotnet test' # add command-line options as needed + ``` + +- Run using the `DotNetCoreCLI` Azure task with test command (requires that you have [`global.json`](../tools/global-json.md) file in repository root that specifies Microsoft.Testing.Platform as the test runner): + + ```yml + - task: DotNetCoreCLI@2 + displayName: "Run tests" + inputs: + command: test + ``` + + > [!NOTE] + > Support for Microsoft.Testing.Platform in `DotNetCoreCLI` was added in [2.263.0](https://github.com/microsoft/azure-pipelines-tasks/pull/21315) version of the task. --- diff --git a/docs/core/testing/microsoft-testing-platform-migration-from-v1-to-v2.md b/docs/core/testing/microsoft-testing-platform-migration-from-v1-to-v2.md index 00afabb9530e0..9674a57eb168b 100644 --- a/docs/core/testing/microsoft-testing-platform-migration-from-v1-to-v2.md +++ b/docs/core/testing/microsoft-testing-platform-migration-from-v1-to-v2.md @@ -40,7 +40,7 @@ This breaking change doesn't affect typical users of test frameworks. It only af ## Behavior breaking changes -These are breaking changes that might affect the behavior at run time. +These are breaking changes that might affect the behavior at runtime. ### Compatibility with VSTest-based `dotnet test` diff --git a/docs/core/testing/mstest-analyzers/overview.md b/docs/core/testing/mstest-analyzers/overview.md index 04df8a6d0c1b9..d83852448ef84 100644 --- a/docs/core/testing/mstest-analyzers/overview.md +++ b/docs/core/testing/mstest-analyzers/overview.md @@ -45,7 +45,7 @@ This setting follows the default documented behavior for each rule. - Rules that are disabled by default will use `none` severity. > [!NOTE] -> Rules that are enabled by default as warnings are violations that are expected to cause issues at run time. +> Rules that are enabled by default as warnings are violations that are expected to cause issues at runtime. ### `Recommended` diff --git a/docs/core/testing/unit-testing-mstest-configure.md b/docs/core/testing/unit-testing-mstest-configure.md index 25e9de1300d5c..c0e8c220bb88a 100644 --- a/docs/core/testing/unit-testing-mstest-configure.md +++ b/docs/core/testing/unit-testing-mstest-configure.md @@ -54,7 +54,7 @@ The following runsettings entries let you configure how MSTest behaves. ``` -Test run parameters provide a way to define variables and values that are available to the tests at run time. Access the parameters using the MSTest property: +Test run parameters provide a way to define variables and values that are available to the tests at runtime. Access the parameters using the MSTest property: ```csharp private string _appUrl; @@ -79,7 +79,7 @@ Each element of the file is optional because it has a default value. - + diff --git a/docs/core/testing/unit-testing-mstest-migration-v3-v4.md b/docs/core/testing/unit-testing-mstest-migration-v3-v4.md index bfbf4f93558c4..f542536a8d036 100644 --- a/docs/core/testing/unit-testing-mstest-migration-v3-v4.md +++ b/docs/core/testing/unit-testing-mstest-migration-v3-v4.md @@ -191,7 +191,7 @@ The default severity of the following analyzers changed from Info to Warning: ## Behavior breaking changes -These are breaking changes that might affect the behavior at run time. +These are breaking changes that might affect the behavior at runtime. ### DisableAppDomain now defaults to true when running under Microsoft.Testing.Platform diff --git a/docs/core/tools/dotnet-build.md b/docs/core/tools/dotnet-build.md index 08923b0ffe05c..25c37a8e6ad31 100644 --- a/docs/core/tools/dotnet-build.md +++ b/docs/core/tools/dotnet-build.md @@ -15,7 +15,7 @@ ms.date: 09/24/2025 ```dotnetcli dotnet build [||] [-a|--arch ] - [--artifacts-path ] + [--artifacts-path ] [-bl|--binaryLogger:] [-c|--configuration ] [--disable-build-servers] [-f|--framework ] [--force] [--interactive] [--no-dependencies] [--no-incremental] [--no-restore] [--nologo] @@ -81,6 +81,19 @@ Running `dotnet build` is equivalent to running `dotnet msbuild -restore`; howev - [!INCLUDE [artifacts-path](../../../includes/cli-artifacts-path.md)] +- **`-bl|--binaryLogger:`** + + Enables the binary logger and optionally specifies the output file name. + If no file name is provided, the default is `msbuild.binlog` in the current directory. + + The binary log contains detailed build information and can be opened with the + [MSBuild Structured Log Viewer](https://msbuildlog.com). + + ```dotnetcli + dotnet build -bl + dotnet build -bl:build-log.binlog + ``` + - [!INCLUDE [configuration](../../../includes/cli-configuration.md)] - [!INCLUDE [disable-build-servers](../../../includes/cli-disable-build-servers.md)] diff --git a/docs/core/tools/dotnet-nuget-sign.md b/docs/core/tools/dotnet-nuget-sign.md index e80dea25c124f..0c21dd7c39cbc 100644 --- a/docs/core/tools/dotnet-nuget-sign.md +++ b/docs/core/tools/dotnet-nuget-sign.md @@ -82,7 +82,7 @@ The `dotnet nuget sign` command signs all the packages matching the first argume Specifies the certificate password, if needed. If a certificate is password protected but no password is provided, the sign command will fail. > [!NOTE] - > The `sign` command only supports non-interactive mode. There won't be any prompt for a password at run time. + > The `sign` command only supports non-interactive mode. There won't be any prompt for a password at runtime. - **`--hash-algorithm `** diff --git a/docs/core/tools/dotnet.md b/docs/core/tools/dotnet.md index 5010b250b3470..a29e0ee8c2437 100644 --- a/docs/core/tools/dotnet.md +++ b/docs/core/tools/dotnet.md @@ -157,7 +157,7 @@ The following options are available only when `dotnet` runs an application by us - **`--runtimeconfig `** - Path to a *runtimeconfig.json* file. A *runtimeconfig.json* file contains run-time settings and is typically named *\.runtimeconfig.json*. For more information, see [.NET runtime configuration settings](../runtime-config/index.md#runtimeconfigjson). + Path to a *runtimeconfig.json* file. A *runtimeconfig.json* file contains runtime settings and is typically named *\.runtimeconfig.json*. For more information, see [.NET runtime configuration settings](../runtime-config/index.md#runtimeconfigjson). ## dotnet commands diff --git a/docs/core/unmanaged-api/debugging/icordebug/icordebugclass2-getparameterizedtype-method.md b/docs/core/unmanaged-api/debugging/icordebug/icordebugclass2-getparameterizedtype-method.md index fd47f9d9300c0..7a4bb7313f271 100644 --- a/docs/core/unmanaged-api/debugging/icordebug/icordebugclass2-getparameterizedtype-method.md +++ b/docs/core/unmanaged-api/debugging/icordebug/icordebugclass2-getparameterizedtype-method.md @@ -55,7 +55,7 @@ If the class accepts type parameters (for example, `ArrayList`), you can use .NET Framework version 2.0 introduced the `ICorDebugType` interface. For a generic type, an `ICorDebugClass` or `ICorDebugClass2` object represents the uninstantiated type (`SortedList`), and an `ICorDebugType` object represents the various instantiated types. Given an `ICorDebugClass` or `ICorDebugClass2` object, you can create an `ICorDebugType` object for any instantiation by calling the `ICorDebugClass2::GetParameterizedType` method. You can also create an `ICorDebugType` object for a simple type, such as Int32, or for a non-generic type. -The introduction of the `ICorDebugType` object to represent the run-time notion of a type has a ripple effect throughout the API. Functions that previously took an `ICorDebugClass` or `ICorDebugClass2` object or even a `CorElementType` value are generalized to take an `ICorDebugType` object. +The introduction of the `ICorDebugType` object to represent the runtime notion of a type has a ripple effect throughout the API. Functions that previously took an `ICorDebugClass` or `ICorDebugClass2` object or even a `CorElementType` value are generalized to take an `ICorDebugType` object. ## Requirements diff --git a/docs/core/unmanaged-api/debugging/icordebug/icordebugvalue-gettype-method.md b/docs/core/unmanaged-api/debugging/icordebug/icordebugvalue-gettype-method.md index af225d57d7e5f..470dd0a3aa5e3 100644 --- a/docs/core/unmanaged-api/debugging/icordebug/icordebugvalue-gettype-method.md +++ b/docs/core/unmanaged-api/debugging/icordebug/icordebugvalue-gettype-method.md @@ -35,7 +35,7 @@ HRESULT GetType ( ## Remarks -If the object is a complex run-time type, that type may be examined through the appropriate subclasses of the `ICorDebugValue` interface. For example, "ICorDebugObjectValue", which inherits from `ICorDebugValue`, represents a complex type. +If the object is a complex runtime type, that type may be examined through the appropriate subclasses of the `ICorDebugValue` interface. For example, "ICorDebugObjectValue", which inherits from `ICorDebugValue`, represents a complex type. The `GetType` and [ICorDebugObjectValue::GetClass](icordebugobjectvalue-getclass-method.md) methods each return information about the type of a value. They are both superseded by the generics-aware [ICorDebugValue2::GetExactType](icordebugvalue2-getexacttype-method.md) method. diff --git a/docs/core/unmanaged-api/metadata/enumerations/corassemblyflags-enumeration.md b/docs/core/unmanaged-api/metadata/enumerations/corassemblyflags-enumeration.md index 2b315d1710985..b5d03d29c8c13 100644 --- a/docs/core/unmanaged-api/metadata/enumerations/corassemblyflags-enumeration.md +++ b/docs/core/unmanaged-api/metadata/enumerations/corassemblyflags-enumeration.md @@ -66,7 +66,7 @@ typedef enum CorAssemblyFlags { | `afPA_Shift` | Indicates a shift count in the processor architecture flags to and from the index. | | `afEnableJITcompileTracking` |Indicates the corresponding value from the of the .| | `afDisableJITcompileOptimizer` |Indicates the corresponding value from the of the .| -| `afRetargetable` | Indicates that the assembly can be retargeted at run time to an assembly from a different publisher. | +| `afRetargetable` | Indicates that the assembly can be retargeted at runtime to an assembly from a different publisher. | | `afContentType_Mask` | A mask that describes the content type. | | `afContentType_Default` | Indicates the default content type. | | `afContentType_WindowsRuntime` | Indicates the Windows Runtime content type. | diff --git a/docs/core/unmanaged-api/metadata/interfaces/imetadataassemblyemit-defineassemblyref-method.md b/docs/core/unmanaged-api/metadata/interfaces/imetadataassemblyemit-defineassemblyref-method.md index d79d1eb3aaff5..eafcf795acc83 100644 --- a/docs/core/unmanaged-api/metadata/interfaces/imetadataassemblyemit-defineassemblyref-method.md +++ b/docs/core/unmanaged-api/metadata/interfaces/imetadataassemblyemit-defineassemblyref-method.md @@ -63,7 +63,7 @@ HRESULT DefineAssemblyRef ( One `AssemblyRef` metadata structure must be defined for each assembly that this assembly references. - At run time, the details of a referenced assembly are passed to the assembly resolver with an indication that they represent the "as built" information. The assembly resolver then applies policy. + At runtime, the details of a referenced assembly are passed to the assembly resolver with an indication that they represent the "as built" information. The assembly resolver then applies policy. ## Requirements diff --git a/docs/core/unmanaged-api/metadata/interfaces/imetadataimport-findfield-method.md b/docs/core/unmanaged-api/metadata/interfaces/imetadataimport-findfield-method.md index 7db7cc6213d7c..a4bd1b701fcdf 100644 --- a/docs/core/unmanaged-api/metadata/interfaces/imetadataimport-findfield-method.md +++ b/docs/core/unmanaged-api/metadata/interfaces/imetadataimport-findfield-method.md @@ -51,7 +51,7 @@ HRESULT FindField ( You specify the field using its enclosing class or interface (`td`), its name (`szName`), and optionally its signature (`pvSigBlob`). - The signature passed to `FindField` must have been generated in the current scope, because signatures are bound to a particular scope. A signature can embed a token that identifies the enclosing class or value type. (The token is an index into the local TypeDef table). You cannot build a run-time signature outside the context of the current scope and use that signature as input to `FindField`. + The signature passed to `FindField` must have been generated in the current scope, because signatures are bound to a particular scope. A signature can embed a token that identifies the enclosing class or value type. (The token is an index into the local TypeDef table). You cannot build a runtime signature outside the context of the current scope and use that signature as input to `FindField`. `FindField` finds only fields that were defined directly in the class or interface; it does not find inherited fields. diff --git a/docs/core/unmanaged-api/metadata/interfaces/imetadataimport-findmember-method.md b/docs/core/unmanaged-api/metadata/interfaces/imetadataimport-findmember-method.md index 948e8f5ce7e9f..c12796e0364b6 100644 --- a/docs/core/unmanaged-api/metadata/interfaces/imetadataimport-findmember-method.md +++ b/docs/core/unmanaged-api/metadata/interfaces/imetadataimport-findmember-method.md @@ -51,7 +51,7 @@ HRESULT FindMember ( You specify the member using its enclosing class or interface (`td`), its name (`szName`), and optionally its signature (`pvSigBlob`). There might be multiple members with the same name in a class or interface. In that case, pass the member's signature to find the unique match. - The signature passed to `FindMember` must have been generated in the current scope, because signatures are bound to a particular scope. A signature can embed a token that identifies the enclosing class or value type. The token is an index into the local TypeDef table. You cannot build a run-time signature outside the context of the current scope and use that signature as input to input to `FindMember`. + The signature passed to `FindMember` must have been generated in the current scope, because signatures are bound to a particular scope. A signature can embed a token that identifies the enclosing class or value type. The token is an index into the local TypeDef table. You cannot build a runtime signature outside the context of the current scope and use that signature as input to input to `FindMember`. `FindMember` finds only members that were defined directly in the class or interface; it does not find inherited members. diff --git a/docs/core/unmanaged-api/metadata/interfaces/imetadataimport-findmemberref-method.md b/docs/core/unmanaged-api/metadata/interfaces/imetadataimport-findmemberref-method.md index adceba0e2f821..64251b3ae49c5 100644 --- a/docs/core/unmanaged-api/metadata/interfaces/imetadataimport-findmemberref-method.md +++ b/docs/core/unmanaged-api/metadata/interfaces/imetadataimport-findmemberref-method.md @@ -51,7 +51,7 @@ HRESULT FindMemberRef ( You specify the member using its enclosing class or interface (`td`), its name (`szName`), and optionally its signature (`pvSigBlob`). - The signature passed to `FindMemberRef` must have been generated in the current scope, because signatures are bound to a particular scope. A signature can embed a token that identifies the enclosing class or value type. The token is an index into the local TypeDef table. You cannot build a run-time signature outside the context of the current scope and use that signature as input to `FindMemberRef`. + The signature passed to `FindMemberRef` must have been generated in the current scope, because signatures are bound to a particular scope. A signature can embed a token that identifies the enclosing class or value type. The token is an index into the local TypeDef table. You cannot build a runtime signature outside the context of the current scope and use that signature as input to `FindMemberRef`. `FindMemberRef` finds only member references that were defined directly in the class or interface; it does not find inherited member references. diff --git a/docs/core/unmanaged-api/metadata/interfaces/imetadataimport-findmethod-method.md b/docs/core/unmanaged-api/metadata/interfaces/imetadataimport-findmethod-method.md index 3bf264743bb07..5f0cfcb69b4e0 100644 --- a/docs/core/unmanaged-api/metadata/interfaces/imetadataimport-findmethod-method.md +++ b/docs/core/unmanaged-api/metadata/interfaces/imetadataimport-findmethod-method.md @@ -51,7 +51,7 @@ HRESULT FindMethod ( You specify the method using its enclosing class or interface (`td`), its name (`szName`), and optionally its signature (`pvSigBlob`). There might be multiple methods with the same name in a class or interface. In that case, pass the method's signature to find the unique match. - The signature passed to `FindMethod` must have been generated in the current scope, because signatures are bound to a particular scope. A signature can embed a token that identifies the enclosing class or value type. The token is an index into the local TypeDef table. You cannot build a run-time signature outside the context of the current scope and use that signature as input to input to `FindMethod`. + The signature passed to `FindMethod` must have been generated in the current scope, because signatures are bound to a particular scope. A signature can embed a token that identifies the enclosing class or value type. The token is an index into the local TypeDef table. You cannot build a runtime signature outside the context of the current scope and use that signature as input to input to `FindMethod`. `FindMethod` finds only methods that were defined directly in the class or interface; it does not find inherited methods. diff --git a/docs/core/unmanaged-api/metadata/interfaces/imetadataimport-interface.md b/docs/core/unmanaged-api/metadata/interfaces/imetadataimport-interface.md index ad95b7d6c047c..134082c5e937b 100644 --- a/docs/core/unmanaged-api/metadata/interfaces/imetadataimport-interface.md +++ b/docs/core/unmanaged-api/metadata/interfaces/imetadataimport-interface.md @@ -15,7 +15,7 @@ topic_type: --- # IMetaDataImport Interface -Provides methods for importing and manipulating existing metadata from a portable executable (PE) file or other source, such as a type library or a stand-alone, run-time metadata binary. +Provides methods for importing and manipulating existing metadata from a portable executable (PE) file or other source, such as a type library or a stand-alone, runtime metadata binary. ## Methods diff --git a/docs/core/versions/selection.md b/docs/core/versions/selection.md index 23fad0a395ed4..d71bd791ce758 100644 --- a/docs/core/versions/selection.md +++ b/docs/core/versions/selection.md @@ -174,7 +174,7 @@ Then the resolved version is as follows in each case: ## Self-contained deployments include the selected runtime -You can publish an application as a [**self-contained distribution**](../deploying/index.md#self-contained-deployment). This approach bundles the .NET runtime and libraries with your application. Self-contained deployments don't have a dependency on runtime environments. Runtime version selection occurs at publishing time, not run time. +You can publish an application as a [**self-contained distribution**](../deploying/index.md#self-contained-deployment). This approach bundles the .NET runtime and libraries with your application. Self-contained deployments don't have a dependency on runtime environments. Runtime version selection occurs at publishing time, not runtime. The *restore* event that occurs when publishing selects the latest patch version of the given runtime family. For example, `dotnet publish` selects .NET 5.0.3 if it's the latest patch version in the .NET 5 runtime family. The target framework (including the latest installed security patches) is packaged with the application. diff --git a/docs/core/whats-new/dotnet-10/runtime.md b/docs/core/whats-new/dotnet-10/runtime.md index 476276c5f3619..cb3046c90ecd6 100644 --- a/docs/core/whats-new/dotnet-10/runtime.md +++ b/docs/core/whats-new/dotnet-10/runtime.md @@ -264,7 +264,7 @@ For more information about de-abstraction improvements in .NET 10, see [dotnet/r #### Delegates -When source code is compiled to IL, each delegate is transformed into a closure class with a method corresponding to the delegate's definition and fields matching any captured variables. At run time, a closure object is created to instantiate the captured variables, along with a `Func` object to invoke the delegate. If escape analysis determines the `Func` object won't outlive its current scope, the JIT allocates it on the stack. +When source code is compiled to IL, each delegate is transformed into a closure class with a method corresponding to the delegate's definition and fields matching any captured variables. At runtime, a closure object is created to instantiate the captured variables, along with a `Func` object to invoke the delegate. If escape analysis determines the `Func` object won't outlive its current scope, the JIT allocates it on the stack. Consider the following `Main` method: diff --git a/docs/core/whats-new/dotnet-10/sdk.md b/docs/core/whats-new/dotnet-10/sdk.md index 4dab76b974366..b5f30d989549a 100644 --- a/docs/core/whats-new/dotnet-10/sdk.md +++ b/docs/core/whats-new/dotnet-10/sdk.md @@ -15,7 +15,7 @@ This article describes new features and enhancements in the .NET SDK for .NET 10 ### Platform-specific .NET tools -.NET tools can now be published with support for multiple RuntimeIdentifiers (RIDs) in a single package. Tool authors can bundle binaries for all supported platforms, and the .NET CLI will select the correct one at install or run time. This makes cross-platform tool authoring and distribution much easier. +.NET tools can now be published with support for multiple RuntimeIdentifiers (RIDs) in a single package. Tool authors can bundle binaries for all supported platforms, and the .NET CLI will select the correct one at install or runtime. This makes cross-platform tool authoring and distribution much easier. These enhanced tools support various packaging variations: diff --git a/docs/core/whats-new/dotnet-6.md b/docs/core/whats-new/dotnet-6.md index e734f27d07700..cf4a69b21689a 100644 --- a/docs/core/whats-new/dotnet-6.md +++ b/docs/core/whats-new/dotnet-6.md @@ -178,7 +178,7 @@ W^X is available all operating systems with .NET 6 but only enabled by default o ## IL trimming -Trimming of self-contained deployments is improved. In .NET 5, only unused assemblies were trimmed. .NET 6 adds trimming of unused types and members too. In addition, trim warnings, which alert you to places where trimming may remove code that's used at run time, are now *enabled* by default. For more information, see [Trim self-contained deployments and executables](../deploying/trimming/trim-self-contained.md). +Trimming of self-contained deployments is improved. In .NET 5, only unused assemblies were trimmed. .NET 6 adds trimming of unused types and members too. In addition, trim warnings, which alert you to places where trimming may remove code that's used at runtime, are now *enabled* by default. For more information, see [Trim self-contained deployments and executables](../deploying/trimming/trim-self-contained.md). ## Code analysis @@ -239,7 +239,7 @@ Several extensions namespaces have improvements in .NET 6, as the following tabl | - | - | | | lets you safely use a `using` statement for a service provider that registers an service. | | | New methods simplify application setup. | -| | has a new source generator for performant logging APIs. The source generator is triggered if you add the new to a `partial` logging method. At compile time, the generator generates the implementation of the `partial` method, which is typically faster at run time than existing logging solutions. For more information, see [Compile-time logging source generation](../extensions/logger-message-generator.md). | +| | has a new source generator for performant logging APIs. The source generator is triggered if you add the new to a `partial` logging method. At compile time, the generator generates the implementation of the `partial` method, which is typically faster at runtime than existing logging solutions. For more information, see [Compile-time logging source generation](../extensions/logger-message-generator.md). | ## New LINQ APIs diff --git a/docs/core/whats-new/dotnet-7.md b/docs/core/whats-new/dotnet-7.md index 0ac6f37b2ab58..f342e5ee45370 100644 --- a/docs/core/whats-new/dotnet-7.md +++ b/docs/core/whats-new/dotnet-7.md @@ -117,7 +117,7 @@ For more information, see [Central package management](/nuget/consume-packages/C ## P/Invoke source generation -.NET 7 introduces a source generator for platform invokes (P/Invokes) in C#. The source generator looks for on `static`, `partial` methods to trigger compile-time source generation of marshalling code. By generating the marshalling code at compile time, no IL stub needs to be generated at run time, as it does when using . The source generator improves application performance and also allows the app to be ahead-of-time (AOT) compiled. For more information, see [Source generation for platform invokes](../../standard/native-interop/pinvoke-source-generation.md) and [Use custom marshallers in source-generated P/Invokes](../../standard/native-interop/tutorial-custom-marshaller.md). +.NET 7 introduces a source generator for platform invokes (P/Invokes) in C#. The source generator looks for on `static`, `partial` methods to trigger compile-time source generation of marshalling code. By generating the marshalling code at compile time, no IL stub needs to be generated at runtime, as it does when using . The source generator improves application performance and also allows the app to be ahead-of-time (AOT) compiled. For more information, see [Source generation for platform invokes](../../standard/native-interop/pinvoke-source-generation.md) and [Use custom marshallers in source-generated P/Invokes](../../standard/native-interop/tutorial-custom-marshaller.md). ## Related releases diff --git a/docs/core/whats-new/dotnet-8/runtime.md b/docs/core/whats-new/dotnet-8/runtime.md index 913d3a18421ea..fe2f861165da6 100644 --- a/docs/core/whats-new/dotnet-8/runtime.md +++ b/docs/core/whats-new/dotnet-8/runtime.md @@ -219,7 +219,7 @@ The serializer has built-in support for the following additional types. - Additional diagnostics (such as [SYSLIB1034](../../../fundamentals/syslib-diagnostics/syslib1034.md) and [SYSLIB1039](../../../fundamentals/syslib-diagnostics/syslib1039.md)). - Don't include types of ignored or inaccessible properties. - Support for nesting `JsonSerializerContext` declarations within arbitrary type kinds. -- Support for compiler-generated or *unspeakable* types in weakly typed source generation scenarios. Since compiler-generated types can't be explicitly specified by the source generator, now performs nearest-ancestor resolution at run time. This resolution determines the most appropriate supertype with which to serialize the value. +- Support for compiler-generated or *unspeakable* types in weakly typed source generation scenarios. Since compiler-generated types can't be explicitly specified by the source generator, now performs nearest-ancestor resolution at runtime. This resolution determines the most appropriate supertype with which to serialize the value. - New converter type `JsonStringEnumConverter`. The existing class isn't supported in Native AOT. You can annotate your enum types as follows: ```csharp diff --git a/docs/core/whats-new/dotnet-9/runtime.md b/docs/core/whats-new/dotnet-9/runtime.md index ec97890352975..849564748de3d 100644 --- a/docs/core/whats-new/dotnet-9/runtime.md +++ b/docs/core/whats-new/dotnet-9/runtime.md @@ -203,7 +203,7 @@ The code size reduction is small, but if the loop runs for a nontrivial number o One of .NET's goals for the JIT compiler's inliner is to remove as many restrictions that block a method from being inlined as possible. .NET 9 enables inlining of: -- Shared generics that require run-time lookups. +- Shared generics that require runtime lookups. As an example, consider the following methods: @@ -212,9 +212,9 @@ One of .NET's goals for the JIT compiler's inliner is to remove as many restrict static bool Callee() => typeof(T) == typeof(int); ``` - When `T` is a reference type like `string`, the runtime creates *shared generics*, which are special instantiations of `Test` and `Callee` that are shared by all ref-type `T` types. To make this work, the runtime builds dictionaries that map generic types to internal types. These dictionaries are specialized per generic type (or per generic method), and are accessed at run time to obtain information about `T` and types that depend on `T`. Historically, code compiled just-in-time was only capable of performing these run-time lookups against the root method's dictionary. This meant the JIT compiler couldn't inline `Callee` into `Test`—there was no way for the inlined code from `Callee` to access the proper dictionary, even though both methods were instantiated over the same type. + When `T` is a reference type like `string`, the runtime creates *shared generics*, which are special instantiations of `Test` and `Callee` that are shared by all ref-type `T` types. To make this work, the runtime builds dictionaries that map generic types to internal types. These dictionaries are specialized per generic type (or per generic method), and are accessed at runtime to obtain information about `T` and types that depend on `T`. Historically, code compiled just-in-time was only capable of performing these runtime lookups against the root method's dictionary. This meant the JIT compiler couldn't inline `Callee` into `Test`—there was no way for the inlined code from `Callee` to access the proper dictionary, even though both methods were instantiated over the same type. - .NET 9 has lifted this restriction by freely enabling run-time type lookups in callees, meaning the JIT compiler can now inline methods like `Callee` into `Test`. + .NET 9 has lifted this restriction by freely enabling runtime type lookups in callees, meaning the JIT compiler can now inline methods like `Callee` into `Test`. Suppose we call `Test` in another method. In pseudocode, the inlining looks like this: @@ -238,7 +238,7 @@ One of .NET's goals for the JIT compiler's inliner is to remove as many restrict ### PGO improvements: Type checks and casts -.NET 8 enabled [dynamic profile-guided optimization (PGO)](../../runtime-config/compilation.md#profile-guided-optimization) by default. NET 9 expands the JIT compiler's PGO implementation to profile more code patterns. When tiered compilation is enabled, the JIT compiler already inserts instrumentation into your program to profile its behavior. When it recompiles with optimizations, the compiler leverages the profile it built at run time to make decisions specific to the current run of your program. In .NET 9, the JIT compiler uses PGO data to improve the performance of *type checks*. +.NET 8 enabled [dynamic profile-guided optimization (PGO)](../../runtime-config/compilation.md#profile-guided-optimization) by default. NET 9 expands the JIT compiler's PGO implementation to profile more code patterns. When tiered compilation is enabled, the JIT compiler already inserts instrumentation into your program to profile its behavior. When it recompiles with optimizations, the compiler leverages the profile it built at runtime to make decisions specific to the current run of your program. In .NET 9, the JIT compiler uses PGO data to improve the performance of *type checks*. Determining the type of an object requires a call into the runtime, which comes with a performance penalty. When the type of an object needs to be checked, the JIT compiler emits this call for the sake of correctness (compilers usually cannot rule out any possibilities, even if they seem improbable). However, if PGO data suggests an object is likely to be a specific type, the JIT compiler now emits a *fast path* that cheaply checks for that type, and falls back on the slow path of calling into the runtime only if necessary. @@ -307,7 +307,7 @@ The use of `size` in the call to `Sse2.ShiftRightLogical128BitLane` can be subst ### Constant folding for floating point and SIMD operations -*Constant folding* is an existing optimization in the JIT compiler. *Constant folding* refers to the replacement of expressions that can be computed at compile time with the constants they evaluate to, thus eliminating computations at run time. .NET 9 adds new constant-folding capabilities: +*Constant folding* is an existing optimization in the JIT compiler. *Constant folding* refers to the replacement of expressions that can be computed at compile time with the constants they evaluate to, thus eliminating computations at runtime. .NET 9 adds new constant-folding capabilities: - For floating-point binary operations, where one of the operands is a constant: - `x + NaN` is now folded into `NaN`. diff --git a/docs/core/whats-new/dotnet-core-2-1.md b/docs/core/whats-new/dotnet-core-2-1.md index 9e667b2f73f7d..d9d4123a1c8f9 100644 --- a/docs/core/whats-new/dotnet-core-2-1.md +++ b/docs/core/whats-new/dotnet-core-2-1.md @@ -86,7 +86,7 @@ In .NET Core 2.1 SDK, all tools operations use the `dotnet tool` command. The fo All .NET Core applications starting with .NET Core 2.0 automatically roll forward to the latest *minor version* installed on a system. -Starting with .NET Core 2.0, if the version of .NET Core that an application was built with is not present at run time, the application automatically runs against the latest installed *minor version* of .NET Core. In other words, if an application is built with .NET Core 2.0, and .NET Core 2.0 is not present on the host system but .NET Core 2.1 is, the application runs with .NET Core 2.1. +Starting with .NET Core 2.0, if the version of .NET Core that an application was built with is not present at runtime, the application automatically runs against the latest installed *minor version* of .NET Core. In other words, if an application is built with .NET Core 2.0, and .NET Core 2.0 is not present on the host system but .NET Core 2.1 is, the application runs with .NET Core 2.1. > [!IMPORTANT] > This roll-forward behavior doesn't apply to preview releases. By default, it also doesn't apply to major releases, but this can be changed with the settings below. diff --git a/docs/core/whats-new/dotnet-core-3-0.md b/docs/core/whats-new/dotnet-core-3-0.md index f53245ee3f9cc..c5504f6b88dd3 100644 --- a/docs/core/whats-new/dotnet-core-3-0.md +++ b/docs/core/whats-new/dotnet-core-3-0.md @@ -175,7 +175,7 @@ To disable TC completely, use this MSBuild property in your project file: > [!TIP] > If you change these settings in the project file, you may need to perform a clean build for the new settings to be reflected (delete the `obj` and `bin` directories and rebuild). -For more information about configuring compilation at run time, see [Runtime configuration options for compilation](../runtime-config/compilation.md). +For more information about configuring compilation at runtime, see [Runtime configuration options for compilation](../runtime-config/compilation.md). ### ReadyToRun images diff --git a/docs/csharp/fundamentals/tutorials/file-based-programs.md b/docs/csharp/fundamentals/tutorials/file-based-programs.md index 0c4fcddb9bc1a..c6ca05192fe02 100644 --- a/docs/csharp/fundamentals/tutorials/file-based-programs.md +++ b/docs/csharp/fundamentals/tutorials/file-based-programs.md @@ -4,13 +4,12 @@ description: File-based apps are command line utilities that are built and execu ms.date: 08/14/2025 ms.topic: tutorial ai-usage: ai-assisted -#customer intent: As a developer, I want build utilities so that more work is automated. +#customer intent: As a developer, I want to build utilities so that more work is automated. --- # Tutorial: Build file-based C# programs -*File-based apps* are programs contained within a single `*.cs` file that are built and run without a corresponding project (`*.csproj`) file. File-based apps are ideal for learning C# because they have less complexity: The entire program is stored in a single file. File-based apps are also useful for building command line utilities. On Unix platforms, file-based apps can be run using `#!` (shebang) directives. - +*File-based apps* are programs contained within a single `*.cs` file that are built and run without a corresponding project (`*.csproj`) file. File-based apps are ideal for learning C# because they have less complexity: The entire program is stored in a single file. File-based apps are also useful for building command line utilities. On Unix platforms, file-based apps can be run using `#!` (shebang) [directives](../../language-reference/preprocessor-directives.md). In this tutorial, you: > [!div class="checklist"] diff --git a/docs/csharp/fundamentals/tutorials/snippets/xml-documentation/BankAccount.cs b/docs/csharp/fundamentals/tutorials/snippets/xml-documentation/BankAccount.cs index c41fa0e1ff61a..111fd44c36983 100644 --- a/docs/csharp/fundamentals/tutorials/snippets/xml-documentation/BankAccount.cs +++ b/docs/csharp/fundamentals/tutorials/snippets/xml-documentation/BankAccount.cs @@ -163,8 +163,6 @@ public string GetAccountHistory() return report.ToString(); } - // Added for OO tutorial: - /// /// Performs month-end processing for the account. This virtual method can be overridden in derived classes /// to implement specific month-end behaviors such as interest calculations, fee assessments, or statement generation. diff --git a/docs/csharp/fundamentals/tutorials/snippets/xml-documentation/GiftCardAccount.cs b/docs/csharp/fundamentals/tutorials/snippets/xml-documentation/GiftCardAccount.cs index 9ec4f25976d95..c7d4d2e1c469d 100644 --- a/docs/csharp/fundamentals/tutorials/snippets/xml-documentation/GiftCardAccount.cs +++ b/docs/csharp/fundamentals/tutorials/snippets/xml-documentation/GiftCardAccount.cs @@ -1,9 +1,6 @@ namespace OOProgramming; -/// -/// Represents a gift card account that extends with optional recurring monthly deposits. -/// Designed for prepaid gift cards that can optionally receive automatic monthly top-ups. -/// +/// /// /// A gift card account is a specialized prepaid account that can be loaded with an initial balance and optionally /// configured to receive automatic monthly deposits. This account type is ideal for gift cards, allowances, or diff --git a/docs/csharp/fundamentals/tutorials/snippets/xml-documentation/InterestEarningAccount.cs b/docs/csharp/fundamentals/tutorials/snippets/xml-documentation/InterestEarningAccount.cs index 15a9f77c52e29..abeb171e68792 100644 --- a/docs/csharp/fundamentals/tutorials/snippets/xml-documentation/InterestEarningAccount.cs +++ b/docs/csharp/fundamentals/tutorials/snippets/xml-documentation/InterestEarningAccount.cs @@ -1,9 +1,7 @@ namespace OOProgramming; -/// -/// Represents an interest-earning bank account that extends with monthly interest payments. -/// Earns interest on balances above $500 at a rate of 2% annually, applied monthly. -/// +// +/// /// /// An interest-earning account is a specialized savings account that rewards customers for maintaining higher balances. /// Interest is only earned when the account balance exceeds $500, encouraging customers to maintain substantial deposits. @@ -11,6 +9,7 @@ /// This account type uses the standard minimum balance of $0 from the base class. /// public class InterestEarningAccount : BankAccount +// { /// /// Initializes a new instance of the class with the specified owner name and initial balance. diff --git a/docs/csharp/fundamentals/tutorials/snippets/xml-documentation/LineOfCreditAccount.cs b/docs/csharp/fundamentals/tutorials/snippets/xml-documentation/LineOfCreditAccount.cs index 3e6dac527be6e..fc4031a8a3c91 100644 --- a/docs/csharp/fundamentals/tutorials/snippets/xml-documentation/LineOfCreditAccount.cs +++ b/docs/csharp/fundamentals/tutorials/snippets/xml-documentation/LineOfCreditAccount.cs @@ -1,9 +1,6 @@ namespace OOProgramming; -/// -/// Represents a line of credit account that extends with credit limit functionality. -/// Allows negative balances up to a specified credit limit and applies monthly interest charges on outstanding balances. -/// +/// /// /// A line of credit account differs from a regular bank account in that it allows the balance to go negative /// up to a predefined credit limit. When the balance is negative (indicating borrowed money), the account diff --git a/docs/csharp/fundamentals/tutorials/xml-documentation.md b/docs/csharp/fundamentals/tutorials/xml-documentation.md index fed376ec885c0..5c0a77ead845b 100644 --- a/docs/csharp/fundamentals/tutorials/xml-documentation.md +++ b/docs/csharp/fundamentals/tutorials/xml-documentation.md @@ -1,7 +1,7 @@ --- title: Generate XML documentation from your source code description: "Learn to add `///` comments that generate XML documentation directly from your source code. Learn which tags are available and how to add documentation blocks to types and members." -ms.topic: tutorial #Don't change. +ms.topic: tutorial ms.date: 10/14/2025 ai-usage: ai-assisted #customer intent: As a developer, I want to generate XML documentation comments so that other developers can use my code successfully. @@ -50,7 +50,9 @@ Build the project now. You see warnings for any public members that are missing ``` -With the file in place, start adding targeted XML comments and immediately verify how each one appears in the generated output. +With the file in place, start adding targeted XML comments and immediately verify how each one appears in the generated output. Start with the `Transaction` record type: + +:::code language="csharp" source="./snippets/xml-documentation/transaction.cs"::: ## Add documentation comments @@ -65,6 +67,10 @@ You now cycle through the build warnings to add concise, useful documentation to 1. For methods that return a value, add `` with a short description of what callers receive. Avoid repeating the method name or managed type. 1. Work with the `BankAccount` base class first. +Your version should look something like the following code: + +:::code language="csharp" source="./snippets/xml-documentation/BankAccount.cs"::: + When you're done, open the regenerated XML file and confirm that each member appears with your new elements. A trimmed portion might look like this: ```xml @@ -83,19 +89,17 @@ When you're done, open the regenerated XML file and confirm that each member app ## Use `` in derived classes -If you derive from `BankAccount` (for example, a `SavingsAccount` that applies interest), you can inherit base documentation instead of copying it. Add a self-closing `` element inside the derived member's documentation block. You can still append more elements (such as extra `` details) after `` to document the specialized behavior. +If you derive from `BankAccount` (for example, a `SavingsAccount` that applies interest), you can inherit base documentation instead of copying it. Add a self-closing `` element inside the derived member's documentation block. You can still append more elements (such as extra `` details) after `` to document the specialized behavior: -```csharp -/// -/// Adds monthly interest during month-end processing. -public class SavingsAccount : BankAccount { /* ... */ } -``` +:::code language="csharp" source="./snippets/xml-documentation/InterestEarningAccount.cs" id="InterestEarningAccountComments"::: > [!NOTE] > `` reduces duplication and helps maintain consistency when you update base type documentation later. After you finish documenting the public surface, build one final time to confirm there are no remaining CS1591 warnings. Your project now produces useful IntelliSense and a structured XML file ready for publishing workflows. +You can see the full annotated sample in [the source folder](https://github.com/dotnet/docs/tree/main/docs/csharp/fundamentals/tutorials/snippets/xml-documentation) of the [dotnet/docs](https://github.com/dotnet/docs) repository on GitHub. + ## Build output from comments You can explore more by trying any of these tools to create output from XML comments: diff --git a/docs/csharp/linq/get-started/features-that-support-linq.md b/docs/csharp/linq/get-started/features-that-support-linq.md index 8761fcc66e4e8..04e6b6827da64 100644 --- a/docs/csharp/linq/get-started/features-that-support-linq.md +++ b/docs/csharp/linq/get-started/features-that-support-linq.md @@ -1,15 +1,16 @@ --- -title: "Language Features That Support LINQ" +title: "Language features that support LINQ" description: Learn about C# features to use with LINQ queries and in other contexts. -ms.date: 04/22/2024 +ms.date: 12/01/2025 +ai-usage: ai-assisted helpviewer_keywords: - "LINQ [C#], features supporting LINQ" --- -# C# Features That Support LINQ +# C# features that support LINQ -## Query Expressions +## Query expressions -Query expressions use a declarative syntax similar to SQL or XQuery to query over collections. At compile time, query syntax is converted to method calls to a LINQ provider's implementation of the standard query methods. Applications control the standard query operators that are in scope by specifying the appropriate namespace with a [`using`](../../language-reference/keywords/using-directive.md) directive. The following query expression takes an array of strings, groups them according to the first character in the string, and orders the groups. +Query expressions use a declarative syntax similar to SQL or XQuery to query over collections. At compile time, the compiler converts query syntax to method calls to a LINQ provider's implementation of the standard query methods. Applications control the standard query operators that are in scope by specifying the appropriate namespace with a [`using`](../../language-reference/keywords/using-directive.md) directive. The following query expression takes an array of strings, groups them according to the first character in the string, and orders the groups. ```csharp var query = from str in stringArray @@ -18,7 +19,7 @@ var query = from str in stringArray select stringGroup; ``` -## Implicitly Typed Variables (var) +## Implicitly typed variables (var) You can use the [var](../../language-reference/statements/declarations.md#implicitly-typed-local-variables) modifier to instruct the compiler to infer and assign the type, as shown here: @@ -30,17 +31,17 @@ var query = from str in stringArray select str; ``` -Variables declared as `var` are strongly typed, just like variables whose type you specify explicitly. The use of `var` makes it possible to create anonymous types, but only for local variables. For more information, see [Implicitly Typed Local Variables](../../programming-guide/classes-and-structs/implicitly-typed-local-variables.md). +Variables declared as `var` are strongly typed, just like variables whose type you specify explicitly. Using `var` makes it possible to create anonymous types, but only for local variables. For more information, see [Implicitly Typed Local Variables](../../programming-guide/classes-and-structs/implicitly-typed-local-variables.md). -## Object and Collection Initializers +## Object and collection initializers -Object and collection initializers make it possible to initialize objects without explicitly calling a constructor for the object. Initializers are typically used in query expressions when they project the source data into a new data type. Assuming a class named `Customer` with public `Name` and `Phone` properties, the object initializer can be used as in the following code: +Object and collection initializers make it possible to initialize objects without explicitly calling a constructor for the object. You typically use initializers in query expressions when they project the source data into a new data type. Assuming a class named `Customer` with public `Name` and `Phone` properties, you can use the object initializer as in the following code: ```csharp var cust = new Customer { Name = "Mike", Phone = "555-1212" }; ``` -Continuing with your `Customer` class, assume that there's a data source called `IncomingOrders`, and that for each order with a large `OrderSize`, you would like to create a new `Customer` based off of that order. A LINQ query can be executed on this data source and use object initialization to fill a collection: +Continuing with your `Customer` class, assume that there's a data source called `IncomingOrders`, and that for each order with a large `OrderSize`, you want to create a new `Customer` based off of that order. You can execute a LINQ query on this data source and use object initialization to fill a collection: ```csharp var newLargeOrderCustomers = from o in IncomingOrders @@ -48,7 +49,7 @@ var newLargeOrderCustomers = from o in IncomingOrders select new Customer { Name = o.Name, Phone = o.Phone }; ``` -The data source might have more properties defined than the `Customer` class such as `OrderSize`, but with object initialization, the data returned from the query is molded into the desired data type; you choose the data that is relevant to your class. As a result, you now have an filled with the new `Customer`s you wanted. The preceding example can also be written in LINQ's method syntax: +The data source might have more properties defined than the `Customer` class such as `OrderSize`, but with object initialization, the data returned from the query is molded into the desired data type; you choose the data that's relevant to your class. As a result, you now have an filled with the new `Customer`s you wanted. You can also write the preceding example in LINQ's method syntax: ```csharp var newLargeOrderCustomers = IncomingOrders.Where(x => x.OrderSize > 5).Select(y => new Customer { Name = y.Name, Phone = y.Phone }); @@ -61,9 +62,9 @@ For more information, see: - [Object and Collection Initializers](../../programming-guide/classes-and-structs/object-and-collection-initializers.md) - [Query Expression Syntax for Standard Query Operators](../standard-query-operators/index.md) -## Anonymous Types +## Anonymous types -The compiler constructs an [anonymous type](../../fundamentals/types/anonymous-types.md). The type name is only available to the compiler. Anonymous types provide a convenient way to group a set of properties temporarily in a query result without having to define a separate named type. Anonymous types are initialized with a new expression and an object initializer, as shown here: +The compiler constructs an [anonymous type](../../fundamentals/types/anonymous-types.md). Only the compiler can access the type name. Anonymous types provide a convenient way to group a set of properties temporarily in a query result without having to define a separate named type. You initialize anonymous types with a new expression and an object initializer, as shown here: ```csharp select new {name = cust.Name, phone = cust.Phone}; @@ -71,35 +72,36 @@ select new {name = cust.Name, phone = cust.Phone}; Beginning with C# 7, you can use [tuples](../../language-reference/builtin-types/value-tuples.md) to create unnamed types. -## Extension Methods +## Extension members -An [extension method](../../programming-guide/classes-and-structs/extension-methods.md) is a static method that can be associated with a type, so that it can be called as if it were an instance method on the type. This feature enables you to, in effect, "add" new methods to existing types without actually modifying them. The standard query operators are a set of extension methods that provide LINQ query functionality for any type that implements . +An [extension member](../../programming-guide/classes-and-structs/extension-methods.md) is a static member of a static class associated with a type called the *receiver type*. You can call an extension member as if it were a member of the receiver type. This feature enables you to "add" new members to existing types without actually modifying them. The standard query operators are a set of extension methods that provide LINQ query functionality for any type that implements . -## Lambda Expressions +## Lambda expressions -A [lambda expressions](../../language-reference/operators/lambda-expressions.md) is an inline function that uses the `=>` operator to separate input parameters from the function body and can be converted at compile time to a delegate or an expression tree. In LINQ programming, you encounter lambda expressions when you make direct method calls to the standard query operators. +A [lambda expression](../../language-reference/operators/lambda-expressions.md) is an inline function that uses the `=>` operator to separate input parameters from the function body and can be converted at compile time to a delegate or an expression tree. In LINQ programming, you encounter lambda expressions when you make direct method calls to the standard query operators. ## Expressions as data -Query objects are composable, meaning that you can return a query from a method. Objects that represent queries don't store the resulting collection, but rather the steps to produce the results when needed. The advantage of returning query objects from methods is that they can be further composed or modified. Therefore any return value or `out` parameter of a method that returns a query must also have that type. If a method materializes a query into a concrete or type, it returns the query results instead of the query itself. A query variable that is returned from a method can still be composed or modified. +Query objects are composable, meaning that you can return a query from a method. Objects that represent queries don't store the resulting collection, but rather the steps to produce the results when needed. The advantage of returning query objects from methods is that you can further compose or modify them. Therefore, any return value or `out` parameter of a method that returns a query must also have that type. If a method materializes a query into a concrete or type, it returns the query results instead of the query itself. You can still compose or modify a query variable that's returned from a method. -In the following example, the first method `QueryMethod1` returns a query as a return value, and the second method `QueryMethod2` returns a query as an `out` parameter (`returnQ` in the example). In both cases, it's a query that is returned, not query results. +In the following example, the first method `QueryMethod1` returns a query as a return value, and the second method `QueryMethod2` returns a query as an `out` parameter (`returnQ` in the example). In both cases, it's a query that's returned, not query results. :::code language="csharp" source="./snippets/SnippetApp/ReturnQueryFromMethod.cs" id="return_query_from_method_1"::: -Query `myQuery1` is executed in the following foreach loop. +The following `foreach` loop executes query `myQuery1`. :::code language="csharp" source="./snippets/SnippetApp/ReturnQueryFromMethod.cs" id="return_query_from_method_2"::: Rest the mouse pointer over `myQuery1` to see its type. -You also can execute the query returned from `QueryMethod1` directly, without using `myQuery1`. +You can also execute the query returned from `QueryMethod1` directly, without using `myQuery1`. :::code language="csharp" source="./snippets/SnippetApp/ReturnQueryFromMethod.cs" id="return_query_from_method_3"::: Rest the mouse pointer over the call to `QueryMethod1` to see its return type. `QueryMethod2` returns a query as the value of its `out` parameter: + :::code language="csharp" source="./snippets/SnippetApp/ReturnQueryFromMethod.cs" id="return_query_from_method_4"::: You can modify a query by using query composition. In this case, the previous query object is used to create a new query object. This new object returns different results than the original query object. diff --git a/docs/csharp/linq/get-started/write-linq-queries.md b/docs/csharp/linq/get-started/write-linq-queries.md index 6e64fab2fd58d..04261bf8bbe8a 100644 --- a/docs/csharp/linq/get-started/write-linq-queries.md +++ b/docs/csharp/linq/get-started/write-linq-queries.md @@ -1,13 +1,14 @@ --- title: Write LINQ queries description: Learn how to write LINQ queries in C#. -ms.date: 01/16/2025 +ms.date: 12/01/2025 +ai-usage: ai-assisted --- # Write C# LINQ queries to query data -Most queries in the introductory Language Integrated Query (LINQ) documentation are written by using the LINQ declarative query syntax. The C# compiler translates query syntax into method calls. These method calls implement the standard query operators, and have names such as `Where`, `Select`, `GroupBy`, `Join`, `Max`, and `Average`. You can call them directly by using method syntax instead of query syntax. +Most queries in the introductory Language Integrated Query (LINQ) documentation use the LINQ declarative query syntax. The C# compiler translates query syntax into method calls. These method calls implement the standard query operators. They have names such as `Where`, `Select`, `GroupBy`, `Join`, `Max`, and `Average`. You call them directly by using method syntax instead of query syntax. -Query syntax and method syntax are semantically identical, but query syntax is often simpler and easier to read. Some queries must be expressed as method calls. For example, you must use a method call to express a query that retrieves the number of elements that match a specified condition. You also must use a method call for a query that retrieves the element that has the maximum value in a source sequence. The reference documentation for the standard query operators in the namespace generally uses method syntax. You should become familiar with how to use method syntax in queries and in query expressions themselves. +Query syntax and method syntax are semantically identical, but query syntax is often simpler and easier to read. You must express some queries as method calls. For example, you must use a method call to express a query that retrieves the number of elements that match a specified condition. You also must use a method call for a query that retrieves the element that has the maximum value in a source sequence. The reference documentation for the standard query operators in the namespace generally uses method syntax. Become familiar with how to use method syntax in queries and in query expressions themselves. ## Standard query operator extension methods @@ -21,13 +22,13 @@ On the right side of the expression, notice that the `where` clause is now expre ![Screenshot showing all the standard query operators in Intellisense.](./media/write-linq-queries/standard-query-operators.png) -Although it looks as if includes more methods, it doesn't. The standard query operators are implemented as *extension methods*. Extensions methods "extend" an existing type; they can be called as if they were instance methods on the type. The standard query operators extend and that is why you can write `numbers.Where(...)`. You bring extensions into scope with `using` directives before calling them. +Although it looks as if includes more methods, it doesn't. The standard query operators are implemented as *extension methods*. Extension members "extend" an existing type; they can be called as if they were members on the type. The standard query operators extend , and that's why you can write `numbers.Where(...)`. You bring extensions into scope with `using` directives before calling them. -For more information about extension methods, see [Extension Methods](../../programming-guide/classes-and-structs/extension-methods.md). For more information about standard query operators, see [Standard Query Operators Overview (C#)](../standard-query-operators/index.md). Some LINQ providers, such as [Entity Framework](/ef/core/) and LINQ to XML, implement their own standard query operators and extension methods for other types besides . +For more information about extension members, see [Extension members](../../programming-guide/classes-and-structs/extension-methods.md). For more information about standard query operators, see [Standard Query Operators Overview (C#)](../standard-query-operators/index.md). Some LINQ providers, such as [Entity Framework](/ef/core/) and LINQ to XML, implement their own standard query operators and extension members for other types besides . ## Lambda expressions -In the preceding example, the conditional expression (`num % 2 == 0`) is passed as an in-line argument to the method: `Where(num => num % 2 == 0).` This inline expression is a [lambda expression](../../language-reference/operators/lambda-expressions.md). It's a convenient way to write code that would otherwise have to be written in more cumbersome form. The `num` on the left of the operator is the input variable, which corresponds to `num` in the query expression. The compiler can infer the type of `num` because it knows that `numbers` is a generic type. The body of the lambda is the same as the expression in query syntax or in any other C# expression or statement. It can include method calls and other complex logic. The return value is the expression result. Certain queries can only be expressed in method syntax and some of those queries require lambda expressions. Lambda expressions are a powerful and flexible tool in your LINQ toolbox. +In the preceding example, the conditional expression (`num % 2 == 0`) is passed as an in-line argument to the method: `Where(num => num % 2 == 0).` This inline expression is a [lambda expression](../../language-reference/operators/lambda-expressions.md). It's a convenient way to write code that would otherwise have to be written in more cumbersome form. The `num` on the left of the operator is the input variable, which corresponds to `num` in the query expression. The compiler can infer the type of `num` because it knows that `numbers` is a generic type. The body of the lambda is the same as the expression in query syntax or in any other C# expression or statement. It can include method calls and other complex logic. The return value is the expression result. You can only express certain queries in method syntax, and some of those queries require lambda expressions. Lambda expressions are a powerful and flexible tool in your LINQ toolbox. ## Composability of queries @@ -36,55 +37,55 @@ In the preceding code example, the [!NOTE] -> These queries operate on in-memory collections; however, the syntax is identical to that used in LINQ to Entities and LINQ to XML. +> These queries operate on in-memory collections; however, the syntax is identical to the syntax used in LINQ to Entities and LINQ to XML. -## Example - Query syntax +## Example - query syntax -You write most queries with *query syntax* to create *query expressions*. The following example shows three query expressions. The first query expression demonstrates how to filter or restrict results by applying conditions with a `where` clause. It returns all elements in the source sequence whose values are greater than 7 or less than 3. The second expression demonstrates how to order the returned results. The third expression demonstrates how to group results according to a key. This query returns two groups based on the first letter of the word. +Write most queries with *query syntax* to create *query expressions*. The following example shows three query expressions. The first query expression demonstrates how to filter or restrict results by applying conditions with a `where` clause. It returns all elements in the source sequence whose values are greater than 7 or less than 3. The second expression demonstrates how to order the returned results. The third expression demonstrates how to group results according to a key. This query returns two groups based on the first letter of the word. :::code language="csharp" source="./snippets/SnippetApp/WriteLinqQueries.cs" id="write_linq_queries_1"::: -The type of the queries is . All of these queries could be written using [`var`](../../language-reference/statements/declarations.md#implicitly-typed-local-variables) as shown in the following example: +The type of the queries is . All of these queries can be written using [`var`](../../language-reference/statements/declarations.md#implicitly-typed-local-variables) as shown in the following example: `var query = from num in numbers...` In each previous example, the queries don't actually execute until you iterate over the query variable in a [`foreach`](../../language-reference/statements/iteration-statements.md#the-foreach-statement) statement or other statement. -## Example - Method syntax +## Example - method syntax -Some query operations must be expressed as a method call. The most common such methods are those methods that return singleton numeric values, such as , , , , and so on. These methods must always be called last in any query because they return a single value and can't serve as the source for an additional query operation. The following example shows a method call in a query expression: +You must express some query operations as a method call. The most common such methods are those methods that return singleton numeric values, such as , , , , and so on. Call these methods last in any query because they return a single value and can't serve as the source for more query operations. The following example shows a method call in a query expression: :::code language="csharp" source="./snippets/SnippetApp/WriteLinqQueries.cs" id="write_linq_queries_2"::: -If the method has or parameters, these arguments are provided in the form of a [lambda expression](../../language-reference/operators/lambda-expressions.md), as shown in the following example: +If the method has or parameters, provide these arguments in the form of a [lambda expression](../../language-reference/operators/lambda-expressions.md), as shown in the following example: :::code language="csharp" source="./snippets/SnippetApp/WriteLinqQueries.cs" id="write_linq_queries_3"::: -In the previous queries, only Query #4 executes immediately, because it returns a single value, and not a generic collection. The method itself uses `foreach` or similar code in order to compute its value. +In the previous queries, only Query #4 executes immediately because it returns a single value, and not a generic collection. The method itself uses `foreach` or similar code in order to compute its value. -Each of the previous queries can be written by using implicit typing with [`var`](../../language-reference/statements/declarations.md#implicitly-typed-local-variables), as shown in the following example: +You can write each of the previous queries by using implicit typing with [`var`](../../language-reference/statements/declarations.md#implicitly-typed-local-variables), as shown in the following example: :::code language="csharp" source="./snippets/SnippetApp/WriteLinqQueries.cs" id="write_linq_queries_4"::: -## Example - Mixed query and method syntax +## Example - mixed query and method syntax -This example shows how to use method syntax on the results of a query clause. Just enclose the query expression in parentheses, and then apply the dot operator and call the method. In the following example, query #7 returns a count of the numbers whose value is between 3 and 7. +This example shows how to use method syntax on the results of a query clause. Enclose the query expression in parentheses, and then apply the dot operator and call the method. In the following example, query #7 returns a count of the numbers whose value is between 3 and 7. :::code language="csharp" source="./snippets/SnippetApp/WriteLinqQueries.cs" id="write_linq_queries_5"::: Because Query #7 returns a single value and not a collection, the query executes immediately. -The previous query can be written by using implicit typing with `var`, as follows: +You can write the previous query by using implicit typing with `var`, as follows: ```csharp var numCount = (from num in numbers... ``` -It can be written in method syntax as follows: +You can write it in method syntax as follows: :::code language="csharp" source="./snippets/SnippetApp/WriteLinqQueries.cs" id="write_linq_queries_5a"::: -It can be written by using explicit typing, as follows: +You can write it by using explicit typing, as follows: :::code language="csharp" source="./snippets/SnippetApp/WriteLinqQueries.cs" id="write_linq_queries_5b"::: @@ -135,23 +136,23 @@ In each of the examples, the `equals` query keyword is used. You can also use [p ## Handle exceptions in query expressions -It's possible to call any method in the context of a query expression. Don't call any method in a query expression that can create a side effect such as modifying the contents of the data source or throwing an exception. This example shows how to avoid raising exceptions when you call methods in a query expression without violating the general .NET guidelines on exception handling. Those guidelines state that it's acceptable to catch a specific exception when you understand why it was thrown in a given context. For more information, see [Best Practices for Exceptions](../../../standard/exceptions/best-practices-for-exceptions.md). +You can call any method in the context of a query expression. Don't call any method in a query expression that can create a side effect such as modifying the contents of the data source or throwing an exception. This example shows how to avoid raising exceptions when you call methods in a query expression without violating the general .NET guidelines on exception handling. Those guidelines state that it's acceptable to catch a specific exception when you understand why it's thrown in a given context. For more information, see [Best Practices for Exceptions](../../../standard/exceptions/best-practices-for-exceptions.md). The final example shows how to handle those cases when you must throw an exception during execution of a query. -The following example shows how to move exception handling code outside a query expression. This refactoring is only possible when the method doesn't depend on any variables local to the query. It's easier to deal with exceptions outside of the query expression. +The following example shows how to move exception handling code outside a query expression. You can only refactor this way when the method doesn't depend on any variables local to the query. It's easier to deal with exceptions outside of the query expression. :::code language="csharp" source="./snippets/SnippetApp/Exceptions.cs" id="exceptions_1"::: -In the `catch (InvalidOperationException)` block in the preceding example, handle (or don't handle) the exception in the way that is appropriate for your application. +In the `catch (InvalidOperationException)` block in the preceding example, handle (or don't handle) the exception in the way that's appropriate for your application. -In some cases, the best response to an exception that is thrown from within a query might be to stop the query execution immediately. The following example shows how to handle exceptions that might be thrown from inside a query body. Assume that `SomeMethodThatMightThrow` can potentially cause an exception that requires the query execution to stop. +In some cases, the best response to an exception that's thrown from within a query might be to stop the query execution immediately. The following example shows how to handle exceptions that might be thrown from inside a query body. Assume that `SomeMethodThatMightThrow` can potentially cause an exception that requires the query execution to stop. -The `try` block encloses the `foreach` loop, and not the query itself. The `foreach` loop is the point at which the query is executed. Run-time exceptions are thrown when the query is executed. Therefore they must be handled in the `foreach` loop. +The `try` block encloses the `foreach` loop, and not the query itself. The `foreach` loop is the point at which the query is executed. Run-time exceptions are thrown when the query is executed. Therefore, handle them in the `foreach` loop. :::code language="csharp" source="./snippets/SnippetApp/Exceptions.cs" id="exceptions_2"::: -Remember to catch whatever exception you expect to raise and/or do any necessary cleanup in a `finally` block. +Catch whatever exception you expect to raise, and do any necessary cleanup in a `finally` block. ## See also diff --git a/docs/csharp/linq/how-to-extend-linq.md b/docs/csharp/linq/how-to-extend-linq.md index a2334c30434da..75c64c1a2f3be 100644 --- a/docs/csharp/linq/how-to-extend-linq.md +++ b/docs/csharp/linq/how-to-extend-linq.md @@ -1,22 +1,23 @@ --- -title: "How to: Write your own extensions to LINQ" +title: "Write your own extensions to LINQ" description: Learn techniques to extend the standard LINQ methods. Query based on runtime state, modify query objects, and extend LINQ capabilities. ms.topic: how-to -ms.date: 04/17/2025 +ms.date: 12/01/2025 +ai-usage: ai-assisted --- -# How to extend LINQ +# Write your own extensions to LINQ -All LINQ based methods follow one of two similar patterns. They take an enumerable sequence. They return either a different sequence, or a single value. The consistency of the shape enables you to extend LINQ by writing methods with a similar shape. In fact, the .NET libraries gained new methods in many .NET releases since LINQ was first introduced. In this article, you see examples of extending LINQ by writing your own methods that follow the same pattern. +All LINQ based methods follow one of two similar patterns. They take an enumerable sequence. They return either a different sequence or a single value. The consistency of the shape enables you to extend LINQ by writing methods with a similar shape. In fact, the .NET libraries gained new methods in many .NET releases since LINQ was first introduced. In this article, you see examples of extending LINQ by writing your own methods that follow the same pattern. ## Add custom methods for LINQ queries -You extend the set of methods that you use for LINQ queries by adding extension methods to the interface. For example, in addition to the standard average or maximum operations, you create a custom aggregate method to compute a single value from a sequence of values. You also create a method that works as a custom filter or a specific data transform for a sequence of values and returns a new sequence. Examples of such methods are , , and . +Extend the set of methods that you use for LINQ queries by adding extension methods to the interface. For example, in addition to the standard average or maximum operations, you create a custom aggregate method to compute a single value from a sequence of values. You also create a method that works as a custom filter or a specific data transform for a sequence of values and returns a new sequence. Examples of such methods are , , and . -When you extend the interface, you can apply your custom methods to any enumerable collection. For more information, see [Extension Methods](../programming-guide/classes-and-structs/extension-methods.md). +When you extend the interface, you can apply your custom methods to any enumerable collection. For more information, see [Extension members](../programming-guide/classes-and-structs/extension-methods.md). -An *aggregate* method computes a single value from a set of values. LINQ provides several aggregate methods, including , , and . You can create your own aggregate method by adding an extension method to the interface. +An *aggregate* method computes a single value from a set of values. LINQ provides several aggregate methods, including , , and . Create your own aggregate method by adding an extension method to the interface. -Beginning in C# 14, you can declare an *extension block* to contain multiple extension members. You declare an extension block with the keyword `extension` followed by the receiver parameter in parentheses. The following code example shows how to create an extension method called `Median` in an extension block. The method computes a median for a sequence of numbers of type `double`. +Beginning in C# 14, you can declare an *extension block* to contain multiple extension members. Declare an extension block with the keyword `extension` followed by the receiver parameter in parentheses. The following code example shows how to create an extension method called `Median` in an extension block. The method computes a median for a sequence of numbers of type `double`. :::code language="csharp" source="./snippets/HowToExtend/ExtensionMembers.cs" ID="MedianExtensionMember"::: @@ -24,15 +25,15 @@ You can also add the `this` modifier to a static method to declare an *extension :::code language="csharp" source="./snippets/HowToExtend/LinqExtensions.cs" ID="LinqExtensionClass"::: -You call either extension method for any enumerable collection in the same way you call other aggregate methods from the interface. +Call either extension method for any enumerable collection in the same way you call other aggregate methods from the interface. The following code example shows how to use the `Median` method for an array of type `double`. :::code language="csharp" source="./snippets/HowToExtend/Program.cs" ID="MedianUsage"::: -You can *overload your aggregate method* so that it accepts sequences of various types. The standard approach is to create an overload for each type. Another approach is to create an overload that takes a generic type and convert it to a specific type by using a delegate. You can also combine both approaches. +*Overload your aggregate method* so that it accepts sequences of various types. The standard approach is to create an overload for each type. Another approach is to create an overload that takes a generic type and convert it to a specific type by using a delegate. You can also combine both approaches. -You can create a specific overload for each type that you want to support. The following code example shows an overload of the `Median` method for the `int` type. +Create a specific overload for each type that you want to support. The following code example shows an overload of the `Median` method for the `int` type. :::code language="csharp" source="./snippets/HowToExtend/LinqExtensions.cs" ID="IntOverload"::: @@ -46,26 +47,26 @@ The following code shows an overload of the `Median` method that takes the delegate parameter to the `Median` method for each case. :::code language="csharp" source="./snippets/HowToExtend/Program.cs" ID="GenericUsage"::: -You can extend the interface with a custom query method that returns a *sequence of values*. In this case, the method must return a collection of type . Such methods can be used to apply filters or data transforms to a sequence of values. +Extend the interface with a custom query method that returns a *sequence of values*. In this case, the method must return a collection of type . Such methods can be used to apply filters or data transforms to a sequence of values. The following example shows how to create an extension method named `AlternateElements` that returns every other element in a collection, starting from the first element. :::code language="csharp" source="./snippets/HowToExtend/LinqExtensions.cs" ID="SequenceElement"::: -You can call this extension method for any enumerable collection just as you would call other methods from the interface, as shown in the following code: +Call this extension method for any enumerable collection just as you would call other methods from the interface, as shown in the following code: :::code language="csharp" source="./snippets/HowToExtend/Program.cs" ID="SequenceUsage"::: -Each example shown in this article has a different *receiver*. That means each method must be declared in a different extension block that specifies the unique receiver. The following code example shows a single static class with three different extension blocks, each of which contains one of the methods defined in this article: +Each example shown in this article has a different *receiver*. That means you must declare each method in a different extension block that specifies the unique receiver. The following code example shows a single static class with three different extension blocks, each of which contains one of the methods defined in this article: :::code language="csharp" source="./snippets/HowToExtend/ExtensionMembers.cs" ID="ExtensionMemberClass"::: The final extension block declares a generic extension block. The type parameter for the receiver is declared on the `extension` itself. -The preceding example declares one extension member in each extension block. In most cases, you create multiple extension members for the same receiver. In those cases, you should declare the extensions for those members in a single extension block. +The preceding example declares one extension member in each extension block. In most cases, you create multiple extension members for the same receiver. In those cases, declare the extensions for those members in a single extension block. diff --git a/docs/csharp/linq/index.md b/docs/csharp/linq/index.md index 87d3628bb1038..77ec4ab178ecf 100644 --- a/docs/csharp/linq/index.md +++ b/docs/csharp/linq/index.md @@ -2,13 +2,14 @@ title: Language Integrated Query (LINQ) description: Introduces Language Integrated Query (LINQ) in C#. ms.topic: concept-article -ms.date: 08/08/2025 +ms.date: 12/01/2025 +ai-usage: ai-assisted --- # Language Integrated Query (LINQ) Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support. Furthermore, you have to learn a different query language for each type of data source: SQL databases, XML documents, various Web services, and so on. With LINQ, a query is a first-class language construct, just like classes, methods, and events. -When you write queries, the most visible "language-integrated" part of LINQ is the query expression. Query expressions are written in a declarative *query syntax*. By using query syntax, you perform filtering, ordering, and grouping operations on data sources with a minimum of code. You use the same query expression patterns to query and transform data from any type of data source. +When you write queries, the most visible "language-integrated" part of LINQ is the query expression. You write query expressions in a declarative *query syntax*. By using query syntax, you perform filtering, ordering, and grouping operations on data sources with a minimum of code. You use the same query expression patterns to query and transform data from any type of data source. The following example shows a complete query operation. The complete operation includes creating a data source, defining the query expression, and executing the query in a [`foreach`](../language-reference/statements/iteration-statements.md#the-foreach-statement) statement. @@ -18,31 +19,30 @@ You might need to add a [`using`](../language-reference/keywords/using-directive ## Query expression overview -- Query expressions query and transform data from any LINQ-enabled data source. For example, a single query can retrieve data from an SQL database and produce an XML stream as output. +- Query expressions examine and transform data from any LINQ-enabled data source. For example, a single query can retrieve data from a SQL database and produce an XML stream as output. - Query expressions use many familiar C# language constructs, which make them easy to read. - The variables in a query expression are all strongly typed. - A query isn't executed until you iterate over the query variable, for example in a `foreach` statement. -- At compile time, query expressions are converted to standard query operator method calls according to the rules defined in the C# specification. Any query that can be expressed by using query syntax can also be expressed by using method syntax. In some cases, query syntax is more readable and concise. In others, method syntax is more readable. There's no semantic or performance difference between the two different forms. For more information, see [C# language specification](~/_csharpstandard/standard/expressions.md#1222-query-expressions) and [Standard query operators overview](standard-query-operators/index.md). -- Some query operations, such as or , have no equivalent query expression clause and must therefore be expressed as a method call. Method syntax can be combined with query syntax in various ways. -- Query expressions can be compiled to expression trees or to delegates, depending on the type that the query is applied to. queries are compiled to delegates. and queries are compiled to expression trees. For more information, see [Expression trees](/dotnet/csharp/advanced-topics/expression-trees). +- At compile time, the compiler converts query expressions to standard query operator method calls according to the rules defined in the C# specification. You can express any query that uses query syntax by using method syntax. In some cases, query syntax is more readable and concise. In others, method syntax is more readable. There's no semantic or performance difference between the two different forms. For more information, see [C# language specification](~/_csharpstandard/standard/expressions.md#1222-query-expressions) and [Standard query operators overview](standard-query-operators/index.md). +- Some query operations, such as or , have no equivalent query expression clause and must be expressed as a method call. You can combine method syntax with query syntax in various ways. +- Query expressions can be compiled to expression trees or to delegates, depending on the type that the query is applied to. The compiler compiles queries to delegates. The compiler compiles and queries to expression trees. For more information, see [Expression trees](/dotnet/csharp/advanced-topics/expression-trees). ## How to enable LINQ querying of your data source ### In-memory data - There are two ways you enable LINQ querying of in-memory data. If the data is of a type that implements , you query the data by using LINQ to Objects. If it doesn't make sense to enable enumeration by implementing the interface, you define LINQ standard query operator methods, either in that type or as [extension methods](../programming-guide/classes-and-structs/extension-methods.md) for that type. Custom implementations of the standard query operators should use deferred execution to return the results. +You can enable LINQ querying of in-memory data in two ways. If the data is of a type that implements , query the data by using LINQ to Objects. If it doesn't make sense to enable enumeration by implementing the interface, define LINQ standard query operator methods either in that type or as [extension members](../programming-guide/classes-and-structs/extension-methods.md) for that type. Custom implementations of the standard query operators should use deferred execution to return the results. ### Remote data - The best option for enabling LINQ querying of a remote data source is to implement the interface. +The best option for enabling LINQ querying of a remote data source is to implement the interface. ## IQueryable LINQ providers - LINQ providers that implement can vary widely in their complexity. +LINQ providers that implement can vary widely in their complexity. - A less complex `IQueryable` provider might access a single method from a Web service. This type of provider is specific to the data source because it expects specific information in the queries that it handles. It has a closed type system, perhaps exposing a single result type. Most of the execution of the query occurs locally, for example by using the implementations of the standard query operators. A less complex provider might examine only one method call expression in the expression tree that represents the query, and let the remaining logic of the query be handled elsewhere. +A less complex `IQueryable` provider might access a single method from a Web service. This type of provider is specific to the data source because it expects specific information in the queries that it handles. It has a closed type system, perhaps exposing a single result type. Most of the execution of the query occurs locally, for example by using the implementations of the standard query operators. A less complex provider might examine only one method call expression in the expression tree that represents the query and let the remaining logic of the query be handled elsewhere. - An `IQueryable` provider of medium complexity might target a data source that has a partially expressive query language. If it targets a Web service, it might access more than one method of the Web service and select which method to call based on the information that the query seeks. A provider of medium complexity would have a richer type system than a simple provider, but it would still be a fixed type system. For example, the provider might expose types that have one-to-many relationships that can be traversed, but it wouldn't provide mapping technology for user-defined types. +An `IQueryable` provider of medium complexity might target a data source that has a partially expressive query language. If it targets a Web service, it might access more than one method of the Web service and select which method to call based on the information that the query seeks. A provider of medium complexity has a richer type system than a simple provider, but it's still a fixed type system. For example, the provider might expose types that have one-to-many relationships that can be traversed, but it doesn't provide mapping technology for user-defined types. - A complex `IQueryable` provider, such as the [Entity Framework Core](/ef/core/) provider, might translate complete LINQ queries to an expressive query language, such as SQL. A complex provider is more general because it can handle a wider variety of questions in the query. It also has an open type system and therefore must contain extensive infrastructure to map user-defined types. Developing a complex provider requires a significant amount of effort. - \ No newline at end of file +A complex `IQueryable` provider, such as the [Entity Framework Core](/ef/core/) provider, might translate complete LINQ queries to an expressive query language, such as SQL. A complex provider is more general because it can handle a wider variety of questions in the query. It also has an open type system and therefore must contain extensive infrastructure to map user-defined types. Developing a complex provider requires a significant amount of effort. diff --git a/docs/csharp/linq/standard-query-operators/index.md b/docs/csharp/linq/standard-query-operators/index.md index c4220d9eb4ce4..aac0616c2d60c 100644 --- a/docs/csharp/linq/standard-query-operators/index.md +++ b/docs/csharp/linq/standard-query-operators/index.md @@ -1,15 +1,16 @@ --- -title: "Standard Query Operators Overview" +title: "Standard query operators overview" description: The LINQ standard query operators provide query capabilities including filtering, projection, aggregation, and sorting in C#. -ms.date: 05/29/2024 +ms.date: 12/01/2025 +ai-usage: ai-assisted --- -# Standard Query Operators Overview +# Standard query operators overview -The *standard query operators* are the keywords and methods that form the LINQ pattern. The C# language defines [LINQ query keywords](../../language-reference/keywords/query-keywords.md) that you use for the most common query expression. The compiler translates expressions using these keywords to the equivalent method calls. The two forms are synonymous. Other methods that are part of the namespace don't have equivalent query keywords. In those cases, you must use the method syntax. This section covers all the query operator keywords. The runtime and other NuGet packages add more methods designed to work with LINQ queries each release. The most common methods, including those that have query keyword equivalents are covered in this section. For the full list of query methods supported by the .NET Runtime, see the API documentation. In addition to the methods covered here, this class contains methods for concatenating data sources, computing a single value from a data source, such as a sum, average, or other value. +The *standard query operators* are the keywords and methods that form the LINQ pattern. The C# language defines [LINQ query keywords](../../language-reference/keywords/query-keywords.md) that you use for the most common query expression. The compiler translates expressions using these keywords to the equivalent method calls. The two forms are synonymous. Other methods that are part of the namespace don't have equivalent query keywords. In those cases, you must use the method syntax. This section covers all the query operator keywords. The runtime and other NuGet packages add more methods designed to work with LINQ queries each release. The most common methods, including those that have query keyword equivalents, are covered in this section. For the full list of query methods supported by the .NET Runtime, see the API documentation. In addition to the methods covered here, this class contains methods for concatenating data sources, computing a single value from a data source, such as a sum, average, or other value. [!INCLUDE [Prerequisites](../includes/linq-syntax.md)] -Most of these methods operate on sequences, where a sequence is an object whose type implements the interface or the interface. The standard query operators provide query capabilities including filtering, projection, aggregation, sorting and more. The methods that make up each set are static members of the and classes, respectively. They're defined as [*extension methods*](../../programming-guide/classes-and-structs/extension-methods.md) of the type that they operate on. +Most of these methods operate on sequences, where a sequence is an object whose type implements the interface or the interface. The standard query operators provide query capabilities including filtering, projection, aggregation, sorting, and more. The methods that make up each set are extension members defined in the and classes, respectively. They're defined as [*extension members*](../../programming-guide/classes-and-structs/extension-methods.md) where the receiver type is either the `IEnumerable` or `IQueryable` type that they operate on. The distinction between and sequences determines how the query is executed at runtime. @@ -17,7 +18,7 @@ For `IEnumerable`, the returned enumerable object captures the arguments that For `IQueryable`, the query is translated into an [expression tree](../../advanced-topics/expression-trees/index.md). The expression tree can be translated to a native query when the data source can optimize the query. Libraries such as [Entity Framework](/ef/core/) translate LINQ queries into native SQL queries that execute at the database. -The following code example demonstrates how the standard query operators can be used to obtain information about a sequence. +The following code example demonstrates how you can use the standard query operators to obtain information about a sequence. :::code language="csharp" source="./snippets/standard-query-operators/IndexExamples.cs" id="FirstSentence"::: @@ -25,13 +26,13 @@ Where possible, the queries in this section use a sequence of words or numbers a :::code language="csharp" source="./snippets/standard-query-operators/DataSources.cs" id="QueryDataSource"::: -Each `Student` has a grade level, a primary department, and a series of scores. A `Teacher` also has a `City` property that identifies the campus where the teacher holds classes. A `Department` has a name, and a reference to a `Teacher` who serves as the department head. +Each `Student` has a grade level, a primary department, and a series of scores. A `Teacher` also has a `City` property that identifies the campus where the teacher holds classes. A `Department` has a name and a reference to a `Teacher` who serves as the department head. You can find the data set in the [source repo](https://github.com/dotnet/docs/blob/main/docs/csharp/linq/standard-query-operators/snippets/standard-query-operators/DataSources.cs#L41). ## Types of query operators -The standard query operators differ in the timing of their execution, depending on whether they return a singleton value or a sequence of values. Those methods that return a singleton value (such as and ) execute immediately. Methods that return a sequence defer the query execution and return an enumerable object. You can use the output sequence of one query as the input sequence to another query. Calls to query methods can be chained together in one query, which enables queries to become arbitrarily complex. +The standard query operators differ in the timing of their execution, depending on whether they return a singleton value or a sequence of values. Those methods that return a singleton value (such as and ) execute immediately. Methods that return a sequence defer the query execution and return an enumerable object. You can use the output sequence of one query as the input sequence to another query. You chain query methods together in one query, which enables queries to become arbitrarily complex. ## Query operators @@ -42,7 +43,7 @@ In a LINQ query, the first step is to specify the data source. In a LINQ query, The range variable is like the iteration variable in a `foreach` loop except that no actual iteration occurs in a query expression. When the query is executed, the range variable serves as a reference to each successive element in `students`. Because the compiler can infer the type of `student`, you don't have to specify it explicitly. You can introduce more range variables in a `let` clause. For more information, see [let clause](../../language-reference/keywords/let-clause.md). > [!NOTE] -> For non-generic data sources such as , the range variable must be explicitly typed. For more information, see [How to query an ArrayList with LINQ (C#)](../how-to-query-collections.md) and [from clause](../../language-reference/keywords/from-clause.md). +> For non-generic data sources such as , you must explicitly type the range variable. For more information, see [How to query an ArrayList with LINQ (C#)](../how-to-query-collections.md) and [from clause](../../language-reference/keywords/from-clause.md). Once you obtain a data source, you can perform any number of operations on that data source: @@ -52,7 +53,7 @@ Once you obtain a data source, you can perform any number of operations on that - [Join data](join-operations.md) using the `join` keyword. - [Project data](projection-operations.md) using the `select` keyword. -## Query Expression Syntax Table +## Query expression syntax table The following table lists the standard query operators that have equivalent query expression clauses. @@ -70,7 +71,7 @@ The following table lists the standard query operators that have equivalent quer ||`orderby …, … descending`

(For more information, see [orderby clause](../../language-reference/keywords/orderby-clause.md).)| ||`where`

(For more information, see [where clause](../../language-reference/keywords/where-clause.md).)| -## Data Transformations with LINQ +## Data transformations with LINQ Language-Integrated Query (LINQ) isn't only about retrieving data. It's also a powerful tool for transforming data. By using a LINQ query, you can use a source sequence as input and modify it in many ways to create a new output sequence. You can modify the sequence itself without modifying the elements themselves by sorting and grouping. But perhaps the most powerful feature of LINQ queries is the ability to create new types. The [select](../../language-reference/keywords/select-clause.md) clause creates an output element from an input element. You use it to transform an input element into an output element: @@ -79,7 +80,7 @@ Language-Integrated Query (LINQ) isn't only about retrieving data. It's also a p - Create output sequences whose elements consist of the results of operations performed on the source data. - Create output sequences in a different format. For example, you can transform data from SQL rows or text files into XML. -These transformations can be combined in various ways in the same query. Furthermore, the output sequence of one query can be used as the input sequence for a new query. The following example transforms objects in an in-memory data structure into XML elements. +You combine these transformations in various ways in the same query. Furthermore, you can use the output sequence of one query as the input sequence for a new query. The following example transforms objects in an in-memory data structure into XML elements. :::code language="csharp" source="./snippets/standard-query-operators/IndexExamples.cs" id="XmlTransformation"::: @@ -89,7 +90,7 @@ The code produces the following XML output: For more information, see [Creating XML Trees in C# (LINQ to XML)](../../../standard/linq/create-xml-trees.md). -You can use the results of one query as the data source for a subsequent query. This example shows how to order the results of a join operation. This query creates a group join, and then sorts the groups based on the `department` element, which is still in scope. Inside the anonymous type initializer, a subquery orders all the matching elements from the `students` sequence. +You can use the results of one query as the data source for a subsequent query. This example shows how to order the results of a join operation. This query creates a group join and then sorts the groups based on the `department` element, which is still in scope. Inside the anonymous type initializer, a subquery orders all the matching elements from the `students` sequence. :::code language="csharp" source="./snippets/standard-query-operators/OrderResultsOfJoin.cs" id="OrderResultsOfJoinQuery"::: @@ -97,13 +98,13 @@ The equivalent query using method syntax is shown in the following code: :::code language="csharp" source="./snippets/standard-query-operators/OrderResultsOfJoin.cs" id="OrderResultsOfJoinMethod"::: -Although you can use an `orderby` clause with one or more of the source sequences before the join, generally we don't recommend it. Some LINQ providers might not preserve that ordering after the join. For more information, see [join clause](../../language-reference/keywords/join-clause.md). +Although you can use an `orderby` clause with one or more of the source sequences before the join, we generally don't recommend it. Some LINQ providers might not preserve that ordering after the join. For more information, see [join clause](../../language-reference/keywords/join-clause.md). ## See also - - - [select clause](../../language-reference/keywords/select-clause.md) -- [Extension Methods](../../programming-guide/classes-and-structs/extension-methods.md) +- [Extension members](../../programming-guide/classes-and-structs/extension-methods.md) - [Query Keywords (LINQ)](../../language-reference/keywords/query-keywords.md) - [Anonymous Types](../../fundamentals/types/anonymous-types.md) diff --git a/docs/framework/additional-apis/pos-for-net/pos-exception-handling.md b/docs/framework/additional-apis/pos-for-net/pos-exception-handling.md index cd7401f8c0244..a7281a6f2a29d 100644 --- a/docs/framework/additional-apis/pos-for-net/pos-exception-handling.md +++ b/docs/framework/additional-apis/pos-for-net/pos-exception-handling.md @@ -8,7 +8,7 @@ ms.custom: "pos-restored-from-archive" # POS Exception Handling (POS for .NET v1.14 SDK Documentation) -Error handling in Microsoft Point of Service for .NET (POS for .NET) is built on the object-oriented model of throwing and catching exceptions. Different exceptions are thrown in response to run-time errors, and each exception contains information about the error that triggered it in the form of an . +Error handling in Microsoft Point of Service for .NET (POS for .NET) is built on the object-oriented model of throwing and catching exceptions. Different exceptions are thrown in response to runtime errors, and each exception contains information about the error that triggered it in the form of an . The **ErrorCode** property of a thrown exception holds information about the cause of the error. Possible values for this property represent the full set of standard Unified Point Of Service (UnifiedPOS) error codes. For more information about the mapping between UnifiedPOS error codes and the POS for .NET **ErrorCode** values, see POS for .NET [Exception Classes](exception-classes.md). diff --git a/docs/framework/app-domains/application-domains.md b/docs/framework/app-domains/application-domains.md index 9bd146b9669b0..11fab79cceb50 100644 --- a/docs/framework/app-domains/application-domains.md +++ b/docs/framework/app-domains/application-domains.md @@ -85,7 +85,7 @@ Operating systems and runtime environments typically provide some form of isolat ## Application domains and threads - An application domain forms an isolation boundary for security, versioning, reliability, and unloading of managed code. A thread is the operating system construct used by the common language runtime to execute code. At run time, all managed code is loaded into an application domain and is run by one or more managed threads. + An application domain forms an isolation boundary for security, versioning, reliability, and unloading of managed code. A thread is the operating system construct used by the common language runtime to execute code. At runtime, all managed code is loaded into an application domain and is run by one or more managed threads. There is not a one-to-one correlation between application domains and threads. Several threads can execute in a single application domain at any given time, and a particular thread is not confined to a single application domain. That is, threads are free to cross application domain boundaries; a new thread is not created for each application domain. diff --git a/docs/framework/configure-apps/file-schema/runtime/bindingredirect-element.md b/docs/framework/configure-apps/file-schema/runtime/bindingredirect-element.md index c7dc795d95738..0cae76f49d868 100644 --- a/docs/framework/configure-apps/file-schema/runtime/bindingredirect-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/bindingredirect-element.md @@ -57,7 +57,7 @@ newVersion="new assembly version"/> ## Remarks - When you build a .NET Framework application against a strong-named assembly, the application uses that version of the assembly at run time by default, even if a new version is available. However, you can configure the application to run against a newer version of the assembly. For details on how the runtime uses these files to determine which assembly version to use, see [How the Runtime Locates Assemblies](../../../deployment/how-the-runtime-locates-assemblies.md). + When you build a .NET Framework application against a strong-named assembly, the application uses that version of the assembly at runtime by default, even if a new version is available. However, you can configure the application to run against a newer version of the assembly. For details on how the runtime uses these files to determine which assembly version to use, see [How the Runtime Locates Assemblies](../../../deployment/how-the-runtime-locates-assemblies.md). You can redirect more than one assembly version by including multiple `bindingRedirect` elements in a `dependentAssembly` element. You can also redirect from a newer version to an older version of the assembly. diff --git a/docs/framework/configure-apps/file-schema/runtime/gcconservememory-element.md b/docs/framework/configure-apps/file-schema/runtime/gcconservememory-element.md index 99bea4da1239c..4dc361b35f89a 100644 --- a/docs/framework/configure-apps/file-schema/runtime/gcconservememory-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/gcconservememory-element.md @@ -54,7 +54,7 @@ This setting was introduced in .NET Framework 4.8. ## See also - [Configure apps by using configuration files](../../index.md) -- [Run-time settings schema](index.md) +- [Runtime settings schema](index.md) - [Configuration file schema](../index.md) - [Fundamentals of garbage collection](../../../../standard/garbage-collection/fundamentals.md) - [NET Core runtime config options for GC](../../../../core/runtime-config/garbage-collector.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/gclohthreshold-element.md b/docs/framework/configure-apps/file-schema/runtime/gclohthreshold-element.md index 8a1aee433476a..b81b316303f3b 100644 --- a/docs/framework/configure-apps/file-schema/runtime/gclohthreshold-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/gclohthreshold-element.md @@ -51,7 +51,7 @@ This setting was introduced in .NET Framework 4.8. ## See also - [Configure apps by using configuration files](../../index.md) -- [Run-time settings schema](index.md) +- [Runtime settings schema](index.md) - [Configuration file schema](../index.md) - [Fundamentals of garbage collection](../../../../standard/garbage-collection/fundamentals.md) - [NET Core runtime config options for GC](../../../../core/runtime-config/garbage-collector.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/index.md b/docs/framework/configure-apps/file-schema/runtime/index.md index 9f31eaff4555a..1370784a086db 100644 --- a/docs/framework/configure-apps/file-schema/runtime/index.md +++ b/docs/framework/configure-apps/file-schema/runtime/index.md @@ -114,7 +114,7 @@ Runtime settings are used by the common language runtime to configure applicatio |[\](memorycache-element-cache-settings.md)|Defines an element that is used to configure a cache that is based on the class.| |[\](namedcaches-element-cache-settings.md)|Contains a collection of configuration settings for the `namedCache` instance.| |[\](netfx40-legacysecuritypolicy-element.md)|Specifies whether the runtime uses legacy code access security (CAS) policy.| -|[\](netfx40-pinvokestackresilience-element.md)|Specifies whether the runtime automatically fixes incorrect platform invoke declarations at run time, at the cost of slower transitions between managed and unmanaged code.| +|[\](netfx40-pinvokestackresilience-element.md)|Specifies whether the runtime automatically fixes incorrect platform invoke declarations at runtime, at the cost of slower transitions between managed and unmanaged code.| |[\](netfx45-cultureawarecomparergethashcode-longstrings-element.md)|Specifies whether the runtime uses a fixed amount of memory to calculate hash codes for the method.| |[\](prefercominsteadofmanagedremoting-element.md)|Specifies that the runtime will use COM interop instead of remoting across application domain boundaries.| |[\](probing-element.md)|Specifies subdirectories that the runtime searches when loading assemblies.| diff --git a/docs/framework/configure-apps/file-schema/runtime/netfx40-pinvokestackresilience-element.md b/docs/framework/configure-apps/file-schema/runtime/netfx40-pinvokestackresilience-element.md index 20d039b9f6517..b8348db2a7931 100644 --- a/docs/framework/configure-apps/file-schema/runtime/netfx40-pinvokestackresilience-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/netfx40-pinvokestackresilience-element.md @@ -9,7 +9,7 @@ ms.assetid: 39fb1588-72a4-4479-af74-0605233b68bd --- # `` Element -Specifies whether the runtime automatically fixes incorrect platform invoke declarations at run time, at the cost of slower transitions between managed and unmanaged code. +Specifies whether the runtime automatically fixes incorrect platform invoke declarations at runtime, at the cost of slower transitions between managed and unmanaged code. [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\ @@ -29,7 +29,7 @@ The following sections describe attributes, child elements, and parent elements. |Attribute|Description| |---------------|-----------------| -|`enabled`|Required attribute.

Specifies whether the runtime detects incorrect platform invoke declarations and automatically fixes the stack at run time on 32-bit platforms.| +|`enabled`|Required attribute.

Specifies whether the runtime detects incorrect platform invoke declarations and automatically fixes the stack at runtime on 32-bit platforms.| ## enabled Attribute @@ -51,7 +51,7 @@ None. ## Remarks -This element enables you to trade faster interop marshalling for run-time resilience against incorrect platform invoke declarations. +This element enables you to trade faster interop marshalling for runtime resilience against incorrect platform invoke declarations. Starting with the .NET Framework 4, a streamlined interop marshalling architecture provides a significant performance improvement for transitions from managed code to unmanaged code. In earlier versions of the .NET Framework, the marshalling layer detected incorrect platform invoke declarations on 32-bit platforms and automatically fixed the stack. The new marshalling architecture eliminates this step. As a result, transitions are very fast, but an incorrect platform invoke declaration can cause a program failure. diff --git a/docs/framework/configure-apps/file-schema/runtime/runtime-element.md b/docs/framework/configure-apps/file-schema/runtime/runtime-element.md index 68040ff85ddcb..82c66f028a3b9 100644 --- a/docs/framework/configure-apps/file-schema/runtime/runtime-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/runtime-element.md @@ -68,7 +68,7 @@ None. |[\](legacyimpersonationpolicy-element.md)|Specifies that the Windows identity does not flow across asynchronous points, regardless of the flow settings for the execution context on the current thread.| |[\](loadfromremotesources-element.md)|Specifies whether assemblies from remote sources are loaded as full trust.| |[\](netfx40-legacysecuritypolicy-element.md)|Specifies whether the runtime uses legacy code access security (CAS) policy.| -|[\](netfx40-pinvokestackresilience-element.md)|Specifies whether the runtime automatically fixes incorrect platform invoke declarations at run time, at the cost of slower transitions between managed and unmanaged code.| +|[\](netfx40-pinvokestackresilience-element.md)|Specifies whether the runtime automatically fixes incorrect platform invoke declarations at runtime, at the cost of slower transitions between managed and unmanaged code.| |[\](netfx45-cultureawarecomparergethashcode-longstrings-element.md)|Specifies whether the runtime uses a fixed amount of memory to calculate hash codes for the method.| |[\](prefercominsteadofmanagedremoting-element.md)|Specifies that the runtime will use COM interop instead of remoting across application domain boundaries.| |[\](relativebindforresources-element.md)|Optimizes the probe for satellite assemblies.| diff --git a/docs/framework/configure-apps/file-schema/trace-debug/add-element-for-sharedlisteners.md b/docs/framework/configure-apps/file-schema/trace-debug/add-element-for-sharedlisteners.md index 07a6a0ca89d3b..4b442735660bc 100644 --- a/docs/framework/configure-apps/file-schema/trace-debug/add-element-for-sharedlisteners.md +++ b/docs/framework/configure-apps/file-schema/trace-debug/add-element-for-sharedlisteners.md @@ -12,7 +12,7 @@ ms.assetid: 1595e1bc-2492-421f-8384-7f382eb8eb57 --- # `` Element for \ -Adds a listener to the `sharedListeners` collection. `sharedListeners` is a collection of listeners that any [\](source-element.md) or [\](trace-element.md) can reference. By default, listeners in the `sharedListeners` collection are not placed in a `Listeners` collection. They must be added by name to the [\](source-element.md) or [\](trace-element.md). It is not possible to get the listeners in the `sharedListeners` collection in code at run time. +Adds a listener to the `sharedListeners` collection. `sharedListeners` is a collection of listeners that any [\](source-element.md) or [\](trace-element.md) can reference. By default, listeners in the `sharedListeners` collection are not placed in a `Listeners` collection. They must be added by name to the [\](source-element.md) or [\](trace-element.md). It is not possible to get the listeners in the `sharedListeners` collection in code at runtime. [**\**](../configuration-element.md)\   [**\**](system-diagnostics-element.md)\ diff --git a/docs/framework/configure-apps/file-schema/trace-debug/sharedlisteners-element.md b/docs/framework/configure-apps/file-schema/trace-debug/sharedlisteners-element.md index ff5e81a201af4..d0060d9584a03 100644 --- a/docs/framework/configure-apps/file-schema/trace-debug/sharedlisteners-element.md +++ b/docs/framework/configure-apps/file-schema/trace-debug/sharedlisteners-element.md @@ -15,7 +15,7 @@ ms.assetid: de200534-19dd-4156-86cf-c50521802c4c --- # `` Element -Contains listeners that any source or trace element can reference. These listeners do not receive any traces by default, and it is not possible to retrieve these listeners at run time. Listeners identified as shared listeners can be added to sources or traces by name. +Contains listeners that any source or trace element can reference. These listeners do not receive any traces by default, and it is not possible to retrieve these listeners at runtime. Listeners identified as shared listeners can be added to sources or traces by name. [**\**](../configuration-element.md)   [**\**](system-diagnostics-element.md) diff --git a/docs/framework/configure-apps/file-schema/wcf/add-of-protocolmapping.md b/docs/framework/configure-apps/file-schema/wcf/add-of-protocolmapping.md index ffeff94c71cf6..6a69740654bc3 100644 --- a/docs/framework/configure-apps/file-schema/wcf/add-of-protocolmapping.md +++ b/docs/framework/configure-apps/file-schema/wcf/add-of-protocolmapping.md @@ -6,50 +6,50 @@ ms.assetid: 08e62249-1641-41d1-91b1-66d7b46244e4 --- # \ of \ -Represents a default protocol mapping between a transport protocol scheme (e.g., http, net.tcp, net.pipe, etc.) and a Windows Communication Foundation (WCF) binding. When creating default endpoints at run time, WCF looks at the configured mappings and decides on which binding to use for a particular based address. - +Represents a default protocol mapping between a transport protocol scheme (e.g., http, net.tcp, net.pipe, etc.) and a Windows Communication Foundation (WCF) binding. When creating default endpoints at runtime, WCF looks at the configured mappings and decides on which binding to use for a particular based address. + [**\**](../configuration-element.md)\   [**\**](system-servicemodel.md)\     [**\**](protocolmapping.md)\ -      **\** - -## Syntax - -```xml +      **\** + +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Element|Description| -|-------------|-----------------| -|binding|A string that specifies the type of binding to be used for an endpoint during default endpoint creation.| -|bindingConfiguration|A string that specifies the name of the binding configuration section to be referenced.| -|scheme|The transport protocol scheme to be used for the default endpoint.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](protocolmapping.md)|Represents a configuration section for defining default protocol mappings between transport protocol schemes (e.g., http, net.tcp, net.pipe, etc.) and Windows Communication Foundation (WCF) bindings.| - -## Example - - The following configuration example shows the default protocol mapping in the machine.config file. You can override this default mapping at the machine level by modifying the machine.config file. Or if you would only like to override it within the scope of an application, you can override this section within your application configuration file and change the mapping for individual protocol schemes. - -```xml +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Element|Description| +|-------------|-----------------| +|binding|A string that specifies the type of binding to be used for an endpoint during default endpoint creation.| +|bindingConfiguration|A string that specifies the name of the binding configuration section to be referenced.| +|scheme|The transport protocol scheme to be used for the default endpoint.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](protocolmapping.md)|Represents a configuration section for defining default protocol mappings between transport protocol schemes (e.g., http, net.tcp, net.pipe, etc.) and Windows Communication Foundation (WCF) bindings.| + +## Example + + The following configuration example shows the default protocol mapping in the machine.config file. You can override this default mapping at the machine level by modifying the machine.config file. Or if you would only like to override it within the scope of an application, you can override this section within your application configuration file and change the mapping for individual protocol schemes. + +```xml @@ -60,8 +60,8 @@ Represents a default protocol mapping between a transport protocol scheme (e.g., -``` - +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/wcf/behavior-of-endpointbehaviors.md b/docs/framework/configure-apps/file-schema/wcf/behavior-of-endpointbehaviors.md index 0ff36d1c698b3..ae3428158c33a 100644 --- a/docs/framework/configure-apps/file-schema/wcf/behavior-of-endpointbehaviors.md +++ b/docs/framework/configure-apps/file-schema/wcf/behavior-of-endpointbehaviors.md @@ -6,17 +6,17 @@ ms.assetid: b90ca3bc-3c22-4174-b903-e3a39898bd27 --- # \ of \ -The `behavior` element contains a collection of settings for the behavior of an endpoint. Each behavior is indexed by its `name`. Endpoints can link to each behavior through this name. Starting with .NET Framework 4, bindings and behaviors are not required to have a name. For more information about default configuration and nameless bindings and behaviors, see [Simplified Configuration](../../../wcf/simplified-configuration.md) and [Simplified Configuration for WCF Services](../../../wcf/samples/simplified-configuration-for-wcf-services.md). - +The `behavior` element contains a collection of settings for the behavior of an endpoint. Each behavior is indexed by its `name`. Endpoints can link to each behavior through this name. Starting with .NET Framework 4, bindings and behaviors are not required to have a name. For more information about default configuration and nameless bindings and behaviors, see [Simplified Configuration](../../../wcf/simplified-configuration.md) and [Simplified Configuration for WCF Services](../../../wcf/samples/simplified-configuration-for-wcf-services.md). + [**\**](../configuration-element.md)\   [**\**](system-servicemodel.md)\     [**\**](behaviors.md)\       [**\**](endpointbehaviors.md)\ -        **\** - -## Syntax - -```xml +        **\** + +## Syntax + +```xml @@ -24,37 +24,37 @@ The `behavior` element contains a collection of settings for the behavior of an -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|name|A unique string that contains the configuration name of the behavior. This value is a user-defined string that must be unique, since it acts as the identification string for the element. Starting with .NET Framework 4, bindings and behaviors are not required to have a name. For more information about default configuration and nameless bindings and behaviors, see [Simplified Configuration](../../../wcf/simplified-configuration.md) and [Simplified Configuration for WCF Services](../../../wcf/samples/simplified-configuration-for-wcf-services.md).| - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](clientcredentials.md)|Specifies the credentials used to authenticate the client to a service.| -|[\](callbackdebug.md)|Specifies service debugging for a Windows Communication Foundation (WCF) callback object.| -|[\](callbacktimeouts.md)|Specifies the timeout for the client callback.| -|[\](clientvia.md)|Specifies the route a message should take.| -|[\](datacontractserializer.md)|Contains configuration data for the DataContractSerializer.| -|[\](dispatchersynchronization.md)|Specifies an endpoint behavior that enables a service to send replies asynchronously.| -|[\](enablewebscript.md)|Enables the endpoint behavior that makes it possible to consume the service from ASP.NET AJAX web pages. The behavior should only be used in conjunction with either the \ standard binding, or the \ binding element.| -|[\](endpointdiscovery.md)|Specifies the various discovery settings for an endpoint, such as its discoverability, scopes, and any custom extensions to its metadata.| -|[\](soapprocessing.md)|Defines the client endpoint behavior used to marshal messages between different binding types and message versions.| -|[\](synchronousreceive-element.md)|Specifies run-time behavior for receiving messages in either a service or client application. It does not have any attributes or child elements.| -|[\](transactedbatching.md)|Specifies whether transaction batching is supported for receive operations.| -|[\](webhttp.md)|Specifies the WebHttpBehavior on an endpoint through configuration. This behavior, when used in conjunction with the \ standard binding, enables the Web programming model for a WCF service.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|name|A unique string that contains the configuration name of the behavior. This value is a user-defined string that must be unique, since it acts as the identification string for the element. Starting with .NET Framework 4, bindings and behaviors are not required to have a name. For more information about default configuration and nameless bindings and behaviors, see [Simplified Configuration](../../../wcf/simplified-configuration.md) and [Simplified Configuration for WCF Services](../../../wcf/samples/simplified-configuration-for-wcf-services.md).| + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](clientcredentials.md)|Specifies the credentials used to authenticate the client to a service.| +|[\](callbackdebug.md)|Specifies service debugging for a Windows Communication Foundation (WCF) callback object.| +|[\](callbacktimeouts.md)|Specifies the timeout for the client callback.| +|[\](clientvia.md)|Specifies the route a message should take.| +|[\](datacontractserializer.md)|Contains configuration data for the DataContractSerializer.| +|[\](dispatchersynchronization.md)|Specifies an endpoint behavior that enables a service to send replies asynchronously.| +|[\](enablewebscript.md)|Enables the endpoint behavior that makes it possible to consume the service from ASP.NET AJAX web pages. The behavior should only be used in conjunction with either the \ standard binding, or the \ binding element.| +|[\](endpointdiscovery.md)|Specifies the various discovery settings for an endpoint, such as its discoverability, scopes, and any custom extensions to its metadata.| +|[\](soapprocessing.md)|Defines the client endpoint behavior used to marshal messages between different binding types and message versions.| +|[\](synchronousreceive-element.md)|Specifies runtime behavior for receiving messages in either a service or client application. It does not have any attributes or child elements.| +|[\](transactedbatching.md)|Specifies whether transaction batching is supported for receive operations.| +|[\](webhttp.md)|Specifies the WebHttpBehavior on an endpoint through configuration. This behavior, when used in conjunction with the \ standard binding, enables the Web programming model for a WCF service.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| |[\](endpointbehaviors.md)|A collection of endpoint behavior elements.| diff --git a/docs/framework/configure-apps/file-schema/wcf/behavior-of-servicebehaviors.md b/docs/framework/configure-apps/file-schema/wcf/behavior-of-servicebehaviors.md index 7145982c704f5..871ffb52f3f51 100644 --- a/docs/framework/configure-apps/file-schema/wcf/behavior-of-servicebehaviors.md +++ b/docs/framework/configure-apps/file-schema/wcf/behavior-of-servicebehaviors.md @@ -6,20 +6,20 @@ ms.assetid: 78fc0a08-55de-416a-ac12-a5e6ffc9a987 --- # \ of \ -The `behavior` element contains a collection of settings for the behavior of a service. Each behavior is indexed by its `name`. Services can link to each behavior through this name using the `behaviorConfiguration` attribute of the [\](endpoint-element.md) element. This allows endpoints to share common behavior configurations without redefining the settings. Starting with .NET Framework 4, bindings and behaviors are not required to have a name. For more information about default configuration and nameless bindings and behaviors, see [Simplified Configuration](../../../wcf/simplified-configuration.md) and [Simplified Configuration for WCF Services](../../../wcf/samples/simplified-configuration-for-wcf-services.md). - +The `behavior` element contains a collection of settings for the behavior of a service. Each behavior is indexed by its `name`. Services can link to each behavior through this name using the `behaviorConfiguration` attribute of the [\](endpoint-element.md) element. This allows endpoints to share common behavior configurations without redefining the settings. Starting with .NET Framework 4, bindings and behaviors are not required to have a name. For more information about default configuration and nameless bindings and behaviors, see [Simplified Configuration](../../../wcf/simplified-configuration.md) and [Simplified Configuration for WCF Services](../../../wcf/samples/simplified-configuration-for-wcf-services.md). + > [!NOTE] -> Behavior elements specific to Windows Workflow activities, such as the [\](../windows-workflow-foundation/sendmessagechannelcache.md) element, are documented in the [\ of \](../windows-workflow-foundation/behavior-of-servicebehaviors-of-workflow.md) page. - +> Behavior elements specific to Windows Workflow activities, such as the [\](../windows-workflow-foundation/sendmessagechannelcache.md) element, are documented in the [\ of \](../windows-workflow-foundation/behavior-of-servicebehaviors-of-workflow.md) page. + [**\**](../configuration-element.md)\   [**\**](system-servicemodel.md)\     [**\**](behaviors.md)\       [**\**](servicebehaviors.md)\ -        **\** - -## Syntax - -```xml +        **\** + +## Syntax + +```xml @@ -27,39 +27,39 @@ The `behavior` element contains a collection of settings for the behavior of a s -``` - -## Attributes and Elements +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|name|A unique string that contains the configuration name of the behavior. This value is a user-defined string that must be unique, since it acts as the identification string for the element. Starting with .NET Framework 4, bindings and behaviors are not required to have a name. For more information about default configuration and nameless bindings and behaviors, see [Simplified Configuration](../../../wcf/simplified-configuration.md) and [Simplified Configuration for WCF Services](../../../wcf/samples/simplified-configuration-for-wcf-services.md).| + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](datacontractserializer-element.md)|Contains configuration data for the DataContractSerializer.| +|[\](persistenceprovider.md)|Specifies the type of the persistence provider implementation to use, as well as the time-out to use for persistence operations.| +|[\](routing-of-servicebehavior.md)|Provides runtime access to the routing service to allow dynamic modification of the routing configuration.| +|[\](serviceauthenticationmanager.md)|Provides a workflow configuration element that establishes at the service level the validity of a transmission, message, or originator..| +|[\](serviceauthorization-element.md)|Specifies settings that authorize access to service operations.| +|[\](servicecredentials.md)|Specifies the credential to be used in authenticating the service and the client credential validation-related settings.| +|[\](servicedebug.md)|Specifies debugging and help information features for a Windows Communication Foundation (WCF) service.| +|[\](servicediscovery.md)|Specifies the discoverability of service endpoints.| +|[\](servicemetadata.md)|Specifies the publication of service metadata and associated information.| +|[\](servicesecurityaudit.md)|Specifies settings that enable auditing of security events during service operations.| +|[\](servicethrottling.md)|Specifies the throttling mechanism of a WCF service.| +|[\](servicetimeouts.md)|Specifies the timeout for a service.| +|[\](workflowruntime.md)|Specifies settings for an instance of WorkflowRuntime for hosting workflow-based WCF services.| +|[\](userequestheadersformetadataaddress.md)|Enables the retrieval of metadata address information from the request message headers.| + +### Parent Elements - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|name|A unique string that contains the configuration name of the behavior. This value is a user-defined string that must be unique, since it acts as the identification string for the element. Starting with .NET Framework 4, bindings and behaviors are not required to have a name. For more information about default configuration and nameless bindings and behaviors, see [Simplified Configuration](../../../wcf/simplified-configuration.md) and [Simplified Configuration for WCF Services](../../../wcf/samples/simplified-configuration-for-wcf-services.md).| - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](datacontractserializer-element.md)|Contains configuration data for the DataContractSerializer.| -|[\](persistenceprovider.md)|Specifies the type of the persistence provider implementation to use, as well as the time-out to use for persistence operations.| -|[\](routing-of-servicebehavior.md)|Provides run-time access to the routing service to allow dynamic modification of the routing configuration.| -|[\](serviceauthenticationmanager.md)|Provides a workflow configuration element that establishes at the service level the validity of a transmission, message, or originator..| -|[\](serviceauthorization-element.md)|Specifies settings that authorize access to service operations.| -|[\](servicecredentials.md)|Specifies the credential to be used in authenticating the service and the client credential validation-related settings.| -|[\](servicedebug.md)|Specifies debugging and help information features for a Windows Communication Foundation (WCF) service.| -|[\](servicediscovery.md)|Specifies the discoverability of service endpoints.| -|[\](servicemetadata.md)|Specifies the publication of service metadata and associated information.| -|[\](servicesecurityaudit.md)|Specifies settings that enable auditing of security events during service operations.| -|[\](servicethrottling.md)|Specifies the throttling mechanism of a WCF service.| -|[\](servicetimeouts.md)|Specifies the timeout for a service.| -|[\](workflowruntime.md)|Specifies settings for an instance of WorkflowRuntime for hosting workflow-based WCF services.| -|[\](userequestheadersformetadataaddress.md)|Enables the retrieval of metadata address information from the request message headers.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| +|Element|Description| +|-------------|-----------------| |[\](servicebehaviors.md)|A collection of service behavior elements.| diff --git a/docs/framework/configure-apps/file-schema/wcf/clientcredentials.md b/docs/framework/configure-apps/file-schema/wcf/clientcredentials.md index 6566dc550c91c..13b2286cbc40a 100644 --- a/docs/framework/configure-apps/file-schema/wcf/clientcredentials.md +++ b/docs/framework/configure-apps/file-schema/wcf/clientcredentials.md @@ -43,7 +43,7 @@ Specifies the credentials used to authenticate the client to a service. |Attribute|Description| |---------------|-----------------| -|`supportInteractive`|A Boolean value that specifies whether an interactive user can be involved in selecting a client credential at run time. The default value is `true`.| +|`supportInteractive`|A Boolean value that specifies whether an interactive user can be involved in selecting a client credential at runtime. The default value is `true`.| |`type`|A string that specifies the type of this configuration element.| ### Child Elements diff --git a/docs/framework/configure-apps/file-schema/wcf/diagnostics.md b/docs/framework/configure-apps/file-schema/wcf/diagnostics.md index f924419f61dba..cb2ca3ea866d6 100644 --- a/docs/framework/configure-apps/file-schema/wcf/diagnostics.md +++ b/docs/framework/configure-apps/file-schema/wcf/diagnostics.md @@ -6,15 +6,15 @@ ms.assetid: 0c2f95c4-cc12-4fb5-a70c-7fc6fa95db58 --- # \ -The `diagnostics` element defines settings that can be used by an administrator for run-time inspection and control. - +The `diagnostics` element defines settings that can be used by an administrator for runtime inspection and control. + [**\**](../configuration-element.md)\   [**\**](system-servicemodel.md)\ -    **\** - -## Syntax - -```xml +    **\** + +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|etwProviderId|A string that specifies the identifier for the Event-Tracing provider, which writes events to ETW sessions.| -|performanceCounters|Specifies whether performance counters for the assembly are enabled. Valid values are

- Off: Performance counters are disabled.
- ServiceOnly: Only performance counters relevant to this service is enabled.
- All: Performance counters can be viewed at run time.
- Default: A single performance counter instance _WCF_Admin is created. This instance is used to enable the collection of SQM data for used by the infrastructure. None of the counter values for this instance are updated and therefore will remain at zero. This is the default value if no configuration is present for WCF.| -|wmiProviderEnabled|A Boolean value that specifies whether the WMI provider for the assembly is enabled. The WMI provider is required for user to gain run-time access to the inspection and control features of Windows Communication Foundation (WCF). The default is `false`.| - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](endtoendtracing.md)|A configuration element that allows you to enable and disable different aspects of end-to-end tracing during the running of a service application.| -|[\](messagelogging.md)|Describes the settings for WCF message logging.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|serviceModel|The root element of all WCF configuration elements.| - -## Remarks - - The `diagnostics` section defines the diagnostics settings for all services located in an assembly. It is not possible to define separate diagnostics settings at the service level unless there is only one service in the assembly. Attributes are set according to the requirements of the section. - -## Example - -```xml +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|etwProviderId|A string that specifies the identifier for the Event-Tracing provider, which writes events to ETW sessions.| +|performanceCounters|Specifies whether performance counters for the assembly are enabled. Valid values are

- Off: Performance counters are disabled.
- ServiceOnly: Only performance counters relevant to this service is enabled.
- All: Performance counters can be viewed at runtime.
- Default: A single performance counter instance _WCF_Admin is created. This instance is used to enable the collection of SQM data for used by the infrastructure. None of the counter values for this instance are updated and therefore will remain at zero. This is the default value if no configuration is present for WCF.| +|wmiProviderEnabled|A Boolean value that specifies whether the WMI provider for the assembly is enabled. The WMI provider is required for user to gain runtime access to the inspection and control features of Windows Communication Foundation (WCF). The default is `false`.| + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](endtoendtracing.md)|A configuration element that allows you to enable and disable different aspects of end-to-end tracing during the running of a service application.| +|[\](messagelogging.md)|Describes the settings for WCF message logging.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|serviceModel|The root element of all WCF configuration elements.| + +## Remarks + + The `diagnostics` section defines the diagnostics settings for all services located in an assembly. It is not possible to define separate diagnostics settings at the service level unless there is only one service in the assembly. Attributes are set according to the requirements of the section. + +## Example + +```xml -``` - +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/wcf/discoveryclient.md b/docs/framework/configure-apps/file-schema/wcf/discoveryclient.md index c726cee0753f6..c06f571a3e67f 100644 --- a/docs/framework/configure-apps/file-schema/wcf/discoveryclient.md +++ b/docs/framework/configure-apps/file-schema/wcf/discoveryclient.md @@ -6,18 +6,18 @@ ms.assetid: a78f74c3-1152-4149-ab29-3f12d316caeb --- # \ -A configuration element for creating a custom binding that enables a client application to automatically search for a discoverable service and find its address at run time. - +A configuration element for creating a custom binding that enables a client application to automatically search for a discoverable service and find its address at runtime. + [**\**](../configuration-element.md)\   [**\**](system-servicemodel.md)\     [**\**](bindings.md)\       [**\**](custombinding.md)\         **\**\ -          **\** - -## Syntax - -```xml +          **\** + +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|discoveryEndpoint|A string that contains the name of the Discovery Endpoint that enables a client application to automatically search for a discoverable service and find its address at run time.| - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](standardendpoints.md)|A configuration element that supplies a set of criteria used by a client application to search for a discovery service. Criteria can be grouped into search criteria (specifying what services you’re looking for) and find termination criteria (how long the search should last).| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](bindings.md)|Defines all binding capabilities of the custom binding.| - +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|discoveryEndpoint|A string that contains the name of the Discovery Endpoint that enables a client application to automatically search for a discoverable service and find its address at runtime.| + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](standardendpoints.md)|A configuration element that supplies a set of criteria used by a client application to search for a discovery service. Criteria can be grouped into search criteria (specifying what services you’re looking for) and find termination criteria (how long the search should last).| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](bindings.md)|Defines all binding capabilities of the custom binding.| + ## See also - diff --git a/docs/framework/configure-apps/file-schema/wcf/discoveryclientsettings.md b/docs/framework/configure-apps/file-schema/wcf/discoveryclientsettings.md index ba0f0457d5bae..b5c389b82fb0d 100644 --- a/docs/framework/configure-apps/file-schema/wcf/discoveryclientsettings.md +++ b/docs/framework/configure-apps/file-schema/wcf/discoveryclientsettings.md @@ -6,18 +6,18 @@ ms.assetid: 02e1b823-a8bb-4074-90d5-8599f71e8f9d --- # \ -Contains the settings needed by an application to participate in the service discovery process as a client. - +Contains the settings needed by an application to participate in the service discovery process as a client. + [**\**](../configuration-element.md)\   [**\**](system-servicemodel.md)\     [**\**](standardendpoints.md)\       [**\**](dynamicendpoint.md)\         **\**\ -          **\** - -## Syntax - -```xml +          **\** + +## Syntax + +```xml @@ -40,30 +40,30 @@ Contains the settings needed by an application to participate in the service dis -``` - -## Attributes and Elements +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|discoveryEndpoint|A string that contains the name of the Discovery Endpoint that enables a client application to automatically search for a discoverable service and find its address at runtime.| + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](standardendpoints.md)|A configuration element that supplies a set of criteria used by a client application to search for a discovery service. Criteria can be grouped into search criteria (specifying what services you’re looking for) and find termination criteria (how long the search should last).| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](standardendpoints.md)|Defines a standard endpoint that contains information to enable an application to function as a client program that can find the endpoint address dynamically at runtime.| - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|discoveryEndpoint|A string that contains the name of the Discovery Endpoint that enables a client application to automatically search for a discoverable service and find its address at run time.| - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](standardendpoints.md)|A configuration element that supplies a set of criteria used by a client application to search for a discovery service. Criteria can be grouped into search criteria (specifying what services you’re looking for) and find termination criteria (how long the search should last).| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](standardendpoints.md)|Defines a standard endpoint that contains information to enable an application to function as a client program that can find the endpoint address dynamically at run time.| - ## See also - diff --git a/docs/framework/configure-apps/file-schema/wcf/dynamicendpoint.md b/docs/framework/configure-apps/file-schema/wcf/dynamicendpoint.md index 35c3dd0977366..2279a10aa31b5 100644 --- a/docs/framework/configure-apps/file-schema/wcf/dynamicendpoint.md +++ b/docs/framework/configure-apps/file-schema/wcf/dynamicendpoint.md @@ -6,16 +6,16 @@ ms.assetid: 929f223d-176d-4205-9505-234ddb6dbff4 --- # \ -This configuration element defines a standard endpoint that contains information to enable an application to function as a client program that can find the endpoint address dynamically at run time. - +This configuration element defines a standard endpoint that contains information to enable an application to function as a client program that can find the endpoint address dynamically at runtime. + [**\**](../configuration-element.md)\   [**\**](system-servicemodel.md)\     [**\**](standardendpoints.md)\ -      **\** - -## Syntax - -```xml +      **\** + +## Syntax + +```xml @@ -38,28 +38,28 @@ This configuration element defines a standard endpoint that contains information -``` - -## Attributes and Elements +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](discoveryclientsettings.md)|Contains the settings needed by an application to participate in the service discovery process as a client.| + +### Parent Elements - The following sections describe attributes, child elements, and parent elements. - -### Attributes +|Element|Description| +|-------------|-----------------| +|[\](standardendpoints.md)|A collection of standard endpoints that are pre-defined endpoints with one or more of their properties (address, binding, contract) fixed.| - None. - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](discoveryclientsettings.md)|Contains the settings needed by an application to participate in the service discovery process as a client.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](standardendpoints.md)|A collection of standard endpoints that are pre-defined endpoints with one or more of their properties (address, binding, contract) fixed.| - ## See also - diff --git a/docs/framework/configure-apps/file-schema/wcf/netnamedpipebinding.md b/docs/framework/configure-apps/file-schema/wcf/netnamedpipebinding.md index 357bcb14df4a6..a90f59bf4e212 100644 --- a/docs/framework/configure-apps/file-schema/wcf/netnamedpipebinding.md +++ b/docs/framework/configure-apps/file-schema/wcf/netnamedpipebinding.md @@ -6,16 +6,16 @@ ms.assetid: 00a8580b-face-47a4-838d-b9fed48e72df --- # \ -Defines a binding that is secure, reliable, optimized for on-machine cross process communication. By default, it generates a runtime communication stack with WS-ReliableMessaging for reliability, transport security for transfer security, named pipes for message delivery, and binary message encoding. - +Defines a binding that is secure, reliable, optimized for on-machine cross process communication. By default, it generates a runtime communication stack with WS-ReliableMessaging for reliability, transport security for transfer security, named pipes for message delivery, and binary message encoding. + [**\**](../configuration-element.md)\   [**\**](system-servicemodel.md)\     [**\**](bindings.md)\ -      **\** - -## Syntax - -```xml +      **\** + +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|closeTimeout|A value that specifies the interval of time provided for a close operation to complete. This value should be greater than or equal to . The default is 00:01:00.| -|hostNameComparisonMode|Specifies the HTTP hostname comparison mode used to parse URIs. This attribute is of type , which indicates whether the hostname is used to reach the service when matching on the URI. The default value is , which ignores the hostname in the match.| -|maxBufferPoolSize|An integer that specifies the maximum buffer pool size for this binding. The default is 524,288 bytes (512 * 1024). Many parts of Windows Communication Foundation (WCF) use buffers. Creating and destroying buffers each time they are used is expensive, and garbage collection for buffers is also expensive. With buffer pools, you can take a buffer from the pool, use it, and return it to the pool once you are done. Thus the overhead in creating and destroying buffers is avoided.| -|maxBufferSize|A positive integer that specifies the maximum size, in bytes, of the buffer used to store messages in memory. If the buffer is full, excess data remains in the underlying socket until the buffer has room again. This value cannot be less than `maxReceivedMessageSize` attribute. The default is 65536. For more information, see .| -|maxConnections|An integer that specifies the maximum number of outbound and inbound connections the service will create/accept. Incoming and outgoing connections are counted against a separate limit specified by this attribute.

Inbound connections in excess of the limit are queued until a space below the limit becomes available.

Outbound connections in excess of the limit are queued until a space below the limit becomes available.

The default is 10.| -|maxReceivedMessageSize|A positive integer that specifies the maximum message size, in bytes, including headers, that can be received on a channel configured with this binding. The sender of a message exceeding this limit will receive a SOAP fault. The receiver drops the message and creates an entry of the event in the trace log. The default is 65536.| -|name|A string that contains the configuration name of the binding. This value should be unique because it is used as an identification for the binding. Starting with .NET Framework 4, bindings and behaviors are not required to have a name. For more information about default configuration and nameless bindings and behaviors, see [Simplified Configuration](../../../wcf/simplified-configuration.md) and [Simplified Configuration for WCF Services](../../../wcf/samples/simplified-configuration-for-wcf-services.md).| -|openTimeout|A value that specifies the interval of time provided for an open operation to complete. This value should be greater than or equal to . The default is 00:01:00.| -|receiveTimeout|A value that specifies the interval of time provided for a receive operation to complete. This value should be greater than or equal to . The default is 00:10:00.| -|sendTimeout|A value that specifies the interval of time provided for a send operation to complete. This value should be greater than or equal to . The default is 00:01:00.| -|transactionFlow|A Boolean value that specifies whether the binding supports flowing WS-Transactions. The default is `false`.| -|transactionProtocol|Specifies the transaction protocol to be used with this binding. Valid values are

- OleTransactions
- WS-AtomicTransactionOctober2004

The default is OleTransactions. This attribute is of type .| -|transferMode|A value that specifies whether messages are buffered or streamed or a request or response.| - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](security-of-netnamedpipebinding.md)|Defines the security settings for the binding. This element is of type .| -|[\](/previous-versions/dotnet/netframework-4.0/ms731325(v=vs.100))|Defines the constraints on the complexity of SOAP messages that can be processed by endpoints configured with this binding. This element is of type .| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](bindings.md)|This element holds a collection of standard and custom bindings.| - -## Remarks - - The `NetNamedPipeBinding` generates a run-time communication stack by default, which uses transport security, named pipes for message delivery, and a binary message encoding. This binding is an appropriate Windows Communication Foundation (WCF) system-provided choice for on-machine communication. It also supports transactions. - - The default configuration for the `NetNamedPipeBinding` is similar to the configuration provided by the `NetTcpBinding`, but it is simpler because the WCF implementation is only meant for on-machine use and consequently there are fewer exposed features. The most notable difference is that the `securityMode` setting only offers the `None` and `Transport` options. SOAP security support is not an included option. The security behavior is configurable using the optional `securityMode` attribute. - -## Example - - The following example demonstrates the netNamedPipeBinding binding, which provides cross-process communication on the same machine. Named pipes do not work across machines. - - The binding is specified in the configuration files for the client and service. The binding type is specified in the `binding` attribute of the `` element. If you want to configure the netNamedPipeBinding binding and change some of its settings, you must define a binding configuration. The endpoint must reference the binding configuration by name with a `bindingConfiguration` attribute. In this example, the binding configuration is named Binding1. - -```xml +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|closeTimeout|A value that specifies the interval of time provided for a close operation to complete. This value should be greater than or equal to . The default is 00:01:00.| +|hostNameComparisonMode|Specifies the HTTP hostname comparison mode used to parse URIs. This attribute is of type , which indicates whether the hostname is used to reach the service when matching on the URI. The default value is , which ignores the hostname in the match.| +|maxBufferPoolSize|An integer that specifies the maximum buffer pool size for this binding. The default is 524,288 bytes (512 * 1024). Many parts of Windows Communication Foundation (WCF) use buffers. Creating and destroying buffers each time they are used is expensive, and garbage collection for buffers is also expensive. With buffer pools, you can take a buffer from the pool, use it, and return it to the pool once you are done. Thus the overhead in creating and destroying buffers is avoided.| +|maxBufferSize|A positive integer that specifies the maximum size, in bytes, of the buffer used to store messages in memory. If the buffer is full, excess data remains in the underlying socket until the buffer has room again. This value cannot be less than `maxReceivedMessageSize` attribute. The default is 65536. For more information, see .| +|maxConnections|An integer that specifies the maximum number of outbound and inbound connections the service will create/accept. Incoming and outgoing connections are counted against a separate limit specified by this attribute.

Inbound connections in excess of the limit are queued until a space below the limit becomes available.

Outbound connections in excess of the limit are queued until a space below the limit becomes available.

The default is 10.| +|maxReceivedMessageSize|A positive integer that specifies the maximum message size, in bytes, including headers, that can be received on a channel configured with this binding. The sender of a message exceeding this limit will receive a SOAP fault. The receiver drops the message and creates an entry of the event in the trace log. The default is 65536.| +|name|A string that contains the configuration name of the binding. This value should be unique because it is used as an identification for the binding. Starting with .NET Framework 4, bindings and behaviors are not required to have a name. For more information about default configuration and nameless bindings and behaviors, see [Simplified Configuration](../../../wcf/simplified-configuration.md) and [Simplified Configuration for WCF Services](../../../wcf/samples/simplified-configuration-for-wcf-services.md).| +|openTimeout|A value that specifies the interval of time provided for an open operation to complete. This value should be greater than or equal to . The default is 00:01:00.| +|receiveTimeout|A value that specifies the interval of time provided for a receive operation to complete. This value should be greater than or equal to . The default is 00:10:00.| +|sendTimeout|A value that specifies the interval of time provided for a send operation to complete. This value should be greater than or equal to . The default is 00:01:00.| +|transactionFlow|A Boolean value that specifies whether the binding supports flowing WS-Transactions. The default is `false`.| +|transactionProtocol|Specifies the transaction protocol to be used with this binding. Valid values are

- OleTransactions
- WS-AtomicTransactionOctober2004

The default is OleTransactions. This attribute is of type .| +|transferMode|A value that specifies whether messages are buffered or streamed or a request or response.| + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](security-of-netnamedpipebinding.md)|Defines the security settings for the binding. This element is of type .| +|[\](/previous-versions/dotnet/netframework-4.0/ms731325(v=vs.100))|Defines the constraints on the complexity of SOAP messages that can be processed by endpoints configured with this binding. This element is of type .| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](bindings.md)|This element holds a collection of standard and custom bindings.| + +## Remarks + + The `NetNamedPipeBinding` generates a runtime communication stack by default, which uses transport security, named pipes for message delivery, and a binary message encoding. This binding is an appropriate Windows Communication Foundation (WCF) system-provided choice for on-machine communication. It also supports transactions. + + The default configuration for the `NetNamedPipeBinding` is similar to the configuration provided by the `NetTcpBinding`, but it is simpler because the WCF implementation is only meant for on-machine use and consequently there are fewer exposed features. The most notable difference is that the `securityMode` setting only offers the `None` and `Transport` options. SOAP security support is not an included option. The security behavior is configurable using the optional `securityMode` attribute. + +## Example + + The following example demonstrates the netNamedPipeBinding binding, which provides cross-process communication on the same machine. Named pipes do not work across machines. + + The binding is specified in the configuration files for the client and service. The binding type is specified in the `binding` attribute of the `` element. If you want to configure the netNamedPipeBinding binding and change some of its settings, you must define a binding configuration. The endpoint must reference the binding configuration by name with a `bindingConfiguration` attribute. In this example, the binding configuration is named Binding1. + +```xml @@ -141,8 +141,8 @@ Defines a binding that is secure, reliable, optimized for on-machine cross proce
-``` - +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/wcf/nettcpbinding.md b/docs/framework/configure-apps/file-schema/wcf/nettcpbinding.md index 865352275d690..330f141e33dd2 100644 --- a/docs/framework/configure-apps/file-schema/wcf/nettcpbinding.md +++ b/docs/framework/configure-apps/file-schema/wcf/nettcpbinding.md @@ -2,7 +2,7 @@ title: "" description: Represents a secure, reliable, optimized binding intended only for WCF cross-machine communication using TCP. Reliable messaging is off by default. ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "netTcpBinding Element" ms.assetid: 5c5104a7-8754-4335-8233-46a45322503e --- @@ -13,11 +13,11 @@ Specifies a secure, reliable, optimized binding suitable for cross-machine commu [**\**](../configuration-element.md)\   [**\**](system-servicemodel.md)\     [**\**](bindings.md)\ -      **\** - -## Syntax - -```xml +      **\** + +## Syntax + +```xml -``` - +``` + ## Attributes and elements -The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`closeTimeout`|A value that specifies the interval of time provided for a close operation to complete. This value should be greater than or equal to . The default is 00:01:00.| -|`hostNameComparisonMode`|Specifies the HTTP hostname comparison mode used to parse URIs. This attribute is of type , which indicates whether the hostname is used to reach the service when matching on the URI. The default value is , which ignores the hostname in the match.| -|`listenBacklog`|A positive integer that specifies the maximum number of channels waiting to be accepted on the listener. Connections in excess of this limit are queued until space below the limit becomes available. The `connectionTimeout` attribute limits the time a client will wait to be connected before throwing a connection exception. The default is 10.| -|`maxBufferPoolSize`|An integer that specifies the maximum buffer pool size for this binding. The default is 512 * 1024 bytes. Many parts of Windows Communication Foundation (WCF) use buffers. Creating and destroying buffers each time they are used is expensive, and garbage collection for buffers is also expensive. With buffer pools, you can take a buffer from the pool, use it, and return it to the pool once you are done. Thus the overhead in creating and destroying buffers is avoided.| -|`maxBufferSize`|A positive integer that specifies the maximum size, in bytes, of the buffer used to store messages in memory.

If the `transferMode` attribute equals to `Buffered`, this attribute should be equal to the `maxReceivedMessageSize` attribute value.

If the `transferMode` attribute equals to `Streamed`, this attribute cannot be more than the `maxReceivedMessageSize` attribute value, and should be at least the size of the headers.

The default is 65536. For more information, see .| -|`maxConnections`|An integer that specifies the maximum number of outbound and inbound connections the service will create/accept. Incoming and outgoing connections are counted against a separate limit specified by this attribute.

Inbound connections in excess of the limit are queued until a space below the limit becomes available.

Outbound connections in excess of the limit are queued until a space below the limit becomes available.

The default is 10.| -|`maxReceivedMessageSize`|A positive integer that specifies the maximum message size, in bytes, including headers, that can be received on a channel configured with this binding. The sender of a message exceeding this limit will receive a SOAP fault. The receiver drops the message and creates an entry of the event in the trace log. The default is 65536.| -|`name`|A string that contains the configuration name of the binding. This value should be unique because it is used as an identification for the binding. Starting with .NET Framework 4, bindings and behaviors are not required to have a name. For more information about default configuration and nameless bindings and behaviors, see [Simplified Configuration](../../../wcf/simplified-configuration.md) and [Simplified Configuration for WCF Services](../../../wcf/samples/simplified-configuration-for-wcf-services.md).| -|`openTimeout`|A value that specifies the interval of time provided for an open operation to complete. This value should be greater than or equal to . The default is 00:01:00.| -|`portSharingEnabled`|A Boolean value that specifies whether TCP port sharing is enabled for this connection. If this is `false`, each binding uses its own exclusive port. This setting is relevant only to services, because clients are not affected.| -|`receiveTimeout`|A value that specifies the interval of time provided for a receive operation to complete. This value should be greater than or equal to . The default is 00:10:00.| -|`sendTimeout`|A value that specifies the interval of time provided for a send operation to complete. This value should be greater than or equal to . The default is 00:01:00.| -|`transactionFlow`|A Boolean value that specifies whether the binding supports flowing WS-Transactions. The default is `false`.| -|`transactionProtocol`|Specifies the transaction protocol to be used with this binding. Valid values are

- OleTransactions
- WSAtomicTransactionOctober2004

The default is OleTransactions. This attribute is of type .| -|`transferMode`|A value that specifies whether messages are buffered or streamed or a request or response.| - -### Child elements - -|Element|Description| -|-------------|-----------------| -|[\](security-of-nettcpbinding.md)|Defines the security settings for the binding. This element is of type .| -|[\](/previous-versions/dotnet/netframework-4.0/ms731325(v=vs.100))|Defines the constraints on the complexity of SOAP messages that can be processed by endpoints configured with this binding. This element is of type .| -|[\](/previous-versions/ms731375(v=vs.90))|Specifies if reliable sessions are established between channel endpoints.| - -### Parent elements - -|Element|Description| -|-------------|-----------------| -|[\](bindings.md)|This element holds a collection of standard and custom bindings.| - +The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`closeTimeout`|A value that specifies the interval of time provided for a close operation to complete. This value should be greater than or equal to . The default is 00:01:00.| +|`hostNameComparisonMode`|Specifies the HTTP hostname comparison mode used to parse URIs. This attribute is of type , which indicates whether the hostname is used to reach the service when matching on the URI. The default value is , which ignores the hostname in the match.| +|`listenBacklog`|A positive integer that specifies the maximum number of channels waiting to be accepted on the listener. Connections in excess of this limit are queued until space below the limit becomes available. The `connectionTimeout` attribute limits the time a client will wait to be connected before throwing a connection exception. The default is 10.| +|`maxBufferPoolSize`|An integer that specifies the maximum buffer pool size for this binding. The default is 512 * 1024 bytes. Many parts of Windows Communication Foundation (WCF) use buffers. Creating and destroying buffers each time they are used is expensive, and garbage collection for buffers is also expensive. With buffer pools, you can take a buffer from the pool, use it, and return it to the pool once you are done. Thus the overhead in creating and destroying buffers is avoided.| +|`maxBufferSize`|A positive integer that specifies the maximum size, in bytes, of the buffer used to store messages in memory.

If the `transferMode` attribute equals to `Buffered`, this attribute should be equal to the `maxReceivedMessageSize` attribute value.

If the `transferMode` attribute equals to `Streamed`, this attribute cannot be more than the `maxReceivedMessageSize` attribute value, and should be at least the size of the headers.

The default is 65536. For more information, see .| +|`maxConnections`|An integer that specifies the maximum number of outbound and inbound connections the service will create/accept. Incoming and outgoing connections are counted against a separate limit specified by this attribute.

Inbound connections in excess of the limit are queued until a space below the limit becomes available.

Outbound connections in excess of the limit are queued until a space below the limit becomes available.

The default is 10.| +|`maxReceivedMessageSize`|A positive integer that specifies the maximum message size, in bytes, including headers, that can be received on a channel configured with this binding. The sender of a message exceeding this limit will receive a SOAP fault. The receiver drops the message and creates an entry of the event in the trace log. The default is 65536.| +|`name`|A string that contains the configuration name of the binding. This value should be unique because it is used as an identification for the binding. Starting with .NET Framework 4, bindings and behaviors are not required to have a name. For more information about default configuration and nameless bindings and behaviors, see [Simplified Configuration](../../../wcf/simplified-configuration.md) and [Simplified Configuration for WCF Services](../../../wcf/samples/simplified-configuration-for-wcf-services.md).| +|`openTimeout`|A value that specifies the interval of time provided for an open operation to complete. This value should be greater than or equal to . The default is 00:01:00.| +|`portSharingEnabled`|A Boolean value that specifies whether TCP port sharing is enabled for this connection. If this is `false`, each binding uses its own exclusive port. This setting is relevant only to services, because clients are not affected.| +|`receiveTimeout`|A value that specifies the interval of time provided for a receive operation to complete. This value should be greater than or equal to . The default is 00:10:00.| +|`sendTimeout`|A value that specifies the interval of time provided for a send operation to complete. This value should be greater than or equal to . The default is 00:01:00.| +|`transactionFlow`|A Boolean value that specifies whether the binding supports flowing WS-Transactions. The default is `false`.| +|`transactionProtocol`|Specifies the transaction protocol to be used with this binding. Valid values are

- OleTransactions
- WSAtomicTransactionOctober2004

The default is OleTransactions. This attribute is of type .| +|`transferMode`|A value that specifies whether messages are buffered or streamed or a request or response.| + +### Child elements + +|Element|Description| +|-------------|-----------------| +|[\](security-of-nettcpbinding.md)|Defines the security settings for the binding. This element is of type .| +|[\](/previous-versions/dotnet/netframework-4.0/ms731325(v=vs.100))|Defines the constraints on the complexity of SOAP messages that can be processed by endpoints configured with this binding. This element is of type .| +|[\](/previous-versions/ms731375(v=vs.90))|Specifies if reliable sessions are established between channel endpoints.| + +### Parent elements + +|Element|Description| +|-------------|-----------------| +|[\](bindings.md)|This element holds a collection of standard and custom bindings.| + ## Remarks -This binding generates a run-time communication stack by default, which uses transport security, TCP for message delivery, and a binary message encoding. This binding is an appropriate Windows Communication Foundation (WCF) system-provided choice for communicating over an Intranet. - - The default configuration for the `netTcpBinding` is faster than the configuration provided by the `wsHttpBinding`, but it is intended only for WCF communication. The security behavior is configurable using the optional `securityMode` attribute. The use of WS-ReliableMessaging is configurable using the optional `reliableSessionEnabled` attribute. But reliable messaging is off by default. More generally, the HTTP system-provided bindings such as `wsHttpBinding` and `basicHttpBinding` are configured to turn things on by default, whereas the `netTcpBinding` binding turns things off by default so that you have to opt-in to get support, for example, for one of the WS-* specifications. This means that the default configuration for TCP is faster at exchanging messages between endpoints than those configured for the HTTP bindings by default. - +This binding generates a runtime communication stack by default, which uses transport security, TCP for message delivery, and a binary message encoding. This binding is an appropriate Windows Communication Foundation (WCF) system-provided choice for communicating over an Intranet. + + The default configuration for the `netTcpBinding` is faster than the configuration provided by the `wsHttpBinding`, but it is intended only for WCF communication. The security behavior is configurable using the optional `securityMode` attribute. The use of WS-ReliableMessaging is configurable using the optional `reliableSessionEnabled` attribute. But reliable messaging is off by default. More generally, the HTTP system-provided bindings such as `wsHttpBinding` and `basicHttpBinding` are configured to turn things on by default, whereas the `netTcpBinding` binding turns things off by default so that you have to opt-in to get support, for example, for one of the WS-* specifications. This means that the default configuration for TCP is faster at exchanging messages between endpoints than those configured for the HTTP bindings by default. + ## Example -The binding is specified in the configuration files for the client and service. The binding type is specified in the `binding` attribute of the `` element. If you want to configure the netTcpBinding binding and change some of its settings, it is necessary to define a binding configuration. The endpoint must reference the binding configuration with a `bindingConfiguration` attribute. In the following example, a binding configuration is defined. - -```xml +The binding is specified in the configuration files for the client and service. The binding type is specified in the `binding` attribute of the `` element. If you want to configure the netTcpBinding binding and change some of its settings, it is necessary to define a binding configuration. The endpoint must reference the binding configuration with a `bindingConfiguration` attribute. In the following example, a binding configuration is defined. + +```xml @@ -140,8 +140,8 @@ The binding is specified in the configuration files for the client and service.
-``` - +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/wcf/protocolmapping.md b/docs/framework/configure-apps/file-schema/wcf/protocolmapping.md index 23867df0f31f8..9a9b622344ff4 100644 --- a/docs/framework/configure-apps/file-schema/wcf/protocolmapping.md +++ b/docs/framework/configure-apps/file-schema/wcf/protocolmapping.md @@ -6,47 +6,47 @@ ms.assetid: 5076644b-1f33-4f26-9488-87de9fcda04c --- # \ -Represents a configuration section for defining a set of default protocol mapping between transport protocol schemes (e.g., http, net.tcp, net.pipe, etc.) and WCF bindings. When creating default endpoints at run time, Windows Communication Foundation (WCF) looks at the configured mappings and decides on which binding to use for a particular based address. - +Represents a configuration section for defining a set of default protocol mapping between transport protocol schemes (e.g., http, net.tcp, net.pipe, etc.) and WCF bindings. When creating default endpoints at runtime, Windows Communication Foundation (WCF) looks at the configured mappings and decides on which binding to use for a particular based address. + [**\**](../configuration-element.md)\   [**\**](system-servicemodel.md)\ -    **\** - -## Syntax - -```xml +    **\** + +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](filters-of-routing.md)|Contains a default protocol mapping between a transport protocol scheme (e.g., http, net.tcp, net.pipe, etc.) and a WCF binding.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](system-servicemodel.md)|The root element of all WCF configuration elements.| - -## Example - - The following configuration example shows the default protocol mapping in the machine.config file. You can override this default mapping at the machine level by modifying the machine.config file. Or if you would only like to override it within the scope of an application, you can override this section within your application configuration file and change the mapping for individual protocol schemes. - -```xml +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](filters-of-routing.md)|Contains a default protocol mapping between a transport protocol scheme (e.g., http, net.tcp, net.pipe, etc.) and a WCF binding.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](system-servicemodel.md)|The root element of all WCF configuration elements.| + +## Example + + The following configuration example shows the default protocol mapping in the machine.config file. You can override this default mapping at the machine level by modifying the machine.config file. Or if you would only like to override it within the scope of an application, you can override this section within your application configuration file and change the mapping for individual protocol schemes. + +```xml @@ -57,8 +57,8 @@ Represents a configuration section for defining a set of default protocol mappin -``` - +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/wcf/reliablesession.md b/docs/framework/configure-apps/file-schema/wcf/reliablesession.md index f10c1fc8e4162..353175c934d6b 100644 --- a/docs/framework/configure-apps/file-schema/wcf/reliablesession.md +++ b/docs/framework/configure-apps/file-schema/wcf/reliablesession.md @@ -6,18 +6,18 @@ ms.assetid: 129b4a59-37f0-4030-b664-03795d257d29 --- # \ -Defines setting for WS-Reliable Messaging. When this element is added to a custom binding, the resulting channel can support exactly-once delivery assurances. - +Defines setting for WS-Reliable Messaging. When this element is added to a custom binding, the resulting channel can support exactly-once delivery assurances. + [**\**](../configuration-element.md)\   [**\**](system-servicemodel.md)\     [**\**](bindings.md)\       [**\**](custombinding.md)\         **\**\ -          **\** - -## Syntax - -```xml +          **\** + +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|acknowledgementInterval|A that contains the maximum time interval the channel is going to wait to send an acknowledgment for messages received up to that point. The default is 00:00:0.2.| -|flowControlEnabled|A Boolean value that indicates whether advanced flow control, a Microsoft-specific implementation of flow control for WS-Reliable messaging, is activated. The default is `true`.| -|inactivityTimeout|A that specifies the maximum duration that the channel is going to allow the other communication party not to send any messages, before faulting the channel. The default is 00:10:00.

Activity on a channel is defined as receiving an application or infrastructure messages. This property controls the maximum amount of time to keep an inactive session alive. If longer time passes with no activity, the session is aborted by the infrastructure and the channel faults. **Note:** It is not necessary for the application to periodically send messages to keep the connection alive.| -|maxPendingChannels|An integer that specifies the maximum number of channels that can wait on the listener to be accepted. This value should be between 1 to 16384 inclusive. The default is 4.

Channels are pending when they are waiting to be accepted. Once that limit is reached, no channels are created. Rather, they are put in pending mode until this number goes down (by accepting pending channels). This is a per-factory limit.

When the threshold is reached and a remote application tries to establish a new reliable session, the request is denied and the open operation that prompted this faults. This limit does not apply to the number of pending outgoing channels.| -|maxRetryCount|An integer that specifies the maximum number of times a reliable channel attempts to retransmit a message it has not received an acknowledgment for, by calling Send on its underlying channel.

This value should be greater than zero. The default is 8.

This value should be an integer greater than zero. If an acknowledgment is not received after the last retransmission, the channel faults.

A message is considered to be transferred if its delivery at the recipient has been acknowledged by the recipient.

If an acknowledgment has not been received within a certain amount of time for a message that has been transmitted, the infrastructure automatically retransmits the message. The infrastructure tries to resend the message for at most the number of times specified by this property. If an acknowledgment is not received after the last retransmission, the channel faults.

The infrastructure uses an exponential back-off algorithm to determine when to retransmit, based on a computed average round-trip time. The time initially starts at 1 second before retransmission and doubling the delay with every attempt, which results in approximately 8.5 minutes passing between the first transmission attempt and the last retransmission attempt. The time for the first retransmission attempt is adjusted according to the calculated round-trip time and the resulting stretch of time that those attempts take varies accordingly. This allows the retransmission time to dynamically adapt to varying network conditions.| -|maxTransferWindowSize|An integer that specifies the maximum size of the buffer. Valid values are from 1 to 4096 inclusive.

On the client, this attribute defines the maximum size of the buffer used by a reliable channel to hold messages not yet acknowledged by the receiver. The unit of the quota is a message. If the buffer is full, further SEND operations are blocked.

On the receiver, this attribute defines the maximum size of the buffer used by the channel to store incoming messages not yet dispatched to the application. If the buffer is full, further messages are silently dropped by the receiver and require retransmission by the client.| -|ordered|A Boolean that specifies whether messages are guaranteed to arrive in the order they were sent. If this setting is `false`, messages can arrive out of order. The default is `true`.| -|reliableMessagingVersion|A valid value from that specifies the WS-ReliableMessaging version to be used.| - -### Child Elements - - None - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](bindings.md)|Defines all binding capabilities of the custom binding.| - -## Remarks - - Reliable sessions provide features for reliable messaging and sessions. Reliable messaging retries communication on failure and allows delivery assurances such as in-order arrival of messages to be specified. Sessions maintain state for clients between calls. This element also optionally provides ordered message delivery. This implemented session can cross SOAP and transport intermediaries. - - Each binding element represents a processing step when sending or receiving messages. At run time, binding elements create the channel factories and listeners that are necessary to build outgoing and incoming channel stacks required to send and receive messages. The `reliableSession` provides an optional layer in the stack that can establish a reliable session between endpoints and configure the behavior of this session. - - For more information, see [Reliable Sessions](../../../wcf/feature-details/reliable-sessions.md). - -## Example - - The following example demonstrates how to configure a custom binding with various transport and message encoding elements, especially enabling reliable sessions, which maintains client state and specifies in-order delivery assurances. This feature is configured in the application configuration files for the client and service. The example show the service configuration. - -```xml +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|acknowledgementInterval|A that contains the maximum time interval the channel is going to wait to send an acknowledgment for messages received up to that point. The default is 00:00:0.2.| +|flowControlEnabled|A Boolean value that indicates whether advanced flow control, a Microsoft-specific implementation of flow control for WS-Reliable messaging, is activated. The default is `true`.| +|inactivityTimeout|A that specifies the maximum duration that the channel is going to allow the other communication party not to send any messages, before faulting the channel. The default is 00:10:00.

Activity on a channel is defined as receiving an application or infrastructure messages. This property controls the maximum amount of time to keep an inactive session alive. If longer time passes with no activity, the session is aborted by the infrastructure and the channel faults. **Note:** It is not necessary for the application to periodically send messages to keep the connection alive.| +|maxPendingChannels|An integer that specifies the maximum number of channels that can wait on the listener to be accepted. This value should be between 1 to 16384 inclusive. The default is 4.

Channels are pending when they are waiting to be accepted. Once that limit is reached, no channels are created. Rather, they are put in pending mode until this number goes down (by accepting pending channels). This is a per-factory limit.

When the threshold is reached and a remote application tries to establish a new reliable session, the request is denied and the open operation that prompted this faults. This limit does not apply to the number of pending outgoing channels.| +|maxRetryCount|An integer that specifies the maximum number of times a reliable channel attempts to retransmit a message it has not received an acknowledgment for, by calling Send on its underlying channel.

This value should be greater than zero. The default is 8.

This value should be an integer greater than zero. If an acknowledgment is not received after the last retransmission, the channel faults.

A message is considered to be transferred if its delivery at the recipient has been acknowledged by the recipient.

If an acknowledgment has not been received within a certain amount of time for a message that has been transmitted, the infrastructure automatically retransmits the message. The infrastructure tries to resend the message for at most the number of times specified by this property. If an acknowledgment is not received after the last retransmission, the channel faults.

The infrastructure uses an exponential back-off algorithm to determine when to retransmit, based on a computed average round-trip time. The time initially starts at 1 second before retransmission and doubling the delay with every attempt, which results in approximately 8.5 minutes passing between the first transmission attempt and the last retransmission attempt. The time for the first retransmission attempt is adjusted according to the calculated round-trip time and the resulting stretch of time that those attempts take varies accordingly. This allows the retransmission time to dynamically adapt to varying network conditions.| +|maxTransferWindowSize|An integer that specifies the maximum size of the buffer. Valid values are from 1 to 4096 inclusive.

On the client, this attribute defines the maximum size of the buffer used by a reliable channel to hold messages not yet acknowledged by the receiver. The unit of the quota is a message. If the buffer is full, further SEND operations are blocked.

On the receiver, this attribute defines the maximum size of the buffer used by the channel to store incoming messages not yet dispatched to the application. If the buffer is full, further messages are silently dropped by the receiver and require retransmission by the client.| +|ordered|A Boolean that specifies whether messages are guaranteed to arrive in the order they were sent. If this setting is `false`, messages can arrive out of order. The default is `true`.| +|reliableMessagingVersion|A valid value from that specifies the WS-ReliableMessaging version to be used.| + +### Child Elements + + None + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](bindings.md)|Defines all binding capabilities of the custom binding.| + +## Remarks + + Reliable sessions provide features for reliable messaging and sessions. Reliable messaging retries communication on failure and allows delivery assurances such as in-order arrival of messages to be specified. Sessions maintain state for clients between calls. This element also optionally provides ordered message delivery. This implemented session can cross SOAP and transport intermediaries. + + Each binding element represents a processing step when sending or receiving messages. At runtime, binding elements create the channel factories and listeners that are necessary to build outgoing and incoming channel stacks required to send and receive messages. The `reliableSession` provides an optional layer in the stack that can establish a reliable session between endpoints and configure the behavior of this session. + + For more information, see [Reliable Sessions](../../../wcf/feature-details/reliable-sessions.md). + +## Example + + The following example demonstrates how to configure a custom binding with various transport and message encoding elements, especially enabling reliable sessions, which maintains client state and specifies in-order delivery assurances. This feature is configured in the application configuration files for the client and service. The example show the service configuration. + +```xml @@ -118,8 +118,8 @@ Defines setting for WS-Reliable Messaging. When this element is added to a custo
-``` - +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/wcf/routing-of-servicebehavior.md b/docs/framework/configure-apps/file-schema/wcf/routing-of-servicebehavior.md index 68b0993b24e0e..dd8514f12aa8e 100644 --- a/docs/framework/configure-apps/file-schema/wcf/routing-of-servicebehavior.md +++ b/docs/framework/configure-apps/file-schema/wcf/routing-of-servicebehavior.md @@ -6,18 +6,18 @@ ms.assetid: d8f9c844-4629-4a45-9599-856dc8f01794 --- # \ of \ -Provides run-time access to the routing service to allow dynamic modification of the routing configuration. - +Provides runtime access to the routing service to allow dynamic modification of the routing configuration. + [**\**](../configuration-element.md)\   [**\**](system-servicemodel.md)\     [**\**](behaviors.md)\       [**\**](servicebehaviors.md)\         [**\**](behavior-of-servicebehaviors.md)\ -          **\** - -## Syntax - -```xml +          **\** + +## Syntax + +```xml @@ -27,32 +27,32 @@ Provides run-time access to the routing service to allow dynamic modification of -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|filterTable|A string that specifies the name of the routing table that contains filters to be evaluated by the routing service. This value must match the `name` attribute of a [\](filtertable.md) element in the [\](filtertables.md) section.| -|routeOnHeaderOnly|A Boolean value that specifies whether the filter will examine both the message body and the header, or the header only. The default is `true`.| -|soapProcessingEnabled|A Boolean value that specifies whether SOAP processing should occur.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](behavior-of-endpointbehaviors.md)|Specifies a behavior element.| - -## Remarks - - When added to the service’s behavior configuration, this configuration element enables routing for the service. You can specify the actual routing table to be used by the service in this element. - - Using this configuration section, you can change your routing settings on the fly when your deployment pattern changes. At run time, you can register your own routing extension with new routing settings and the routing service will begin using the updated configuration information for new messages and sessions, while leaving in-flight messages/sessions using whatever rules were in place when they started. This gives you the ability to do session-safe, recycle-less reconfiguration of the Routing Service during runtime. +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|filterTable|A string that specifies the name of the routing table that contains filters to be evaluated by the routing service. This value must match the `name` attribute of a [\](filtertable.md) element in the [\](filtertables.md) section.| +|routeOnHeaderOnly|A Boolean value that specifies whether the filter will examine both the message body and the header, or the header only. The default is `true`.| +|soapProcessingEnabled|A Boolean value that specifies whether SOAP processing should occur.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](behavior-of-endpointbehaviors.md)|Specifies a behavior element.| + +## Remarks + + When added to the service’s behavior configuration, this configuration element enables routing for the service. You can specify the actual routing table to be used by the service in this element. + + Using this configuration section, you can change your routing settings on the fly when your deployment pattern changes. At runtime, you can register your own routing extension with new routing settings and the routing service will begin using the updated configuration information for new messages and sessions, while leaving in-flight messages/sessions using whatever rules were in place when they started. This gives you the ability to do session-safe, recycle-less reconfiguration of the Routing Service during runtime. diff --git a/docs/framework/configure-apps/file-schema/wcf/standardendpoints.md b/docs/framework/configure-apps/file-schema/wcf/standardendpoints.md index 3e8c2a710f0df..205b7bca2c57b 100644 --- a/docs/framework/configure-apps/file-schema/wcf/standardendpoints.md +++ b/docs/framework/configure-apps/file-schema/wcf/standardendpoints.md @@ -6,49 +6,49 @@ ms.assetid: d62153d7-a6e6-462a-a784-cca61e9c2ba1 --- # \ -This configuration section allows you to define a collection of standard endpoints, which are reusable preconfigured endpoints. A standard endpoint will have one or more of the address, binding and contract attributes set to a fixed value. For example, in the discovery endpoint the contract is fixed. You can also use standard endpoints to extend service endpoint with new properties similar to defining custom bindings. - +This configuration section allows you to define a collection of standard endpoints, which are reusable preconfigured endpoints. A standard endpoint will have one or more of the address, binding and contract attributes set to a fixed value. For example, in the discovery endpoint the contract is fixed. You can also use standard endpoints to extend service endpoint with new properties similar to defining custom bindings. + [**\**](../configuration-element.md)\   [**\**](system-servicemodel.md)\ -    **\** - -## Syntax - -```xml +    **\** + +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](announcementendpoint.md)|Defines a standard endpoint with a fixed announcement contract. A service can optionally announce its availability by sending an online and offline announcement message when it is opened or closed respectively. A Windows Communication Foundation (WCF) service specifies the announcement endpoints in the [\](servicediscovery.md) element and uses the AnnouncementClient to perform the announcements. A client wishing to listen for the announcement from other service is actually acting as a WCF service; thus you have to configure the announcement endpoints for that client in the [\](services.md) section.| -|[\](discoveryendpoint.md)|Defines a standard endpoint with a fixed discovery contract. When added to the service configuration, it specifies where to listen for the discovery messages. When added to the client configuration it specifies where to send the discovery queries.| -|[\](dynamicendpoint.md)|This configuration element defines a standard endpoint that contains information to enable an application to function as a client program that can find the endpoint address dynamically at run time.| -|[\](mexendpoint.md)|Defines a standard endpoint with a fixed IMetadataExchange contract. Since all metadata exchange endpoints specify IMetadataExchange as their contract, you can use this standard point instead of defining one for yourself.| -|[\](udpannouncementendpoint.md)|Defines a standard endpoint that is used by services to send announcement messages over a UDP binding. It has a fixed contract and supports two discovery versions. In addition it has a fixed UDP binding and a default address value as specified in the WS-Discovery specifications (WS-Discovery April 2005 or WS-Discovery version 1.1). You can specify the multicast address to use for sending and receiving the announcement messages.| -|[\](udpdiscoveryendpoint.md)|Defines a standard endpoint that is pre-configured for discovery operations over a UDP multicast binding. This endpoint has a fixed contract and supports two WS-Discovery protocol versions. In addition, it has a fixed UDP binding and a default address as specified in the WS-Discovery specifications (WS-Discovery April 2005 or WS-Discovery V1.1).| -|[\](webhttpendpoint.md)|Defines a standard endpoint with a fixed [\](webhttpbinding.md) binding that automatically adds the [\](webhttp.md) behavior. Use this endpoint when writing a REST service.| -|[\](webscriptendpoint.md)|Defines a standard endpoint with a fixed [\](webhttpbinding.md) binding that automatically adds the [\](enablewebscript.md) behavior. Use this endpoint when you are writing a service that is called from an ASP.NET AJAX application.| -|[\](workflowcontrolendpoint.md)|Defines a standard endpoint for controlling the execution of workflow instances (create, run, suspend, terminate, etc).| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|\|The root element of all WCF configuration elements.| - +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](announcementendpoint.md)|Defines a standard endpoint with a fixed announcement contract. A service can optionally announce its availability by sending an online and offline announcement message when it is opened or closed respectively. A Windows Communication Foundation (WCF) service specifies the announcement endpoints in the [\](servicediscovery.md) element and uses the AnnouncementClient to perform the announcements. A client wishing to listen for the announcement from other service is actually acting as a WCF service; thus you have to configure the announcement endpoints for that client in the [\](services.md) section.| +|[\](discoveryendpoint.md)|Defines a standard endpoint with a fixed discovery contract. When added to the service configuration, it specifies where to listen for the discovery messages. When added to the client configuration it specifies where to send the discovery queries.| +|[\](dynamicendpoint.md)|This configuration element defines a standard endpoint that contains information to enable an application to function as a client program that can find the endpoint address dynamically at runtime.| +|[\](mexendpoint.md)|Defines a standard endpoint with a fixed IMetadataExchange contract. Since all metadata exchange endpoints specify IMetadataExchange as their contract, you can use this standard point instead of defining one for yourself.| +|[\](udpannouncementendpoint.md)|Defines a standard endpoint that is used by services to send announcement messages over a UDP binding. It has a fixed contract and supports two discovery versions. In addition it has a fixed UDP binding and a default address value as specified in the WS-Discovery specifications (WS-Discovery April 2005 or WS-Discovery version 1.1). You can specify the multicast address to use for sending and receiving the announcement messages.| +|[\](udpdiscoveryendpoint.md)|Defines a standard endpoint that is pre-configured for discovery operations over a UDP multicast binding. This endpoint has a fixed contract and supports two WS-Discovery protocol versions. In addition, it has a fixed UDP binding and a default address as specified in the WS-Discovery specifications (WS-Discovery April 2005 or WS-Discovery V1.1).| +|[\](webhttpendpoint.md)|Defines a standard endpoint with a fixed [\](webhttpbinding.md) binding that automatically adds the [\](webhttp.md) behavior. Use this endpoint when writing a REST service.| +|[\](webscriptendpoint.md)|Defines a standard endpoint with a fixed [\](webhttpbinding.md) binding that automatically adds the [\](enablewebscript.md) behavior. Use this endpoint when you are writing a service that is called from an ASP.NET AJAX application.| +|[\](workflowcontrolendpoint.md)|Defines a standard endpoint for controlling the execution of workflow instances (create, run, suspend, terminate, etc).| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|\|The root element of all WCF configuration elements.| + ## See also - [Standard Endpoints](../../../wcf/feature-details/standard-endpoints.md) diff --git a/docs/framework/configure-apps/file-schema/wcf/synchronousreceive-element.md b/docs/framework/configure-apps/file-schema/wcf/synchronousreceive-element.md index 99d22ca03a03c..0a193eb43f1c3 100644 --- a/docs/framework/configure-apps/file-schema/wcf/synchronousreceive-element.md +++ b/docs/framework/configure-apps/file-schema/wcf/synchronousreceive-element.md @@ -6,43 +6,43 @@ ms.assetid: cc070387-3d11-4b02-a952-bc08ad2df05a --- # \ element -This configuration element is used to specify run-time behavior for receiving messages in either a service or client application. It does not have any attributes or child elements. - +This configuration element is used to specify runtime behavior for receiving messages in either a service or client application. It does not have any attributes or child elements. + [**\**](../configuration-element.md)\   [**\**](system-servicemodel.md)\     [**\**](behaviors.md)\       [**\**](endpointbehaviors.md)\         [**\**](behavior-of-endpointbehaviors.md)\ -          **\** - -## Syntax - -```xml +          **\** + +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](behavior-of-endpointbehaviors.md)|Specifies an endpoint behavior.| - -## Remarks - - Use this behavior to instruct the channel listener to use a synchronous receive rather than the default, asynchronous. Windows Communication Foundation (WCF) issues a new thread to pump for each accepted channel. If there are a lot of channels, there is the possibility of running out of threads. - +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](behavior-of-endpointbehaviors.md)|Specifies an endpoint behavior.| + +## Remarks + + Use this behavior to instruct the channel listener to use a synchronous receive rather than the default, asynchronous. Windows Communication Foundation (WCF) issues a new thread to pump for each accepted channel. If there are a lot of channels, there is the possibility of running out of threads. + ## See also - diff --git a/docs/framework/configure-apps/file-schema/wcf/trackingprofile-of-wcf.md b/docs/framework/configure-apps/file-schema/wcf/trackingprofile-of-wcf.md index bc27ec7e6c89b..3dfd7ed5f9039 100644 --- a/docs/framework/configure-apps/file-schema/wcf/trackingprofile-of-wcf.md +++ b/docs/framework/configure-apps/file-schema/wcf/trackingprofile-of-wcf.md @@ -6,19 +6,19 @@ ms.assetid: 09b651c2-c0d2-4850-a101-b0e009a1dc3a --- # \ of WCF -Represents a configuration section for creating a subscription to workflow tracking records in a tracking participant. A tracking profile contains tracking queries that permit a tracking participant to subscribe to workflow events that are emitted when the state of a workflow instance changes at run time. The queries defined within the tracking profile section define the kinds of events that are returned by the subscription. - -For more information in workflow tracking and its configuration, see [Workflow Tracking and Tracing](../../../windows-workflow-foundation/workflow-tracking-and-tracing.md) and [Tracking Profiles](../../../windows-workflow-foundation/tracking-profiles.md). - +Represents a configuration section for creating a subscription to workflow tracking records in a tracking participant. A tracking profile contains tracking queries that permit a tracking participant to subscribe to workflow events that are emitted when the state of a workflow instance changes at runtime. The queries defined within the tracking profile section define the kinds of events that are returned by the subscription. + +For more information in workflow tracking and its configuration, see [Workflow Tracking and Tracing](../../../windows-workflow-foundation/workflow-tracking-and-tracing.md) and [Tracking Profiles](../../../windows-workflow-foundation/tracking-profiles.md). + [**\**](../configuration-element.md)\   [**\**](system-servicemodel.md)\     [**\**](tracking-of-wcf.md)\       **\**\ -        **\** - -## Syntax - -```xml +        **\** + +## Syntax + +```xml @@ -71,39 +71,39 @@ For more information in workflow tracking and its configuration, see [Workflow T -``` - -## Attributes and Elements - -The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|name|A string that specifies the name of the tracking profile.| - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](../windows-workflow-foundation/participants.md)|A configuration element that contains all queries for a specific workflow identified by the property.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](../windows-workflow-foundation/tracking.md)|Represents a configuration section for defining tracking settings for a workflow service.| - -## Remarks - - Tracking profiles contains tracking queries that permit a tracking participant to subscribe to workflow events that are emitted when the state of a workflow instance changes at run time. Depending on your monitoring requirements you may write a profile that is very coarse, which subscribes to a small set of high-level state changes on a workflow. Conversely, you may create a very specific profile whose resulting events are rich enough to reconstruct a detailed execution flow later. - +``` + +## Attributes and Elements + +The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|name|A string that specifies the name of the tracking profile.| + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](../windows-workflow-foundation/participants.md)|A configuration element that contains all queries for a specific workflow identified by the property.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](../windows-workflow-foundation/tracking.md)|Represents a configuration section for defining tracking settings for a workflow service.| + +## Remarks + + Tracking profiles contains tracking queries that permit a tracking participant to subscribe to workflow events that are emitted when the state of a workflow instance changes at runtime. Depending on your monitoring requirements you may write a profile that is very coarse, which subscribes to a small set of high-level state changes on a workflow. Conversely, you may create a very specific profile whose resulting events are rich enough to reconstruct a detailed execution flow later. + Tracking profiles are structured as declarative subscriptions for tracking records that allow you to query the workflow runtime for specific tracking records. There are a handful of query types that allow you subscribe to different classes of objects. For a complete list of queries, see [\](../windows-workflow-foundation/participants.md) and [Tracking Profiles](../../../windows-workflow-foundation/tracking-profiles.md). - -The following example shows a tracking profile in a configuration file that allows a tracking participant to subscribe to the `Started` and `Completed` workflow events. - -```xml + +The following example shows a tracking profile in a configuration file that allows a tracking participant to subscribe to the `Started` and `Completed` workflow events. + +```xml @@ -122,8 +122,8 @@ The following example shows a tracking profile in a configuration file that allo -``` - +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/wcf/udptransportsettings-of-udpannouncementendpoint.md b/docs/framework/configure-apps/file-schema/wcf/udptransportsettings-of-udpannouncementendpoint.md index 1f9702d268a0d..c2598a2f72e9b 100644 --- a/docs/framework/configure-apps/file-schema/wcf/udptransportsettings-of-udpannouncementendpoint.md +++ b/docs/framework/configure-apps/file-schema/wcf/udptransportsettings-of-udpannouncementendpoint.md @@ -6,17 +6,17 @@ ms.assetid: a7ddff1a-5eed-4bbc-8580-b95ef8890e1f --- # \ of \ -This configuration element exposes UDP transport settings for [\](udpannouncementendpoint.md). - +This configuration element exposes UDP transport settings for [\](udpannouncementendpoint.md). + [**\**](../configuration-element.md)\   [**\**](system-servicemodel.md)\     [**\**](standardendpoints.md)\       [**\**](udpannouncementendpoint.md)\ -        **\** +        **\** + +## Syntax -## Syntax - -```xml +```xml @@ -34,36 +34,36 @@ This configuration element exposes UDP transport settings for [\ -``` - -## Attributes and Elements +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|duplicateMessageHistoryLength|An integer that specifies the maximum number of message hashes used by the transport for identifying duplicate messages. Duplicate detection will be done at the TransportManager level. Setting this property to 0 disables duplicate detection.

This attribute allows system administrators or developers to turn off duplicate message detection algorithms. This may be desirable if you want to implement your own duplicate detection algorithm.

The default is 4112.| +|maxBufferPoolSize|An integer that specifies the maximum size of any buffer pools used by the transport.| +|maxMulticastRetransmitCount|An integer that specifies the maximum number of times the message should be retransmitted (in addition to the first send).

The default is 2.| +|maxPendingMessageCount|An integer that specifies the maximum number of messages that have been received but not yet removed from the InputQueue for an individual channel instance. If the InputQueue has hit its pending message count limit, the message will be dropped.

The default is 32.| +|maxReceivedMessageSize|An integer that specifies the maximum size for a message that can be processed by the binding.

The default value is 65507.| +|maxUnicastRetransmitCount|An integer that specifies the maximum number of times the message should be retransmitted (in addition to the first send). If the message is sent to a unicast address and a response message is received with a corresponding RelatesTo header, then retransmission may terminate early (before retransmitting the configured number of times).

The default value is 1.| +|multicastInterfaceId|A string that uniquely identifies the network adapter that should be used when sending and receiving multicast traffic on multi-homed machines. At runtime, the transport will use this attribute value to lookup the interface index, which is then used to set the `IP_MULTICAST_IF` and `IPV6_MULTICAST_IF` socket options. The same interface index will be used when joining a multicast group, if applicable.

The default value is `null`.| +|socketReceiveBufferSize|An integer that specifies the receive buffer size on the underlying WinSock socket.

A user of a receiving channel can use this attribute on the Binding to control how the system behaves when it receives data. For example, given an application that is consuming inbound WCF messages at the maximum threshold, using a higher value for this attribute would allow messages to stack up in the WinSock buffer while waiting for the application to be able to process them. Using a lower value in the same situation would result in messages getting dropped.This attribute exposes the underlying WinSock `SO_RCVBUF` socket option.This attribute value must be at least the size of `maxReceivedMessageSize`. Setting it to a value smaller than the `maxReceivedMessageSize` will result in runtime exception.

The default value is 65536.| +|timeToLive|An integer that specifies the number of network segment hops that a multicast packet can traverse. This attribute exposes the functionality associated with the `IP_MULTICAST_TTL` and `IP_TTL` socket options.

The default value is 1.| + +### Child Elements + + None. + +### Parent Elements - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|duplicateMessageHistoryLength|An integer that specifies the maximum number of message hashes used by the transport for identifying duplicate messages. Duplicate detection will be done at the TransportManager level. Setting this property to 0 disables duplicate detection.

This attribute allows system administrators or developers to turn off duplicate message detection algorithms. This may be desirable if you want to implement your own duplicate detection algorithm.

The default is 4112.| -|maxBufferPoolSize|An integer that specifies the maximum size of any buffer pools used by the transport.| -|maxMulticastRetransmitCount|An integer that specifies the maximum number of times the message should be retransmitted (in addition to the first send).

The default is 2.| -|maxPendingMessageCount|An integer that specifies the maximum number of messages that have been received but not yet removed from the InputQueue for an individual channel instance. If the InputQueue has hit its pending message count limit, the message will be dropped.

The default is 32.| -|maxReceivedMessageSize|An integer that specifies the maximum size for a message that can be processed by the binding.

The default value is 65507.| -|maxUnicastRetransmitCount|An integer that specifies the maximum number of times the message should be retransmitted (in addition to the first send). If the message is sent to a unicast address and a response message is received with a corresponding RelatesTo header, then retransmission may terminate early (before retransmitting the configured number of times).

The default value is 1.| -|multicastInterfaceId|A string that uniquely identifies the network adapter that should be used when sending and receiving multicast traffic on multi-homed machines. At run time, the transport will use this attribute value to lookup the interface index, which is then used to set the `IP_MULTICAST_IF` and `IPV6_MULTICAST_IF` socket options. The same interface index will be used when joining a multicast group, if applicable.

The default value is `null`.| -|socketReceiveBufferSize|An integer that specifies the receive buffer size on the underlying WinSock socket.

A user of a receiving channel can use this attribute on the Binding to control how the system behaves when it receives data. For example, given an application that is consuming inbound WCF messages at the maximum threshold, using a higher value for this attribute would allow messages to stack up in the WinSock buffer while waiting for the application to be able to process them. Using a lower value in the same situation would result in messages getting dropped.This attribute exposes the underlying WinSock `SO_RCVBUF` socket option.This attribute value must be at least the size of `maxReceivedMessageSize`. Setting it to a value smaller than the `maxReceivedMessageSize` will result in runtime exception.

The default value is 65536.| -|timeToLive|An integer that specifies the number of network segment hops that a multicast packet can traverse. This attribute exposes the functionality associated with the `IP_MULTICAST_TTL` and `IP_TTL` socket options.

The default value is 1.| - -### Child Elements +|Element|Description| +|-------------|-----------------| +|[\](udpannouncementendpoint.md)|A standard endpoint that has fixed announcement contract and UDP transport binding.| - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](udpannouncementendpoint.md)|A standard endpoint that has fixed announcement contract and UDP transport binding.| - ## See also - diff --git a/docs/framework/configure-apps/file-schema/wcf/udptransportsettings.md b/docs/framework/configure-apps/file-schema/wcf/udptransportsettings.md index 9de197bd8701f..2ca6514aec23f 100644 --- a/docs/framework/configure-apps/file-schema/wcf/udptransportsettings.md +++ b/docs/framework/configure-apps/file-schema/wcf/udptransportsettings.md @@ -6,17 +6,17 @@ ms.assetid: 842d92e9-6199-4ec5-b2d1-58533054e1f0 --- # \ -This configuration element exposes UDP transport settings for [\](udpdiscoveryendpoint.md). - +This configuration element exposes UDP transport settings for [\](udpdiscoveryendpoint.md). + [**\**](../configuration-element.md)\   [**\**](system-servicemodel.md)\     [**\**](standardendpoints.md)\       [**\**](udpdiscoveryendpoint.md)\ -        **\** - -## Syntax - -```xml +        **\** + +## Syntax + +```xml @@ -34,36 +34,36 @@ This configuration element exposes UDP transport settings for [\ -``` - -## Attributes and Elements +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|duplicateMessageHistoryLength|An integer that specifies the maximum number of message hashes used by the transport for identifying duplicate messages. Duplicate detection will be done at the TransportManager level. Setting this property to 0 disables duplicate detection.

This attribute allows system administrators or developers to turn off duplicate message detection algorithms. This may be desirable if you want to implement your own duplicate detection algorithm.

The default is 4112.| +|maxBufferPoolSize|An integer that specifies the maximum size of any buffer pools used by the transport.| +|maxMulticastRetransmitCount|An integer that specifies the maximum number of times the message should be retransmitted (in addition to the first send).

The default is 2.| +|maxPendingMessageCount|An integer that specifies the maximum number of messages that have been received but not yet removed from the InputQueue for an individual channel instance. If the InputQueue has hit its pending message count limit, the message will be dropped.

The default is 32.| +|maxReceivedMessageSize|An integer that specifies the maximum size for a message that can be processed by the binding.

The default value is 65507.| +|maxUnicastRetransmitCount|An integer that specifies the maximum number of times the message should be retransmitted (in addition to the first send). If the message is sent to a unicast address and a response message is received with a corresponding RelatesTo header, then retransmission may terminate early (before retransmitting the configured number of times).

The default value is 1.| +|multicastInterfaceId|A string that uniquely identifies the network adapter that should be used when sending and receiving multicast traffic on multi-homed machines. At runtime, the transport will use this attribute value to lookup the interface index, which is then used to set the `IP_MULTICAST_IF` and `IPV6_MULTICAST_IF` socket options. The same interface index will be used when joining a multicast group, if applicable.

The default value is `null`.| +|socketReceiveBufferSize|An integer that specifies the receive buffer size on the underlying WinSock socket.

A user of a receiving channel can use this attribute on the Binding to control how the system behaves when it receives data. For example, given an application that is consuming inbound WCF messages at the maximum threshold, using a higher value for this attribute would allow messages to stack up in the WinSock buffer while waiting for the application to be able to process them. Using a lower value in the same situation would result in messages getting dropped. This attribute exposes the underlying WinSock `SO_RCVBUF` socket option.This attribute value must be at least the size of `maxReceivedMessageSize`. Setting it to a value smaller than the `maxReceivedMessageSize` will result in a runtime exception.

The default value is 65536.| +|timeToLive|An integer that specifies the number of network segment hops that a multicast packet can traverse. This attribute exposes the functionality associated with the `IP_MULTICAST_TTL` and `IP_TTL` socket options.

The default value is 1.| + +### Child Elements + + None. + +### Parent Elements - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|duplicateMessageHistoryLength|An integer that specifies the maximum number of message hashes used by the transport for identifying duplicate messages. Duplicate detection will be done at the TransportManager level. Setting this property to 0 disables duplicate detection.

This attribute allows system administrators or developers to turn off duplicate message detection algorithms. This may be desirable if you want to implement your own duplicate detection algorithm.

The default is 4112.| -|maxBufferPoolSize|An integer that specifies the maximum size of any buffer pools used by the transport.| -|maxMulticastRetransmitCount|An integer that specifies the maximum number of times the message should be retransmitted (in addition to the first send).

The default is 2.| -|maxPendingMessageCount|An integer that specifies the maximum number of messages that have been received but not yet removed from the InputQueue for an individual channel instance. If the InputQueue has hit its pending message count limit, the message will be dropped.

The default is 32.| -|maxReceivedMessageSize|An integer that specifies the maximum size for a message that can be processed by the binding.

The default value is 65507.| -|maxUnicastRetransmitCount|An integer that specifies the maximum number of times the message should be retransmitted (in addition to the first send). If the message is sent to a unicast address and a response message is received with a corresponding RelatesTo header, then retransmission may terminate early (before retransmitting the configured number of times).

The default value is 1.| -|multicastInterfaceId|A string that uniquely identifies the network adapter that should be used when sending and receiving multicast traffic on multi-homed machines. At run time, the transport will use this attribute value to lookup the interface index, which is then used to set the `IP_MULTICAST_IF` and `IPV6_MULTICAST_IF` socket options. The same interface index will be used when joining a multicast group, if applicable.

The default value is `null`.| -|socketReceiveBufferSize|An integer that specifies the receive buffer size on the underlying WinSock socket.

A user of a receiving channel can use this attribute on the Binding to control how the system behaves when it receives data. For example, given an application that is consuming inbound WCF messages at the maximum threshold, using a higher value for this attribute would allow messages to stack up in the WinSock buffer while waiting for the application to be able to process them. Using a lower value in the same situation would result in messages getting dropped. This attribute exposes the underlying WinSock `SO_RCVBUF` socket option.This attribute value must be at least the size of `maxReceivedMessageSize`. Setting it to a value smaller than the `maxReceivedMessageSize` will result in a runtime exception.

The default value is 65536.| -|timeToLive|An integer that specifies the number of network segment hops that a multicast packet can traverse. This attribute exposes the functionality associated with the `IP_MULTICAST_TTL` and `IP_TTL` socket options.

The default value is 1.| - -### Child Elements +|Element|Description| +|-------------|-----------------| +|[\](udpdiscoveryendpoint.md)|A standard endpoint that has fixed discovery contract and UDP transport binding.| - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](udpdiscoveryendpoint.md)|A standard endpoint that has fixed discovery contract and UDP transport binding.| - ## See also - diff --git a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/trackingprofile.md b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/trackingprofile.md index 4e7bc5b8d777d..0416272da73ce 100644 --- a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/trackingprofile.md +++ b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/trackingprofile.md @@ -6,18 +6,18 @@ ms.assetid: 154830ff-ddd3-4397-a3b5-5b334907777f --- # \ -Represents a configuration section for creating a subscription to workflow tracking records in a tracking participant. A tracking profile contains tracking queries that permit a tracking participant to subscribe to workflow events that are emitted when the state of a workflow instance changes at run time. The queries defined within the tracking profile section define the kinds of events that are returned by the subscription. - - For more information in workflow tracking and its configuration, see [Workflow Tracking and Tracing](../../../windows-workflow-foundation/workflow-tracking-and-tracing.md) and [Tracking Profiles](../../../windows-workflow-foundation/tracking-profiles.md). - +Represents a configuration section for creating a subscription to workflow tracking records in a tracking participant. A tracking profile contains tracking queries that permit a tracking participant to subscribe to workflow events that are emitted when the state of a workflow instance changes at runtime. The queries defined within the tracking profile section define the kinds of events that are returned by the subscription. + + For more information in workflow tracking and its configuration, see [Workflow Tracking and Tracing](../../../windows-workflow-foundation/workflow-tracking-and-tracing.md) and [Tracking Profiles](../../../windows-workflow-foundation/tracking-profiles.md). + [**\**](../configuration-element.md)\   [**\**](system-servicemodel-of-workflow.md)\     [**\**](tracking.md)\ -      **\** - -## Syntax - -```xml +      **\** + +## Syntax + +```xml @@ -70,60 +70,60 @@ Represents a configuration section for creating a subscription to workflow track
-
-``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|name|A string that specifies the name of the tracking profile.| - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](participants.md)|A configuration element that contains all queries for a specific workflow identified by the property.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](tracking.md)|Represents a configuration section for defining tracking settings for a workflow service.| - -## Remarks - - Tracking profiles contains tracking queries that permit a tracking participant to subscribe to workflow events that are emitted when the state of a workflow instance changes at run time. Depending on your monitoring requirements you may write a profile that is very coarse, which subscribes to a small set of high-level state changes on a workflow. Conversely, you may create a very specific profile whose resulting events are rich enough to reconstruct a detailed execution flow later. - - Tracking profiles are structured as declarative subscriptions for tracking records that allow you to query the workflow runtime for specific tracking records. There are a handful of query types that allow you subscribe to different classes of objects. For a complete list of queries, see [\](participants.md) and [Tracking Profiles](../../../windows-workflow-foundation/tracking-profiles.md).. - - The following example shows a tracking profile in a configuration file that allows a tracking participant to subscribe to the `Started` and `Completed` workflow events. - -```xml - + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|name|A string that specifies the name of the tracking profile.| + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](participants.md)|A configuration element that contains all queries for a specific workflow identified by the property.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](tracking.md)|Represents a configuration section for defining tracking settings for a workflow service.| + +## Remarks + + Tracking profiles contains tracking queries that permit a tracking participant to subscribe to workflow events that are emitted when the state of a workflow instance changes at runtime. Depending on your monitoring requirements you may write a profile that is very coarse, which subscribes to a small set of high-level state changes on a workflow. Conversely, you may create a very specific profile whose resulting events are rich enough to reconstruct a detailed execution flow later. + + Tracking profiles are structured as declarative subscriptions for tracking records that allow you to query the workflow runtime for specific tracking records. There are a handful of query types that allow you subscribe to different classes of objects. For a complete list of queries, see [\](participants.md) and [Tracking Profiles](../../../windows-workflow-foundation/tracking-profiles.md).. + + The following example shows a tracking profile in a configuration file that allows a tracking participant to subscribe to the `Started` and `Completed` workflow events. + +```xml + - - - - - - - - - - - + + + + + + + + + + + - - - -``` - + + +
+``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/workflow.md b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/workflow.md index da7b778453441..2d86d63d6a5ac 100644 --- a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/workflow.md +++ b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/workflow.md @@ -6,19 +6,19 @@ ms.assetid: 560aa9b6-9cf3-460e-b798-f87d14b1d2de --- # \ -A configuration element that contains all queries for a specific workflow identified by the property. - - For more information in workflow tracking and its configuration, see [Workflow Tracking and Tracing](../../../windows-workflow-foundation/workflow-tracking-and-tracing.md) and [Tracking Profiles](../../../windows-workflow-foundation/tracking-profiles.md). - +A configuration element that contains all queries for a specific workflow identified by the property. + + For more information in workflow tracking and its configuration, see [Workflow Tracking and Tracing](../../../windows-workflow-foundation/workflow-tracking-and-tracing.md) and [Tracking Profiles](../../../windows-workflow-foundation/tracking-profiles.md). + [**\**](../configuration-element.md)\   [**\**](system-servicemodel-of-workflow.md)\     [**\**](tracking.md)\       [**\**](trackingprofile.md)\ -        **\** - -## Syntax - -```xml +        **\** + +## Syntax + +```xml @@ -71,68 +71,68 @@ A configuration element that contains all queries for a specific workflow identi - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|activityDefinitionId|A string that specifies the activity definition ID of the workflow being tracked.| - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](activityscheduledqueries.md)|Represents a collection of queries that are used to track an activity scheduled for execution by a parent activity. The query is necessary for a tracking participant to subscribe to activity scheduled records.| -|[\](activitystatequeries.md)|Represents a collection of queries that are used to track life cycle changes of the activities that make up a workflow instance. For example, you may want to keep track of every time the "Send E-Mail" activity completes within a workflow instance. This query is necessary for a tracking participant to subscribe to activity state record objects. The available states to subscribe to are specified in ActivityStates.| -|[\](bookmarkresumptionqueries.md)|Represents a collection of queries that are used to track resumption of a bookmark within a workflow instance. The query is necessary for a tracking participant to subscribe to bookmark resumption records.| -|[\](cancelrequestedqueries.md)|Represents a collection of queries that are used to track requests to cancel a child activity by the parent activity. The query is necessary for a tracking participant to subscribe to cancel request record objects.| -|[\](customtrackingqueries.md)|Represents a collection of queries that are used to track events that you define in your code activities. The query is necessary for a tracking participant to subscribe to custom tracking records.| -|[\](faultpropagationqueries.md)|Represents a collection of queries that are used to track the handling of faults that occur within an activity. This event occurs each time a FaultHandler processes a fault. You should use such query to track the handling of faults that occur within an activity. The query is necessary for a tracking participant to subscribe to fault propagation records.| -|[\](workflowinstancequeries.md)|Represents a collection of configuration elements that track workflow instance life cycle changes such as a started or completed event.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](trackingprofile.md)|Represents a configuration section for creating a subscription to workflow tracking records in a tracking participant. A tracking profile contains tracking queries that permit a tracking participant to subscribe to workflow events that are emitted when the state of a workflow instance changes at run time. The queries defined within the tracking profile section define the kinds of events that are returned by the subscription.| - -## Remarks - - Tracking profiles contains tracking queries that permit a tracking participant to subscribe to workflow events that are emitted when the state of a particular workflow instance changes at run time. The workflow instance being tracked is identified by this configuration element. - - Depending on your monitoring requirements you may write a profile that is very coarse, which subscribes to a small set of high-level state changes on a workflow. Conversely, you may create a very specific profile whose resulting events are rich enough to reconstruct a detailed execution flow later. - - Tracking profiles are structured as declarative subscriptions for tracking records that allow you to query the workflow runtime for specific tracking records. There are a handful of query types that allow you subscribe to different classes of tracking records. For a complete list of queries, see the child element list of this topic and [Tracking Profiles](../../../windows-workflow-foundation/tracking-profiles.md). - - The following example shows a tracking profile in a configuration file that allows a tracking participant to subscribe to the `Started` and `Completed` workflow events. - -```xml - + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|activityDefinitionId|A string that specifies the activity definition ID of the workflow being tracked.| + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](activityscheduledqueries.md)|Represents a collection of queries that are used to track an activity scheduled for execution by a parent activity. The query is necessary for a tracking participant to subscribe to activity scheduled records.| +|[\](activitystatequeries.md)|Represents a collection of queries that are used to track life cycle changes of the activities that make up a workflow instance. For example, you may want to keep track of every time the "Send E-Mail" activity completes within a workflow instance. This query is necessary for a tracking participant to subscribe to activity state record objects. The available states to subscribe to are specified in ActivityStates.| +|[\](bookmarkresumptionqueries.md)|Represents a collection of queries that are used to track resumption of a bookmark within a workflow instance. The query is necessary for a tracking participant to subscribe to bookmark resumption records.| +|[\](cancelrequestedqueries.md)|Represents a collection of queries that are used to track requests to cancel a child activity by the parent activity. The query is necessary for a tracking participant to subscribe to cancel request record objects.| +|[\](customtrackingqueries.md)|Represents a collection of queries that are used to track events that you define in your code activities. The query is necessary for a tracking participant to subscribe to custom tracking records.| +|[\](faultpropagationqueries.md)|Represents a collection of queries that are used to track the handling of faults that occur within an activity. This event occurs each time a FaultHandler processes a fault. You should use such query to track the handling of faults that occur within an activity. The query is necessary for a tracking participant to subscribe to fault propagation records.| +|[\](workflowinstancequeries.md)|Represents a collection of configuration elements that track workflow instance life cycle changes such as a started or completed event.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](trackingprofile.md)|Represents a configuration section for creating a subscription to workflow tracking records in a tracking participant. A tracking profile contains tracking queries that permit a tracking participant to subscribe to workflow events that are emitted when the state of a workflow instance changes at runtime. The queries defined within the tracking profile section define the kinds of events that are returned by the subscription.| + +## Remarks + + Tracking profiles contains tracking queries that permit a tracking participant to subscribe to workflow events that are emitted when the state of a particular workflow instance changes at runtime. The workflow instance being tracked is identified by this configuration element. + + Depending on your monitoring requirements you may write a profile that is very coarse, which subscribes to a small set of high-level state changes on a workflow. Conversely, you may create a very specific profile whose resulting events are rich enough to reconstruct a detailed execution flow later. + + Tracking profiles are structured as declarative subscriptions for tracking records that allow you to query the workflow runtime for specific tracking records. There are a handful of query types that allow you subscribe to different classes of tracking records. For a complete list of queries, see the child element list of this topic and [Tracking Profiles](../../../windows-workflow-foundation/tracking-profiles.md). + + The following example shows a tracking profile in a configuration file that allows a tracking participant to subscribe to the `Started` and `Completed` workflow events. + +```xml + - - - - - - - - - - - + + + + + + + + + + + - - - -``` - + + +
+``` + ## See also - diff --git a/docs/framework/data/adonet/association-set-end.md b/docs/framework/data/adonet/association-set-end.md index 0aa6a663bdeb0..82ff11ce9d48e 100644 --- a/docs/framework/data/adonet/association-set-end.md +++ b/docs/framework/data/adonet/association-set-end.md @@ -6,28 +6,28 @@ ms.assetid: fe4bf1d3-047a-4a37-98c5-a66e70811346 --- # association set end -An *association set end* identifies the [entity type](entity-type.md) and the [entity set](entity-set.md) at the end of an [association set](association-set.md). Association set ends are defined as part of an association set; an association set must have exactly two association set ends. - - An association set end definition contains the following information: - -- One of the entity types involved in the association set. (Required) - -- The entity set for the entity type involved in the association set. (Required) - -## Example - - The diagram below shows a conceptual model with two associations: `WrittenBy` and `PublishedBy`. - - ![Example model with three entity types](./media/association-set-end/example-model-three-entity-types.gif) - - The following diagram shows an association set (`PublishedBy`) and two entity sets (`Books` and `Publishers`) based on the conceptual model shown above. The association set ends are the `Books` and `Publishers` entity sets. Bi in the `Books` entity set represents an instance of the `Book` entity type at run time. Similarly, Pj represents a `Publisher` instance in the `Publishers` entity set. BiPj represents an instance of the `PublishedBy` association in the `PublishedBy` association set. - - ![Screenshot that shows a Sets example.](./media/association-set-end/sets-example-association.gif) - - The [ADO.NET Entity Framework](./ef/index.md) uses a DSL called conceptual schema definition language ([CSDL](/ef/ef6/modeling/designer/advanced/edmx/csdl-spec)) to define conceptual models. The following CSDL defines an entity container with one association set for each association in the diagram above. Note that association set ends are defined as part of each association set definition. - - [!code-xml[EDM_Example_Model#EntityContainerExample](../../../../samples/snippets/xml/VS_Snippets_Data/edm_example_model/xml/books.edmx#entitycontainerexample)] - +An *association set end* identifies the [entity type](entity-type.md) and the [entity set](entity-set.md) at the end of an [association set](association-set.md). Association set ends are defined as part of an association set; an association set must have exactly two association set ends. + + An association set end definition contains the following information: + +- One of the entity types involved in the association set. (Required) + +- The entity set for the entity type involved in the association set. (Required) + +## Example + + The diagram below shows a conceptual model with two associations: `WrittenBy` and `PublishedBy`. + + ![Example model with three entity types](./media/association-set-end/example-model-three-entity-types.gif) + + The following diagram shows an association set (`PublishedBy`) and two entity sets (`Books` and `Publishers`) based on the conceptual model shown above. The association set ends are the `Books` and `Publishers` entity sets. Bi in the `Books` entity set represents an instance of the `Book` entity type at runtime. Similarly, Pj represents a `Publisher` instance in the `Publishers` entity set. BiPj represents an instance of the `PublishedBy` association in the `PublishedBy` association set. + + ![Screenshot that shows a Sets example.](./media/association-set-end/sets-example-association.gif) + + The [ADO.NET Entity Framework](./ef/index.md) uses a DSL called conceptual schema definition language ([CSDL](/ef/ef6/modeling/designer/advanced/edmx/csdl-spec)) to define conceptual models. The following CSDL defines an entity container with one association set for each association in the diagram above. Note that association set ends are defined as part of each association set definition. + + [!code-xml[EDM_Example_Model#EntityContainerExample](../../../../samples/snippets/xml/VS_Snippets_Data/edm_example_model/xml/books.edmx#entitycontainerexample)] + ## See also - [Entity Data Model Key Concepts](entity-data-model-key-concepts.md) diff --git a/docs/framework/data/adonet/association-set.md b/docs/framework/data/adonet/association-set.md index beb5828ad4196..59e3701a96082 100644 --- a/docs/framework/data/adonet/association-set.md +++ b/docs/framework/data/adonet/association-set.md @@ -6,36 +6,36 @@ ms.assetid: a65247b6-ce59-44ea-974c-14ae20a7995f --- # association set -An *association set* is a logical container for [association](association-type.md) instances of the same type. An association set is not a data modeling construct; that is, it does not describe the structure of data or relationships. Instead, an association set provides a construct for a hosting or storage environment (such as the common language runtime or a SQL Server database) to group association instances so that they can be mapped to a data store. - - An association set is defined within an [entity container](entity-container.md), which is a logical grouping of [entity sets](entity-set.md) and association sets. - - A definition for an association set contains the following information: - -- The association set name. (Required) - -- The association of which it will contain instances. (Required) - -- Two [association set ends](association-set-end.md). - -## Example - - The diagram below shows a conceptual model with two associations: `PublishedBy`, and `WrittenBy`. Although information about association sets is not conveyed in the diagram, the next diagram shows an example of association sets and entity sets based on this model. - - ![Example model with three entity types](./media/association-set/example-model-three-entity-types.gif) - - The following example shows an association set (`PublishedBy`) and two entity sets (`Books` and `Publishers`) based on the conceptual model shown above. Bi in the `Books` entity set represents an instance of the `Book` entity type at run time. Similarly, Pj represents a `Publisher` instance in the `Publishers` entity set. BiPj represents an instance of the `PublishedBy` association in the `PublishedBy` association set. - - ![Screenshot that shows a Sets example.](./media/association-set/sets-example-association.gif) - - The [ADO.NET Entity Framework](./ef/index.md) uses a domain-specific language (DSL) called conceptual schema definition language ([CSDL](/ef/ef6/modeling/designer/advanced/edmx/csdl-spec)) to define conceptual models. The following CSDL defines an entity container with one association set for each association in the diagram above. Note that the name and association for each association set are defined using XML attributes. - - [!code-xml[EDM_Example_Model#EntityContainerExample](../../../../samples/snippets/xml/VS_Snippets_Data/edm_example_model/xml/books.edmx#entitycontainerexample)] - - It is possible to define multiple association sets per association, as long as no two association sets share an [association set end](association-set-end.md). The following CSDL defines an entity container with two association sets for the `WrittenBy` association. Notice that multiple entity sets have been defined for the `Book` and `Author` entity types and that no association set shares an association set end. - - [!code-xml[EDM_Example_Model#MultipleAssociationSets](../../../../samples/snippets/xml/VS_Snippets_Data/edm_example_model/xml/books3.edmx#multipleassociationsets)] - +An *association set* is a logical container for [association](association-type.md) instances of the same type. An association set is not a data modeling construct; that is, it does not describe the structure of data or relationships. Instead, an association set provides a construct for a hosting or storage environment (such as the common language runtime or a SQL Server database) to group association instances so that they can be mapped to a data store. + + An association set is defined within an [entity container](entity-container.md), which is a logical grouping of [entity sets](entity-set.md) and association sets. + + A definition for an association set contains the following information: + +- The association set name. (Required) + +- The association of which it will contain instances. (Required) + +- Two [association set ends](association-set-end.md). + +## Example + + The diagram below shows a conceptual model with two associations: `PublishedBy`, and `WrittenBy`. Although information about association sets is not conveyed in the diagram, the next diagram shows an example of association sets and entity sets based on this model. + + ![Example model with three entity types](./media/association-set/example-model-three-entity-types.gif) + + The following example shows an association set (`PublishedBy`) and two entity sets (`Books` and `Publishers`) based on the conceptual model shown above. Bi in the `Books` entity set represents an instance of the `Book` entity type at runtime. Similarly, Pj represents a `Publisher` instance in the `Publishers` entity set. BiPj represents an instance of the `PublishedBy` association in the `PublishedBy` association set. + + ![Screenshot that shows a Sets example.](./media/association-set/sets-example-association.gif) + + The [ADO.NET Entity Framework](./ef/index.md) uses a domain-specific language (DSL) called conceptual schema definition language ([CSDL](/ef/ef6/modeling/designer/advanced/edmx/csdl-spec)) to define conceptual models. The following CSDL defines an entity container with one association set for each association in the diagram above. Note that the name and association for each association set are defined using XML attributes. + + [!code-xml[EDM_Example_Model#EntityContainerExample](../../../../samples/snippets/xml/VS_Snippets_Data/edm_example_model/xml/books.edmx#entitycontainerexample)] + + It is possible to define multiple association sets per association, as long as no two association sets share an [association set end](association-set-end.md). The following CSDL defines an entity container with two association sets for the `WrittenBy` association. Notice that multiple entity sets have been defined for the `Book` and `Author` entity types and that no association set shares an association set end. + + [!code-xml[EDM_Example_Model#MultipleAssociationSets](../../../../samples/snippets/xml/VS_Snippets_Data/edm_example_model/xml/books3.edmx#multipleassociationsets)] + ## See also - [Entity Data Model Key Concepts](entity-data-model-key-concepts.md) diff --git a/docs/framework/data/adonet/code-access-security.md b/docs/framework/data/adonet/code-access-security.md index e56da94ad3ce7..6571c77f98af5 100644 --- a/docs/framework/data/adonet/code-access-security.md +++ b/docs/framework/data/adonet/code-access-security.md @@ -41,7 +41,7 @@ To determine whether code is authorized to access a resource or perform an opera Implementing both role-based security and code-accessed security (CAS) enhances overall security for your application. Role-based security can be based on a Windows account or a custom identity, making information about the security principal available to the current thread. In addition, applications are often required to provide access to data or resources based on credentials supplied by the user. Typically, such applications check the role of a user and provide access to resources based on those roles. - Role-based security enables a component to identify current users and their associated roles at run time. This information is then mapped using a CAS policy to determine the set of permissions granted at run time. For a specified application domain, the host can change the default role-based security policy and set a default security principal that represents a user and the roles associated with that user. + Role-based security enables a component to identify current users and their associated roles at runtime. This information is then mapped using a CAS policy to determine the set of permissions granted at runtime. For a specified application domain, the host can change the default role-based security policy and set a default security principal that represents a user and the roles associated with that user. The CLR uses permissions to implement its mechanism for enforcing restrictions on managed code. Role-based security permissions provide a mechanism for discovering whether a user (or the agent acting on the user's behalf) has a particular identity or is a member of a specified role. For more information, see [Security Permissions](/previous-versions/dotnet/netframework-4.0/5ba4k1c5(v=vs.100)). diff --git a/docs/framework/data/adonet/connection-string-builders.md b/docs/framework/data/adonet/connection-string-builders.md index 9685c8f0f5e85..7f351bcc4b9c0 100644 --- a/docs/framework/data/adonet/connection-string-builders.md +++ b/docs/framework/data/adonet/connection-string-builders.md @@ -8,7 +8,7 @@ dev_langs: --- # Connection string builders -In early versions of ADO.NET, compile-time checking of connection strings with concatenated string values did not occur, so that at run time, an incorrect keyword generated an . Each of the .NET Framework data providers supported different syntax for connection string keywords, which made constructing valid connection strings difficult if done manually. To address this problem, ADO.NET 2.0 introduced new connection string builders for each .NET Framework data provider. Each data provider includes a strongly typed connection string builder class that inherits from . The following table lists the .NET Framework data providers and their associated connection string builder classes. +In early versions of ADO.NET, compile-time checking of connection strings with concatenated string values did not occur, so that at runtime, an incorrect keyword generated an . Each of the .NET Framework data providers supported different syntax for connection string keywords, which made constructing valid connection strings difficult if done manually. To address this problem, ADO.NET 2.0 introduced new connection string builders for each .NET Framework data provider. Each data provider includes a strongly typed connection string builder class that inherits from . The following table lists the .NET Framework data providers and their associated connection string builder classes. | Provider | ConnectionStringBuilder class | |---------------------------------|--------------------------------------------------------------------------------------------| @@ -53,9 +53,9 @@ initial catalog="AdventureWorks;NewValue=Bad" ## Build connection strings from configuration files - If certain elements of a connection string are known beforehand, they can be stored in a configuration file and retrieved at run time to construct a complete connection string. For example, the name of the database might be known in advance, but not the name of the server. + If certain elements of a connection string are known beforehand, they can be stored in a configuration file and retrieved at runtime to construct a complete connection string. For example, the name of the database might be known in advance, but not the name of the server. - One of the overloaded constructors for a connection string builder takes a as an argument, which enables you to supply a partial connection string that can then be completed from user input. The partial connection string can be stored in a configuration file and retrieved at run time. + One of the overloaded constructors for a connection string builder takes a as an argument, which enables you to supply a partial connection string that can then be completed from user input. The partial connection string can be stored in a configuration file and retrieved at runtime. > [!NOTE] > The namespace allows programmatic access to configuration files that use the for web apps and the for Windows applications. For more information about working with connection strings and configuration files, see [Connection Strings and Configuration Files](connection-strings-and-configuration-files.md). diff --git a/docs/framework/data/adonet/connection-string-syntax.md b/docs/framework/data/adonet/connection-string-syntax.md index 57290b31b4f87..927689f7aef8c 100644 --- a/docs/framework/data/adonet/connection-string-syntax.md +++ b/docs/framework/data/adonet/connection-string-syntax.md @@ -23,7 +23,7 @@ Each .NET Framework data provider has a `Connection` object that inherits from < - - - The connection string builders allow you to construct syntactically valid connection strings at run time, so you do not have to manually concatenate connection string values in your code. For more information, see [Connection String Builders](connection-string-builders.md). + The connection string builders allow you to construct syntactically valid connection strings at runtime, so you do not have to manually concatenate connection string values in your code. For more information, see [Connection String Builders](connection-string-builders.md). ## Windows authentication @@ -131,7 +131,7 @@ You can also set the property of a allows you to get or set a connection string for an OLE DB data source, such as Microsoft Access. You can also create an `OleDb` connection string at run time by using the class. + The property of a allows you to get or set a connection string for an OLE DB data source, such as Microsoft Access. You can also create an `OleDb` connection string at runtime by using the class. ### OleDb connection string syntax diff --git a/docs/framework/data/adonet/connection-strings-and-configuration-files.md b/docs/framework/data/adonet/connection-strings-and-configuration-files.md index 253a5ff92c5eb..c781dd043ffe6 100644 --- a/docs/framework/data/adonet/connection-strings-and-configuration-files.md +++ b/docs/framework/data/adonet/connection-strings-and-configuration-files.md @@ -21,7 +21,7 @@ Embedding connection strings in your application's code can lead to security vul Connection strings can be stored as key/value pairs in the `connectionStrings` section of the `configuration` element of an application configuration file. Child elements include **add**, **clear**, and **remove**. - The following configuration file fragment demonstrates the schema and syntax for storing a connection string. The `name` attribute is a name that you provide to uniquely identify a connection string so that it can be retrieved at run time. The `providerName` is the invariant name of the .NET Framework data provider, which is registered in the machine.config file. + The following configuration file fragment demonstrates the schema and syntax for storing a connection string. The `name` attribute is a name that you provide to uniquely identify a connection string so that it can be retrieved at runtime. The `providerName` is the invariant name of the .NET Framework data provider, which is registered in the machine.config file. ```xml @@ -36,11 +36,11 @@ Embedding connection strings in your application's code can lead to security vul ``` > [!NOTE] -> You can save part of a connection string in a configuration file and use the class to complete it at run time. This is useful in scenarios where you do not know elements of the connection string ahead of time, or when you don't want to save sensitive information in a configuration file. For more information, see [Connection String Builders](connection-string-builders.md). +> You can save part of a connection string in a configuration file and use the class to complete it at runtime. This is useful in scenarios where you do not know elements of the connection string ahead of time, or when you don't want to save sensitive information in a configuration file. For more information, see [Connection String Builders](connection-string-builders.md). ### Use External Configuration Files - External configuration files are separate files that contain a fragment of a configuration file consisting of a single section. The external configuration file is then referenced by the main configuration file. Storing the `connectionStrings` section in a physically separate file is useful in situations where connection strings might be edited after the application is deployed. For example, the standard ASP.NET behavior is to restart an application domain when configuration files are modified, which results in state information being lost. However, modifying an external configuration file does not cause an application restart. External configuration files are not limited to ASP.NET; they can also be used by Windows applications. In addition, file access security and permissions can be used to restrict access to external configuration files. Working with external configuration files at run time is transparent, and requires no special coding. + External configuration files are separate files that contain a fragment of a configuration file consisting of a single section. The external configuration file is then referenced by the main configuration file. Storing the `connectionStrings` section in a physically separate file is useful in situations where connection strings might be edited after the application is deployed. For example, the standard ASP.NET behavior is to restart an application domain when configuration files are modified, which results in state information being lost. However, modifying an external configuration file does not cause an application restart. External configuration files are not limited to ASP.NET; they can also be used by Windows applications. In addition, file access security and permissions can be used to restrict access to external configuration files. Working with external configuration files at runtime is transparent, and requires no special coding. To store connection strings in an external configuration file, create a separate file that contains only the `connectionStrings` section. Do not include any additional elements, sections, or attributes. This example shows the syntax for an external configuration file. @@ -63,7 +63,7 @@ Embedding connection strings in your application's code can lead to security vul ## Retrieve Connection Strings at Run Time -.NET Framework 2.0 introduced new classes in the namespace to simplify retrieving connection strings from configuration files at run time. You can programmatically retrieve a connection string by name or by provider name. +.NET Framework 2.0 introduced new classes in the namespace to simplify retrieving connection strings from configuration files at runtime. You can programmatically retrieve a connection string by name or by provider name. > [!NOTE] > The **machine.config** file also contains a `connectionStrings` section, which contains connection strings used by Visual Studio. When retrieving connection strings by provider name from the **app.config** file in a Windows application, the connection strings in **machine.config** get loaded first, and then the entries from **app.config**. Adding `clear` immediately after the `connectionStrings` element removes all inherited references from the data structure in memory, so that only the connection strings defined in the local **app.config** file are considered. @@ -73,7 +73,7 @@ Embedding connection strings in your application's code can lead to security vul Starting with .NET Framework 2.0, is used when working with configuration files on the local computer, replacing the deprecated class. is used to work with ASP.NET configuration files. It is designed to work with configuration files on a Web server, and allows programmatic access to configuration file sections such as **system.web**. > [!NOTE] -> Accessing configuration files at run time requires granting permissions to the caller; the required permissions depend on the type of application, configuration file, and location. For more information, see for ASP.NET applications, and for Windows applications. +> Accessing configuration files at runtime requires granting permissions to the caller; the required permissions depend on the type of application, configuration file, and location. For more information, see for ASP.NET applications, and for Windows applications. You can use the to retrieve connection strings from application configuration files. It contains a collection of objects, each of which represents a single entry in the `connectionStrings` section. Its properties map to connection string attributes, allowing you to retrieve a connection string by specifying the name or the provider name. @@ -123,7 +123,7 @@ Embedding connection strings in your application's code can lead to security vul ``` - When the encrypted connection string is retrieved at run time, .NET Framework uses the specified provider to decrypt the `CipherValue` and make it available to your application. You do not need to write any additional code to manage the decryption process. + When the encrypted connection string is retrieved at runtime, .NET Framework uses the specified provider to decrypt the `CipherValue` and make it available to your application. You do not need to write any additional code to manage the decryption process. ### Protected Configuration Providers diff --git a/docs/framework/data/adonet/connection-strings.md b/docs/framework/data/adonet/connection-strings.md index db7a0f78d9ae0..3b85ba85756d0 100644 --- a/docs/framework/data/adonet/connection-strings.md +++ b/docs/framework/data/adonet/connection-strings.md @@ -53,14 +53,14 @@ All connection strings share the same basic syntax described previously. The set Typing mistakes can cause errors. For example, `Integrated Security=true` is valid, but `IntegratedSecurity=true` causes an error. -Connection strings constructed manually at run time from unvalidated user input are vulnerable to string-injection attacks and jeopardize security at the data source. To address these problems, *ADO.NET* 2.0 introduced [connection string builders](connection-string-builders.md) for each *.NET Framework* data provider. These connection string builders expose parameters as strongly typed properties and make it possible to validate the connection string before it's sent to the data source. +Connection strings constructed manually at runtime from unvalidated user input are vulnerable to string-injection attacks and jeopardize security at the data source. To address these problems, *ADO.NET* 2.0 introduced [connection string builders](connection-string-builders.md) for each *.NET Framework* data provider. These connection string builders expose parameters as strongly typed properties and make it possible to validate the connection string before it's sent to the data source. [!INCLUDE [managed-identities](../../../includes/managed-identities.md)] ## In this section [Connection String Builders](connection-string-builders.md)\ -Demonstrates how to use the `ConnectionStringBuilder` classes to construct valid connection strings at run time. +Demonstrates how to use the `ConnectionStringBuilder` classes to construct valid connection strings at runtime. [Connection Strings and Configuration Files](connection-strings-and-configuration-files.md)\ Demonstrates how to store and retrieve connection strings in configuration files. diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/navigating-datarelations.md b/docs/framework/data/adonet/dataset-datatable-dataview/navigating-datarelations.md index 6867a447c0510..9409f0826f9e1 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/navigating-datarelations.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/navigating-datarelations.md @@ -22,7 +22,7 @@ One of the primary functions of a is to allow na Notice that when the `DataRelation` is created for the `Customers` and `Orders` tables, no value is specified for the `createConstraints` flag (the default is **true**). This assumes that all the rows in the `Orders` table have a `CustomerID` value that exists in the parent `Customers` table. If a `CustomerID` exists in the `Orders` table that does not exist in the `Customers` table, a causes an exception to be thrown. - When the child column might contain values that the parent column does not contain, set the `createConstraints` flag to `false` when adding the **DataRelation**. In the example, the `createConstraints` flag is set to `false` for the `DataRelation` between the `Orders` table and the `OrderDetails` table. This enables the application to return all the records from the `OrderDetails` table and only a subset of records from the `Orders` table without generating a run-time exception. The expanded sample generates output in the following format. + When the child column might contain values that the parent column does not contain, set the `createConstraints` flag to `false` when adding the **DataRelation**. In the example, the `createConstraints` flag is set to `false` for the `DataRelation` between the `Orders` table and the `OrderDetails` table. This enables the application to return all the records from the `OrderDetails` table and only a subset of records from the `Orders` table without generating a runtime exception. The expanded sample generates output in the following format. ```output Customer ID: NORTS diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/typed-datasets.md b/docs/framework/data/adonet/dataset-datatable-dataview/typed-datasets.md index 1e9e8131d5fef..89a82d2a9037f 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/typed-datasets.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/typed-datasets.md @@ -10,7 +10,7 @@ Along with late bound access to values through weakly typed variables, the object for the underlying provider. This value is constant.

When the `Name` keyword is not included in an entity connection string, a non-empty value for the `Provider` keyword is required. This keyword is mutually exclusive with the `Name` keyword.| -|`Provider Connection String`|Optional. Specifies the provider-specific connection string that is passed to the underlying data source. This connection string contains valid keyword/value pairs for the data provider. An invalid `Provider Connection String` will cause a run-time error when it is evaluated by the data source.

This keyword is mutually exclusive with the `Name` keyword.

Make sure to escape the value according to the general syntax of [ADO.NET connection strings](../connection-strings.md). Consider for example the following connection string: `Server=serverName; User ID = userID`. It must be escaped because it contains a semicolon. Since it does not contain double quotation marks, they may be used for escaping:

`Provider Connection String ="Server=serverName; User ID = userID";`| +|`Provider Connection String`|Optional. Specifies the provider-specific connection string that is passed to the underlying data source. This connection string contains valid keyword/value pairs for the data provider. An invalid `Provider Connection String` will cause a runtime error when it is evaluated by the data source.

This keyword is mutually exclusive with the `Name` keyword.

Make sure to escape the value according to the general syntax of [ADO.NET connection strings](../connection-strings.md). Consider for example the following connection string: `Server=serverName; User ID = userID`. It must be escaped because it contains a semicolon. Since it does not contain double quotation marks, they may be used for escaping:

`Provider Connection String ="Server=serverName; User ID = userID";`| |`Metadata`|Required if the `Name` keyword is not specified. A pipe-delimited list of directories, files, and resource locations in which to look for metadata and mapping information. The following is an example:

`Metadata=`

`c:\model | c:\model\sql\mapping.msl;`

Blank spaces on each side of the pipe separator are ignored.

This keyword is mutually exclusive with the `Name` keyword.| |`Name`|The application can optionally specify the connection name in an application configuration file that provides the required keyword/value connection string values. In this case, you cannot supply them directly in the connection string. The `Name` keyword is not allowed in a configuration file.

When the `Name` keyword is not included in the connection string, a non-empty values for Provider keyword is required.

This keyword is mutually exclusive with all the other connection string keywords.| diff --git a/docs/framework/data/adonet/ef/language-reference/comparison-expressions.md b/docs/framework/data/adonet/ef/language-reference/comparison-expressions.md index c02c5b927979f..04994d4990756 100644 --- a/docs/framework/data/adonet/ef/language-reference/comparison-expressions.md +++ b/docs/framework/data/adonet/ef/language-reference/comparison-expressions.md @@ -2,53 +2,53 @@ description: "Learn more about: Comparison Expressions" title: "Comparison Expressions" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: ec7637a9-01d5-4a95-8bb0-478311cd263b --- # Comparison Expressions -A comparison expression checks whether a constant value, property value, or method result is equal, not equal, greater than, or less than another value. If a particular comparison is not valid for LINQ to Entities, an exception will be thrown. All comparisons, both implicit and explicit, require that all components are comparable in the data source. Comparison expressions are frequently used in `Where` clauses for restricting the query results. - - The following example in query expression syntax shows a query that returns results where the sales order number is equal to "SO43663": - +A comparison expression checks whether a constant value, property value, or method result is equal, not equal, greater than, or less than another value. If a particular comparison is not valid for LINQ to Entities, an exception will be thrown. All comparisons, both implicit and explicit, require that all components are comparable in the data source. Comparison expressions are frequently used in `Where` clauses for restricting the query results. + + The following example in query expression syntax shows a query that returns results where the sales order number is equal to "SO43663": + [!code-csharp[DP L2E Conceptual Examples#RestrictionExpression](../../../../../../samples/snippets/csharp/VS_Snippets_Data/DP L2E Conceptual Examples/CS/Program.cs#restrictionexpression)] - [!code-vb[DP L2E Conceptual Examples#RestrictionExpression](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#restrictionexpression)] - - The following example in method-based query syntax shows a query that returns results where the sales order number is equal to "SO43663": - + [!code-vb[DP L2E Conceptual Examples#RestrictionExpression](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#restrictionexpression)] + + The following example in method-based query syntax shows a query that returns results where the sales order number is equal to "SO43663": + [!code-csharp[DP L2E Conceptual Examples#RestrictionExpression_MQ](../../../../../../samples/snippets/csharp/VS_Snippets_Data/DP L2E Conceptual Examples/CS/Program.cs#restrictionexpression_mq)] - [!code-vb[DP L2E Conceptual Examples#RestrictionExpression_MQ](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#restrictionexpression_mq)] - - The following example in query expression syntax shows a query that returns sales order information where the ship date is equal to July 8, 2001: - + [!code-vb[DP L2E Conceptual Examples#RestrictionExpression_MQ](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#restrictionexpression_mq)] + + The following example in query expression syntax shows a query that returns sales order information where the ship date is equal to July 8, 2001: + [!code-csharp[DP L2E Conceptual Examples#DateTimeComparison](../../../../../../samples/snippets/csharp/VS_Snippets_Data/DP L2E Conceptual Examples/CS/Program.cs#datetimecomparison)] - [!code-vb[DP L2E Conceptual Examples#DateTimeComparison](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#datetimecomparison)] - - The following example in method-based query syntax shows a query that returns sales order information where the ship date is equal to July 8, 2001: - + [!code-vb[DP L2E Conceptual Examples#DateTimeComparison](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#datetimecomparison)] + + The following example in method-based query syntax shows a query that returns sales order information where the ship date is equal to July 8, 2001: + [!code-csharp[DP L2E Conceptual Examples#DateTimeComparison_MQ](../../../../../../samples/snippets/csharp/VS_Snippets_Data/DP L2E Conceptual Examples/CS/Program.cs#datetimecomparison_mq)] - [!code-vb[DP L2E Conceptual Examples#DateTimeComparison_MQ](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#datetimecomparison_mq)] - - Expressions that yield a constant are converted at the server, and no attempt to do local evaluation is performed. The following example uses an expression in the `Where` clause that yields a constant. - + [!code-vb[DP L2E Conceptual Examples#DateTimeComparison_MQ](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#datetimecomparison_mq)] + + Expressions that yield a constant are converted at the server, and no attempt to do local evaluation is performed. The following example uses an expression in the `Where` clause that yields a constant. + [!code-csharp[DP L2E Conceptual Examples#ConstantExpression](../../../../../../samples/snippets/csharp/VS_Snippets_Data/DP L2E Conceptual Examples/CS/Program.cs#constantexpression)] - [!code-vb[DP L2E Conceptual Examples#ConstantExpression](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#constantexpression)] - - LINQ to Entities does not support using a user class as a constant. However, a property reference on a user class is considered a constant, and will be converted to a command tree constant expression and executed on the data source. - + [!code-vb[DP L2E Conceptual Examples#ConstantExpression](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#constantexpression)] + + LINQ to Entities does not support using a user class as a constant. However, a property reference on a user class is considered a constant, and will be converted to a command tree constant expression and executed on the data source. + [!code-csharp[DP L2E Conceptual Examples#MyClass](../../../../../../samples/snippets/csharp/VS_Snippets_Data/DP L2E Conceptual Examples/CS/Program.cs#myclass)] - [!code-vb[DP L2E Conceptual Examples#MyClass](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#myclass)] - + [!code-vb[DP L2E Conceptual Examples#MyClass](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#myclass)] + [!code-csharp[DP L2E Conceptual Examples#PropertyAsConstant](../../../../../../samples/snippets/csharp/VS_Snippets_Data/DP L2E Conceptual Examples/CS/Program.cs#propertyasconstant)] - [!code-vb[DP L2E Conceptual Examples#PropertyAsConstant](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#propertyasconstant)] - - Methods that return a constant expression are not supported. The following example contains a method in the `Where` clause that returns a constant. This example will throw an exception at run time. - + [!code-vb[DP L2E Conceptual Examples#PropertyAsConstant](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#propertyasconstant)] + + Methods that return a constant expression are not supported. The following example contains a method in the `Where` clause that returns a constant. This example will throw an exception at runtime. + [!code-csharp[DP L2E Conceptual Examples#MethodAsConstantFails](../../../../../../samples/snippets/csharp/VS_Snippets_Data/DP L2E Conceptual Examples/CS/Program.cs#methodasconstantfails)] - [!code-vb[DP L2E Conceptual Examples#MethodAsConstantFails](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#methodasconstantfails)] - + [!code-vb[DP L2E Conceptual Examples#MethodAsConstantFails](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#methodasconstantfails)] + ## See also - [Expressions in LINQ to Entities Queries](expressions-in-linq-to-entities-queries.md) diff --git a/docs/framework/data/adonet/ef/language-reference/compiled-queries-linq-to-entities.md b/docs/framework/data/adonet/ef/language-reference/compiled-queries-linq-to-entities.md index fd05bf0c610db..0000d335a58ba 100644 --- a/docs/framework/data/adonet/ef/language-reference/compiled-queries-linq-to-entities.md +++ b/docs/framework/data/adonet/ef/language-reference/compiled-queries-linq-to-entities.md @@ -2,75 +2,75 @@ description: "Learn more about: Compiled queries (LINQ to Entities)" title: "Compiled Queries (LINQ to Entities)" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 8025ba1d-29c7-4407-841b-d5a3bed40b7a --- # Compiled queries (LINQ to Entities) -When you have an application that executes structurally similar queries many times in the Entity Framework, you can frequently increase performance by compiling the query one time and executing it several times with different parameters. For example, an application might have to retrieve all the customers in a particular city; the city is specified at run time by the user in a form. LINQ to Entities supports using compiled queries for this purpose. - - Starting with .NET Framework 4.5, LINQ queries are cached automatically. However, you can still use compiled LINQ queries to reduce this cost in later executions and compiled queries can be more efficient than LINQ queries that are automatically cached. LINQ to Entities queries that apply the `Enumerable.Contains` operator to in-memory collections are not automatically cached. Also, parameterizing in-memory collections in compiled LINQ queries is not allowed. - +When you have an application that executes structurally similar queries many times in the Entity Framework, you can frequently increase performance by compiling the query one time and executing it several times with different parameters. For example, an application might have to retrieve all the customers in a particular city; the city is specified at runtime by the user in a form. LINQ to Entities supports using compiled queries for this purpose. + + Starting with .NET Framework 4.5, LINQ queries are cached automatically. However, you can still use compiled LINQ queries to reduce this cost in later executions and compiled queries can be more efficient than LINQ queries that are automatically cached. LINQ to Entities queries that apply the `Enumerable.Contains` operator to in-memory collections are not automatically cached. Also, parameterizing in-memory collections in compiled LINQ queries is not allowed. + The class provides compilation and caching of queries for reuse. Conceptually, this class contains a 's `Compile` method with several overloads. Call the `Compile` method to create a new delegate to represent the compiled query. The `Compile` methods, provided with a and parameter values, return a delegate that produces some result (such as an instance). The query compiles once during only the first execution. The merge options set for the query at the time of the compilation cannot be changed later. Once the query is compiled, you can only supply parameters of primitive type but you cannot replace parts of the query that would change the generated SQL. For more information, see [EF Merge Options and Compiled Queries](/archive/blogs/dsimmons/ef-merge-options-and-compiled-queries). - - The LINQ to Entities query expression that the 's `Compile` method compiles is represented by one of the generic `Func` delegates, such as . At most, the query expression can encapsulate an `ObjectContext` parameter, a return parameter, and 16 query parameters. If more than 16 query parameters are required, you can create a structure whose properties represent query parameters. You can then use the properties on the structure in the query expression after you set the properties. - -## Example 1 - The following example compiles and then invokes a query that accepts a input parameter and returns a sequence of orders where the total due is greater than or equal to $200.00: - + The LINQ to Entities query expression that the 's `Compile` method compiles is represented by one of the generic `Func` delegates, such as . At most, the query expression can encapsulate an `ObjectContext` parameter, a return parameter, and 16 query parameters. If more than 16 query parameters are required, you can create a structure whose properties represent query parameters. You can then use the properties on the structure in the query expression after you set the properties. + +## Example 1 + + The following example compiles and then invokes a query that accepts a input parameter and returns a sequence of orders where the total due is greater than or equal to $200.00: + [!code-csharp[DP L2E Conceptual Examples - compiled query 2](../../../../../../samples/snippets/csharp/VS_Snippets_Data/DP L2E Conceptual Examples/CS/Program.cs#compiledquery2)] - [!code-vb[DP L2E Conceptual Examples - compiled query2](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#compiledquery2)] - -## Example 2 + [!code-vb[DP L2E Conceptual Examples - compiled query2](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#compiledquery2)] + +## Example 2 + + The following example compiles and then invokes a query that returns an instance: - The following example compiles and then invokes a query that returns an instance: - [!code-csharp[DP L2E Conceptual Examples - compiled query1_MQ](../../../../../../samples/snippets/csharp/VS_Snippets_Data/DP L2E Conceptual Examples/CS/Program.cs#compiledquery1_mq)] - [!code-vb[DP L2E Conceptual Examples - compiled query1_MQ](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#compiledquery1_mq)] - -## Example 3 + [!code-vb[DP L2E Conceptual Examples - compiled query1_MQ](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#compiledquery1_mq)] + +## Example 3 + + The following example compiles and then invokes a query that returns the average of the product list prices as a value: - The following example compiles and then invokes a query that returns the average of the product list prices as a value: - [!code-csharp[DP L2E Conceptual Examples - compiled query3_MQ](../../../../../../samples/snippets/csharp/VS_Snippets_Data/DP L2E Conceptual Examples/CS/Program.cs#compiledquery3_mq)] - [!code-vb[DP L2E Conceptual Examples - compiled query3_MQ](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#compiledquery3_mq)] - -## Example 4 + [!code-vb[DP L2E Conceptual Examples - compiled query3_MQ](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#compiledquery3_mq)] + +## Example 4 + + The following example compiles and then invokes a query that accepts a input parameter and then returns a `Contact` whose email address starts with the specified string: - The following example compiles and then invokes a query that accepts a input parameter and then returns a `Contact` whose email address starts with the specified string: - [!code-csharp[DP L2E Conceptual Examples - compiled query4_MQ](../../../../../../samples/snippets/csharp/VS_Snippets_Data/DP L2E Conceptual Examples/CS/Program.cs#compiledquery4_mq)] - [!code-vb[DP L2E Conceptual Examples - compiled query4_MQ](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#compiledquery4_mq)] - -## Example 5 + [!code-vb[DP L2E Conceptual Examples - compiled query4_MQ](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#compiledquery4_mq)] + +## Example 5 + + The following example compiles and then invokes a query that accepts and input parameters and returns a sequence of orders where the order date is later than March 8, 2003, and the total due is less than $300.00: - The following example compiles and then invokes a query that accepts and input parameters and returns a sequence of orders where the order date is later than March 8, 2003, and the total due is less than $300.00: - [!code-csharp[DP L2E Conceptual Examples - compiled query5](../../../../../../samples/snippets/csharp/VS_Snippets_Data/DP L2E Conceptual Examples/CS/Program.cs#compiledquery5)] - [!code-vb[DP L2E Conceptual Examples - compiled query5](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#compiledquery5)] - -## Example 6 + [!code-vb[DP L2E Conceptual Examples - compiled query5](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#compiledquery5)] + +## Example 6 + + The following example compiles and then invokes a query that accepts a input parameter and returns a sequence of orders where the order date is later than March 8, 2004. This query returns the order information as a sequence of anonymous types. Anonymous types are inferred by the compiler, so you cannot specify type parameters in the 's `Compile` method and the type is defined in the query itself. - The following example compiles and then invokes a query that accepts a input parameter and returns a sequence of orders where the order date is later than March 8, 2004. This query returns the order information as a sequence of anonymous types. Anonymous types are inferred by the compiler, so you cannot specify type parameters in the 's `Compile` method and the type is defined in the query itself. - [!code-csharp[DP L2E Conceptual Examples - compiled query6](../../../../../../samples/snippets/csharp/VS_Snippets_Data/DP L2E Conceptual Examples/CS/Program.cs#compiledquery6)] - [!code-vb[DP L2E Conceptual Examples - compiled query6](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#compiledquery6)] - -## Example 7 + [!code-vb[DP L2E Conceptual Examples - compiled query6](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#compiledquery6)] + +## Example 7 + + The following example compiles and then invokes a query that accepts a user-defined structure input parameter and returns a sequence of orders. The structure defines start date, end date, and total due query parameters, and the query returns orders shipped between March 3 and March 8, 2003 with a total due greater than $700.00. - The following example compiles and then invokes a query that accepts a user-defined structure input parameter and returns a sequence of orders. The structure defines start date, end date, and total due query parameters, and the query returns orders shipped between March 3 and March 8, 2003 with a total due greater than $700.00. - [!code-csharp[DP L2E Conceptual Examples - compiled query7](../../../../../../samples/snippets/csharp/VS_Snippets_Data/DP L2E Conceptual Examples/CS/Program.cs#compiledquery7)] - [!code-vb[DP L2E Conceptual Examples - compiled query7](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#compiledquery7)] - - The structure that defines the query parameters: - + [!code-vb[DP L2E Conceptual Examples - compiled query7](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#compiledquery7)] + + The structure that defines the query parameters: + [!code-csharp[DP L2E Conceptual Examples - MyParamsStruct](../../../../../../samples/snippets/csharp/VS_Snippets_Data/DP L2E Conceptual Examples/CS/Program.cs#myparamsstruct)] - [!code-vb[DP L2E Conceptual Examples - MyParamsStruct](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#myparamsstruct)] - + [!code-vb[DP L2E Conceptual Examples - MyParamsStruct](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DP L2E Conceptual Examples/VB/Module1.vb#myparamsstruct)] + ## See also - [ADO.NET Entity Framework](../index.md) diff --git a/docs/framework/data/adonet/ef/language-reference/entity-sql-language.md b/docs/framework/data/adonet/ef/language-reference/entity-sql-language.md index 8f1b46cbccd92..8e7caccf1348d 100644 --- a/docs/framework/data/adonet/ef/language-reference/entity-sql-language.md +++ b/docs/framework/data/adonet/ef/language-reference/entity-sql-language.md @@ -8,7 +8,7 @@ ms.assetid: 9e7d8837-28c5-429d-a824-7bafb59724cf Entity SQL is a storage-independent query language that is similar to SQL. Entity SQL allows you to query entity data, either as objects or in a tabular form. You should consider using Entity SQL in the following cases: -- When a query must be dynamically constructed at run time. In this case, you should also consider using the query builder methods of instead of constructing an Entity SQL query string at run time. +- When a query must be dynamically constructed at runtime. In this case, you should also consider using the query builder methods of instead of constructing an Entity SQL query string at runtime. - When you want to define a query as part of the model definition. Only Entity SQL is supported in a data model. For more information, see [QueryView Element (MSL)](/ef/ef6/modeling/designer/advanced/edmx/msl-spec#queryview-element-msl). diff --git a/docs/framework/data/adonet/ef/language-reference/isof-entity-sql.md b/docs/framework/data/adonet/ef/language-reference/isof-entity-sql.md index 4c5c4969df662..c313085284928 100644 --- a/docs/framework/data/adonet/ef/language-reference/isof-entity-sql.md +++ b/docs/framework/data/adonet/ef/language-reference/isof-entity-sql.md @@ -30,7 +30,7 @@ expression IS [ NOT ] OF ( [ ONLY ] type ) ## Return Value - `true` if `expression` is of type T and T is either a base type, or a derived type of `type`; null if `expression` is null at run time; otherwise, `false`. + `true` if `expression` is of type T and T is either a base type, or a derived type of `type`; null if `expression` is null at runtime; otherwise, `false`. ## Remarks diff --git a/docs/framework/data/adonet/ef/overview.md b/docs/framework/data/adonet/ef/overview.md index af5b661ce3205..8fe0d9d06a80e 100644 --- a/docs/framework/data/adonet/ef/overview.md +++ b/docs/framework/data/adonet/ef/overview.md @@ -18,7 +18,7 @@ The Entity Framework enables developers to work with data in the form of domain- The Entity Framework gives life to models by enabling developers to query entities and relationships in the domain model (called a *conceptual* model in the Entity Framework) while relying on the Entity Framework to translate those operations to data source–specific commands. This frees applications from hard-coded dependencies on a particular data source. - When working with Code First, the conceptual model is mapped to the storage model in code. The Entity Framework can infer the conceptual model based on the object types and additional configurations that you define. The mapping metadata is generated during run time based on a combination of how you defined your domain types and additional configuration information that you provide in code. Entity Framework generates the database as needed based on the metadata. For more information, see [Creating a Model](/ef/ef6/modeling/). + When working with Code First, the conceptual model is mapped to the storage model in code. The Entity Framework can infer the conceptual model based on the object types and additional configurations that you define. The mapping metadata is generated during runtime based on a combination of how you defined your domain types and additional configuration information that you provide in code. Entity Framework generates the database as needed based on the metadata. For more information, see [Creating a Model](/ef/ef6/modeling/). When working with the Entity Data Model Tools, the conceptual model, the storage model, and the mappings between the two are expressed in XML-based schemas and defined in files that have corresponding name extensions: diff --git a/docs/framework/data/adonet/ef/performance-considerations.md b/docs/framework/data/adonet/ef/performance-considerations.md index 41e330331ca4f..108a272e980b9 100644 --- a/docs/framework/data/adonet/ef/performance-considerations.md +++ b/docs/framework/data/adonet/ef/performance-considerations.md @@ -6,170 +6,170 @@ ms.assetid: 61913f3b-4f42-4d9b-810f-2a13c2388a4a --- # Performance Considerations (Entity Framework) -This topic describes performance characteristics of the ADO.NET Entity Framework and provides some considerations to help improve the performance of Entity Framework applications. - -## Stages of Query Execution - - In order to better understand the performance of queries in the Entity Framework, it is helpful to understand the operations that occur when a query executes against a conceptual model and returns data as objects. The following table describes this series of operations. - -|Operation|Relative Cost|Frequency|Comments| -|---------------|-------------------|---------------|--------------| -|Loading metadata|Moderate|Once in each application domain.|Model and mapping metadata used by the Entity Framework is loaded into a . This metadata is cached globally and is available to other instances of in the same application domain.| -|Opening the database connection|Moderate1|As needed.|Because an open connection to the database consumes a valuable resource, the Entity Framework opens and closes the database connection only as needed. You can also explicitly open the connection. For more information, see [Managing Connections and Transactions](/previous-versions/dotnet/netframework-4.0/bb896325(v=vs.100)).| -|Generating views|High|Once in each application domain. (Can be pre-generated.)|Before the Entity Framework can execute a query against a conceptual model or save changes to the data source, it must generate a set of local query views to access the database. Because of the high cost of generating these views, you can pre-generate the views and add them to the project at design-time. For more information, see [How to: Pre-Generate Views to Improve Query Performance](/previous-versions/dotnet/netframework-4.0/bb896240(v=vs.100)).| -|Preparing the query|Moderate2|Once for each unique query.|Includes the costs to compose the query command, generate a command tree based on model and mapping metadata, and define the shape of the returned data. Because now both Entity SQL query commands and LINQ queries are cached, later executions of the same query take less time. You can still use compiled LINQ queries to reduce this cost in later executions and compiled queries can be more efficient than LINQ queries that are automatically cached. For more information, see [Compiled Queries (LINQ to Entities)](./language-reference/compiled-queries-linq-to-entities.md). For general information about LINQ query execution, see [LINQ to Entities](./language-reference/linq-to-entities.md). **Note:** LINQ to Entities queries that apply the `Enumerable.Contains` operator to in-memory collections are not automatically cached. Also parameterizing in-memory collections in compiled LINQ queries is not allowed.| -|Executing the query|Low2|Once for each query.|The cost of executing the command against the data source by using the ADO.NET data provider. Because most data sources cache query plans, later executions of the same query may take even less time.| -|Loading and validating types|Low3|Once for each instance.|Types are loaded and validated against the types that the conceptual model defines.| -|Tracking|Low3|Once for each object that a query returns. 4|If a query uses the merge option, this stage does not affect performance.

If the query uses the , , or merge option, query results are tracked in the . An is generated for each tracked object that the query returns and is used to create an in the . If an existing can be found for the , the existing object is returned. If the , or option is used, the object is updated before it is returned.

For more information, see [Identity Resolution, State Management, and Change Tracking](/previous-versions/dotnet/netframework-4.0/bb896269(v=vs.100)).| -|Materializing the objects|Moderate3|Once for each object that a query returns. 4|The process of reading the returned object and creating objects and setting property values that are based on the values in each instance of the class. If the object already exists in the and the query uses the or merge options, this stage does not affect performance. For more information, see [Identity Resolution, State Management, and Change Tracking](/previous-versions/dotnet/netframework-4.0/bb896269(v=vs.100)).| - - 1 When a data source provider implements connection pooling, the cost of opening a connection is distributed across the pool. The .NET Provider for SQL Server supports connection pooling. - - 2 Cost increases with increased query complexity. - - 3 Total cost increases proportional to the number of objects returned by the query. - - 4 This overhead is not required for EntityClient queries because EntityClient queries return an instead of objects. For more information, see [EntityClient Provider for the Entity Framework](entityclient-provider-for-the-entity-framework.md). - -## Additional Considerations - - The following are other considerations that may affect the performance of Entity Framework applications. - -### Query Execution - - Because queries can be resource intensive, consider at what point in your code and on what computer a query is executed. - -#### Deferred versus immediate execution - - When you create an or LINQ query, the query may not be executed immediately. Query execution is deferred until the results are needed, such as during a `foreach` (C#) or `For Each` (Visual Basic) enumeration or when it is assigned to fill a collection. Query execution begins immediately when you call the method on an or when you call a LINQ method that returns a singleton query, such as or . For more information, see [Object Queries](/previous-versions/dotnet/netframework-4.0/bb896241(v=vs.100)) and [Query Execution (LINQ to Entities)](./language-reference/query-execution.md). - -#### Client-side execution of LINQ queries - - Although the execution of a LINQ query occurs on the computer that hosts the data source, some parts of a LINQ query may be evaluated on the client computer. For more information, see the Store Execution section of [Query Execution (LINQ to Entities)](./language-reference/query-execution.md). - -### Query and Mapping Complexity - - The complexity of individual queries and of the mapping in the entity model will have a significant effect on query performance. - -#### Mapping complexity - - Models that are more complex than a simple one-to-one mapping between entities in the conceptual model and tables in the storage model generate more complex commands than models that have a one-to-one mapping. - -#### Query complexity - - Queries that require a large number of joins in the commands that are executed against the data source or that return a large amount of data may affect performance in the following ways: - -- Queries against a conceptual model that seem simple may result in the execution of more complex queries against the data source. This can occur because the Entity Framework translates a query against a conceptual model into an equivalent query against the data source. When a single entity set in the conceptual model maps to more than one table in the data source, or when a relationship between entities is mapped to a join table, the query command executed against the data source query may require one or more joins. - +This topic describes performance characteristics of the ADO.NET Entity Framework and provides some considerations to help improve the performance of Entity Framework applications. + +## Stages of Query Execution + + In order to better understand the performance of queries in the Entity Framework, it is helpful to understand the operations that occur when a query executes against a conceptual model and returns data as objects. The following table describes this series of operations. + +|Operation|Relative Cost|Frequency|Comments| +|---------------|-------------------|---------------|--------------| +|Loading metadata|Moderate|Once in each application domain.|Model and mapping metadata used by the Entity Framework is loaded into a . This metadata is cached globally and is available to other instances of in the same application domain.| +|Opening the database connection|Moderate1|As needed.|Because an open connection to the database consumes a valuable resource, the Entity Framework opens and closes the database connection only as needed. You can also explicitly open the connection. For more information, see [Managing Connections and Transactions](/previous-versions/dotnet/netframework-4.0/bb896325(v=vs.100)).| +|Generating views|High|Once in each application domain. (Can be pre-generated.)|Before the Entity Framework can execute a query against a conceptual model or save changes to the data source, it must generate a set of local query views to access the database. Because of the high cost of generating these views, you can pre-generate the views and add them to the project at design-time. For more information, see [How to: Pre-Generate Views to Improve Query Performance](/previous-versions/dotnet/netframework-4.0/bb896240(v=vs.100)).| +|Preparing the query|Moderate2|Once for each unique query.|Includes the costs to compose the query command, generate a command tree based on model and mapping metadata, and define the shape of the returned data. Because now both Entity SQL query commands and LINQ queries are cached, later executions of the same query take less time. You can still use compiled LINQ queries to reduce this cost in later executions and compiled queries can be more efficient than LINQ queries that are automatically cached. For more information, see [Compiled Queries (LINQ to Entities)](./language-reference/compiled-queries-linq-to-entities.md). For general information about LINQ query execution, see [LINQ to Entities](./language-reference/linq-to-entities.md). **Note:** LINQ to Entities queries that apply the `Enumerable.Contains` operator to in-memory collections are not automatically cached. Also parameterizing in-memory collections in compiled LINQ queries is not allowed.| +|Executing the query|Low2|Once for each query.|The cost of executing the command against the data source by using the ADO.NET data provider. Because most data sources cache query plans, later executions of the same query may take even less time.| +|Loading and validating types|Low3|Once for each instance.|Types are loaded and validated against the types that the conceptual model defines.| +|Tracking|Low3|Once for each object that a query returns. 4|If a query uses the merge option, this stage does not affect performance.

If the query uses the , , or merge option, query results are tracked in the . An is generated for each tracked object that the query returns and is used to create an in the . If an existing can be found for the , the existing object is returned. If the , or option is used, the object is updated before it is returned.

For more information, see [Identity Resolution, State Management, and Change Tracking](/previous-versions/dotnet/netframework-4.0/bb896269(v=vs.100)).| +|Materializing the objects|Moderate3|Once for each object that a query returns. 4|The process of reading the returned object and creating objects and setting property values that are based on the values in each instance of the class. If the object already exists in the and the query uses the or merge options, this stage does not affect performance. For more information, see [Identity Resolution, State Management, and Change Tracking](/previous-versions/dotnet/netframework-4.0/bb896269(v=vs.100)).| + + 1 When a data source provider implements connection pooling, the cost of opening a connection is distributed across the pool. The .NET Provider for SQL Server supports connection pooling. + + 2 Cost increases with increased query complexity. + + 3 Total cost increases proportional to the number of objects returned by the query. + + 4 This overhead is not required for EntityClient queries because EntityClient queries return an instead of objects. For more information, see [EntityClient Provider for the Entity Framework](entityclient-provider-for-the-entity-framework.md). + +## Additional Considerations + + The following are other considerations that may affect the performance of Entity Framework applications. + +### Query Execution + + Because queries can be resource intensive, consider at what point in your code and on what computer a query is executed. + +#### Deferred versus immediate execution + + When you create an or LINQ query, the query may not be executed immediately. Query execution is deferred until the results are needed, such as during a `foreach` (C#) or `For Each` (Visual Basic) enumeration or when it is assigned to fill a collection. Query execution begins immediately when you call the method on an or when you call a LINQ method that returns a singleton query, such as or . For more information, see [Object Queries](/previous-versions/dotnet/netframework-4.0/bb896241(v=vs.100)) and [Query Execution (LINQ to Entities)](./language-reference/query-execution.md). + +#### Client-side execution of LINQ queries + + Although the execution of a LINQ query occurs on the computer that hosts the data source, some parts of a LINQ query may be evaluated on the client computer. For more information, see the Store Execution section of [Query Execution (LINQ to Entities)](./language-reference/query-execution.md). + +### Query and Mapping Complexity + + The complexity of individual queries and of the mapping in the entity model will have a significant effect on query performance. + +#### Mapping complexity + + Models that are more complex than a simple one-to-one mapping between entities in the conceptual model and tables in the storage model generate more complex commands than models that have a one-to-one mapping. + +#### Query complexity + + Queries that require a large number of joins in the commands that are executed against the data source or that return a large amount of data may affect performance in the following ways: + +- Queries against a conceptual model that seem simple may result in the execution of more complex queries against the data source. This can occur because the Entity Framework translates a query against a conceptual model into an equivalent query against the data source. When a single entity set in the conceptual model maps to more than one table in the data source, or when a relationship between entities is mapped to a join table, the query command executed against the data source query may require one or more joins. + > [!NOTE] - > Use the method of the or classes to view the commands that are executed against the data source for a given query. For more information, see [How to: View the Store Commands](/previous-versions/dotnet/netframework-4.0/bb896348(v=vs.100)). - -- Nested Entity SQL queries may create joins on the server and can return a large number of rows. - - The following is an example of a nested query in a projection clause: - - ```sql + > Use the method of the or classes to view the commands that are executed against the data source for a given query. For more information, see [How to: View the Store Commands](/previous-versions/dotnet/netframework-4.0/bb896348(v=vs.100)). + +- Nested Entity SQL queries may create joins on the server and can return a large number of rows. + + The following is an example of a nested query in a projection clause: + + ```sql SELECT c, (SELECT c, (SELECT c FROM AdventureWorksModel.Vendor AS c ) As Inner2 FROM AdventureWorksModel.JobCandidate AS c ) As Inner1 - FROM AdventureWorksModel.EmployeeDepartmentHistory AS c - ``` - - In addition, such queries cause the query pipeline to generate a single query with duplication of objects across nested queries. Because of this, a single column may be duplicated multiple times. On some databases, including SQL Server, this can cause the TempDB table to grow very large, which can decrease server performance. Care should be taken when you execute nested queries. - -- Any queries that return a large amount of data can cause decreased performance if the client is performing operations that consume resources in a way that is proportional to the size of the result set. In such cases, you should consider limiting the amount of data returned by the query. For more information, see [How to: Page Through Query Results](/previous-versions/dotnet/netframework-4.0/bb738702(v=vs.100)). - - Any commands automatically generated by the Entity Framework may be more complex than similar commands written explicitly by a database developer. If you need explicit control over the commands executed against your data source, consider defining a mapping to a table-valued function or stored procedure. - -#### Relationships - - For optimal query performance, you must define relationships between entities both as associations in the entity model and as logical relationships in the data source. - -### Query Paths - - By default, when you execute an , related objects are not returned (although objects that represent the relationships themselves are). You can load related objects in one of three ways: - -1. Set the query path before the is executed. - -2. Call the `Load` method on the navigation property that the object exposes. - -3. Set the option on the to `true`. Note that this is done automatically when you generate object-layer code with the [Entity Data Model Designer](/previous-versions/dotnet/netframework-4.0/cc716685(v=vs.100)). For more information see [Generated Code Overview](/previous-versions/dotnet/netframework-4.0/cc982041(v=vs.100)). - - When you consider which option to use, be aware that there is a tradeoff between the number of requests against the database and the amount of data returned in a single query. For more information, see [Loading Related Objects](/previous-versions/dotnet/netframework-4.0/bb896272(v=vs.100)). - -#### Using query paths - - Query paths define the graph of objects that a query returns. When you define a query path, only a single request against the database is required to return all objects that the path defines. Using query paths can result in complex commands being executed against the data source from seemingly simple object queries. This occurs because one or more joins are required to return related objects in a single query. This complexity is greater in queries against a complex entity model, such as an entity with inheritance or a path that includes many-to-many relationships. - + FROM AdventureWorksModel.EmployeeDepartmentHistory AS c + ``` + + In addition, such queries cause the query pipeline to generate a single query with duplication of objects across nested queries. Because of this, a single column may be duplicated multiple times. On some databases, including SQL Server, this can cause the TempDB table to grow very large, which can decrease server performance. Care should be taken when you execute nested queries. + +- Any queries that return a large amount of data can cause decreased performance if the client is performing operations that consume resources in a way that is proportional to the size of the result set. In such cases, you should consider limiting the amount of data returned by the query. For more information, see [How to: Page Through Query Results](/previous-versions/dotnet/netframework-4.0/bb738702(v=vs.100)). + + Any commands automatically generated by the Entity Framework may be more complex than similar commands written explicitly by a database developer. If you need explicit control over the commands executed against your data source, consider defining a mapping to a table-valued function or stored procedure. + +#### Relationships + + For optimal query performance, you must define relationships between entities both as associations in the entity model and as logical relationships in the data source. + +### Query Paths + + By default, when you execute an , related objects are not returned (although objects that represent the relationships themselves are). You can load related objects in one of three ways: + +1. Set the query path before the is executed. + +2. Call the `Load` method on the navigation property that the object exposes. + +3. Set the option on the to `true`. Note that this is done automatically when you generate object-layer code with the [Entity Data Model Designer](/previous-versions/dotnet/netframework-4.0/cc716685(v=vs.100)). For more information see [Generated Code Overview](/previous-versions/dotnet/netframework-4.0/cc982041(v=vs.100)). + + When you consider which option to use, be aware that there is a tradeoff between the number of requests against the database and the amount of data returned in a single query. For more information, see [Loading Related Objects](/previous-versions/dotnet/netframework-4.0/bb896272(v=vs.100)). + +#### Using query paths + + Query paths define the graph of objects that a query returns. When you define a query path, only a single request against the database is required to return all objects that the path defines. Using query paths can result in complex commands being executed against the data source from seemingly simple object queries. This occurs because one or more joins are required to return related objects in a single query. This complexity is greater in queries against a complex entity model, such as an entity with inheritance or a path that includes many-to-many relationships. + > [!NOTE] -> Use the method to see the command that will be generated by an . For more information, see [How to: View the Store Commands](/previous-versions/dotnet/netframework-4.0/bb896348(v=vs.100)). - - When a query path includes too many related objects or the objects contain too much row data, the data source might be unable to complete the query. This occurs if the query requires intermediate temporary storage that exceeds the capabilities of the data source. When this occurs, you can reduce the complexity of the data source query by explicitly loading related objects. - -#### Explicitly loading related objects - - You can explicitly load related objects by calling the `Load` method on a navigation property that returns an or . Explicitly loading objects requires a round-trip to the database every time `Load` is called. - +> Use the method to see the command that will be generated by an . For more information, see [How to: View the Store Commands](/previous-versions/dotnet/netframework-4.0/bb896348(v=vs.100)). + + When a query path includes too many related objects or the objects contain too much row data, the data source might be unable to complete the query. This occurs if the query requires intermediate temporary storage that exceeds the capabilities of the data source. When this occurs, you can reduce the complexity of the data source query by explicitly loading related objects. + +#### Explicitly loading related objects + + You can explicitly load related objects by calling the `Load` method on a navigation property that returns an or . Explicitly loading objects requires a round-trip to the database every time `Load` is called. + > [!NOTE] -> if you call `Load` while looping through a collection of returned objects, such as when you use the `foreach` statement (`For Each` in Visual Basic), the data source-specific provider must support multiple active results sets on a single connection. For a SQL Server database, you must specify a value of `MultipleActiveResultSets = true` in the provider connection string. - - You can also use the method when there is no or properties on entities. This is useful when you are using POCO entities. - - Although explicitly loading related objects will reduce the number of joins and reduced the amount of redundant data, `Load` requires repeated connections to the database, which can become costly when explicitly loading a large number of objects. - -### Saving Changes - - When you call the method on an , a separate create, update, or delete command is generated for every added, updated, or deleted object in the context. These commands are executed on the data source in a single transaction. As with queries, the performance of create, update, and delete operations depends on the complexity of the mapping in the conceptual model. - -### Distributed Transactions - - Operations in an explicit transaction that require resources that are managed by the distributed transaction coordinator (DTC) will be much more expensive than a similar operation that does not require the DTC. Promotion to the DTC will occur in the following situations: - -- An explicit transaction with an operation against a SQL Server 2000 database or other data source that always promote explicit transactions to the DTC. - -- An explicit transaction with an operation against SQL Server 2005 when the connection is managed by the Entity Framework. This occurs because SQL Server 2005 promotes to a DTC whenever a connection is closed and reopened within a single transaction, which is the default behavior of the Entity Framework. This DTC promotion does not occur when using SQL Server 2008. To avoid this promotion when using SQL Server 2005, you must explicitly open and close the connection within the transaction. For more information, see [Managing Connections and Transactions](/previous-versions/dotnet/netframework-4.0/bb896325(v=vs.100)). - - An explicit transaction is used when one or more operations are executed inside a transaction. For more information, see [Managing Connections and Transactions](/previous-versions/dotnet/netframework-4.0/bb896325(v=vs.100)). - -## Strategies for Improving Performance - - You can improve the overall performance of queries in the Entity Framework by using the following strategies. - -#### Pre-generate views - - Generating views based on an entity model is a significant cost the first time that an application executes a query. Use the EdmGen.exe utility to pre-generate views as a Visual Basic or C# code file that can be added to the project during design. You could also use the Text Template Transformation Toolkit to generate pre-compiled views. Pre-generated views are validated at run time to ensure that they are consistent with the current version of the specified entity model. For more information, see [How to: Pre-Generate Views to Improve Query Performance](/previous-versions/dotnet/netframework-4.0/bb896240(v=vs.100)). - - When working with very large models, the following consideration applies: - - The .NET metadata format limits the number of user string characters in a given binary to 16,777,215 (0xFFFFFF). If you are generating views for a very large model and the view file reaches this size limit, you will get the "No logical space left to create more user strings." compile error. This size limitation applies to all managed binaries. For more information see the [blog](/archive/blogs/appfabriccat/solving-the-no-logical-space-left-to-create-more-user-strings-error-and-improving-performance-of-pre-generated-views-in-visual-studio-net4-entity-framework) that demonstrates how to avoid the error when working with large and complex models. - -#### Consider using the NoTracking merge option for queries - - There is a cost required to track returned objects in the object context. Detecting changes to objects and ensuring that multiple requests for the same logical entity return the same object instance requires that objects be attached to an instance. If you do not plan to make updates or deletes to objects and do not require identity management, consider using the merge options when you execute queries. - -#### Return the correct amount of data - - In some scenarios, specifying a query path using the method is much faster because it requires fewer round trips to the database. However, in other scenarios, additional round trips to the database to load related objects may be faster because the simpler queries with fewer joins result in less redundancy of data. Because of this, we recommend that you test the performance of various ways to retrieve related objects. For more information, see [Loading Related Objects](/previous-versions/dotnet/netframework-4.0/bb896272(v=vs.100)). - - To avoid returning too much data in a single query, consider paging the results of the query into more manageable groups. For more information, see [How to: Page Through Query Results](/previous-versions/dotnet/netframework-4.0/bb738702(v=vs.100)). - -#### Limit the scope of the ObjectContext - - In most cases, you should create an instance within a `using` statement (`Using…End Using` in Visual Basic). This can increase performance by ensuring that the resources associated with the object context are disposed automatically when the code exits the statement block. However, when controls are bound to objects managed by the object context, the instance should be maintained as long as the binding is needed and disposed of manually. For more information, see [Managing Connections and Transactions](/previous-versions/dotnet/netframework-4.0/bb896325(v=vs.100)). - -#### Consider opening the database connection manually - - When your application executes a series of object queries or frequently calls to persist create, update, and delete operations to the data source, the Entity Framework must continuously open and close the connection to the data source. In these situations, consider manually opening the connection at the start of these operations and either closing or disposing of the connection when the operations are complete. For more information, see [Managing Connections and Transactions](/previous-versions/dotnet/netframework-4.0/bb896325(v=vs.100)). - -## Performance Data - - Some performance data for the Entity Framework is published in the following posts on the [ADO.NET team blog](/archive/blogs/adonet/): - -- [Exploring the Performance of the ADO.NET Entity Framework - Part 1](/archive/blogs/adonet/exploring-the-performance-of-the-ado-net-entity-framework-part-1) - -- [Exploring the Performance of the ADO.NET Entity Framework – Part 2](/archive/blogs/adonet/exploring-the-performance-of-the-ado-net-entity-framework-part-2) - -- [ADO.NET Entity Framework Performance Comparison](/archive/blogs/adonet/ado-net-entity-framework-performance-comparison) - +> if you call `Load` while looping through a collection of returned objects, such as when you use the `foreach` statement (`For Each` in Visual Basic), the data source-specific provider must support multiple active results sets on a single connection. For a SQL Server database, you must specify a value of `MultipleActiveResultSets = true` in the provider connection string. + + You can also use the method when there is no or properties on entities. This is useful when you are using POCO entities. + + Although explicitly loading related objects will reduce the number of joins and reduced the amount of redundant data, `Load` requires repeated connections to the database, which can become costly when explicitly loading a large number of objects. + +### Saving Changes + + When you call the method on an , a separate create, update, or delete command is generated for every added, updated, or deleted object in the context. These commands are executed on the data source in a single transaction. As with queries, the performance of create, update, and delete operations depends on the complexity of the mapping in the conceptual model. + +### Distributed Transactions + + Operations in an explicit transaction that require resources that are managed by the distributed transaction coordinator (DTC) will be much more expensive than a similar operation that does not require the DTC. Promotion to the DTC will occur in the following situations: + +- An explicit transaction with an operation against a SQL Server 2000 database or other data source that always promote explicit transactions to the DTC. + +- An explicit transaction with an operation against SQL Server 2005 when the connection is managed by the Entity Framework. This occurs because SQL Server 2005 promotes to a DTC whenever a connection is closed and reopened within a single transaction, which is the default behavior of the Entity Framework. This DTC promotion does not occur when using SQL Server 2008. To avoid this promotion when using SQL Server 2005, you must explicitly open and close the connection within the transaction. For more information, see [Managing Connections and Transactions](/previous-versions/dotnet/netframework-4.0/bb896325(v=vs.100)). + + An explicit transaction is used when one or more operations are executed inside a transaction. For more information, see [Managing Connections and Transactions](/previous-versions/dotnet/netframework-4.0/bb896325(v=vs.100)). + +## Strategies for Improving Performance + + You can improve the overall performance of queries in the Entity Framework by using the following strategies. + +#### Pre-generate views + + Generating views based on an entity model is a significant cost the first time that an application executes a query. Use the EdmGen.exe utility to pre-generate views as a Visual Basic or C# code file that can be added to the project during design. You could also use the Text Template Transformation Toolkit to generate pre-compiled views. Pre-generated views are validated at runtime to ensure that they are consistent with the current version of the specified entity model. For more information, see [How to: Pre-Generate Views to Improve Query Performance](/previous-versions/dotnet/netframework-4.0/bb896240(v=vs.100)). + + When working with very large models, the following consideration applies: + + The .NET metadata format limits the number of user string characters in a given binary to 16,777,215 (0xFFFFFF). If you are generating views for a very large model and the view file reaches this size limit, you will get the "No logical space left to create more user strings." compile error. This size limitation applies to all managed binaries. For more information see the [blog](/archive/blogs/appfabriccat/solving-the-no-logical-space-left-to-create-more-user-strings-error-and-improving-performance-of-pre-generated-views-in-visual-studio-net4-entity-framework) that demonstrates how to avoid the error when working with large and complex models. + +#### Consider using the NoTracking merge option for queries + + There is a cost required to track returned objects in the object context. Detecting changes to objects and ensuring that multiple requests for the same logical entity return the same object instance requires that objects be attached to an instance. If you do not plan to make updates or deletes to objects and do not require identity management, consider using the merge options when you execute queries. + +#### Return the correct amount of data + + In some scenarios, specifying a query path using the method is much faster because it requires fewer round trips to the database. However, in other scenarios, additional round trips to the database to load related objects may be faster because the simpler queries with fewer joins result in less redundancy of data. Because of this, we recommend that you test the performance of various ways to retrieve related objects. For more information, see [Loading Related Objects](/previous-versions/dotnet/netframework-4.0/bb896272(v=vs.100)). + + To avoid returning too much data in a single query, consider paging the results of the query into more manageable groups. For more information, see [How to: Page Through Query Results](/previous-versions/dotnet/netframework-4.0/bb738702(v=vs.100)). + +#### Limit the scope of the ObjectContext + + In most cases, you should create an instance within a `using` statement (`Using…End Using` in Visual Basic). This can increase performance by ensuring that the resources associated with the object context are disposed automatically when the code exits the statement block. However, when controls are bound to objects managed by the object context, the instance should be maintained as long as the binding is needed and disposed of manually. For more information, see [Managing Connections and Transactions](/previous-versions/dotnet/netframework-4.0/bb896325(v=vs.100)). + +#### Consider opening the database connection manually + + When your application executes a series of object queries or frequently calls to persist create, update, and delete operations to the data source, the Entity Framework must continuously open and close the connection to the data source. In these situations, consider manually opening the connection at the start of these operations and either closing or disposing of the connection when the operations are complete. For more information, see [Managing Connections and Transactions](/previous-versions/dotnet/netframework-4.0/bb896325(v=vs.100)). + +## Performance Data + + Some performance data for the Entity Framework is published in the following posts on the [ADO.NET team blog](/archive/blogs/adonet/): + +- [Exploring the Performance of the ADO.NET Entity Framework - Part 1](/archive/blogs/adonet/exploring-the-performance-of-the-ado-net-entity-framework-part-1) + +- [Exploring the Performance of the ADO.NET Entity Framework – Part 2](/archive/blogs/adonet/exploring-the-performance-of-the-ado-net-entity-framework-part-2) + +- [ADO.NET Entity Framework Performance Comparison](/archive/blogs/adonet/ado-net-entity-framework-performance-comparison) + ## See also - [Development and Deployment Considerations](development-and-deployment-considerations.md) diff --git a/docs/framework/data/adonet/ef/security-considerations.md b/docs/framework/data/adonet/ef/security-considerations.md index 9a94a18393891..63820d743e403 100644 --- a/docs/framework/data/adonet/ef/security-considerations.md +++ b/docs/framework/data/adonet/ef/security-considerations.md @@ -47,7 +47,7 @@ This article describes security considerations that are specific to developing, - Use connection string builders when dynamically creating connections. - If you must construct connection strings at run time, use the class. This string builder class helps prevent connection string injection attacks by validating and escaping invalid input information. Also use the appropriate string builder class to construct the data source connection string that is part of the Entity Framework connection string. For information about connection string builders for ADO.NET providers, see [Connection String Builders](../connection-string-builders.md). + If you must construct connection strings at runtime, use the class. This string builder class helps prevent connection string injection attacks by validating and escaping invalid input information. Also use the appropriate string builder class to construct the data source connection string that is part of the Entity Framework connection string. For information about connection string builders for ADO.NET providers, see [Connection String Builders](../connection-string-builders.md). For more information, see [Protecting Connection Information](../protecting-connection-information.md). @@ -95,7 +95,7 @@ This article describes security considerations that are specific to developing, ### Restrict permissions to the model and mapping files - An administrator must restrict write access to the model and mapping files (.edmx, .csdl, .ssdl, and .msl) to only users who modify the model or mappings. Entity Framework only requires read access to these files at run time. An administrator should also restrict access to object layer and pre-compiled view source code files that are generated by the Entity Data Model tools. + An administrator must restrict write access to the model and mapping files (.edmx, .csdl, .ssdl, and .msl) to only users who modify the model or mappings. Entity Framework only requires read access to these files at runtime. An administrator should also restrict access to object layer and pre-compiled view source code files that are generated by the Entity Data Model tools. ## Security Considerations for Queries diff --git a/docs/framework/data/adonet/entity-key.md b/docs/framework/data/adonet/entity-key.md index f42fca5185de7..59c9f56fa9b94 100644 --- a/docs/framework/data/adonet/entity-key.md +++ b/docs/framework/data/adonet/entity-key.md @@ -6,36 +6,36 @@ ms.assetid: 0d447a6d-fa7a-4db0-8e7a-fd45e385fca0 --- # entity key -An *entity key* is a [property](property.md) or a set of properties of an [entity type](entity-type.md) that are used to determine identity. The properties that make up an entity key are chosen at design time. The values of entity key properties must uniquely identify an entity type instance within an [entity set](entity-set.md) at run time. The properties that make up an entity key should be chosen to guarantee uniqueness of instances in an entity set. - - The following are the requirements for a set of properties to be an entity key: - -- No two entity keys within an entity set can be identical. That is, for any two entities within an entity set, the values for all of the properties that constitute a key cannot be the same. However, some (but not all) of the values that make up an entity key can be the same. - -- An entity key must consist of a set of non-nullable, immutable, [primitive type properties](entity-data-model-primitive-data-types.md). - -- The properties that make up an entity key for a given entity type cannot change. You cannot allow more than one possible entity key for a given entity type; surrogate keys are not supported. - -- When an entity is involved in an inheritance hierarchy, the root entity must contain all the properties that make up the entity key, and the entity key must be defined on the root entity type. For more information, see [Entity Data Model: Inheritance](entity-data-model-inheritance.md). - -## Example - - The diagram below shows a conceptual model with three entity types: `Book`, `Publisher`, and `Author`. The properties of each entity type that make up its entity key are denoted with "(Key)". Note that the `Author` entity type has an entity key that consists of two properties, `Name` and `Address`. - - ![Example model with three entity types](./media/entity-key/example-model-three-entity-types.gif) - - The [ADO.NET Entity Framework](./ef/index.md) uses a domain-specific language (DSL) called conceptual schema definition language ([CSDL](/ef/ef6/modeling/designer/advanced/edmx/csdl-spec)) to define conceptual models. The CSDL below defines the `Book` entity type shown in the diagram above. Note that the entity key is defined by referencing the `ISBN` property of the entity type. - - [!code-xml[EDM_Example_Model#EntityExample](../../../../samples/snippets/xml/VS_Snippets_Data/edm_example_model/xml/books.edmx#entityexample)] - - The `ISBN` property is a good choice for the entity key because an International Standard Book Number (ISBN) uniquely identifies a book. - - The CSDL below defines the `Author` entity type shown in the diagram above. Note that the entity key consists of two properties, `Name` and `Address`. - - [!code-xml[EDM_Example_Model#CompositeKeyExample](../../../../samples/snippets/xml/VS_Snippets_Data/edm_example_model/xml/books.edmx#compositekeyexample)] - - Using `Name` and `Address` for the entity key is a reasonable choice, because two authors of the same name are unlikely to live at the same address. However, this choice for an entity key does not absolutely guarantee unique entity keys in an entity set. Adding a property, such as `AuthorId`, that could be used to uniquely identify an author would be recommended in this case. - +An *entity key* is a [property](property.md) or a set of properties of an [entity type](entity-type.md) that are used to determine identity. The properties that make up an entity key are chosen at design time. The values of entity key properties must uniquely identify an entity type instance within an [entity set](entity-set.md) at runtime. The properties that make up an entity key should be chosen to guarantee uniqueness of instances in an entity set. + + The following are the requirements for a set of properties to be an entity key: + +- No two entity keys within an entity set can be identical. That is, for any two entities within an entity set, the values for all of the properties that constitute a key cannot be the same. However, some (but not all) of the values that make up an entity key can be the same. + +- An entity key must consist of a set of non-nullable, immutable, [primitive type properties](entity-data-model-primitive-data-types.md). + +- The properties that make up an entity key for a given entity type cannot change. You cannot allow more than one possible entity key for a given entity type; surrogate keys are not supported. + +- When an entity is involved in an inheritance hierarchy, the root entity must contain all the properties that make up the entity key, and the entity key must be defined on the root entity type. For more information, see [Entity Data Model: Inheritance](entity-data-model-inheritance.md). + +## Example + + The diagram below shows a conceptual model with three entity types: `Book`, `Publisher`, and `Author`. The properties of each entity type that make up its entity key are denoted with "(Key)". Note that the `Author` entity type has an entity key that consists of two properties, `Name` and `Address`. + + ![Example model with three entity types](./media/entity-key/example-model-three-entity-types.gif) + + The [ADO.NET Entity Framework](./ef/index.md) uses a domain-specific language (DSL) called conceptual schema definition language ([CSDL](/ef/ef6/modeling/designer/advanced/edmx/csdl-spec)) to define conceptual models. The CSDL below defines the `Book` entity type shown in the diagram above. Note that the entity key is defined by referencing the `ISBN` property of the entity type. + + [!code-xml[EDM_Example_Model#EntityExample](../../../../samples/snippets/xml/VS_Snippets_Data/edm_example_model/xml/books.edmx#entityexample)] + + The `ISBN` property is a good choice for the entity key because an International Standard Book Number (ISBN) uniquely identifies a book. + + The CSDL below defines the `Author` entity type shown in the diagram above. Note that the entity key consists of two properties, `Name` and `Address`. + + [!code-xml[EDM_Example_Model#CompositeKeyExample](../../../../samples/snippets/xml/VS_Snippets_Data/edm_example_model/xml/books.edmx#compositekeyexample)] + + Using `Name` and `Address` for the entity key is a reasonable choice, because two authors of the same name are unlikely to live at the same address. However, this choice for an entity key does not absolutely guarantee unique entity keys in an entity set. Adding a property, such as `AuthorId`, that could be used to uniquely identify an author would be recommended in this case. + ## See also - [Entity Data Model Key Concepts](entity-data-model-key-concepts.md) diff --git a/docs/framework/data/adonet/entity-set.md b/docs/framework/data/adonet/entity-set.md index 01eac9587246f..f7c4816d8cf5b 100644 --- a/docs/framework/data/adonet/entity-set.md +++ b/docs/framework/data/adonet/entity-set.md @@ -6,41 +6,41 @@ ms.assetid: 59ec6ab0-88e5-4d25-b112-7a4eccbe61f0 --- # entity set -An *entity set* is a logical container for instances of an [entity type](entity-type.md) and instances of any type derived from that entity type. (For information about derived types, see [Entity Data Model: Inheritance](entity-data-model-inheritance.md).) The relationship between an entity type and an entity set is analogous to the relationship between a row and a table in a relational database: Like a row, an entity type describes data structure, and, like a table, an entity set contains instances of a given structure. An entity set is not a data modeling construct; it does not describe the structure of data. Instead, an entity set provides a construct for a hosting or storage environment (such as the common language runtime or a SQL Server database) to group entity type instances so that they can be mapped to a data store. - - An entity set is defined within an [entity container](entity-container.md), which is a logical grouping of entity sets and [association sets](association-set.md). - - For an entity type instance to exist in an entity set, the following must be true: - -- The type of the instance is either the same as the entity type on which the entity set is based, or the type of the instance is a subtype of the entity type. - -- The [entity key](entity-key.md) for the instance is unique within the entity set. - -- The instance does not exist in any other entity set. - +An *entity set* is a logical container for instances of an [entity type](entity-type.md) and instances of any type derived from that entity type. (For information about derived types, see [Entity Data Model: Inheritance](entity-data-model-inheritance.md).) The relationship between an entity type and an entity set is analogous to the relationship between a row and a table in a relational database: Like a row, an entity type describes data structure, and, like a table, an entity set contains instances of a given structure. An entity set is not a data modeling construct; it does not describe the structure of data. Instead, an entity set provides a construct for a hosting or storage environment (such as the common language runtime or a SQL Server database) to group entity type instances so that they can be mapped to a data store. + + An entity set is defined within an [entity container](entity-container.md), which is a logical grouping of entity sets and [association sets](association-set.md). + + For an entity type instance to exist in an entity set, the following must be true: + +- The type of the instance is either the same as the entity type on which the entity set is based, or the type of the instance is a subtype of the entity type. + +- The [entity key](entity-key.md) for the instance is unique within the entity set. + +- The instance does not exist in any other entity set. + > [!NOTE] - > Multiple entity sets can be defined using the same entity type, but an instance of a given entity type can only exist in one entity set. - - You do not have to define an entity set for each entity type in a conceptual model. - -## Example - - The diagram below shows a conceptual model with three entity types: `Book`, `Publisher`, and `Author`. - - ![Example model with three entity types](./media/entity-set/example-model-three-entity-types.gif) - - The following diagram shows two entity sets (`Books` and `Publishers`) and an association set (`PublishedBy`) based on the conceptual model shown above. Bi in the `Books` entity set represents an instance of the `Book` entity type at run time. Similarly, Pj represent a `Publisher` instance in the `Publishers` entity set. BiPj represents an instance of the `PublishedBy` association in the `PublishedBy` association set. - - ![Screenshot that shows a Sets example.](./media/entity-set/sets-example-association.gif) - - The [ADO.NET Entity Framework](./ef/index.md) uses a domain-specific language (DSL) called conceptual schema definition language ([CSDL](/ef/ef6/modeling/designer/advanced/edmx/csdl-spec)) to define conceptual models. The following CSDL defines an entity container with one entity set for each entity type in the conceptual model shown above. Note that the name and entity type for each entity set are defined using XML attributes. - - [!code-xml[EDM_Example_Model#EntityContainerExample](../../../../samples/snippets/xml/VS_Snippets_Data/edm_example_model/xml/books.edmx#entitycontainerexample)] - - It is possible to define multiple entity sets per type (MEST). The following CSDL defines an entity container with two entity sets for the `Book` entity type: - - [!code-xml[EDM_Example_Model#MESTExample](../../../../samples/snippets/xml/VS_Snippets_Data/edm_example_model/xml/books2.edmx#mestexample)] - + > Multiple entity sets can be defined using the same entity type, but an instance of a given entity type can only exist in one entity set. + + You do not have to define an entity set for each entity type in a conceptual model. + +## Example + + The diagram below shows a conceptual model with three entity types: `Book`, `Publisher`, and `Author`. + + ![Example model with three entity types](./media/entity-set/example-model-three-entity-types.gif) + + The following diagram shows two entity sets (`Books` and `Publishers`) and an association set (`PublishedBy`) based on the conceptual model shown above. Bi in the `Books` entity set represents an instance of the `Book` entity type at runtime. Similarly, Pj represent a `Publisher` instance in the `Publishers` entity set. BiPj represents an instance of the `PublishedBy` association in the `PublishedBy` association set. + + ![Screenshot that shows a Sets example.](./media/entity-set/sets-example-association.gif) + + The [ADO.NET Entity Framework](./ef/index.md) uses a domain-specific language (DSL) called conceptual schema definition language ([CSDL](/ef/ef6/modeling/designer/advanced/edmx/csdl-spec)) to define conceptual models. The following CSDL defines an entity container with one entity set for each entity type in the conceptual model shown above. Note that the name and entity type for each entity set are defined using XML attributes. + + [!code-xml[EDM_Example_Model#EntityContainerExample](../../../../samples/snippets/xml/VS_Snippets_Data/edm_example_model/xml/books.edmx#entitycontainerexample)] + + It is possible to define multiple entity sets per type (MEST). The following CSDL defines an entity container with two entity sets for the `Book` entity type: + + [!code-xml[EDM_Example_Model#MESTExample](../../../../samples/snippets/xml/VS_Snippets_Data/edm_example_model/xml/books2.edmx#mestexample)] + ## See also - [Entity Data Model Key Concepts](entity-data-model-key-concepts.md) diff --git a/docs/framework/data/adonet/establishing-the-connection.md b/docs/framework/data/adonet/establishing-the-connection.md index cab7d4bf87ff6..a2c438a92757a 100644 --- a/docs/framework/data/adonet/establishing-the-connection.md +++ b/docs/framework/data/adonet/establishing-the-connection.md @@ -25,7 +25,7 @@ To connect to Microsoft SQL Server, use the property of the object. You can also use the class to create syntactically valid connection strings at run time. For more information, see [Connection String Builders](connection-string-builders.md). + The .NET Framework Data Provider for SQL Server supports a connection string format that is similar to the OLE DB (ADO) connection string format. For valid string format names and values, see the property of the object. You can also use the class to create syntactically valid connection strings at runtime. For more information, see [Connection String Builders](connection-string-builders.md). The following code example demonstrates how to create and open a connection to a SQL Server database. @@ -62,7 +62,7 @@ using (SqlConnection connection = new SqlConnection(connectionString)) - The **URL**, **Remote Provider**, and **Remote Server** keywords are not supported. - For more information about OLE DB connection strings, see the article. You can also use the to create connection strings at run time. + For more information about OLE DB connection strings, see the article. You can also use the to create connection strings at runtime. > [!NOTE] > The `OleDbConnection` object does not support setting or retrieving dynamic properties specific to an OLE DB provider. Only properties that can be passed in the connection string for the OLE DB provider are supported. diff --git a/docs/framework/data/adonet/facet.md b/docs/framework/data/adonet/facet.md index ff3006776452c..dc2332b93ee0e 100644 --- a/docs/framework/data/adonet/facet.md +++ b/docs/framework/data/adonet/facet.md @@ -6,31 +6,31 @@ ms.assetid: 91c4e6aa-3e54-4b6c-a38a-abf27808cc85 --- # facet -A *facet* is used to add detail to a primitive type property definition. A [property](property.md) definition contains information about the property type, but often more detail is necessary. For example, an entity type in a conceptual model might have a property of type `String` whose value cannot be set to null. Facets allow you to specify this level of detail. - - The table below describes the facets that are supported in the EDM. - +A *facet* is used to add detail to a primitive type property definition. A [property](property.md) definition contains information about the property type, but often more detail is necessary. For example, an entity type in a conceptual model might have a property of type `String` whose value cannot be set to null. Facets allow you to specify this level of detail. + + The table below describes the facets that are supported in the EDM. + > [!NOTE] -> The exact values and behaviors of facets are determined by the run-time environment that uses an EDM implementation. - -|Facet|Description|Applies to| -|-----------|-----------------|----------------| -|`Collation`|Specifies the collating sequence (or sorting sequence) to be used when performing comparison and ordering operations on values of the property.|`String`| -|`ConcurrencyMode`|Indicates that the value of the property should be used for optimistic concurrency checks.|All primitive type properties| -|`Default`|Specifies the default value of the property if no value is supplied upon instantiation.|All primitive type properties| -|`FixedLength`|Specifies whether the length of the property value can vary.|`Binary`, `String`| -|`MaxLength`|Specifies the maximum length of the property value.|`Binary`, `String`| -|`Nullable`|Specifies whether the property can have a null value.|All primitive type properties| -|`Precision`|For properties of type `Decimal`, specifies the number of digits a property value can have. For properties of type `Time`, `DateTime`, and `DateTimeOffset`, specifies the number of digits for the fractional part of seconds of the property value.|`DateTime`, `DateTimeOffset`, `Decimal`, `Time`,| -|`Scale`|Specifies the number of digits to the right of the decimal point for the property value.|Decimal| -|`Unicode`|Indicates whether the property value is stored as Unicode.|`String`| - -## Example - - The [ADO.NET Entity Framework](./ef/index.md) uses a domain-specific language (DSL) called conceptual schema definition language ([CSDL](/ef/ef6/modeling/designer/advanced/edmx/csdl-spec)) to define conceptual models. The following CSDL defines a `Book` entity type. Note that facets are implemented as XML attributes. The facet values indicate that no property can be set to null, and that the `Scale` and `Precision` of the `Revision` property are each set to 29. - - [!code-xml[EDM_Example_Model#EntityExample](../../../../samples/snippets/xml/VS_Snippets_Data/edm_example_model/xml/books.edmx#entityexample)] - +> The exact values and behaviors of facets are determined by the runtime environment that uses an EDM implementation. + +|Facet|Description|Applies to| +|-----------|-----------------|----------------| +|`Collation`|Specifies the collating sequence (or sorting sequence) to be used when performing comparison and ordering operations on values of the property.|`String`| +|`ConcurrencyMode`|Indicates that the value of the property should be used for optimistic concurrency checks.|All primitive type properties| +|`Default`|Specifies the default value of the property if no value is supplied upon instantiation.|All primitive type properties| +|`FixedLength`|Specifies whether the length of the property value can vary.|`Binary`, `String`| +|`MaxLength`|Specifies the maximum length of the property value.|`Binary`, `String`| +|`Nullable`|Specifies whether the property can have a null value.|All primitive type properties| +|`Precision`|For properties of type `Decimal`, specifies the number of digits a property value can have. For properties of type `Time`, `DateTime`, and `DateTimeOffset`, specifies the number of digits for the fractional part of seconds of the property value.|`DateTime`, `DateTimeOffset`, `Decimal`, `Time`,| +|`Scale`|Specifies the number of digits to the right of the decimal point for the property value.|Decimal| +|`Unicode`|Indicates whether the property value is stored as Unicode.|`String`| + +## Example + + The [ADO.NET Entity Framework](./ef/index.md) uses a domain-specific language (DSL) called conceptual schema definition language ([CSDL](/ef/ef6/modeling/designer/advanced/edmx/csdl-spec)) to define conceptual models. The following CSDL defines a `Book` entity type. Note that facets are implemented as XML attributes. The facet values indicate that no property can be set to null, and that the `Scale` and `Precision` of the `Revision` property are each set to 29. + + [!code-xml[EDM_Example_Model#EntityExample](../../../../samples/snippets/xml/VS_Snippets_Data/edm_example_model/xml/books.edmx#entityexample)] + ## See also - [Entity Data Model Key Concepts](entity-data-model-key-concepts.md) diff --git a/docs/framework/data/adonet/factory-model-overview.md b/docs/framework/data/adonet/factory-model-overview.md index 15e0eb8416f28..40fdc44bd20c0 100644 --- a/docs/framework/data/adonet/factory-model-overview.md +++ b/docs/framework/data/adonet/factory-model-overview.md @@ -6,16 +6,16 @@ ms.assetid: b5dc81c4-7554-44b9-b513-769bd61e2e7b --- # Factory Model Overview -ADO.NET 2.0 introduced new base classes in the namespace. The base classes are abstract, which means that they can't be directly instantiated. They include , , and and are shared by the .NET Framework data providers, such as and . The addition of base classes simplifies adding functionality to the .NET Framework data providers without having to create new interfaces. - - ADO.NET 2.0 also introduced abstract base classes, which enable a developer to write generic data access code that does not depend on a specific data provider. - -## The Factory Design Pattern +ADO.NET 2.0 introduced new base classes in the namespace. The base classes are abstract, which means that they can't be directly instantiated. They include , , and and are shared by the .NET Framework data providers, such as and . The addition of base classes simplifies adding functionality to the .NET Framework data providers without having to create new interfaces. + + ADO.NET 2.0 also introduced abstract base classes, which enable a developer to write generic data access code that does not depend on a specific data provider. + +## The Factory Design Pattern The programming model for writing provider-independent code is based on the use of the "factory" design pattern, which uses a single API to access databases across multiple providers. This pattern is aptly named, as it calls for the use of a specialized object solely to create other objects, much like a real-world factory. For a more detailed description of the factory design pattern, see [Writing Generic Data Access Code in ASP.NET 2.0 and ADO.NET 2.0](/previous-versions/dotnet/articles/ms971499(v=msdn.10)). - - Starting with ADO.NET 2.0, the class provides `static` (or `Shared` in Visual Basic) methods for creating a instance. The instance then returns a correct strongly typed object based on provider information and the connection string supplied at run time. - + + Starting with ADO.NET 2.0, the class provides `static` (or `Shared` in Visual Basic) methods for creating a instance. The instance then returns a correct strongly typed object based on provider information and the connection string supplied at runtime. + ## See also - [Obtaining a DbProviderFactory](obtaining-a-dbproviderfactory.md) diff --git a/docs/framework/data/adonet/generating-commands-with-commandbuilders.md b/docs/framework/data/adonet/generating-commands-with-commandbuilders.md index 46ca339e6085f..cdea1a52c09f9 100644 --- a/docs/framework/data/adonet/generating-commands-with-commandbuilders.md +++ b/docs/framework/data/adonet/generating-commands-with-commandbuilders.md @@ -9,7 +9,7 @@ ms.assetid: 6e3fb8b5-373b-4f9e-ab03-a22693df8e91 --- # Generating Commands with CommandBuilders -When the `SelectCommand` property is dynamically specified at run time, such as through a query tool that takes a textual command from the user, you may not be able to specify the appropriate `InsertCommand`, `UpdateCommand`, or `DeleteCommand` at design time. If your maps to or is generated from a single database table, you can take advantage of the object to automatically generate the `DeleteCommand`, `InsertCommand`, and `UpdateCommand` of the . +When the `SelectCommand` property is dynamically specified at runtime, such as through a query tool that takes a textual command from the user, you may not be able to specify the appropriate `InsertCommand`, `UpdateCommand`, or `DeleteCommand` at design time. If your maps to or is generated from a single database table, you can take advantage of the object to automatically generate the `DeleteCommand`, `InsertCommand`, and `UpdateCommand` of the . As a minimum requirement, you must set the `SelectCommand` property in order for automatic command generation to work. The table schema retrieved by the `SelectCommand` property determines the syntax of the automatically generated INSERT, UPDATE, and DELETE statements. diff --git a/docs/framework/data/adonet/generic-field-and-setfield-methods-linq-to-dataset.md b/docs/framework/data/adonet/generic-field-and-setfield-methods-linq-to-dataset.md index de98df8a6783e..63751704dcf1d 100644 --- a/docs/framework/data/adonet/generic-field-and-setfield-methods-linq-to-dataset.md +++ b/docs/framework/data/adonet/generic-field-and-setfield-methods-linq-to-dataset.md @@ -2,29 +2,29 @@ description: "Learn more about: Generic Field and SetField Methods (LINQ to DataSet)" title: "Generic Field and SetField Methods (LINQ to DataSet)" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 1883365f-9d6c-4ccb-9187-df309f47706d --- # Generic Field and SetField Methods (LINQ to DataSet) -LINQ to DataSet provides extension methods to the class for accessing column values: the method and the method. These methods provide easier access to column values for developers, especially regarding null values. The uses to represent null values, whereas LINQ uses the and types. Using the pre-existing column accessor in requires you to cast the return object to the appropriate type. If a particular field in a can be null, you must explicitly check for a null value because returning and implicitly casting it to another type throws an . In the following example, if the method was not used to check for a null value, an exception would be thrown if the indexer returned and tried to cast it to a . - +LINQ to DataSet provides extension methods to the class for accessing column values: the method and the method. These methods provide easier access to column values for developers, especially regarding null values. The uses to represent null values, whereas LINQ uses the and types. Using the pre-existing column accessor in requires you to cast the return object to the appropriate type. If a particular field in a can be null, you must explicitly check for a null value because returning and implicitly casting it to another type throws an . In the following example, if the method was not used to check for a null value, an exception would be thrown if the indexer returned and tried to cast it to a . + [!code-csharp[DP LINQ to DataSet Examples#WhereIsNull](../../../../samples/snippets/csharp/VS_Snippets_ADO.NET/DP LINQ to DataSet Examples/CS/Program.cs#whereisnull)] - [!code-vb[DP LINQ to DataSet Examples#WhereIsNull](../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DP LINQ to DataSet Examples/VB/Module1.vb#whereisnull)] - - The method provides access to the column values of a and the sets column values in a . Both the method and method handle nullable value types, so you do not have to explicitly check for null values as in the previous example. Both methods are generic methods, also, so you do not have to cast the return type. - - The following example uses the method. - + [!code-vb[DP LINQ to DataSet Examples#WhereIsNull](../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DP LINQ to DataSet Examples/VB/Module1.vb#whereisnull)] + + The method provides access to the column values of a and the sets column values in a . Both the method and method handle nullable value types, so you do not have to explicitly check for null values as in the previous example. Both methods are generic methods, also, so you do not have to cast the return type. + + The following example uses the method. + [!code-csharp[DP LINQ to DataSet Examples#Where3](../../../../samples/snippets/csharp/VS_Snippets_ADO.NET/DP LINQ to DataSet Examples/CS/Program.cs#where3)] - [!code-vb[DP LINQ to DataSet Examples#Where3](../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DP LINQ to DataSet Examples/VB/Module1.vb#where3)] - - Note that the data type specified in the generic parameter `T` of the method and the method must match the type of the underlying value. Otherwise, an exception will be thrown. The specified column name must also match the name of a column in the , or an will be thrown. In both cases, the exception is thrown at run time during the enumeration of the data when the query is executed. - - The method itself does not perform any type conversions. This does not mean, however, that a type conversion will not occur. The method exposes the ADO.NET behavior of the class. A type conversion could be performed by the object and the converted value would then be saved to the object. - + [!code-vb[DP LINQ to DataSet Examples#Where3](../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DP LINQ to DataSet Examples/VB/Module1.vb#where3)] + + Note that the data type specified in the generic parameter `T` of the method and the method must match the type of the underlying value. Otherwise, an exception will be thrown. The specified column name must also match the name of a column in the , or an will be thrown. In both cases, the exception is thrown at runtime during the enumeration of the data when the query is executed. + + The method itself does not perform any type conversions. This does not mean, however, that a type conversion will not occur. The method exposes the ADO.NET behavior of the class. A type conversion could be performed by the object and the converted value would then be saved to the object. + ## See also - diff --git a/docs/framework/data/adonet/obtaining-a-dbproviderfactory.md b/docs/framework/data/adonet/obtaining-a-dbproviderfactory.md index 63936d65b4328..368a3a29f99d5 100644 --- a/docs/framework/data/adonet/obtaining-a-dbproviderfactory.md +++ b/docs/framework/data/adonet/obtaining-a-dbproviderfactory.md @@ -30,7 +30,7 @@ The process of obtaining a involves ``` - The `invariant` attribute identifies the underlying data provider. This three-part naming syntax is also used when creating a new factory and for identifying the provider in an application configuration file so that the provider name, along with its associated connection string, can be retrieved at run time. + The `invariant` attribute identifies the underlying data provider. This three-part naming syntax is also used when creating a new factory and for identifying the provider in an application configuration file so that the provider name, along with its associated connection string, can be retrieved at runtime. ## Retrieving Provider Information @@ -43,7 +43,7 @@ The process of obtaining a involves | 2 | `InvariantName` | System.Data.SqlClient | Name that can be used programmatically to refer to the data provider| | 3 | `AssemblyQualifiedName` | System.Data.SqlClient.SqlClientFactory, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 | Fully qualified name of the factory class, which contains enough information to instantiate the object | - This `DataTable` can be used to enable a user to select a at run time. The selected `DataRow` can then be passed to the method to create a strongly typed . A selected can be passed to the `GetFactory` method to create the desired `DbProviderFactory` object. + This `DataTable` can be used to enable a user to select a at runtime. The selected `DataRow` can then be passed to the method to create a strongly typed . A selected can be passed to the `GetFactory` method to create the desired `DbProviderFactory` object. ## Listing the Installed Provider Factory Classes diff --git a/docs/framework/data/adonet/protecting-connection-information.md b/docs/framework/data/adonet/protecting-connection-information.md index 250e8598b437b..ad3670876083a 100644 --- a/docs/framework/data/adonet/protecting-connection-information.md +++ b/docs/framework/data/adonet/protecting-connection-information.md @@ -7,7 +7,7 @@ ms.date: "03/30/2017" Protecting access to your data source is one of the most important goals when securing an application. A connection string presents a potential vulnerability if it isn't secured. Storing connection information in plain text or persisting it in memory risks compromising your entire system. Connection strings embedded in your source code can be read using the [Ildasm.exe (IL Disassembler)](../../tools/ildasm-exe-il-disassembler.md) to view common intermediate language (CIL) in a compiled assembly. -Security vulnerabilities involving connection strings can arise based on the type of authentication used, how connection strings are persisted in memory and on disk, and the techniques used to construct them at run time. +Security vulnerabilities involving connection strings can arise based on the type of authentication used, how connection strings are persisted in memory and on disk, and the techniques used to construct them at runtime. [!INCLUDE [managed-identities](../../../includes/managed-identities.md)] diff --git a/docs/framework/data/adonet/querying-typed-datasets.md b/docs/framework/data/adonet/querying-typed-datasets.md index 02e854c337531..56c3ad23b4951 100644 --- a/docs/framework/data/adonet/querying-typed-datasets.md +++ b/docs/framework/data/adonet/querying-typed-datasets.md @@ -11,7 +11,7 @@ ms.assetid: ad712fa1-2baf-462a-b163-574cce6d376a If the schema of the is known at application design time, we recommend that you use a typed when using LINQ to DataSet. A typed is a class that derives from a . As such, it inherits all the methods, events, and properties of a . Additionally, a typed provides strongly typed methods, events, and properties. This means that you can access tables and columns by name, instead of using collection-based methods. This makes queries simpler and more readable. For more information, see [Typed DataSets](./dataset-datatable-dataview/typed-datasets.md). -LINQ to DataSet also supports querying over a typed . With a typed , you do not have to use the generic method or method to access column data. Property names are available at compile time because the type information is included in the . LINQ to DataSet provides access to column values as the correct type, so that type mismatch errors are caught when the code is compiled instead of at run time. +LINQ to DataSet also supports querying over a typed . With a typed , you do not have to use the generic method or method to access column data. Property names are available at compile time because the type information is included in the . LINQ to DataSet provides access to column values as the correct type, so that type mismatch errors are caught when the code is compiled instead of at runtime. Before you can begin querying a typed , you must generate the class by using the **DataSet Designer** in Visual Studio. For more information, see [Create and configure DataSets](/visualstudio/data-tools/create-and-configure-datasets-in-visual-studio). diff --git a/docs/framework/data/adonet/secure-data-access.md b/docs/framework/data/adonet/secure-data-access.md index 050b56cf8a7b5..7952c8696f701 100644 --- a/docs/framework/data/adonet/secure-data-access.md +++ b/docs/framework/data/adonet/secure-data-access.md @@ -11,7 +11,7 @@ To write secure ADO.NET code, you have to understand the security mechanisms ava ## Authentication, Authorization, and Permissions -When connecting to Microsoft SQL Server, you can use Windows Authentication, also known as Integrated Security, which uses the identity of the current active Windows user rather than passing a user ID and password. Using Windows Authentication is recommended for on-premises databases because user credentials aren't exposed in the connection string. If you can't use Windows Authentication to connect to SQL Server, then consider creating connection strings at run time using the . +When connecting to Microsoft SQL Server, you can use Windows Authentication, also known as Integrated Security, which uses the identity of the current active Windows user rather than passing a user ID and password. Using Windows Authentication is recommended for on-premises databases because user credentials aren't exposed in the connection string. If you can't use Windows Authentication to connect to SQL Server, then consider creating connection strings at runtime using the . [!INCLUDE [managed-identities](../../../includes/managed-identities.md)] @@ -24,7 +24,7 @@ When connecting to Microsoft SQL Server, you can use Windows Authentication, als |Resource|Description| |--------------|-----------------| |[Protecting Connection Information](protecting-connection-information.md)|Describes security best practices and techniques for protecting connection information, such as using protected configuration to encrypt connection strings.| -|[Connection String Builders](connection-string-builders.md)|Describes how to build connection strings from user input at run time.| +|[Connection String Builders](connection-string-builders.md)|Describes how to build connection strings from user input at runtime.| |[Security for SQL Server Database Engine and Azure SQL Database](/sql/relational-databases/security/security-center-for-sql-server-database-engine-and-azure-sql-database)|Provides links to help you locate information about security and protection in the SQL Server Database Engine and Azure SQL Database.| ## Parameterized Commands and SQL Injection diff --git a/docs/framework/data/adonet/security-overview.md b/docs/framework/data/adonet/security-overview.md index f7b9f653d9b7d..fab5742438563 100644 --- a/docs/framework/data/adonet/security-overview.md +++ b/docs/framework/data/adonet/security-overview.md @@ -58,7 +58,7 @@ Code access security (CAS) is a mechanism that helps limit the access that code - Enables code to demand that its callers possess a digital signature, thus allowing only callers from a particular organization or site to call the protected code. -- Enforces restrictions on code at run time by comparing the granted permissions of every caller on the call stack to the permissions that callers must have. +- Enforces restrictions on code at runtime by comparing the granted permissions of every caller on the call stack to the permissions that callers must have. To minimize the amount of damage that can occur if an attack succeeds, choose a security context for your code that grants access only to the resources it needs to get its work done and no more. diff --git a/docs/framework/data/adonet/single-table-queries-linq-to-dataset.md b/docs/framework/data/adonet/single-table-queries-linq-to-dataset.md index 3de552ce1a512..d34d7f6a99659 100644 --- a/docs/framework/data/adonet/single-table-queries-linq-to-dataset.md +++ b/docs/framework/data/adonet/single-table-queries-linq-to-dataset.md @@ -2,30 +2,30 @@ description: "Learn more about: Single-Table Queries (LINQ to DataSet)" title: "Single-Table Queries (LINQ to DataSet)" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 0b74bcf8-3f87-449f-bff7-6bcb0d69d212 --- # Single-Table Queries (LINQ to DataSet) -Language-Integrated Query (LINQ) queries work on data sources that implement the interface or the interface. The class does not implement either interface, so you must call the method if you want to use the as a source in the `From` clause of a LINQ query. - - The following example gets all the online orders from the SalesOrderHeader table and outputs the order ID, order date, and order number to the console. - - [!code-csharp[DP LINQ to DataSet Examples#Where1](../../../../samples/snippets/csharp/VS_Snippets_ADO.NET/DP LINQ to DataSet Examples/CS/Program.cs#where1)] +Language-Integrated Query (LINQ) queries work on data sources that implement the interface or the interface. The class does not implement either interface, so you must call the method if you want to use the as a source in the `From` clause of a LINQ query. + + The following example gets all the online orders from the SalesOrderHeader table and outputs the order ID, order date, and order number to the console. + + [!code-csharp[DP LINQ to DataSet Examples#Where1](../../../../samples/snippets/csharp/VS_Snippets_ADO.NET/DP LINQ to DataSet Examples/CS/Program.cs#where1)] [!code-vb[DP LINQ to DataSet Examples#Where1](../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DP LINQ to DataSet Examples/VB/Module1.vb#where1)] - - The local variable query is initialized with a query expression, which operates on one or more information sources by applying one or more query operators from either the standard query operators or, in the case of LINQ to DataSet, operators specific to the class. The query expression in the previous example uses two of the standard query operators: `Where` and `Select`. - - The `Where` clause filters the sequence based on a condition, in this case that the `OnlineOrderFlag` is set to `true`. The `Select` operator allocates and returns an enumerable object that captures the arguments passed to the operator. In this above example, an anonymous type is created with three properties: `SalesOrderID`, `OrderDate`, and `SalesOrderNumber`. The values of these three properties are set to the values of the `SalesOrderID`, `OrderDate`, and `SalesOrderNumber` columns from the `SalesOrderHeader` table. - - The `foreach` loop then enumerates the enumerable object returned by `Select` and yields the query results. Because query is an type, which implements , the evaluation of the query is deferred until the query variable is iterated over using the `foreach` loop. Deferred query evaluation allows queries to be kept as values that can be evaluated multiple times, each time yielding potentially different results. - - The method provides access to the column values of a and the (not shown in the previous example) sets column values in a . Both the method and method handle nullable value types, so you do not have to explicitly check for null values. Both methods are generic methods, also, which means you do not have to cast the return type. You could use the pre-existing column accessor in (for example, `o["OrderDate"]`), but doing so would require you to cast the return object to the appropriate type. If the column is a nullable value type you have to check if the value is null by using the method. For more information, see [Generic Field and SetField Methods](generic-field-and-setfield-methods-linq-to-dataset.md). - - Note that the data type specified in the generic parameter `T` of the method and method must match the type of the underlying value or an will be thrown. The specified column name must also match the name of a column in the or an will be thrown. In both cases, the exception is thrown at run time data enumeration when the query is executed. - + + The local variable query is initialized with a query expression, which operates on one or more information sources by applying one or more query operators from either the standard query operators or, in the case of LINQ to DataSet, operators specific to the class. The query expression in the previous example uses two of the standard query operators: `Where` and `Select`. + + The `Where` clause filters the sequence based on a condition, in this case that the `OnlineOrderFlag` is set to `true`. The `Select` operator allocates and returns an enumerable object that captures the arguments passed to the operator. In this above example, an anonymous type is created with three properties: `SalesOrderID`, `OrderDate`, and `SalesOrderNumber`. The values of these three properties are set to the values of the `SalesOrderID`, `OrderDate`, and `SalesOrderNumber` columns from the `SalesOrderHeader` table. + + The `foreach` loop then enumerates the enumerable object returned by `Select` and yields the query results. Because query is an type, which implements , the evaluation of the query is deferred until the query variable is iterated over using the `foreach` loop. Deferred query evaluation allows queries to be kept as values that can be evaluated multiple times, each time yielding potentially different results. + + The method provides access to the column values of a and the (not shown in the previous example) sets column values in a . Both the method and method handle nullable value types, so you do not have to explicitly check for null values. Both methods are generic methods, also, which means you do not have to cast the return type. You could use the pre-existing column accessor in (for example, `o["OrderDate"]`), but doing so would require you to cast the return object to the appropriate type. If the column is a nullable value type you have to check if the value is null by using the method. For more information, see [Generic Field and SetField Methods](generic-field-and-setfield-methods-linq-to-dataset.md). + + Note that the data type specified in the generic parameter `T` of the method and method must match the type of the underlying value or an will be thrown. The specified column name must also match the name of a column in the or an will be thrown. In both cases, the exception is thrown at runtime data enumeration when the query is executed. + ## See also - [Cross-Table Queries](cross-table-queries-linq-to-dataset.md) diff --git a/docs/framework/data/adonet/sql/date-and-time-data.md b/docs/framework/data/adonet/sql/date-and-time-data.md index 0140308da70df..e57d376d39bf5 100644 --- a/docs/framework/data/adonet/sql/date-and-time-data.md +++ b/docs/framework/data/adonet/sql/date-and-time-data.md @@ -221,7 +221,7 @@ command.Parameters.AddWithValue( _ ## Specifying Date and Time Values as Literals - You can specify date and time data types by using a variety of different literal string formats, which SQL Server then evaluates at run time, converting them to internal date/time structures. SQL Server recognizes date and time data that is enclosed in single quotation marks ('). The following examples demonstrate some formats: + You can specify date and time data types by using a variety of different literal string formats, which SQL Server then evaluates at runtime, converting them to internal date/time structures. SQL Server recognizes date and time data that is enclosed in single quotation marks ('). The following examples demonstrate some formats: - Alphabetic date formats, such as `'October 15, 2006'`. diff --git a/docs/framework/data/adonet/sql/enabling-query-notifications.md b/docs/framework/data/adonet/sql/enabling-query-notifications.md index eba20cfaad4a0..93a66a4d3ca34 100644 --- a/docs/framework/data/adonet/sql/enabling-query-notifications.md +++ b/docs/framework/data/adonet/sql/enabling-query-notifications.md @@ -2,90 +2,90 @@ description: "Learn more about: Enabling Query Notifications" title: "Enabling Query Notifications" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: a5333e19-8e55-4aa9-82dc-ca8745e516ed --- # Enabling Query Notifications -Applications that consume query notifications have a common set of requirements. Your data source must be correctly configured to support SQL query notifications, and the user must have the correct client-side and server-side permissions. - - To use query notifications you must: - -- Enable query notifications for your database. - -- Ensure that the user ID used to connect to the database has the necessary permissions. - -- Use a object to execute a valid SELECT statement with an associated notification object—either or . - -- Provide code to process the notification if the data being monitored changes. - -## Query Notifications Requirements +Applications that consume query notifications have a common set of requirements. Your data source must be correctly configured to support SQL query notifications, and the user must have the correct client-side and server-side permissions. + + To use query notifications you must: + +- Enable query notifications for your database. + +- Ensure that the user ID used to connect to the database has the necessary permissions. + +- Use a object to execute a valid SELECT statement with an associated notification object—either or . + +- Provide code to process the notification if the data being monitored changes. + +## Query Notifications Requirements Query notifications are supported only for SELECT statements that meet a list of specific requirements. The following table provides links to the Service Broker and Query Notifications documentation in the SQL Server docs. - - **SQL Server documentation** - -- [Creating a Query for Notification](/previous-versions/sql/sql-server-2008-r2/ms181122(v=sql.105)) - -- [Security Considerations for Service Broker](/previous-versions/sql/sql-server-2005/ms166059(v=sql.90)) - -- [Security and Protection (Service Broker)](/previous-versions/sql/sql-server-2008-r2/bb522911(v=sql.105)) - -- [Security Considerations for Notifications Services](/previous-versions/sql/sql-server-2005/ms172604(v=sql.90)) - -- [Query Notification Permissions](/previous-versions/sql/sql-server-2008-r2/ms188311(v=sql.105)) - -- [International Considerations for Service Broker](/previous-versions/sql/sql-server-2005/ms166028(v=sql.90)) - -- [Solution Design Considerations (Service Broker)](/previous-versions/sql/sql-server-2008-r2/bb522899(v=sql.105)) - -- [Service Broker Developer InfoCenter](/previous-versions/sql/sql-server-2008-r2/ms166100(v=sql.105)) - -- [Developer's Guide (Service Broker)](/previous-versions/sql/sql-server-2008-r2/bb522908(v=sql.105)) - -## Enabling Query Notifications to Run Sample Code - - To enable Service Broker on the **AdventureWorks** database by using SQL Server Management Studio, execute the following Transact-SQL statement: - - `ALTER DATABASE AdventureWorks SET ENABLE_BROKER;` - - For the query notification samples to run correctly, the following Transact-SQL statements must be executed on the database server. - + + **SQL Server documentation** + +- [Creating a Query for Notification](/previous-versions/sql/sql-server-2008-r2/ms181122(v=sql.105)) + +- [Security Considerations for Service Broker](/previous-versions/sql/sql-server-2005/ms166059(v=sql.90)) + +- [Security and Protection (Service Broker)](/previous-versions/sql/sql-server-2008-r2/bb522911(v=sql.105)) + +- [Security Considerations for Notifications Services](/previous-versions/sql/sql-server-2005/ms172604(v=sql.90)) + +- [Query Notification Permissions](/previous-versions/sql/sql-server-2008-r2/ms188311(v=sql.105)) + +- [International Considerations for Service Broker](/previous-versions/sql/sql-server-2005/ms166028(v=sql.90)) + +- [Solution Design Considerations (Service Broker)](/previous-versions/sql/sql-server-2008-r2/bb522899(v=sql.105)) + +- [Service Broker Developer InfoCenter](/previous-versions/sql/sql-server-2008-r2/ms166100(v=sql.105)) + +- [Developer's Guide (Service Broker)](/previous-versions/sql/sql-server-2008-r2/bb522908(v=sql.105)) + +## Enabling Query Notifications to Run Sample Code + + To enable Service Broker on the **AdventureWorks** database by using SQL Server Management Studio, execute the following Transact-SQL statement: + + `ALTER DATABASE AdventureWorks SET ENABLE_BROKER;` + + For the query notification samples to run correctly, the following Transact-SQL statements must be executed on the database server. + ```sql -CREATE QUEUE ContactChangeMessages; - -CREATE SERVICE ContactChangeNotifications - ON QUEUE ContactChangeMessages -([http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification]); -``` - -## Query Notifications Permissions - - Users who execute commands requesting notification must have SUBSCRIBE QUERY NOTIFICATIONS database permission on the server. - - Client-side code that runs in a partial trust situation requires the . - - The following code creates a object, setting the to . The will force a at run time if all callers higher in the call stack have not been granted the permission. - +CREATE QUEUE ContactChangeMessages; + +CREATE SERVICE ContactChangeNotifications + ON QUEUE ContactChangeMessages +([http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification]); +``` + +## Query Notifications Permissions + + Users who execute commands requesting notification must have SUBSCRIBE QUERY NOTIFICATIONS database permission on the server. + + Client-side code that runs in a partial trust situation requires the . + + The following code creates a object, setting the to . The will force a at runtime if all callers higher in the call stack have not been granted the permission. + [!code-csharp[DataWorks SqlNotification.Perms#1](../../../../../samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlNotification.Perms/CS/source.cs#1)] - [!code-vb[DataWorks SqlNotification.Perms#1](../../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlNotification.Perms/VB/source.vb#1)] - -## Choosing a Notification Object - - The query notifications API provides two objects to process notifications: and . In general, most non-ASP.NET applications should use the object. ASP.NET applications should use the higher-level , which wraps and provides a framework for administering the notification and cache objects. - -### Using SqlDependency - - To use , Service Broker must be enabled for the SQL Server database being used, and users must have permissions to receive notifications. Service Broker objects, such as the notification queue, are predefined. - - In addition, automatically launches a worker thread to process notifications as they are posted to the queue; it also parses the Service Broker message, exposing the information as event argument data. must be initialized by calling the `Start` method to establish a dependency to the database. This is a static method that needs to be called only once during application initialization for each database connection required. The `Stop` method should be called at application termination for each dependency connection that was made. - -### Using SqlNotificationRequest - - In contrast, requires you to implement the entire listening infrastructure yourself. In addition, all the supporting Service Broker objects such as the queue, service, and message types supported by the queue must be defined. This manual approach is useful if your application requires special notification messages or notification behaviors, or if your application is part of a larger Service Broker application. - + [!code-vb[DataWorks SqlNotification.Perms#1](../../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlNotification.Perms/VB/source.vb#1)] + +## Choosing a Notification Object + + The query notifications API provides two objects to process notifications: and . In general, most non-ASP.NET applications should use the object. ASP.NET applications should use the higher-level , which wraps and provides a framework for administering the notification and cache objects. + +### Using SqlDependency + + To use , Service Broker must be enabled for the SQL Server database being used, and users must have permissions to receive notifications. Service Broker objects, such as the notification queue, are predefined. + + In addition, automatically launches a worker thread to process notifications as they are posted to the queue; it also parses the Service Broker message, exposing the information as event argument data. must be initialized by calling the `Start` method to establish a dependency to the database. This is a static method that needs to be called only once during application initialization for each database connection required. The `Stop` method should be called at application termination for each dependency connection that was made. + +### Using SqlNotificationRequest + + In contrast, requires you to implement the entire listening infrastructure yourself. In addition, all the supporting Service Broker objects such as the queue, service, and message types supported by the queue must be defined. This manual approach is useful if your application requires special notification messages or notification behaviors, or if your application is part of a larger Service Broker application. + ## See also - [Query Notifications in SQL Server](query-notifications-in-sql-server.md) diff --git a/docs/framework/data/adonet/sql/linq/how-to-directly-execute-sql-queries.md b/docs/framework/data/adonet/sql/linq/how-to-directly-execute-sql-queries.md index 73a78dc50e5b9..9c261b4bafc59 100644 --- a/docs/framework/data/adonet/sql/linq/how-to-directly-execute-sql-queries.md +++ b/docs/framework/data/adonet/sql/linq/how-to-directly-execute-sql-queries.md @@ -2,37 +2,37 @@ title: "How to: Directly Execute SQL Queries" description: Learn how to use ExecuteQuery to run a query and then convert the results directly into objects in cases where a LINQ to SQL query is insufficient. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: e491b9bf-741a-4296-9f51-76c25ddf6a82 --- # How to: Directly Execute SQL Queries -[!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] translates the queries you write into parameterized SQL queries (in text form) and sends them to the SQL server for processing. - - SQL cannot execute the variety of methods that might be locally available to your application. [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] tries to convert these local methods to equivalent operations and functions that are available inside the SQL environment. Most methods and operators on .NET Framework built-in types have direct translations to SQL commands. Some can be produced from the functions that are available. Those that cannot be produced generate run-time exceptions. For more information, see [SQL-CLR Type Mapping](sql-clr-type-mapping.md). - - In cases where a [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] query is insufficient for a specialized task, you can use the method to execute a SQL query, and then convert the result of your query directly into objects. - +[!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] translates the queries you write into parameterized SQL queries (in text form) and sends them to the SQL server for processing. + + SQL cannot execute the variety of methods that might be locally available to your application. [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] tries to convert these local methods to equivalent operations and functions that are available inside the SQL environment. Most methods and operators on .NET Framework built-in types have direct translations to SQL commands. Some can be produced from the functions that are available. Those that cannot be produced generate runtime exceptions. For more information, see [SQL-CLR Type Mapping](sql-clr-type-mapping.md). + + In cases where a [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] query is insufficient for a specialized task, you can use the method to execute a SQL query, and then convert the result of your query directly into objects. + ## Example 1 - In the following example, assume that the data for the `Customer` class is spread over two tables (customer1 and customer2). The query returns a sequence of `Customer` objects. - + In the following example, assume that the data for the `Customer` class is spread over two tables (customer1 and customer2). The query returns a sequence of `Customer` objects. + [!code-csharp[DLinqQuerying#4](../../../../../../samples/snippets/csharp/VS_Snippets_Data/DLinqQuerying/cs/Program.cs#4)] - [!code-vb[DLinqQuerying#4](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DLinqQuerying/vb/Module1.vb#4)] - - As long as the column names in the tabular results match column properties of your entity class, [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] creates your objects out of any SQL query. - -## Example 2 - - The method also allows for parameters. Use code such as the following to execute a parameterized query. - + [!code-vb[DLinqQuerying#4](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DLinqQuerying/vb/Module1.vb#4)] + + As long as the column names in the tabular results match column properties of your entity class, [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] creates your objects out of any SQL query. + +## Example 2 + + The method also allows for parameters. Use code such as the following to execute a parameterized query. + [!code-csharp[DLinqQuerying#5](../../../../../../samples/snippets/csharp/VS_Snippets_Data/DLinqQuerying/cs/Program.cs#5)] - [!code-vb[DLinqQuerying#5](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DLinqQuerying/vb/Module1.vb#5)] - - The parameters are expressed in the query text by using the same curly notation used by `Console.WriteLine()` and `String.Format()`. In fact, `String.Format()` is actually called on the query string you provide, substituting the curly braced parameters with generated parameter names such as @p0, @p1 …, @p(n). - + [!code-vb[DLinqQuerying#5](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DLinqQuerying/vb/Module1.vb#5)] + + The parameters are expressed in the query text by using the same curly notation used by `Console.WriteLine()` and `String.Format()`. In fact, `String.Format()` is actually called on the query string you provide, substituting the curly braced parameters with generated parameter names such as @p0, @p1 …, @p(n). + ## See also - [Background Information](background-information.md) diff --git a/docs/framework/data/adonet/sql/linq/how-to-specify-which-members-are-tested-for-concurrency-conflicts.md b/docs/framework/data/adonet/sql/linq/how-to-specify-which-members-are-tested-for-concurrency-conflicts.md index c8fc80278ec53..0638126463c2c 100644 --- a/docs/framework/data/adonet/sql/linq/how-to-specify-which-members-are-tested-for-concurrency-conflicts.md +++ b/docs/framework/data/adonet/sql/linq/how-to-specify-which-members-are-tested-for-concurrency-conflicts.md @@ -2,47 +2,47 @@ description: "Learn more about: How to: Specify Which Members are Tested for Concurrency Conflicts" title: "How to: Specify Which Members are Tested for Concurrency Conflicts" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: d2cda293-1e2f-4878-af0e-5aaf0d092120 --- # How to: Specify Which Members are Tested for Concurrency Conflicts -Apply one of three enums to the [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] property on a attribute to specify which members are to be included in update checks for the detection of optimistic concurrency conflicts. - - The property (mapped at design time) is used together with run-time concurrency features in [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)]. For more information, see [Optimistic Concurrency: Overview](optimistic-concurrency-overview.md). - +Apply one of three enums to the [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] property on a attribute to specify which members are to be included in update checks for the detection of optimistic concurrency conflicts. + + The property (mapped at design time) is used together with runtime concurrency features in [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)]. For more information, see [Optimistic Concurrency: Overview](optimistic-concurrency-overview.md). + > [!NOTE] -> Original member values are compared with the current database state as long as no member is designated as `IsVersion=true`. For more information, see . - - For code examples, see . - -### To always use this member for detecting conflicts - -1. Add the property to the attribute. - -2. Set the property value to `Always`. - -### To never use this member for detecting conflicts - -1. Add the property to the attribute. - -2. Set the property value to `Never`. - -### To use this member for detecting conflicts only when the application has changed the value of the member - -1. Add the property to the attribute. - -2. Set the property value to `WhenChanged`. - -## Example - - The following example specifies that `HomePage` objects should never be tested during update checks. For more information, see . - +> Original member values are compared with the current database state as long as no member is designated as `IsVersion=true`. For more information, see . + + For code examples, see . + +### To always use this member for detecting conflicts + +1. Add the property to the attribute. + +2. Set the property value to `Always`. + +### To never use this member for detecting conflicts + +1. Add the property to the attribute. + +2. Set the property value to `Never`. + +### To use this member for detecting conflicts only when the application has changed the value of the member + +1. Add the property to the attribute. + +2. Set the property value to `WhenChanged`. + +## Example + + The following example specifies that `HomePage` objects should never be tested during update checks. For more information, see . + [!code-csharp[System.Data.Linq.Mapping.UpdateCheck#1](../../../../../../samples/snippets/csharp/VS_Snippets_Data/system.data.linq.mapping.updatecheck/cs/northwind.cs#1)] - [!code-vb[System.Data.Linq.Mapping.UpdateCheck#1](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/system.data.linq.mapping.updatecheck/vb/northwind.vb#1)] - + [!code-vb[System.Data.Linq.Mapping.UpdateCheck#1](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/system.data.linq.mapping.updatecheck/vb/northwind.vb#1)] + ## See also - [How to: Manage Change Conflicts](how-to-manage-change-conflicts.md) diff --git a/docs/framework/data/adonet/sql/linq/how-to-store-and-reuse-queries.md b/docs/framework/data/adonet/sql/linq/how-to-store-and-reuse-queries.md index 32323de0f772f..b00ef5856c5d3 100644 --- a/docs/framework/data/adonet/sql/linq/how-to-store-and-reuse-queries.md +++ b/docs/framework/data/adonet/sql/linq/how-to-store-and-reuse-queries.md @@ -2,35 +2,35 @@ description: "Learn more about: How to: Store and Reuse Queries" title: "How to: Store and Reuse Queries" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: a012bd79-1809-45e3-adea-0229532396cc --- # How to: Store and Reuse Queries -When you have an application that executes structurally similar queries many times, you can often increase performance by compiling the query one time and executing it several times with different parameters. For example, an application might have to retrieve all the customers who are in a particular city, where the city is specified at run time by the user in a form. [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] supports the use of *compiled queries* for this purpose. - +When you have an application that executes structurally similar queries many times, you can often increase performance by compiling the query one time and executing it several times with different parameters. For example, an application might have to retrieve all the customers who are in a particular city, where the city is specified at runtime by the user in a form. [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] supports the use of *compiled queries* for this purpose. + > [!NOTE] -> This pattern of usage represents the most common use for compiled queries. Other approaches are possible. For example, compiled queries can be stored as static members on a partial class that extends the code generated by the designer. - +> This pattern of usage represents the most common use for compiled queries. Other approaches are possible. For example, compiled queries can be stored as static members on a partial class that extends the code generated by the designer. + ## Example 1 - In many scenarios you might want to reuse the queries across thread boundaries. In such cases, storing the compiled queries in static variables is especially effective. The following code example assumes a `Queries` class designed to store compiled queries, and assumes a Northwind class that represents a strongly typed . - + In many scenarios you might want to reuse the queries across thread boundaries. In such cases, storing the compiled queries in static variables is especially effective. The following code example assumes a `Queries` class designed to store compiled queries, and assumes a Northwind class that represents a strongly typed . + [!code-csharp[DLinqQuerying#6](../../../../../../samples/snippets/csharp/VS_Snippets_Data/DLinqQuerying/cs/Program.cs#6)] - [!code-vb[DLinqQuerying#6](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DLinqQuerying/vb/Module1.vb#6)] - + [!code-vb[DLinqQuerying#6](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DLinqQuerying/vb/Module1.vb#6)] + [!code-csharp[DLinqQuerying#7](../../../../../../samples/snippets/csharp/VS_Snippets_Data/DLinqQuerying/cs/Program.cs#7)] - [!code-vb[DLinqQuerying#7](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DLinqQuerying/vb/Module1.vb#7)] - -## Example 2 + [!code-vb[DLinqQuerying#7](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DLinqQuerying/vb/Module1.vb#7)] + +## Example 2 + + You cannot currently store (in static variables) queries that return an *anonymous type*, because type has no name to provide as a generic argument. The following example shows how you can work around the issue by creating a type that can represent the result, and then use it as a generic argument. - You cannot currently store (in static variables) queries that return an *anonymous type*, because type has no name to provide as a generic argument. The following example shows how you can work around the issue by creating a type that can represent the result, and then use it as a generic argument. - [!code-csharp[DLinqQuerying#8](../../../../../../samples/snippets/csharp/VS_Snippets_Data/DLinqQuerying/cs/Program.cs#8)] - [!code-vb[DLinqQuerying#8](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DLinqQuerying/vb/Module1.vb#8)] - + [!code-vb[DLinqQuerying#8](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DLinqQuerying/vb/Module1.vb#8)] + ## See also - diff --git a/docs/framework/data/adonet/sql/linq/index.md b/docs/framework/data/adonet/sql/linq/index.md index a549434e0c2ee..50493df3916d9 100644 --- a/docs/framework/data/adonet/sql/linq/index.md +++ b/docs/framework/data/adonet/sql/linq/index.md @@ -1,55 +1,55 @@ --- title: "LINQ to SQL" -description: LINQ to SQL is a component of the .NET Framework that provides a run-time infrastructure for managing relational data as objects. +description: LINQ to SQL is a component of the .NET Framework that provides a runtime infrastructure for managing relational data as objects. ms.date: "03/30/2017" ms.assetid: 73d13345-eece-471a-af40-4cc7a2f11655 --- # LINQ to SQL -[!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] is a component of .NET Framework version 3.5 that provides a run-time infrastructure for managing relational data as objects. - +[!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] is a component of .NET Framework version 3.5 that provides a runtime infrastructure for managing relational data as objects. + > [!NOTE] -> Relational data appears as a collection of two-dimensional tables (*relations* or *flat files*), where common columns relate tables to each other. To use [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] effectively, you must have some familiarity with the underlying principles of relational databases. - - In [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)], the data model of a relational database is mapped to an object model expressed in the programming language of the developer. When the application runs, [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] translates into SQL the language-integrated queries in the object model and sends them to the database for execution. When the database returns the results, [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] translates them back to objects that you can work with in your own programming language. - - Developers using Visual Studio typically use the Object Relational Designer, which provides a user interface for implementing many of the features of [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)]. - - The documentation that is included with this release of [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] describes the basic building blocks, processes, and techniques you need for building [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] applications. You can also search Microsoft Docs for specific issues, and you can participate in the [LINQ Forum](https://social.msdn.microsoft.com/forums/home?forum=linqtosql), where you can discuss more complex topics in detail with experts. Finally, the [LINQ to SQL: .NET Language-Integrated Query for Relational Data](/previous-versions/dotnet/articles/bb425822(v=msdn.10)) white paper details [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] technology, complete with Visual Basic and C# code examples. - -## In This Section - - [Getting Started](getting-started.md) - Provides a condensed overview of [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] along with information about how to get started using [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)]. - - [Programming Guide](programming-guide.md) - Provides steps for mapping, querying, updating, debugging, and similar tasks. - - [Reference](reference.md) - Provides reference information about several aspects of [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)]. Topics include SQL-CLR Type Mapping, Standard Query Operator Translation, and more. - - [Samples](samples.md) - Provides links to Visual Basic and C# samples. - -## Related Sections +> Relational data appears as a collection of two-dimensional tables (*relations* or *flat files*), where common columns relate tables to each other. To use [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] effectively, you must have some familiarity with the underlying principles of relational databases. + + In [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)], the data model of a relational database is mapped to an object model expressed in the programming language of the developer. When the application runs, [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] translates into SQL the language-integrated queries in the object model and sends them to the database for execution. When the database returns the results, [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] translates them back to objects that you can work with in your own programming language. + + Developers using Visual Studio typically use the Object Relational Designer, which provides a user interface for implementing many of the features of [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)]. + + The documentation that is included with this release of [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] describes the basic building blocks, processes, and techniques you need for building [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] applications. You can also search Microsoft Docs for specific issues, and you can participate in the [LINQ Forum](https://social.msdn.microsoft.com/forums/home?forum=linqtosql), where you can discuss more complex topics in detail with experts. Finally, the [LINQ to SQL: .NET Language-Integrated Query for Relational Data](/previous-versions/dotnet/articles/bb425822(v=msdn.10)) white paper details [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] technology, complete with Visual Basic and C# code examples. + +## In This Section + + [Getting Started](getting-started.md) + Provides a condensed overview of [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] along with information about how to get started using [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)]. + + [Programming Guide](programming-guide.md) + Provides steps for mapping, querying, updating, debugging, and similar tasks. + + [Reference](reference.md) + Provides reference information about several aspects of [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)]. Topics include SQL-CLR Type Mapping, Standard Query Operator Translation, and more. + + [Samples](samples.md) + Provides links to Visual Basic and C# samples. + +## Related Sections [Language-Integrated Query (LINQ) - C#](../../../../../csharp/linq/index.md)\ Provides overviews of LINQ technologies in C#. - [Language-Integrated Query (LINQ) - Visual Basic](../../../../../visual-basic/programming-guide/concepts/linq/index.md) + [Language-Integrated Query (LINQ) - Visual Basic](../../../../../visual-basic/programming-guide/concepts/linq/index.md) Provides overviews of LINQ technologies in Visual Basic. - - [LINQ](../../../../../visual-basic/programming-guide/language-features/linq/index.md) - Describes LINQ technologies for Visual Basic users. - - [LINQ and ADO.NET](../../linq-and-ado-net.md) - Links to the ADO.NET portal. - - [LINQ to SQL Walkthroughs](/previous-versions/visualstudio/visual-studio-2008/bb386295(v=vs.90)) - Lists walkthroughs available for [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)]. - - [Downloading Sample Databases](downloading-sample-databases.md) - Describes how to download sample databases used in the documentation. - - [LinqDataSource Web Server Control Overview](/previous-versions/aspnet/bb547113(v=vs.100)) + + [LINQ](../../../../../visual-basic/programming-guide/language-features/linq/index.md) + Describes LINQ technologies for Visual Basic users. + + [LINQ and ADO.NET](../../linq-and-ado-net.md) + Links to the ADO.NET portal. + + [LINQ to SQL Walkthroughs](/previous-versions/visualstudio/visual-studio-2008/bb386295(v=vs.90)) + Lists walkthroughs available for [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)]. + + [Downloading Sample Databases](downloading-sample-databases.md) + Describes how to download sample databases used in the documentation. + + [LinqDataSource Web Server Control Overview](/previous-versions/aspnet/bb547113(v=vs.100)) Describes how the control exposes Language-Integrated Query (LINQ) to Web developers through the ASP.NET data-source control architecture. diff --git a/docs/framework/data/adonet/sql/linq/learning-by-walkthroughs.md b/docs/framework/data/adonet/sql/linq/learning-by-walkthroughs.md index 26190cd6fa0c8..41ee6be5a85f2 100644 --- a/docs/framework/data/adonet/sql/linq/learning-by-walkthroughs.md +++ b/docs/framework/data/adonet/sql/linq/learning-by-walkthroughs.md @@ -6,89 +6,89 @@ ms.assetid: a8ae2965-6a49-4155-89b0-7fab2c488ab1 --- # Learning by Walkthroughs -The [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] documentation provides several walkthroughs. This topic addresses some general walkthrough issues (including troubleshooting), and provides links to several entry-level walkthroughs for learning about [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)]. - +The [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] documentation provides several walkthroughs. This topic addresses some general walkthrough issues (including troubleshooting), and provides links to several entry-level walkthroughs for learning about [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)]. + > [!NOTE] -> The walkthroughs in this Getting Started section expose you to the basic code that supports [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] technology. In actual practice, you will typically use the Object Relational Designer and Windows Forms projects to implement your [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] applications. The O/R Designer documentation provides examples and walkthroughs for this purpose. - -## Getting Started Walkthroughs - - Several walkthroughs are available in this section. These walkthroughs are based on the sample Northwind database, and present [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] features at a gentle pace with minimal complexities. - - A typical progression to follow would be as follows: - -|Objective|Visual Basic|C#| -|---------------|------------------|---------| -|Create an entity class and execute a simple query.|[Walkthrough: Simple Object Model and Query (Visual Basic)](walkthrough-simple-object-model-and-query-visual-basic.md)|[Walkthrough: Simple Object Model and Query (C#)](walkthrough-simple-object-model-and-query-csharp.md)| -|Add a second class and execute a more complex query.

(Requires completion of previous walkthrough).|[Walkthrough: Querying Across Relationships (Visual Basic)](walkthrough-querying-across-relationships-visual-basic.md)|[Walkthrough: Querying Across Relationships (C#)](walkthrough-querying-across-relationships-csharp.md)| -|Add, change, and delete items in the database.|[Walkthrough: Manipulating Data (Visual Basic)](walkthrough-manipulating-data-visual-basic.md)|[Walkthrough: Manipulating Data (C#)](walkthrough-manipulating-data-csharp.md)| -|Use stored procedures.|[Walkthrough: Using Only Stored Procedures (Visual Basic)](walkthrough-using-only-stored-procedures-visual-basic.md)|[Walkthrough: Using Only Stored Procedures (C#)](walkthrough-using-only-stored-procedures-csharp.md)| - -## General - - The following information pertains to these walkthroughs in general: - -- Environment: Each [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] walkthrough uses Visual Studio as its integrated development environment (IDE). - -- SQL engines: These walkthroughs are written to be implemented by using SQL Server Express. If you do not have SQL Server Express, you can download it free of charge. For more information, see [Downloading Sample Databases](downloading-sample-databases.md). - +> The walkthroughs in this Getting Started section expose you to the basic code that supports [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] technology. In actual practice, you will typically use the Object Relational Designer and Windows Forms projects to implement your [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] applications. The O/R Designer documentation provides examples and walkthroughs for this purpose. + +## Getting Started Walkthroughs + + Several walkthroughs are available in this section. These walkthroughs are based on the sample Northwind database, and present [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] features at a gentle pace with minimal complexities. + + A typical progression to follow would be as follows: + +|Objective|Visual Basic|C#| +|---------------|------------------|---------| +|Create an entity class and execute a simple query.|[Walkthrough: Simple Object Model and Query (Visual Basic)](walkthrough-simple-object-model-and-query-visual-basic.md)|[Walkthrough: Simple Object Model and Query (C#)](walkthrough-simple-object-model-and-query-csharp.md)| +|Add a second class and execute a more complex query.

(Requires completion of previous walkthrough).|[Walkthrough: Querying Across Relationships (Visual Basic)](walkthrough-querying-across-relationships-visual-basic.md)|[Walkthrough: Querying Across Relationships (C#)](walkthrough-querying-across-relationships-csharp.md)| +|Add, change, and delete items in the database.|[Walkthrough: Manipulating Data (Visual Basic)](walkthrough-manipulating-data-visual-basic.md)|[Walkthrough: Manipulating Data (C#)](walkthrough-manipulating-data-csharp.md)| +|Use stored procedures.|[Walkthrough: Using Only Stored Procedures (Visual Basic)](walkthrough-using-only-stored-procedures-visual-basic.md)|[Walkthrough: Using Only Stored Procedures (C#)](walkthrough-using-only-stored-procedures-csharp.md)| + +## General + + The following information pertains to these walkthroughs in general: + +- Environment: Each [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] walkthrough uses Visual Studio as its integrated development environment (IDE). + +- SQL engines: These walkthroughs are written to be implemented by using SQL Server Express. If you do not have SQL Server Express, you can download it free of charge. For more information, see [Downloading Sample Databases](downloading-sample-databases.md). + > [!NOTE] - > [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] walkthroughs use a file name as a connection string. Simply specifying a file name is a convenience that [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] provides for SQL Server Express users. Always pay attention to security issues. For more information, see [Security in LINQ to SQL](security-in-linq-to-sql.md). - -- [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] walkthroughs typically require the Northwind sample database. For more information, see [Downloading Sample Databases](downloading-sample-databases.md). - -- The dialog boxes and menu commands you see in walkthroughs might differ from those described in Help, depending on your active settings or Visual Studio edition. To change your settings, click **Import and Export Settings** on the **Tools** menu. For more information, see [Personalize the Visual Studio IDE](/visualstudio/ide/personalizing-the-visual-studio-ide). - -- For walkthroughs that address multi-tier scenarios, a server must be located on a computer that is distinct from the development computer, and you must have appropriate permissions to access the server. - -- The name of the class that typically represents the Orders table in the Northwind sample database is `[Order]`. The escaping is required because `Order` is a keyword in Visual Basic. - -## Troubleshooting - - Run-time errors can occur because you do not have sufficient permissions to access the databases used in these walkthroughs. See the following steps to help resolve the most common of these issues. - -### Log-On Issues - - Your application might be trying to access the database by way of a database logon it does not accept. - -##### To verify or change the database log on - -1. On the Windows **Start** menu, point to **All Programs**, **Microsoft SQL Server 2005**, point to **Configuration Tools**, and then click **SQL Server Configuration Manager**. - -2. In the left pane of the **SQL Server Configuration Manager**, click **SQL Server 2005 Services**. - -3. In the right pane, right-click **SQL Server (SQLEXPRESS)**, and then click **Properties**. - -4. Click the **Log On** tab and verify how you are trying to log on to the server. - - In most cases, **Local System** works. - - If you make a change, click **Restart** to restart the service. - -### Protocols - - At times, protocols might not be set correctly for your application to access the database. For example, the **Named Pipes** protocol, which is required for walkthroughs in [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)], is not enabled by default. - -##### To enable the Named Pipes protocol - -1. In the left pane of the **SQL Server Configuration Manager**, expand **SQL Server 2005 Network Configuration**, and then click **Protocols for SQLEXPRESS**. - -2. In the right pane, make sure that the **Named Pipes** protocol is enabled. If it is not, right-click **Name Pipes** and then click **Enable**. - - You will have to stop and restart the service. Follow the steps in the next block. - -### Stopping and Restarting the Service - - You must stop and restart services before your changes can take effect. - -##### To stop and restart the service - -1. In the left pane of the **SQL Server Configuration Manager**, click **SQL Server 2005 Services**. - -2. In the right pane, right-click **SQL Server (SQLEXPRESS)**, and then click **Stop**. - -3. Right-click **SQL Server (SQLEXPRESS)**, and then click **Restart**. - + > [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] walkthroughs use a file name as a connection string. Simply specifying a file name is a convenience that [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] provides for SQL Server Express users. Always pay attention to security issues. For more information, see [Security in LINQ to SQL](security-in-linq-to-sql.md). + +- [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] walkthroughs typically require the Northwind sample database. For more information, see [Downloading Sample Databases](downloading-sample-databases.md). + +- The dialog boxes and menu commands you see in walkthroughs might differ from those described in Help, depending on your active settings or Visual Studio edition. To change your settings, click **Import and Export Settings** on the **Tools** menu. For more information, see [Personalize the Visual Studio IDE](/visualstudio/ide/personalizing-the-visual-studio-ide). + +- For walkthroughs that address multi-tier scenarios, a server must be located on a computer that is distinct from the development computer, and you must have appropriate permissions to access the server. + +- The name of the class that typically represents the Orders table in the Northwind sample database is `[Order]`. The escaping is required because `Order` is a keyword in Visual Basic. + +## Troubleshooting + + Runtime errors can occur because you do not have sufficient permissions to access the databases used in these walkthroughs. See the following steps to help resolve the most common of these issues. + +### Log-On Issues + + Your application might be trying to access the database by way of a database logon it does not accept. + +##### To verify or change the database log on + +1. On the Windows **Start** menu, point to **All Programs**, **Microsoft SQL Server 2005**, point to **Configuration Tools**, and then click **SQL Server Configuration Manager**. + +2. In the left pane of the **SQL Server Configuration Manager**, click **SQL Server 2005 Services**. + +3. In the right pane, right-click **SQL Server (SQLEXPRESS)**, and then click **Properties**. + +4. Click the **Log On** tab and verify how you are trying to log on to the server. + + In most cases, **Local System** works. + + If you make a change, click **Restart** to restart the service. + +### Protocols + + At times, protocols might not be set correctly for your application to access the database. For example, the **Named Pipes** protocol, which is required for walkthroughs in [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)], is not enabled by default. + +##### To enable the Named Pipes protocol + +1. In the left pane of the **SQL Server Configuration Manager**, expand **SQL Server 2005 Network Configuration**, and then click **Protocols for SQLEXPRESS**. + +2. In the right pane, make sure that the **Named Pipes** protocol is enabled. If it is not, right-click **Name Pipes** and then click **Enable**. + + You will have to stop and restart the service. Follow the steps in the next block. + +### Stopping and Restarting the Service + + You must stop and restart services before your changes can take effect. + +##### To stop and restart the service + +1. In the left pane of the **SQL Server Configuration Manager**, click **SQL Server 2005 Services**. + +2. In the right pane, right-click **SQL Server (SQLEXPRESS)**, and then click **Stop**. + +3. Right-click **SQL Server (SQLEXPRESS)**, and then click **Restart**. + ## See also - [Getting Started](getting-started.md) diff --git a/docs/framework/data/adonet/sql/linq/linq-to-sql-queries.md b/docs/framework/data/adonet/sql/linq/linq-to-sql-queries.md index 44cea087ebef4..2a1da68fa3a4c 100644 --- a/docs/framework/data/adonet/sql/linq/linq-to-sql-queries.md +++ b/docs/framework/data/adonet/sql/linq/linq-to-sql-queries.md @@ -6,27 +6,27 @@ ms.assetid: f4897aaa-7f44-4c20-a471-b948c2971aae --- # LINQ to SQL Queries -You define [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] queries by using the same syntax as you would in LINQ. The only difference is that the objects referenced in your queries are mapped to elements in a database. For more information, see [Introduction to LINQ Queries (C#)](../../../../../csharp/linq/get-started/introduction-to-linq-queries.md). - - [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] translates the queries you write into equivalent SQL queries and sends them to the server for processing. More specifically, your application uses the [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] API to request query execution. The [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] provider then transforms the query into SQL text and delegates execution to the ADO provider. The ADO provider returns query results as a `DataReader`. The [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] provider translates the ADO results to an collection of user objects. - +You define [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] queries by using the same syntax as you would in LINQ. The only difference is that the objects referenced in your queries are mapped to elements in a database. For more information, see [Introduction to LINQ Queries (C#)](../../../../../csharp/linq/get-started/introduction-to-linq-queries.md). + + [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] translates the queries you write into equivalent SQL queries and sends them to the server for processing. More specifically, your application uses the [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] API to request query execution. The [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] provider then transforms the query into SQL text and delegates execution to the ADO provider. The ADO provider returns query results as a `DataReader`. The [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] provider translates the ADO results to an collection of user objects. + > [!NOTE] -> Most methods and operators on .NET Framework built-in types have direct translations to SQL. Those that LINQ cannot translate generate run-time exceptions. For more information, see [SQL-CLR Type Mapping](sql-clr-type-mapping.md). - - The following table shows the similarities and differences between LINQ and [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] query items. - -|Item|LINQ Query|[!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] Query| -|----------|----------------|----------------------------------------------------------------------| -|Return type of the local variable that holds the query (for queries that return sequences)|Generic `IEnumerable`|Generic `IQueryable`| -|Specifying the data source|Uses the `From` (Visual Basic) or `from` (C#) clause|Same| -|Filtering|Uses the `Where`/`where` clause|Same| -|Grouping|Uses the `Group…By`/`groupby` clause|Same| -|Selecting (Projecting)|Uses the `Select`/`select` clause|Same| -|Deferred versus immediate execution|See [Introduction to LINQ Queries (C#)](../../../../../csharp/linq/get-started/introduction-to-linq-queries.md)|Same| -|Implementing joins|Uses the `Join`/`join` clause|Can use the `Join`/`join` clause, but more effectively uses the attribute. For more information, see [Querying Across Relationships](querying-across-relationships.md).| -|Remote versus local execution||For more information, see [Remote vs. Local Execution](remote-vs-local-execution.md).| -|Streaming versus cached querying|Not applicable in a local memory scenario|| - +> Most methods and operators on .NET Framework built-in types have direct translations to SQL. Those that LINQ cannot translate generate runtime exceptions. For more information, see [SQL-CLR Type Mapping](sql-clr-type-mapping.md). + + The following table shows the similarities and differences between LINQ and [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] query items. + +|Item|LINQ Query|[!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] Query| +|----------|----------------|----------------------------------------------------------------------| +|Return type of the local variable that holds the query (for queries that return sequences)|Generic `IEnumerable`|Generic `IQueryable`| +|Specifying the data source|Uses the `From` (Visual Basic) or `from` (C#) clause|Same| +|Filtering|Uses the `Where`/`where` clause|Same| +|Grouping|Uses the `Group…By`/`groupby` clause|Same| +|Selecting (Projecting)|Uses the `Select`/`select` clause|Same| +|Deferred versus immediate execution|See [Introduction to LINQ Queries (C#)](../../../../../csharp/linq/get-started/introduction-to-linq-queries.md)|Same| +|Implementing joins|Uses the `Join`/`join` clause|Can use the `Join`/`join` clause, but more effectively uses the attribute. For more information, see [Querying Across Relationships](querying-across-relationships.md).| +|Remote versus local execution||For more information, see [Remote vs. Local Execution](remote-vs-local-execution.md).| +|Streaming versus cached querying|Not applicable in a local memory scenario|| + ## See also - [Introduction to LINQ Queries (C#)](../../../../../csharp/linq/get-started/introduction-to-linq-queries.md) diff --git a/docs/framework/data/adonet/sql/linq/serialization.md b/docs/framework/data/adonet/sql/linq/serialization.md index 66d18336ee764..4d7b9689ea694 100644 --- a/docs/framework/data/adonet/sql/linq/serialization.md +++ b/docs/framework/data/adonet/sql/linq/serialization.md @@ -2,76 +2,76 @@ description: "Learn more about serialization in LINQ to SQL" title: "Serialization in LINQ to SQL" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: a15ae411-8dc2-4ca3-84d2-01c9d5f1972a --- # Serialization in LINQ to SQL -This article describes LINQ to SQL serialization capabilities. The paragraphs that follow provide information about how to add serialization during code generation at design time and the run-time serialization behavior of LINQ to SQL classes. - - You can add serialization code at design time by either of the following methods: - -- In the Object Relational Designer, change the **Serialization Mode** property to **Unidirectional**. - -- On the SQLMetal command line, add the **/serialization** option. For more information, see [SqlMetal.exe (Code Generation Tool)](../../../../tools/sqlmetal-exe-code-generation-tool.md). - -## Overview - - The code generated by LINQ to SQL provides deferred loading capabilities by default. Deferred loading is very convenient on the mid-tier for transparent loading of data on demand. However, it is problematic for serialization, because the serializer triggers deferred loading whether deferred loading is intended or not. In effect, when an object is serialized, its transitive closure under all outbound defer-loaded references is serialized. - - The LINQ to SQL serialization feature addresses this problem, primarily through two mechanisms: - -- A mode for turning off deferred loading (). For more information, see . - -- A code-generation switch to generate and attributes on generated entities. This aspect, including the behavior of defer-loading classes under serialization, is the major subject of this topic. - -### Definitions - -- *DataContract serializer*: Default serializer used by the Windows Communication Framework (WCF) component of the .NET Framework 3.0 or later versions. - -- *Unidirectional serialization*: The serialized version of a class that contains only a one-way association property (to avoid a cycle). By convention, the property on the parent side of a primary-foreign key relationship is marked for serialization. The other side in a bidirectional association is not serialized. - - Unidirectional serialization is the only type of serialization supported by LINQ to SQL. - -## Code Example - - The following code uses the traditional `Customer` and `Order` classes from the Northwind sample database, and shows how these classes are decorated with serialization attributes. - +This article describes LINQ to SQL serialization capabilities. The paragraphs that follow provide information about how to add serialization during code generation at design time and the runtime serialization behavior of LINQ to SQL classes. + + You can add serialization code at design time by either of the following methods: + +- In the Object Relational Designer, change the **Serialization Mode** property to **Unidirectional**. + +- On the SQLMetal command line, add the **/serialization** option. For more information, see [SqlMetal.exe (Code Generation Tool)](../../../../tools/sqlmetal-exe-code-generation-tool.md). + +## Overview + + The code generated by LINQ to SQL provides deferred loading capabilities by default. Deferred loading is very convenient on the mid-tier for transparent loading of data on demand. However, it is problematic for serialization, because the serializer triggers deferred loading whether deferred loading is intended or not. In effect, when an object is serialized, its transitive closure under all outbound defer-loaded references is serialized. + + The LINQ to SQL serialization feature addresses this problem, primarily through two mechanisms: + +- A mode for turning off deferred loading (). For more information, see . + +- A code-generation switch to generate and attributes on generated entities. This aspect, including the behavior of defer-loading classes under serialization, is the major subject of this topic. + +### Definitions + +- *DataContract serializer*: Default serializer used by the Windows Communication Framework (WCF) component of the .NET Framework 3.0 or later versions. + +- *Unidirectional serialization*: The serialized version of a class that contains only a one-way association property (to avoid a cycle). By convention, the property on the parent side of a primary-foreign key relationship is marked for serialization. The other side in a bidirectional association is not serialized. + + Unidirectional serialization is the only type of serialization supported by LINQ to SQL. + +## Code Example + + The following code uses the traditional `Customer` and `Order` classes from the Northwind sample database, and shows how these classes are decorated with serialization attributes. + [!code-csharp[DLinqSerialization#1](../../../../../../samples/snippets/csharp/VS_Snippets_Data/DLinqSerialization/cs/northwind-ser.cs#1)] - [!code-vb[DLinqSerialization#1](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DLinqSerialization/vb/northwind-ser.vb#1)] - + [!code-vb[DLinqSerialization#1](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DLinqSerialization/vb/northwind-ser.vb#1)] + [!code-csharp[DLinqSerialization#2](../../../../../../samples/snippets/csharp/VS_Snippets_Data/DLinqSerialization/cs/northwind-ser.cs#2)] - [!code-vb[DLinqSerialization#2](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DLinqSerialization/vb/northwind-ser.vb#2)] - + [!code-vb[DLinqSerialization#2](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DLinqSerialization/vb/northwind-ser.vb#2)] + [!code-csharp[DLinqSerialization#3](../../../../../../samples/snippets/csharp/VS_Snippets_Data/DLinqSerialization/cs/northwind-ser.cs#3)] - [!code-vb[DLinqSerialization#3](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DLinqSerialization/vb/northwind-ser.vb#3)] - - For the `Order` class in the following example, only the reverse association property corresponding to the `Customer` class is shown for brevity. It does not have a attribute to avoid a cycle. - + [!code-vb[DLinqSerialization#3](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DLinqSerialization/vb/northwind-ser.vb#3)] + + For the `Order` class in the following example, only the reverse association property corresponding to the `Customer` class is shown for brevity. It does not have a attribute to avoid a cycle. + [!code-csharp[DLinqSerialization#4](../../../../../../samples/snippets/csharp/VS_Snippets_Data/DLinqSerialization/cs/northwind-ser.cs#4)] - [!code-vb[DLinqSerialization#4](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DLinqSerialization/vb/northwind-ser.vb#4)] - + [!code-vb[DLinqSerialization#4](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DLinqSerialization/vb/northwind-ser.vb#4)] + [!code-csharp[DLinqSerialization#5](../../../../../../samples/snippets/csharp/VS_Snippets_Data/DLinqSerialization/cs/northwind-ser.cs#5)] - [!code-vb[DLinqSerialization#5](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DLinqSerialization/vb/northwind-ser.vb#5)] - -### How to Serialize the Entities + [!code-vb[DLinqSerialization#5](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DLinqSerialization/vb/northwind-ser.vb#5)] + +### How to Serialize the Entities + + You can serialize the entities in the codes shown in the previous section as follows; - You can serialize the entities in the codes shown in the previous section as follows; - [!code-csharp[DLinqSerialization#6](../../../../../../samples/snippets/csharp/VS_Snippets_Data/DLinqSerialization/cs/Program.cs#6)] - [!code-vb[DLinqSerialization#6](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DLinqSerialization/vb/Module1.vb#6)] - -### Self-Recursive Relationships - - Self-recursive relationships follow the same pattern. The association property corresponding to the foreign key does not have a attribute, whereas the parent property does. - - Consider the following class that has two self-recursive relationships: Employee.Manager/Reports and Employee.Mentor/Mentees. - + [!code-vb[DLinqSerialization#6](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DLinqSerialization/vb/Module1.vb#6)] + +### Self-Recursive Relationships + + Self-recursive relationships follow the same pattern. The association property corresponding to the foreign key does not have a attribute, whereas the parent property does. + + Consider the following class that has two self-recursive relationships: Employee.Manager/Reports and Employee.Mentor/Mentees. + [!code-csharp[DLinqSerialization#7](../../../../../../samples/snippets/csharp/VS_Snippets_Data/DLinqSerialization/cs/northwind-ser.cs#7)] - [!code-vb[DLinqSerialization#7](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DLinqSerialization/vb/northwind-ser.vb#7)] - + [!code-vb[DLinqSerialization#7](../../../../../../samples/snippets/visualbasic/VS_Snippets_Data/DLinqSerialization/vb/northwind-ser.vb#7)] + ## See also - [Background Information](background-information.md) diff --git a/docs/framework/data/adonet/sql/linq/sql-clr-custom-type-mappings.md b/docs/framework/data/adonet/sql/linq/sql-clr-custom-type-mappings.md index 0d89941404f4a..0753a206e2026 100644 --- a/docs/framework/data/adonet/sql/linq/sql-clr-custom-type-mappings.md +++ b/docs/framework/data/adonet/sql/linq/sql-clr-custom-type-mappings.md @@ -6,29 +6,29 @@ ms.assetid: d916c7fb-4b56-4214-acbe-5e23365047b2 --- # SQL-CLR Custom Type Mappings -Type mapping between SQL Server and the common language runtime (CLR) is automatically specified when you use the SQLMetal command-line tool, Object Relational Designer (O/R Designer). - - When no customized mapping is performed, these tools assign default type mappings as described in [SQL-CLR Type Mapping](sql-clr-type-mapping.md). If you want to type mappings differently from these defaults, you need to do some customization of the type mappings. - - When customizing type mappings, the recommended approach is to make the changes in an intermediary DBML file. Then, your customized DBML file should be used when you create you code and mapping files with SQLMetal or O/R Designer. - - Once you instantiate the object from the code and mapping files, the method creates a database based on the type mappings that are specified. If there are no CLR `type` attributes specified in the mappings, the default type mappings will be used. - -## Customization with SQLMetal or O/R Designer - - With SQLMetal and O/R Designer, you can automatically create an object model that includes the type mapping information inside or outside the code file. Because these files are overwritten by SQLMetal or O/R Designer, each time you recreate your mappings, the recommended approach to specifying custom type mappings is to customize a DBML file. - - To customize type mappings with SQLMetal or O/R Designer, first generate a DBML file. Then, before generating the code file or mapping file, modify the DBML file to identify the desired type mappings. With SQLMetal, you have to manually change the `Type` and `DbType` attributes in the DBML file to make your type mapping customizations. With O/R Designer, you can make your changes within the Designer. For more information about using the O/R Designer, see [LINQ to SQL Tools in Visual Studio](/visualstudio/data-tools/linq-to-sql-tools-in-visual-studio2). - +Type mapping between SQL Server and the common language runtime (CLR) is automatically specified when you use the SQLMetal command-line tool, Object Relational Designer (O/R Designer). + + When no customized mapping is performed, these tools assign default type mappings as described in [SQL-CLR Type Mapping](sql-clr-type-mapping.md). If you want to type mappings differently from these defaults, you need to do some customization of the type mappings. + + When customizing type mappings, the recommended approach is to make the changes in an intermediary DBML file. Then, your customized DBML file should be used when you create you code and mapping files with SQLMetal or O/R Designer. + + Once you instantiate the object from the code and mapping files, the method creates a database based on the type mappings that are specified. If there are no CLR `type` attributes specified in the mappings, the default type mappings will be used. + +## Customization with SQLMetal or O/R Designer + + With SQLMetal and O/R Designer, you can automatically create an object model that includes the type mapping information inside or outside the code file. Because these files are overwritten by SQLMetal or O/R Designer, each time you recreate your mappings, the recommended approach to specifying custom type mappings is to customize a DBML file. + + To customize type mappings with SQLMetal or O/R Designer, first generate a DBML file. Then, before generating the code file or mapping file, modify the DBML file to identify the desired type mappings. With SQLMetal, you have to manually change the `Type` and `DbType` attributes in the DBML file to make your type mapping customizations. With O/R Designer, you can make your changes within the Designer. For more information about using the O/R Designer, see [LINQ to SQL Tools in Visual Studio](/visualstudio/data-tools/linq-to-sql-tools-in-visual-studio2). + > [!NOTE] -> Some type mappings may result in overflow or data loss exceptions while translating to or from the database. Carefully review the Type Mapping Run-time Behavior Matrix in [SQL-CLR Type Mapping](sql-clr-type-mapping.md) before making any customizations. - - In order for your type mapping customizations to be recognized by SQLMetal or O/R Designer, you need to make sure that these tools are supplied with the path to your custom DBML file when you generate your code file or external mapping file. Although not required for type mapping customization, it is recommended that you always separate your type mapping information from your code file and generate the additional external type mapping file. Doing so will leave some flexibility by not requiring that the code file be recompiled. - -## Incorporating Database Changes - - When your database changes, you will need to update your DBML file to reflect those changes. One way to do this is to automatically create a new DBML file and then re-do your type mapping customizations. Alternatively, you could compare the differences between your new DBML file and your customized DBML file and update your custom DBML file manually to reflect the database change. - +> Some type mappings may result in overflow or data loss exceptions while translating to or from the database. Carefully review the Type Mapping Runtime Behavior Matrix in [SQL-CLR Type Mapping](sql-clr-type-mapping.md) before making any customizations. + + In order for your type mapping customizations to be recognized by SQLMetal or O/R Designer, you need to make sure that these tools are supplied with the path to your custom DBML file when you generate your code file or external mapping file. Although not required for type mapping customization, it is recommended that you always separate your type mapping information from your code file and generate the additional external type mapping file. Doing so will leave some flexibility by not requiring that the code file be recompiled. + +## Incorporating Database Changes + + When your database changes, you will need to update your DBML file to reflect those changes. One way to do this is to automatically create a new DBML file and then re-do your type mapping customizations. Alternatively, you could compare the differences between your new DBML file and your customized DBML file and update your custom DBML file manually to reflect the database change. + ## See also - [SQL-CLR Type Mapping](sql-clr-type-mapping.md) diff --git a/docs/framework/data/adonet/sql/linq/sql-clr-type-mapping.md b/docs/framework/data/adonet/sql/linq/sql-clr-type-mapping.md index 441220be42d6e..cea421d43f556 100644 --- a/docs/framework/data/adonet/sql/linq/sql-clr-type-mapping.md +++ b/docs/framework/data/adonet/sql/linq/sql-clr-type-mapping.md @@ -6,279 +6,279 @@ ms.assetid: 4ed76327-54a7-414b-82a9-7579bfcec04b --- # SQL-CLR Type Mapping -In LINQ to SQL, the data model of a relational database maps to an object model that is expressed in the programming language of your choice. When the application runs, LINQ to SQL translates the language-integrated queries in the object model into SQL and sends them to the database for execution. When the database returns the results, LINQ to SQL translates the results back to objects that you can work with in your own programming language. - - In order to translate data between the object model and the database, a *type mapping* must be defined. LINQ to SQL uses a type mapping to match each common language runtime (CLR) type with a particular SQL Server type. You can define type mappings and other mapping information, such as database structure and table relationships, inside the object model with attribute-based mapping. Alternatively, you can specify the mapping information outside the object model with an external mapping file. For more information, see [Attribute-Based Mapping](attribute-based-mapping.md) and [External Mapping](external-mapping.md). - - This topic discusses the following points: - -- [Default Type Mapping](#DefaultTypeMapping) - -- [Type Mapping Run-time Behavior Matrix](#BehaviorMatrix) - -- [Behavior Differences Between CLR and SQL Execution](#BehaviorDiffs) - -- [Enum Mapping](#EnumMapping) - -- [Numeric Mapping](#NumericMapping) - -- [Text and XML Mapping](#TextMapping) - -- [Date and Time Mapping](#DateMapping) - -- [Binary Mapping](#BinaryMapping) - -- [Miscellaneous Mapping](#MiscMapping) - +In LINQ to SQL, the data model of a relational database maps to an object model that is expressed in the programming language of your choice. When the application runs, LINQ to SQL translates the language-integrated queries in the object model into SQL and sends them to the database for execution. When the database returns the results, LINQ to SQL translates the results back to objects that you can work with in your own programming language. + + In order to translate data between the object model and the database, a *type mapping* must be defined. LINQ to SQL uses a type mapping to match each common language runtime (CLR) type with a particular SQL Server type. You can define type mappings and other mapping information, such as database structure and table relationships, inside the object model with attribute-based mapping. Alternatively, you can specify the mapping information outside the object model with an external mapping file. For more information, see [Attribute-Based Mapping](attribute-based-mapping.md) and [External Mapping](external-mapping.md). + + This topic discusses the following points: + +- [Default Type Mapping](#DefaultTypeMapping) + +- [Type Mapping Runtime Behavior Matrix](#BehaviorMatrix) + +- [Behavior Differences Between CLR and SQL Execution](#BehaviorDiffs) + +- [Enum Mapping](#EnumMapping) + +- [Numeric Mapping](#NumericMapping) + +- [Text and XML Mapping](#TextMapping) + +- [Date and Time Mapping](#DateMapping) + +- [Binary Mapping](#BinaryMapping) + +- [Miscellaneous Mapping](#MiscMapping) + -## Default Type Mapping +## Default Type Mapping + + You can create the object model or external mapping file automatically with the Object Relational Designer (O/R Designer) or the SQLMetal command-line tool. The default type mappings for these tools define which CLR types are chosen to map to columns inside the SQL Server database. For more information about using these tools, see [Creating the Object Model](creating-the-object-model.md). + + You can also use the method to create a SQL Server database based on the mapping information in the object model or external mapping file. The default type mappings for the method define which type of SQL Server columns are created to map to the CLR types in the object model. For more information, see [How to: Dynamically Create a Database](how-to-dynamically-create-a-database.md). - You can create the object model or external mapping file automatically with the Object Relational Designer (O/R Designer) or the SQLMetal command-line tool. The default type mappings for these tools define which CLR types are chosen to map to columns inside the SQL Server database. For more information about using these tools, see [Creating the Object Model](creating-the-object-model.md). - - You can also use the method to create a SQL Server database based on the mapping information in the object model or external mapping file. The default type mappings for the method define which type of SQL Server columns are created to map to the CLR types in the object model. For more information, see [How to: Dynamically Create a Database](how-to-dynamically-create-a-database.md). - -## Type Mapping Run-time Behavior Matrix +## Type Mapping Runtime Behavior Matrix - The following diagram shows the expected run-time behavior of specific type mappings when data is retrieved from or saved to the database. With the exception of serialization, LINQ to SQL does not support mapping between any CLR or SQL Server data types that are not specified in this matrix. For more information on serialization support, see [Binary Serialization](#BinarySerialization). + The following diagram shows the expected runtime behavior of specific type mappings when data is retrieved from or saved to the database. With the exception of serialization, LINQ to SQL does not support mapping between any CLR or SQL Server data types that are not specified in this matrix. For more information on serialization support, see [Binary Serialization](#BinarySerialization). ![SQL Server to SQL CLR data type mapping table](./media/sql-clr-type-mapping.png) > [!NOTE] -> Some type mappings may result in overflow or data loss exceptions while translating to or from the database. - -### Custom Type Mapping +> Some type mappings may result in overflow or data loss exceptions while translating to or from the database. + +### Custom Type Mapping + + With LINQ to SQL, you are not limited to the default type mappings used by the O/R Designer, SQLMetal, and the method. You can create custom type mappings by explicitly specifying them in a DBML file. Then you can use that DBML file to create the object model code and mapping file. For more information, see [SQL-CLR Custom Type Mappings](sql-clr-custom-type-mappings.md). - With LINQ to SQL, you are not limited to the default type mappings used by the O/R Designer, SQLMetal, and the method. You can create custom type mappings by explicitly specifying them in a DBML file. Then you can use that DBML file to create the object model code and mapping file. For more information, see [SQL-CLR Custom Type Mappings](sql-clr-custom-type-mappings.md). - -## Behavior Differences Between CLR and SQL Execution +## Behavior Differences Between CLR and SQL Execution + + Because of differences in precision and execution between the CLR and SQL Server, you may receive different results or experience different behavior depending on where you perform your calculations. Calculations performed in LINQ to SQL queries are actually translated to Transact-SQL and then executed on the SQL Server database. Calculations performed outside LINQ to SQL queries are executed within the context of the CLR. + + For example, the following are some differences in behavior between the CLR and SQL Server: + +- SQL Server orders some data types differently than data of equivalent type in the CLR. For example, SQL Server data of type `UNIQUEIDENTIFIER` is ordered differently than CLR data of type . - Because of differences in precision and execution between the CLR and SQL Server, you may receive different results or experience different behavior depending on where you perform your calculations. Calculations performed in LINQ to SQL queries are actually translated to Transact-SQL and then executed on the SQL Server database. Calculations performed outside LINQ to SQL queries are executed within the context of the CLR. - - For example, the following are some differences in behavior between the CLR and SQL Server: - -- SQL Server orders some data types differently than data of equivalent type in the CLR. For example, SQL Server data of type `UNIQUEIDENTIFIER` is ordered differently than CLR data of type . - - SQL Server handles some string comparison operations differently than the CLR. In SQL Server, string comparison behavior depends on the collation settings on the server. For more information, see [Working with Collations](/previous-versions/sql/sql-server-2008-r2/ms187582(v=sql.105)). - -- SQL Server may return different values for some mapped functions than the CLR. For example, equality functions will differ because SQL Server considers two strings to be equal if they only differ in trailing white space; whereas the CLR considers them to be not equal. - + +- SQL Server may return different values for some mapped functions than the CLR. For example, equality functions will differ because SQL Server considers two strings to be equal if they only differ in trailing white space; whereas the CLR considers them to be not equal. + -## Enum Mapping - - LINQ to SQL supports mapping the CLR type to SQL Server types in two ways: - -- Mapping to SQL numeric types (`TINYINT`, `SMALLINT`, `INT`, `BIGINT`) - - When you map a CLR type to a SQL numeric type, you map the underlying integer value of the CLR to the value of the SQL Server database column. For example, if a named `DaysOfWeek` contains a member named `Tue` with an underlying integer value of 3, that member maps to a database value of 3. - -- Mapping to SQL text types (`CHAR`, `NCHAR`, `VARCHAR`, `NVARCHAR`) - - When you map a CLR type to a SQL text type, the SQL database value is mapped to the names of the CLR members. For example, if a named `DaysOfWeek` contains a member named `Tue` with an underlying integer value of 3, that member maps to a database value of `Tue`. - +## Enum Mapping + + LINQ to SQL supports mapping the CLR type to SQL Server types in two ways: + +- Mapping to SQL numeric types (`TINYINT`, `SMALLINT`, `INT`, `BIGINT`) + + When you map a CLR type to a SQL numeric type, you map the underlying integer value of the CLR to the value of the SQL Server database column. For example, if a named `DaysOfWeek` contains a member named `Tue` with an underlying integer value of 3, that member maps to a database value of 3. + +- Mapping to SQL text types (`CHAR`, `NCHAR`, `VARCHAR`, `NVARCHAR`) + + When you map a CLR type to a SQL text type, the SQL database value is mapped to the names of the CLR members. For example, if a named `DaysOfWeek` contains a member named `Tue` with an underlying integer value of 3, that member maps to a database value of `Tue`. + > [!NOTE] -> When mapping SQL text types to a CLR , include only the names of the members in the mapped SQL column. Other values are not supported in the -mapped SQL column. - - The O/R Designer and SQLMetal command-line tool cannot automatically map a SQL type to a CLR class. You must explicitly configure this mapping by customizing a DBML file for use by the O/R Designer and SQLMetal. For more information about custom type mapping, see [SQL-CLR Custom Type Mappings](sql-clr-custom-type-mappings.md). - - Because a SQL column intended for enumeration will be of the same type as other numeric and text columns; these tools will not recognize your intent and default to mapping as described in the following [Numeric Mapping](#NumericMapping) and [Text and XML Mapping](#TextMapping) sections. For more information about generating code with the DBML file, see [Code Generation in LINQ to SQL](code-generation-in-linq-to-sql.md). - - The method creates a SQL column of numeric type to map a CLR type. - +> When mapping SQL text types to a CLR , include only the names of the members in the mapped SQL column. Other values are not supported in the -mapped SQL column. + + The O/R Designer and SQLMetal command-line tool cannot automatically map a SQL type to a CLR class. You must explicitly configure this mapping by customizing a DBML file for use by the O/R Designer and SQLMetal. For more information about custom type mapping, see [SQL-CLR Custom Type Mappings](sql-clr-custom-type-mappings.md). + + Because a SQL column intended for enumeration will be of the same type as other numeric and text columns; these tools will not recognize your intent and default to mapping as described in the following [Numeric Mapping](#NumericMapping) and [Text and XML Mapping](#TextMapping) sections. For more information about generating code with the DBML file, see [Code Generation in LINQ to SQL](code-generation-in-linq-to-sql.md). + + The method creates a SQL column of numeric type to map a CLR type. + -## Numeric Mapping - - LINQ to SQL lets you map many CLR and SQL Server numeric types. The following table shows the CLR types that O/R Designer and SQLMetal select when building an object model or external mapping file based on your database. - -|SQL Server Type|Default CLR Type mapping used by O/R Designer and SQLMetal| -|---------------------|-----------------------------------------------------------------| -|`BIT`|| -|`TINYINT`|| -|`INT`|| -|`BIGINT`|| -|`SMALLMONEY`|| -|`MONEY`|| -|`DECIMAL`|| -|`NUMERIC`|| -|`REAL/FLOAT(24)`|| -|`FLOAT/FLOAT(53)`|| - - The next table shows the default type mappings used by the method to define which type of SQL columns are created to map to the CLR types defined in your object model or external mapping file. - -|CLR Type|Default SQL Server Type used by | -|--------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -||`BIT`| -||`TINYINT`| -||`SMALLINT`| -||`INT`| -||`BIGINT`| -||`SMALLINT`| -||`INT`| -||`BIGINT`| -||`DECIMAL(20)`| -||`DECIMAL(29,4)`| -||`REAL`| -||`FLOAT`| - - There are many other numeric mappings you can choose, but some may result in overflow or data loss exceptions while translating to or from the database. For more information, see the [Type Mapping Run Time Behavior Matrix](#BehaviorMatrix). - -### Decimal and Money Types - - The default precision of SQL Server `DECIMAL` type (18 decimal digits to the left and right of the decimal point) is much smaller than the precision of the CLR type that it is paired with by default. This can result in precision loss when you save data to the database. However, just the opposite can happen if the SQL Server `DECIMAL` type is configured with greater than 29 digits of precision. When a SQL Server `DECIMAL` type has been configured with a greater precision than the CLR , precision loss can occur when retrieving data from the database. - - The SQL Server `MONEY` and `SMALLMONEY` types, which are also paired with the CLR type by default, have a much smaller precision, which can result in overflow or data loss exceptions when saving data to the database. - +## Numeric Mapping + + LINQ to SQL lets you map many CLR and SQL Server numeric types. The following table shows the CLR types that O/R Designer and SQLMetal select when building an object model or external mapping file based on your database. + +|SQL Server Type|Default CLR Type mapping used by O/R Designer and SQLMetal| +|---------------------|-----------------------------------------------------------------| +|`BIT`|| +|`TINYINT`|| +|`INT`|| +|`BIGINT`|| +|`SMALLMONEY`|| +|`MONEY`|| +|`DECIMAL`|| +|`NUMERIC`|| +|`REAL/FLOAT(24)`|| +|`FLOAT/FLOAT(53)`|| + + The next table shows the default type mappings used by the method to define which type of SQL columns are created to map to the CLR types defined in your object model or external mapping file. + +|CLR Type|Default SQL Server Type used by | +|--------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +||`BIT`| +||`TINYINT`| +||`SMALLINT`| +||`INT`| +||`BIGINT`| +||`SMALLINT`| +||`INT`| +||`BIGINT`| +||`DECIMAL(20)`| +||`DECIMAL(29,4)`| +||`REAL`| +||`FLOAT`| + + There are many other numeric mappings you can choose, but some may result in overflow or data loss exceptions while translating to or from the database. For more information, see the [Type Mapping Run Time Behavior Matrix](#BehaviorMatrix). + +### Decimal and Money Types + + The default precision of SQL Server `DECIMAL` type (18 decimal digits to the left and right of the decimal point) is much smaller than the precision of the CLR type that it is paired with by default. This can result in precision loss when you save data to the database. However, just the opposite can happen if the SQL Server `DECIMAL` type is configured with greater than 29 digits of precision. When a SQL Server `DECIMAL` type has been configured with a greater precision than the CLR , precision loss can occur when retrieving data from the database. + + The SQL Server `MONEY` and `SMALLMONEY` types, which are also paired with the CLR type by default, have a much smaller precision, which can result in overflow or data loss exceptions when saving data to the database. + -## Text and XML Mapping - - There are also many text-based and XML types that you can map with LINQ to SQL. The following table shows the CLR types that O/R Designer and SQLMetal select when building an object model or external mapping file based on your database. - -|SQL Server Type|Default CLR Type mapping used by O/R Designer and SQLMetal| -|---------------------|-----------------------------------------------------------------| -|`CHAR`|| -|`NCHAR`|| -|`VARCHAR`|| -|`NVARCHAR`|| -|`TEXT`|| -|`NTEXT`|| -|`XML`|| - - The next table shows the default type mappings used by the method to define which type of SQL columns are created to map to the CLR types defined in your object model or external mapping file. - -|CLR Type|Default SQL Server Type used by | -|--------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -||`NCHAR(1)`| -||`NVARCHAR(4000)`| -|[]|`NVARCHAR(4000)`| -|Custom type implementing `Parse()` and `ToString()`|`NVARCHAR(MAX)`| - - There are many other text-based and XML mappings you can choose, but some may result in overflow or data loss exceptions while translating to or from the database. For more information, see the [Type Mapping Run Time Behavior Matrix](#BehaviorMatrix). - -### XML Types - - The SQL Server `XML` data type is available starting in Microsoft SQL Server 2005. You can map the SQL Server `XML` data type to , , or . If the column stores XML fragments that cannot be read into , the column must be mapped to to avoid run-time errors. XML fragments that must be mapped to include the following: - -- A sequence of XML elements - -- Attributes - -- Public Identifiers (PI) - -- Comments - - Although you can map and to SQL Server as shown in the [Type Mapping Run Time Behavior Matrix](#BehaviorMatrix), the method has no default SQL Server type mapping for these types. - -### Custom Types - - If a class implements `Parse()` and `ToString()`, you can map the object to any SQL text type (`CHAR`, `NCHAR`, `VARCHAR`, `NVARCHAR`, `TEXT`, `NTEXT`, `XML`). The object is stored in the database by sending the value returned by `ToString()` to the mapped database column. The object is reconstructed by invoking `Parse()` on the string returned by the database. - +## Text and XML Mapping + + There are also many text-based and XML types that you can map with LINQ to SQL. The following table shows the CLR types that O/R Designer and SQLMetal select when building an object model or external mapping file based on your database. + +|SQL Server Type|Default CLR Type mapping used by O/R Designer and SQLMetal| +|---------------------|-----------------------------------------------------------------| +|`CHAR`|| +|`NCHAR`|| +|`VARCHAR`|| +|`NVARCHAR`|| +|`TEXT`|| +|`NTEXT`|| +|`XML`|| + + The next table shows the default type mappings used by the method to define which type of SQL columns are created to map to the CLR types defined in your object model or external mapping file. + +|CLR Type|Default SQL Server Type used by | +|--------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +||`NCHAR(1)`| +||`NVARCHAR(4000)`| +|[]|`NVARCHAR(4000)`| +|Custom type implementing `Parse()` and `ToString()`|`NVARCHAR(MAX)`| + + There are many other text-based and XML mappings you can choose, but some may result in overflow or data loss exceptions while translating to or from the database. For more information, see the [Type Mapping Run Time Behavior Matrix](#BehaviorMatrix). + +### XML Types + + The SQL Server `XML` data type is available starting in Microsoft SQL Server 2005. You can map the SQL Server `XML` data type to , , or . If the column stores XML fragments that cannot be read into , the column must be mapped to to avoid runtime errors. XML fragments that must be mapped to include the following: + +- A sequence of XML elements + +- Attributes + +- Public Identifiers (PI) + +- Comments + + Although you can map and to SQL Server as shown in the [Type Mapping Run Time Behavior Matrix](#BehaviorMatrix), the method has no default SQL Server type mapping for these types. + +### Custom Types + + If a class implements `Parse()` and `ToString()`, you can map the object to any SQL text type (`CHAR`, `NCHAR`, `VARCHAR`, `NVARCHAR`, `TEXT`, `NTEXT`, `XML`). The object is stored in the database by sending the value returned by `ToString()` to the mapped database column. The object is reconstructed by invoking `Parse()` on the string returned by the database. + > [!NOTE] -> LINQ to SQL does not support serialization by using . - +> LINQ to SQL does not support serialization by using . + -## Date and Time Mapping - - With LINQ to SQL, you can map many SQL Server date and time types. The following table shows the CLR types that O/R Designer and SQLMetal select when building an object model or external mapping file based on your database. - -|SQL Server Type|Default CLR Type mapping used by O/R Designer and SQLMetal| -|---------------------|-----------------------------------------------------------------| -|`SMALLDATETIME`|| -|`DATETIME`|| -|`DATETIME2`|| -|`DATETIMEOFFSET`|| -|`DATE`|| -|`TIME`|| - - The next table shows the default type mappings used by the method to define which type of SQL columns are created to map to the CLR types defined in your object model or external mapping file. - -|CLR Type|Default SQL Server Type used by | -|--------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -||`DATETIME`| -||`DATETIMEOFFSET`| -||`TIME`| - - There are many other date and time mappings you can choose, but some may result in overflow or data loss exceptions while translating to or from the database. For more information, see the [Type Mapping Run Time Behavior Matrix](#BehaviorMatrix). - +## Date and Time Mapping + + With LINQ to SQL, you can map many SQL Server date and time types. The following table shows the CLR types that O/R Designer and SQLMetal select when building an object model or external mapping file based on your database. + +|SQL Server Type|Default CLR Type mapping used by O/R Designer and SQLMetal| +|---------------------|-----------------------------------------------------------------| +|`SMALLDATETIME`|| +|`DATETIME`|| +|`DATETIME2`|| +|`DATETIMEOFFSET`|| +|`DATE`|| +|`TIME`|| + + The next table shows the default type mappings used by the method to define which type of SQL columns are created to map to the CLR types defined in your object model or external mapping file. + +|CLR Type|Default SQL Server Type used by | +|--------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +||`DATETIME`| +||`DATETIMEOFFSET`| +||`TIME`| + + There are many other date and time mappings you can choose, but some may result in overflow or data loss exceptions while translating to or from the database. For more information, see the [Type Mapping Run Time Behavior Matrix](#BehaviorMatrix). + > [!NOTE] -> The SQL Server types `DATETIME2`, `DATETIMEOFFSET`, `DATE`, and `TIME` are available starting with Microsoft SQL Server 2008. LINQ to SQL supports mapping to these new types starting with the .NET Framework version 3.5 SP1. - -### System.Datetime - - The range and precision of the CLR type is greater than the range and precision of the SQL Server `DATETIME` type, which is the default type mapping for the method. To help avoid exceptions related to dates outside the range of `DATETIME`, use `DATETIME2`, which is available starting with Microsoft SQL Server 2008. `DATETIME2` can match the range and precision of the CLR . - - SQL Server dates have no concept of , a feature that is richly supported in the CLR. values are saved as is to the database without conversion, regardless of the original information. When values are retrieved from the database, their value is loaded as is into a with a of . For more information about supported methods, see [System.DateTime Methods](system-datetime-methods.md). - -### System.TimeSpan - - Microsoft SQL Server 2008 and the .NET Framework 3.5 SP1 let you map the CLR type to the SQL Server `TIME` type. However, there is a large difference between the range that the CLR supports and what the SQL Server `TIME` type supports. Mapping values less than 0 or greater than 23:59:59.9999999 hours to the SQL `TIME` will result in overflow exceptions. For more information, see [System.TimeSpan Methods](system-timespan-methods.md). - - In Microsoft SQL Server 2000 and SQL Server 2005, you cannot map database fields to . However, operations on are supported because values can be returned from subtraction or introduced into an expression as a literal or bound variable. - +> The SQL Server types `DATETIME2`, `DATETIMEOFFSET`, `DATE`, and `TIME` are available starting with Microsoft SQL Server 2008. LINQ to SQL supports mapping to these new types starting with the .NET Framework version 3.5 SP1. + +### System.Datetime + + The range and precision of the CLR type is greater than the range and precision of the SQL Server `DATETIME` type, which is the default type mapping for the method. To help avoid exceptions related to dates outside the range of `DATETIME`, use `DATETIME2`, which is available starting with Microsoft SQL Server 2008. `DATETIME2` can match the range and precision of the CLR . + + SQL Server dates have no concept of , a feature that is richly supported in the CLR. values are saved as is to the database without conversion, regardless of the original information. When values are retrieved from the database, their value is loaded as is into a with a of . For more information about supported methods, see [System.DateTime Methods](system-datetime-methods.md). + +### System.TimeSpan + + Microsoft SQL Server 2008 and the .NET Framework 3.5 SP1 let you map the CLR type to the SQL Server `TIME` type. However, there is a large difference between the range that the CLR supports and what the SQL Server `TIME` type supports. Mapping values less than 0 or greater than 23:59:59.9999999 hours to the SQL `TIME` will result in overflow exceptions. For more information, see [System.TimeSpan Methods](system-timespan-methods.md). + + In Microsoft SQL Server 2000 and SQL Server 2005, you cannot map database fields to . However, operations on are supported because values can be returned from subtraction or introduced into an expression as a literal or bound variable. + -## Binary Mapping - - There are many SQL Server types that can map to the CLR type . The following table shows the SQL Server types that cause O/R Designer and SQLMetal to define a CLR type when building an object model or external mapping file based on your database. - -|SQL Server Type|Default CLR Type mapping used by O/R Designer and SQLMetal| -|---------------------|-----------------------------------------------------------------| -|`BINARY(50)`|| -|`VARBINARY(50)`|| -|`VARBINARY(MAX)`|| -|`VARBINARY(MAX)` with the `FILESTREAM` attribute|| -|`IMAGE`|| -|`TIMESTAMP`|| - - The next table shows the default type mappings used by the method to define which type of SQL columns are created to map to the CLR types defined in your object model or external mapping file. - -|CLR Type|Default SQL Server Type used by | -|--------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -||`VARBINARY(MAX)`| -||`VARBINARY(MAX)`| -||`VARBINARY(MAX)`| - - There are many other binary mappings you can choose, but some may result in overflow or data loss exceptions while translating to or from the database. For more information, see the [Type Mapping Run Time Behavior Matrix](#BehaviorMatrix). - -### SQL Server FILESTREAM - - The `FILESTREAM` attribute for `VARBINARY(MAX)` columns is available starting with Microsoft SQL Server 2008; you can map to it with LINQ to SQL starting with the .NET Framework version 3.5 SP1. - - Although you can map `VARBINARY(MAX)` columns with the `FILESTREAM` attribute to objects, the method is unable to automatically create columns with the `FILESTREAM` attribute. For more information about `FILESTREAM`, see [FILESTREAM Overview](/previous-versions/sql/sql-server-2008-r2/bb933993(v=sql.105)). - +## Binary Mapping + + There are many SQL Server types that can map to the CLR type . The following table shows the SQL Server types that cause O/R Designer and SQLMetal to define a CLR type when building an object model or external mapping file based on your database. + +|SQL Server Type|Default CLR Type mapping used by O/R Designer and SQLMetal| +|---------------------|-----------------------------------------------------------------| +|`BINARY(50)`|| +|`VARBINARY(50)`|| +|`VARBINARY(MAX)`|| +|`VARBINARY(MAX)` with the `FILESTREAM` attribute|| +|`IMAGE`|| +|`TIMESTAMP`|| + + The next table shows the default type mappings used by the method to define which type of SQL columns are created to map to the CLR types defined in your object model or external mapping file. + +|CLR Type|Default SQL Server Type used by | +|--------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +||`VARBINARY(MAX)`| +||`VARBINARY(MAX)`| +||`VARBINARY(MAX)`| + + There are many other binary mappings you can choose, but some may result in overflow or data loss exceptions while translating to or from the database. For more information, see the [Type Mapping Run Time Behavior Matrix](#BehaviorMatrix). + +### SQL Server FILESTREAM + + The `FILESTREAM` attribute for `VARBINARY(MAX)` columns is available starting with Microsoft SQL Server 2008; you can map to it with LINQ to SQL starting with the .NET Framework version 3.5 SP1. + + Although you can map `VARBINARY(MAX)` columns with the `FILESTREAM` attribute to objects, the method is unable to automatically create columns with the `FILESTREAM` attribute. For more information about `FILESTREAM`, see [FILESTREAM Overview](/previous-versions/sql/sql-server-2008-r2/bb933993(v=sql.105)). + -### Binary Serialization +### Binary Serialization If a class implements the interface, you can serialize an object to any SQL binary field (`BINARY`, `VARBINARY`, `IMAGE`). The object is serialized and deserialized according to how the interface is implemented. For more information, see [Binary Serialization](/previous-versions/dotnet/fundamentals/serialization/binary/binary-serialization). - + -## Miscellaneous Mapping - - The following table shows the default type mappings for some miscellaneous types that have not yet been mentioned. The following table shows the CLR types that O/R Designer and SQLMetal select when building an object model or external mapping file based on your database. - -|SQL Server Type|Default CLR Type mapping used by O/R Designer and SQLMetal| -|---------------------|-----------------------------------------------------------------| -|`UNIQUEIDENTIFIER`|| -|`SQL_VARIANT`|| - - The next table shows the default type mappings used by the method to define which type of SQL columns are created to map to the CLR types defined in your object model or external mapping file. - -|CLR Type|Default SQL Server Type used by | -|--------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -||`UNIQUEIDENTIFIER`| -||`SQL_VARIANT`| - - LINQ to SQL does not support any other type mappings for these miscellaneous types. For more information, see the [Type Mapping Run Time Behavior Matrix](#BehaviorMatrix). - +## Miscellaneous Mapping + + The following table shows the default type mappings for some miscellaneous types that have not yet been mentioned. The following table shows the CLR types that O/R Designer and SQLMetal select when building an object model or external mapping file based on your database. + +|SQL Server Type|Default CLR Type mapping used by O/R Designer and SQLMetal| +|---------------------|-----------------------------------------------------------------| +|`UNIQUEIDENTIFIER`|| +|`SQL_VARIANT`|| + + The next table shows the default type mappings used by the method to define which type of SQL columns are created to map to the CLR types defined in your object model or external mapping file. + +|CLR Type|Default SQL Server Type used by | +|--------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +||`UNIQUEIDENTIFIER`| +||`SQL_VARIANT`| + + LINQ to SQL does not support any other type mappings for these miscellaneous types. For more information, see the [Type Mapping Run Time Behavior Matrix](#BehaviorMatrix). + ## See also - [Attribute-Based Mapping](attribute-based-mapping.md) diff --git a/docs/framework/data/adonet/sql/linq/troubleshooting.md b/docs/framework/data/adonet/sql/linq/troubleshooting.md index cdcae1e0349dd..15eca4db1f44f 100644 --- a/docs/framework/data/adonet/sql/linq/troubleshooting.md +++ b/docs/framework/data/adonet/sql/linq/troubleshooting.md @@ -6,76 +6,76 @@ ms.assetid: 8cd4401c-b12c-4116-a421-f3dcffa65670 --- # Troubleshooting -The following information exposes some issues you might encounter in your [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] applications, and provides suggestions to avoid or otherwise reduce the effect of these issues. - - Additional issues are addressed in [Frequently Asked Questions](frequently-asked-questions.yml). - -## Unsupported Standard Query Operators - - [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] does not support all standard query operator methods (for example, ). As a result, projects that compile can still produce run-time errors. For more information, see [Standard Query Operator Translation](standard-query-operator-translation.md). - -## Memory Issues - - If a query involves an in-memory collection and [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] , the query might be executed in memory, depending on the order in which the two collections are specified. If the query must be executed in memory, then the data from the database table will need to be retrieved. - - This approach is inefficient and could result in significant memory and processor usage. Try to avoid such multi-domain queries. - -## File Names and SQLMetal - - To specify an input file name, add the name to the command line as the input file. Including the file name in the connection string (using the **/conn** option) is not supported. For more information, see [SqlMetal.exe (Code Generation Tool)](../../../../tools/sqlmetal-exe-code-generation-tool.md). - -## Class Library Projects - - The Object Relational Designer creates a connection string in the `app.config` file of the project. In class library projects, the `app.config` file is not used. [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] uses the Connection String provided in the design-time files. Changing the value in `app.config` does not change the database to which your application connects. - -## Cascade Delete - - [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] does not support or recognize cascade-delete operations. If you want to delete a row in a table that has constraints against it, you must do either of the following: - -- Set the `ON DELETE CASCADE` rule in the foreign-key constraint in the database. - -- Use your own code to first delete the child objects that prevent the parent object from being deleted. - - Otherwise, a exception is thrown. - - For more information, see [How to: Delete Rows From the Database](how-to-delete-rows-from-the-database.md). - -## Expression Not Queryable - - If you get the "Expression [expression] is not queryable; are you missing an assembly reference?" error, make sure of the following: - -- Your application is targeting .NET Compact Framework 3.5. - -- You have a reference to `System.Core.dll` and `System.Data.Linq.dll`. - -- You have an `Imports` (Visual Basic) or `using` (C#) directive for and . - -## DuplicateKeyException - - In the course of debugging a [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] project, you might traverse an entity's relations. Doing so brings these items into the cache, and [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] becomes aware of their presence. If you then try to execute or or a similar method that produces multiple rows that have the same key, a is thrown. - -## String Concatenation Exceptions - - Concatenation on operands mapped to `[n]text` and other `[n][var]char` is not supported. An exception is thrown for concatenation of strings mapped to the two different sets of types. For more information, see [System.String Methods](system-string-methods.md). - -## Skip and Take Exceptions in SQL Server 2000 - - You must use identity members () when you use or against a SQL Server 2000 database. The query must be against a single table (that is, not a join), or be a , , , or operation, and must not include a operation. For more information, see the "SQL Server 2000 Support" section in [Standard Query Operator Translation](standard-query-operator-translation.md). - - This requirement does not apply to SQL Server 2005. - -## GroupBy InvalidOperationException - - This exception is thrown when a column value is null in a query that groups by a `boolean` expression, such as `group x by (Phone==@phone)`. Because the expression is a `boolean`, the key is inferred to be `boolean`, not `nullable` `boolean`. When the translated comparison produces a null, an attempt is made to assign a `nullable` `boolean` to a `boolean`, and the exception is thrown. - - To avoid this situation (assuming you want to treat nulls as false), use an approach such as the following: - - `GroupBy="(Phone != null) && (Phone=@Phone)"` - -## OnCreated() Partial Method - - The generated method `OnCreated()` is called each time the object constructor is called, including the scenario in which [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] calls the constructor to make a copy for original values. Take this behavior into account if you implement the `OnCreated()` method in your own partial class. - +The following information exposes some issues you might encounter in your [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] applications, and provides suggestions to avoid or otherwise reduce the effect of these issues. + + Additional issues are addressed in [Frequently Asked Questions](frequently-asked-questions.yml). + +## Unsupported Standard Query Operators + + [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] does not support all standard query operator methods (for example, ). As a result, projects that compile can still produce runtime errors. For more information, see [Standard Query Operator Translation](standard-query-operator-translation.md). + +## Memory Issues + + If a query involves an in-memory collection and [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] , the query might be executed in memory, depending on the order in which the two collections are specified. If the query must be executed in memory, then the data from the database table will need to be retrieved. + + This approach is inefficient and could result in significant memory and processor usage. Try to avoid such multi-domain queries. + +## File Names and SQLMetal + + To specify an input file name, add the name to the command line as the input file. Including the file name in the connection string (using the **/conn** option) is not supported. For more information, see [SqlMetal.exe (Code Generation Tool)](../../../../tools/sqlmetal-exe-code-generation-tool.md). + +## Class Library Projects + + The Object Relational Designer creates a connection string in the `app.config` file of the project. In class library projects, the `app.config` file is not used. [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] uses the Connection String provided in the design-time files. Changing the value in `app.config` does not change the database to which your application connects. + +## Cascade Delete + + [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] does not support or recognize cascade-delete operations. If you want to delete a row in a table that has constraints against it, you must do either of the following: + +- Set the `ON DELETE CASCADE` rule in the foreign-key constraint in the database. + +- Use your own code to first delete the child objects that prevent the parent object from being deleted. + + Otherwise, a exception is thrown. + + For more information, see [How to: Delete Rows From the Database](how-to-delete-rows-from-the-database.md). + +## Expression Not Queryable + + If you get the "Expression [expression] is not queryable; are you missing an assembly reference?" error, make sure of the following: + +- Your application is targeting .NET Compact Framework 3.5. + +- You have a reference to `System.Core.dll` and `System.Data.Linq.dll`. + +- You have an `Imports` (Visual Basic) or `using` (C#) directive for and . + +## DuplicateKeyException + + In the course of debugging a [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] project, you might traverse an entity's relations. Doing so brings these items into the cache, and [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] becomes aware of their presence. If you then try to execute or or a similar method that produces multiple rows that have the same key, a is thrown. + +## String Concatenation Exceptions + + Concatenation on operands mapped to `[n]text` and other `[n][var]char` is not supported. An exception is thrown for concatenation of strings mapped to the two different sets of types. For more information, see [System.String Methods](system-string-methods.md). + +## Skip and Take Exceptions in SQL Server 2000 + + You must use identity members () when you use or against a SQL Server 2000 database. The query must be against a single table (that is, not a join), or be a , , , or operation, and must not include a operation. For more information, see the "SQL Server 2000 Support" section in [Standard Query Operator Translation](standard-query-operator-translation.md). + + This requirement does not apply to SQL Server 2005. + +## GroupBy InvalidOperationException + + This exception is thrown when a column value is null in a query that groups by a `boolean` expression, such as `group x by (Phone==@phone)`. Because the expression is a `boolean`, the key is inferred to be `boolean`, not `nullable` `boolean`. When the translated comparison produces a null, an attempt is made to assign a `nullable` `boolean` to a `boolean`, and the exception is thrown. + + To avoid this situation (assuming you want to treat nulls as false), use an approach such as the following: + + `GroupBy="(Phone != null) && (Phone=@Phone)"` + +## OnCreated() Partial Method + + The generated method `OnCreated()` is called each time the object constructor is called, including the scenario in which [!INCLUDE[vbtecdlinq](../../../../../../includes/vbtecdlinq-md.md)] calls the constructor to make a copy for original values. Take this behavior into account if you implement the `OnCreated()` method in your own partial class. + ## See also - [Debugging Support](debugging-support.md) diff --git a/docs/framework/data/adonet/sql/linq/walkthrough-simple-object-model-and-query-csharp.md b/docs/framework/data/adonet/sql/linq/walkthrough-simple-object-model-and-query-csharp.md index 4f47f9a91a520..f93616596fd63 100644 --- a/docs/framework/data/adonet/sql/linq/walkthrough-simple-object-model-and-query-csharp.md +++ b/docs/framework/data/adonet/sql/linq/walkthrough-simple-object-model-and-query-csharp.md @@ -135,7 +135,7 @@ In this step, you actually execute the query. The query expressions you created 2. Press F5 to debug the application. > [!NOTE] - > If your application generates a run-time error, see the Troubleshooting section of [Learning by Walkthroughs](learning-by-walkthroughs.md). + > If your application generates a runtime error, see the Troubleshooting section of [Learning by Walkthroughs](learning-by-walkthroughs.md). The query results in the console window should appear as follows: diff --git a/docs/framework/data/adonet/sql/linq/walkthrough-simple-object-model-and-query-visual-basic.md b/docs/framework/data/adonet/sql/linq/walkthrough-simple-object-model-and-query-visual-basic.md index f9ef00253d82e..495793c8fc40a 100644 --- a/docs/framework/data/adonet/sql/linq/walkthrough-simple-object-model-and-query-visual-basic.md +++ b/docs/framework/data/adonet/sql/linq/walkthrough-simple-object-model-and-query-visual-basic.md @@ -139,7 +139,7 @@ In this step, you actually execute the query. The query expressions you created 2. Press F5 to debug the application. > [!NOTE] - > If your application generates a run-time error, see the Troubleshooting section of [Learning by Walkthroughs](learning-by-walkthroughs.md). + > If your application generates a runtime error, see the Troubleshooting section of [Learning by Walkthroughs](learning-by-walkthroughs.md). The message box displays a list of six customers. The Console window displays the generated SQL code. diff --git a/docs/framework/data/adonet/sql/provider-statistics-for-sql-server.md b/docs/framework/data/adonet/sql/provider-statistics-for-sql-server.md index cdd08a7e715ef..569a417cbb5ad 100644 --- a/docs/framework/data/adonet/sql/provider-statistics-for-sql-server.md +++ b/docs/framework/data/adonet/sql/provider-statistics-for-sql-server.md @@ -8,7 +8,7 @@ dev_langs: --- # Provider statistics for SQL Server -Starting with .NET Framework version 2.0, the .NET Framework Data Provider for SQL Server supports run-time statistics. You must enable statistics by setting the property of the object to `True` after you have a valid connection object created. +Starting with .NET Framework version 2.0, the .NET Framework Data Provider for SQL Server supports runtime statistics. You must enable statistics by setting the property of the object to `True` after you have a valid connection object created. After statistics are enabled, you can review them as a "snapshot in time" by retrieving an reference via the method of the object. You enumerate through the list as a set of name/value pair dictionary entries. These name/value pairs are unordered. At any time, you can call the method of the object to reset the counters. diff --git a/docs/framework/data/adonet/sql/sql-server-express-user-instances.md b/docs/framework/data/adonet/sql/sql-server-express-user-instances.md index fc507d6707020..a3f7b42c6fb1e 100644 --- a/docs/framework/data/adonet/sql/sql-server-express-user-instances.md +++ b/docs/framework/data/adonet/sql/sql-server-express-user-instances.md @@ -52,7 +52,7 @@ In this connection string: - The `|DataDirectory|` substitution string enclosed in the pipe symbols refers to the data directory of the application opening the connection and provides a relative path indicating the location of the .mdf and .ldf database and log files. If you want to locate these files elsewhere, you must provide the full path to the files. > [!NOTE] -> You can also use the and properties to build a connection string at run time. +> You can also use the and properties to build a connection string at runtime. [!INCLUDE [managed-identities](../../../../includes/managed-identities.md)] @@ -76,7 +76,7 @@ Initial Catalog=Northwind; > [!NOTE] > resolves the substitution strings into full paths against the local computer file system. Therefore, remote server, HTTP, and UNC path names are not supported. An exception is thrown when the connection is opened if the server is not located on the local computer. - When the is opened, it is redirected from the default SQL Server Express instance to a run-time initiated instance running under the caller's account. + When the is opened, it is redirected from the default SQL Server Express instance to a runtime initiated instance running under the caller's account. > [!NOTE] > It may be necessary to increase the value since user instances may take longer to load than regular instances. @@ -137,7 +137,7 @@ private static void OpenSqlConnection() ## User Instance Scenarios - User instances provide developers of database applications with a SQL Server data store that does not depend on developers having administrative accounts on their development computers. User instances are based on the Access/Jet model, where the database application simply connects to a file, and the user automatically has full permissions on all of the database objects without needing the intervention of a system administrator to grant permissions. It is intended to work in situations where the user is running under a least-privilege user account (LUA) and does not have administrative privileges on the server or local machine, yet needs to create database objects and applications. User instances allow users to create instances at run time that run under the user's own security context, and not in the security context of a more privileged system service. + User instances provide developers of database applications with a SQL Server data store that does not depend on developers having administrative accounts on their development computers. User instances are based on the Access/Jet model, where the database application simply connects to a file, and the user automatically has full permissions on all of the database objects without needing the intervention of a system administrator to grant permissions. It is intended to work in situations where the user is running under a least-privilege user account (LUA) and does not have administrative privileges on the server or local machine, yet needs to create database objects and applications. User instances allow users to create instances at runtime that run under the user's own security context, and not in the security context of a more privileged system service. > [!IMPORTANT] > User instances should only be used in scenarios where all the applications using it are fully trusted. diff --git a/docs/framework/data/adonet/sql/sql-server-features-and-adonet.md b/docs/framework/data/adonet/sql/sql-server-features-and-adonet.md index 42916ec9ee93b..f1179de5f64b7 100644 --- a/docs/framework/data/adonet/sql/sql-server-features-and-adonet.md +++ b/docs/framework/data/adonet/sql/sql-server-features-and-adonet.md @@ -7,39 +7,39 @@ ms.assetid: 2839529b-a79b-4450-be5d-07a98dbc7a0f --- # SQL Server Features and ADO.NET -The articles in this section discuss features in SQL Server that are targeted at developing database applications using ADO.NET. - +The articles in this section discuss features in SQL Server that are targeted at developing database applications using ADO.NET. + For more information, see [Development (Database Engine)](/previous-versions/sql/sql-server-2008/bb500155(v=sql.100)). - -## In This Section - - [Enumerating Instances of SQL Server (ADO.NET)](enumerating-instances-of-sql-server.md) - Describes how to enumerate active instances of SQL Server. - - [Provider Statistics for SQL Server](provider-statistics-for-sql-server.md) - Describes support for obtaining SQL Server run-time statistics. - - [SQL Server Express User Instances](sql-server-express-user-instances.md) - Describes support for SQL Server Express user instances. - - [Database Mirroring in SQL Server](database-mirroring-in-sql-server.md) - Describes database mirroring functionality. - - [SQL Server Common Language Runtime Integration](sql-server-common-language-runtime-integration.md) - Describes how data can be accessed from within a common language runtime (CLR) database object in SQL Server. - - [Query Notifications in SQL Server](query-notifications-in-sql-server.md) - Describes how .NET Framework applications can request notification from SQL Server when data has changed. - - [Snapshot Isolation in SQL Server](snapshot-isolation-in-sql-server.md) - Describes support for snapshot isolation, a row versioning mechanism designed to reduce blocking in transactional applications. - - [SqlClient Support for High Availability, Disaster Recovery](sqlclient-support-for-high-availability-disaster-recovery.md) - Describes SqlClient support for high-availability, disaster recovery (AlwaysOn) availability groups. - - [SqlClient Support for LocalDB](sqlclient-support-for-localdb.md) - Describes SqlClient support for LocalDB databases. - + +## In This Section + + [Enumerating Instances of SQL Server (ADO.NET)](enumerating-instances-of-sql-server.md) + Describes how to enumerate active instances of SQL Server. + + [Provider Statistics for SQL Server](provider-statistics-for-sql-server.md) + Describes support for obtaining SQL Server runtime statistics. + + [SQL Server Express User Instances](sql-server-express-user-instances.md) + Describes support for SQL Server Express user instances. + + [Database Mirroring in SQL Server](database-mirroring-in-sql-server.md) + Describes database mirroring functionality. + + [SQL Server Common Language Runtime Integration](sql-server-common-language-runtime-integration.md) + Describes how data can be accessed from within a common language runtime (CLR) database object in SQL Server. + + [Query Notifications in SQL Server](query-notifications-in-sql-server.md) + Describes how .NET Framework applications can request notification from SQL Server when data has changed. + + [Snapshot Isolation in SQL Server](snapshot-isolation-in-sql-server.md) + Describes support for snapshot isolation, a row versioning mechanism designed to reduce blocking in transactional applications. + + [SqlClient Support for High Availability, Disaster Recovery](sqlclient-support-for-high-availability-disaster-recovery.md) + Describes SqlClient support for high-availability, disaster recovery (AlwaysOn) availability groups. + + [SqlClient Support for LocalDB](sqlclient-support-for-localdb.md) + Describes SqlClient support for LocalDB databases. + ## See also - [SQL Server Data Operations in ADO.NET](sql-server-data-operations.md) diff --git a/docs/framework/data/transactions/committing-a-transaction-in-single-phase-and-multi-phase.md b/docs/framework/data/transactions/committing-a-transaction-in-single-phase-and-multi-phase.md index 74423de510155..dcced87b7f19d 100644 --- a/docs/framework/data/transactions/committing-a-transaction-in-single-phase-and-multi-phase.md +++ b/docs/framework/data/transactions/committing-a-transaction-in-single-phase-and-multi-phase.md @@ -2,114 +2,114 @@ title: "Committing a Transaction in Single-Phase and Multi-Phase" description: Read about committing transactions in one or two phases in .NET. A two-phase commit (2PC) must be performed if the transaction involves more than one resource. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 694ea153-e4db-41ae-96ac-9ac66dcb69a9 --- # Committing a Transaction in Single-Phase and Multi-Phase -Each resource used in a transaction is managed by a resource manager (RM), whose actions are coordinated by a transaction manager (TM). The [Enlisting Resources as Participants in a Transaction](enlisting-resources-as-participants-in-a-transaction.md) topic discusses how a resource (or multiple resources) can be enlisted in a transaction. This topic discusses how transaction commitment can be coordinated among enlisted resources. - - At the end of the transaction, the application requests the transaction to be either committed or rolled back. The transaction manager must eliminate risks like some resource managers voting to commit while others voting to roll back the transaction. - - If your transaction involves more than one resource, you must perform a two-phase commit (2PC). The two-phase commit protocol (the prepare phase and the commit phase) ensures that when the transaction ends, all changes to all resources are either totally committed or fully rolled back. All the participants are then informed of the final result. For a detailed discussion of the two-phase commit protocol, please consult the book "*Transaction Processing : Concepts and Techniques (Morgan Kaufmann Series in Data Management Systems) ISBN:1558601902*" by Jim Gray. - - You can also optimize your transaction's performance by taking part in the Single Phase Commit protocol. For more information, see [Optimization using Single Phase Commit and Promotable Single Phase Notification](optimization-spc-and-promotable-spn.md). - - If you just want to be informed of a transaction's outcome, and do not want to participate in voting, you should register for the event. - -## Two-phase Commit (2PC) - - In the first transaction phase, the transaction manager queries each resource to determine whether a transaction should be committed or rolled back. In the second transaction phase, the transaction manager notifies each resource of the outcome of its queries, allowing it to perform any necessary cleanup. - - To participate in this kind of transaction, a resource manager must implement the interface, which provides methods that are called by the TM as notifications during a 2PC. The following sample shows an example of such implementation. - +Each resource used in a transaction is managed by a resource manager (RM), whose actions are coordinated by a transaction manager (TM). The [Enlisting Resources as Participants in a Transaction](enlisting-resources-as-participants-in-a-transaction.md) topic discusses how a resource (or multiple resources) can be enlisted in a transaction. This topic discusses how transaction commitment can be coordinated among enlisted resources. + + At the end of the transaction, the application requests the transaction to be either committed or rolled back. The transaction manager must eliminate risks like some resource managers voting to commit while others voting to roll back the transaction. + + If your transaction involves more than one resource, you must perform a two-phase commit (2PC). The two-phase commit protocol (the prepare phase and the commit phase) ensures that when the transaction ends, all changes to all resources are either totally committed or fully rolled back. All the participants are then informed of the final result. For a detailed discussion of the two-phase commit protocol, please consult the book "*Transaction Processing : Concepts and Techniques (Morgan Kaufmann Series in Data Management Systems) ISBN:1558601902*" by Jim Gray. + + You can also optimize your transaction's performance by taking part in the Single Phase Commit protocol. For more information, see [Optimization using Single Phase Commit and Promotable Single Phase Notification](optimization-spc-and-promotable-spn.md). + + If you just want to be informed of a transaction's outcome, and do not want to participate in voting, you should register for the event. + +## Two-phase Commit (2PC) + + In the first transaction phase, the transaction manager queries each resource to determine whether a transaction should be committed or rolled back. In the second transaction phase, the transaction manager notifies each resource of the outcome of its queries, allowing it to perform any necessary cleanup. + + To participate in this kind of transaction, a resource manager must implement the interface, which provides methods that are called by the TM as notifications during a 2PC. The following sample shows an example of such implementation. + [!code-csharp[Tx_Enlist#2](../../../../samples/snippets/csharp/VS_Snippets_CFX/tx_enlist/cs/enlist.cs#2)] - [!code-vb[Tx_Enlist#2](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/tx_enlist/vb/enlist.vb#2)] - -### Prepare phase (Phase 1) - - Upon receiving a request from the application, the transaction manager begins the Prepare phase of all the enlisted participants by calling the method on each enlisted resource, in order to obtain each resource's vote on the transaction. - - Your resource manager that implements the interface should first implement the method as the following simple example shows. - + [!code-vb[Tx_Enlist#2](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/tx_enlist/vb/enlist.vb#2)] + +### Prepare phase (Phase 1) + + Upon receiving a request from the application, the transaction manager begins the Prepare phase of all the enlisted participants by calling the method on each enlisted resource, in order to obtain each resource's vote on the transaction. + + Your resource manager that implements the interface should first implement the method as the following simple example shows. + ```csharp -public void Prepare(PreparingEnlistment preparingEnlistment) -{ - Console.WriteLine("Prepare notification received"); - //Perform work - - Console.Write("reply with prepared? [Y|N] "); - c = Console.ReadKey(); - Console.WriteLine(); - - //If work finished correctly, reply with prepared - if ((c.KeyChar == 'Y') || (c.KeyChar == 'y')) - { - preparingEnlistment.Prepared(); - break; - } - - // otherwise, do a ForceRollback - else if ((c.KeyChar == 'N') || (c.KeyChar == 'n')) - { - preparingEnlistment.ForceRollback(); - break; - } -} -``` - - When the durable resource manager receives this call, it should log the transaction's recovery information (available by retrieving the property) and whatever information is necessary to complete the transaction on commit. This does not need to be performed within the method because the RM can do this on a worker thread. - - When the RM has finished its prepare work, it should vote to commit or roll back by calling the or method. Notice that the class inherits a method from the class. If you call this method on the callback during the Prepare phase, it informs the TM that it is a Read-Only enlistment (that is, resource managers that can read but cannot update transaction-protected data) and the RM receives no further notifications from the transaction manager as to the outcome of the transaction in phase 2. - - The application is told of the successful commitment of the transaction after all the resource managers vote . - -### Commit phase (Phase 2) - - In the second phase of the transaction, if the transaction manager receives successful prepares from all the resource managers (all the resource managers have invoked at the end of phase 1), it invokes the method for each resource manager. The resource managers can then make the changes durable and complete the commit. - - If any resource manager reported a failure to prepare in phase 1, the transaction manager invokes the method for each resource manager and indicates the failure of the commit to the application. - - Thus, your resource manager should implement the following methods. - +public void Prepare(PreparingEnlistment preparingEnlistment) +{ + Console.WriteLine("Prepare notification received"); + //Perform work + + Console.Write("reply with prepared? [Y|N] "); + c = Console.ReadKey(); + Console.WriteLine(); + + //If work finished correctly, reply with prepared + if ((c.KeyChar == 'Y') || (c.KeyChar == 'y')) + { + preparingEnlistment.Prepared(); + break; + } + + // otherwise, do a ForceRollback + else if ((c.KeyChar == 'N') || (c.KeyChar == 'n')) + { + preparingEnlistment.ForceRollback(); + break; + } +} +``` + + When the durable resource manager receives this call, it should log the transaction's recovery information (available by retrieving the property) and whatever information is necessary to complete the transaction on commit. This does not need to be performed within the method because the RM can do this on a worker thread. + + When the RM has finished its prepare work, it should vote to commit or roll back by calling the or method. Notice that the class inherits a method from the class. If you call this method on the callback during the Prepare phase, it informs the TM that it is a Read-Only enlistment (that is, resource managers that can read but cannot update transaction-protected data) and the RM receives no further notifications from the transaction manager as to the outcome of the transaction in phase 2. + + The application is told of the successful commitment of the transaction after all the resource managers vote . + +### Commit phase (Phase 2) + + In the second phase of the transaction, if the transaction manager receives successful prepares from all the resource managers (all the resource managers have invoked at the end of phase 1), it invokes the method for each resource manager. The resource managers can then make the changes durable and complete the commit. + + If any resource manager reported a failure to prepare in phase 1, the transaction manager invokes the method for each resource manager and indicates the failure of the commit to the application. + + Thus, your resource manager should implement the following methods. + ```csharp -public void Commit (Enlistment enlistment) -{ - // Do any work necessary when commit notification is received - - // Declare done on the enlistment - enlistment.Done(); -} - -public void Rollback (Enlistment enlistment) -{ - // Do any work necessary when rollback notification is received - +public void Commit (Enlistment enlistment) +{ + // Do any work necessary when commit notification is received + + // Declare done on the enlistment + enlistment.Done(); +} + +public void Rollback (Enlistment enlistment) +{ + // Do any work necessary when rollback notification is received + // Declare done on the enlistment enlistment.Done(); -} -``` - - The RM should perform any work necessary to finish the transaction based on the notification type, and inform the TM that it has finished by calling method on the parameter. This work can be done on a worker thread. Note that the phase 2 notifications can happen inline on the same thread that called the method in phase 1. As such, you should not do any work after the call (for example, releasing locks) that you would expect to have completed before receiving the phase 2 notifications. - -### Implementing InDoubt - - Finally, you should implement the method for the volatile resource manager. This method is called if the transaction manager loses contact with one or more participants, so their status is unknown. If this occurs, you should log this fact so that you can investigate later whether any of the transaction participants has been left in an inconsistent state. - +} +``` + + The RM should perform any work necessary to finish the transaction based on the notification type, and inform the TM that it has finished by calling method on the parameter. This work can be done on a worker thread. Note that the phase 2 notifications can happen inline on the same thread that called the method in phase 1. As such, you should not do any work after the call (for example, releasing locks) that you would expect to have completed before receiving the phase 2 notifications. + +### Implementing InDoubt + + Finally, you should implement the method for the volatile resource manager. This method is called if the transaction manager loses contact with one or more participants, so their status is unknown. If this occurs, you should log this fact so that you can investigate later whether any of the transaction participants has been left in an inconsistent state. + ```csharp -public void InDoubt (Enlistment enlistment) -{ - // log this - enlistment.Done(); -} -``` - -## Single Phase Commit Optimization - - The Single Phase Commit protocol is more efficient at run time because all updates are done without any explicit coordination. For more information on this protocol, see [Optimization using Single Phase Commit and Promotable Single Phase Notification](optimization-spc-and-promotable-spn.md). - +public void InDoubt (Enlistment enlistment) +{ + // log this + enlistment.Done(); +} +``` + +## Single Phase Commit Optimization + + The Single Phase Commit protocol is more efficient at runtime because all updates are done without any explicit coordination. For more information on this protocol, see [Optimization using Single Phase Commit and Promotable Single Phase Notification](optimization-spc-and-promotable-spn.md). + ## See also - [Optimization using Single Phase Commit and Promotable Single Phase Notification](optimization-spc-and-promotable-spn.md) diff --git a/docs/framework/data/transactions/optimization-spc-and-promotable-spn.md b/docs/framework/data/transactions/optimization-spc-and-promotable-spn.md index 48807e935a1e5..4d47bb851f574 100644 --- a/docs/framework/data/transactions/optimization-spc-and-promotable-spn.md +++ b/docs/framework/data/transactions/optimization-spc-and-promotable-spn.md @@ -17,7 +17,7 @@ However, if the transaction is provided to another object in another application To optimize performance, the infrastructure provides the Promotable Single Phase Enlistment (PSPE) that allows a single remote durable resource, located in a different application domain, process or machine, to participate in a transaction without causing it to be escalated to an MSDTC transaction. This resource manager (RM) can host and "own" a transaction that can later be escalated to a distributed transaction (or MSDTC transaction) if necessary. This reduces the chance of using the MSDTC. -This specific resource manager usually has its own internal non distributed transactions and it needs to support converting those transactions to distributed transactions at run time. For example, SQL Server 2005 is such a resource manager. In such case, the infrastructure takes a passive management role by just monitoring the transaction for a need for escalation. To support the interaction between the infrastructure and resource manager, the latter needs to implement the interface . +This specific resource manager usually has its own internal non distributed transactions and it needs to support converting those transactions to distributed transactions at runtime. For example, SQL Server 2005 is such a resource manager. In such case, the infrastructure takes a passive management role by just monitoring the transaction for a need for escalation. To support the interaction between the infrastructure and resource manager, the latter needs to implement the interface . The method is used to enlist a single durable resource that can be escalated later. This method ensures that the enlistment can be escalated as needed. If the enlistment succeeds, the RM creates its internal transaction and associates it with the transaction. If the PSPE enlistment fails, the RM should instead enlist using the method. Failures to enlist in PSPE might happen when the transaction is already a distributed transaction, or when another RM has already performed a PSPE enlistment @@ -54,7 +54,7 @@ In this scenario, ## Single Phase Commit Optimization -The Single Phase Commit protocol is more efficient at run time as all updates are done without any explicit coordination. To take advantage of this optimization, you should implement a resource manager using interface for the resource and enlist in a transaction using the or method. Specifically, the *EnlistmentOptions* parameter should equal to to ensure that a single phase commit would be performed. +The Single Phase Commit protocol is more efficient at runtime as all updates are done without any explicit coordination. To take advantage of this optimization, you should implement a resource manager using interface for the resource and enlist in a transaction using the or method. Specifically, the *EnlistmentOptions* parameter should equal to to ensure that a single phase commit would be performed. Since the interface derives from the interface, if your RM is not eligible for single phase commit, it can still receive the two phase commit notifications. If your RM receives a notification from the TM, it should try to do the work necessary for it to commit and correspondingly inform the transaction manager if the transaction is to be committed or rolled back by calling the , , or method on the parameter. A response of on the enlistment at this stage implies ReadOnly semantics. Therefore, you should not reply in addition to any of the other methods. diff --git a/docs/framework/debug-trace-profile/callbackoncollecteddelegate-mda.md b/docs/framework/debug-trace-profile/callbackoncollecteddelegate-mda.md index b3788b7d6c7a9..6d1a21ae657c2 100644 --- a/docs/framework/debug-trace-profile/callbackoncollecteddelegate-mda.md +++ b/docs/framework/debug-trace-profile/callbackoncollecteddelegate-mda.md @@ -12,7 +12,7 @@ helpviewer_keywords: - "callbackOnCollectedDelegate MDA" - "managed debugging assistants (MDAs), garbage collection" - "call back collected delegates" - - "garbage collection, run-time errors" + - "garbage collection, runtime errors" - "delegates [.NET Framework], garbage collection" ms.assetid: 398b0ce0-5cc9-4518-978d-b8263aa21e5b --- diff --git a/docs/framework/debug-trace-profile/code-contracts.md b/docs/framework/debug-trace-profile/code-contracts.md index 3c6ebe86e64d9..1ec523e08ee96 100644 --- a/docs/framework/debug-trace-profile/code-contracts.md +++ b/docs/framework/debug-trace-profile/code-contracts.md @@ -39,7 +39,7 @@ For tools and detailed instructions for using code contracts, see [Code Contract ## Preconditions -You can express preconditions by using the method. Preconditions specify state when a method is invoked. They are generally used to specify valid parameter values. All members that are mentioned in preconditions must be at least as accessible as the method itself; otherwise, the precondition might not be understood by all callers of a method. The condition must have no side-effects. The run-time behavior of failed preconditions is determined by the runtime analyzer. +You can express preconditions by using the method. Preconditions specify state when a method is invoked. They are generally used to specify valid parameter values. All members that are mentioned in preconditions must be at least as accessible as the method itself; otherwise, the precondition might not be understood by all callers of a method. The condition must have no side-effects. The runtime behavior of failed preconditions is determined by the runtime analyzer. For example, the following precondition expresses that parameter `x` must be non-null. @@ -72,7 +72,7 @@ Note that the condition in the preceding test is a negated precondition. (The ac ## Postconditions -Postconditions are contracts for the state of a method when it terminates. The postcondition is checked just before exiting a method. The run-time behavior of failed postconditions is determined by the runtime analyzer. +Postconditions are contracts for the state of a method when it terminates. The postcondition is checked just before exiting a method. The runtime behavior of failed postconditions is determined by the runtime analyzer. Unlike preconditions, postconditions may reference members with less visibility. A client may not be able to understand or make use of some of the information expressed by a postcondition using private state, but this does not affect the client's ability to use the method correctly. @@ -164,7 +164,7 @@ protected void ObjectInvariant () } ``` -Invariants are conditionally defined by the CONTRACTS_FULL preprocessor symbol. During run-time checking, invariants are checked at the end of each public method. If an invariant mentions a public method in the same class, the invariant check that would normally happen at the end of that public method is disabled. Instead, the check occurs only at the end of the outermost method call to that class. This also happens if the class is re-entered because of a call to a method on another class. Invariants are not checked for an object finalizer and an implementation. +Invariants are conditionally defined by the CONTRACTS_FULL preprocessor symbol. During runtime checking, invariants are checked at the end of each public method. If an invariant mentions a public method in the same class, the invariant check that would normally happen at the end of that public method is disabled. Instead, the check occurs only at the end of the outermost method call to that class. This also happens if the class is re-entered because of a call to a method on another class. Invariants are not checked for an object finalizer and an implementation. diff --git a/docs/framework/debug-trace-profile/diagnosing-errors-with-managed-debugging-assistants.md b/docs/framework/debug-trace-profile/diagnosing-errors-with-managed-debugging-assistants.md index 0bb7b597f2621..4c3ece72622c0 100644 --- a/docs/framework/debug-trace-profile/diagnosing-errors-with-managed-debugging-assistants.md +++ b/docs/framework/debug-trace-profile/diagnosing-errors-with-managed-debugging-assistants.md @@ -5,8 +5,8 @@ ms.date: 08/14/2018 f1_keywords: - "EHMDA" helpviewer_keywords: - - "run-time error debugging" - - "managed code, run-time debugging" + - "runtime error debugging" + - "managed code, runtime debugging" - "resource debugging" - "registry, MDAs" - "common language runtime, debugging" @@ -18,12 +18,12 @@ helpviewer_keywords: - "environment variables, MDAs" - "access violation debugging [.NET Framework]" - "diagnostics, managed debugging assistants" - - "unmanaged code, run-time debugging" + - "unmanaged code, runtime debugging" - "default debug output stream" - "memory, debugging" - "app.config files, managed debugging assistants" - "managed debugging assistants (MDAs)" - - "debugging [.NET Framework], run-time errors" + - "debugging [.NET Framework], runtime errors" - "trapping events" - "runtime, error debugging" - "disabling MDAs" diff --git a/docs/framework/debug-trace-profile/gcmanagedtounmanaged-mda.md b/docs/framework/debug-trace-profile/gcmanagedtounmanaged-mda.md index 3f67d2057b8ee..79e722ab30672 100644 --- a/docs/framework/debug-trace-profile/gcmanagedtounmanaged-mda.md +++ b/docs/framework/debug-trace-profile/gcmanagedtounmanaged-mda.md @@ -11,7 +11,7 @@ helpviewer_keywords: - "managed to unmanaged garbage collection" - "managed debugging assistants (MDAs), garbage collection" - "threading [.NET Framework], managed debugging assistants" - - "garbage collection, run-time errors" + - "garbage collection, runtime errors" ms.assetid: 7417f837-805e-4fed-a430-ca919c8421dc --- # gcManagedToUnmanaged MDA diff --git a/docs/framework/debug-trace-profile/gcunmanagedtomanaged-mda.md b/docs/framework/debug-trace-profile/gcunmanagedtomanaged-mda.md index de271de1af30f..50a6d834495ae 100644 --- a/docs/framework/debug-trace-profile/gcunmanagedtomanaged-mda.md +++ b/docs/framework/debug-trace-profile/gcunmanagedtomanaged-mda.md @@ -10,7 +10,7 @@ helpviewer_keywords: - "threading [.NET Framework], garbage collection" - "managed debugging assistants (MDAs), garbage collection" - "threading [.NET Framework], managed debugging assistants" - - "garbage collection, run-time errors" + - "garbage collection, runtime errors" - "unmanaged to managed garbage collection" ms.assetid: 103eb3a3-1cf0-4406-8a9a-a7798fdc22d1 --- diff --git a/docs/framework/debug-trace-profile/how-to-create-and-initialize-trace-sources.md b/docs/framework/debug-trace-profile/how-to-create-and-initialize-trace-sources.md index f228c418c2d47..ee1c853749c5b 100644 --- a/docs/framework/debug-trace-profile/how-to-create-and-initialize-trace-sources.md +++ b/docs/framework/debug-trace-profile/how-to-create-and-initialize-trace-sources.md @@ -15,7 +15,7 @@ ms.assetid: f88dda6f-5fda-45be-9b3c-745a9b708c4d [!INCLUDE [net-framework-specific](../includes/net-framework-specific.md)] -The class is used by applications to produce traces that can be associated with the application. provides tracing methods that allow you to easily trace events, trace data, and issue informational traces. Trace output from can be created and initialized with or without the use of configuration files. This topic provides instructions for both options. However, we recommend that you use configuration files to facilitate the reconfiguration of the traces produced by trace sources at run time. +The class is used by applications to produce traces that can be associated with the application. provides tracing methods that allow you to easily trace events, trace data, and issue informational traces. Trace output from can be created and initialized with or without the use of configuration files. This topic provides instructions for both options. However, we recommend that you use configuration files to facilitate the reconfiguration of the traces produced by trace sources at runtime. ### To create and initialize a trace source using a configuration file diff --git a/docs/framework/debug-trace-profile/invalidcercall-mda.md b/docs/framework/debug-trace-profile/invalidcercall-mda.md index 99db6fd4475fc..805731a45268b 100644 --- a/docs/framework/debug-trace-profile/invalidcercall-mda.md +++ b/docs/framework/debug-trace-profile/invalidcercall-mda.md @@ -19,7 +19,7 @@ The `invalidCERCall` managed debugging assistant (MDA) is activated when there i ## Symptoms - Unexpected results when executing code in a CER. The symptoms are not specific. They could be an unexpected , a , or other exceptions at the call into the unreliable method because the runtime did not prepare it ahead of time or protect it from exceptions at run time. A greater threat is that any exception resulting from the method at run time could leave the or process in an unstable state, which is contrary to the objective of a CER. The reason a CER is created is to avoid state corruptions such as this. The symptoms of corrupt state are application specific because the definition of consistent state is different between applications. + Unexpected results when executing code in a CER. The symptoms are not specific. They could be an unexpected , a , or other exceptions at the call into the unreliable method because the runtime did not prepare it ahead of time or protect it from exceptions at runtime. A greater threat is that any exception resulting from the method at runtime could leave the or process in an unstable state, which is contrary to the objective of a CER. The reason a CER is created is to avoid state corruptions such as this. The symptoms of corrupt state are application specific because the definition of consistent state is different between applications. ## Cause diff --git a/docs/framework/debug-trace-profile/invalidfunctionpointerindelegate-mda.md b/docs/framework/debug-trace-profile/invalidfunctionpointerindelegate-mda.md index 35b7665974346..17c1b38a55d51 100644 --- a/docs/framework/debug-trace-profile/invalidfunctionpointerindelegate-mda.md +++ b/docs/framework/debug-trace-profile/invalidfunctionpointerindelegate-mda.md @@ -7,7 +7,7 @@ helpviewer_keywords: - "managed debugging assistants (MDAs), invalid function pointer to delegates" - "MDAs (managed debugging assistants), invalid function pointer to delegates" - "function pointers, invalid" - - "marshaling, run-time errors" + - "marshaling, runtime errors" - "managed debugging assistants (MDAs), marshalling" - "MDAs (managed debugging assistants), marshalling" - "invalid function pointers" diff --git a/docs/framework/debug-trace-profile/invalidmemberdeclaration-mda.md b/docs/framework/debug-trace-profile/invalidmemberdeclaration-mda.md index e95b085b1af93..e6f401ff5e629 100644 --- a/docs/framework/debug-trace-profile/invalidmemberdeclaration-mda.md +++ b/docs/framework/debug-trace-profile/invalidmemberdeclaration-mda.md @@ -5,7 +5,7 @@ ms.date: "03/30/2017" helpviewer_keywords: - "invalid member declaration" - "InvalidMemberDeclaration MDA" - - "marshaling, run-time errors" + - "marshaling, runtime errors" - "managed debugging assistants (MDAs), marshalling" - "MDAs (managed debugging assistants), marshalling" ms.assetid: a84dd9a3-d6cf-4824-989a-ecbbf443eeb4 diff --git a/docs/framework/debug-trace-profile/marshalcleanuperror-mda.md b/docs/framework/debug-trace-profile/marshalcleanuperror-mda.md index bbe4803a1ef4e..e01318131f034 100644 --- a/docs/framework/debug-trace-profile/marshalcleanuperror-mda.md +++ b/docs/framework/debug-trace-profile/marshalcleanuperror-mda.md @@ -4,7 +4,7 @@ description: Review the marshalCleanupError managed debugging assistant (MDA), w ms.date: "03/30/2017" helpviewer_keywords: - "cleanup operations" - - "marshaling, run-time errors" + - "marshaling, runtime errors" - "managed debugging assistants (MDAs), marshalling" - "MDAs (managed debugging assistants), marshalling" - "marshaling cleanup error" diff --git a/docs/framework/debug-trace-profile/marshaling-mda.md b/docs/framework/debug-trace-profile/marshaling-mda.md index 75132483c8b86..c0e73fbe57a37 100644 --- a/docs/framework/debug-trace-profile/marshaling-mda.md +++ b/docs/framework/debug-trace-profile/marshaling-mda.md @@ -3,7 +3,7 @@ title: "marshaling MDA" description: Review the marshaling managed debugging assistant (MDA), which is invoked if the CLR sets up marshalling information for a method parameter or a structure field. ms.date: "03/30/2017" helpviewer_keywords: - - "marshalling, run-time errors" + - "marshalling, runtime errors" - "marshaling MDA" - "managed debugging assistants (MDAs), marshaling" - "MDAs (managed debugging assistants), marshaling" diff --git a/docs/framework/debug-trace-profile/memberinfocachecreation-mda.md b/docs/framework/debug-trace-profile/memberinfocachecreation-mda.md index 38caf2afc1724..5f8ca78abedc1 100644 --- a/docs/framework/debug-trace-profile/memberinfocachecreation-mda.md +++ b/docs/framework/debug-trace-profile/memberinfocachecreation-mda.md @@ -5,7 +5,7 @@ ms.date: "03/30/2017" helpviewer_keywords: - "member info cache creation" - "MemberInfoCacheCreation MDA" - - "reflection, run-time errors" + - "reflection, runtime errors" - "MDAs (managed debugging assistants), cache" - "cache [.NET Framework], reflection" - "managed debugging assistants (MDAs), cache" diff --git a/docs/framework/debug-trace-profile/notmarshalable-mda.md b/docs/framework/debug-trace-profile/notmarshalable-mda.md index 0ac86612494d4..6556ffce42340 100644 --- a/docs/framework/debug-trace-profile/notmarshalable-mda.md +++ b/docs/framework/debug-trace-profile/notmarshalable-mda.md @@ -6,7 +6,7 @@ helpviewer_keywords: - "managed debugging assistants (MDAs), interface pointer not marshalable" - "interface pointer not marshalable MDA" - "MDAs (managed debugging assistants), interface pointer not marshalable" - - "marshaling, run-time errors" + - "marshaling, runtime errors" - "managed debugging assistants (MDAs), marshalling" - "marshalable interface pointers" - "MDAs (managed debugging assistants), marshalling" diff --git a/docs/framework/debug-trace-profile/opengenericcercall-mda.md b/docs/framework/debug-trace-profile/opengenericcercall-mda.md index 616c03a676231..4226667fae315 100644 --- a/docs/framework/debug-trace-profile/opengenericcercall-mda.md +++ b/docs/framework/debug-trace-profile/opengenericcercall-mda.md @@ -24,9 +24,9 @@ CER code does not run when a thread is aborted or when an application domain is ## Cause -At JIT-compilation time, an instantiation containing an object reference type is only representative because the resultant code is shared, and each of the object reference type variables might be any object reference type. This can prevent the preparation of some run-time resources ahead of time. +At JIT-compilation time, an instantiation containing an object reference type is only representative because the resultant code is shared, and each of the object reference type variables might be any object reference type. This can prevent the preparation of some runtime resources ahead of time. -In particular, methods with generic type variables can lazily allocate resources in the background. These are referred to as generic dictionary entries. For instance, for the statement `List list = new List();` where `T` is a generic type variable the runtime must look up and possibly create the exact instantiation at run time, for example, `List, List`, and so forth. This can fail for a variety of reasons beyond the developer's control, such as running out of memory. +In particular, methods with generic type variables can lazily allocate resources in the background. These are referred to as generic dictionary entries. For instance, for the statement `List list = new List();` where `T` is a generic type variable the runtime must look up and possibly create the exact instantiation at runtime, for example, `List, List`, and so forth. This can fail for a variety of reasons beyond the developer's control, such as running out of memory. This MDA should only be activated at JIT-compilation time, not when there is an exact instantiation. @@ -46,7 +46,7 @@ The following is a sample of output from this MDA: ```output Method 'GenericMethodWithCer', which contains at least one constrained execution region, cannot be prepared automatically since it has one or more unbound generic type parameters. - The caller must ensure this method is prepared explicitly at run time prior to execution. + The caller must ensure this method is prepared explicitly at runtime prior to execution. method name="GenericMethodWithCer" declaringType name="OpenGenericCERCall" ``` @@ -84,7 +84,7 @@ class Program // This call is incorrect. A shared version of the method that // cannot be completely analyzed will be JIT-compiled. The - // MDA will be activated at JIT-compile time, not at run time. + // MDA will be activated at JIT-compile time, not at runtime. MyClass.GenericMethodWithCer(); } } diff --git a/docs/framework/debug-trace-profile/pinvokelog-mda.md b/docs/framework/debug-trace-profile/pinvokelog-mda.md index 3fe9df02ccd9e..5fe63b8b03012 100644 --- a/docs/framework/debug-trace-profile/pinvokelog-mda.md +++ b/docs/framework/debug-trace-profile/pinvokelog-mda.md @@ -5,7 +5,7 @@ ms.date: "03/30/2017" helpviewer_keywords: - "signatures, platform invoke" - "MDAs (managed debugging assistants), platform invoke" - - "platform invoke, run-time errors" + - "platform invoke, runtime errors" - "platform invoke log" - "PInvokeLog MDA" - "managed debugging assistants (MDAs), platform invoke" diff --git a/docs/framework/debug-trace-profile/pinvokestackimbalance-mda.md b/docs/framework/debug-trace-profile/pinvokestackimbalance-mda.md index c41b76660d667..80fd9f90007a9 100644 --- a/docs/framework/debug-trace-profile/pinvokestackimbalance-mda.md +++ b/docs/framework/debug-trace-profile/pinvokestackimbalance-mda.md @@ -7,7 +7,7 @@ helpviewer_keywords: - "stack depth" - "platform invoke stack imbalance" - "MDAs (managed debugging assistants), platform invoke" - - "platform invoke, run-time errors" + - "platform invoke, runtime errors" - "PInvokeStackImbalance MDA" - "managed debugging assistants (MDAs), platform invoke" ms.assetid: 34ddc6bd-1675-4f35-86aa-de1645d5c631 diff --git a/docs/framework/debug-trace-profile/releasehandlefailed-mda.md b/docs/framework/debug-trace-profile/releasehandlefailed-mda.md index 1f2d59f1e094e..04501579da8f1 100644 --- a/docs/framework/debug-trace-profile/releasehandlefailed-mda.md +++ b/docs/framework/debug-trace-profile/releasehandlefailed-mda.md @@ -5,10 +5,10 @@ ms.date: "03/30/2017" helpviewer_keywords: - "managed debugging assistants (MDAs), handles" - "release handle failed" - - "CriticalHandle class, run-time errors" + - "CriticalHandle class, runtime errors" - "releaseHandleFailed MDA" - "ReleaseHandle method" - - "SafeHandle class, run-time errors" + - "SafeHandle class, runtime errors" - "MDAs (managed debugging assistants), handles" ms.assetid: 44cd98ba-95e5-40a1-874d-e8e163612c51 --- diff --git a/docs/framework/debug-trace-profile/tracing-and-instrumenting-applications.md b/docs/framework/debug-trace-profile/tracing-and-instrumenting-applications.md index 4dc6942461c8b..56a7a64925471 100644 --- a/docs/framework/debug-trace-profile/tracing-and-instrumenting-applications.md +++ b/docs/framework/debug-trace-profile/tracing-and-instrumenting-applications.md @@ -23,7 +23,7 @@ Tracing is a way for you to monitor the execution of your application while it i The term *instrumentation* refers to an ability to monitor or measure the level of a product's performance and to diagnose errors. In programming, this means the ability of an application to incorporate: -- **Code tracing** - Receiving informative messages about the execution of an application at run time. +- **Code tracing** - Receiving informative messages about the execution of an application at runtime. - **Debugging** - Tracking down and fixing programming errors in an application under development. For more information, see [Debugging](/visualstudio/debugger/debugger-feature-tour). @@ -95,7 +95,7 @@ System.Diagnostics.Debug.WriteLine("Hello World!"); - Use the **Trace** and **Debug** compiler directives for the command-line method of compiling. For more information, see [Compiling Conditionally with Trace and Debug](how-to-compile-conditionally-with-trace-and-debug.md). Use this when compiling from the command line. -7. If a problem occurs during run time, turn on the appropriate trace switch. For more information, see [Configuring Trace Switches](how-to-create-initialize-and-configure-trace-switches.md). +7. If a problem occurs during runtime, turn on the appropriate trace switch. For more information, see [Configuring Trace Switches](how-to-create-initialize-and-configure-trace-switches.md). The tracing code writes tracing messages to a specified target, for example, a screen, a text file, or an event log. The type of listener you included in the collection determines the target. @@ -105,13 +105,13 @@ System.Diagnostics.Debug.WriteLine("Hello World!"); When you create a distributed application, you might find it difficult to test the application in the manner in which it will be used. Few development teams have the capability to test all possible combinations of operating systems or Web browsers (including all the localized language options), or to simulate the high number of users that will access the application at the same time. Under these circumstances, you cannot test how a distributed application will respond to high volumes, different setups, and unique end-user behaviors. Also, many parts of a distributed application have no user interface with which you can interact directly or view the activity of those parts. - However, you can compensate for this by enabling distributed applications to describe certain events of interest to system administrators, especially things that go wrong, by *instrumenting* the application — that is, by placing trace statements at strategic locations in your code. Then if something unexpected occurs at run time (for example, excessively slow response time), you can determine the likely cause. + However, you can compensate for this by enabling distributed applications to describe certain events of interest to system administrators, especially things that go wrong, by *instrumenting* the application — that is, by placing trace statements at strategic locations in your code. Then if something unexpected occurs at runtime (for example, excessively slow response time), you can determine the likely cause. - With trace statements you can avoid the difficult task of examining the original source code, modifying it, recompiling, and attempting to produce the run-time error within the debugging environment. Remember that you can instrument an application not only to display errors, but also to monitor performance. + With trace statements you can avoid the difficult task of examining the original source code, modifying it, recompiling, and attempting to produce the runtime error within the debugging environment. Remember that you can instrument an application not only to display errors, but also to monitor performance. ## Strategic Placement of Trace Statements - You must exercise special care when placing your trace statements for use during run time. You must consider what tracing information is likely to be needed in a deployed application, so that all likely tracing scenarios are adequately covered. Because applications that use tracing vary widely, however, there are no general guidelines for strategic placement of tracing. For more information on placing trace statements, see [How to: Add Trace Statements to Application Code](how-to-add-trace-statements-to-application-code.md). + You must exercise special care when placing your trace statements for use during runtime. You must consider what tracing information is likely to be needed in a deployed application, so that all likely tracing scenarios are adequately covered. Because applications that use tracing vary widely, however, there are no general guidelines for strategic placement of tracing. For more information on placing trace statements, see [How to: Add Trace Statements to Application Code](how-to-add-trace-statements-to-application-code.md). ## Output from Tracing diff --git a/docs/framework/debug-trace-profile/virtualcercall-mda.md b/docs/framework/debug-trace-profile/virtualcercall-mda.md index 269aafd2815f3..a1523d20238d4 100644 --- a/docs/framework/debug-trace-profile/virtualcercall-mda.md +++ b/docs/framework/debug-trace-profile/virtualcercall-mda.md @@ -15,7 +15,7 @@ ms.assetid: 1eb18c7a-f5e0-443f-80fb-67bfbb047da2 [!INCLUDE [net-framework-specific](../includes/net-framework-specific.md)] -The `virtualCERCall` managed debugging assistant (MDA) is activated as a warning indicating that a call site within a constrained execution region (CER) call graph refers to a virtual target, that is, a virtual call to a non-final virtual method or a call using an interface. The common language runtime (CLR) cannot predict the destination method of these calls from the intermediate language and metadata analysis alone. As a result, the call tree cannot be prepared as part of the CER graph and thread aborts in that subtree cannot be automatically blocked. This MDA warns of cases where a CER might need to be extended by using explicit calls to the method once the additional information required to compute the call target is known at run time. +The `virtualCERCall` managed debugging assistant (MDA) is activated as a warning indicating that a call site within a constrained execution region (CER) call graph refers to a virtual target, that is, a virtual call to a non-final virtual method or a call using an interface. The common language runtime (CLR) cannot predict the destination method of these calls from the intermediate language and metadata analysis alone. As a result, the call tree cannot be prepared as part of the CER graph and thread aborts in that subtree cannot be automatically blocked. This MDA warns of cases where a CER might need to be extended by using explicit calls to the method once the additional information required to compute the call target is known at runtime. ## Symptoms diff --git a/docs/framework/get-started/index.md b/docs/framework/get-started/index.md index ce03122485ba7..7e8d7436c6d3e 100644 --- a/docs/framework/get-started/index.md +++ b/docs/framework/get-started/index.md @@ -9,7 +9,7 @@ ms.assetid: c693fd34-88fe-4d90-b332-19eeadf3b7e7 --- # Get started with .NET Framework -.NET Framework is a run-time execution environment that manages apps that target .NET Framework. It consists of the common language runtime, which provides memory management and other system services, and an extensive class library, which enables programmers to take advantage of robust, reliable code for all major areas of app development. +.NET Framework is a runtime execution environment that manages apps that target .NET Framework. It consists of the common language runtime, which provides memory management and other system services, and an extensive class library, which enables programmers to take advantage of robust, reliable code for all major areas of app development. [!INCLUDE [net-framework-future](../../../includes/net-framework-future.md)] @@ -25,7 +25,7 @@ ms.assetid: c693fd34-88fe-4d90-b332-19eeadf3b7e7 - Development frameworks and technologies. .NET Framework includes libraries for specific areas of app development, such as ASP.NET for web apps, ADO.NET for data access, Windows Communication Foundation for service-oriented apps, and Windows Presentation Foundation for Windows desktop apps. -- Language interoperability. Language compilers that target .NET Framework emit an intermediate code named Common Intermediate Language (CIL), which, in turn, is compiled at run time by the common language runtime. With this feature, routines written in one language are accessible to other languages, and programmers focus on creating apps in their preferred languages. +- Language interoperability. Language compilers that target .NET Framework emit an intermediate code named Common Intermediate Language (CIL), which, in turn, is compiled at runtime by the common language runtime. With this feature, routines written in one language are accessible to other languages, and programmers focus on creating apps in their preferred languages. - Version compatibility. With rare exceptions, apps that are developed by using a particular version of .NET Framework run without modification on a later version. diff --git a/docs/framework/install/guide-for-developers.md b/docs/framework/install/guide-for-developers.md index b6346f2d6a5fc..2b59d006d1d68 100644 --- a/docs/framework/install/guide-for-developers.md +++ b/docs/framework/install/guide-for-developers.md @@ -84,7 +84,7 @@ From the developer pack download page, choose **Download**. Next, choose **Run** :::image type="content" source="media/guide-for-developers/visual-studio-framework.png" alt-text="Visual Studio installer with .NET Framework options selected." lightbox="media/guide-for-developers/visual-studio-framework-large.png"::: -When you target a particular version of .NET Framework, your application is built by using the reference assemblies that are included with that version's developer pack. At run time, assemblies are resolved from the Global Assembly Cache, and the reference assemblies are not used. +When you target a particular version of .NET Framework, your application is built by using the reference assemblies that are included with that version's developer pack. At runtime, assemblies are resolved from the Global Assembly Cache, and the reference assemblies are not used. When building an application from Visual Studio or using MSBuild from the command line, MSBuild may display error MSB3644, "The reference assemblies for framework "*framework-version*" were not found." To address the error, download the developer pack or the targeting pack for that version of .NET Framework. diff --git a/docs/framework/interop/configure-net-framework-based-com-components-for-reg.md b/docs/framework/interop/configure-net-framework-based-com-components-for-reg.md index bb0540e7aa13b..def0841ddd9b8 100644 --- a/docs/framework/interop/configure-net-framework-based-com-components-for-reg.md +++ b/docs/framework/interop/configure-net-framework-based-com-components-for-reg.md @@ -17,7 +17,7 @@ Registration-free activation for .NET Framework-based components is only slightl - COM applications must have a Win32-style application manifest to identify the managed component. -- .NET Framework-based components must have a component manifest for activation information needed at run time. +- .NET Framework-based components must have a component manifest for activation information needed at runtime. This topic describes how to associate an application manifest with an application; associate a component manifest with a component; and embed a component manifest in an assembly. diff --git a/docs/framework/interop/consuming-unmanaged-dll-functions.md b/docs/framework/interop/consuming-unmanaged-dll-functions.md index 5f634b257f08c..29e6bca2f5194 100644 --- a/docs/framework/interop/consuming-unmanaged-dll-functions.md +++ b/docs/framework/interop/consuming-unmanaged-dll-functions.md @@ -47,7 +47,7 @@ Platform invoke is a service that enables managed code to call unmanaged functio ## A closer look at platform invoke - Platform invoke relies on metadata to locate exported functions and marshal their arguments at run time. The following illustration shows this process. + Platform invoke relies on metadata to locate exported functions and marshal their arguments at runtime. The following illustration shows this process. ![Diagram that shows a platform invoke call.](./media/consuming-unmanaged-dll-functions/platform-invoke-call.gif) diff --git a/docs/framework/interop/default-marshalling-for-arrays.md b/docs/framework/interop/default-marshalling-for-arrays.md index fed2c00de0252..da72f6ffe330e 100644 --- a/docs/framework/interop/default-marshalling-for-arrays.md +++ b/docs/framework/interop/default-marshalling-for-arrays.md @@ -49,7 +49,7 @@ In an application consisting entirely of managed code, the common language runti When a safe array is imported from a type library to a .NET assembly, the array is converted to a one-dimensional array of a known type (such as **int**). The same type conversion rules that apply to parameters also apply to array elements. For example, a safe array of `BSTR` types becomes a managed array of strings and a safe array of variants becomes a managed array of objects. The `SAFEARRAY` element type is captured from the type library and saved in the `SAFEARRAY` value of the enumeration. - Because the rank and bounds of the safe array cannot be determined from the type library, the rank is assumed to equal 1 and the lower bound is assumed to equal 0. The rank and bounds must be defined in the managed signature produced by the [Type Library Importer (Tlbimp.exe)](../tools/tlbimp-exe-type-library-importer.md). If the rank passed to the method at run time differs, a is thrown. If the type of the array passed at run time differs, a is thrown. The following example shows safe arrays in managed and unmanaged code. + Because the rank and bounds of the safe array cannot be determined from the type library, the rank is assumed to equal 1 and the lower bound is assumed to equal 0. The rank and bounds must be defined in the managed signature produced by the [Type Library Importer (Tlbimp.exe)](../tools/tlbimp-exe-type-library-importer.md). If the rank passed to the method at runtime differs, a is thrown. If the type of the array passed at runtime differs, a is thrown. The following example shows safe arrays in managed and unmanaged code. **Unmanaged signature** @@ -184,9 +184,9 @@ void New3(ref String ar); |Managed array type|Exported as| |------------------------|-----------------| -|**ELEMENT_TYPE_SZARRAY** **\<** *type* **>**| **.SafeArray(** *type* **)**

**UnmanagedType.LPArray**

Type is provided in the signature. Rank is always 1, lower bound is always 0. Size is always known at run time.| -|**ELEMENT_TYPE_ARRAY** **\<** *type* **>** **\<** *rank* **>**[**\<** *bounds* **>**]|**UnmanagedType.SafeArray(** *type* **)**

**UnmanagedType.LPArray**

Type, rank, bounds are provided in the signature. Size is always known at run time.| -|**ELEMENT_TYPE_CLASS** **\<****>**|**UT_Interface**

**UnmanagedType.SafeArray(** *type* **)**

Type, rank, bounds, and size are always known at run time.| +|**ELEMENT_TYPE_SZARRAY** **\<** *type* **>**| **.SafeArray(** *type* **)**

**UnmanagedType.LPArray**

Type is provided in the signature. Rank is always 1, lower bound is always 0. Size is always known at runtime.| +|**ELEMENT_TYPE_ARRAY** **\<** *type* **>** **\<** *rank* **>**[**\<** *bounds* **>**]|**UnmanagedType.SafeArray(** *type* **)**

**UnmanagedType.LPArray**

Type, rank, bounds are provided in the signature. Size is always known at runtime.| +|**ELEMENT_TYPE_CLASS** **\<****>**|**UT_Interface**

**UnmanagedType.SafeArray(** *type* **)**

Type, rank, bounds, and size are always known at runtime.| There is a limitation in OLE Automation relating to arrays of structures that contain LPSTR or LPWSTR. Therefore, `String` fields have to be marshalled as **UnmanagedType.BSTR**. Otherwise, an exception will be thrown. @@ -213,7 +213,7 @@ HRESULT New([in] SAFEARRAY( long ) ar); HRESULT New([in] SAFEARRAY( BSTR ) ar); ``` - The rank of the safe arrays is always 1 and the lower bound is always 0. The size is determined at run time by the size of the managed array being passed. + The rank of the safe arrays is always 1 and the lower bound is always 0. The size is determined at runtime by the size of the managed array being passed. The array can also be marshalled as a C-style array by using the attribute. For example: @@ -272,7 +272,7 @@ HRESULT New([in] SAFEARRAY( long ) ar); HRESULT New([in] SAFEARRAY( BSTR ) ar); ``` - The rank, size, and bounds of the safe arrays are determined at run time by the characteristics of the managed array. + The rank, size, and bounds of the safe arrays are determined at runtime by the characteristics of the managed array. The array can also be marshalled as a C-style array by applying the attribute. For example: diff --git a/docs/framework/interop/default-marshalling-for-objects.md b/docs/framework/interop/default-marshalling-for-objects.md index e013d2e4a17c5..7eca706d170ff 100644 --- a/docs/framework/interop/default-marshalling-for-objects.md +++ b/docs/framework/interop/default-marshalling-for-objects.md @@ -115,7 +115,7 @@ When an object is exposed to COM as an interface, that interface is the class in ## Marshalling Object to Variant -When an object is marshalled to a variant, the internal variant type is determined at run time, based on the following rules: +When an object is marshalled to a variant, the internal variant type is determined at runtime, based on the following rules: - If the object reference is null (**Nothing** in Visual Basic), the object is marshalled to a variant of type **VT_EMPTY**. @@ -206,7 +206,7 @@ The wrapper classes are defined in the nam ### Marshalling the IConvertible Interface to Variant -Types other than those listed in the previous section can control how they are marshalled by implementing the interface. If the object implements the `IConvertible` interface, the COM variant type is determined at run time by the value of the enumeration returned from the method. +Types other than those listed in the previous section can control how they are marshalled by implementing the interface. If the object implements the `IConvertible` interface, the COM variant type is determined at runtime by the value of the enumeration returned from the method. The following table shows the possible values for the `TypeCode` enumeration and the corresponding COM variant type for each value. diff --git a/docs/framework/interop/how-to-create-com-wrappers.md b/docs/framework/interop/how-to-create-com-wrappers.md index 38c0266547dd2..e0929d2aee678 100644 --- a/docs/framework/interop/how-to-create-com-wrappers.md +++ b/docs/framework/interop/how-to-create-com-wrappers.md @@ -40,7 +40,7 @@ You can now write code to access the COM object. You can begin by declaring the - Run the [Tlbimp.exe (Type Library Importer)](../tools/tlbimp-exe-type-library-importer.md) tool. - This tool creates an assembly that contains run-time metadata for the types defined in the original type library. + This tool creates an assembly that contains runtime metadata for the types defined in the original type library. ## Wrap Managed Objects in a Native Application diff --git a/docs/framework/interop/interop-marshalling.md b/docs/framework/interop/interop-marshalling.md index dfa31d9bc1795..292fa367bcfaa 100644 --- a/docs/framework/interop/interop-marshalling.md +++ b/docs/framework/interop/interop-marshalling.md @@ -10,7 +10,7 @@ ms.assetid: 115f7a2f-d422-4605-ab36-13a8dd28142a --- # Interop Marshaling -Interop marshalling governs how data is passed in method arguments and return values between managed and unmanaged memory during calls. Interop marshalling is a run-time activity performed by the common language runtime's marshalling service. +Interop marshalling governs how data is passed in method arguments and return values between managed and unmanaged memory during calls. Interop marshalling is a runtime activity performed by the common language runtime's marshalling service. Most data types have common representations in both managed and unmanaged memory. The interop marshaller handles these types for you. Other types can be ambiguous or not represented at all in managed memory. diff --git a/docs/framework/interop/marshalling-classes-structures-and-unions.md b/docs/framework/interop/marshalling-classes-structures-and-unions.md index 008ad3872b4f3..692a0c00cc0c1 100644 --- a/docs/framework/interop/marshalling-classes-structures-and-unions.md +++ b/docs/framework/interop/marshalling-classes-structures-and-unions.md @@ -281,9 +281,9 @@ public struct STRRET_64 Failure to properly consider the native layout in an interop scenario can result in random crashes or worse, incorrect computations. -By default, .NET assemblies can run in both a 32-bit and 64-bit version of the .NET runtime. The app must wait until run time to decide which of the previous definitions to use. +By default, .NET assemblies can run in both a 32-bit and 64-bit version of the .NET runtime. The app must wait until runtime to decide which of the previous definitions to use. -The following code snippet shows an example of how to choose between the 32-bit and 64-bit definition at run time. +The following code snippet shows an example of how to choose between the 32-bit and 64-bit definition at runtime. ```csharp if (IntPtr.Size == 8) diff --git a/docs/framework/interop/specifying-a-character-set.md b/docs/framework/interop/specifying-a-character-set.md index 63364c11ae41a..e1b4403dd567f 100644 --- a/docs/framework/interop/specifying-a-character-set.md +++ b/docs/framework/interop/specifying-a-character-set.md @@ -56,7 +56,7 @@ The -- Platform invoke chooses between ANSI and Unicode formats at run time, based on the target platform. +- Platform invoke chooses between ANSI and Unicode formats at runtime, based on the target platform. ## Specify a character set in Visual Basic diff --git a/docs/framework/mef/index.md b/docs/framework/mef/index.md index 81e3dbe6d4016..a78af893a0420 100644 --- a/docs/framework/mef/index.md +++ b/docs/framework/mef/index.md @@ -37,7 +37,7 @@ Finally, the component developers must accept a hard dependency on what assembly Instead of this explicit registration of available components, MEF provides a way to discover them implicitly, via *composition*. A MEF component, called a *part*, declaratively specifies both its dependencies (known as *imports*) and what capabilities (known as *exports*) it makes available. When a part is created, the MEF composition engine satisfies its imports with what is available from other parts. -This approach solves the problems discussed in the previous section. Because MEF parts declaratively specify their capabilities, they are discoverable at run time, which means an application can make use of parts without either hard-coded references or fragile configuration files. MEF allows applications to discover and examine parts by their metadata, without instantiating them or even loading their assemblies. As a result, there is no need to carefully specify when and how extensions should be loaded. +This approach solves the problems discussed in the previous section. Because MEF parts declaratively specify their capabilities, they are discoverable at runtime, which means an application can make use of parts without either hard-coded references or fragile configuration files. MEF allows applications to discover and examine parts by their metadata, without instantiating them or even loading their assemblies. As a result, there is no need to carefully specify when and how extensions should be loaded. In addition to its provided exports, a part can specify its imports, which will be filled by other parts. This makes communication among parts not only possible, but easy, and allows for good factoring of code. For example, services common to many components can be factored into a separate part and easily modified or replaced. diff --git a/docs/framework/migration-guide/net-framework-4-migration-issues.md b/docs/framework/migration-guide/net-framework-4-migration-issues.md index 71010e7099a4a..a5ce16c1ab5fe 100644 --- a/docs/framework/migration-guide/net-framework-4-migration-issues.md +++ b/docs/framework/migration-guide/net-framework-4-migration-issues.md @@ -122,7 +122,7 @@ Assembly: mscorlib (in mscorlib.dll) | **Buffer length** (unmanaged API) | To save memory, the functionality for the `pBufferLengthOffset` parameter for the [ICorProfilerInfo2::GetStringLayout](../unmanaged-api/profiling/icorprofilerinfo2-getstringlayout-method.md) method has been changed to match the `pStringLengthOffset` parameter. Both parameters now point to the offset location of the string's length. Buffer length has been removed from the representation of the string class. | Remove any dependency on the buffer length. | | **JIT debugging** | To simplify registration for just-in-time (JIT) debugging, the .NET Framework debugger now uses only the AeDebug registry key, which controls the JIT debugging behavior for native code. This change results in the following:

\* You can no longer register two different debuggers for managed and native code.
\* You can no longer start the debugger automatically for a non-interactive process, but you can prompt the user for an interactive process.
\* You are no longer notified when the debugger fails to start, or when there is no registered debugger that should be started.
\* Auto-launch policies that depend on the interactivity of the application are no longer supported. | Adjust debugging operations as required. | | **Platform invoke** | To improve performance in interoperability with unmanaged code, incorrect calling conventions in a platform invoke now cause the application to fail. In previous versions, the marshalling layer resolved these errors up the stack. | Debugging your applications in Microsoft Visual Studio alerts you to these errors so you can correct them.

If you have binaries that cannot be updated, you can include the [\](../configure-apps/file-schema/runtime/netfx40-pinvokestackresilience-element.md) element in your application's configuration file to enable calling errors to be resolved up the stack as in earlier versions. However, this may affect the performance of your application. | -| **Removed interfaces** (unmanaged API) | To avoid developer confusion, the following interfaces were removed, because they did not provide any useful run-time scenarios, and the CLR did not provide or accept any implementations:

\* **INativeImageINativeImageDependency**
\* **INativeImageInstallInfo**
\* **INativeImageEvaluate**
\* **INativeImageConverter**
\* **ICorModule**
\* **IMetaDataConverter** | None. | +| **Removed interfaces** (unmanaged API) | To avoid developer confusion, the following interfaces were removed, because they did not provide any useful runtime scenarios, and the CLR did not provide or accept any implementations:

\* **INativeImageINativeImageDependency**
\* **INativeImageInstallInfo**
\* **INativeImageEvaluate**
\* **INativeImageConverter**
\* **ICorModule**
\* **IMetaDataConverter** | None. | ## Data @@ -142,7 +142,7 @@ Assemblies: System.Data (in System.Data.dll), System.Data.Entity (in System.Data | **Editing Rows** | The method, as implemented by the class, now correctly returns the value of a row that is being edited, instead of returning -1. | | **Events** | The event is now raised when a row is in a modified state and the method is called. This change makes it easier to create UI controls that expose the contents of a object. | | **Exceptions** | The method now throws an when a connection is not set or open instead of a . | -| **Mapping Views** | Query view mapping errors are now caught at design time instead of throwing a at run time.

Mapping validation now catches the error in which two association sets in Conceptual Schema (CSDL) are mapped to the same column. | +| **Mapping Views** | Query view mapping errors are now caught at design time instead of throwing a at runtime.

Mapping validation now catches the error in which two association sets in Conceptual Schema (CSDL) are mapped to the same column. | | **Transactions** | If an application tries to execute a statement on a connection after a transaction has been completed (including aborted or rolled back), an is now thrown. Previous versions did not throw an exception and let you execute additional commands even if a transaction was aborted. | ### Entity Framework @@ -213,7 +213,7 @@ Assemblies: PresentationFramework (in PresentationFramework.dll) | Feature | Differences from 3.5 SP1 | Recommended changes | | ------- | ------------------------ | ------------------- | | **Exception handling** | To enable errors to be detected earlier, WPF throws a and sets the property to critical exceptions, such as , , , and , instead of catching the original exception. | None. | -| **Linked resources** | To make linking easier, resource files (such as images) that are located in a location other than the project's folder structure use the resource file's full path instead of just its file name as the resource ID when the application is built. The application will be able to locate the files at run time. | None. | +| **Linked resources** | To make linking easier, resource files (such as images) that are located in a location other than the project's folder structure use the resource file's full path instead of just its file name as the resource ID when the application is built. The application will be able to locate the files at runtime. | None. | | **Partial-trust applications** | For security considerations, Windows-based applications that run in partial trust and contain a control or a control that contains HTML will throw a when the control is created.

Browser applications will throw an exception and display a message if all of the following conditions are met:

\* The application is running in Firefox.
\* The application is running in partial trust in the Internet zone from non-trusted sites.
\* The application contains a control or a control that contains HTML.

Applications that run from trusted sites or from the intranet zone will not be affected. | In your browser applications, you can ease this change by doing one of the following:

\* Run the browser application in full trust.
\* Have customers add the application's site to the trusted sites zone. | | **Resource dictionaries** | To improve theme-level resource dictionaries and prevent them from changing, freezable resources that are defined in a resource dictionary and merged into a theme-level dictionary are now always marked as frozen and are immutable. This is the expected behavior for freezable resources. | Applications that modify a resource that is defined in a theme-level merged dictionary should clone the resource and modify the cloned copy. Alternatively, the resource can be marked `x:Shared="false"` so that the creates a new copy every time the resource is queried. | | **Windows 7** | To make WPF applications work better on Windows 7, the following improvements were made to correct the behavior of a window:

\* Dock and gesture states now work as expected based on user interactions.
\* The taskbar commands **Cascade windows, Show windows stacked**, and **Show windows side-by-side** now have the correct behavior and update the appropriate properties.
\* The `Top`, `Left`, `Width`, and `Height` properties for a maximized or minimized window now contain the correct restore location of the window instead of other values, depending on the monitor. | None. | diff --git a/docs/framework/performance/lazy-initialization.md b/docs/framework/performance/lazy-initialization.md index 30951b1e54ac5..3055500d41a79 100644 --- a/docs/framework/performance/lazy-initialization.md +++ b/docs/framework/performance/lazy-initialization.md @@ -2,160 +2,160 @@ title: "Lazy Initialization" description: Explore lazy initialization in .NET, a performance improvement that means an object creation is deferred until the object is first used. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" -helpviewer_keywords: +helpviewer_keywords: - "lazy initialization in .NET, introduction" ms.assetid: 56b4ae5c-4745-44ff-ad78-ffe4fcde6b9b --- # Lazy Initialization -*Lazy initialization* of an object means that its creation is deferred until it is first used. (For this topic, the terms *lazy initialization* and *lazy instantiation* are synonymous.) Lazy initialization is primarily used to improve performance, avoid wasteful computation, and reduce program memory requirements. These are the most common scenarios: - -- When you have an object that is expensive to create, and the program might not use it. For example, assume that you have in memory a `Customer` object that has an `Orders` property that contains a large array of `Order` objects that, to be initialized, requires a database connection. If the user never asks to display the Orders or use the data in a computation, then there is no reason to use system memory or computing cycles to create it. By using `Lazy` to declare the `Orders` object for lazy initialization, you can avoid wasting system resources when the object is not used. - -- When you have an object that is expensive to create, and you want to defer its creation until after other expensive operations have been completed. For example, assume that your program loads several object instances when it starts, but only some of them are required immediately. You can improve the startup performance of the program by deferring initialization of the objects that are not required until the required objects have been created. - - Although you can write your own code to perform lazy initialization, we recommend that you use instead. and its related types also support thread-safety and provide a consistent exception propagation policy. - - The following table lists the types that the .NET Framework version 4 provides to enable lazy initialization in different scenarios. - -|Type|Description| -|----------|-----------------| -||A wrapper class that provides lazy initialization semantics for any class library or user-defined type.| -||Resembles except that it provides lazy initialization semantics on a thread-local basis. Every thread has access to its own unique value.| -||Provides advanced `static` (`Shared` in Visual Basic) methods for lazy initialization of objects without the overhead of a class.| - -## Basic Lazy Initialization - - To define a lazy-initialized type, for example, `MyType`, use `Lazy` (`Lazy(Of MyType)` in Visual Basic), as shown in the following example. If no delegate is passed in the constructor, the wrapped type is created by using when the value property is first accessed. If the type does not have a parameterless constructor, a run-time exception is thrown. - - In the following example, assume that `Orders` is a class that contains an array of `Order` objects retrieved from a database. A `Customer` object contains an instance of `Orders`, but depending on user actions, the data from the `Orders` object might not be required. - +*Lazy initialization* of an object means that its creation is deferred until it is first used. (For this topic, the terms *lazy initialization* and *lazy instantiation* are synonymous.) Lazy initialization is primarily used to improve performance, avoid wasteful computation, and reduce program memory requirements. These are the most common scenarios: + +- When you have an object that is expensive to create, and the program might not use it. For example, assume that you have in memory a `Customer` object that has an `Orders` property that contains a large array of `Order` objects that, to be initialized, requires a database connection. If the user never asks to display the Orders or use the data in a computation, then there is no reason to use system memory or computing cycles to create it. By using `Lazy` to declare the `Orders` object for lazy initialization, you can avoid wasting system resources when the object is not used. + +- When you have an object that is expensive to create, and you want to defer its creation until after other expensive operations have been completed. For example, assume that your program loads several object instances when it starts, but only some of them are required immediately. You can improve the startup performance of the program by deferring initialization of the objects that are not required until the required objects have been created. + + Although you can write your own code to perform lazy initialization, we recommend that you use instead. and its related types also support thread-safety and provide a consistent exception propagation policy. + + The following table lists the types that the .NET Framework version 4 provides to enable lazy initialization in different scenarios. + +|Type|Description| +|----------|-----------------| +||A wrapper class that provides lazy initialization semantics for any class library or user-defined type.| +||Resembles except that it provides lazy initialization semantics on a thread-local basis. Every thread has access to its own unique value.| +||Provides advanced `static` (`Shared` in Visual Basic) methods for lazy initialization of objects without the overhead of a class.| + +## Basic Lazy Initialization + + To define a lazy-initialized type, for example, `MyType`, use `Lazy` (`Lazy(Of MyType)` in Visual Basic), as shown in the following example. If no delegate is passed in the constructor, the wrapped type is created by using when the value property is first accessed. If the type does not have a parameterless constructor, a runtime exception is thrown. + + In the following example, assume that `Orders` is a class that contains an array of `Order` objects retrieved from a database. A `Customer` object contains an instance of `Orders`, but depending on user actions, the data from the `Orders` object might not be required. + [!code-csharp[Lazy#1](../../../samples/snippets/csharp/VS_Snippets_Misc/lazy/cs/cs_lazycodefile.cs#1)] - [!code-vb[Lazy#1](../../../samples/snippets/visualbasic/VS_Snippets_Misc/lazy/vb/lazy_vb.vb#1)] - - You can also pass a delegate in the constructor that invokes a specific constructor overload on the wrapped type at creation time, and perform any other initialization steps that are required, as shown in the following example. - + [!code-vb[Lazy#1](../../../samples/snippets/visualbasic/VS_Snippets_Misc/lazy/vb/lazy_vb.vb#1)] + + You can also pass a delegate in the constructor that invokes a specific constructor overload on the wrapped type at creation time, and perform any other initialization steps that are required, as shown in the following example. + [!code-csharp[Lazy#2](../../../samples/snippets/csharp/VS_Snippets_Misc/lazy/cs/cs_lazycodefile.cs#2)] - [!code-vb[Lazy#2](../../../samples/snippets/visualbasic/VS_Snippets_Misc/lazy/vb/lazy_vb.vb#2)] - - After the Lazy object is created, no instance of `Orders` is created until the property of the Lazy variable is accessed for the first time. On first access, the wrapped type is created and returned, and stored for any future access. - + [!code-vb[Lazy#2](../../../samples/snippets/visualbasic/VS_Snippets_Misc/lazy/vb/lazy_vb.vb#2)] + + After the Lazy object is created, no instance of `Orders` is created until the property of the Lazy variable is accessed for the first time. On first access, the wrapped type is created and returned, and stored for any future access. + [!code-csharp[Lazy#3](../../../samples/snippets/csharp/VS_Snippets_Misc/lazy/cs/cs_lazycodefile.cs#3)] - [!code-vb[Lazy#3](../../../samples/snippets/visualbasic/VS_Snippets_Misc/lazy/vb/lazy_vb.vb#3)] - - A object always returns the same object or value that it was initialized with. Therefore, the property is read-only. If stores a reference type, you cannot assign a new object to it. (However, you can change the value of its settable public fields and properties.) If stores a value type, you cannot modify its value. Nevertheless, you can create a new variable by invoking the variable constructor again by using new arguments. - + [!code-vb[Lazy#3](../../../samples/snippets/visualbasic/VS_Snippets_Misc/lazy/vb/lazy_vb.vb#3)] + + A object always returns the same object or value that it was initialized with. Therefore, the property is read-only. If stores a reference type, you cannot assign a new object to it. (However, you can change the value of its settable public fields and properties.) If stores a value type, you cannot modify its value. Nevertheless, you can create a new variable by invoking the variable constructor again by using new arguments. + [!code-csharp[Lazy#4](../../../samples/snippets/csharp/VS_Snippets_Misc/lazy/cs/cs_lazycodefile.cs#4)] - [!code-vb[Lazy#4](../../../samples/snippets/visualbasic/VS_Snippets_Misc/lazy/vb/lazy_vb.vb#4)] - - The new lazy instance, like the earlier one, does not instantiate `Orders` until its property is first accessed. - -### Thread-Safe Initialization - - By default, objects are thread-safe. That is, if the constructor does not specify the kind of thread safety, the objects it creates are thread-safe. In multi-threaded scenarios, the first thread to access the property of a thread-safe object initializes it for all subsequent accesses on all threads, and all threads share the same data. Therefore, it does not matter which thread initializes the object, and race conditions are benign. - + [!code-vb[Lazy#4](../../../samples/snippets/visualbasic/VS_Snippets_Misc/lazy/vb/lazy_vb.vb#4)] + + The new lazy instance, like the earlier one, does not instantiate `Orders` until its property is first accessed. + +### Thread-Safe Initialization + + By default, objects are thread-safe. That is, if the constructor does not specify the kind of thread safety, the objects it creates are thread-safe. In multi-threaded scenarios, the first thread to access the property of a thread-safe object initializes it for all subsequent accesses on all threads, and all threads share the same data. Therefore, it does not matter which thread initializes the object, and race conditions are benign. + > [!NOTE] -> You can extend this consistency to error conditions by using exception caching. For more information, see the next section, [Exceptions in Lazy Objects](lazy-initialization.md#ExceptionsInLazyObjects). - - The following example shows that the same `Lazy` instance has the same value for three separate threads. - +> You can extend this consistency to error conditions by using exception caching. For more information, see the next section, [Exceptions in Lazy Objects](lazy-initialization.md#ExceptionsInLazyObjects). + + The following example shows that the same `Lazy` instance has the same value for three separate threads. + [!code-csharp[Lazy#8](../../../samples/snippets/csharp/VS_Snippets_Misc/lazy/cs/cs_lazycodefile.cs#8)] - [!code-vb[Lazy#8](../../../samples/snippets/visualbasic/VS_Snippets_Misc/lazy/vb/lazy_vb.vb#8)] - - If you require separate data on each thread, use the type, as described later in this topic. - - Some constructors have a Boolean parameter named `isThreadSafe` that is used to specify whether the property will be accessed from multiple threads. If you intend to access the property from just one thread, pass in `false` to obtain a modest performance benefit. If you intend to access the property from multiple threads, pass in `true` to instruct the instance to correctly handle race conditions in which one thread throws an exception at initialization time. - - Some constructors have a parameter named `mode`. These constructors provide an additional thread safety mode. The following table shows how the thread safety of a object is affected by constructor parameters that specify thread safety. Each constructor has at most one such parameter. - -|Thread safety of the object|`LazyThreadSafetyMode` `mode` parameter|Boolean `isThreadSafe` parameter|No thread safety parameters| -|---------------------------------|---------------------------------------------|--------------------------------------|---------------------------------| -|Fully thread-safe; only one thread at a time tries to initialize the value.||`true`|Yes.| -|Not thread-safe.||`false`|Not applicable.| -|Fully thread-safe; threads race to initialize the value.||Not applicable.|Not applicable.| - - As the table shows, specifying for the `mode` parameter is the same as specifying `true` for the `isThreadSafe` parameter, and specifying is the same as specifying `false`. - - For more information about what `Execution` and `Publication` refer to, see . - - Specifying allows multiple threads to attempt to initialize the instance. Only one thread can win this race, and all the other threads receive the value that was initialized by the successful thread. If an exception is thrown on a thread during initialization, that thread does not receive the value set by the successful thread. Exceptions are not cached, so a subsequent attempt to access the property can result in successful initialization. This differs from the way exceptions are treated in other modes, which is described in the following section. For more information, see the enumeration. - + [!code-vb[Lazy#8](../../../samples/snippets/visualbasic/VS_Snippets_Misc/lazy/vb/lazy_vb.vb#8)] + + If you require separate data on each thread, use the type, as described later in this topic. + + Some constructors have a Boolean parameter named `isThreadSafe` that is used to specify whether the property will be accessed from multiple threads. If you intend to access the property from just one thread, pass in `false` to obtain a modest performance benefit. If you intend to access the property from multiple threads, pass in `true` to instruct the instance to correctly handle race conditions in which one thread throws an exception at initialization time. + + Some constructors have a parameter named `mode`. These constructors provide an additional thread safety mode. The following table shows how the thread safety of a object is affected by constructor parameters that specify thread safety. Each constructor has at most one such parameter. + +|Thread safety of the object|`LazyThreadSafetyMode` `mode` parameter|Boolean `isThreadSafe` parameter|No thread safety parameters| +|---------------------------------|---------------------------------------------|--------------------------------------|---------------------------------| +|Fully thread-safe; only one thread at a time tries to initialize the value.||`true`|Yes.| +|Not thread-safe.||`false`|Not applicable.| +|Fully thread-safe; threads race to initialize the value.||Not applicable.|Not applicable.| + + As the table shows, specifying for the `mode` parameter is the same as specifying `true` for the `isThreadSafe` parameter, and specifying is the same as specifying `false`. + + For more information about what `Execution` and `Publication` refer to, see . + + Specifying allows multiple threads to attempt to initialize the instance. Only one thread can win this race, and all the other threads receive the value that was initialized by the successful thread. If an exception is thrown on a thread during initialization, that thread does not receive the value set by the successful thread. Exceptions are not cached, so a subsequent attempt to access the property can result in successful initialization. This differs from the way exceptions are treated in other modes, which is described in the following section. For more information, see the enumeration. + -## Exceptions in Lazy Objects +## Exceptions in Lazy Objects + + As stated earlier, a object always returns the same object or value that it was initialized with, and therefore the property is read-only. If you enable exception caching, this immutability also extends to exception behavior. If a lazy-initialized object has exception caching enabled and throws an exception from its initialization method when the property is first accessed, that same exception is thrown on every subsequent attempt to access the property. In other words, the constructor of the wrapped type is never re-invoked, even in multithreaded scenarios. Therefore, the object cannot throw an exception on one access and return a value on a subsequent access. + + Exception caching is enabled when you use any constructor that takes an initialization method (`valueFactory` parameter); for example, it is enabled when you use the `Lazy(T)(Func(T))`constructor. If the constructor also takes a value (`mode` parameter), specify or . Specifying an initialization method enables exception caching for these two modes. The initialization method can be very simple. For example, it might call the parameterless constructor for `T`: `new Lazy(() => new Contents(), mode)` in C#, or `New Lazy(Of Contents)(Function() New Contents())` in Visual Basic. If you use a constructor that does not specify an initialization method, exceptions that are thrown by the parameterless constructor for `T` are not cached. For more information, see the enumeration. - As stated earlier, a object always returns the same object or value that it was initialized with, and therefore the property is read-only. If you enable exception caching, this immutability also extends to exception behavior. If a lazy-initialized object has exception caching enabled and throws an exception from its initialization method when the property is first accessed, that same exception is thrown on every subsequent attempt to access the property. In other words, the constructor of the wrapped type is never re-invoked, even in multithreaded scenarios. Therefore, the object cannot throw an exception on one access and return a value on a subsequent access. - - Exception caching is enabled when you use any constructor that takes an initialization method (`valueFactory` parameter); for example, it is enabled when you use the `Lazy(T)(Func(T))`constructor. If the constructor also takes a value (`mode` parameter), specify or . Specifying an initialization method enables exception caching for these two modes. The initialization method can be very simple. For example, it might call the parameterless constructor for `T`: `new Lazy(() => new Contents(), mode)` in C#, or `New Lazy(Of Contents)(Function() New Contents())` in Visual Basic. If you use a constructor that does not specify an initialization method, exceptions that are thrown by the parameterless constructor for `T` are not cached. For more information, see the enumeration. - > [!NOTE] -> If you create a object with the `isThreadSafe` constructor parameter set to `false` or the `mode` constructor parameter set to , you must access the object from a single thread or provide your own synchronization. This applies to all aspects of the object, including exception caching. - - As noted in the previous section, objects created by specifying treat exceptions differently. With , multiple threads can compete to initialize the instance. In this case, exceptions are not cached, and attempts to access the property can continue until initialization is successful. - - The following table summarizes the way the constructors control exception caching. - -|Constructor|Thread safety mode|Uses initialization method|Exceptions are cached| -|-----------------|------------------------|--------------------------------|---------------------------| -|Lazy(T)()|()|No|No| -|Lazy(T)(Func(T))|()|Yes|Yes| -|Lazy(T)(Boolean)|`True` () or `false` ()|No|No| -|Lazy(T)(Func(T), Boolean)|`True` () or `false` ()|Yes|Yes| -|Lazy(T)(LazyThreadSafetyMode)|User-specified|No|No| -|Lazy(T)(Func(T), LazyThreadSafetyMode)|User-specified|Yes|No if user specifies ; otherwise, yes.| - -## Implementing a Lazy-Initialized Property - - To implement a public property by using lazy initialization, define the backing field of the property as a , and return the property from the `get` accessor of the property. - +> If you create a object with the `isThreadSafe` constructor parameter set to `false` or the `mode` constructor parameter set to , you must access the object from a single thread or provide your own synchronization. This applies to all aspects of the object, including exception caching. + + As noted in the previous section, objects created by specifying treat exceptions differently. With , multiple threads can compete to initialize the instance. In this case, exceptions are not cached, and attempts to access the property can continue until initialization is successful. + + The following table summarizes the way the constructors control exception caching. + +|Constructor|Thread safety mode|Uses initialization method|Exceptions are cached| +|-----------------|------------------------|--------------------------------|---------------------------| +|Lazy(T)()|()|No|No| +|Lazy(T)(Func(T))|()|Yes|Yes| +|Lazy(T)(Boolean)|`True` () or `false` ()|No|No| +|Lazy(T)(Func(T), Boolean)|`True` () or `false` ()|Yes|Yes| +|Lazy(T)(LazyThreadSafetyMode)|User-specified|No|No| +|Lazy(T)(Func(T), LazyThreadSafetyMode)|User-specified|Yes|No if user specifies ; otherwise, yes.| + +## Implementing a Lazy-Initialized Property + + To implement a public property by using lazy initialization, define the backing field of the property as a , and return the property from the `get` accessor of the property. + [!code-csharp[Lazy#5](../../../samples/snippets/csharp/VS_Snippets_Misc/lazy/cs/cs_lazycodefile.cs#5)] - [!code-vb[Lazy#5](../../../samples/snippets/visualbasic/VS_Snippets_Misc/lazy/vb/lazy_vb.vb#5)] - - The property is read-only; therefore, the property that exposes it has no `set` accessor. If you require a read/write property backed by a object, the `set` accessor must create a new object and assign it to the backing store. The `set` accessor must create a lambda expression that returns the new property value that was passed to the `set` accessor, and pass that lambda expression to the constructor for the new object. The next access of the property will cause initialization of the new , and its property will thereafter return the new value that was assigned to the property. The reason for this convoluted arrangement is to preserve the multithreading protections built into . Otherwise, the property accessors would have to cache the first value returned by the property and only modify the cached value, and you would have to write your own thread-safe code to do that. Because of the additional initializations required by a read/write property backed by a object, the performance might not be acceptable. Furthermore, depending on the specific scenario, additional coordination might be required to avoid race conditions between setters and getters. - -## Thread-Local Lazy Initialization - - In some multithreaded scenarios, you might want to give each thread its own private data. Such data is called *thread-local data*. In the .NET Framework version 3.5 and earlier, you could apply the `ThreadStatic` attribute to a static variable to make it thread-local. However, using the `ThreadStatic` attribute can lead to subtle errors. For example, even basic initialization statements will cause the variable to be initialized only on the first thread that accesses it, as shown in the following example. - + [!code-vb[Lazy#5](../../../samples/snippets/visualbasic/VS_Snippets_Misc/lazy/vb/lazy_vb.vb#5)] + + The property is read-only; therefore, the property that exposes it has no `set` accessor. If you require a read/write property backed by a object, the `set` accessor must create a new object and assign it to the backing store. The `set` accessor must create a lambda expression that returns the new property value that was passed to the `set` accessor, and pass that lambda expression to the constructor for the new object. The next access of the property will cause initialization of the new , and its property will thereafter return the new value that was assigned to the property. The reason for this convoluted arrangement is to preserve the multithreading protections built into . Otherwise, the property accessors would have to cache the first value returned by the property and only modify the cached value, and you would have to write your own thread-safe code to do that. Because of the additional initializations required by a read/write property backed by a object, the performance might not be acceptable. Furthermore, depending on the specific scenario, additional coordination might be required to avoid race conditions between setters and getters. + +## Thread-Local Lazy Initialization + + In some multithreaded scenarios, you might want to give each thread its own private data. Such data is called *thread-local data*. In the .NET Framework version 3.5 and earlier, you could apply the `ThreadStatic` attribute to a static variable to make it thread-local. However, using the `ThreadStatic` attribute can lead to subtle errors. For example, even basic initialization statements will cause the variable to be initialized only on the first thread that accesses it, as shown in the following example. + [!code-csharp[Lazy#6](../../../samples/snippets/csharp/VS_Snippets_Misc/lazy/cs/cs_lazycodefile.cs#6)] - [!code-vb[Lazy#6](../../../samples/snippets/visualbasic/VS_Snippets_Misc/lazy/vb/lazy_vb.vb#6)] - - On all other threads, the variable will be initialized by using its default value (zero). As an alternative in the .NET Framework version 4, you can use the type to create an instance-based, thread-local variable that is initialized on all threads by the delegate that you provide. In the following example, all threads that access `counter` will see its starting value as 1. - + [!code-vb[Lazy#6](../../../samples/snippets/visualbasic/VS_Snippets_Misc/lazy/vb/lazy_vb.vb#6)] + + On all other threads, the variable will be initialized by using its default value (zero). As an alternative in the .NET Framework version 4, you can use the type to create an instance-based, thread-local variable that is initialized on all threads by the delegate that you provide. In the following example, all threads that access `counter` will see its starting value as 1. + [!code-csharp[Lazy#7](../../../samples/snippets/csharp/VS_Snippets_Misc/lazy/cs/cs_lazycodefile.cs#7)] - [!code-vb[Lazy#7](../../../samples/snippets/visualbasic/VS_Snippets_Misc/lazy/vb/lazy_vb.vb#7)] - - wraps its object in much the same way as , with these essential differences: - -- Each thread initializes the thread-local variable by using its own private data that is not accessible from other threads. - -- The property is read-write, and can be modified any number of times. This can affect exception propagation, for example, one `get` operation can raise an exception but the next one can successfully initialize the value. - -- If no initialization delegate is provided, will initialize its wrapped type by using the default value of the type. In this regard, is consistent with the attribute. - - The following example demonstrates that every thread that accesses the `ThreadLocal` instance gets its own unique copy of the data. - + [!code-vb[Lazy#7](../../../samples/snippets/visualbasic/VS_Snippets_Misc/lazy/vb/lazy_vb.vb#7)] + + wraps its object in much the same way as , with these essential differences: + +- Each thread initializes the thread-local variable by using its own private data that is not accessible from other threads. + +- The property is read-write, and can be modified any number of times. This can affect exception propagation, for example, one `get` operation can raise an exception but the next one can successfully initialize the value. + +- If no initialization delegate is provided, will initialize its wrapped type by using the default value of the type. In this regard, is consistent with the attribute. + + The following example demonstrates that every thread that accesses the `ThreadLocal` instance gets its own unique copy of the data. + [!code-csharp[Lazy#9](../../../samples/snippets/csharp/VS_Snippets_Misc/lazy/cs/cs_lazycodefile.cs#9)] - [!code-vb[Lazy#9](../../../samples/snippets/visualbasic/VS_Snippets_Misc/lazy/vb/lazy_vb.vb#9)] - -## Thread-Local Variables in Parallel.For and ForEach - - When you use the method or method to iterate over data sources in parallel, you can use the overloads that have built-in support for thread-local data. In these methods, the thread-locality is achieved by using local delegates to create, access, and clean up the data. For more information, see [How to: Write a Parallel.For Loop with Thread-Local Variables](../../standard/parallel-programming/how-to-write-a-parallel-for-loop-with-thread-local-variables.md) and [How to: Write a Parallel.ForEach Loop with Partition-Local Variables](../../standard/parallel-programming/how-to-write-a-parallel-foreach-loop-with-partition-local-variables.md). - -## Using Lazy Initialization for Low-Overhead Scenarios - - In scenarios where you have to lazy-initialize a large number of objects, you might decide that wrapping each object in a requires too much memory or too many computing resources. Or, you might have stringent requirements about how lazy initialization is exposed. In such cases, you can use the `static` (`Shared` in Visual Basic) methods of the class to lazy-initialize each object without wrapping it in an instance of . - - In the following example, assume that, instead of wrapping an entire `Orders` object in one object, you have lazy-initialized individual `Order` objects only if they are required. - + [!code-vb[Lazy#9](../../../samples/snippets/visualbasic/VS_Snippets_Misc/lazy/vb/lazy_vb.vb#9)] + +## Thread-Local Variables in Parallel.For and ForEach + + When you use the method or method to iterate over data sources in parallel, you can use the overloads that have built-in support for thread-local data. In these methods, the thread-locality is achieved by using local delegates to create, access, and clean up the data. For more information, see [How to: Write a Parallel.For Loop with Thread-Local Variables](../../standard/parallel-programming/how-to-write-a-parallel-for-loop-with-thread-local-variables.md) and [How to: Write a Parallel.ForEach Loop with Partition-Local Variables](../../standard/parallel-programming/how-to-write-a-parallel-foreach-loop-with-partition-local-variables.md). + +## Using Lazy Initialization for Low-Overhead Scenarios + + In scenarios where you have to lazy-initialize a large number of objects, you might decide that wrapping each object in a requires too much memory or too many computing resources. Or, you might have stringent requirements about how lazy initialization is exposed. In such cases, you can use the `static` (`Shared` in Visual Basic) methods of the class to lazy-initialize each object without wrapping it in an instance of . + + In the following example, assume that, instead of wrapping an entire `Orders` object in one object, you have lazy-initialized individual `Order` objects only if they are required. + [!code-csharp[Lazy#10](../../../samples/snippets/csharp/VS_Snippets_Misc/lazy/cs/cs_lazycodefile.cs#10)] - [!code-vb[Lazy#10](../../../samples/snippets/visualbasic/VS_Snippets_Misc/lazy/vb/lazy_vb.vb#10)] - - In this example, notice that the initialization procedure is invoked on every iteration of the loop. In multi-threaded scenarios, the first thread to invoke the initialization procedure is the one whose value is seen by all threads. Later threads also invoke the initialization procedure, but their results are not used. If this kind of potential race condition is not acceptable, use the overload of that takes a Boolean argument and a synchronization object. - + [!code-vb[Lazy#10](../../../samples/snippets/visualbasic/VS_Snippets_Misc/lazy/vb/lazy_vb.vb#10)] + + In this example, notice that the initialization procedure is invoked on every iteration of the loop. In multi-threaded scenarios, the first thread to invoke the initialization procedure is the one whose value is seen by all threads. Later threads also invoke the initialization procedure, but their results are not used. If this kind of potential race condition is not acceptable, use the overload of that takes a Boolean argument and a synchronization object. + ## See also - [Managed Threading Basics](../../standard/threading/managed-threading-basics.md) diff --git a/docs/framework/reflection-and-codedom/dynamic-language-runtime-overview.md b/docs/framework/reflection-and-codedom/dynamic-language-runtime-overview.md index 6de4954309930..2fd655c47dbfd 100644 --- a/docs/framework/reflection-and-codedom/dynamic-language-runtime-overview.md +++ b/docs/framework/reflection-and-codedom/dynamic-language-runtime-overview.md @@ -12,7 +12,7 @@ helpviewer_keywords: The *dynamic language runtime* (DLR) is a runtime environment that adds a set of services for dynamic languages to the common language runtime (CLR). The DLR makes it easier to develop dynamic languages to run on .NET and to add dynamic features to statically typed languages. -Dynamic languages can identify the type of an object at run time, whereas in statically typed languages such as C# and Visual Basic (when you use `Option Explicit On`), you must specify object types at design time. Examples of dynamic languages are Lisp, Smalltalk, JavaScript, PHP, Ruby, Python, ColdFusion, Lua, Cobra, and Groovy. +Dynamic languages can identify the type of an object at runtime, whereas in statically typed languages such as C# and Visual Basic (when you use `Option Explicit On`), you must specify object types at design time. Examples of dynamic languages are Lisp, Smalltalk, JavaScript, PHP, Ruby, Python, ColdFusion, Lua, Cobra, and Groovy. Most dynamic languages provide the following advantages for developers: diff --git a/docs/framework/reflection-and-codedom/dynamic-source-code-generation-and-compilation.md b/docs/framework/reflection-and-codedom/dynamic-source-code-generation-and-compilation.md index d309f5e8f2983..ec0d55fd45973 100644 --- a/docs/framework/reflection-and-codedom/dynamic-source-code-generation-and-compilation.md +++ b/docs/framework/reflection-and-codedom/dynamic-source-code-generation-and-compilation.md @@ -14,7 +14,7 @@ ms.assetid: d077a3e8-bd81-4bdf-b6a3-323857ea30fb --- # Compile and generate dynamic source code -.NET includes a mechanism called the Code Document Object Model (CodeDOM) that enables developers of programs that emit source code to generate source code in multiple programming languages at run time, based on a single model that represents the code to render. +.NET includes a mechanism called the Code Document Object Model (CodeDOM) that enables developers of programs that emit source code to generate source code in multiple programming languages at runtime, based on a single model that represents the code to render. To represent source code, CodeDOM elements are linked to each other to form a data structure known as a CodeDOM graph, which models the structure of some source code. @@ -32,7 +32,7 @@ Language-independent source code modeling can be valuable when a program needs t - - Defines interfaces for generating and compiling code at run time. + Defines interfaces for generating and compiling code at runtime. ## Related sections diff --git a/docs/framework/reflection-and-codedom/security-considerations-for-reflection.md b/docs/framework/reflection-and-codedom/security-considerations-for-reflection.md index 72b19719b3a6e..3197ca384f48d 100644 --- a/docs/framework/reflection-and-codedom/security-considerations-for-reflection.md +++ b/docs/framework/reflection-and-codedom/security-considerations-for-reflection.md @@ -84,7 +84,7 @@ For example, suppose you grant an application domain Internet permissions plus < - Assembly A can use reflection to access private members of assembly B, because the grant set of assembly B does not include any permissions that A has not been granted. -- Assembly A cannot use reflection to access private members of .NET Framework assemblies such as mscorlib.dll, because mscorlib.dll is fully trusted and therefore has permissions that have not been granted to assembly A. A is thrown when code access security walks the stack at run time. +- Assembly A cannot use reflection to access private members of .NET Framework assemblies such as mscorlib.dll, because mscorlib.dll is fully trusted and therefore has permissions that have not been granted to assembly A. A is thrown when code access security walks the stack at runtime. ## Serialization diff --git a/docs/framework/release-notes/2024/07-25-july-preview-cumulative-update.md b/docs/framework/release-notes/2024/07-25-july-preview-cumulative-update.md index 41eec69c17bec..314a50e2320e7 100644 --- a/docs/framework/release-notes/2024/07-25-july-preview-cumulative-update.md +++ b/docs/framework/release-notes/2024/07-25-july-preview-cumulative-update.md @@ -26,7 +26,7 @@ Addresses an issue with bypass serialization binder with binary formatter mutati Addresses an issue to remove meta tags information referencing "Recreational Software Advisory Council" and the content-rating schema from ASP.NET WebForms SmartNavigation feature -Addresses an issue with .NET Framework interaction with Visual Studio. The fix avoids conflicts between design-time and debug or run-time compilation of some .NET Framework ASP.NET projects that could result in slowed developer experience for large projects. +Addresses an issue with .NET Framework interaction with Visual Studio. The fix avoids conflicts between design-time and debug or runtime compilation of some .NET Framework ASP.NET projects that could result in slowed developer experience for large projects. #### .NET libraries diff --git a/docs/framework/tools/al-exe-assembly-linker.md b/docs/framework/tools/al-exe-assembly-linker.md index 7264e542831ac..99d00f614a837 100644 --- a/docs/framework/tools/al-exe-assembly-linker.md +++ b/docs/framework/tools/al-exe-assembly-linker.md @@ -33,15 +33,15 @@ You can specify one or more of the following `sources`. | Source | Description | | ------ | ----------- | |`file`[,`target`]|Copies the contents of `file` (a module) to the file name specified by `target`. After copying, *Al.exe* compiles `target` into an assembly.| -|**/embed[resource]:** `file`[,`name`[,`private`]]|Embeds the resource specified by `file` in the image that contains the assembly manifest; *Al.exe* copies the contents of `file` into the portable executable (PE) image.

The `name` parameter is an internal identifier for the resource. By default, resources are public in the assembly (visible to other assemblies). Specifying `private` makes the resource not visible to other assemblies.

If `file` is a .NET Framework resource file created, for example, by the [Resource File Generator (*Resgen.exe*)](resgen-exe-resource-file-generator.md) or in the development environment, it can be accessed with members in the . For more information, see . For all other resources, use the `GetManifestResource*` methods in the to access the resource at run time.

If only resource files are passed to *Al.exe*, the output file is a satellite resource assembly.| -|**/link[resource]:** `file`[,`name`[,`target`[,`private`]]]|Links a resource file to an assembly. The resource specified by `file` becomes part of the assembly; the file is not copied. The `file` parameter can be in any file format. For example, you can specify a native DLL as the `file` parameter. This will make the native DLL part of the assembly so that it can be installed into the global assembly cache and accessed from managed code in the assembly. You can also do this by using the **/linkresource** compiler option. For more information, see [-linkresource (C# Compiler Options)](../../csharp/language-reference/compiler-options/resources.md#linkresources).

The `name` parameter is an internal identifier for the resource. The `target` parameter specifies a path and file name into which *Al.exe* copies the `file`*.* After copying, *Al.exe* compiles `target` into an assembly. By default, resources are public in the assembly (visible to other assemblies). Specifying `private` makes the resource not visible to other assemblies.

If `file` is a .NET Framework resource file created, for example, by the Resource File Generator (*Resgen.exe*) or in the development environment, it can be accessed with members in the namespace. For more information, see . For all other resources, use the `GetManifestResource*` methods in the class to access the resource at run time.

If only resource files are passed to *Al.exe*, the output file is a satellite resource assembly.| +|**/embed[resource]:** `file`[,`name`[,`private`]]|Embeds the resource specified by `file` in the image that contains the assembly manifest; *Al.exe* copies the contents of `file` into the portable executable (PE) image.

The `name` parameter is an internal identifier for the resource. By default, resources are public in the assembly (visible to other assemblies). Specifying `private` makes the resource not visible to other assemblies.

If `file` is a .NET Framework resource file created, for example, by the [Resource File Generator (*Resgen.exe*)](resgen-exe-resource-file-generator.md) or in the development environment, it can be accessed with members in the . For more information, see . For all other resources, use the `GetManifestResource*` methods in the to access the resource at runtime.

If only resource files are passed to *Al.exe*, the output file is a satellite resource assembly.| +|**/link[resource]:** `file`[,`name`[,`target`[,`private`]]]|Links a resource file to an assembly. The resource specified by `file` becomes part of the assembly; the file is not copied. The `file` parameter can be in any file format. For example, you can specify a native DLL as the `file` parameter. This will make the native DLL part of the assembly so that it can be installed into the global assembly cache and accessed from managed code in the assembly. You can also do this by using the **/linkresource** compiler option. For more information, see [-linkresource (C# Compiler Options)](../../csharp/language-reference/compiler-options/resources.md#linkresources).

The `name` parameter is an internal identifier for the resource. The `target` parameter specifies a path and file name into which *Al.exe* copies the `file`*.* After copying, *Al.exe* compiles `target` into an assembly. By default, resources are public in the assembly (visible to other assemblies). Specifying `private` makes the resource not visible to other assemblies.

If `file` is a .NET Framework resource file created, for example, by the Resource File Generator (*Resgen.exe*) or in the development environment, it can be accessed with members in the namespace. For more information, see . For all other resources, use the `GetManifestResource*` methods in the class to access the resource at runtime.

If only resource files are passed to *Al.exe*, the output file is a satellite resource assembly.| You can specify the following `options`; you must specify **/out**. | Option | Description | | ------ | ----------- | |**/algid:** `id`|Specifies an algorithm to hash all files in a multifile assembly except the file that contains the assembly manifest. The default algorithm is CALG_SHA1. See ALG_ID in the Platform SDK documentation for other algorithms. For the first release of the .NET Framework, only CALG_SHA1 and CALG_MD5 are valid.

The hash values are stored in the file table of the assembly manifest. At installation and load time, the assembly's files are checked against their hashes.

You can also specify this option as a custom attribute () in the source code for any module.| -|**/base[address]:** `addr`|Specifies the address at which a DLL will be loaded on the user's computer at run time. Applications load faster if you specify the base address of the DLLs, instead of letting the operating system relocate the DLLs in the process space.| +|**/base[address]:** `addr`|Specifies the address at which a DLL will be loaded on the user's computer at runtime. Applications load faster if you specify the base address of the DLLs, instead of letting the operating system relocate the DLLs in the process space.| |**/bugreport**: `filename`|Creates a file (`filename`) that contains information for reporting bugs.| |**/comp[any]:** `text`|Specifies a string for the Company field in the assembly. Place the string in double quotation marks (" ") if `text` contains a space. This string is a custom attribute on the assembly and is available for viewing with reflection.

If you do not specify **/win32res**, `text` appears in File Explorer as the `Company` property for the file. If you specify **/win32res**, the company information in the specified resource file appears as the `Company` property in File Explorer.

If text is an empty string (""), the Win32 `Company` resource appears as a single space.

If you specify **/win32res**, **/company** will not affect the Win32 resource information.

You can also specify this option as a custom attribute () in the source code for any CIL module.| |**/config[uration]:** `text`|Specifies a string for the Configuration field in the assembly. Place the string in double quotation marks (" ") if `text` contains a space. This string is a custom attribute on the assembly and is available for viewing with reflection.

If text is an empty string, the Win32 Configuration resource appears as a single space.

You can also specify this option as a custom attribute () in the source code for any CIL module.| diff --git a/docs/framework/tools/clrver-exe-clr-version-tool.md b/docs/framework/tools/clrver-exe-clr-version-tool.md index c659d9ea2b8dc..051ebaa486132 100644 --- a/docs/framework/tools/clrver-exe-clr-version-tool.md +++ b/docs/framework/tools/clrver-exe-clr-version-tool.md @@ -2,56 +2,56 @@ title: "Clrver.exe (CLR Version Tool)" description: Review Clrver.exe, the CLR Version tool. This tool reports all installed versions of the common language runtime (CLR) on the computer. ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "Clrver.exe" - "CLR Version tool" ms.assetid: cbc2ee86-bdc8-4a65-a8f1-ba23bce3a699 --- # Clrver.exe (CLR Version Tool) -The CLR Version tool (Clrver.exe) reports all the installed versions of the common language runtime (CLR) on the computer. - - This tool is automatically installed with Visual Studio. To run the tool, use [Visual Studio Developer Command Prompt or Visual Studio Developer PowerShell](/visualstudio/ide/reference/command-prompt-powershell). - - At the command prompt, enter the following command: - -## Syntax - -```console -clrver [option] -``` - -## Options - -|Option|Description| -|------------|-----------------| -|`-all`|Displays all processes on the computer that are using the CLR.| -|*pid*|Displays the version(s) of the CLR used by the process that has the specified process ID (PID).| -|`-?`|Displays command syntax and options for the tool.| - -## Remarks - - If you call Clrver.exe with no options, it displays all installed CLR versions. If you specify a PID for another user, you must have administrative permissions to obtain the version information. - +The CLR Version tool (Clrver.exe) reports all the installed versions of the common language runtime (CLR) on the computer. + + This tool is automatically installed with Visual Studio. To run the tool, use [Visual Studio Developer Command Prompt or Visual Studio Developer PowerShell](/visualstudio/ide/reference/command-prompt-powershell). + + At the command prompt, enter the following command: + +## Syntax + +```console +clrver [option] +``` + +## Options + +|Option|Description| +|------------|-----------------| +|`-all`|Displays all processes on the computer that are using the CLR.| +|*pid*|Displays the version(s) of the CLR used by the process that has the specified process ID (PID).| +|`-?`|Displays command syntax and options for the tool.| + +## Remarks + + If you call Clrver.exe with no options, it displays all installed CLR versions. If you specify a PID for another user, you must have administrative permissions to obtain the version information. + > [!NOTE] -> In Windows Vista and later, User Account Control (UAC) determines the privileges of a user. If you are a member of the Built-in Administrators group, you are assigned two run-time access tokens: a standard user access token and an administrator access token. By default, you are in the standard user role. To execute code that requires administrative permission, you must first elevate your privileges from standard user to administrator. You can do this when you start the command prompt by right-clicking the command prompt icon and indicating that you want to run as an administrator. - - Attempting to determine the CLR version for SYSTEM, LOCAL SERVICE, and NETWORK SERVICE processes results in a message indicating that the PID doesn't exist. - -## Examples - - The following command displays all the versions of the CLR installed on the computer. - - `clrver` - - The following command displays the version of the CLR used by process 128. - - `clrver 128` - - The following command displays all the managed processes and the version of the CLR they are using. - - `Clrver -all` - +> In Windows Vista and later, User Account Control (UAC) determines the privileges of a user. If you are a member of the Built-in Administrators group, you are assigned two runtime access tokens: a standard user access token and an administrator access token. By default, you are in the standard user role. To execute code that requires administrative permission, you must first elevate your privileges from standard user to administrator. You can do this when you start the command prompt by right-clicking the command prompt icon and indicating that you want to run as an administrator. + + Attempting to determine the CLR version for SYSTEM, LOCAL SERVICE, and NETWORK SERVICE processes results in a message indicating that the PID doesn't exist. + +## Examples + + The following command displays all the versions of the CLR installed on the computer. + + `clrver` + + The following command displays the version of the CLR used by process 128. + + `clrver 128` + + The following command displays all the managed processes and the version of the CLR they are using. + + `Clrver -all` + ## See also - [Tools](index.md) diff --git a/docs/framework/tools/fuslogvw-exe-assembly-binding-log-viewer.md b/docs/framework/tools/fuslogvw-exe-assembly-binding-log-viewer.md index 8829aebb873aa..676596d09b396 100644 --- a/docs/framework/tools/fuslogvw-exe-assembly-binding-log-viewer.md +++ b/docs/framework/tools/fuslogvw-exe-assembly-binding-log-viewer.md @@ -1,6 +1,6 @@ --- title: "Fuslogvw.exe (Assembly Binding Log Viewer)" -description: Use Fuslogvw.exe, the Assembly Binding Log Viewer. This viewer shows assembly bind details, which helps diagnose why .NET can't find an assembly at run time. +description: Use Fuslogvw.exe, the Assembly Binding Log Viewer. This viewer shows assembly bind details, which helps diagnose why .NET can't find an assembly at runtime. ms.date: "03/30/2017" helpviewer_keywords: - "failed assembly binds" @@ -13,7 +13,7 @@ ms.assetid: e32fa443-0778-4cc3-bf36-5c8ea297d296 --- # Fuslogvw.exe (Assembly Binding Log Viewer) -The Assembly Binding Log Viewer displays details for assembly binds. This information helps you diagnose why the .NET Framework cannot locate an assembly at run time. These failures are usually the result of an assembly deployed to the wrong location, a native image that is no longer valid, or a mismatch in version numbers or cultures. The common language runtime's failure to locate an assembly typically shows up as a in your application. +The Assembly Binding Log Viewer displays details for assembly binds. This information helps you diagnose why the .NET Framework cannot locate an assembly at runtime. These failures are usually the result of an assembly deployed to the wrong location, a native image that is no longer valid, or a mismatch in version numbers or cultures. The common language runtime's failure to locate an assembly typically shows up as a in your application. > [!IMPORTANT] > You must run fuslogvw.exe with administrator privileges. @@ -136,7 +136,7 @@ By default, Fuslogvw.exe logs normal assembly bind requests. Alternatively, you - In the **Log Categories** group, select the **Native Images** option button. -The following log shows a failure caused by a dependency that did not exist when the native image was created for the application. If the dependencies at run time differ from the dependencies when Ngen.exe is run, binding to a native image is not allowed. +The following log shows a failure caused by a dependency that did not exist when the native image was created for the application. If the dependencies at runtime differ from the dependencies when Ngen.exe is run, binding to a native image is not allowed. ```output *** Assembly Binder Log Entry (12/8/2006 @ 5:22:07 PM) *** diff --git a/docs/framework/tools/index.md b/docs/framework/tools/index.md index 0680d038496bf..95104cdf4ef27 100644 --- a/docs/framework/tools/index.md +++ b/docs/framework/tools/index.md @@ -46,7 +46,7 @@ Reports all the installed versions of the common language runtime (CLR) on the c Lets you configure the CorFlags section of the header of a portable executable (PE) image. [Fuslogvw.exe (Assembly Binding Log Viewer)](fuslogvw-exe-assembly-binding-log-viewer.md)\ -Displays information about assembly binds to help you diagnose why the .NET Framework cannot locate an assembly at run time. +Displays information about assembly binds to help you diagnose why the .NET Framework cannot locate an assembly at runtime. [Gacutil.exe (Global Assembly Cache Tool)](gacutil-exe-gac-tool.md)\ Lets you view and manipulate the contents of the global assembly cache and download cache. diff --git a/docs/framework/tools/mageui-exe-manifest-generation-and-editing-tool-graphical-client.md b/docs/framework/tools/mageui-exe-manifest-generation-and-editing-tool-graphical-client.md index b0c926034342a..fbceffccfb241 100644 --- a/docs/framework/tools/mageui-exe-manifest-generation-and-editing-tool-graphical-client.md +++ b/docs/framework/tools/mageui-exe-manifest-generation-and-editing-tool-graphical-client.md @@ -16,187 +16,187 @@ MageUI.exe supports the same functionality as the command-line tool Mage.exe, bu Two versions of Mage.exe and MageUI.exe are included as a component of Visual Studio. To see version information, run MageUI.exe, select **Help**, and select **About**. This documentation describes version 4.0.x.x of Mage.exe and MageUI.exe. > [!NOTE] -> MageUI.exe does not support the [compatibleFrameworks](/visualstudio/deployment/compatibleframeworks-element-clickonce-deployment) element when saving an application manifest that has already been signed with a certificate using MageUI.exe. Instead, you must use [Mage.exe](mage-exe-manifest-generation-and-editing-tool.md). - -## UIElement List - - The following table lists the menu and toolbar items that are available. - -|Command|Menu|Shortcut|Description| -|-------------|----------|--------------|-----------------| -|**Application Manifest**|**File, New**||Creates a new application manifest.| -|**Deployment Manifest**|**File, New**||Creates a new deployment manifest.| -|**Open**|**File**|CTRL+O|Opens an existing deployment manifest, application manifest, or trust license for editing.| -|**Close**|**File**|CTRL+F4|Closes an open file.

If you modify a file before closing it, MageUI.exe prompts you to re-sign the file with a public key, key pair, or stored certificate.| -|**Save**|**File**|CTRL+S|Saves to disk the document which currently has user input focus.| -|**Save As**|**File**||Saves a file to disk, enabling you to supply a new file name and/or location.| -|**Save All**|**File**||Saves the changes made to all files currently open within MageUI.exe.| -|**Preferences**|**File**||Opens the **Preferences** dialog box. See the following section for more information.| -|**Exit**|**File**|ALT+F4|Quits MageUI.exe.| -|**Cut**|**Edit**|CTRL+X|Removes the currently selected text from the application and moves it to the system Clipboard.| -|**Copy**|**Edit**|CTRL+C|Copies the currently selected text to the system Clipboard.| -|**Paste**|**Edit**|CTRL+V|Pastes text from the system Clipboard into the currently active text element.| -|**Delete**|**Edit**||Deletes an element currently selected in a list, such as a trust license on the **Deployment Manifest** tab.| -|**Close All**|**Window**||Closes all files currently open in MageUI.exe. If one or more files need saving, MageUI.exe prompts you to save them. MageUI.exe also prompts you to select a signing key for each unsigned or changed file.| -|**About**|**Help**||Displays version and copyright information about MageUI.exe.| - -## Preferences Dialog Box - - The **Preferences** dialog box contains the following elements. - -|UI Element|Description| -|----------------|-----------------| -|**Sign on save**|Prompts you to sign a file whenever you save your modifications.| -|**Use default signing certificate**|Uses the key entered in the **Certificate file** text box to sign all files. This eliminates the signing prompt that typically appears when you save a file and **Sign on Save** is selected. Use the ellipsis (**…**) button next to the **Certificate file** text box to select a key file.| -|Digest algorithm|Specifies the algorithm to generate dependency digests with. Value must be "sha256RSA" or "sha1RSA". Uses SHA1 as the default. Used both in application and deployment manifests. If the user provides a certificate when saving the manifest, uses the algorithms in the certificate to generate dependency digests with.| - -## Signing Options Dialog Box - - The **Signing Options** dialog box appears when you save a manifest or trust license for the first time, or when you change a manifest or trust license. It only appears if the **Sign on Save** option in the **Preferences** dialog box is selected. You must be connected to the Internet when signing a manifest that specifies a value in the **TimeStamping URI** text box. - - This dialog box contains the following elements. - -|UI Element|Description| -|----------------|-----------------| -|**Sign with certificate file**|Signs the manifest with a digital certificate stored on the file system.| -|**File**|Provides an area to type the path to the .pfx file representing the certificate.| -|**...**|Opens a **Choose File** dialog box for selecting an existing .pfx file.| -|**New**|Generates a new .pfx that is not verifiable through a Certificate Authority (CA). For more information about the types of certificates used for signing ClickOnce deployments, see [Trusted Application Deployment Overview](/visualstudio/deployment/trusted-application-deployment-overview).| -|**Password**|Provides an area to type the password used for signing with this certificate. If not applicable, can be left blank.| -|**Sign with stored certificate**|Displays a selectable list of digital certificates stored in your computer's certificate store.| -|**TimeStamping URI**|Displays the Uniform Resource Locator (URI) of a digital timestamping service. Timestamping the manifests prevents you from having to re-sign the manifests if your digital certificate expires before you deploy the next version of your application. For more information, see [Windows root certificate program members](/previous-versions/windows/it-pro/windows-server-2012-R2-and-2012/dn265983(v=ws.11)) and [ClickOnce and Authenticode](/visualstudio/deployment/clickonce-and-authenticode).| -|**Don't Sign**|Allows you to save the manifest without adding a signature from a digital certificate.| - -## Tab and Panel Descriptions - - When you open a document with MageUI.exe, it appears within its own tab page. Each tab contains a set of property panels. The panels contain grouped subsets of the document's data. - -### Application Manifest Tab - - The **Application Manifest** tab displays the contents of an application manifest. The application manifest describes all files included with the deployment, and the permissions required for the application to run on the client. - - The **Application Manifest** tab contains the following tabs. - -|UI Element|Description| -|----------------|-----------------| -|**Name**|Specifies identifying information about this deployment.| -|**Description**|Specifies publisher, product, and support information.| -|**Application Options**|Specifies whether this is a browser application, and whether this manifest is the source of trust information.| -|**Files**|Specifies all of the files that constitute this deployment.| -|**Permissions Required**|Specifies the minimum permission set required by the application to run on a client.| - -### Name Tab - - The **Name** tab is displayed when you first create or open an application manifest. It uniquely identifies the deployment, and optionally specifies a valid target platform. - -|UI Element|Description| -|----------------|-----------------| -|**Name**|Required. The name of the application manifest. Usually the same as the file name.| -|**Version**|Required. The version number of the deployment in the form *N.N.N.N*. Only the first major build number is required. For example, for version 1.0 of an application, valid values would include `1`, `1.0`, `1.0.0`, and `1.0.0.0`.| -|**Processor**|Optional. The machine architecture on which this deployment can run. The default is `msil`, or Microsoft Intermediate Language, which is the default format of all managed assemblies. Change this field if you have pre-compiled the assemblies in your application for a specific architecture. For more information about pre-compilation, see [Ngen.exe (Native Image Generator)](ngen-exe-native-image-generator.md).| -|**Culture**|Optional. The two-part ISO country and region code in which this application runs. The default is `neutral`.| -|**Public key token**|Optional. The public key with which this application manifest has been signed. If this is a new or unsigned manifest, this field will appear as `Unsigned`.| - -### Description Tab - - This information is usually provided within the deployment manifest. These fields can only be modified if the **Use Application Manifest Trust Information** check box is selected on the **Application Options** tab. - -|UI Element|Description| -|----------------|-----------------| -|**Publisher**|The name of the person or organization responsible for the application. This value is used as the Start menu folder name.| -|**Product**|The full product name. If you selected **Install Locally** for the **Application Type** element on the **Deployment Options** tab of the deployment manifest, this name will be what appears in the **Start** menu link and in **Add or Remove Programs** for this application.| -|**Support Location**|The URL from which customers can obtain help and support for the application.| - -### Application Options Tab - -|UI Element|Description| -|----------------|-----------------| -|**Windows Presentation Foundation Browser Application**|Specifies whether this is a WPF application that runs in the browser as a XAML browser application (XBAP).| -|**Use Application Manifest Trust Information**|Specifies whether this manifest contains trust information.| - -### Files Tab - -|UI Element|Description| -|----------------|-----------------| -|**Application directory**|The directory in which the application's files reside. Use the ellipses (**…**) button to select the directory.| -|**Populate**|Adds all of the files in the application directory and subdirectories to the application manifest. If MageUI.exe finds a single executable file in the directory, it automatically marks this as the Entry Point, which is the file first executed when the ClickOnce application is launched on the client.| -|**Application Files**|Lists all of the files in the application. Each file has three editable attributes, discussed below.| -|**File Type**|File Type can be one of four values:

- None.
- Entry Point. The application's primary executable. Only one executable file can be marked as the entry point.
- Data File. A file, such as an XML file, that supplies data to the application.
- Icon File. An application icon, such as appears on the desktop or in the corner of an application's window.| -|**Optional**|Files marked optional are not downloaded on initial install or update, but may be downloaded at run time using the System.Deployment On-Demand API. For more information, see [Walkthrough: Downloading Assemblies on Demand with the ClickOnce Deployment API Using the Designer](/visualstudio/deployment/walkthrough-downloading-assemblies-on-demand-with-the-clickonce-deployment-api-using-the-designer).| -|**Group**|A label for a set of optional files. You can apply a Group label to a set of files, and use the On-Demand API to download a batch of files with a single API call.| - -### Permissions Required Tab - - Use the **Permissions Required** tab if you need to grant your application more access to the local computer than is granted by default. For more information, see [Securing ClickOnce Applications](/visualstudio/deployment/securing-clickonce-applications). - -|UI Element|Description| -|----------------|-----------------| -|**Permission set type**|The minimum permission set required by this application to run on the client. For a description of these permission sets and which permissions they do or do not demand, see [Named Permission Sets](/previous-versions/dotnet/netframework-4.0/4652tyx7(v=vs.100)).| -|**Details**|The XML created for the application manifest to represent the permission set. Unless you have a good understanding of the application manifest XML format, you should not edit this XML manually. For more information, see [ClickOnce Application Manifest](/visualstudio/deployment/clickonce-application-manifest).| - -### Deployment Manifest Tab - - The **Deployment Manifest** tab contains the following tabs. - -|UI Element|Description| -|----------------|-----------------| -|**Name**|Specifies identifying information about this deployment.| -|**Description**|Specifies publisher, product, and support information.| -|**Deployment Options**|Specifies additional information about the deployment, such as the application type and the start location.| -|**Update Options**|Specifies how often ClickOnce should check for application updates.| -|**Application Reference**|Specifies the application manifest for this deployment.| - -### Name Tab - - The **Name** tab is displayed when you first create or open a deployment manifest. It uniquely identifies the deployment, and optionally specifies a valid target platform. - -|UI Element|Description| -|----------------|-----------------| -|**Name**|Required. The name of the deployment manifest. Usually the same as the file name.| -|**Version**|Required. The version number of the deployment in the form *N.N.N.N*. Only the first major build number is required. For example, for version 1.0 of an application, valid values would include `1`, `1.0`, `1.0.0`, and `1.0.0.0`.| -|**Processor**|Optional. The machine architecture on which this deployment can run. The default is `msil`, or Microsoft Intermediate Language, the default format of all managed assemblies. Change this field if you have compiled the assemblies in your application for a specific architecture.| -|**Culture**|Optional. The two-part ISO country/region code in which this application runs. The default is `neutral`.| -|**Public key token**|Optional. The public key with which this deployment manifest has been signed. If this is a new or unsigned manifest, this field will appear as `Unsigned`.| - -### Description Tab - -|UI Element|Description| -|----------------|-----------------| -|**Publisher**|Required. The name of the person or organization responsible for the application. This value is used as the Start menu folder name.| -|**Product**|Required. The full product name. If you selected **Install Locally** for the **Application Type** element on the **Deployment Options** tab, this name will be what appears in the **Start** menu link and in **Add or Remove Programs** for this application.| -|**Support Location**|Optional. The URL from which customers can obtain help and support for the application.| - -### Deployment Options Tab - -|UI Element|Description| -|----------------|-----------------| -|**Application Type**|Optional. Specifies whether this application installs itself to the client computer (**Install Locally**), runs online (**Online Only**), or is a WPF application that runs in the browser (**WPF Browser Application**). The default is **Install Locally**.| -|**Start Location**|Optional. The URL from which the application should actually be started. Useful when deploying an application from a CD that should update itself from the Web.| -|**Include Start Location (ProviderURL) in the manifest**|Optional. Specifies the URL which ClickOnce will examine for application updates.| -|**Automatically run application after installing**|Required. Specifies that the ClickOnce application should run immediately after the initial installation from a URL. The default is the check box is selected.| -|**Allow URL parameters to be passed to application**|Required. Permits the transfer of parameter data to the ClickOnce application through a query string appended to the deployment manifest's URL. The default is the check box is cleared.| -|**Use .deploy file extension**|Required. When selected, all files in the application manifest must have the .deploy extension. The default is the check box is cleared.| - -### Update Options Tab - - The **Update Options** tab only contains options mentioned here when the **Application Type** selection box on the **Name** tab is set to **Install Locally**. - -|UI Element|Description| -|----------------|-----------------| -|**This application should check for updates**|Specifies whether ClickOnce should check for application updates. If this check box is not selected, the application will not check for updates unless you update it programmatically by using the APIs in the namespace.| -|**Choose when the application should check for updates**|Provides two options for update checks:

- **Before the application starts**. The update check is performed prior to application execution.
- **After the application starts**. The update check begins once the main form of the application has initialized, and will run the next time the application starts.| -|**Update check frequency**|Determines how often ClickOnce should check for updates:

- **Check every time the application runs**. ClickOnce will perform an update check every time the user opens the application.
- **Check every**: Select a time interval and a unit (hours, days, or weeks) that must elapse before checking for updates.| -|**Specify a minimum required version for this application**|Optional. Specifies that a specific version of your application is a required installation, preventing your users from working with an earlier version.| -|**Version**|Required if **Specify a minimum required version for this application** check box is selected. The version number supplied must be of the form *N.N.N.N*. Only the first major build number is required. For example, for version 1.0 of an application, valid values would include `1`, `1.0`, `1.0.0`, and `1.0.0.0`.| - -### Application Reference Tab - - The **Application Reference** tab contains the same fields as the **Name** tab described earlier in this topic. The one exception is the following field. - -|UI Element|Description| -|----------------|-----------------| -|**Select Manifest**|Allows you to choose the application manifest. All of the other fields on this page will populate when you choose an application manifest.| - +> MageUI.exe does not support the [compatibleFrameworks](/visualstudio/deployment/compatibleframeworks-element-clickonce-deployment) element when saving an application manifest that has already been signed with a certificate using MageUI.exe. Instead, you must use [Mage.exe](mage-exe-manifest-generation-and-editing-tool.md). + +## UIElement List + + The following table lists the menu and toolbar items that are available. + +|Command|Menu|Shortcut|Description| +|-------------|----------|--------------|-----------------| +|**Application Manifest**|**File, New**||Creates a new application manifest.| +|**Deployment Manifest**|**File, New**||Creates a new deployment manifest.| +|**Open**|**File**|CTRL+O|Opens an existing deployment manifest, application manifest, or trust license for editing.| +|**Close**|**File**|CTRL+F4|Closes an open file.

If you modify a file before closing it, MageUI.exe prompts you to re-sign the file with a public key, key pair, or stored certificate.| +|**Save**|**File**|CTRL+S|Saves to disk the document which currently has user input focus.| +|**Save As**|**File**||Saves a file to disk, enabling you to supply a new file name and/or location.| +|**Save All**|**File**||Saves the changes made to all files currently open within MageUI.exe.| +|**Preferences**|**File**||Opens the **Preferences** dialog box. See the following section for more information.| +|**Exit**|**File**|ALT+F4|Quits MageUI.exe.| +|**Cut**|**Edit**|CTRL+X|Removes the currently selected text from the application and moves it to the system Clipboard.| +|**Copy**|**Edit**|CTRL+C|Copies the currently selected text to the system Clipboard.| +|**Paste**|**Edit**|CTRL+V|Pastes text from the system Clipboard into the currently active text element.| +|**Delete**|**Edit**||Deletes an element currently selected in a list, such as a trust license on the **Deployment Manifest** tab.| +|**Close All**|**Window**||Closes all files currently open in MageUI.exe. If one or more files need saving, MageUI.exe prompts you to save them. MageUI.exe also prompts you to select a signing key for each unsigned or changed file.| +|**About**|**Help**||Displays version and copyright information about MageUI.exe.| + +## Preferences Dialog Box + + The **Preferences** dialog box contains the following elements. + +|UI Element|Description| +|----------------|-----------------| +|**Sign on save**|Prompts you to sign a file whenever you save your modifications.| +|**Use default signing certificate**|Uses the key entered in the **Certificate file** text box to sign all files. This eliminates the signing prompt that typically appears when you save a file and **Sign on Save** is selected. Use the ellipsis (**…**) button next to the **Certificate file** text box to select a key file.| +|Digest algorithm|Specifies the algorithm to generate dependency digests with. Value must be "sha256RSA" or "sha1RSA". Uses SHA1 as the default. Used both in application and deployment manifests. If the user provides a certificate when saving the manifest, uses the algorithms in the certificate to generate dependency digests with.| + +## Signing Options Dialog Box + + The **Signing Options** dialog box appears when you save a manifest or trust license for the first time, or when you change a manifest or trust license. It only appears if the **Sign on Save** option in the **Preferences** dialog box is selected. You must be connected to the Internet when signing a manifest that specifies a value in the **TimeStamping URI** text box. + + This dialog box contains the following elements. + +|UI Element|Description| +|----------------|-----------------| +|**Sign with certificate file**|Signs the manifest with a digital certificate stored on the file system.| +|**File**|Provides an area to type the path to the .pfx file representing the certificate.| +|**...**|Opens a **Choose File** dialog box for selecting an existing .pfx file.| +|**New**|Generates a new .pfx that is not verifiable through a Certificate Authority (CA). For more information about the types of certificates used for signing ClickOnce deployments, see [Trusted Application Deployment Overview](/visualstudio/deployment/trusted-application-deployment-overview).| +|**Password**|Provides an area to type the password used for signing with this certificate. If not applicable, can be left blank.| +|**Sign with stored certificate**|Displays a selectable list of digital certificates stored in your computer's certificate store.| +|**TimeStamping URI**|Displays the Uniform Resource Locator (URI) of a digital timestamping service. Timestamping the manifests prevents you from having to re-sign the manifests if your digital certificate expires before you deploy the next version of your application. For more information, see [Windows root certificate program members](/previous-versions/windows/it-pro/windows-server-2012-R2-and-2012/dn265983(v=ws.11)) and [ClickOnce and Authenticode](/visualstudio/deployment/clickonce-and-authenticode).| +|**Don't Sign**|Allows you to save the manifest without adding a signature from a digital certificate.| + +## Tab and Panel Descriptions + + When you open a document with MageUI.exe, it appears within its own tab page. Each tab contains a set of property panels. The panels contain grouped subsets of the document's data. + +### Application Manifest Tab + + The **Application Manifest** tab displays the contents of an application manifest. The application manifest describes all files included with the deployment, and the permissions required for the application to run on the client. + + The **Application Manifest** tab contains the following tabs. + +|UI Element|Description| +|----------------|-----------------| +|**Name**|Specifies identifying information about this deployment.| +|**Description**|Specifies publisher, product, and support information.| +|**Application Options**|Specifies whether this is a browser application, and whether this manifest is the source of trust information.| +|**Files**|Specifies all of the files that constitute this deployment.| +|**Permissions Required**|Specifies the minimum permission set required by the application to run on a client.| + +### Name Tab + + The **Name** tab is displayed when you first create or open an application manifest. It uniquely identifies the deployment, and optionally specifies a valid target platform. + +|UI Element|Description| +|----------------|-----------------| +|**Name**|Required. The name of the application manifest. Usually the same as the file name.| +|**Version**|Required. The version number of the deployment in the form *N.N.N.N*. Only the first major build number is required. For example, for version 1.0 of an application, valid values would include `1`, `1.0`, `1.0.0`, and `1.0.0.0`.| +|**Processor**|Optional. The machine architecture on which this deployment can run. The default is `msil`, or Microsoft Intermediate Language, which is the default format of all managed assemblies. Change this field if you have pre-compiled the assemblies in your application for a specific architecture. For more information about pre-compilation, see [Ngen.exe (Native Image Generator)](ngen-exe-native-image-generator.md).| +|**Culture**|Optional. The two-part ISO country and region code in which this application runs. The default is `neutral`.| +|**Public key token**|Optional. The public key with which this application manifest has been signed. If this is a new or unsigned manifest, this field will appear as `Unsigned`.| + +### Description Tab + + This information is usually provided within the deployment manifest. These fields can only be modified if the **Use Application Manifest Trust Information** check box is selected on the **Application Options** tab. + +|UI Element|Description| +|----------------|-----------------| +|**Publisher**|The name of the person or organization responsible for the application. This value is used as the Start menu folder name.| +|**Product**|The full product name. If you selected **Install Locally** for the **Application Type** element on the **Deployment Options** tab of the deployment manifest, this name will be what appears in the **Start** menu link and in **Add or Remove Programs** for this application.| +|**Support Location**|The URL from which customers can obtain help and support for the application.| + +### Application Options Tab + +|UI Element|Description| +|----------------|-----------------| +|**Windows Presentation Foundation Browser Application**|Specifies whether this is a WPF application that runs in the browser as a XAML browser application (XBAP).| +|**Use Application Manifest Trust Information**|Specifies whether this manifest contains trust information.| + +### Files Tab + +|UI Element|Description| +|----------------|-----------------| +|**Application directory**|The directory in which the application's files reside. Use the ellipses (**…**) button to select the directory.| +|**Populate**|Adds all of the files in the application directory and subdirectories to the application manifest. If MageUI.exe finds a single executable file in the directory, it automatically marks this as the Entry Point, which is the file first executed when the ClickOnce application is launched on the client.| +|**Application Files**|Lists all of the files in the application. Each file has three editable attributes, discussed below.| +|**File Type**|File Type can be one of four values:

- None.
- Entry Point. The application's primary executable. Only one executable file can be marked as the entry point.
- Data File. A file, such as an XML file, that supplies data to the application.
- Icon File. An application icon, such as appears on the desktop or in the corner of an application's window.| +|**Optional**|Files marked optional are not downloaded on initial install or update, but may be downloaded at runtime using the System.Deployment On-Demand API. For more information, see [Walkthrough: Downloading Assemblies on Demand with the ClickOnce Deployment API Using the Designer](/visualstudio/deployment/walkthrough-downloading-assemblies-on-demand-with-the-clickonce-deployment-api-using-the-designer).| +|**Group**|A label for a set of optional files. You can apply a Group label to a set of files, and use the On-Demand API to download a batch of files with a single API call.| + +### Permissions Required Tab + + Use the **Permissions Required** tab if you need to grant your application more access to the local computer than is granted by default. For more information, see [Securing ClickOnce Applications](/visualstudio/deployment/securing-clickonce-applications). + +|UI Element|Description| +|----------------|-----------------| +|**Permission set type**|The minimum permission set required by this application to run on the client. For a description of these permission sets and which permissions they do or do not demand, see [Named Permission Sets](/previous-versions/dotnet/netframework-4.0/4652tyx7(v=vs.100)).| +|**Details**|The XML created for the application manifest to represent the permission set. Unless you have a good understanding of the application manifest XML format, you should not edit this XML manually. For more information, see [ClickOnce Application Manifest](/visualstudio/deployment/clickonce-application-manifest).| + +### Deployment Manifest Tab + + The **Deployment Manifest** tab contains the following tabs. + +|UI Element|Description| +|----------------|-----------------| +|**Name**|Specifies identifying information about this deployment.| +|**Description**|Specifies publisher, product, and support information.| +|**Deployment Options**|Specifies additional information about the deployment, such as the application type and the start location.| +|**Update Options**|Specifies how often ClickOnce should check for application updates.| +|**Application Reference**|Specifies the application manifest for this deployment.| + +### Name Tab + + The **Name** tab is displayed when you first create or open a deployment manifest. It uniquely identifies the deployment, and optionally specifies a valid target platform. + +|UI Element|Description| +|----------------|-----------------| +|**Name**|Required. The name of the deployment manifest. Usually the same as the file name.| +|**Version**|Required. The version number of the deployment in the form *N.N.N.N*. Only the first major build number is required. For example, for version 1.0 of an application, valid values would include `1`, `1.0`, `1.0.0`, and `1.0.0.0`.| +|**Processor**|Optional. The machine architecture on which this deployment can run. The default is `msil`, or Microsoft Intermediate Language, the default format of all managed assemblies. Change this field if you have compiled the assemblies in your application for a specific architecture.| +|**Culture**|Optional. The two-part ISO country/region code in which this application runs. The default is `neutral`.| +|**Public key token**|Optional. The public key with which this deployment manifest has been signed. If this is a new or unsigned manifest, this field will appear as `Unsigned`.| + +### Description Tab + +|UI Element|Description| +|----------------|-----------------| +|**Publisher**|Required. The name of the person or organization responsible for the application. This value is used as the Start menu folder name.| +|**Product**|Required. The full product name. If you selected **Install Locally** for the **Application Type** element on the **Deployment Options** tab, this name will be what appears in the **Start** menu link and in **Add or Remove Programs** for this application.| +|**Support Location**|Optional. The URL from which customers can obtain help and support for the application.| + +### Deployment Options Tab + +|UI Element|Description| +|----------------|-----------------| +|**Application Type**|Optional. Specifies whether this application installs itself to the client computer (**Install Locally**), runs online (**Online Only**), or is a WPF application that runs in the browser (**WPF Browser Application**). The default is **Install Locally**.| +|**Start Location**|Optional. The URL from which the application should actually be started. Useful when deploying an application from a CD that should update itself from the Web.| +|**Include Start Location (ProviderURL) in the manifest**|Optional. Specifies the URL which ClickOnce will examine for application updates.| +|**Automatically run application after installing**|Required. Specifies that the ClickOnce application should run immediately after the initial installation from a URL. The default is the check box is selected.| +|**Allow URL parameters to be passed to application**|Required. Permits the transfer of parameter data to the ClickOnce application through a query string appended to the deployment manifest's URL. The default is the check box is cleared.| +|**Use .deploy file extension**|Required. When selected, all files in the application manifest must have the .deploy extension. The default is the check box is cleared.| + +### Update Options Tab + + The **Update Options** tab only contains options mentioned here when the **Application Type** selection box on the **Name** tab is set to **Install Locally**. + +|UI Element|Description| +|----------------|-----------------| +|**This application should check for updates**|Specifies whether ClickOnce should check for application updates. If this check box is not selected, the application will not check for updates unless you update it programmatically by using the APIs in the namespace.| +|**Choose when the application should check for updates**|Provides two options for update checks:

- **Before the application starts**. The update check is performed prior to application execution.
- **After the application starts**. The update check begins once the main form of the application has initialized, and will run the next time the application starts.| +|**Update check frequency**|Determines how often ClickOnce should check for updates:

- **Check every time the application runs**. ClickOnce will perform an update check every time the user opens the application.
- **Check every**: Select a time interval and a unit (hours, days, or weeks) that must elapse before checking for updates.| +|**Specify a minimum required version for this application**|Optional. Specifies that a specific version of your application is a required installation, preventing your users from working with an earlier version.| +|**Version**|Required if **Specify a minimum required version for this application** check box is selected. The version number supplied must be of the form *N.N.N.N*. Only the first major build number is required. For example, for version 1.0 of an application, valid values would include `1`, `1.0`, `1.0.0`, and `1.0.0.0`.| + +### Application Reference Tab + + The **Application Reference** tab contains the same fields as the **Name** tab described earlier in this topic. The one exception is the following field. + +|UI Element|Description| +|----------------|-----------------| +|**Select Manifest**|Allows you to choose the application manifest. All of the other fields on this page will populate when you choose an application manifest.| + ## See also - [ClickOnce Security and Deployment](/visualstudio/deployment/clickonce-security-and-deployment) diff --git a/docs/framework/tools/mpgo-exe-managed-profile-guided-optimization-tool.md b/docs/framework/tools/mpgo-exe-managed-profile-guided-optimization-tool.md index 9e7f2c8e711d8..0412c0d046726 100644 --- a/docs/framework/tools/mpgo-exe-managed-profile-guided-optimization-tool.md +++ b/docs/framework/tools/mpgo-exe-managed-profile-guided-optimization-tool.md @@ -66,7 +66,7 @@ mpgo -Scenario -AppID -Timeout If an assembly in the list is in the global assembly cache, it will not be updated to contain the profile information. Remove it from the global assembly cache to collect profile information. - The use of Ngen.exe and Mpgo.exe is recommended only for large managed applications, because the benefit of precompiled native images is typically seen only when it eliminates significant JIT compilation at run time. Running Mpgo.exe on "Hello World" style applications that aren’t working-set intensive will not provide any benefits, and Mpgo.exe may even fail to gather profile data. + The use of Ngen.exe and Mpgo.exe is recommended only for large managed applications, because the benefit of precompiled native images is typically seen only when it eliminates significant JIT compilation at runtime. Running Mpgo.exe on "Hello World" style applications that aren’t working-set intensive will not provide any benefits, and Mpgo.exe may even fail to gather profile data. > [!NOTE] > Ngen.exe and Mpgo.exe are not recommended for ASP.NET applications and Windows Communication Foundation (WCF) services. diff --git a/docs/framework/tools/ngen-exe-native-image-generator.md b/docs/framework/tools/ngen-exe-native-image-generator.md index 44b39be01101d..9e5f9342e9a56 100644 --- a/docs/framework/tools/ngen-exe-native-image-generator.md +++ b/docs/framework/tools/ngen-exe-native-image-generator.md @@ -113,7 +113,7 @@ The following table shows the syntax of each `action`. For descriptions of the i |Configuration|Description| |-------------------|-----------------| -|`/ExeConfig:` `exePath`|Use the configuration of the specified executable assembly.

Ngen.exe needs to make the same decisions as the loader when binding to dependencies. When a shared component is loaded at run time, using the method, the application's configuration file determines the dependencies that are loaded for the shared component — for example, the version of a dependency that is loaded. The `/ExeConfig` switch gives Ngen.exe guidance on which dependencies would be loaded at run time.| +|`/ExeConfig:` `exePath`|Use the configuration of the specified executable assembly.

Ngen.exe needs to make the same decisions as the loader when binding to dependencies. When a shared component is loaded at runtime, using the method, the application's configuration file determines the dependencies that are loaded for the shared component — for example, the version of a dependency that is loaded. The `/ExeConfig` switch gives Ngen.exe guidance on which dependencies would be loaded at runtime.| |`/AppBase:` `directoryPath`|When locating dependencies, use the specified directory as the application base.| @@ -265,7 +265,7 @@ In addition to these general considerations, the nature of your application must - Large applications generally benefit from compilation to native images. Small applications generally do not benefit. -- For long-running applications, run-time JIT compilation performs slightly better than native images. (Hard binding can mitigate this performance difference to some degree.) +- For long-running applications, runtime JIT compilation performs slightly better than native images. (Hard binding can mitigate this performance difference to some degree.) diff --git a/docs/framework/ui-automation/use-the-automationid-property.md b/docs/framework/ui-automation/use-the-automationid-property.md index 8c453d7a2ca92..9dd3cce2a7b6f 100644 --- a/docs/framework/ui-automation/use-the-automationid-property.md +++ b/docs/framework/ui-automation/use-the-automationid-property.md @@ -32,7 +32,7 @@ ms.topic: how-to #### Use a unique and discoverable AutomationID to locate a specific element in the UI Automation tree -- Use a tool such as UI Spy to report the of a UI element of interest. This value can then be copied and pasted into a client application such as a test script for subsequent automated testing. This approach reduces and simplifies the code necessary to identify and locate an element at run time. +- Use a tool such as UI Spy to report the of a UI element of interest. This value can then be copied and pasted into a client application such as a test script for subsequent automated testing. This approach reduces and simplifies the code necessary to identify and locate an element at runtime. > [!CAUTION] > In general, you should try to obtain only direct children of the . A search for descendants may iterate through hundreds or even thousands of elements, possibly resulting in a stack overflow. If you are attempting to obtain a specific element at a lower level, you should start your search from the application window or from a container at a lower level. diff --git a/docs/framework/unmanaged-api/debugging/isosdacinterface-getmethoddescptrfromip-method.md b/docs/framework/unmanaged-api/debugging/isosdacinterface-getmethoddescptrfromip-method.md index a7c6b208a89f2..5e1b57294305f 100644 --- a/docs/framework/unmanaged-api/debugging/isosdacinterface-getmethoddescptrfromip-method.md +++ b/docs/framework/unmanaged-api/debugging/isosdacinterface-getmethoddescptrfromip-method.md @@ -35,7 +35,7 @@ HRESULT GetMethodDescPtrFromIP( ## Parameters `ip`\ -[in] An address within the method at run time. +[in] An address within the method at runtime. `ppMD`\ [out] The address of the `MethodDesc` for the particular method. @@ -46,10 +46,10 @@ The provided method is part of the [`ISOSDacInterface` interface](isosdacinterfa ## Requirements -**Platforms:** See [System Requirements](../../get-started/system-requirements.md). -**Header:** None -**Library:** None -**.NET Framework Versions:** [!INCLUDE[net_current_v47plus](../../../../includes/net-current-v47plus.md)] +**Platforms:** See [System Requirements](../../get-started/system-requirements.md). +**Header:** None +**Library:** None +**.NET Framework Versions:** [!INCLUDE[net_current_v47plus](../../../../includes/net-current-v47plus.md)] ## See also diff --git a/docs/framework/unmanaged-api/hosting/clr-hosting-interfaces.md b/docs/framework/unmanaged-api/hosting/clr-hosting-interfaces.md index 842da1be4ba10..8a44ab561b2cc 100644 --- a/docs/framework/unmanaged-api/hosting/clr-hosting-interfaces.md +++ b/docs/framework/unmanaged-api/hosting/clr-hosting-interfaces.md @@ -2,7 +2,7 @@ description: "Learn more about: CLR Hosting Interfaces" title: "CLR Hosting Interfaces" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "interfaces [.NET Framework hosting], version 2.0" - "hosting interfaces [.NET Framework], version 2.0" - ".NET Framework 2.0, hosting interfaces" @@ -10,181 +10,181 @@ ms.assetid: 703b8381-43db-4a4d-9faa-cca39302d922 --- # CLR Hosting Interfaces -This section describes the interfaces that unmanaged hosts can use to integrate the common language runtime (CLR) into their applications. The information pertains to the .NET Framework version 2.0 and later versions. These interfaces enable the host to control many more aspects of the runtime than was possible in versions 1.0 and 1.1, and provide much tighter integration between the CLR and the host's execution model. - - In the .NET Framework version 1.0 and 1.1, the hosting model enabled an unmanaged host to load the CLR into a process, to configure certain settings, and to receive event notifications. However, in general, the host and the CLR ran independently in that process. In the .NET Framework version 2.0 and later versions, new layers of abstraction let the host provide many of the resources currently provided by the types in the Win32 assembly, and extend the set of capabilities that the host can configure. - -## In This Section - - [IActionOnCLREvent Interface](iactiononclrevent-interface.md) - Provides a method that performs a callback for a registered event. - - [IApartmentCallback Interface](iapartmentcallback-interface.md) - Provides methods for making callbacks within an apartment. - - [IAppDomainBinding Interface](iappdomainbinding-interface.md) - Provides methods for setting run-time configuration. - - [ICatalogServices Interface](icatalogservices-interface.md) - Provides methods for cataloging services. (This interface supports the .NET Framework infrastructure and is not intended to be used directly from your code.) - - [ICLRAssemblyIdentityManager Interface](iclrassemblyidentitymanager-interface.md) - Provides methods that support communication between the host and the CLR about assemblies. - - [ICLRAssemblyReferenceList Interface](iclrassemblyreferencelist-interface.md) - Manages a list of assemblies that are loaded by the CLR and not by the host. - - [ICLRControl Interface](iclrcontrol-interface.md) - Provides methods for the host to gain access to, and configure various aspects of, the CLR. - - [ICLRDebugManager Interface](iclrdebugmanager-interface.md) - Provides methods that enable a host to associate a set of tasks with an identifier and a friendly name. - - [ICLRErrorReportingManager Interface](iclrerrorreportingmanager-interface.md) - Provides methods that enable the host to configure custom heap dumps for error reporting. - - [ICLRGCManager Interface](iclrgcmanager-interface.md) - Provides methods that enable a host to interact with the CLR's garbage collection system. - - [ICLRHostBindingPolicyManager Interface](iclrhostbindingpolicymanager-interface.md) - Provides methods for the host to evaluate and communicate changes in policy information for assemblies. - - [ICLRHostProtectionManager Interface](iclrhostprotectionmanager-interface.md) - Enables the host to block specific managed classes, methods, properties, and fields from running in partially trusted code. - - [ICLRIoCompletionManager Interface](iclriocompletionmanager-interface.md) - Implements a callback method that enables the host to notify the CLR of the status of specified I/O requests. - - [ICLRMemoryNotificationCallback Interface](iclrmemorynotificationcallback-interface.md) - Enables the host to report memory pressure conditions using an approach similar to that of the Win32 `CreateMemoryResourceNotification` function. - - [ICLROnEventManager Interface](iclroneventmanager-interface.md) - Provides methods that enable the host to register and unregister callbacks for CLR events. - - [ICLRPolicyManager Interface](iclrpolicymanager-interface.md) - Provides methods that enable the host to specify policy actions to be taken in the event of failures and timeouts. - - [ICLRProbingAssemblyEnum Interface](iclrprobingassemblyenum-interface.md) - Provides methods that enable the host to get the probing identities of an assembly by using the assembly's identity information that is internal to the CLR, without needing to create or understand that identity. - - [ICLRReferenceAssemblyEnum Interface](iclrreferenceassemblyenum-interface.md) - Provides methods that enable the host to manipulate the set of assemblies referenced by a file or stream using assembly identity data that is internal to the CLR, without needing to create or understand those identities. - - [ICLRRuntimeHost Interface](iclrruntimehost-interface.md) - Provides capabilities similar to [ICorRuntimeHost](icorruntimehost-interface.md), with an additional method to set the host control interface. - - [ICLRSyncManager Interface](iclrsyncmanager-interface.md) - Provides methods for the host to get information about requested tasks and to detect deadlocks in its synchronization implementation. - - [ICLRTask Interface](iclrtask-interface.md) - Provides methods that enable the host to make requests of the CLR, or to provide notification to the CLR about the associated task. - - [ICLRTaskManager Interface](iclrtaskmanager-interface.md) - Provides methods that enable the host to request explicitly that the CLR create a new task, get the currently executing task, and set the geographic language and culture for the task. - - [ICLRValidator Interface](iclrvalidator-interface.md) - Provides methods for validating portable executable (PE) images and reporting validation errors. - - [ICorConfiguration Interface](icorconfiguration-interface.md) - Provides methods for configuring the CLR. - - [ICorThreadpool Interface](icorthreadpool-interface.md) - Provides methods for accessing the thread pool. - - [IDebuggerInfo Interface](idebuggerinfo-interface.md) - Provides methods for obtaining information about the state of the debugging services. - - [IDebuggerThreadControl Interface](idebuggerthreadcontrol-interface.md) - Provides methods for notifying the host about the blocking and unblocking of threads by the debugging services. - - [IGCHost Interface](igchost-interface.md) - Provides methods for obtaining information about the garbage collection system and for controlling some aspects of garbage collection. - - [IGCHost2 Interface](igchost2-interface.md) - Provides the [SetGCStartupLimitsEx](igchost2-setgcstartuplimitsex-method.md) method that enables a host to set the size of the garbage collection segment and the maximum size of the garbage collection system's generation zero to values greater than `DWORD`. - - [IGCHostControl Interface](igchostcontrol-interface.md) - Provides a method that enables the garbage collector to request the host to change the limits of virtual memory. - - [IGCThreadControl Interface](igcthreadcontrol-interface.md) - Provides methods for participating in the scheduling of threads that would otherwise be blocked for garbage collection. - - [IHostAssemblyManager Interface](ihostassemblymanager-interface.md) - Provides methods that enable a host to specify sets of assemblies that should be loaded by the CLR or by the host. - - [IHostAssemblyStore Interface](ihostassemblystore-interface.md) - Provides methods that enable a host to load assemblies and modules independently of the CLR. - - [IHostAutoEvent Interface](ihostautoevent-interface.md) - Provides a representation of an auto-reset event implemented by the host. - - [IHostControl Interface](ihostcontrol-interface.md) - Provides methods for configuring the loading of assemblies, and for determining which hosting interfaces the host supports. - - [IHostCrst Interface](ihostcrst-interface.md) - Serves as the host's representation of a critical section for threading. - - [IHostGCManager Interface](ihostgcmanager-interface.md) - Provides methods that notify the host of events in the garbage collection mechanism implemented by the CLR. - - [IHostIoCompletionManager Interface](ihostiocompletionmanager-interface.md) - Provides methods that enable the CLR to interact with I/O completion ports provided by the host. - - [IHostMalloc Interface](ihostmalloc-interface.md) - Provides methods for the CLR to request fine-grained allocations from the heap through the host. - - [IHostManualEvent Interface](ihostmanualevent-interface.md) - Provides the host's implementation of a representation of a manual reset event. - - [IHostMemoryManager Interface](ihostmemorymanager-interface.md) - Provides methods for the CLR to make virtual memory requests through the host, instead of using the standard Win32 virtual memory functions. - - [IHostPolicyManager Interface](ihostpolicymanager-interface.md) - Provides methods that notify the host of the actions the CLR performs in case of aborts, timeouts, or failures. - - [IHostSecurityContext Interface](ihostsecuritycontext-interface.md) - Enables the CLR to maintain security context information implemented by the host. - - [IHostSecurityManager Interface](ihostsecuritymanager-interface.md) - Provides methods that enable access to, and control over, the security context of the currently executing thread. - - [IHostSemaphore Interface](ihostsemaphore-interface.md) - Provides a representation of a semaphore implemented by the host. - - [IHostSyncManager Interface](ihostsyncmanager-interface.md) - Provides methods for the CLR to create synchronization primitives by calling the host, instead of using the Win32 synchronization functions. - - [IHostTask Interface](ihosttask-interface.md) - Provides methods that enable the CLR to communicate with the host to manage tasks. - - [IHostTaskManager Interface](ihosttaskmanager-interface.md) - Provides methods that enable the CLR to work with tasks through the host instead of using the standard operating system threading or fiber functions. - - [IHostThreadPoolManager Interface](ihostthreadpoolmanager-interface.md) - Provides methods for the CLR to configure the thread pool and to queue work items to the thread pool. - - [IManagedObject Interface](imanagedobject-interface.md) - Provides methods for controlling a managed object. - - "IObjectHandle" - Provides a method for unwrapping marshal-by-value objects from indirection. - - [ITypeName Interface](itypename-interface.md) - Provides methods for obtaining type name information. (This interface supports the .NET Framework infrastructure and is not intended to be used directly from your code.) - - [ITypeNameBuilder Interface](itypenamebuilder-interface.md) - Provides methods for building a type name. (This interface supports the .NET Framework infrastructure and is not intended to be used directly from your code.) - - [ITypeNameFactory Interface](itypenamefactory-interface.md) - Provides methods for deconstructing a type name. (This interface supports the .NET Framework infrastructure and is not intended to be used directly from your code.) - - "IValidator" - Provides methods for validating portable executable (PE) images and reporting validation errors. - -## Related Sections - - [Deprecated CLR Hosting Interfaces and Coclasses](deprecated-clr-hosting-interfaces-and-coclasses.md) - Contains topics that describe the hosting interfaces provided in the .NET Framework version 1.0 and 1.1. - - [CLR Hosting Interfaces Added in the .NET Framework 4 and 4.5](clr-hosting-interfaces-added-in-the-net-framework-4-and-4-5.md) +This section describes the interfaces that unmanaged hosts can use to integrate the common language runtime (CLR) into their applications. The information pertains to the .NET Framework version 2.0 and later versions. These interfaces enable the host to control many more aspects of the runtime than was possible in versions 1.0 and 1.1, and provide much tighter integration between the CLR and the host's execution model. + + In the .NET Framework version 1.0 and 1.1, the hosting model enabled an unmanaged host to load the CLR into a process, to configure certain settings, and to receive event notifications. However, in general, the host and the CLR ran independently in that process. In the .NET Framework version 2.0 and later versions, new layers of abstraction let the host provide many of the resources currently provided by the types in the Win32 assembly, and extend the set of capabilities that the host can configure. + +## In This Section + + [IActionOnCLREvent Interface](iactiononclrevent-interface.md) + Provides a method that performs a callback for a registered event. + + [IApartmentCallback Interface](iapartmentcallback-interface.md) + Provides methods for making callbacks within an apartment. + + [IAppDomainBinding Interface](iappdomainbinding-interface.md) + Provides methods for setting runtime configuration. + + [ICatalogServices Interface](icatalogservices-interface.md) + Provides methods for cataloging services. (This interface supports the .NET Framework infrastructure and is not intended to be used directly from your code.) + + [ICLRAssemblyIdentityManager Interface](iclrassemblyidentitymanager-interface.md) + Provides methods that support communication between the host and the CLR about assemblies. + + [ICLRAssemblyReferenceList Interface](iclrassemblyreferencelist-interface.md) + Manages a list of assemblies that are loaded by the CLR and not by the host. + + [ICLRControl Interface](iclrcontrol-interface.md) + Provides methods for the host to gain access to, and configure various aspects of, the CLR. + + [ICLRDebugManager Interface](iclrdebugmanager-interface.md) + Provides methods that enable a host to associate a set of tasks with an identifier and a friendly name. + + [ICLRErrorReportingManager Interface](iclrerrorreportingmanager-interface.md) + Provides methods that enable the host to configure custom heap dumps for error reporting. + + [ICLRGCManager Interface](iclrgcmanager-interface.md) + Provides methods that enable a host to interact with the CLR's garbage collection system. + + [ICLRHostBindingPolicyManager Interface](iclrhostbindingpolicymanager-interface.md) + Provides methods for the host to evaluate and communicate changes in policy information for assemblies. + + [ICLRHostProtectionManager Interface](iclrhostprotectionmanager-interface.md) + Enables the host to block specific managed classes, methods, properties, and fields from running in partially trusted code. + + [ICLRIoCompletionManager Interface](iclriocompletionmanager-interface.md) + Implements a callback method that enables the host to notify the CLR of the status of specified I/O requests. + + [ICLRMemoryNotificationCallback Interface](iclrmemorynotificationcallback-interface.md) + Enables the host to report memory pressure conditions using an approach similar to that of the Win32 `CreateMemoryResourceNotification` function. + + [ICLROnEventManager Interface](iclroneventmanager-interface.md) + Provides methods that enable the host to register and unregister callbacks for CLR events. + + [ICLRPolicyManager Interface](iclrpolicymanager-interface.md) + Provides methods that enable the host to specify policy actions to be taken in the event of failures and timeouts. + + [ICLRProbingAssemblyEnum Interface](iclrprobingassemblyenum-interface.md) + Provides methods that enable the host to get the probing identities of an assembly by using the assembly's identity information that is internal to the CLR, without needing to create or understand that identity. + + [ICLRReferenceAssemblyEnum Interface](iclrreferenceassemblyenum-interface.md) + Provides methods that enable the host to manipulate the set of assemblies referenced by a file or stream using assembly identity data that is internal to the CLR, without needing to create or understand those identities. + + [ICLRRuntimeHost Interface](iclrruntimehost-interface.md) + Provides capabilities similar to [ICorRuntimeHost](icorruntimehost-interface.md), with an additional method to set the host control interface. + + [ICLRSyncManager Interface](iclrsyncmanager-interface.md) + Provides methods for the host to get information about requested tasks and to detect deadlocks in its synchronization implementation. + + [ICLRTask Interface](iclrtask-interface.md) + Provides methods that enable the host to make requests of the CLR, or to provide notification to the CLR about the associated task. + + [ICLRTaskManager Interface](iclrtaskmanager-interface.md) + Provides methods that enable the host to request explicitly that the CLR create a new task, get the currently executing task, and set the geographic language and culture for the task. + + [ICLRValidator Interface](iclrvalidator-interface.md) + Provides methods for validating portable executable (PE) images and reporting validation errors. + + [ICorConfiguration Interface](icorconfiguration-interface.md) + Provides methods for configuring the CLR. + + [ICorThreadpool Interface](icorthreadpool-interface.md) + Provides methods for accessing the thread pool. + + [IDebuggerInfo Interface](idebuggerinfo-interface.md) + Provides methods for obtaining information about the state of the debugging services. + + [IDebuggerThreadControl Interface](idebuggerthreadcontrol-interface.md) + Provides methods for notifying the host about the blocking and unblocking of threads by the debugging services. + + [IGCHost Interface](igchost-interface.md) + Provides methods for obtaining information about the garbage collection system and for controlling some aspects of garbage collection. + + [IGCHost2 Interface](igchost2-interface.md) + Provides the [SetGCStartupLimitsEx](igchost2-setgcstartuplimitsex-method.md) method that enables a host to set the size of the garbage collection segment and the maximum size of the garbage collection system's generation zero to values greater than `DWORD`. + + [IGCHostControl Interface](igchostcontrol-interface.md) + Provides a method that enables the garbage collector to request the host to change the limits of virtual memory. + + [IGCThreadControl Interface](igcthreadcontrol-interface.md) + Provides methods for participating in the scheduling of threads that would otherwise be blocked for garbage collection. + + [IHostAssemblyManager Interface](ihostassemblymanager-interface.md) + Provides methods that enable a host to specify sets of assemblies that should be loaded by the CLR or by the host. + + [IHostAssemblyStore Interface](ihostassemblystore-interface.md) + Provides methods that enable a host to load assemblies and modules independently of the CLR. + + [IHostAutoEvent Interface](ihostautoevent-interface.md) + Provides a representation of an auto-reset event implemented by the host. + + [IHostControl Interface](ihostcontrol-interface.md) + Provides methods for configuring the loading of assemblies, and for determining which hosting interfaces the host supports. + + [IHostCrst Interface](ihostcrst-interface.md) + Serves as the host's representation of a critical section for threading. + + [IHostGCManager Interface](ihostgcmanager-interface.md) + Provides methods that notify the host of events in the garbage collection mechanism implemented by the CLR. + + [IHostIoCompletionManager Interface](ihostiocompletionmanager-interface.md) + Provides methods that enable the CLR to interact with I/O completion ports provided by the host. + + [IHostMalloc Interface](ihostmalloc-interface.md) + Provides methods for the CLR to request fine-grained allocations from the heap through the host. + + [IHostManualEvent Interface](ihostmanualevent-interface.md) + Provides the host's implementation of a representation of a manual reset event. + + [IHostMemoryManager Interface](ihostmemorymanager-interface.md) + Provides methods for the CLR to make virtual memory requests through the host, instead of using the standard Win32 virtual memory functions. + + [IHostPolicyManager Interface](ihostpolicymanager-interface.md) + Provides methods that notify the host of the actions the CLR performs in case of aborts, timeouts, or failures. + + [IHostSecurityContext Interface](ihostsecuritycontext-interface.md) + Enables the CLR to maintain security context information implemented by the host. + + [IHostSecurityManager Interface](ihostsecuritymanager-interface.md) + Provides methods that enable access to, and control over, the security context of the currently executing thread. + + [IHostSemaphore Interface](ihostsemaphore-interface.md) + Provides a representation of a semaphore implemented by the host. + + [IHostSyncManager Interface](ihostsyncmanager-interface.md) + Provides methods for the CLR to create synchronization primitives by calling the host, instead of using the Win32 synchronization functions. + + [IHostTask Interface](ihosttask-interface.md) + Provides methods that enable the CLR to communicate with the host to manage tasks. + + [IHostTaskManager Interface](ihosttaskmanager-interface.md) + Provides methods that enable the CLR to work with tasks through the host instead of using the standard operating system threading or fiber functions. + + [IHostThreadPoolManager Interface](ihostthreadpoolmanager-interface.md) + Provides methods for the CLR to configure the thread pool and to queue work items to the thread pool. + + [IManagedObject Interface](imanagedobject-interface.md) + Provides methods for controlling a managed object. + + "IObjectHandle" + Provides a method for unwrapping marshal-by-value objects from indirection. + + [ITypeName Interface](itypename-interface.md) + Provides methods for obtaining type name information. (This interface supports the .NET Framework infrastructure and is not intended to be used directly from your code.) + + [ITypeNameBuilder Interface](itypenamebuilder-interface.md) + Provides methods for building a type name. (This interface supports the .NET Framework infrastructure and is not intended to be used directly from your code.) + + [ITypeNameFactory Interface](itypenamefactory-interface.md) + Provides methods for deconstructing a type name. (This interface supports the .NET Framework infrastructure and is not intended to be used directly from your code.) + + "IValidator" + Provides methods for validating portable executable (PE) images and reporting validation errors. + +## Related Sections + + [Deprecated CLR Hosting Interfaces and Coclasses](deprecated-clr-hosting-interfaces-and-coclasses.md) + Contains topics that describe the hosting interfaces provided in the .NET Framework version 1.0 and 1.1. + + [CLR Hosting Interfaces Added in the .NET Framework 4 and 4.5](clr-hosting-interfaces-added-in-the-net-framework-4-and-4-5.md) Contains topics that describe the hosting interfaces provided in the .NET Framework 4. diff --git a/docs/framework/unmanaged-api/hosting/ecustomdumpflavor-enumeration.md b/docs/framework/unmanaged-api/hosting/ecustomdumpflavor-enumeration.md index 303c9461d4244..bfb15ecbd9b47 100644 --- a/docs/framework/unmanaged-api/hosting/ecustomdumpflavor-enumeration.md +++ b/docs/framework/unmanaged-api/hosting/ecustomdumpflavor-enumeration.md @@ -2,54 +2,54 @@ description: "Learn more about: ECustomDumpFlavor Enumeration" title: "ECustomDumpFlavor Enumeration" ms.date: "03/30/2017" -api_name: +api_name: - "ECustomDumpFlavor" -api_location: +api_location: - "mscoree.dll" -api_type: +api_type: - "COM" -f1_keywords: +f1_keywords: - "ECustomDumpFlavor" -helpviewer_keywords: +helpviewer_keywords: - "ECustomDumpFlavor enumeration [.NET Framework hosting]" ms.assetid: b39b3320-fac7-41f1-9a03-ab6fb0cd89c7 -topic_type: +topic_type: - "apiref" --- # ECustomDumpFlavor Enumeration -Contains values that indicate which items to include in a custom subset of a heap dump when reporting errors. - -## Syntax - -```cpp -typedef enum { - DUMP_FLAVOR_Mini = 1, - DUMP_FLAVOR_NonHeapCLRState = 2 -} ECustomDumpFlavor; -``` - -## Members - -|Member|Description| -|------------|-----------------| -|`DUMP_FLAVOR_Mini`|Specifies that the custom heap dump should start as a minidump and include extra data specified by any [CustomDumpItem](customdumpitem-structure.md) instances passed to the same method.| -|`DUMP_FLAVOR_NonHeapCLRState`|Specifies that the custom heap dump should gather all run-time state data that was not dynamically allocated.| - -## Remarks - - A parameter of type `ECustomDumpFlavor` is passed to the [ICLRErrorReportingManager::BeginCustomDump](iclrerrorreportingmanager-begincustomdump-method.md) method. - -## Requirements - - **Platforms:** See [System Requirements](../../get-started/system-requirements.md). - - **Header:** MSCorEE.h - - **Library:** MSCorEE.dll - - **.NET Framework Versions:** [!INCLUDE[net_current_v20plus](../../../../includes/net-current-v20plus-md.md)] - +Contains values that indicate which items to include in a custom subset of a heap dump when reporting errors. + +## Syntax + +```cpp +typedef enum { + DUMP_FLAVOR_Mini = 1, + DUMP_FLAVOR_NonHeapCLRState = 2 +} ECustomDumpFlavor; +``` + +## Members + +|Member|Description| +|------------|-----------------| +|`DUMP_FLAVOR_Mini`|Specifies that the custom heap dump should start as a minidump and include extra data specified by any [CustomDumpItem](customdumpitem-structure.md) instances passed to the same method.| +|`DUMP_FLAVOR_NonHeapCLRState`|Specifies that the custom heap dump should gather all runtime state data that was not dynamically allocated.| + +## Remarks + + A parameter of type `ECustomDumpFlavor` is passed to the [ICLRErrorReportingManager::BeginCustomDump](iclrerrorreportingmanager-begincustomdump-method.md) method. + +## Requirements + + **Platforms:** See [System Requirements](../../get-started/system-requirements.md). + + **Header:** MSCorEE.h + + **Library:** MSCorEE.dll + + **.NET Framework Versions:** [!INCLUDE[net_current_v20plus](../../../../includes/net-current-v20plus-md.md)] + ## See also - [ECustomDumpItemKind Enumeration](ecustomdumpitemkind-enumeration.md) diff --git a/docs/framework/unmanaged-api/hosting/getrequestedruntimeinfo-function.md b/docs/framework/unmanaged-api/hosting/getrequestedruntimeinfo-function.md index fbafb3d896062..bf398abcab399 100644 --- a/docs/framework/unmanaged-api/hosting/getrequestedruntimeinfo-function.md +++ b/docs/framework/unmanaged-api/hosting/getrequestedruntimeinfo-function.md @@ -2,31 +2,31 @@ description: "Learn more about: GetRequestedRuntimeInfo Function" title: "GetRequestedRuntimeInfo Function" ms.date: "03/30/2017" -api_name: +api_name: - "GetRequestedRuntimeInfo" -api_location: +api_location: - "mscoree.dll" - "mscoreei.dll" -api_type: +api_type: - "DLLExport" -f1_keywords: +f1_keywords: - "GetRequestedRuntimeInfo" -helpviewer_keywords: +helpviewer_keywords: - "GetRequestedRuntimeInfo function [.NET Framework hosting]" ms.assetid: 0dfd7cdc-c116-4e25-b56a-ac7b0378c942 -topic_type: +topic_type: - "apiref" --- # GetRequestedRuntimeInfo Function -Gets version and directory information about the common language runtime (CLR) requested by an application. - - This function has been deprecated in the .NET Framework 4. - -## Syntax - -```cpp -HRESULT GetRequestedRuntimeInfo ( +Gets version and directory information about the common language runtime (CLR) requested by an application. + + This function has been deprecated in the .NET Framework 4. + +## Syntax + +```cpp +HRESULT GetRequestedRuntimeInfo ( [in] LPCWSTR pExe, [in] LPCWSTR pwszVersion, [in] LPCWSTR pConfigurationFile, @@ -37,90 +37,90 @@ HRESULT GetRequestedRuntimeInfo ( [out] DWORD *dwDirectoryLength, [out] LPWSTR pVersion, [in] DWORD cchBuffer, - [out] DWORD *dwlength -); -``` - -## Parameters - - `pExe` - [in] The name of the application. - - `pwszVersion` - [in] A string specifying the version number of the runtime. - - `pConfigurationFile` - [in] The name of the configuration file that is associated with `pExe`. - - `startupFlags` - [in] One or more of the [STARTUP_FLAGS](startup-flags-enumeration.md) enumeration values. - - `runtimeInfoFlags` - [in] One or more of the [RUNTIME_INFO_FLAGS](runtime-info-flags-enumeration.md) enumeration values. - - `pDirectory` - [out] A buffer that contains the directory path to the runtime upon successful completion. - - `dwDirectory` - [in] The length of the directory buffer. - - `dwDirectoryLength` - [out] A pointer to the length of the directory path string. - - `pVersion` - [out] A buffer that contains the version number of the runtime upon successful completion. - - `cchBuffer` - [in] The length of the version string buffer. - - `dwlength` - [out] A pointer to the length of the version string. - -## Return Value - - This method returns standard Component Object Model (COM) error codes, as defined in WinError.h, in addition to the following values. - -|Return code|Description| -|-----------------|-----------------| -|S_OK|The method completed successfully.| -|ERROR_INSUFFICIENT_BUFFER|The directory buffer is not large enough to store the directory path.

- or -

The version buffer is not large enough to store the version string.| - -## Remarks - - The `GetRequestedRuntimeInfo` method returns run-time information about the version loaded into the process, which is not necessarily the latest version installed on the computer. - - In .NET Framework version 2.0, you can get information about the latest installed version by using the `GetRequestedRuntimeInfo` method as follows: - -- Specify the `pExe`, `pwszVersion`, and `pConfigurationFile` parameters as null. - -- Specify the RUNTIME_INFO_UPGRADE_VERSION flag in the `RUNTIME_INFO_FLAGS` enumerations for the `runtimeInfoFlags` parameter. - - The `GetRequestedRuntimeInfo` method does not return the latest CLR version in the following circumstances: - -- An application configuration file that specifies loading a particular CLR version exists. Note that the .NET Framework will use the configuration file even if you specify null for the `pConfigurationFile` parameter. - -- The [CorBindToRuntimeEx](corbindtoruntimeex-function.md) method was called specifying an earlier CLR version. - -- An application that was compiled for an earlier CLR version is currently running. - - For the `runtimeInfoFlags` parameter, you can specify only one of the architecture constants of the `RUNTIME_INFO_FLAGS` enumeration at a time: - -- RUNTIME_INFO_REQUEST_IA64 - -- RUNTIME_INFO_REQUEST_AMD64 - -- RUNTIME_INFO_REQUEST_X86 - -## Requirements - - **Platforms:** See [System Requirements](../../get-started/system-requirements.md). - - **Header:** MSCorEE.h - - **Library:** MSCorEE.dll - - **.NET Framework Versions:** [!INCLUDE[net_current_v11plus](../../../../includes/net-current-v11plus-md.md)] - + [out] DWORD *dwlength +); +``` + +## Parameters + + `pExe` + [in] The name of the application. + + `pwszVersion` + [in] A string specifying the version number of the runtime. + + `pConfigurationFile` + [in] The name of the configuration file that is associated with `pExe`. + + `startupFlags` + [in] One or more of the [STARTUP_FLAGS](startup-flags-enumeration.md) enumeration values. + + `runtimeInfoFlags` + [in] One or more of the [RUNTIME_INFO_FLAGS](runtime-info-flags-enumeration.md) enumeration values. + + `pDirectory` + [out] A buffer that contains the directory path to the runtime upon successful completion. + + `dwDirectory` + [in] The length of the directory buffer. + + `dwDirectoryLength` + [out] A pointer to the length of the directory path string. + + `pVersion` + [out] A buffer that contains the version number of the runtime upon successful completion. + + `cchBuffer` + [in] The length of the version string buffer. + + `dwlength` + [out] A pointer to the length of the version string. + +## Return Value + + This method returns standard Component Object Model (COM) error codes, as defined in WinError.h, in addition to the following values. + +|Return code|Description| +|-----------------|-----------------| +|S_OK|The method completed successfully.| +|ERROR_INSUFFICIENT_BUFFER|The directory buffer is not large enough to store the directory path.

- or -

The version buffer is not large enough to store the version string.| + +## Remarks + + The `GetRequestedRuntimeInfo` method returns runtime information about the version loaded into the process, which is not necessarily the latest version installed on the computer. + + In .NET Framework version 2.0, you can get information about the latest installed version by using the `GetRequestedRuntimeInfo` method as follows: + +- Specify the `pExe`, `pwszVersion`, and `pConfigurationFile` parameters as null. + +- Specify the RUNTIME_INFO_UPGRADE_VERSION flag in the `RUNTIME_INFO_FLAGS` enumerations for the `runtimeInfoFlags` parameter. + + The `GetRequestedRuntimeInfo` method does not return the latest CLR version in the following circumstances: + +- An application configuration file that specifies loading a particular CLR version exists. Note that the .NET Framework will use the configuration file even if you specify null for the `pConfigurationFile` parameter. + +- The [CorBindToRuntimeEx](corbindtoruntimeex-function.md) method was called specifying an earlier CLR version. + +- An application that was compiled for an earlier CLR version is currently running. + + For the `runtimeInfoFlags` parameter, you can specify only one of the architecture constants of the `RUNTIME_INFO_FLAGS` enumeration at a time: + +- RUNTIME_INFO_REQUEST_IA64 + +- RUNTIME_INFO_REQUEST_AMD64 + +- RUNTIME_INFO_REQUEST_X86 + +## Requirements + + **Platforms:** See [System Requirements](../../get-started/system-requirements.md). + + **Header:** MSCorEE.h + + **Library:** MSCorEE.dll + + **.NET Framework Versions:** [!INCLUDE[net_current_v11plus](../../../../includes/net-current-v11plus-md.md)] + ## See also - [GetRequestedRuntimeVersion Function](getrequestedruntimeversion-function.md) diff --git a/docs/framework/unmanaged-api/metadata/assemblyflags-enumeration.md b/docs/framework/unmanaged-api/metadata/assemblyflags-enumeration.md index 0f2b651fcaac1..48852968850c4 100644 --- a/docs/framework/unmanaged-api/metadata/assemblyflags-enumeration.md +++ b/docs/framework/unmanaged-api/metadata/assemblyflags-enumeration.md @@ -15,7 +15,7 @@ topic_type: --- # AssemblyFlags Enumeration -Contains values that describe run-time features of an assembly. +Contains values that describe runtime features of an assembly. ## Syntax diff --git a/docs/framework/unmanaged-api/metadata/metadata-enumerations.md b/docs/framework/unmanaged-api/metadata/metadata-enumerations.md index 72e9b2bf15f9a..2613a47bf04ab 100644 --- a/docs/framework/unmanaged-api/metadata/metadata-enumerations.md +++ b/docs/framework/unmanaged-api/metadata/metadata-enumerations.md @@ -15,7 +15,7 @@ This section describes the unmanaged enumerations that the metadata API uses. ## In This Section [AssemblyFlags enumeration](assemblyflags-enumeration.md)\ -Contains values that describe the run-time features of an assembly. +Contains values that describe the runtime features of an assembly. [CeeSectionAttr Enumeration](ceesectionattr-enumeration.md)\ Provides values that specify the attributes of a section for use by the [ICeeGen](iceegen-interface.md) interface. diff --git a/docs/framework/unmanaged-api/metadata/metadata-interfaces.md b/docs/framework/unmanaged-api/metadata/metadata-interfaces.md index 3a1d746464b6f..e727d3e40db41 100644 --- a/docs/framework/unmanaged-api/metadata/metadata-interfaces.md +++ b/docs/framework/unmanaged-api/metadata/metadata-interfaces.md @@ -17,7 +17,7 @@ This section describes the unmanaged interfaces that provide access to the metad Provides methods for dynamic code compilation. [IHostFilter Interface](ihostfilter-interface.md)\ -Provides a method for the run-time host to mark metadata tokens for processing. +Provides a method for the runtime host to mark metadata tokens for processing. [IMetaDataConverter interface](imetadataconverter-interface.md)\ Provides methods to map type libraries to their metadata signatures, and to convert from one to the other. diff --git a/docs/framework/unmanaged-api/profiling/icorprofilercallback-interface.md b/docs/framework/unmanaged-api/profiling/icorprofilercallback-interface.md index 6f6f27609cf2d..a5deff7be0eb4 100644 --- a/docs/framework/unmanaged-api/profiling/icorprofilercallback-interface.md +++ b/docs/framework/unmanaged-api/profiling/icorprofilercallback-interface.md @@ -2,119 +2,119 @@ description: "Learn more about: ICorProfilerCallback Interface" title: "ICorProfilerCallback Interface" ms.date: "03/30/2017" -api_name: +api_name: - "ICorProfilerCallback" -api_location: +api_location: - "mscorwks.dll" -api_type: +api_type: - "COM" -f1_keywords: +f1_keywords: - "ICorProfilerCallback" -helpviewer_keywords: +helpviewer_keywords: - "ICorProfilerCallback interface [.NET Framework profiling]" ms.assetid: 4bae06f7-94d7-4ba8-b250-648b2da78674 -topic_type: +topic_type: - "apiref" --- # ICorProfilerCallback Interface -Provides methods that are used by the common language runtime (CLR) to notify a code profiler when the events to which the profiler has subscribed occur. - -## Methods - -|Method|Description| -|------------|-----------------| -|[AppDomainCreationFinished Method](icorprofilercallback-appdomaincreationfinished-method.md)|Notifies the profiler that an application domain has been created.| -|[AppDomainCreationStarted Method](icorprofilercallback-appdomaincreationstarted-method.md)|Notifies the profiler that an application domain is being created.| -|[AppDomainShutdownFinished Method](icorprofilercallback-appdomainshutdownfinished-method.md)|Notifies the profiler that an application domain has been unloaded from a process.| -|[AppDomainShutdownStarted Method](icorprofilercallback-appdomainshutdownstarted-method.md)|Notifies the profiler that an application domain is being unloaded from a process.| -|[AssemblyLoadFinished Method](icorprofilercallback-assemblyloadfinished-method.md)|Notifies the profiler that an assembly has finished loading.| -|[AssemblyLoadStarted Method](icorprofilercallback-assemblyloadstarted-method.md)|Notifies the profiler that an assembly is being loaded.| -|[AssemblyUnloadFinished Method](icorprofilercallback-assemblyunloadfinished-method.md)|Notifies the profiler that an assembly has been unloaded.| -|[AssemblyUnloadStarted Method](icorprofilercallback-assemblyunloadstarted-method.md)|Notifies the profiler that an assembly is being unloaded.| -|[ClassLoadFinished Method](icorprofilercallback-classloadfinished-method.md)|Notifies the profiler that a class has finished loading.| -|[ClassLoadStarted Method](icorprofilercallback-classloadstarted-method.md)|Notifies the profiler that a class is being loaded.| -|[ClassUnloadFinished Method](icorprofilercallback-classunloadfinished-method.md)|Notifies the profiler that a class has finished unloading.| -|[ClassUnloadStarted Method](icorprofilercallback-classunloadstarted-method.md)|Notifies the profiler that a class is being unloaded.| -|[COMClassicVTableCreated Method](icorprofilercallback-comclassicvtablecreated-method.md)|Notifies the profiler that a runtime callable wrapper (RCW) for the specified IID and class has been created.| -|[COMClassicVTableDestroyed Method](icorprofilercallback-comclassicvtabledestroyed-method.md)|Notifies the profiler that an RCW is being destroyed.| -|[ExceptionCatcherEnter Method](icorprofilercallback-exceptioncatcherenter-method.md)|Notifies the profiler that control is being passed to the appropriate `catch` block.| -|[ExceptionCatcherLeave Method](icorprofilercallback-exceptioncatcherleave-method.md)|Notifies the profiler that control is being passed out of the appropriate `catch` block.| -|[ExceptionCLRCatcherExecute Method](icorprofilercallback-exceptionclrcatcherexecute-method.md)|Obsolete in .NET Framework version 2.0.| -|[ExceptionCLRCatcherFound Method](icorprofilercallback-exceptionclrcatcherfound-method.md)|Obsolete in the .NET Framework 2.0.| -|[ExceptionOSHandlerEnter Method](icorprofilercallback-exceptionoshandlerenter-method.md)|Not implemented. A profiler that needs unmanaged exception information must obtain this information through other means.| -|[ExceptionOSHandlerLeave Method](icorprofilercallback-exceptionoshandlerleave-method.md)|Not implemented. A profiler that needs unmanaged exception information must obtain this information through other means.| -|[ExceptionSearchCatcherFound Method](icorprofilercallback-exceptionsearchcatcherfound-method.md)|Notifies the profiler that the search phase of exception handling has located a handler for the exception that was thrown.| -|[ExceptionSearchFilterEnter Method](icorprofilercallback-exceptionsearchfilterenter-method.md)|Notifies the profiler that a user filter is being executed.| -|[ExceptionSearchFilterLeave Method](icorprofilercallback-exceptionsearchfilterleave-method.md)|Notifies the profiler that a user filter has just finished executing.| -|[ExceptionSearchFunctionEnter Method](icorprofilercallback-exceptionsearchfunctionenter-method.md)|Notifies the profiler that the search phase of exception handling has entered a function.| -|[ExceptionSearchFunctionLeave Method](icorprofilercallback-exceptionsearchfunctionleave-method.md)|Notifies the profiler that the search phase of exception handling has finished searching a function.| -|[ExceptionThrown Method](icorprofilercallback-exceptionthrown-method.md)|Notifies the profiler that an exception has been thrown.| -|[ExceptionUnwindFinallyEnter Method](icorprofilercallback-exceptionunwindfinallyenter-method.md)|Notifies the profiler that the unwind phase of exception handling is entering a `finally` clause contained in the specified function.| -|[ExceptionUnwindFinallyLeave Method](icorprofilercallback-exceptionunwindfinallyleave-method.md)|Notifies the profiler that the unwind phase of exception handling has left a `finally` clause.| -|[ExceptionUnwindFunctionEnter Method](icorprofilercallback-exceptionunwindfunctionenter-method.md)|Notifies the profiler that the unwind phase of exception handling has entered a function.| -|[ExceptionUnwindFunctionLeave Method](icorprofilercallback-exceptionunwindfunctionleave-method.md)|Notifies the profiler that the unwind phase of exception handling has finished unwinding a function.| -|[FunctionUnloadStarted Method](icorprofilercallback-functionunloadstarted-method.md)|Notifies the profiler that the runtime has started to unload a function.| -|[Initialize Method](icorprofilercallback-initialize-method.md)|Called to initialize the profiler whenever a new CLR application is started.| -|[JITCachedFunctionSearchFinished Method](icorprofilercallback-jitcachedfunctionsearchfinished-method.md)|Notifies the profiler that a search has finished for a function that was compiled previously using NGen.exe.| -|[JITCachedFunctionSearchStarted Method](icorprofilercallback-jitcachedfunctionsearchstarted-method.md)|Notifies the profiler that a search has started for a function that was compiled previously using NGen.exe.| -|[JITCompilationFinished Method](icorprofilercallback-jitcompilationfinished-method.md)|Notifies the profiler that the JIT compiler has finished compiling a function.| -|[JITCompilationStarted Method](icorprofilercallback-jitcompilationstarted-method.md)|Notifies the profiler that the just-in-time (JIT) compiler has started to compile a function.| -|[JITFunctionPitched Method](icorprofilercallback-jitfunctionpitched-method.md)|Notifies the profiler that a function that has been JIT-compiled has been removed from memory.| -|[JITInlining Method](icorprofilercallback-jitinlining-method.md)|Notifies the profiler that the JIT compiler is about to insert a function in line with another function.| -|[ManagedToUnmanagedTransition Method](icorprofilercallback-managedtounmanagedtransition-method.md)|Notifies the profiler that a transition from managed code to unmanaged code has occurred.| -|[ModuleAttachedToAssembly Method](icorprofilercallback-moduleattachedtoassembly-method.md)|Notifies the profiler that a module is being attached to its parent assembly.| -|[ModuleLoadFinished Method](icorprofilercallback-moduleloadfinished-method.md)|Notifies the profiler that a module has finished loading.| -|[ModuleLoadStarted Method](icorprofilercallback-moduleloadstarted-method.md)|Notifies the profiler that a module is being loaded.| -|[ModuleUnloadFinished Method](icorprofilercallback-moduleunloadfinished-method.md)|Notifies the profiler that a module has finished unloading.| -|[ModuleUnloadStarted Method](icorprofilercallback-moduleunloadstarted-method.md)|Notifies the profiler that a module is being unloaded.| -|[MovedReferences Method](icorprofilercallback-movedreferences-method.md)|Notifies the profiler about object references that were moved during garbage collection.| -|[ObjectAllocated Method](icorprofilercallback-objectallocated-method.md)|Notifies the profiler that memory within the heap has been allocated for an object.| -|[ObjectReferences Method](icorprofilercallback-objectreferences-method.md)|Notifies the profiler about objects in memory referenced by the specified object.| -|[ObjectsAllocatedByClass Method](icorprofilercallback-objectsallocatedbyclass-method.md)|Notifies the profiler about the number of instances of each specified class that have been created since the previous garbage collection.| -|[RemotingClientInvocationFinished Method](icorprofilercallback-remotingclientinvocationfinished-method.md)|Notifies the profiler that a remoting call has run to completion on the client.| -|[RemotingClientInvocationStarted Method](icorprofilercallback-remotingclientinvocationstarted-method.md)|Notifies the profiler that a remoting call has started.| -|[RemotingClientReceivingReply Method](icorprofilercallback-remotingclientreceivingreply-method.md)|Notifies the profiler that the server-side portion of a remoting call has completed and the client is now receiving and about to process the reply.| -|[RemotingClientSendingMessage Method](icorprofilercallback-remotingclientsendingmessage-method.md)|Notifies the profiler that the client is sending a request to the server.| -|[RemotingServerInvocationReturned Method](icorprofilercallback-remotingserverinvocationreturned-method.md)|Notifies the profiler that the process has finished invoking a method in response to a remote method invocation request.| -|[RemotingServerInvocationStarted Method](icorprofilercallback-remotingserverinvocationstarted-method.md)|Notifies the profiler that the process is invoking a method in response to a remote method invocation request.| -|[RemotingServerReceivingMessage Method](icorprofilercallback-remotingserverreceivingmessage-method.md)|Notifies the profiler that the process is receiving a remote method invocation or activation request.| -|[RemotingServerSendingReply Method](icorprofilercallback-remotingserversendingreply-method.md)|Notifies the profiler that the process has finished processing a remote method invocation request and is about to transmit the reply through a channel.| -|[RootReferences Method](icorprofilercallback-rootreferences-method.md)|Notifies the profiler with information about root references after garbage collection.| -|[RuntimeResumeFinished Method](icorprofilercallback-runtimeresumefinished-method.md)|Notifies the profiler that the runtime has resumed all runtime threads and has returned to normal operation.| -|[RuntimeResumeStarted Method](icorprofilercallback-runtimeresumestarted-method.md)|Notifies the profiler that the runtime is resuming all run-time threads.| -|[RuntimeSuspendAborted Method](icorprofilercallback-runtimesuspendaborted-method.md)|Notifies the profiler that the runtime has aborted the run-time suspension that was occurring.| -|[RuntimeSuspendFinished Method](icorprofilercallback-runtimesuspendfinished-method.md)|Notifies the profiler that the runtime has completed suspension of all run-time threads.| -|[RuntimeSuspendStarted Method](icorprofilercallback-runtimesuspendstarted-method.md)|Notifies the profiler that the runtime is about to suspend all run-time threads.| -|[RuntimeThreadResumed Method](icorprofilercallback-runtimethreadresumed-method.md)|Notifies the profiler that the specified thread has resumed after being suspended.| -|[RuntimeThreadSuspended Method](icorprofilercallback-runtimethreadsuspended-method.md)|Notifies the profiler that the specified thread has been, or is about to be, suspended.| -|[Shutdown Method](icorprofilercallback-shutdown-method.md)|Notifies the profiler that the application is shutting down.| -|[ThreadAssignedToOSThread Method](icorprofilercallback-threadassignedtoosthread-method.md)|Notifies the profiler that a managed thread is being implemented using a particular operating system (OS) thread.| -|[ThreadCreated Method](icorprofilercallback-threadcreated-method.md)|Notifies the profiler that a thread has been created.| -|[ThreadDestroyed Method](icorprofilercallback-threaddestroyed-method.md)|Notifies the profiler that a thread has been destroyed.| -|[UnmanagedToManagedTransition Method](icorprofilercallback-unmanagedtomanagedtransition-method.md)|Notifies the profiler that a transition from unmanaged code to managed code has occurred.| - -## Remarks +Provides methods that are used by the common language runtime (CLR) to notify a code profiler when the events to which the profiler has subscribed occur. + +## Methods + +|Method|Description| +|------------|-----------------| +|[AppDomainCreationFinished Method](icorprofilercallback-appdomaincreationfinished-method.md)|Notifies the profiler that an application domain has been created.| +|[AppDomainCreationStarted Method](icorprofilercallback-appdomaincreationstarted-method.md)|Notifies the profiler that an application domain is being created.| +|[AppDomainShutdownFinished Method](icorprofilercallback-appdomainshutdownfinished-method.md)|Notifies the profiler that an application domain has been unloaded from a process.| +|[AppDomainShutdownStarted Method](icorprofilercallback-appdomainshutdownstarted-method.md)|Notifies the profiler that an application domain is being unloaded from a process.| +|[AssemblyLoadFinished Method](icorprofilercallback-assemblyloadfinished-method.md)|Notifies the profiler that an assembly has finished loading.| +|[AssemblyLoadStarted Method](icorprofilercallback-assemblyloadstarted-method.md)|Notifies the profiler that an assembly is being loaded.| +|[AssemblyUnloadFinished Method](icorprofilercallback-assemblyunloadfinished-method.md)|Notifies the profiler that an assembly has been unloaded.| +|[AssemblyUnloadStarted Method](icorprofilercallback-assemblyunloadstarted-method.md)|Notifies the profiler that an assembly is being unloaded.| +|[ClassLoadFinished Method](icorprofilercallback-classloadfinished-method.md)|Notifies the profiler that a class has finished loading.| +|[ClassLoadStarted Method](icorprofilercallback-classloadstarted-method.md)|Notifies the profiler that a class is being loaded.| +|[ClassUnloadFinished Method](icorprofilercallback-classunloadfinished-method.md)|Notifies the profiler that a class has finished unloading.| +|[ClassUnloadStarted Method](icorprofilercallback-classunloadstarted-method.md)|Notifies the profiler that a class is being unloaded.| +|[COMClassicVTableCreated Method](icorprofilercallback-comclassicvtablecreated-method.md)|Notifies the profiler that a runtime callable wrapper (RCW) for the specified IID and class has been created.| +|[COMClassicVTableDestroyed Method](icorprofilercallback-comclassicvtabledestroyed-method.md)|Notifies the profiler that an RCW is being destroyed.| +|[ExceptionCatcherEnter Method](icorprofilercallback-exceptioncatcherenter-method.md)|Notifies the profiler that control is being passed to the appropriate `catch` block.| +|[ExceptionCatcherLeave Method](icorprofilercallback-exceptioncatcherleave-method.md)|Notifies the profiler that control is being passed out of the appropriate `catch` block.| +|[ExceptionCLRCatcherExecute Method](icorprofilercallback-exceptionclrcatcherexecute-method.md)|Obsolete in .NET Framework version 2.0.| +|[ExceptionCLRCatcherFound Method](icorprofilercallback-exceptionclrcatcherfound-method.md)|Obsolete in the .NET Framework 2.0.| +|[ExceptionOSHandlerEnter Method](icorprofilercallback-exceptionoshandlerenter-method.md)|Not implemented. A profiler that needs unmanaged exception information must obtain this information through other means.| +|[ExceptionOSHandlerLeave Method](icorprofilercallback-exceptionoshandlerleave-method.md)|Not implemented. A profiler that needs unmanaged exception information must obtain this information through other means.| +|[ExceptionSearchCatcherFound Method](icorprofilercallback-exceptionsearchcatcherfound-method.md)|Notifies the profiler that the search phase of exception handling has located a handler for the exception that was thrown.| +|[ExceptionSearchFilterEnter Method](icorprofilercallback-exceptionsearchfilterenter-method.md)|Notifies the profiler that a user filter is being executed.| +|[ExceptionSearchFilterLeave Method](icorprofilercallback-exceptionsearchfilterleave-method.md)|Notifies the profiler that a user filter has just finished executing.| +|[ExceptionSearchFunctionEnter Method](icorprofilercallback-exceptionsearchfunctionenter-method.md)|Notifies the profiler that the search phase of exception handling has entered a function.| +|[ExceptionSearchFunctionLeave Method](icorprofilercallback-exceptionsearchfunctionleave-method.md)|Notifies the profiler that the search phase of exception handling has finished searching a function.| +|[ExceptionThrown Method](icorprofilercallback-exceptionthrown-method.md)|Notifies the profiler that an exception has been thrown.| +|[ExceptionUnwindFinallyEnter Method](icorprofilercallback-exceptionunwindfinallyenter-method.md)|Notifies the profiler that the unwind phase of exception handling is entering a `finally` clause contained in the specified function.| +|[ExceptionUnwindFinallyLeave Method](icorprofilercallback-exceptionunwindfinallyleave-method.md)|Notifies the profiler that the unwind phase of exception handling has left a `finally` clause.| +|[ExceptionUnwindFunctionEnter Method](icorprofilercallback-exceptionunwindfunctionenter-method.md)|Notifies the profiler that the unwind phase of exception handling has entered a function.| +|[ExceptionUnwindFunctionLeave Method](icorprofilercallback-exceptionunwindfunctionleave-method.md)|Notifies the profiler that the unwind phase of exception handling has finished unwinding a function.| +|[FunctionUnloadStarted Method](icorprofilercallback-functionunloadstarted-method.md)|Notifies the profiler that the runtime has started to unload a function.| +|[Initialize Method](icorprofilercallback-initialize-method.md)|Called to initialize the profiler whenever a new CLR application is started.| +|[JITCachedFunctionSearchFinished Method](icorprofilercallback-jitcachedfunctionsearchfinished-method.md)|Notifies the profiler that a search has finished for a function that was compiled previously using NGen.exe.| +|[JITCachedFunctionSearchStarted Method](icorprofilercallback-jitcachedfunctionsearchstarted-method.md)|Notifies the profiler that a search has started for a function that was compiled previously using NGen.exe.| +|[JITCompilationFinished Method](icorprofilercallback-jitcompilationfinished-method.md)|Notifies the profiler that the JIT compiler has finished compiling a function.| +|[JITCompilationStarted Method](icorprofilercallback-jitcompilationstarted-method.md)|Notifies the profiler that the just-in-time (JIT) compiler has started to compile a function.| +|[JITFunctionPitched Method](icorprofilercallback-jitfunctionpitched-method.md)|Notifies the profiler that a function that has been JIT-compiled has been removed from memory.| +|[JITInlining Method](icorprofilercallback-jitinlining-method.md)|Notifies the profiler that the JIT compiler is about to insert a function in line with another function.| +|[ManagedToUnmanagedTransition Method](icorprofilercallback-managedtounmanagedtransition-method.md)|Notifies the profiler that a transition from managed code to unmanaged code has occurred.| +|[ModuleAttachedToAssembly Method](icorprofilercallback-moduleattachedtoassembly-method.md)|Notifies the profiler that a module is being attached to its parent assembly.| +|[ModuleLoadFinished Method](icorprofilercallback-moduleloadfinished-method.md)|Notifies the profiler that a module has finished loading.| +|[ModuleLoadStarted Method](icorprofilercallback-moduleloadstarted-method.md)|Notifies the profiler that a module is being loaded.| +|[ModuleUnloadFinished Method](icorprofilercallback-moduleunloadfinished-method.md)|Notifies the profiler that a module has finished unloading.| +|[ModuleUnloadStarted Method](icorprofilercallback-moduleunloadstarted-method.md)|Notifies the profiler that a module is being unloaded.| +|[MovedReferences Method](icorprofilercallback-movedreferences-method.md)|Notifies the profiler about object references that were moved during garbage collection.| +|[ObjectAllocated Method](icorprofilercallback-objectallocated-method.md)|Notifies the profiler that memory within the heap has been allocated for an object.| +|[ObjectReferences Method](icorprofilercallback-objectreferences-method.md)|Notifies the profiler about objects in memory referenced by the specified object.| +|[ObjectsAllocatedByClass Method](icorprofilercallback-objectsallocatedbyclass-method.md)|Notifies the profiler about the number of instances of each specified class that have been created since the previous garbage collection.| +|[RemotingClientInvocationFinished Method](icorprofilercallback-remotingclientinvocationfinished-method.md)|Notifies the profiler that a remoting call has run to completion on the client.| +|[RemotingClientInvocationStarted Method](icorprofilercallback-remotingclientinvocationstarted-method.md)|Notifies the profiler that a remoting call has started.| +|[RemotingClientReceivingReply Method](icorprofilercallback-remotingclientreceivingreply-method.md)|Notifies the profiler that the server-side portion of a remoting call has completed and the client is now receiving and about to process the reply.| +|[RemotingClientSendingMessage Method](icorprofilercallback-remotingclientsendingmessage-method.md)|Notifies the profiler that the client is sending a request to the server.| +|[RemotingServerInvocationReturned Method](icorprofilercallback-remotingserverinvocationreturned-method.md)|Notifies the profiler that the process has finished invoking a method in response to a remote method invocation request.| +|[RemotingServerInvocationStarted Method](icorprofilercallback-remotingserverinvocationstarted-method.md)|Notifies the profiler that the process is invoking a method in response to a remote method invocation request.| +|[RemotingServerReceivingMessage Method](icorprofilercallback-remotingserverreceivingmessage-method.md)|Notifies the profiler that the process is receiving a remote method invocation or activation request.| +|[RemotingServerSendingReply Method](icorprofilercallback-remotingserversendingreply-method.md)|Notifies the profiler that the process has finished processing a remote method invocation request and is about to transmit the reply through a channel.| +|[RootReferences Method](icorprofilercallback-rootreferences-method.md)|Notifies the profiler with information about root references after garbage collection.| +|[RuntimeResumeFinished Method](icorprofilercallback-runtimeresumefinished-method.md)|Notifies the profiler that the runtime has resumed all runtime threads and has returned to normal operation.| +|[RuntimeResumeStarted Method](icorprofilercallback-runtimeresumestarted-method.md)|Notifies the profiler that the runtime is resuming all runtime threads.| +|[RuntimeSuspendAborted Method](icorprofilercallback-runtimesuspendaborted-method.md)|Notifies the profiler that the runtime has aborted the runtime suspension that was occurring.| +|[RuntimeSuspendFinished Method](icorprofilercallback-runtimesuspendfinished-method.md)|Notifies the profiler that the runtime has completed suspension of all runtime threads.| +|[RuntimeSuspendStarted Method](icorprofilercallback-runtimesuspendstarted-method.md)|Notifies the profiler that the runtime is about to suspend all runtime threads.| +|[RuntimeThreadResumed Method](icorprofilercallback-runtimethreadresumed-method.md)|Notifies the profiler that the specified thread has resumed after being suspended.| +|[RuntimeThreadSuspended Method](icorprofilercallback-runtimethreadsuspended-method.md)|Notifies the profiler that the specified thread has been, or is about to be, suspended.| +|[Shutdown Method](icorprofilercallback-shutdown-method.md)|Notifies the profiler that the application is shutting down.| +|[ThreadAssignedToOSThread Method](icorprofilercallback-threadassignedtoosthread-method.md)|Notifies the profiler that a managed thread is being implemented using a particular operating system (OS) thread.| +|[ThreadCreated Method](icorprofilercallback-threadcreated-method.md)|Notifies the profiler that a thread has been created.| +|[ThreadDestroyed Method](icorprofilercallback-threaddestroyed-method.md)|Notifies the profiler that a thread has been destroyed.| +|[UnmanagedToManagedTransition Method](icorprofilercallback-unmanagedtomanagedtransition-method.md)|Notifies the profiler that a transition from unmanaged code to managed code has occurred.| + +## Remarks + + The CLR calls a method in the `ICorProfilerCallback` (or [ICorProfilerCallback2](icorprofilercallback2-interface.md)) interface to notify the profiler when an event, to which the profiler has subscribed, occurs. This is the primary callback interface through which the CLR communicates with the code profiler. + + A code profiler must implement the methods of the `ICorProfilerCallback` interface. For the .NET Framework version 2.0 or later, the profiler must also implement the `ICorProfilerCallback2` methods. Each method implementation must return an HRESULT that has a value of S_OK on success or E_FAIL on failure. Currently, the CLR ignores the HRESULT that is returned by each callback except [ICorProfilerCallback::ObjectReferences](icorprofilercallback-objectreferences-method.md). + + In the Microsoft Windows registry, a code profiler must register its Component Object Model (COM) object that implements the `ICorProfilerCallback` and `ICorProfilerCallback2` interfaces. A code profiler subscribes to the events for which it wants to receive notification by calling [ICorProfilerInfo::SetEventMask](icorprofilerinfo-seteventmask-method.md). This is usually done in the profiler's implementation of [ICorProfilerCallback::Initialize](icorprofilercallback-initialize-method.md). The profiler is then able to receive notification from the runtime when an event is about to occur or has just occurred in an executing runtime process. - The CLR calls a method in the `ICorProfilerCallback` (or [ICorProfilerCallback2](icorprofilercallback2-interface.md)) interface to notify the profiler when an event, to which the profiler has subscribed, occurs. This is the primary callback interface through which the CLR communicates with the code profiler. - - A code profiler must implement the methods of the `ICorProfilerCallback` interface. For the .NET Framework version 2.0 or later, the profiler must also implement the `ICorProfilerCallback2` methods. Each method implementation must return an HRESULT that has a value of S_OK on success or E_FAIL on failure. Currently, the CLR ignores the HRESULT that is returned by each callback except [ICorProfilerCallback::ObjectReferences](icorprofilercallback-objectreferences-method.md). - - In the Microsoft Windows registry, a code profiler must register its Component Object Model (COM) object that implements the `ICorProfilerCallback` and `ICorProfilerCallback2` interfaces. A code profiler subscribes to the events for which it wants to receive notification by calling [ICorProfilerInfo::SetEventMask](icorprofilerinfo-seteventmask-method.md). This is usually done in the profiler's implementation of [ICorProfilerCallback::Initialize](icorprofilercallback-initialize-method.md). The profiler is then able to receive notification from the runtime when an event is about to occur or has just occurred in an executing runtime process. - > [!NOTE] -> The profiler registers a single COM object. If the profiler is targeting the .NET Framework version 1.0 or 1.1, that COM object needs to implement only the methods of `ICorProfilerCallback`. If it is targeting .NET Framework version 2.0 or later, the COM object must also implement the methods of `ICorProfilerCallback2`. - -## Requirements +> The profiler registers a single COM object. If the profiler is targeting the .NET Framework version 1.0 or 1.1, that COM object needs to implement only the methods of `ICorProfilerCallback`. If it is targeting .NET Framework version 2.0 or later, the COM object must also implement the methods of `ICorProfilerCallback2`. + +## Requirements + + **Platforms:** See [System Requirements](../../get-started/system-requirements.md). + + **Header:** CorProf.idl, CorProf.h + + **Library:** CorGuids.lib + + **.NET Framework Versions:** [!INCLUDE[net_current_v10plus](../../../../includes/net-current-v10plus-md.md)] - **Platforms:** See [System Requirements](../../get-started/system-requirements.md). - - **Header:** CorProf.idl, CorProf.h - - **Library:** CorGuids.lib - - **.NET Framework Versions:** [!INCLUDE[net_current_v10plus](../../../../includes/net-current-v10plus-md.md)] - ## See also - [Profiling Interfaces](profiling-interfaces.md) diff --git a/docs/framework/unmanaged-api/profiling/icorprofilercallback-runtimeresumestarted-method.md b/docs/framework/unmanaged-api/profiling/icorprofilercallback-runtimeresumestarted-method.md index 57df80f285aa0..05e4dfadafd74 100644 --- a/docs/framework/unmanaged-api/profiling/icorprofilercallback-runtimeresumestarted-method.md +++ b/docs/framework/unmanaged-api/profiling/icorprofilercallback-runtimeresumestarted-method.md @@ -2,41 +2,41 @@ description: "Learn more about: ICorProfilerCallback::RuntimeResumeStarted Method" title: "ICorProfilerCallback::RuntimeResumeStarted Method" ms.date: "03/30/2017" -api_name: +api_name: - "ICorProfilerCallback.RuntimeResumeStarted" -api_location: +api_location: - "mscorwks.dll" -api_type: +api_type: - "COM" -f1_keywords: +f1_keywords: - "ICorProfilerCallback::RuntimeResumeStarted" -helpviewer_keywords: +helpviewer_keywords: - "ICorProfilerCallback::RuntimeResumeStarted method [.NET Framework profiling]" - "RuntimeResumeStarted method [.NET Framework profiling]" ms.assetid: 5854bfb2-c568-4f19-904a-7c9d41e7b995 -topic_type: +topic_type: - "apiref" --- # ICorProfilerCallback::RuntimeResumeStarted Method -Notifies the profiler that the runtime is resuming all run-time threads. - -## Syntax - -```cpp -HRESULT RuntimeResumeStarted(); -``` - -## Requirements - - **Platforms:** See [System Requirements](../../get-started/system-requirements.md). - - **Header:** CorProf.idl, CorProf.h - - **Library:** CorGuids.lib - - **.NET Framework Versions:** [!INCLUDE[net_current_v20plus](../../../../includes/net-current-v20plus-md.md)] - +Notifies the profiler that the runtime is resuming all runtime threads. + +## Syntax + +```cpp +HRESULT RuntimeResumeStarted(); +``` + +## Requirements + + **Platforms:** See [System Requirements](../../get-started/system-requirements.md). + + **Header:** CorProf.idl, CorProf.h + + **Library:** CorGuids.lib + + **.NET Framework Versions:** [!INCLUDE[net_current_v20plus](../../../../includes/net-current-v20plus-md.md)] + ## See also - [ICorProfilerCallback Interface](icorprofilercallback-interface.md) diff --git a/docs/framework/unmanaged-api/profiling/icorprofilercallback-runtimesuspendaborted-method.md b/docs/framework/unmanaged-api/profiling/icorprofilercallback-runtimesuspendaborted-method.md index 18f7732f48334..b01268121565a 100644 --- a/docs/framework/unmanaged-api/profiling/icorprofilercallback-runtimesuspendaborted-method.md +++ b/docs/framework/unmanaged-api/profiling/icorprofilercallback-runtimesuspendaborted-method.md @@ -2,49 +2,49 @@ description: "Learn more about: ICorProfilerCallback::RuntimeSuspendAborted Method" title: "ICorProfilerCallback::RuntimeSuspendAborted Method" ms.date: "03/30/2017" -api_name: +api_name: - "ICorProfilerCallback.RuntimeSuspendAborted" -api_location: +api_location: - "mscorwks.dll" -api_type: +api_type: - "COM" -f1_keywords: +f1_keywords: - "ICorProfilerCallback::RuntimeSuspendAborted" -helpviewer_keywords: +helpviewer_keywords: - "ICorProfilerCallback::RuntimeSuspendAborted method [.NET Framework profiling]" - "RuntimeSuspendAborted method [.NET Framework profiling]" ms.assetid: 5a8a4277-345b-448b-a028-fc8cff9998aa -topic_type: +topic_type: - "apiref" --- # ICorProfilerCallback::RuntimeSuspendAborted Method -Notifies the profiler that the runtime has aborted the runtime suspension that was occurring. - -## Syntax - -```cpp -HRESULT RuntimeSuspendAborted(); -``` - -## Remarks - - The run-time suspension might be aborted if two threads simultaneously attempt to suspend the runtime. - - Either the [ICorProfilerCallback::RuntimeSuspendFinished](icorprofilercallback-runtimesuspendfinished-method.md) callback or the `RuntimeSuspendAborted` callback will occur on a single thread following a [ICorProfilerCallback::RuntimeSuspendStarted](icorprofilercallback-runtimesuspendstarted-method.md) callback. - - The `RuntimeSuspendAborted` callback is guaranteed to occur on the same thread as the `RuntimeSuspendStarted` callback. - -## Requirements - - **Platforms:** See [System Requirements](../../get-started/system-requirements.md). - - **Header:** CorProf.idl, CorProf.h - - **Library:** CorGuids.lib - - **.NET Framework Versions:** [!INCLUDE[net_current_v20plus](../../../../includes/net-current-v20plus-md.md)] - +Notifies the profiler that the runtime has aborted the runtime suspension that was occurring. + +## Syntax + +```cpp +HRESULT RuntimeSuspendAborted(); +``` + +## Remarks + + The runtime suspension might be aborted if two threads simultaneously attempt to suspend the runtime. + + Either the [ICorProfilerCallback::RuntimeSuspendFinished](icorprofilercallback-runtimesuspendfinished-method.md) callback or the `RuntimeSuspendAborted` callback will occur on a single thread following a [ICorProfilerCallback::RuntimeSuspendStarted](icorprofilercallback-runtimesuspendstarted-method.md) callback. + + The `RuntimeSuspendAborted` callback is guaranteed to occur on the same thread as the `RuntimeSuspendStarted` callback. + +## Requirements + + **Platforms:** See [System Requirements](../../get-started/system-requirements.md). + + **Header:** CorProf.idl, CorProf.h + + **Library:** CorGuids.lib + + **.NET Framework Versions:** [!INCLUDE[net_current_v20plus](../../../../includes/net-current-v20plus-md.md)] + ## See also - [ICorProfilerCallback Interface](icorprofilercallback-interface.md) diff --git a/docs/framework/unmanaged-api/profiling/profiling-overview.md b/docs/framework/unmanaged-api/profiling/profiling-overview.md index 38f91aa7b0e24..20b85ea6f418f 100644 --- a/docs/framework/unmanaged-api/profiling/profiling-overview.md +++ b/docs/framework/unmanaged-api/profiling/profiling-overview.md @@ -31,13 +31,13 @@ ms.assetid: 864c2344-71dc-46f9-96b2-ed59fb6427a8 --- # Profiling Overview -A profiler is a tool that monitors the execution of another application. A common language runtime (CLR) profiler is a dynamic link library (DLL) that consists of functions that receive messages from, and send messages to, the CLR by using the profiling API. The profiler DLL is loaded by the CLR at run time. +A profiler is a tool that monitors the execution of another application. A common language runtime (CLR) profiler is a dynamic link library (DLL) that consists of functions that receive messages from, and send messages to, the CLR by using the profiling API. The profiler DLL is loaded by the CLR at runtime. Traditional profiling tools focus on measuring the execution of the application. That is, they measure the time that is spent in each function or the memory usage of the application over time. The profiling API targets a broader class of diagnostic tools such as code-coverage utilities and even advanced debugging aids. These uses are all diagnostic in nature. The profiling API not only measures but also monitors the execution of an application. For this reason, the profiling API should never be used by the application itself, and the application’s execution should not depend on (or be affected by) the profiler. Profiling a CLR application requires more support than profiling conventionally compiled machine code. This is because the CLR introduces concepts such as application domains, garbage collection, managed exception handling, just-in-time (JIT) compilation of code (converting common intermediate language, or CIL, code into native machine code), and similar features. Conventional profiling mechanisms cannot identify or provide useful information about these features. The profiling API provides this missing information efficiently, with minimal effect on the performance of the CLR and the profiled application. -JIT compilation at run time provides good opportunities for profiling. The profiling API enables a profiler to change the in-memory CIL code stream for a routine before it is JIT-compiled. In this manner, the profiler can dynamically add instrumentation code to particular routines that need deeper investigation. Although this approach is possible in conventional scenarios, it is much easier to implement for the CLR by using the profiling API. +JIT compilation at runtime provides good opportunities for profiling. The profiling API enables a profiler to change the in-memory CIL code stream for a routine before it is JIT-compiled. In this manner, the profiler can dynamically add instrumentation code to particular routines that need deeper investigation. Although this approach is possible in conventional scenarios, it is much easier to implement for the CLR by using the profiling API. ## The Profiling API @@ -114,7 +114,7 @@ The profiling API does not support the following functionality: - Remote profiling, which is not supported for the following reasons: - - Remote profiling extends execution time. When you use the profiling interfaces, you must minimize execution time so that profiling results will not be unduly affected. This is especially true when execution performance is being monitored. However, remote profiling is not a limitation when the profiling interfaces are used to monitor memory usage or to obtain run-time information about stack frames, objects, and so on. + - Remote profiling extends execution time. When you use the profiling interfaces, you must minimize execution time so that profiling results will not be unduly affected. This is especially true when execution performance is being monitored. However, remote profiling is not a limitation when the profiling interfaces are used to monitor memory usage or to obtain runtime information about stack frames, objects, and so on. - The CLR code profiler must register one or more callback interfaces with the runtime on the local computer on which the profiled application is running. This limits the ability to create a remote code profiler. diff --git a/docs/framework/wcf/configuring-bindings-for-wcf-services.md b/docs/framework/wcf/configuring-bindings-for-wcf-services.md index 8e69a1efd05d2..bb17118dd41bf 100644 --- a/docs/framework/wcf/configuring-bindings-for-wcf-services.md +++ b/docs/framework/wcf/configuring-bindings-for-wcf-services.md @@ -2,167 +2,167 @@ title: "Configuring Bindings for Windows Communication Foundation Services" description: Learn about configuring bindings at deployment time for a WCF application by editing items under the system.ServiceModel element. ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "binding configuration [WCF]" ms.assetid: 99a85fd8-f7eb-4a84-a93e-7721b37d415c --- # Configuring Bindings for Windows Communication Foundation Services -When creating an application, you often want to defer decisions to the administrator after the deployment of the application. For example, there is often no way of knowing in advance what a service address, or Uniform Resource Identifier (URI), will be. Instead of hard-coding an address, it is preferable to allow an administrator to do so after creating a service. This flexibility is accomplished through configuration. - +When creating an application, you often want to defer decisions to the administrator after the deployment of the application. For example, there is often no way of knowing in advance what a service address, or Uniform Resource Identifier (URI), will be. Instead of hard-coding an address, it is preferable to allow an administrator to do so after creating a service. This flexibility is accomplished through configuration. + > [!NOTE] -> Use the [ServiceModel Metadata Utility Tool (Svcutil.exe)](servicemodel-metadata-utility-tool-svcutil-exe.md) with the `/config` switch to quickly create configuration files. - -## Major Sections - - The Windows Communication Foundation (WCF) configuration scheme includes the following three major sections (`serviceModel`, `bindings`, and `services`): - -```xml - - - - - - - - - - -``` - -### ServiceModel Elements - - You can use the section bounded by the `system.ServiceModel` element to configure a service type with one or more endpoints, as well as settings for a service. Each endpoint can then be configured with an address, a contract, and a binding. For more information about endpoints, see [Endpoint Creation Overview](endpoint-creation-overview.md). If no endpoints are specified, the runtime adds default endpoints. For more information about default endpoints, bindings, and behaviors, see [Simplified Configuration](simplified-configuration.md) and [Simplified Configuration for WCF Services](./samples/simplified-configuration-for-wcf-services.md). - - A binding specifies transports (HTTP, TCP, pipes, Message Queuing) and protocols (Security, Reliability, Transaction flows) and consists of binding elements, each of which specifies an aspect of how an endpoint communicates with the world. - - For example, specifying the [\](../configure-apps/file-schema/wcf/basichttpbinding.md) element indicates to use HTTP as the transport for an endpoint. This is used to wire up the endpoint at run time when the service using this endpoint is opened. - - There are two kinds of bindings: predefined and custom. Predefined bindings contain useful combinations of elements that are used in common scenarios. For a list of predefined binding types that WCF provides, see [System-Provided Bindings](system-provided-bindings.md). If no predefined binding collection has the correct combination of features that a service application needs, you can construct custom bindings to meet the application's requirements. For more information about custom bindings, see [\](../configure-apps/file-schema/wcf/custombinding.md). - - The following four examples illustrate the most common binding configurations used for setting up a WCF service. - -#### Specifying an Endpoint to Use a Binding Type - - The first example illustrates how to specify an endpoint configured with an address, a contract, and a binding. - -```xml - - +> Use the [ServiceModel Metadata Utility Tool (Svcutil.exe)](servicemodel-metadata-utility-tool-svcutil-exe.md) with the `/config` switch to quickly create configuration files. + +## Major Sections + + The Windows Communication Foundation (WCF) configuration scheme includes the following three major sections (`serviceModel`, `bindings`, and `services`): + +```xml + + + + + + + + + + +``` + +### ServiceModel Elements + + You can use the section bounded by the `system.ServiceModel` element to configure a service type with one or more endpoints, as well as settings for a service. Each endpoint can then be configured with an address, a contract, and a binding. For more information about endpoints, see [Endpoint Creation Overview](endpoint-creation-overview.md). If no endpoints are specified, the runtime adds default endpoints. For more information about default endpoints, bindings, and behaviors, see [Simplified Configuration](simplified-configuration.md) and [Simplified Configuration for WCF Services](./samples/simplified-configuration-for-wcf-services.md). + + A binding specifies transports (HTTP, TCP, pipes, Message Queuing) and protocols (Security, Reliability, Transaction flows) and consists of binding elements, each of which specifies an aspect of how an endpoint communicates with the world. + + For example, specifying the [\](../configure-apps/file-schema/wcf/basichttpbinding.md) element indicates to use HTTP as the transport for an endpoint. This is used to wire up the endpoint at runtime when the service using this endpoint is opened. + + There are two kinds of bindings: predefined and custom. Predefined bindings contain useful combinations of elements that are used in common scenarios. For a list of predefined binding types that WCF provides, see [System-Provided Bindings](system-provided-bindings.md). If no predefined binding collection has the correct combination of features that a service application needs, you can construct custom bindings to meet the application's requirements. For more information about custom bindings, see [\](../configure-apps/file-schema/wcf/custombinding.md). + + The following four examples illustrate the most common binding configurations used for setting up a WCF service. + +#### Specifying an Endpoint to Use a Binding Type + + The first example illustrates how to specify an endpoint configured with an address, a contract, and a binding. + +```xml + + - -``` - - In this example, the `name` attribute indicates which service type the configuration is for. When you create a service in your code with the `HelloWorld` contract, it is initialized with all of the endpoints defined in the example configuration. If the assembly implements only one service contract, the `name` attribute can be omitted because the service uses the only available type. The attribute takes a string, which must be in the format `Namespace.Class, AssemblyName, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null` - - The `address` attribute specifies the URI that other endpoints use to communicate to the service. The URI can be either an absolute or relative path. If a relative address is provided, the host is expected to provide a base address that is appropriate for the transport scheme used in the binding. If an address is not configured, the base address is assumed to be the address for that endpoint. - - The `contract` attribute specifies the contract this endpoint is exposing. The service implementation type must implement the contract type. If a service implementation implements a single contract type, then this property can be omitted. - - The `binding` attribute selects a predefined or custom binding to use for this specific endpoint. An endpoint that does not explicitly select a binding uses the default binding selection, which is `BasicHttpBinding`. - -#### Modifying a Predefined Binding - - In the following example, a predefined binding is modified. It can then be used to configure any endpoint in the service. The binding is modified by setting the value to 1 second. Note that the property returns a object. - - That altered binding is found in the bindings section. This altered binding can now be used when creating any endpoint by setting the `binding` attribute in the `endpoint` element. - + +``` + + In this example, the `name` attribute indicates which service type the configuration is for. When you create a service in your code with the `HelloWorld` contract, it is initialized with all of the endpoints defined in the example configuration. If the assembly implements only one service contract, the `name` attribute can be omitted because the service uses the only available type. The attribute takes a string, which must be in the format `Namespace.Class, AssemblyName, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null` + + The `address` attribute specifies the URI that other endpoints use to communicate to the service. The URI can be either an absolute or relative path. If a relative address is provided, the host is expected to provide a base address that is appropriate for the transport scheme used in the binding. If an address is not configured, the base address is assumed to be the address for that endpoint. + + The `contract` attribute specifies the contract this endpoint is exposing. The service implementation type must implement the contract type. If a service implementation implements a single contract type, then this property can be omitted. + + The `binding` attribute selects a predefined or custom binding to use for this specific endpoint. An endpoint that does not explicitly select a binding uses the default binding selection, which is `BasicHttpBinding`. + +#### Modifying a Predefined Binding + + In the following example, a predefined binding is modified. It can then be used to configure any endpoint in the service. The binding is modified by setting the value to 1 second. Note that the property returns a object. + + That altered binding is found in the bindings section. This altered binding can now be used when creating any endpoint by setting the `binding` attribute in the `endpoint` element. + > [!NOTE] -> If you give a particular name to the binding, the `bindingConfiguration` specified in the service endpoint must match with it. - -```xml - +> If you give a particular name to the binding, the `bindingConfiguration` specified in the service endpoint must match with it. + +```xml + - - + + - -``` - -## Configuring a Behavior to Apply to a Service - - In the following example, a specific behavior is configured for the service type. The `ServiceMetadataBehavior` element is used to enable the [ServiceModel Metadata Utility Tool (Svcutil.exe)](servicemodel-metadata-utility-tool-svcutil-exe.md) to query the service and generate Web Services Description Language (WSDL) documents from the metadata. - + receiveTimeout="00:00:01" + /> + +``` + +## Configuring a Behavior to Apply to a Service + + In the following example, a specific behavior is configured for the service type. The `ServiceMetadataBehavior` element is used to enable the [ServiceModel Metadata Utility Tool (Svcutil.exe)](servicemodel-metadata-utility-tool-svcutil-exe.md) to query the service and generate Web Services Description Language (WSDL) documents from the metadata. + > [!NOTE] -> If you give a particular name to the behavior, the `behaviorConfiguration` specified in the service or endpoint section must match it. - -```xml - - +> If you give a particular name to the behavior, the `behaviorConfiguration` specified in the service or endpoint section must match it. + +```xml + + - - - + + + - - -``` - - The preceding configuration enables a client to call and get the metadata of the "HelloWorld" typed service. - - `svcutil /config:Client.exe.config http://computer:8080/Hello?wsdl` - -## Specifying a Service with Two Endpoints Using Different Binding Values - - In this last example, two endpoints are configured for the `HelloWorld` service type. Each endpoint uses a different customized `bindingConfiguration` attribute of the same binding type (each modifies the `basicHttpBinding`). - -```xml - - + +``` + + The preceding configuration enables a client to call and get the metadata of the "HelloWorld" typed service. + + `svcutil /config:Client.exe.config http://computer:8080/Hello?wsdl` + +## Specifying a Service with Two Endpoints Using Different Binding Values + + In this last example, two endpoints are configured for the `HelloWorld` service type. Each endpoint uses a different customized `bindingConfiguration` attribute of the same binding type (each modifies the `basicHttpBinding`). + +```xml + + - - - + + + /> - + name="Secure"> + - -``` - - You can get the same behavior using the default configuration by adding a `protocolMapping` section and configuring the bindings as demonstrated in the following example. - -```xml - - - - - + +``` + + You can get the same behavior using the default configuration by adding a `protocolMapping` section and configuring the bindings as demonstrated in the following example. + +```xml + + + + + + /> - - -``` - + name="Secure" /> + + +``` + ## See also - [Simplified Configuration](simplified-configuration.md) diff --git a/docs/framework/wcf/controlling-resource-consumption-and-improving-performance.md b/docs/framework/wcf/controlling-resource-consumption-and-improving-performance.md index b5e6dc0d90d7e..1b12afc72dca3 100644 --- a/docs/framework/wcf/controlling-resource-consumption-and-improving-performance.md +++ b/docs/framework/wcf/controlling-resource-consumption-and-improving-performance.md @@ -29,13 +29,13 @@ This topic describes various properties in different areas of the Windows Commun Typically, when writing the application and debugging it, you set the property to `true` in the configuration file or programmatically. This instructs WCF to return service exception stack traces to the client application for viewing. This feature reports most application-level exceptions in such a way as to display which quota settings might be involved, if that is the problem. - Some exceptions happen at run time below the visibility of the application layer and are not returned using this mechanism, and they might not be handled by a custom implementation. If you are in a development environment like Microsoft Visual Studio, most of these exceptions are displayed automatically. However, some exceptions can be masked by development environment settings such as [Just My Code](/visualstudio/debugger/just-my-code) Visual Studio. + Some exceptions happen at runtime below the visibility of the application layer and are not returned using this mechanism, and they might not be handled by a custom implementation. If you are in a development environment like Microsoft Visual Studio, most of these exceptions are displayed automatically. However, some exceptions can be masked by development environment settings such as [Just My Code](/visualstudio/debugger/just-my-code) Visual Studio. Regardless of the capabilities of your development environment, you can use capabilities of WCF tracing and message logging to debug all exceptions and tune the performance of your applications. For more information, see [Using Tracing to Troubleshoot Your Application](./diagnostics/tracing/using-tracing-to-troubleshoot-your-application.md). ## Performance Issues and XmlSerializer - Services and client applications that use data types that are serializable using the generate and compile serialization code for those data types at run time, which can result in slow start-up performance. + Services and client applications that use data types that are serializable using the generate and compile serialization code for those data types at runtime, which can result in slow start-up performance. > [!NOTE] > Pre-generated serialization code can be used only in client applications and not in services. diff --git a/docs/framework/wcf/designing-and-implementing-services.md b/docs/framework/wcf/designing-and-implementing-services.md index e5129241f6d1e..7bf3d91c64ed7 100644 --- a/docs/framework/wcf/designing-and-implementing-services.md +++ b/docs/framework/wcf/designing-and-implementing-services.md @@ -2,70 +2,70 @@ description: "Learn more about: Designing and Implementing Services" title: "Designing and Implementing Services" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "defining service contracts [WCF]" ms.assetid: 036fae20-7c55-4002-b71d-ac4466e167a3 --- # Designing and Implementing Services -This section shows you how to define and implement WCF contracts. A service contract specifies what an endpoint communicates to the outside world. At a more concrete level, it is a statement about a set of specific messages organized into basic message exchange patterns (MEPs), such as request/reply, one-way, and duplex. If a service contract is a logically related set of message exchanges, a service operation is a single message exchange. For example, a `Hello` operation must obviously accept one message (so the caller can announce the greeting) and may or may not return a message (depending upon the courtesy of the operation). - - For more information about contracts and other core Windows Communication Foundation (WCF) concepts, see [Fundamental Windows Communication Foundation Concepts](fundamental-concepts.md). This topic focuses on understanding service contracts. For more information about how to build clients that use service contracts to connect to services, see [WCF Client Overview](wcf-client-overview.md). - -## Overview - - This topic provides a high level conceptual orientation to designing and implementing WCF services. Subtopics provide more detailed information about the specifics of design and implementation. Before designing and implementing your WCF application, it is recommended that you: - -- Understand what a service contract is, how it works, and how to create one. - -- Understand that contracts state minimum requirements that runtime configuration or the hosting environment may not support. - -## Service Contracts - - A service contract specifies the following: - -- The operations a contract exposes. - -- The signature of the operations in terms of messages exchanged. - -- The data types of these messages. - -- The location of the operations. - -- The specific protocols and serialization formats that are used to support successful communication with the service. - - For example, a purchase order contract might have a `CreateOrder` operation that accepts an input of order information types and returns success or failure information, including an order identifier. It might also have a `GetOrderStatus` operation that accepts an order identifier and returns order status information. A service contract of this sort would specify: - -1. That the purchase order contract consisted of `CreateOrder` and `GetOrderStatus` operations. - -2. That the operations have specified input messages and output messages. - -3. The data that these messages can carry. - -4. Categorical statements about the communication infrastructure necessary to successfully process the messages. For example, these details include whether and what forms of security are required to establish successful communication. - - To convey this kind of information to other applications on many platforms (including non-Microsoft platforms), XML service contracts are publicly expressed in standard XML formats, such as [Web Services Description Language](https://www.w3.org/TR/2001/NOTE-wsdl-20010315) (WSDL) and [XML Schema](https://www.w3.org/XML/Schema) (XSD), among others. Developers for many platforms can use this public contract information to create applications that can communicate with the service, both because they understand the language of the specification and because those languages are designed to enable interoperation by describing the public forms, formats, and protocols that the service supports. For more information about how WCF handles this kind of information, see [Metadata](./feature-details/metadata.md). - - Contracts can be expressed many ways, and while WSDL and XSD are excellent languages to describe services in an accessible way, they are difficult languages to use directly and are merely descriptions of a service, not service contract implementations. Therefore, WCF applications use managed attributes, interfaces, and classes both to define the structure of a service and to implement it. - - The resulting contract defined in managed types can be *exported* as metadata—WSDL and XSD—when needed by clients or other service implementers. The result is a straightforward programming model that can be described (using public metadata) to any client application. The details of the underlying SOAP messages, the transportation and security-related information, and so on, can be left to WCF, which performs the necessary conversions to and from the service contract type system to the XML type system automatically. - - For more information about designing contracts, see [Designing Service Contracts](designing-service-contracts.md). For more information about implementing contracts, see [Implementing Service Contracts](implementing-service-contracts.md). - -### Messages Up Front and Center - - Using managed interfaces, classes, and methods to model service operations is straightforward when you are used to remote procedure call (RPC)-style method signatures, in which passing parameters into a method and receiving return values is the normal form of requesting functionality from an object or other type of code. For example, programmers using managed languages such as Visual Basic and C++ COM can apply their knowledge of the RPC-style approach (whether using objects or interfaces) to the creation of WCF service contracts without experiencing the problems inherent in RPC-style distributed object systems. Service orientation provides the benefits of loosely coupled, message-oriented programming while retaining the ease and familiarity of the RPC programming experience. - - Many programmers are more comfortable with message-oriented application programming interfaces, such as message queues like Microsoft MSMQ, the namespaces in the .NET Framework, or sending unstructured XML in HTTP requests, to name a few. For more information about programming at the message level, see [Using Message Contracts](./feature-details/using-message-contracts.md), [Service Channel-Level Programming](./extending/service-channel-level-programming.md), and [Interoperability with POX Applications](./feature-details/interoperability-with-pox-applications.md). - -### Understanding the Hierarchy of Requirements - - A service contract groups the operations; specifies the message exchange pattern, message types, and data types those messages carry; and indicates categories of run-time behavior an implementation must have to support the contract (for example, it may require that messages be encrypted and signed). The service contract itself does not specify precisely how these requirements are met, only that they must be. The type of encryption or the manner in which a message is signed is up to the implementation and configuration of a compliant service. - - Notice the way that the contract requires certain things of the service contract implementation and the run-time configuration to add behavior. The set of requirements that must be met to expose a service for use builds on the preceding set of requirements. If a contract makes requirements of the implementation, an implementation can require yet more of the configuration and bindings that enable the service to run. Finally, the host application must also support any requirements that the service configuration and bindings add. - - This additive requirement process is important to keep in mind while designing, implementing, configuring, and hosting a Windows Communication Foundation (WCF) service application. For example, the contract can specify that it needs to support a session. If so, then you must configure the binding to support that contractual requirement, or the service implementation will not work. Or if your service requires Windows Integrated Authentication and is hosted in Internet Information Services (IIS), the Web application in which the service resides must have Windows Integrated Authentication turned on and anonymous support turned off. For more information about the features and impact of the different service host application types, see [Hosting Services](hosting-services.md). - +This section shows you how to define and implement WCF contracts. A service contract specifies what an endpoint communicates to the outside world. At a more concrete level, it is a statement about a set of specific messages organized into basic message exchange patterns (MEPs), such as request/reply, one-way, and duplex. If a service contract is a logically related set of message exchanges, a service operation is a single message exchange. For example, a `Hello` operation must obviously accept one message (so the caller can announce the greeting) and may or may not return a message (depending upon the courtesy of the operation). + + For more information about contracts and other core Windows Communication Foundation (WCF) concepts, see [Fundamental Windows Communication Foundation Concepts](fundamental-concepts.md). This topic focuses on understanding service contracts. For more information about how to build clients that use service contracts to connect to services, see [WCF Client Overview](wcf-client-overview.md). + +## Overview + + This topic provides a high level conceptual orientation to designing and implementing WCF services. Subtopics provide more detailed information about the specifics of design and implementation. Before designing and implementing your WCF application, it is recommended that you: + +- Understand what a service contract is, how it works, and how to create one. + +- Understand that contracts state minimum requirements that runtime configuration or the hosting environment may not support. + +## Service Contracts + + A service contract specifies the following: + +- The operations a contract exposes. + +- The signature of the operations in terms of messages exchanged. + +- The data types of these messages. + +- The location of the operations. + +- The specific protocols and serialization formats that are used to support successful communication with the service. + + For example, a purchase order contract might have a `CreateOrder` operation that accepts an input of order information types and returns success or failure information, including an order identifier. It might also have a `GetOrderStatus` operation that accepts an order identifier and returns order status information. A service contract of this sort would specify: + +1. That the purchase order contract consisted of `CreateOrder` and `GetOrderStatus` operations. + +2. That the operations have specified input messages and output messages. + +3. The data that these messages can carry. + +4. Categorical statements about the communication infrastructure necessary to successfully process the messages. For example, these details include whether and what forms of security are required to establish successful communication. + + To convey this kind of information to other applications on many platforms (including non-Microsoft platforms), XML service contracts are publicly expressed in standard XML formats, such as [Web Services Description Language](https://www.w3.org/TR/2001/NOTE-wsdl-20010315) (WSDL) and [XML Schema](https://www.w3.org/XML/Schema) (XSD), among others. Developers for many platforms can use this public contract information to create applications that can communicate with the service, both because they understand the language of the specification and because those languages are designed to enable interoperation by describing the public forms, formats, and protocols that the service supports. For more information about how WCF handles this kind of information, see [Metadata](./feature-details/metadata.md). + + Contracts can be expressed many ways, and while WSDL and XSD are excellent languages to describe services in an accessible way, they are difficult languages to use directly and are merely descriptions of a service, not service contract implementations. Therefore, WCF applications use managed attributes, interfaces, and classes both to define the structure of a service and to implement it. + + The resulting contract defined in managed types can be *exported* as metadata—WSDL and XSD—when needed by clients or other service implementers. The result is a straightforward programming model that can be described (using public metadata) to any client application. The details of the underlying SOAP messages, the transportation and security-related information, and so on, can be left to WCF, which performs the necessary conversions to and from the service contract type system to the XML type system automatically. + + For more information about designing contracts, see [Designing Service Contracts](designing-service-contracts.md). For more information about implementing contracts, see [Implementing Service Contracts](implementing-service-contracts.md). + +### Messages Up Front and Center + + Using managed interfaces, classes, and methods to model service operations is straightforward when you are used to remote procedure call (RPC)-style method signatures, in which passing parameters into a method and receiving return values is the normal form of requesting functionality from an object or other type of code. For example, programmers using managed languages such as Visual Basic and C++ COM can apply their knowledge of the RPC-style approach (whether using objects or interfaces) to the creation of WCF service contracts without experiencing the problems inherent in RPC-style distributed object systems. Service orientation provides the benefits of loosely coupled, message-oriented programming while retaining the ease and familiarity of the RPC programming experience. + + Many programmers are more comfortable with message-oriented application programming interfaces, such as message queues like Microsoft MSMQ, the namespaces in the .NET Framework, or sending unstructured XML in HTTP requests, to name a few. For more information about programming at the message level, see [Using Message Contracts](./feature-details/using-message-contracts.md), [Service Channel-Level Programming](./extending/service-channel-level-programming.md), and [Interoperability with POX Applications](./feature-details/interoperability-with-pox-applications.md). + +### Understanding the Hierarchy of Requirements + + A service contract groups the operations; specifies the message exchange pattern, message types, and data types those messages carry; and indicates categories of runtime behavior an implementation must have to support the contract (for example, it may require that messages be encrypted and signed). The service contract itself does not specify precisely how these requirements are met, only that they must be. The type of encryption or the manner in which a message is signed is up to the implementation and configuration of a compliant service. + + Notice the way that the contract requires certain things of the service contract implementation and the runtime configuration to add behavior. The set of requirements that must be met to expose a service for use builds on the preceding set of requirements. If a contract makes requirements of the implementation, an implementation can require yet more of the configuration and bindings that enable the service to run. Finally, the host application must also support any requirements that the service configuration and bindings add. + + This additive requirement process is important to keep in mind while designing, implementing, configuring, and hosting a Windows Communication Foundation (WCF) service application. For example, the contract can specify that it needs to support a session. If so, then you must configure the binding to support that contractual requirement, or the service implementation will not work. Or if your service requires Windows Integrated Authentication and is hosted in Internet Information Services (IIS), the Web application in which the service resides must have Windows Integrated Authentication turned on and anonymous support turned off. For more information about the features and impact of the different service host application types, see [Hosting Services](hosting-services.md). + ## See also - [Designing Service Contracts](designing-service-contracts.md) diff --git a/docs/framework/wcf/designing-service-contracts.md b/docs/framework/wcf/designing-service-contracts.md index cb69760f81131..ceb3ec97d2178 100644 --- a/docs/framework/wcf/designing-service-contracts.md +++ b/docs/framework/wcf/designing-service-contracts.md @@ -2,281 +2,281 @@ title: "Designing Service Contracts" description: Learn about service contracts, including how to create them, available operations and data types, and other aspects of service contracts in WCF programming. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" -helpviewer_keywords: +helpviewer_keywords: - "service contracts [WCF]" ms.assetid: 8e89cbb9-ac84-4f0d-85ef-0eb6be0022fd --- # Designing Service Contracts -This topic describes what service contracts are, how they are defined, what operations are available (and the implications for the underlying message exchanges), what data types are used, and other issues that help you design operations that satisfy the requirements of your scenario. - -## Creating a Service Contract - - Services expose a number of operations. In Windows Communication Foundation (WCF) applications, define the operations by creating a method and marking it with the attribute. Then, to create a service contract, group together your operations, either by declaring them within an interface marked with the attribute, or by defining them in a class marked with the same attribute. (For a basic example, see [How to: Define a Service Contract](how-to-define-a-wcf-service-contract.md).) - - Any methods that do not have a attribute are not service operations and are not exposed by WCF services. - - This topic describes the following decision points when designing a service contract: - -- Whether to use classes or interfaces. - -- How to specify the data types you want to exchange. - -- The types of exchange patterns you can use. - -- Whether you can make explicit security requirements part of the contract. - -- The restrictions for operation inputs and outputs. - -## Classes or Interfaces - - Both classes and interfaces represent a grouping of functionality and, therefore, both can be used to define a WCF service contract. However, it is recommended that you use interfaces because they directly model service contracts. Without an implementation, interfaces do no more than define a grouping of methods with certain signatures. Implement a service contract interface and you have implemented a WCF service. - - All the benefits of managed interfaces apply to service contract interfaces: - -- Service contract interfaces can extend any number of other service contract interfaces. - -- A single class can implement any number of service contracts by implementing those service contract interfaces. - -- You can modify the implementation of a service contract by changing the interface implementation, while the service contract remains the same. - -- You can version your service by implementing the old interface and the new one. Old clients connect to the original version, while newer clients can connect to the newer version. - +This topic describes what service contracts are, how they are defined, what operations are available (and the implications for the underlying message exchanges), what data types are used, and other issues that help you design operations that satisfy the requirements of your scenario. + +## Creating a Service Contract + + Services expose a number of operations. In Windows Communication Foundation (WCF) applications, define the operations by creating a method and marking it with the attribute. Then, to create a service contract, group together your operations, either by declaring them within an interface marked with the attribute, or by defining them in a class marked with the same attribute. (For a basic example, see [How to: Define a Service Contract](how-to-define-a-wcf-service-contract.md).) + + Any methods that do not have a attribute are not service operations and are not exposed by WCF services. + + This topic describes the following decision points when designing a service contract: + +- Whether to use classes or interfaces. + +- How to specify the data types you want to exchange. + +- The types of exchange patterns you can use. + +- Whether you can make explicit security requirements part of the contract. + +- The restrictions for operation inputs and outputs. + +## Classes or Interfaces + + Both classes and interfaces represent a grouping of functionality and, therefore, both can be used to define a WCF service contract. However, it is recommended that you use interfaces because they directly model service contracts. Without an implementation, interfaces do no more than define a grouping of methods with certain signatures. Implement a service contract interface and you have implemented a WCF service. + + All the benefits of managed interfaces apply to service contract interfaces: + +- Service contract interfaces can extend any number of other service contract interfaces. + +- A single class can implement any number of service contracts by implementing those service contract interfaces. + +- You can modify the implementation of a service contract by changing the interface implementation, while the service contract remains the same. + +- You can version your service by implementing the old interface and the new one. Old clients connect to the original version, while newer clients can connect to the newer version. + > [!NOTE] -> When inheriting from other service contract interfaces, you cannot override operation properties, such as the name or namespace. If you attempt to do so, you create a new operation in the current service contract. - - For an example of using an interface to create a service contract, see [How to: Create a Service with a Contract Interface](./feature-details/how-to-create-a-service-with-a-contract-interface.md). - - You can, however, use a class to define a service contract and implement that contract at the same time. The advantage of creating your services by applying and directly to the class and the methods on the class, respectively, is speed and simplicity. The disadvantages are that managed classes do not support multiple inheritance, and as a result they can only implement one service contract at a time. In addition, any modification to the class or method signatures modifies the public contract for that service, which can prevent unmodified clients from using your service. For more information, see [Implementing Service Contracts](implementing-service-contracts.md). - - For an example that uses a class to create a service contract and implements it at the same time, see [How to: Create a Service with a Contract Class](./feature-details/how-to-create-a-wcf-contract-with-a-class.md). - - At this point, you should understand the difference between defining your service contract by using an interface and by using a class. The next step is deciding what data can be passed back and forth between a service and its clients. - -## Parameters and Return Values - - Each operation has a return value and a parameter, even if these are `void`. However, unlike a local method, in which you can pass references to objects from one object to another, service operations do not pass references to objects. Instead, they pass copies of the objects. - - This is significant because each type used in a parameter or return value must be serializable; that is, it must be possible to convert an object of that type into a stream of bytes and from a stream of bytes into an object. - - Primitive types are serializable by default, as are many types in the .NET Framework. - +> When inheriting from other service contract interfaces, you cannot override operation properties, such as the name or namespace. If you attempt to do so, you create a new operation in the current service contract. + + For an example of using an interface to create a service contract, see [How to: Create a Service with a Contract Interface](./feature-details/how-to-create-a-service-with-a-contract-interface.md). + + You can, however, use a class to define a service contract and implement that contract at the same time. The advantage of creating your services by applying and directly to the class and the methods on the class, respectively, is speed and simplicity. The disadvantages are that managed classes do not support multiple inheritance, and as a result they can only implement one service contract at a time. In addition, any modification to the class or method signatures modifies the public contract for that service, which can prevent unmodified clients from using your service. For more information, see [Implementing Service Contracts](implementing-service-contracts.md). + + For an example that uses a class to create a service contract and implements it at the same time, see [How to: Create a Service with a Contract Class](./feature-details/how-to-create-a-wcf-contract-with-a-class.md). + + At this point, you should understand the difference between defining your service contract by using an interface and by using a class. The next step is deciding what data can be passed back and forth between a service and its clients. + +## Parameters and Return Values + + Each operation has a return value and a parameter, even if these are `void`. However, unlike a local method, in which you can pass references to objects from one object to another, service operations do not pass references to objects. Instead, they pass copies of the objects. + + This is significant because each type used in a parameter or return value must be serializable; that is, it must be possible to convert an object of that type into a stream of bytes and from a stream of bytes into an object. + + Primitive types are serializable by default, as are many types in the .NET Framework. + > [!NOTE] -> The value of the parameter names in the operation signature are part of the contract and are case sensitive. If you want to use the same parameter name locally but modify the name in the published metadata, see the . - -#### Data Contracts - - Service-oriented applications like Windows Communication Foundation (WCF) applications are designed to interoperate with the widest possible number of client applications on both Microsoft and non-Microsoft platforms. For the widest possible interoperability, it is recommended that you mark your types with the and attributes to create a data contract, which is the portion of the service contract that describes the data that your service operations exchange. - - Data contracts are opt-in style contracts: No type or data member is serialized unless you explicitly apply the data contract attribute. Data contracts are unrelated to the access scope of the managed code: Private data members can be serialized and sent elsewhere to be accessed publicly. (For a basic example of a data contract, see [How to: Create a Basic Data Contract for a Class or Structure](./feature-details/how-to-create-a-basic-data-contract-for-a-class-or-structure.md).) WCF handles the definition of the underlying SOAP messages that enable the operation's functionality as well as the serialization of your data types into and out of the body of the messages. As long as your data types are serializable, you do not need to think about the underlying message exchange infrastructure when designing your operations. - - Although the typical WCF application uses the and attributes to create data contracts for operations, you can use other serialization mechanisms. The standard , , and mechanisms all work to handle the serialization of your data types into the underlying SOAP messages that carry them from one application to another. You can employ more serialization strategies if your data types require special support. For more information about the choices for serialization of data types in WCF applications, see [Specifying Data Transfer in Service Contracts](./feature-details/specifying-data-transfer-in-service-contracts.md). - -#### Mapping Parameters and Return Values to Message Exchanges - - Service operations are supported by an underlying exchange of SOAP messages that transfer application data back and forth, in addition to the data required by the application to support certain standard security, transaction, and session-related features. Because this is the case, the signature of a service operation dictates a certain underlying *message exchange pattern* (MEP) that can support the data transfer and the features an operation requires. You can specify three patterns in the WCF programming model: request/reply, one-way, and duplex message patterns. - -##### Request/Reply - - A request/reply pattern is one in which a request sender (a client application) receives a reply with which the request is correlated. This is the default MEP because it supports an operation in which one or more parameters are passed to the operation and a return value is passed back to the caller. For example, the following C# code example shows a basic service operation that takes one string and returns a string. - -```csharp -[OperationContractAttribute] -string Hello(string greeting); -``` - - The following is the equivalent Visual Basic code. - -```vb - -Function Hello (ByVal greeting As String) As String -``` - - This operation signature dictates the form of underlying message exchange. If no correlation existed, WCF cannot determine for which operation the return value is intended. - - Note that unless you specify a different underlying message pattern, even service operations that return `void` (`Nothing` in Visual Basic) are request/reply message exchanges. The result for your operation is that unless a client invokes the operation asynchronously, the client stops processing until the return message is received, even though that message is empty in the normal case. The following C# code example shows an operation that does not return until the client has received an empty message in response. - -```csharp -[OperationContractAttribute] -void Hello(string greeting); -``` - - The following is the equivalent Visual Basic code. - -```vb - -Sub Hello (ByVal greeting As String) -``` - - The preceding example can slow client performance and responsiveness if the operation takes a long time to perform, but there are advantages to request/reply operations even when they return `void`. The most obvious one is that SOAP faults can be returned in the response message, which indicates that some service-related error condition has occurred, whether in communication or processing. SOAP faults that are specified in a service contract are passed to the client application as a object, where the type parameter is the type specified in the service contract. This makes notifying clients about error conditions in WCF services easy. For more information about exceptions, SOAP faults, and error handling, see [Specifying and Handling Faults in Contracts and Services](specifying-and-handling-faults-in-contracts-and-services.md). To see an example of a request/reply service and client, see [How to: Create a Request-Reply Contract](./feature-details/how-to-create-a-request-reply-contract.md). For more information about issues with the request-reply pattern, see [Request-Reply Services](./feature-details/request-reply-services.md). - -##### One-way - - If the client of a WCF service application should not wait for the operation to complete and does not process SOAP faults, the operation can specify a one-way message pattern. A one-way operation is one in which a client invokes an operation and continues processing after WCF writes the message to the network. Typically this means that unless the data being sent in the outbound message is extremely large the client continues running almost immediately (unless there is an error sending the data). This type of message exchange pattern supports event-like behavior from a client to a service application. - - A message exchange in which one message is sent and none are received cannot support a service operation that specifies a return value other than `void`; in this case an exception is thrown. - - No return message also means that there can be no SOAP fault returned to indicate any errors in processing or communication. (Communicating error information when operations are one-way operations requires a duplex message exchange pattern.) - - To specify a one-way message exchange for an operation that returns `void`, set the property to `true`, as in the following C# code example. - -```csharp -[OperationContractAttribute(IsOneWay=true)] -void Hello(string greeting); -``` - - The following is the equivalent Visual Basic code. - -```vb - -Sub Hello (ByVal greeting As String) -``` - - This method is identical to the preceding request/reply example, but setting the property to `true` means that although the method is identical, the service operation does not send a return message and clients return immediately once the outbound message has been handed to the channel layer. For an example, see [How to: Create a One-Way Contract](./feature-details/how-to-create-a-one-way-contract.md). For more information about the one-way pattern, see [One-Way Services](./feature-details/one-way-services.md). - -##### Duplex - - A duplex pattern is characterized by the ability of both the service and the client to send messages to each other independently whether using one-way or request/reply messaging. This form of two-way communication is useful for services that must communicate directly to the client or for providing an asynchronous experience to either side of a message exchange, including event-like behavior. - - The duplex pattern is slightly more complex than the request/reply or one-way patterns because of the additional mechanism for communicating with the client. - - To design a duplex contract, you must also design a callback contract and assign the type of that callback contract to the property of the attribute that marks your service contract. - - To implement a duplex pattern, you must create a second interface that contains the method declarations that are called on the client. - - For an example of creating a service, and a client that accesses that service, see [How to: Create a Duplex Contract](./feature-details/how-to-create-a-duplex-contract.md) and [How to: Access Services with a Duplex Contract](./feature-details/how-to-access-services-with-a-duplex-contract.md). For a working sample, see [Duplex](./samples/duplex.md). For more information about issues using duplex contracts, see [Duplex Services](./feature-details/duplex-services.md). - +> The value of the parameter names in the operation signature are part of the contract and are case sensitive. If you want to use the same parameter name locally but modify the name in the published metadata, see the . + +#### Data Contracts + + Service-oriented applications like Windows Communication Foundation (WCF) applications are designed to interoperate with the widest possible number of client applications on both Microsoft and non-Microsoft platforms. For the widest possible interoperability, it is recommended that you mark your types with the and attributes to create a data contract, which is the portion of the service contract that describes the data that your service operations exchange. + + Data contracts are opt-in style contracts: No type or data member is serialized unless you explicitly apply the data contract attribute. Data contracts are unrelated to the access scope of the managed code: Private data members can be serialized and sent elsewhere to be accessed publicly. (For a basic example of a data contract, see [How to: Create a Basic Data Contract for a Class or Structure](./feature-details/how-to-create-a-basic-data-contract-for-a-class-or-structure.md).) WCF handles the definition of the underlying SOAP messages that enable the operation's functionality as well as the serialization of your data types into and out of the body of the messages. As long as your data types are serializable, you do not need to think about the underlying message exchange infrastructure when designing your operations. + + Although the typical WCF application uses the and attributes to create data contracts for operations, you can use other serialization mechanisms. The standard , , and mechanisms all work to handle the serialization of your data types into the underlying SOAP messages that carry them from one application to another. You can employ more serialization strategies if your data types require special support. For more information about the choices for serialization of data types in WCF applications, see [Specifying Data Transfer in Service Contracts](./feature-details/specifying-data-transfer-in-service-contracts.md). + +#### Mapping Parameters and Return Values to Message Exchanges + + Service operations are supported by an underlying exchange of SOAP messages that transfer application data back and forth, in addition to the data required by the application to support certain standard security, transaction, and session-related features. Because this is the case, the signature of a service operation dictates a certain underlying *message exchange pattern* (MEP) that can support the data transfer and the features an operation requires. You can specify three patterns in the WCF programming model: request/reply, one-way, and duplex message patterns. + +##### Request/Reply + + A request/reply pattern is one in which a request sender (a client application) receives a reply with which the request is correlated. This is the default MEP because it supports an operation in which one or more parameters are passed to the operation and a return value is passed back to the caller. For example, the following C# code example shows a basic service operation that takes one string and returns a string. + +```csharp +[OperationContractAttribute] +string Hello(string greeting); +``` + + The following is the equivalent Visual Basic code. + +```vb + +Function Hello (ByVal greeting As String) As String +``` + + This operation signature dictates the form of underlying message exchange. If no correlation existed, WCF cannot determine for which operation the return value is intended. + + Note that unless you specify a different underlying message pattern, even service operations that return `void` (`Nothing` in Visual Basic) are request/reply message exchanges. The result for your operation is that unless a client invokes the operation asynchronously, the client stops processing until the return message is received, even though that message is empty in the normal case. The following C# code example shows an operation that does not return until the client has received an empty message in response. + +```csharp +[OperationContractAttribute] +void Hello(string greeting); +``` + + The following is the equivalent Visual Basic code. + +```vb + +Sub Hello (ByVal greeting As String) +``` + + The preceding example can slow client performance and responsiveness if the operation takes a long time to perform, but there are advantages to request/reply operations even when they return `void`. The most obvious one is that SOAP faults can be returned in the response message, which indicates that some service-related error condition has occurred, whether in communication or processing. SOAP faults that are specified in a service contract are passed to the client application as a object, where the type parameter is the type specified in the service contract. This makes notifying clients about error conditions in WCF services easy. For more information about exceptions, SOAP faults, and error handling, see [Specifying and Handling Faults in Contracts and Services](specifying-and-handling-faults-in-contracts-and-services.md). To see an example of a request/reply service and client, see [How to: Create a Request-Reply Contract](./feature-details/how-to-create-a-request-reply-contract.md). For more information about issues with the request-reply pattern, see [Request-Reply Services](./feature-details/request-reply-services.md). + +##### One-way + + If the client of a WCF service application should not wait for the operation to complete and does not process SOAP faults, the operation can specify a one-way message pattern. A one-way operation is one in which a client invokes an operation and continues processing after WCF writes the message to the network. Typically this means that unless the data being sent in the outbound message is extremely large the client continues running almost immediately (unless there is an error sending the data). This type of message exchange pattern supports event-like behavior from a client to a service application. + + A message exchange in which one message is sent and none are received cannot support a service operation that specifies a return value other than `void`; in this case an exception is thrown. + + No return message also means that there can be no SOAP fault returned to indicate any errors in processing or communication. (Communicating error information when operations are one-way operations requires a duplex message exchange pattern.) + + To specify a one-way message exchange for an operation that returns `void`, set the property to `true`, as in the following C# code example. + +```csharp +[OperationContractAttribute(IsOneWay=true)] +void Hello(string greeting); +``` + + The following is the equivalent Visual Basic code. + +```vb + +Sub Hello (ByVal greeting As String) +``` + + This method is identical to the preceding request/reply example, but setting the property to `true` means that although the method is identical, the service operation does not send a return message and clients return immediately once the outbound message has been handed to the channel layer. For an example, see [How to: Create a One-Way Contract](./feature-details/how-to-create-a-one-way-contract.md). For more information about the one-way pattern, see [One-Way Services](./feature-details/one-way-services.md). + +##### Duplex + + A duplex pattern is characterized by the ability of both the service and the client to send messages to each other independently whether using one-way or request/reply messaging. This form of two-way communication is useful for services that must communicate directly to the client or for providing an asynchronous experience to either side of a message exchange, including event-like behavior. + + The duplex pattern is slightly more complex than the request/reply or one-way patterns because of the additional mechanism for communicating with the client. + + To design a duplex contract, you must also design a callback contract and assign the type of that callback contract to the property of the attribute that marks your service contract. + + To implement a duplex pattern, you must create a second interface that contains the method declarations that are called on the client. + + For an example of creating a service, and a client that accesses that service, see [How to: Create a Duplex Contract](./feature-details/how-to-create-a-duplex-contract.md) and [How to: Access Services with a Duplex Contract](./feature-details/how-to-access-services-with-a-duplex-contract.md). For a working sample, see [Duplex](./samples/duplex.md). For more information about issues using duplex contracts, see [Duplex Services](./feature-details/duplex-services.md). + > [!CAUTION] -> When a service receives a duplex message, it looks at the `ReplyTo` element in that incoming message to determine where to send the reply. If the channel that is used to receive the message is not secured, then an untrusted client could send a malicious message with a target machine's `ReplyTo`, leading to a denial of service (DOS) of that target machine. - -##### Out and Ref Parameters - - In most cases, you can use `in` parameters (`ByVal` in Visual Basic) and `out` and `ref` parameters (`ByRef` in Visual Basic). Because both `out` and `ref` parameters indicate that data is returned from an operation, an operation signature such as the following specifies that a request/reply operation is required even though the operation signature returns `void`. - -```csharp -[ServiceContractAttribute] -public interface IMyContract -{ - [OperationContractAttribute] - public void PopulateData(ref CustomDataType data); -} -``` - - The following is the equivalent Visual Basic code. - -```vb - _ -Public Interface IMyContract - _ - Public Sub PopulateData(ByRef data As CustomDataType) -End Interface -``` - - The only exceptions are those cases in which your signature has a particular structure. For example, you can use the binding to communicate with clients only if the method used to declare an operation returns `void`; there can be no output value, whether it is a return value, `ref`, or `out` parameter. - - In addition, using `out` or `ref` parameters requires that the operation have an underlying response message to carry back the modified object. If your operation is a one-way operation, an exception is thrown at run time. - -### Specify Message Protection Level on the Contract - - When designing your contract, you must also decide the message protection level of services that implement your contract. This is necessary only if message security is applied to the binding in the contract's endpoint. If the binding has security turned off (that is, if the system-provided binding sets the to the value ) then you do not have to decide on the message protection level for the contract. In most cases, system-provided bindings with message-level security applied provide a sufficient protection level and you do not have to consider the protection level for each operation or for each message. - - The protection level is a value that specifies whether the messages (or message parts) that support a service are signed, signed and encrypted, or sent without signatures or encryption. The protection level can be set at various scopes: At the service level, for a particular operation, for a message within that operation, or a message part. Values set at one scope become the default value for smaller scopes unless explicitly overridden. If a binding configuration cannot provide the required minimum protection level for the contract, an exception is thrown. And when no protection level values are explicitly set on the contract, the binding configuration controls the protection level for all messages if the binding has message security. This is the default behavior. - +> When a service receives a duplex message, it looks at the `ReplyTo` element in that incoming message to determine where to send the reply. If the channel that is used to receive the message is not secured, then an untrusted client could send a malicious message with a target machine's `ReplyTo`, leading to a denial of service (DOS) of that target machine. + +##### Out and Ref Parameters + + In most cases, you can use `in` parameters (`ByVal` in Visual Basic) and `out` and `ref` parameters (`ByRef` in Visual Basic). Because both `out` and `ref` parameters indicate that data is returned from an operation, an operation signature such as the following specifies that a request/reply operation is required even though the operation signature returns `void`. + +```csharp +[ServiceContractAttribute] +public interface IMyContract +{ + [OperationContractAttribute] + public void PopulateData(ref CustomDataType data); +} +``` + + The following is the equivalent Visual Basic code. + +```vb + _ +Public Interface IMyContract + _ + Public Sub PopulateData(ByRef data As CustomDataType) +End Interface +``` + + The only exceptions are those cases in which your signature has a particular structure. For example, you can use the binding to communicate with clients only if the method used to declare an operation returns `void`; there can be no output value, whether it is a return value, `ref`, or `out` parameter. + + In addition, using `out` or `ref` parameters requires that the operation have an underlying response message to carry back the modified object. If your operation is a one-way operation, an exception is thrown at runtime. + +### Specify Message Protection Level on the Contract + + When designing your contract, you must also decide the message protection level of services that implement your contract. This is necessary only if message security is applied to the binding in the contract's endpoint. If the binding has security turned off (that is, if the system-provided binding sets the to the value ) then you do not have to decide on the message protection level for the contract. In most cases, system-provided bindings with message-level security applied provide a sufficient protection level and you do not have to consider the protection level for each operation or for each message. + + The protection level is a value that specifies whether the messages (or message parts) that support a service are signed, signed and encrypted, or sent without signatures or encryption. The protection level can be set at various scopes: At the service level, for a particular operation, for a message within that operation, or a message part. Values set at one scope become the default value for smaller scopes unless explicitly overridden. If a binding configuration cannot provide the required minimum protection level for the contract, an exception is thrown. And when no protection level values are explicitly set on the contract, the binding configuration controls the protection level for all messages if the binding has message security. This is the default behavior. + > [!IMPORTANT] -> Deciding whether to explicitly set various scopes of a contract to less than the full protection level of is generally a decision that trades some degree of security for increased performance. In these cases, your decisions must revolve around your operations and the value of the data they exchange. For more information, see [Securing Services](securing-services.md). - - For example, the following code example does not set either the or the property on the contract. - -```csharp -[ServiceContract] -public interface ISampleService -{ - [OperationContractAttribute] - public string GetString(); - - [OperationContractAttribute] +> Deciding whether to explicitly set various scopes of a contract to less than the full protection level of is generally a decision that trades some degree of security for increased performance. In these cases, your decisions must revolve around your operations and the value of the data they exchange. For more information, see [Securing Services](securing-services.md). + + For example, the following code example does not set either the or the property on the contract. + +```csharp +[ServiceContract] +public interface ISampleService +{ + [OperationContractAttribute] + public string GetString(); + + [OperationContractAttribute] public int GetInt(); -} -``` - - The following is the equivalent Visual Basic code. - -```vb - _ -Public Interface ISampleService - - _ - Public Function GetString()As String - - _ - Public Function GetData() As Integer - -End Interface -``` - - When interacting with an `ISampleService` implementation in an endpoint with a default (the default , which is ), all messages are encrypted and signed because this is the default protection level. However, when an `ISampleService` service is used with a default (the default , which is ), all messages are sent as text because there is no security for this binding and so the protection level is ignored (that is, the messages are neither encrypted nor signed). If the was changed to , then these messages would be encrypted and signed (because that would now be the binding's default protection level). - - If you want to explicitly specify or adjust the protection requirements for your contract, set the property (or any of the `ProtectionLevel` properties at a smaller scope) to the level your service contract requires. In this case, using an explicit setting requires the binding to support that setting at a minimum for the scope used. For example, the following code example specifies one value explicitly, for the `GetGuid` operation. - -```csharp -[ServiceContract] -public interface IExplicitProtectionLevelSampleService -{ - [OperationContractAttribute] - public string GetString(); - - [OperationContractAttribute(ProtectionLevel=ProtectionLevel.None)] +} +``` + + The following is the equivalent Visual Basic code. + +```vb + _ +Public Interface ISampleService + + _ + Public Function GetString()As String + + _ + Public Function GetData() As Integer + +End Interface +``` + + When interacting with an `ISampleService` implementation in an endpoint with a default (the default , which is ), all messages are encrypted and signed because this is the default protection level. However, when an `ISampleService` service is used with a default (the default , which is ), all messages are sent as text because there is no security for this binding and so the protection level is ignored (that is, the messages are neither encrypted nor signed). If the was changed to , then these messages would be encrypted and signed (because that would now be the binding's default protection level). + + If you want to explicitly specify or adjust the protection requirements for your contract, set the property (or any of the `ProtectionLevel` properties at a smaller scope) to the level your service contract requires. In this case, using an explicit setting requires the binding to support that setting at a minimum for the scope used. For example, the following code example specifies one value explicitly, for the `GetGuid` operation. + +```csharp +[ServiceContract] +public interface IExplicitProtectionLevelSampleService +{ + [OperationContractAttribute] + public string GetString(); + + [OperationContractAttribute(ProtectionLevel=ProtectionLevel.None)] public int GetInt(); - [OperationContractAttribute(ProtectionLevel=ProtectionLevel.EncryptAndSign)] + [OperationContractAttribute(ProtectionLevel=ProtectionLevel.EncryptAndSign)] public int GetGuid(); -} -``` - - The following is the equivalent Visual Basic code. - -```vb +} +``` + + The following is the equivalent Visual Basic code. + +```vb _ Public Interface IExplicitProtectionLevelSampleService _ Public Function GetString() As String End Function - + _ Public Function GetInt() As Integer End Function - + _ Public Function GetGuid() As Integer End Function - -End Interface -``` - - A service that implements this `IExplicitProtectionLevelSampleService` contract and has an endpoint that uses the default (the default , which is ) has the following behavior: - -- The `GetString` operation messages are encrypted and signed. - -- The `GetInt` operation messages are sent as unencrypted and unsigned (that is, plain) text. - -- The `GetGuid` operation is returned in a message that is encrypted and signed. - - For more information about protection levels and how to use them, see [Understanding Protection Level](understanding-protection-level.md). For more information about security, see [Securing Services](securing-services.md). - -##### Other Operation Signature Requirements - - Some application features require a particular kind of operation signature. For example, the binding supports durable services and clients, in which an application can restart in the middle of communication and pick up where it left off without missing any messages. (For more information, see [Queues in WCF](./feature-details/queues-in-wcf.md).) However, durable operations must take only one `in` parameter and have no return value. - - Another example is the use of types in operations. Because the parameter includes the entire message body, if an input or an output (that is, `ref` parameter, `out` parameter, or return value) is of type , then it must be the only input or output specified in your operation. In addition, the parameter or return type must be either , , or . For more information about streams, see [Large Data and Streaming](./feature-details/large-data-and-streaming.md). - -##### Names, Namespaces, and Obfuscation - - The names and namespaces of the .NET types in the definition of contracts and operations are significant when contracts are converted into WSDL and when contract messages are created and sent. Therefore, it is strongly recommended that service contract names and namespaces are explicitly set using the `Name` and `Namespace` properties of all supporting contract attributes such as the , , , , and other contract attributes. - - One result of this is that if the names and namespaces are not explicitly set, the use of IL obfuscation on the assembly alters the contract type names and namespaces and results in modified WSDL and wire exchanges that typically fail. If you do not set the contract names and namespaces explicitly but do intend to use obfuscation, use the and attributes to prevent the modification of the contract type names and namespaces. - + +End Interface +``` + + A service that implements this `IExplicitProtectionLevelSampleService` contract and has an endpoint that uses the default (the default , which is ) has the following behavior: + +- The `GetString` operation messages are encrypted and signed. + +- The `GetInt` operation messages are sent as unencrypted and unsigned (that is, plain) text. + +- The `GetGuid` operation is returned in a message that is encrypted and signed. + + For more information about protection levels and how to use them, see [Understanding Protection Level](understanding-protection-level.md). For more information about security, see [Securing Services](securing-services.md). + +##### Other Operation Signature Requirements + + Some application features require a particular kind of operation signature. For example, the binding supports durable services and clients, in which an application can restart in the middle of communication and pick up where it left off without missing any messages. (For more information, see [Queues in WCF](./feature-details/queues-in-wcf.md).) However, durable operations must take only one `in` parameter and have no return value. + + Another example is the use of types in operations. Because the parameter includes the entire message body, if an input or an output (that is, `ref` parameter, `out` parameter, or return value) is of type , then it must be the only input or output specified in your operation. In addition, the parameter or return type must be either , , or . For more information about streams, see [Large Data and Streaming](./feature-details/large-data-and-streaming.md). + +##### Names, Namespaces, and Obfuscation + + The names and namespaces of the .NET types in the definition of contracts and operations are significant when contracts are converted into WSDL and when contract messages are created and sent. Therefore, it is strongly recommended that service contract names and namespaces are explicitly set using the `Name` and `Namespace` properties of all supporting contract attributes such as the , , , , and other contract attributes. + + One result of this is that if the names and namespaces are not explicitly set, the use of IL obfuscation on the assembly alters the contract type names and namespaces and results in modified WSDL and wire exchanges that typically fail. If you do not set the contract names and namespaces explicitly but do intend to use obfuscation, use the and attributes to prevent the modification of the contract type names and namespaces. + ## See also - [How to: Create a Request-Reply Contract](./feature-details/how-to-create-a-request-reply-contract.md) diff --git a/docs/framework/wcf/diagnostics/configuring-message-logging.md b/docs/framework/wcf/diagnostics/configuring-message-logging.md index ac236966472e6..21f4943afe903 100644 --- a/docs/framework/wcf/diagnostics/configuring-message-logging.md +++ b/docs/framework/wcf/diagnostics/configuring-message-logging.md @@ -97,7 +97,7 @@ In addition to the logging levels, the user can specify the following options: If no trace listener is defined in the configuration file, no logging output is generated regardless of the specified logging level. -Message logging options, such as the attributes described in this section, can be changed at run time using Windows Management Instrumentation (WMI). This can be done by accessing the [AppDomainInfo](./wmi/appdomaininfo.md) instance, which exposes these Boolean properties: `LogMessagesAtServiceLevel`, `LogMessagesAtTransportLevel`, and `LogMalformedMessages`. Therefore, if you configure a trace listener for message logging, but set these options to `false` in configuration, you can later change them to `true` when the application is running. This effectively enables message logging at run time. Similarly, if you enable message logging in your configuration file, you can disable it at run time using WMI. For more information, see [Using Windows Management Instrumentation for Diagnostics](./wmi/index.md). +Message logging options, such as the attributes described in this section, can be changed at runtime using Windows Management Instrumentation (WMI). This can be done by accessing the [AppDomainInfo](./wmi/appdomaininfo.md) instance, which exposes these Boolean properties: `LogMessagesAtServiceLevel`, `LogMessagesAtTransportLevel`, and `LogMalformedMessages`. Therefore, if you configure a trace listener for message logging, but set these options to `false` in configuration, you can later change them to `true` when the application is running. This effectively enables message logging at runtime. Similarly, if you enable message logging in your configuration file, you can disable it at runtime using WMI. For more information, see [Using Windows Management Instrumentation for Diagnostics](./wmi/index.md). The `source` field in a message log specifies in which context the message is logged: when sending/receiving a request message, for a request-reply or 1-way request, at service model or transport layer, or in the case of a malformed message. diff --git a/docs/framework/wcf/diagnostics/deploying-services.md b/docs/framework/wcf/diagnostics/deploying-services.md index a854b297d5d22..ca7b2c406c7a5 100644 --- a/docs/framework/wcf/diagnostics/deploying-services.md +++ b/docs/framework/wcf/diagnostics/deploying-services.md @@ -6,12 +6,12 @@ ms.assetid: ac361bfb-017d-4da9-a2d7-fc0fb72d65bb --- # Deploying Services -This topic describes how you can deploy a Windows Communication Foundation (WCF) application to a run-time environment. - -## Choosing the Hosting Environment for Your Application +This topic describes how you can deploy a Windows Communication Foundation (WCF) application to a runtime environment. + +## Choosing the Hosting Environment for Your Application + + WCF services are designed to run in any Windows process that supports managed code. To become active, a service must be hosted within a runtime environment that creates it and controls its context and lifetime. Hosting options range from running inside the simplest console application to server environments like a Windows service, Internet Information Services (IIS), or within a worker process managed by the Windows Activation Service (WAS). To review the different hosting options for your WCF application, see [Hosting Services](../hosting-services.md). - WCF services are designed to run in any Windows process that supports managed code. To become active, a service must be hosted within a run-time environment that creates it and controls its context and lifetime. Hosting options range from running inside the simplest console application to server environments like a Windows service, Internet Information Services (IIS), or within a worker process managed by the Windows Activation Service (WAS). To review the different hosting options for your WCF application, see [Hosting Services](../hosting-services.md). - ## See also - [Hosting](../feature-details/hosting.md) diff --git a/docs/framework/wcf/diagnostics/index.md b/docs/framework/wcf/diagnostics/index.md index af3a76489e2d7..ba3cc9bfb461f 100644 --- a/docs/framework/wcf/diagnostics/index.md +++ b/docs/framework/wcf/diagnostics/index.md @@ -2,7 +2,7 @@ description: "Learn more about: Administration and Diagnostics" title: "Administration and Diagnostics" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "Windows Communication Foundation, diagnostics" - "Windows Communication Foundation, administration" - "diagnostics [WCF]" @@ -13,29 +13,29 @@ ms.assetid: 34c81c08-0e0f-4fbc-9ae8-91948640ee43 --- # Administration and Diagnostics -Windows Communication Foundation (WCF) provides a rich set of functionalities that can help you monitor the different stages of an application’s life. For example, you can use configuration to set up services and clients at deployment. WCF includes a large set of performance counters to help you gauge your application's performance. WCF also exposes inspection data of a service at run time through a WCF Windows Management Instrumentation (WMI) provider. When the application experiences a failure or starts acting improperly, you can use the Event Log to see if anything significant has occurred. You can also use Message Logging and Tracing to see what events are happening end-to-end in your application. These features assist both developers and IT professionals to troubleshoot an WCF application when it is not behaving correctly. - +Windows Communication Foundation (WCF) provides a rich set of functionalities that can help you monitor the different stages of an application’s life. For example, you can use configuration to set up services and clients at deployment. WCF includes a large set of performance counters to help you gauge your application's performance. WCF also exposes inspection data of a service at runtime through a WCF Windows Management Instrumentation (WMI) provider. When the application experiences a failure or starts acting improperly, you can use the Event Log to see if anything significant has occurred. You can also use Message Logging and Tracing to see what events are happening end-to-end in your application. These features assist both developers and IT professionals to troubleshoot an WCF application when it is not behaving correctly. + > [!NOTE] -> If you are receiving faults with no specific detail information, you should enable the `includeExceptionDetailInFaults` attribute of the [\](../../configure-apps/file-schema/wcf/servicedebug.md) configuration element. This instructs WCF to send exception detail to clients, which enables you to detect many common problems without requiring more advanced diagnosis. For more information, see [Sending and Receiving Faults](../sending-and-receiving-faults.md). - -## Diagnostics Features Provided by WCF - - WCF provides the following diagnostics functionalities: - -- End-To-End tracing provides instrumentation data for troubleshooting an application without using a debugger. WCF outputs traces for process milestones, as well as error messages. This can include opening a channel factory or sending and receiving messages by a service host. Tracing can be enabled for a running application to monitor its progress. For more information, see the [Tracing](./tracing/index.md) topic. To understand how you can use tracing to debug your application, see the [Using Tracing to Troubleshoot Your Application](./tracing/using-tracing-to-troubleshoot-your-application.md) topic. - -- Message logging allows you to see how messages look both before and after transmission. For more information, see the [Message Logging](message-logging.md) topic. - -- Event tracing writes events in the Event Log for any major issues. You can then use the Event Viewer to examine any abnormalities. For more information, see the [Event Logging](./event-logging/index.md) topic. - -- Performance counters exposed through Performance Monitor enable you to monitor your application and system's health. For more information, see the [Performance Counters](./performance-counters/index.md) topic. - -- The namespace allows you to load configuration files and set up a service or client endpoint. You can use the object model to script changes to many applications when updates must be deployed to many computers. Alternatively, you can use the [Configuration Editor Tool (SvcConfigEditor.exe)](../configuration-editor-tool-svcconfigeditor-exe.md) to edit the configuration settings using a GUI wizard. For more information, see the [Configuring Your Application](configuring-your-application.md) topic. - -- WMI enables you to find out what services are listening on a machine and the bindings that are in use. For more information, see the [Using Windows Management Instrumentation for Diagnostics](./wmi/index.md) topic. - - WCF also provides several GUI and command line tools to make it easier for you to create, deploy, and manage WCF applications. For more information, see [Windows Communication Foundation Tools](../tools.md). For example, you can use the [Configuration Editor Tool (SvcConfigEditor.exe)](../configuration-editor-tool-svcconfigeditor-exe.md) to create and edit WCF configuration settings using a wizard, instead of editing XML directly. You can also use the [Service Trace Viewer Tool (SvcTraceViewer.exe)](../service-trace-viewer-tool-svctraceviewer-exe.md) to view, group, and filter trace messages so that you can diagnose, repair, and verify issues with WCF services. - +> If you are receiving faults with no specific detail information, you should enable the `includeExceptionDetailInFaults` attribute of the [\](../../configure-apps/file-schema/wcf/servicedebug.md) configuration element. This instructs WCF to send exception detail to clients, which enables you to detect many common problems without requiring more advanced diagnosis. For more information, see [Sending and Receiving Faults](../sending-and-receiving-faults.md). + +## Diagnostics Features Provided by WCF + + WCF provides the following diagnostics functionalities: + +- End-To-End tracing provides instrumentation data for troubleshooting an application without using a debugger. WCF outputs traces for process milestones, as well as error messages. This can include opening a channel factory or sending and receiving messages by a service host. Tracing can be enabled for a running application to monitor its progress. For more information, see the [Tracing](./tracing/index.md) topic. To understand how you can use tracing to debug your application, see the [Using Tracing to Troubleshoot Your Application](./tracing/using-tracing-to-troubleshoot-your-application.md) topic. + +- Message logging allows you to see how messages look both before and after transmission. For more information, see the [Message Logging](message-logging.md) topic. + +- Event tracing writes events in the Event Log for any major issues. You can then use the Event Viewer to examine any abnormalities. For more information, see the [Event Logging](./event-logging/index.md) topic. + +- Performance counters exposed through Performance Monitor enable you to monitor your application and system's health. For more information, see the [Performance Counters](./performance-counters/index.md) topic. + +- The namespace allows you to load configuration files and set up a service or client endpoint. You can use the object model to script changes to many applications when updates must be deployed to many computers. Alternatively, you can use the [Configuration Editor Tool (SvcConfigEditor.exe)](../configuration-editor-tool-svcconfigeditor-exe.md) to edit the configuration settings using a GUI wizard. For more information, see the [Configuring Your Application](configuring-your-application.md) topic. + +- WMI enables you to find out what services are listening on a machine and the bindings that are in use. For more information, see the [Using Windows Management Instrumentation for Diagnostics](./wmi/index.md) topic. + + WCF also provides several GUI and command line tools to make it easier for you to create, deploy, and manage WCF applications. For more information, see [Windows Communication Foundation Tools](../tools.md). For example, you can use the [Configuration Editor Tool (SvcConfigEditor.exe)](../configuration-editor-tool-svcconfigeditor-exe.md) to create and edit WCF configuration settings using a wizard, instead of editing XML directly. You can also use the [Service Trace Viewer Tool (SvcTraceViewer.exe)](../service-trace-viewer-tool-svctraceviewer-exe.md) to view, group, and filter trace messages so that you can diagnose, repair, and verify issues with WCF services. + ## See also - [Configuring Your Application](configuring-your-application.md) diff --git a/docs/framework/wcf/diagnostics/tracing/activity.md b/docs/framework/wcf/diagnostics/tracing/activity.md index 93adc5b8e43b6..86adc620be46a 100644 --- a/docs/framework/wcf/diagnostics/tracing/activity.md +++ b/docs/framework/wcf/diagnostics/tracing/activity.md @@ -6,100 +6,100 @@ ms.assetid: 70471705-f55f-4da1-919f-4b580f172665 --- # Activity -This topic describes activity traces in the Windows Communication Foundation (WCF) tracing model. Activities are processing units that help the user narrow down the scope of a failure. Errors that occur in the same activity are directly related. For example, an operation fails because message decryption has failed. The traces for both the operation and message decryption failure appear in the same activity, showing direct correlation between the decryption error and the request error. - -## Configuring Activity Tracing - - WCF provides pre-defined activities for processing applications (see [Activity List](activity-list.md)). You can also define activities programmatically to group user traces. For more information, see [Emitting User-Code Traces](emitting-user-code-traces.md). - - To emit activity traces at run time, use the `ActivityTracing` setting for the `System.ServiceModel` trace source, or other WCF or custom trace sources, as demonstrated by the following configuration code. - -```xml - -``` - - To understand more about the configuration element and attributes being used, see the [Configuring Tracing](configuring-tracing.md) topic. - -## Viewing Activities - - You can view the activities and their utility in the [Service Trace Viewer Tool (SvcTraceViewer.exe)](../../service-trace-viewer-tool-svctraceviewer-exe.md). When ActivityTracing is enabled, this tool takes the traces and sorts them based on activity. You can also see trace transfers. A trace transfer indicates how different activities are related to each other. You can see that a particular activity caused another to start. For example, a message request started a security handshake to get a Secure Conversation Token. - -### Correlating Activities in Service Trace Viewer - - The Service Trace Viewer tool provides two views of activities: - -- **List** view, where the activity ID is used to directly correlate traces across processes. Traces from different processes, for example, client and service, but with the same activity ID are grouped in the same activity. Therefore, an error occurring on the service which then causes an error on the client will both show up in the same activity view in the tool. - -- **Graph** view, where activities are grouped by processes. In this view, a client and service with the same activity ID have their traces in different activities. To correlate activities with the same activity ID in different processes, the tool shows message flows across the related activities. - - For more information, and to see a graphical view of the Service Trace Viewer tool, see [Service Trace Viewer Tool (SvcTraceViewer.exe)](../../service-trace-viewer-tool-svctraceviewer-exe.md) and [Using Service Trace Viewer for Viewing Correlated Traces and Troubleshooting](using-service-trace-viewer-for-viewing-correlated-traces-and-troubleshooting.md). - -## Defining the Scope of an Activity - - An activity is defined at design time and denotes a logical unit of work. Emitted traces with the same activity identifier are directly related, they are part of the same activity. Because an activity can cross endpoint boundaries (a request), two scopes for an activity are defined. - -- `Global` scope, per application. In this scope, the activity is identified by its 128-bit globally unique activity identifier, the gAId. The gAid is what is propagated across endpoints. - -- `Local` scope, per endpoint. In this scope, the activity is identified by its gAId, along with the trace source name emitting the activity traces and the process Id. This triplet constitutes the local activity id, lAId. The lAId is used to define the (local) boundaries of an activity. - -## Trace Schema - - Traces can be emitted using any schema, and across Microsoft platforms. "e2e" (for "End to End") is a commonly used schema. This schema includes a 128 bit identifier (gAId), the trace source name, and process ID. In managed code, emits traces in the E2E schema. - - Developers can set the AID that is emitted with a trace by setting the property with a Guid on Thread Local Storage (TLS). The following example demonstrates this. - +This topic describes activity traces in the Windows Communication Foundation (WCF) tracing model. Activities are processing units that help the user narrow down the scope of a failure. Errors that occur in the same activity are directly related. For example, an operation fails because message decryption has failed. The traces for both the operation and message decryption failure appear in the same activity, showing direct correlation between the decryption error and the request error. + +## Configuring Activity Tracing + + WCF provides pre-defined activities for processing applications (see [Activity List](activity-list.md)). You can also define activities programmatically to group user traces. For more information, see [Emitting User-Code Traces](emitting-user-code-traces.md). + + To emit activity traces at runtime, use the `ActivityTracing` setting for the `System.ServiceModel` trace source, or other WCF or custom trace sources, as demonstrated by the following configuration code. + +```xml + +``` + + To understand more about the configuration element and attributes being used, see the [Configuring Tracing](configuring-tracing.md) topic. + +## Viewing Activities + + You can view the activities and their utility in the [Service Trace Viewer Tool (SvcTraceViewer.exe)](../../service-trace-viewer-tool-svctraceviewer-exe.md). When ActivityTracing is enabled, this tool takes the traces and sorts them based on activity. You can also see trace transfers. A trace transfer indicates how different activities are related to each other. You can see that a particular activity caused another to start. For example, a message request started a security handshake to get a Secure Conversation Token. + +### Correlating Activities in Service Trace Viewer + + The Service Trace Viewer tool provides two views of activities: + +- **List** view, where the activity ID is used to directly correlate traces across processes. Traces from different processes, for example, client and service, but with the same activity ID are grouped in the same activity. Therefore, an error occurring on the service which then causes an error on the client will both show up in the same activity view in the tool. + +- **Graph** view, where activities are grouped by processes. In this view, a client and service with the same activity ID have their traces in different activities. To correlate activities with the same activity ID in different processes, the tool shows message flows across the related activities. + + For more information, and to see a graphical view of the Service Trace Viewer tool, see [Service Trace Viewer Tool (SvcTraceViewer.exe)](../../service-trace-viewer-tool-svctraceviewer-exe.md) and [Using Service Trace Viewer for Viewing Correlated Traces and Troubleshooting](using-service-trace-viewer-for-viewing-correlated-traces-and-troubleshooting.md). + +## Defining the Scope of an Activity + + An activity is defined at design time and denotes a logical unit of work. Emitted traces with the same activity identifier are directly related, they are part of the same activity. Because an activity can cross endpoint boundaries (a request), two scopes for an activity are defined. + +- `Global` scope, per application. In this scope, the activity is identified by its 128-bit globally unique activity identifier, the gAId. The gAid is what is propagated across endpoints. + +- `Local` scope, per endpoint. In this scope, the activity is identified by its gAId, along with the trace source name emitting the activity traces and the process Id. This triplet constitutes the local activity id, lAId. The lAId is used to define the (local) boundaries of an activity. + +## Trace Schema + + Traces can be emitted using any schema, and across Microsoft platforms. "e2e" (for "End to End") is a commonly used schema. This schema includes a 128 bit identifier (gAId), the trace source name, and process ID. In managed code, emits traces in the E2E schema. + + Developers can set the AID that is emitted with a trace by setting the property with a Guid on Thread Local Storage (TLS). The following example demonstrates this. + ```csharp -// set the current Activity ID to a new GUID. -CorrelationManager.ActivityId = Guid.NewGuid(); +// set the current Activity ID to a new GUID. +CorrelationManager.ActivityId = Guid.NewGuid(); ``` - - Setting the gAId in TLS will be evident when traces are emitted using a trace source, as shown by the following example. - + + Setting the gAId in TLS will be evident when traces are emitted using a trace source, as shown by the following example. + ```csharp -TraceSource traceSource = new TraceSource("myTraceSource"); -traceSource.TraceEvent(TraceEventType.Warning, eventId, "Information"); -``` - - The trace emitted will contain the gAId currently in TLS, the trace source name passed as a parameter to the trace source’s constructor, and the current process’s ID. - -## Activity Lifetime - - In strictest terms, evidence of an activity starts the first time the activity ID is used in an emitted trace, and ends the last time it is used in an emitted trace. A predefined set of trace types are provided by , including Start and Stop, to explicitly mark the activity lifetime boundaries. - -- Start: Indicates the beginning of an activity. A "Start" trace provides a record of beginning a new processing milestone. It contains a new activity ID for a given trace source in a given process, except when the activity ID is propagated across endpoints, in which case we see one "Start" per endpoint. Examples of starting a new activity include creating a new thread for processing, or entering a new public method. - -- Stop: Indicates the end of an activity. A "Stop" trace provides a record of ending an existing processing milestone. It contains an existing activity ID for a given trace source in a given process, except when the activity ID is propagated across endpoints, in which case we see one "Stop" per endpoint. Examples of stopping an activity include terminating a processing thread, or exiting a method whose beginning was denoted with a "Start" trace. - -- Suspend: Indicates suspension of processing of an activity. A "Suspend" trace contains an existing activity ID whose processing is expected to resume at a later time. No traces are emitted with this ID between the Suspend and Resume events from the current trace source. Examples include pausing an activity when calling into an external library function, or when waiting on a resource such as an I/O completion port. - -- Resume: Indicates the resumption of processing of an activity. A "Resume" trace contains an existing activity id whose last emitted trace from the current trace source was a "Suspend" trace. Examples include returning from a call to an external library function, or when signaled to resume processing by a resource such as an I/O completion port. - -- Transfer: Because some activities are caused by others, or relate to others, activities can be related to other activities through "Transfer" traces. A transfer records the directed relationship of one activity to another - - Start and Stop traces are not critical for correlation. However, they can help in increasing performance, profiling, and activity scope validation. - - Using these types, the tools can optimize navigating the trace logs to find the immediately related events of the same activity, or events in related activities if the tool follows transfer traces. For example, the tools will stop parsing the logs for a given activity when they see a Start/Stop trace. - - These trace types can also be used for profiling. Resources consumed between the start and stop markers represent the activity’s inclusive time including contained logical activities. Subtracting the time intervals between the Suspend and Resume traces provides the actual activity time. - - The Stop trace is also particularly useful for validating the scope of the implemented activities. If some processing traces appear after the Stop trace instead of inside a given activity, this can suggests code defect. - -## Guidelines for Using Activity Tracing - - The following is a guideline of using ActivityTracing traces (Start, Stop, Suspend, Resume, and Transfer). - -- Tracing is a directed cyclic graph, not a tree. You can return control to an activity which spawned an activity. - -- An activity denotes a processing boundary which can be meaningful to the administrator of the system or for supportability. - -- Each WCF method, both on the client and server, is bounded by beginning a new activity, then (after work is done) ending the new activity and returning to the ambient activity. - -- Long running (ongoing) activities such as listening for connections or waiting for messages are represented by corresponding start/stop markers. - -- Activities triggered by the receipt or processing of a message are represented by trace boundaries. - -- Activities represent activities, not necessarily objects. An activity should be interpreted as "this was happening when . . . (meaningful trace emission occurred)." - +TraceSource traceSource = new TraceSource("myTraceSource"); +traceSource.TraceEvent(TraceEventType.Warning, eventId, "Information"); +``` + + The trace emitted will contain the gAId currently in TLS, the trace source name passed as a parameter to the trace source’s constructor, and the current process’s ID. + +## Activity Lifetime + + In strictest terms, evidence of an activity starts the first time the activity ID is used in an emitted trace, and ends the last time it is used in an emitted trace. A predefined set of trace types are provided by , including Start and Stop, to explicitly mark the activity lifetime boundaries. + +- Start: Indicates the beginning of an activity. A "Start" trace provides a record of beginning a new processing milestone. It contains a new activity ID for a given trace source in a given process, except when the activity ID is propagated across endpoints, in which case we see one "Start" per endpoint. Examples of starting a new activity include creating a new thread for processing, or entering a new public method. + +- Stop: Indicates the end of an activity. A "Stop" trace provides a record of ending an existing processing milestone. It contains an existing activity ID for a given trace source in a given process, except when the activity ID is propagated across endpoints, in which case we see one "Stop" per endpoint. Examples of stopping an activity include terminating a processing thread, or exiting a method whose beginning was denoted with a "Start" trace. + +- Suspend: Indicates suspension of processing of an activity. A "Suspend" trace contains an existing activity ID whose processing is expected to resume at a later time. No traces are emitted with this ID between the Suspend and Resume events from the current trace source. Examples include pausing an activity when calling into an external library function, or when waiting on a resource such as an I/O completion port. + +- Resume: Indicates the resumption of processing of an activity. A "Resume" trace contains an existing activity id whose last emitted trace from the current trace source was a "Suspend" trace. Examples include returning from a call to an external library function, or when signaled to resume processing by a resource such as an I/O completion port. + +- Transfer: Because some activities are caused by others, or relate to others, activities can be related to other activities through "Transfer" traces. A transfer records the directed relationship of one activity to another + + Start and Stop traces are not critical for correlation. However, they can help in increasing performance, profiling, and activity scope validation. + + Using these types, the tools can optimize navigating the trace logs to find the immediately related events of the same activity, or events in related activities if the tool follows transfer traces. For example, the tools will stop parsing the logs for a given activity when they see a Start/Stop trace. + + These trace types can also be used for profiling. Resources consumed between the start and stop markers represent the activity’s inclusive time including contained logical activities. Subtracting the time intervals between the Suspend and Resume traces provides the actual activity time. + + The Stop trace is also particularly useful for validating the scope of the implemented activities. If some processing traces appear after the Stop trace instead of inside a given activity, this can suggests code defect. + +## Guidelines for Using Activity Tracing + + The following is a guideline of using ActivityTracing traces (Start, Stop, Suspend, Resume, and Transfer). + +- Tracing is a directed cyclic graph, not a tree. You can return control to an activity which spawned an activity. + +- An activity denotes a processing boundary which can be meaningful to the administrator of the system or for supportability. + +- Each WCF method, both on the client and server, is bounded by beginning a new activity, then (after work is done) ending the new activity and returning to the ambient activity. + +- Long running (ongoing) activities such as listening for connections or waiting for messages are represented by corresponding start/stop markers. + +- Activities triggered by the receipt or processing of a message are represented by trace boundaries. + +- Activities represent activities, not necessarily objects. An activity should be interpreted as "this was happening when . . . (meaningful trace emission occurred)." + ## See also - [Configuring Tracing](configuring-tracing.md) diff --git a/docs/framework/wcf/diagnostics/tracing/configuring-tracing.md b/docs/framework/wcf/diagnostics/tracing/configuring-tracing.md index b81033df7ea23..5bdc8c0075bf5 100644 --- a/docs/framework/wcf/diagnostics/tracing/configuring-tracing.md +++ b/docs/framework/wcf/diagnostics/tracing/configuring-tracing.md @@ -2,185 +2,185 @@ title: "Configuring Tracing" description: Learn how to enable tracing, configure trace sources, set activity tracing and propagation, and set trace listeners to access traces in WCF. ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "tracing [WCF]" ms.assetid: 82922010-e8b3-40eb-98c4-10fc05c6d65d --- # Configuring Tracing -This topic describes how you can enable tracing, configure trace sources to emit traces and set trace levels, set activity tracing and propagation to support end-to-end trace correlation, and set trace listeners to access traces. - - For tracing settings recommendations in production or debugging environment, refer to [Recommended Settings for Tracing and Message Logging](recommended-settings-for-tracing-and-message-logging.md). - +This topic describes how you can enable tracing, configure trace sources to emit traces and set trace levels, set activity tracing and propagation to support end-to-end trace correlation, and set trace listeners to access traces. + + For tracing settings recommendations in production or debugging environment, refer to [Recommended Settings for Tracing and Message Logging](recommended-settings-for-tracing-and-message-logging.md). + > [!IMPORTANT] -> On Windows 8 you must run your application elevated (Run as Administrator) in order for your application to generate trace logs. - -## Enabling Tracing - - Windows Communication Foundation (WCF) outputs the following data for diagnostic tracing: - -- Traces for process milestones across all components of the applications, such as operation calls, code exceptions, warnings, and other significant processing events. - -- Windows error events when the tracing feature malfunctions. See [Event Logging](../event-logging/index.md). - - WCF tracing is built on top of . To use tracing, you should define trace sources in the configuration file or in code. WCF defines a trace source for each WCF assembly. The `System.ServiceModel` trace source is the most general WCF trace source, and records processing milestones across the WCF communication stack, from entering/leaving transport to entering/leaving user code. The `System.ServiceModel.MessageLogging` trace source records all messages that flow through the system. - - Tracing is not enabled by default. To activate tracing, you must create a trace listener and set a trace level other than "Off" for the selected trace source in configuration; otherwise, WCF does not generate any traces. If you do not specify a listener, tracing is automatically disabled. If a listener is defined, but no level is specified, the level is set to "Off" by default, which means that no trace is emitted. - - If you use WCF extensibility points such as custom operation invokers, you should emit your own traces. This is because if you implement an extensibility point, WCF can no longer emit the standard traces in the default path. If you do not implement manual tracing support by emitting traces, you may not see the traces you expect. - - You can configure tracing by editing the application's configuration file—either Web.config for Web-hosted applications, or Appname.exe.config for self-hosted applications. The following is an example of such edit. For more information on these settings, see the "Configuring Trace Listeners to Consume Traces" section. - -```xml - - - +> On Windows 8 you must run your application elevated (Run as Administrator) in order for your application to generate trace logs. + +## Enabling Tracing + + Windows Communication Foundation (WCF) outputs the following data for diagnostic tracing: + +- Traces for process milestones across all components of the applications, such as operation calls, code exceptions, warnings, and other significant processing events. + +- Windows error events when the tracing feature malfunctions. See [Event Logging](../event-logging/index.md). + + WCF tracing is built on top of . To use tracing, you should define trace sources in the configuration file or in code. WCF defines a trace source for each WCF assembly. The `System.ServiceModel` trace source is the most general WCF trace source, and records processing milestones across the WCF communication stack, from entering/leaving transport to entering/leaving user code. The `System.ServiceModel.MessageLogging` trace source records all messages that flow through the system. + + Tracing is not enabled by default. To activate tracing, you must create a trace listener and set a trace level other than "Off" for the selected trace source in configuration; otherwise, WCF does not generate any traces. If you do not specify a listener, tracing is automatically disabled. If a listener is defined, but no level is specified, the level is set to "Off" by default, which means that no trace is emitted. + + If you use WCF extensibility points such as custom operation invokers, you should emit your own traces. This is because if you implement an extensibility point, WCF can no longer emit the standard traces in the default path. If you do not implement manual tracing support by emitting traces, you may not see the traces you expect. + + You can configure tracing by editing the application's configuration file—either Web.config for Web-hosted applications, or Appname.exe.config for self-hosted applications. The following is an example of such edit. For more information on these settings, see the "Configuring Trace Listeners to Consume Traces" section. + +```xml + + + - + switchValue="Information, ActivityTracing" + propagateActivity="true"> + - - - - - -``` - + initializeData= "c:\log\Traces.svclog" /> + + + + + +``` + > [!NOTE] -> To edit the configuration file of a WCF service project in Visual Studio, right click the application's configuration file—either Web.config for Web-hosted applications, or Appname.exe.config for self-hosted application in **Solution Explorer**. Then choose the **Edit WCF Configuration** context menu item. This launches the [Configuration Editor Tool (SvcConfigEditor.exe)](../../configuration-editor-tool-svcconfigeditor-exe.md), which enables you to modify configuration settings for WCF services using a graphical user interface. - -## Configuring Trace Sources to Emit Traces - - WCF defines a trace source for each assembly. Traces generated within an assembly are accessed by the listeners defined for that source. The following trace sources are defined: - -- System.ServiceModel: Logs all stages of WCF processing, whenever configuration is read, a message is processed in transport, security processing, a message is dispatched in user code, and so on. - -- System.ServiceModel.MessageLogging: Logs all messages that flow through the system. - -- System.IdentityModel. - -- System.ServiceModel.Activation. - -- System.IO.Log: Logging for the .NET Framework interface to the Common Log File System (CLFS). - -- System.Runtime.Serialization: Logs when objects are read or written. - -- CardSpace. - - You can configure each trace source to use the same (shared) listener, as indicated in the following configuration example. - -```xml - - - +> To edit the configuration file of a WCF service project in Visual Studio, right click the application's configuration file—either Web.config for Web-hosted applications, or Appname.exe.config for self-hosted application in **Solution Explorer**. Then choose the **Edit WCF Configuration** context menu item. This launches the [Configuration Editor Tool (SvcConfigEditor.exe)](../../configuration-editor-tool-svcconfigeditor-exe.md), which enables you to modify configuration settings for WCF services using a graphical user interface. + +## Configuring Trace Sources to Emit Traces + + WCF defines a trace source for each assembly. Traces generated within an assembly are accessed by the listeners defined for that source. The following trace sources are defined: + +- System.ServiceModel: Logs all stages of WCF processing, whenever configuration is read, a message is processed in transport, security processing, a message is dispatched in user code, and so on. + +- System.ServiceModel.MessageLogging: Logs all messages that flow through the system. + +- System.IdentityModel. + +- System.ServiceModel.Activation. + +- System.IO.Log: Logging for the .NET Framework interface to the Common Log File System (CLFS). + +- System.Runtime.Serialization: Logs when objects are read or written. + +- CardSpace. + + You can configure each trace source to use the same (shared) listener, as indicated in the following configuration example. + +```xml + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -``` - - In addition, you can add user-defined trace sources, as demonstrated by the following example, to emit user code traces. - -```xml - - - - - - - - + switchValue="Information, ActivityTracing" + propagateActivity="true"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +``` + + In addition, you can add user-defined trace sources, as demonstrated by the following example, to emit user code traces. + +```xml + + + + + + + + - -``` - - For more information about creating user-defined trace sources, see [Extending Tracing](../../samples/extending-tracing.md). - -## Configuring Trace Listeners to Consume Traces - - At run time, WCF feeds trace data to the listeners, which process the data. WCF provides several predefined listeners for , which differ in the format they use for output. You can also add custom listener types. - - You can use `add` to specify the name and type of the trace listener you want to use. In our example configuration, we named the Listener `traceListener` and added the standard .NET Framework trace listener (`System.Diagnostics.XmlWriterTraceListener`) as the type we want to use. You can add any number of trace listeners for each source. If the trace listener emits the trace to a file, you must specify the output file location and name in the configuration file. This is done by setting `initializeData` to the name of the file for that listener. If you do not specify a file name, a random file name is generated based on the listener type used. If is used, a file name with no extension is generated. If you implement a custom listener, you can also use this attribute to receive initialization data other than a filename. For example, you can specify a database identifier for this attribute. - - You can configure a custom trace listener to send traces on the wire, for example, to a remote database. As an application deployer, you should enforce proper access control on the trace logs in the remote machine. - - You can also configure a trace listener programmatically. For more information, see [How to: Create and Initialize Trace Listeners](../../../debug-trace-profile/how-to-create-and-initialize-trace-listeners.md) and [Creating a Custom TraceListener](/archive/msdn-magazine/2006/april/clr-inside-out-extending-system-diagnostics). - + +``` + + For more information about creating user-defined trace sources, see [Extending Tracing](../../samples/extending-tracing.md). + +## Configuring Trace Listeners to Consume Traces + + At runtime, WCF feeds trace data to the listeners, which process the data. WCF provides several predefined listeners for , which differ in the format they use for output. You can also add custom listener types. + + You can use `add` to specify the name and type of the trace listener you want to use. In our example configuration, we named the Listener `traceListener` and added the standard .NET Framework trace listener (`System.Diagnostics.XmlWriterTraceListener`) as the type we want to use. You can add any number of trace listeners for each source. If the trace listener emits the trace to a file, you must specify the output file location and name in the configuration file. This is done by setting `initializeData` to the name of the file for that listener. If you do not specify a file name, a random file name is generated based on the listener type used. If is used, a file name with no extension is generated. If you implement a custom listener, you can also use this attribute to receive initialization data other than a filename. For example, you can specify a database identifier for this attribute. + + You can configure a custom trace listener to send traces on the wire, for example, to a remote database. As an application deployer, you should enforce proper access control on the trace logs in the remote machine. + + You can also configure a trace listener programmatically. For more information, see [How to: Create and Initialize Trace Listeners](../../../debug-trace-profile/how-to-create-and-initialize-trace-listeners.md) and [Creating a Custom TraceListener](/archive/msdn-magazine/2006/april/clr-inside-out-extending-system-diagnostics). + > [!CAUTION] -> Because `System.Diagnostics.XmlWriterTraceListener` is not thread-safe, the trace source may lock resources exclusively when outputting traces. When many threads output traces to a trace source configured to use this listener, resource contention may occur, which results in a significant performance issue. To resolve this problem, you should implement a custom listener that is thread-safe. - -## Trace Level - - The tracing level is controlled by the `switchValue` setting of the trace source. The available tracing levels are described in the following table. - -|Trace Level|Nature of the Tracked Events|Content of the Tracked Events|Tracked Events|User Target| -|-----------------|----------------------------------|-----------------------------------|--------------------|-----------------| -|Off|N/A|N/A|No traces are emitted.|N/A| -|Critical|"Negative" events: events that indicate an unexpected processing or an error condition.||Unhandled exceptions including the following are logged:

- OutOfMemoryException
- ThreadAbortException (the CLR invokes any ThreadAbortExceptionHandler)
- StackOverflowException (cannot be caught)
- ConfigurationErrorsException
- SEHException
- Application start errors
- Failfast events
- System hangs
- Poison messages: message traces that cause the application to fail.|Administrators

Application developers| -|Error|"Negative" events: events that indicate an unexpected processing or an error condition.|Unexpected processing has happened. The application was not able to perform a task as expected. However, the application is still up and running.|All exceptions are logged.|Administrators

Application developers| -|Warning|"Negative" events: events that indicate an unexpected processing or an error condition.|A possible problem has occurred or may occur, but the application still functions correctly. However, it may not continue to work properly.|- The application is receiving more requests than its throttling settings allow.
- The receiving queue is near its maximum configured capacity.
- Timeout has exceeded.
- Credentials are rejected.|Administrators

Application developers| -|Information|"Positive" events: events that mark successful milestones|Important and successful milestones of application execution, regardless of whether the application is working properly or not.|In general, messages helpful for monitoring and diagnosing system status, measuring performance or profiling are generated. You can use such information for capacity planning and performance management:

- Channels are created.
- Endpoint listeners are created.
- Message enters/leaves transport.
- Security token is retrieved.
- Configuration setting is read.|Administrators

Application developers

Product developers.| -|Verbose|"Positive" events: events that mark successful milestones.|Low-level events for both user code and servicing are emitted.|In general, you can use this level for debugging or application optimization.

- Understood message header.|Administrators

Application developers

Product developers.| -|ActivityTracing||Flow events between processing activities and components.|This level allows administrators and developers to correlate applications in the same application domain:

- Traces for activity boundaries, such as start/stop.
- Traces for transfers.|All| -|All||Application may function properly. All events are emitted.|All previous events.|All| - - The levels from Verbose to Critical are stacked on top of each other, that is, each trace level includes all levels above it except the Off level. For example, a listener listening at the Warning level receives Critical, Error, and Warning traces. The All level includes events from Verbose to Critical and Activity tracing events. - +> Because `System.Diagnostics.XmlWriterTraceListener` is not thread-safe, the trace source may lock resources exclusively when outputting traces. When many threads output traces to a trace source configured to use this listener, resource contention may occur, which results in a significant performance issue. To resolve this problem, you should implement a custom listener that is thread-safe. + +## Trace Level + + The tracing level is controlled by the `switchValue` setting of the trace source. The available tracing levels are described in the following table. + +|Trace Level|Nature of the Tracked Events|Content of the Tracked Events|Tracked Events|User Target| +|-----------------|----------------------------------|-----------------------------------|--------------------|-----------------| +|Off|N/A|N/A|No traces are emitted.|N/A| +|Critical|"Negative" events: events that indicate an unexpected processing or an error condition.||Unhandled exceptions including the following are logged:

- OutOfMemoryException
- ThreadAbortException (the CLR invokes any ThreadAbortExceptionHandler)
- StackOverflowException (cannot be caught)
- ConfigurationErrorsException
- SEHException
- Application start errors
- Failfast events
- System hangs
- Poison messages: message traces that cause the application to fail.|Administrators

Application developers| +|Error|"Negative" events: events that indicate an unexpected processing or an error condition.|Unexpected processing has happened. The application was not able to perform a task as expected. However, the application is still up and running.|All exceptions are logged.|Administrators

Application developers| +|Warning|"Negative" events: events that indicate an unexpected processing or an error condition.|A possible problem has occurred or may occur, but the application still functions correctly. However, it may not continue to work properly.|- The application is receiving more requests than its throttling settings allow.
- The receiving queue is near its maximum configured capacity.
- Timeout has exceeded.
- Credentials are rejected.|Administrators

Application developers| +|Information|"Positive" events: events that mark successful milestones|Important and successful milestones of application execution, regardless of whether the application is working properly or not.|In general, messages helpful for monitoring and diagnosing system status, measuring performance or profiling are generated. You can use such information for capacity planning and performance management:

- Channels are created.
- Endpoint listeners are created.
- Message enters/leaves transport.
- Security token is retrieved.
- Configuration setting is read.|Administrators

Application developers

Product developers.| +|Verbose|"Positive" events: events that mark successful milestones.|Low-level events for both user code and servicing are emitted.|In general, you can use this level for debugging or application optimization.

- Understood message header.|Administrators

Application developers

Product developers.| +|ActivityTracing||Flow events between processing activities and components.|This level allows administrators and developers to correlate applications in the same application domain:

- Traces for activity boundaries, such as start/stop.
- Traces for transfers.|All| +|All||Application may function properly. All events are emitted.|All previous events.|All| + + The levels from Verbose to Critical are stacked on top of each other, that is, each trace level includes all levels above it except the Off level. For example, a listener listening at the Warning level receives Critical, Error, and Warning traces. The All level includes events from Verbose to Critical and Activity tracing events. + > [!CAUTION] -> The Information, Verbose, and ActivityTracing levels generate a lot of traces, which may negatively impact message throughput if you have used up all available resources on the machine. - -## Configuring Activity Tracing and Propagation for Correlation +> The Information, Verbose, and ActivityTracing levels generate a lot of traces, which may negatively impact message throughput if you have used up all available resources on the machine. + +## Configuring Activity Tracing and Propagation for Correlation + + The `activityTracing` value specified for the `switchValue` attribute is used to enable activity tracing, which emits traces for activity boundaries and transfers within endpoints. - The `activityTracing` value specified for the `switchValue` attribute is used to enable activity tracing, which emits traces for activity boundaries and transfers within endpoints. - > [!NOTE] -> When you use certain extensibility features in WCF, you might get a when activity tracing is enabled. To fix this problem, check your application's configuration file and ensure that the `switchValue` attribute for your trace source is not set to `activityTracing`. - - The `propagateActivity` attribute indicates whether the activity should be propagated to other endpoints that participate in the message exchange. By setting this value to `true`, you can take trace files generated by any two endpoints and observe how a set of traces on one endpoint flowed to a set of traces on another endpoint. - - For more information about activity tracing and propagation, see [Propagation](propagation.md). - - Both `propagateActivity` and `ActivityTracing` Boolean values apply to the System.ServiceModel TraceSource. The `ActivityTracing` value also applies to any trace source, including WCF or user-defined ones. - - You cannot use the `propagateActivity` attribute with user-defined trace sources. For user code activity ID propagation, make sure you do not set ServiceModel `ActivityTracing`, while still having ServiceModel `propagateActivity` attribute set to `true`. - +> When you use certain extensibility features in WCF, you might get a when activity tracing is enabled. To fix this problem, check your application's configuration file and ensure that the `switchValue` attribute for your trace source is not set to `activityTracing`. + + The `propagateActivity` attribute indicates whether the activity should be propagated to other endpoints that participate in the message exchange. By setting this value to `true`, you can take trace files generated by any two endpoints and observe how a set of traces on one endpoint flowed to a set of traces on another endpoint. + + For more information about activity tracing and propagation, see [Propagation](propagation.md). + + Both `propagateActivity` and `ActivityTracing` Boolean values apply to the System.ServiceModel TraceSource. The `ActivityTracing` value also applies to any trace source, including WCF or user-defined ones. + + You cannot use the `propagateActivity` attribute with user-defined trace sources. For user code activity ID propagation, make sure you do not set ServiceModel `ActivityTracing`, while still having ServiceModel `propagateActivity` attribute set to `true`. + ## See also - [Tracing](index.md) diff --git a/docs/framework/wcf/diagnostics/tracing/recommended-settings-for-tracing-and-message-logging.md b/docs/framework/wcf/diagnostics/tracing/recommended-settings-for-tracing-and-message-logging.md index 47c1073425847..32ffaea883289 100644 --- a/docs/framework/wcf/diagnostics/tracing/recommended-settings-for-tracing-and-message-logging.md +++ b/docs/framework/wcf/diagnostics/tracing/recommended-settings-for-tracing-and-message-logging.md @@ -96,7 +96,7 @@ This topic describes recommended tracing and message logging settings for differ ## Using WMI to Modify Settings - You can use WMI to change configuration settings at run time (by enabling the `wmiProviderEnabled` attribute in the configuration, as demonstrated in the previously configuration example). For example, you can use WMI within the CIM Studio to change the trace source levels from Warning to Information at run time. You should be aware that the performance cost of live debugging in this way can be very high. For more information about using WMI, see the [Using Windows Management Instrumentation for Diagnostics](../wmi/index.md) topic. + You can use WMI to change configuration settings at runtime (by enabling the `wmiProviderEnabled` attribute in the configuration, as demonstrated in the previously configuration example). For example, you can use WMI within the CIM Studio to change the trace source levels from Warning to Information at runtime. You should be aware that the performance cost of live debugging in this way can be very high. For more information about using WMI, see the [Using Windows Management Instrumentation for Diagnostics](../wmi/index.md) topic. ## Enable Correlated Events in ASP.NET Tracing diff --git a/docs/framework/wcf/diagnostics/wmi/index.md b/docs/framework/wcf/diagnostics/wmi/index.md index 74714fb471220..d638755a0164d 100644 --- a/docs/framework/wcf/diagnostics/wmi/index.md +++ b/docs/framework/wcf/diagnostics/wmi/index.md @@ -6,180 +6,180 @@ ms.assetid: fe48738d-e31b-454d-b5ec-24c85c6bf79a --- # Using Windows Management Instrumentation for Diagnostics -Windows Communication Foundation (WCF) exposes inspection data of a service at run time through a WCF Windows Management Instrumentation (WMI) provider. - -## Enabling WMI - - WMI is Microsoft's implementation of the Web-Based Enterprise Management (WBEM) standard. For more information about the WMI SDK, see [Windows Management Instrumentation](/windows/desktop/WmiSdk/wmi-start-page). WBEM is an industry standard for how applications expose management instrumentation to external management tools. - - A WMI provider is a component that exposes instrumentation at run time through a WBEM-compatible interface. It consists of a set of WMI objects that have attribute/value pairs. Pairs can be of a number of simple types. Management tools can connect to the services through the interface at run time. WCF exposes attributes of services such as addresses, bindings, behaviors, and listeners. - - The built-in WMI provider can be activated in the configuration file of the application. This is done through the `wmiProviderEnabled` attribute of the [\](../../../configure-apps/file-schema/wcf/diagnostics.md) in the [\](../../../configure-apps/file-schema/wcf/system-servicemodel.md) section, as shown in the following sample configuration. - -```xml - - … - - … - -``` - - This configuration entry exposes a WMI interface. Management applications can now connect through this interface and access the management instrumentation of the application. - -## Accessing WMI Data - - WMI data can be accessed in many different ways. Microsoft provides WMI APIs for scripts, Visual Basic applications, C++ applications, and the .NET Framework. For more information, see [Using WMI](/windows/win32/wmisdk/using-wmi). - +Windows Communication Foundation (WCF) exposes inspection data of a service at runtime through a WCF Windows Management Instrumentation (WMI) provider. + +## Enabling WMI + + WMI is Microsoft's implementation of the Web-Based Enterprise Management (WBEM) standard. For more information about the WMI SDK, see [Windows Management Instrumentation](/windows/desktop/WmiSdk/wmi-start-page). WBEM is an industry standard for how applications expose management instrumentation to external management tools. + + A WMI provider is a component that exposes instrumentation at runtime through a WBEM-compatible interface. It consists of a set of WMI objects that have attribute/value pairs. Pairs can be of a number of simple types. Management tools can connect to the services through the interface at runtime. WCF exposes attributes of services such as addresses, bindings, behaviors, and listeners. + + The built-in WMI provider can be activated in the configuration file of the application. This is done through the `wmiProviderEnabled` attribute of the [\](../../../configure-apps/file-schema/wcf/diagnostics.md) in the [\](../../../configure-apps/file-schema/wcf/system-servicemodel.md) section, as shown in the following sample configuration. + +```xml + + … + + … + +``` + + This configuration entry exposes a WMI interface. Management applications can now connect through this interface and access the management instrumentation of the application. + +## Accessing WMI Data + + WMI data can be accessed in many different ways. Microsoft provides WMI APIs for scripts, Visual Basic applications, C++ applications, and the .NET Framework. For more information, see [Using WMI](/windows/win32/wmisdk/using-wmi). + > [!CAUTION] -> If you use the .NET Framework provided methods to programmatically access WMI data, you should be aware that such methods may throw exceptions when the connection is established. The connection is not established during the construction of the instance, but on the first request involving actual data exchange. Therefore, you should use a `try..catch` block to catch the possible exceptions. - - You can change the trace and message logging level, as well as message logging options for the `System.ServiceModel` trace source in WMI. This can be done by accessing the [AppDomainInfo](appdomaininfo.md) instance, which exposes these Boolean properties: `LogMessagesAtServiceLevel`, `LogMessagesAtTransportLevel`, `LogMalformedMessages`, and `TraceLevel`. Therefore, if you configure a trace listener for message logging, but set these options to `false` in configuration, you can later change them to `true` when the application is running. This will effectively enable message logging at run time. Similarly, if you enable message logging in your configuration file, you can disable it at run time using WMI. - - You should be aware that if no message logging trace listeners for message logging, or no `System.ServiceModel` trace listeners for tracing are specified in the configuration file, none of your changes are taken into effect, even though the changes are accepted by WMI. For more information on properly setting up the respective listeners, see [Configuring Message Logging](../configuring-message-logging.md) and [Configuring Tracing](../tracing/configuring-tracing.md). The trace level of all other trace sources specified by configuration is effective when the application starts, and cannot be changed. - - WCF exposes a `GetOperationCounterInstanceName` method for scripting. This method returns a performance counter instance name if you provide it with an operation name. However, it does not validate your input. Therefore, if you provide an incorrect operation name, an incorrect counter name is returned. - - The `OutgoingChannel` property of the `Service` instance does not count channels opened by a service to connect to another service, if the WCF client to the destination service is not created within the `Service` method. - - **Caution** WMI only supports a value up to 3 decimal points. For example, if your service sets one of its properties to , its value is truncated after 3 decimal points when viewed through WMI. - -## Security - - Because the WCF WMI provider allows the discovery of services in an environment, you should exercise extreme caution for granting access to it. If you relax the default administrator-only access, you may allow less-trusted parties access to sensitive data in your environment. Specifically, if you loosen permissions on remote WMI access, flooding attacks can occur. If a process is flooded by excessive WMI requests, its performance can be degraded. - - In addition, if you relax access permissions for the MOF file, less-trusted parties can manipulate the behavior of WMI and alter the objects that are loaded in the WMI schema. For example, fields can be removed such that critical data is concealed from the administrator or that fields that do not populate or cause exceptions are added to the file. - - By default, the WCF WMI provider grants "execute method", "provider write", and "enable account" permission for Administrator, and "enable account" permission for ASP.NET, Local Service and Network Service. In particular, on non-Windows Vista platforms, the ASP.NET account has read access to the WMI ServiceModel namespace. If you do not want to grant these privileges to a particular user group, you should either deactivate the WMI provider (it is disabled by default), or disable access for the specific user group. - - In addition, when you attempt to enable WMI through configuration, WMI may not be enabled due to insufficient user privilege. However, no event is written to the event log to record this failure. - - To modify user privilege levels, use the following steps. - -1. Click Start and then Run and type **compmgmt.msc**. - -2. Right-click **Services and Application/WMI Controls** to select **Properties**. - -3. Select the **Security** Tab, and navigate to the **Root/ServiceModel** namespace. Click the **Security** button. - -4. Select the specific group or user that you want to control access and use the **Allow** or **Deny** checkbox to configure permissions. - -## Granting WCF WMI Registration Permissions to Additional Users - - WCF exposes management data to WMI. It does so by hosting an in-process WMI provider, sometimes called a "decoupled provider". For the management data to be exposed, the account that registers this provider must have the appropriate permissions. In Windows, only a small set of privileged accounts can register decoupled providers by default. This is a problem because users commonly want to expose WMI data from a WCF service running under an account that is not in the default set. - - To provide this access, an administrator must grant the following permissions to the additional account in the following order: - -1. Permission to access to the WCF WMI Namespace. - -2. Permission to register the WCF Decoupled WMI Provider. - -#### To grant WMI namespace access permission - -1. Run the following PowerShell script. - - ```powershell - write-host "" - write-host "Granting Access to root/servicemodel WMI namespace to built in users group" - write-host "" - - # Create the binary representation of the permissions to grant in SDDL - $newPermissions = "O:BAG:BAD:P(A;CI;CCDCLCSWRPWPRCWD;;;BA)(A;CI;CC;;;NS)(A;CI;CC;;;LS)(A;CI;CC;;;BU)" - $converter = new-object system.management.ManagementClass Win32_SecurityDescriptorHelper - $binarySD = $converter.SDDLToBinarySD($newPermissions) - $convertedPermissions = ,$binarySD.BinarySD - - # Get the object used to set the permissions - $security = gwmi -namespace root/servicemodel -class __SystemSecurity - - # Get and output the current settings - $binarySD = @($null) - $result = $security.PsBase.InvokeMethod("GetSD",$binarySD) - - $outsddl = $converter.BinarySDToSDDL($binarySD[0]) - write-host "Previous ACL: "$outsddl.SDDL - - # Change the Access Control List (ACL) using SDDL +> If you use the .NET Framework provided methods to programmatically access WMI data, you should be aware that such methods may throw exceptions when the connection is established. The connection is not established during the construction of the instance, but on the first request involving actual data exchange. Therefore, you should use a `try..catch` block to catch the possible exceptions. + + You can change the trace and message logging level, as well as message logging options for the `System.ServiceModel` trace source in WMI. This can be done by accessing the [AppDomainInfo](appdomaininfo.md) instance, which exposes these Boolean properties: `LogMessagesAtServiceLevel`, `LogMessagesAtTransportLevel`, `LogMalformedMessages`, and `TraceLevel`. Therefore, if you configure a trace listener for message logging, but set these options to `false` in configuration, you can later change them to `true` when the application is running. This will effectively enable message logging at runtime. Similarly, if you enable message logging in your configuration file, you can disable it at runtime using WMI. + + You should be aware that if no message logging trace listeners for message logging, or no `System.ServiceModel` trace listeners for tracing are specified in the configuration file, none of your changes are taken into effect, even though the changes are accepted by WMI. For more information on properly setting up the respective listeners, see [Configuring Message Logging](../configuring-message-logging.md) and [Configuring Tracing](../tracing/configuring-tracing.md). The trace level of all other trace sources specified by configuration is effective when the application starts, and cannot be changed. + + WCF exposes a `GetOperationCounterInstanceName` method for scripting. This method returns a performance counter instance name if you provide it with an operation name. However, it does not validate your input. Therefore, if you provide an incorrect operation name, an incorrect counter name is returned. + + The `OutgoingChannel` property of the `Service` instance does not count channels opened by a service to connect to another service, if the WCF client to the destination service is not created within the `Service` method. + + **Caution** WMI only supports a value up to 3 decimal points. For example, if your service sets one of its properties to , its value is truncated after 3 decimal points when viewed through WMI. + +## Security + + Because the WCF WMI provider allows the discovery of services in an environment, you should exercise extreme caution for granting access to it. If you relax the default administrator-only access, you may allow less-trusted parties access to sensitive data in your environment. Specifically, if you loosen permissions on remote WMI access, flooding attacks can occur. If a process is flooded by excessive WMI requests, its performance can be degraded. + + In addition, if you relax access permissions for the MOF file, less-trusted parties can manipulate the behavior of WMI and alter the objects that are loaded in the WMI schema. For example, fields can be removed such that critical data is concealed from the administrator or that fields that do not populate or cause exceptions are added to the file. + + By default, the WCF WMI provider grants "execute method", "provider write", and "enable account" permission for Administrator, and "enable account" permission for ASP.NET, Local Service and Network Service. In particular, on non-Windows Vista platforms, the ASP.NET account has read access to the WMI ServiceModel namespace. If you do not want to grant these privileges to a particular user group, you should either deactivate the WMI provider (it is disabled by default), or disable access for the specific user group. + + In addition, when you attempt to enable WMI through configuration, WMI may not be enabled due to insufficient user privilege. However, no event is written to the event log to record this failure. + + To modify user privilege levels, use the following steps. + +1. Click Start and then Run and type **compmgmt.msc**. + +2. Right-click **Services and Application/WMI Controls** to select **Properties**. + +3. Select the **Security** Tab, and navigate to the **Root/ServiceModel** namespace. Click the **Security** button. + +4. Select the specific group or user that you want to control access and use the **Allow** or **Deny** checkbox to configure permissions. + +## Granting WCF WMI Registration Permissions to Additional Users + + WCF exposes management data to WMI. It does so by hosting an in-process WMI provider, sometimes called a "decoupled provider". For the management data to be exposed, the account that registers this provider must have the appropriate permissions. In Windows, only a small set of privileged accounts can register decoupled providers by default. This is a problem because users commonly want to expose WMI data from a WCF service running under an account that is not in the default set. + + To provide this access, an administrator must grant the following permissions to the additional account in the following order: + +1. Permission to access to the WCF WMI Namespace. + +2. Permission to register the WCF Decoupled WMI Provider. + +#### To grant WMI namespace access permission + +1. Run the following PowerShell script. + + ```powershell + write-host "" + write-host "Granting Access to root/servicemodel WMI namespace to built in users group" + write-host "" + + # Create the binary representation of the permissions to grant in SDDL + $newPermissions = "O:BAG:BAD:P(A;CI;CCDCLCSWRPWPRCWD;;;BA)(A;CI;CC;;;NS)(A;CI;CC;;;LS)(A;CI;CC;;;BU)" + $converter = new-object system.management.ManagementClass Win32_SecurityDescriptorHelper + $binarySD = $converter.SDDLToBinarySD($newPermissions) + $convertedPermissions = ,$binarySD.BinarySD + + # Get the object used to set the permissions + $security = gwmi -namespace root/servicemodel -class __SystemSecurity + + # Get and output the current settings + $binarySD = @($null) + $result = $security.PsBase.InvokeMethod("GetSD",$binarySD) + + $outsddl = $converter.BinarySDToSDDL($binarySD[0]) + write-host "Previous ACL: "$outsddl.SDDL + + # Change the Access Control List (ACL) using SDDL $result = $security.PsBase.InvokeMethod("SetSD",$convertedPermissions) - - # Get and output the current settings - $binarySD = @($null) - $result = $security.PsBase.InvokeMethod("GetSD",$binarySD) - - $outsddl = $converter.BinarySDToSDDL($binarySD[0]) - write-host "New ACL: "$outsddl.SDDL - write-host "" - ``` - - This PowerShell script uses Security Descriptor Definition Language (SDDL) to grant the Built-In Users group access to the "root/servicemodel" WMI namespace. It specifies the following ACLs: - - - Built-In Administrator (BA) - Already Had Access. - - - Network Service (NS) - Already Had Access. - - - Local System (LS) - Already Had Access. - - - Built-In Users - The group to grant access to. - -#### To grant provider registration access - -1. Run the following PowerShell script. - - ```powershell - write-host "" - write-host "Granting WCF provider registration access to built in users group" - write-host "" - # Set security on ServiceModel provider - $provider = get-WmiObject -namespace "root\servicemodel" __Win32Provider - - write-host "Previous ACL: "$provider.SecurityDescriptor - $result = $provider.SecurityDescriptor = "O:BUG:BUD:(A;;0x1;;;BA)(A;;0x1;;;NS)(A;;0x1;;;LS)(A;;0x1;;;BU)" - - # Commit the changes and display it to the console - $result = $provider.Put() - write-host "New ACL: "$provider.SecurityDescriptor - write-host "" - ``` - -### Granting Access to Arbitrary Users or Groups - - The example in this section grants WMI Provider registration privileges to all local users. If you want to grant access to a user or group that is not built in, then you must obtain that user or group's Security Identifier (SID). There is no simple way to get the SID for an arbitrary user. One method is to log on as the desired user and then issue the following shell command. - + + # Get and output the current settings + $binarySD = @($null) + $result = $security.PsBase.InvokeMethod("GetSD",$binarySD) + + $outsddl = $converter.BinarySDToSDDL($binarySD[0]) + write-host "New ACL: "$outsddl.SDDL + write-host "" + ``` + + This PowerShell script uses Security Descriptor Definition Language (SDDL) to grant the Built-In Users group access to the "root/servicemodel" WMI namespace. It specifies the following ACLs: + + - Built-In Administrator (BA) - Already Had Access. + + - Network Service (NS) - Already Had Access. + + - Local System (LS) - Already Had Access. + + - Built-In Users - The group to grant access to. + +#### To grant provider registration access + +1. Run the following PowerShell script. + + ```powershell + write-host "" + write-host "Granting WCF provider registration access to built in users group" + write-host "" + # Set security on ServiceModel provider + $provider = get-WmiObject -namespace "root\servicemodel" __Win32Provider + + write-host "Previous ACL: "$provider.SecurityDescriptor + $result = $provider.SecurityDescriptor = "O:BUG:BUD:(A;;0x1;;;BA)(A;;0x1;;;NS)(A;;0x1;;;LS)(A;;0x1;;;BU)" + + # Commit the changes and display it to the console + $result = $provider.Put() + write-host "New ACL: "$provider.SecurityDescriptor + write-host "" + ``` + +### Granting Access to Arbitrary Users or Groups + + The example in this section grants WMI Provider registration privileges to all local users. If you want to grant access to a user or group that is not built in, then you must obtain that user or group's Security Identifier (SID). There is no simple way to get the SID for an arbitrary user. One method is to log on as the desired user and then issue the following shell command. + ```console -Whoami /user -``` - -For more information, see [Well Known SIDs](/troubleshoot/windows-server/identity/security-identifiers-in-windows). - -## Accessing Remote WMI Object Instances - - If you need to access WCF WMI instances on a remote machine, you must enable packet privacy on the tools that you use for access. The following section describes how to achieve these using the WMI CIM Studio, Windows Management Instrumentation Tester, as well as .NET SDK 2.0. - +Whoami /user +``` + +For more information, see [Well Known SIDs](/troubleshoot/windows-server/identity/security-identifiers-in-windows). + +## Accessing Remote WMI Object Instances + + If you need to access WCF WMI instances on a remote machine, you must enable packet privacy on the tools that you use for access. The following section describes how to achieve these using the WMI CIM Studio, Windows Management Instrumentation Tester, as well as .NET SDK 2.0. + ### WMI CIM Studio If you've installed WMI Administrative Tools, you can use the WMI CIM Studio to access WMI instances. The tools are in the following folder: - + *%windir%\Program Files\WMI Tools\\* - -1. In the **Connect to namespace:** window, type **root\ServiceModel** and click **OK.** - -2. In the **WMI CIM Studio Login** window, click the **Options >>** button to expand the window. Select **Packet privacy** for **Authentication level**, and click **OK**. - -### Windows Management Instrumentation Tester - - This tool is installed by Windows. To run it, launch a command console by typing **cmd.exe** in the **Start/Run** dialog box and click **OK**. Then, type **wbemtest.exe** in the command window. The Windows Management Instrumentation Tester tool is then launched. - -1. Click the **Connect** button on the top right corner of the window. - -2. In the new window, enter **root\ServiceModel** for the **Namespace** field, and select **Packet privacy** for **Authentication level**. Click **Connect**. - -### Using Managed Code - - You can also access remote WMI instances programmatically by using classes provided by the namespace. The following code sample demonstrates how to do this. - + +1. In the **Connect to namespace:** window, type **root\ServiceModel** and click **OK.** + +2. In the **WMI CIM Studio Login** window, click the **Options >>** button to expand the window. Select **Packet privacy** for **Authentication level**, and click **OK**. + +### Windows Management Instrumentation Tester + + This tool is installed by Windows. To run it, launch a command console by typing **cmd.exe** in the **Start/Run** dialog box and click **OK**. Then, type **wbemtest.exe** in the command window. The Windows Management Instrumentation Tester tool is then launched. + +1. Click the **Connect** button on the top right corner of the window. + +2. In the new window, enter **root\ServiceModel** for the **Namespace** field, and select **Packet privacy** for **Authentication level**. Click **Connect**. + +### Using Managed Code + + You can also access remote WMI instances programmatically by using classes provided by the namespace. The following code sample demonstrates how to do this. + ```csharp String wcfNamespace = $@"\\{this.serviceMachineName}\Root\ServiceModel"); - -ConnectionOptions connection = new ConnectionOptions(); -connection.Authentication = AuthenticationLevel.PacketPrivacy; -ManagementScope scope = new ManagementScope(this.wcfNamespace, connection); + +ConnectionOptions connection = new ConnectionOptions(); +connection.Authentication = AuthenticationLevel.PacketPrivacy; +ManagementScope scope = new ManagementScope(this.wcfNamespace, connection); ``` diff --git a/docs/framework/wcf/extending/configuring-and-extending-the-runtime-with-behaviors.md b/docs/framework/wcf/extending/configuring-and-extending-the-runtime-with-behaviors.md index c75f93bb3c478..4288d3bbe8a12 100644 --- a/docs/framework/wcf/extending/configuring-and-extending-the-runtime-with-behaviors.md +++ b/docs/framework/wcf/extending/configuring-and-extending-the-runtime-with-behaviors.md @@ -2,253 +2,253 @@ title: "Configuring and Extending the Runtime with Behaviors" description: Learn how to implement behavior interfaces in WCF apps and add them to a service description or endpoint, either programmatically or in a configuration file. ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "attaching extensions using behaviors [WCF]" ms.assetid: 149b99b6-6eb6-4f45-be22-c967279677d9 --- # Configuring and Extending the Runtime with Behaviors -Behaviors enable you to modify default behavior and add custom extensions that inspect and validate service configuration or modify runtime behavior in Windows Communication Foundation (WCF) client and service applications. This topic describes the behavior interfaces, how to implement them, and how to add them to the service description (in a service application) or endpoint (in a client application) programmatically or in a configuration file. For more information about using system-provided behaviors, see [Specifying Service Run-Time Behavior](../specifying-service-run-time-behavior.md) and [Specifying Client Run-Time Behavior](../specifying-client-run-time-behavior.md). - -## Behaviors - - Behavior types are added to the service or service endpoint description objects (on the service or client, respectively) before those objects are used by Windows Communication Foundation (WCF) to create a runtime that executes a WCF service or a WCF client. When these behaviors are called during the runtime construction process they are then able to access runtime properties and methods that modify the runtime constructed by the contract, bindings, and addresses. - -### Behavior Methods - - All behaviors have an `AddBindingParameters` method, an `ApplyDispatchBehavior` method, a `Validate` method, and an `ApplyClientBehavior` method with one exception: Because cannot execute in a client, it does not implement `ApplyClientBehavior`. - -- Use the `AddBindingParameters` method to modify or add custom objects to a collection that custom bindings can access for their use when the runtime is constructed. For example, this how protection requirements are specified that affect the way the channel is built, but are not known by the channel developer. - -- Use the `Validate` method to examine the description tree and corresponding runtime object to ensure it conforms to some set of criteria. - -- Use the `ApplyDispatchBehavior` and `ApplyClientBehavior` methods to examine the description tree and modify the runtime for a particular scope on either the service or the client. You can also insert extension objects as well. - +Behaviors enable you to modify default behavior and add custom extensions that inspect and validate service configuration or modify runtime behavior in Windows Communication Foundation (WCF) client and service applications. This topic describes the behavior interfaces, how to implement them, and how to add them to the service description (in a service application) or endpoint (in a client application) programmatically or in a configuration file. For more information about using system-provided behaviors, see [Specifying Service Run-Time Behavior](../specifying-service-run-time-behavior.md) and [Specifying Client Run-Time Behavior](../specifying-client-run-time-behavior.md). + +## Behaviors + + Behavior types are added to the service or service endpoint description objects (on the service or client, respectively) before those objects are used by Windows Communication Foundation (WCF) to create a runtime that executes a WCF service or a WCF client. When these behaviors are called during the runtime construction process they are then able to access runtime properties and methods that modify the runtime constructed by the contract, bindings, and addresses. + +### Behavior Methods + + All behaviors have an `AddBindingParameters` method, an `ApplyDispatchBehavior` method, a `Validate` method, and an `ApplyClientBehavior` method with one exception: Because cannot execute in a client, it does not implement `ApplyClientBehavior`. + +- Use the `AddBindingParameters` method to modify or add custom objects to a collection that custom bindings can access for their use when the runtime is constructed. For example, this how protection requirements are specified that affect the way the channel is built, but are not known by the channel developer. + +- Use the `Validate` method to examine the description tree and corresponding runtime object to ensure it conforms to some set of criteria. + +- Use the `ApplyDispatchBehavior` and `ApplyClientBehavior` methods to examine the description tree and modify the runtime for a particular scope on either the service or the client. You can also insert extension objects as well. + > [!NOTE] - > Although a description tree is provided in these methods, it is for examination only. If a description tree is modified, the behavior is undefined. - - The properties you can modify and the customization interfaces you can implement are accessed through the service and client runtime classes. The service types are the and classes. The client types are the and classes. The and classes are the extensibility entry points to access client-wide and service-wide runtime properties and extension collections, respectively. Similarly, the and classes expose client operation and service operation runtime properties and extension collections, respectively. You can, however, access the wider scoped runtime object from the operation runtime object and vice versa if need be. - + > Although a description tree is provided in these methods, it is for examination only. If a description tree is modified, the behavior is undefined. + + The properties you can modify and the customization interfaces you can implement are accessed through the service and client runtime classes. The service types are the and classes. The client types are the and classes. The and classes are the extensibility entry points to access client-wide and service-wide runtime properties and extension collections, respectively. Similarly, the and classes expose client operation and service operation runtime properties and extension collections, respectively. You can, however, access the wider scoped runtime object from the operation runtime object and vice versa if need be. + > [!NOTE] -> For a discussion of runtime properties and extension types that you can use to modify the execution behavior of a client, see [Extending Clients](extending-clients.md). For a discussion of runtime properties and extension types that you can use to modify the execution behavior of a service dispatcher, see [Extending Dispatchers](extending-dispatchers.md). - - Most WCF users do not interact with the runtime directly; instead they use core programming model constructs like endpoints, contracts, bindings, addresses, and behavior attributes on classes or behaviors in configuration files. These constructs make up the *description tree*, which is the complete specification for constructing a runtime to support a service or client described by the description tree. - - There are four kinds of behaviors in WCF: - -- Service behaviors ( types) enable the customization of the entire service runtime including . - -- Endpoint behaviors ( types) enable the customization of service endpoints and their associated objects. - -- Contract behaviors ( types) enable the customization of both the and classes in client and service applications, respectively. - -- Operation behaviors ( types) enable the customization of the and classes, again, on the client and service. - - You can add these behaviors to the various description objects by implementing custom attributes, using application configuration files, or directly by adding them to the behaviors collection on the appropriate description object. The must, however, be added to a service description or service endpoint description object prior to calling on the or a . - -### Behavior Scopes - - There are four behavior types, each of which corresponds to a particular scope of runtime access. - -#### Service Behaviors - - Service behaviors, which implement , are the primary mechanism by which you modify the entire service runtime. There are three mechanisms for adding service behaviors to a service. - -1. Using an attribute on the service class. When a is constructed, the implementation uses reflection to discover the set of attributes on the type of the service. If any of those attributes are implementations of , they are added to the behaviors collection on . This allows those behaviors to participate in the construction of the service run time. - -2. Programmatically adding the behavior to the behaviors collection on . This can be accomplished with the following lines of code: - +> For a discussion of runtime properties and extension types that you can use to modify the execution behavior of a client, see [Extending Clients](extending-clients.md). For a discussion of runtime properties and extension types that you can use to modify the execution behavior of a service dispatcher, see [Extending Dispatchers](extending-dispatchers.md). + + Most WCF users do not interact with the runtime directly; instead they use core programming model constructs like endpoints, contracts, bindings, addresses, and behavior attributes on classes or behaviors in configuration files. These constructs make up the *description tree*, which is the complete specification for constructing a runtime to support a service or client described by the description tree. + + There are four kinds of behaviors in WCF: + +- Service behaviors ( types) enable the customization of the entire service runtime including . + +- Endpoint behaviors ( types) enable the customization of service endpoints and their associated objects. + +- Contract behaviors ( types) enable the customization of both the and classes in client and service applications, respectively. + +- Operation behaviors ( types) enable the customization of the and classes, again, on the client and service. + + You can add these behaviors to the various description objects by implementing custom attributes, using application configuration files, or directly by adding them to the behaviors collection on the appropriate description object. The must, however, be added to a service description or service endpoint description object prior to calling on the or a . + +### Behavior Scopes + + There are four behavior types, each of which corresponds to a particular scope of runtime access. + +#### Service Behaviors + + Service behaviors, which implement , are the primary mechanism by which you modify the entire service runtime. There are three mechanisms for adding service behaviors to a service. + +1. Using an attribute on the service class. When a is constructed, the implementation uses reflection to discover the set of attributes on the type of the service. If any of those attributes are implementations of , they are added to the behaviors collection on . This allows those behaviors to participate in the construction of the service runtime. + +2. Programmatically adding the behavior to the behaviors collection on . This can be accomplished with the following lines of code: + ```csharp - ServiceHost host = new ServiceHost(/* Parameters */); - host.Description.Behaviors.Add(/* Service Behavior */); - ``` - -3. Implementing a custom that extends configuration. This enables the use of the service behavior from application configuration files. - - Examples of service behaviors in WCF include the attribute, the , and the behavior. - -#### Contract Behaviors - - Contract behaviors, which implement the interface, are used to extend both the client and service runtime across a contract. - - There are two mechanisms for adding contract behaviors to a contract. The first mechanism is to create a custom attribute to be used on the contract interface. When a contract interface is passed to either a or a , WCF examines the attributes on the interface. If any attributes are implementations of , those are added to the behaviors collection on the created for that interface. - - You can also implement the on the custom contract behavior attribute. In this case, the behavior is as follows when applied to: - - •A contract interface. In this case, the behavior is applied to all contracts of that type in any endpoint and WCF ignores the value of the property. - - •A service class. In this case, the behavior is applied only to endpoints the contract of which is the value of the property. - - •A callback class. In this case, the behavior is applied to the duplex client's endpoint and WCF ignores the value of the property. - - The second mechanism is to add the behavior to the behaviors collection on a . - - Examples of contract behaviors in WCF include the attribute. For more information and an example, see the reference topic. - -#### Endpoint Behaviors - - Endpoint behaviors, which implement , are the primary mechanism by which you modify the entire service or client run time for a specific endpoint. - - There are two mechanisms for adding endpoint behaviors to a service. - -1. Add the behavior to the property. - -2. Implement a custom that extends configuration. - - For more information and an example, see the reference topic. - -#### Operation Behaviors - - Operation behaviors, which implement the interface, are used to extend both the client and service runtime for each operation. - - There are two mechanisms for adding operation behaviors to an operation. The first mechanism is to create a custom attribute to be used on the method that models the operation. When an operation is added to either a or a , WCF adds any attributes to the behaviors collection on the created for that operation. - - The second mechanism is by directly adding the behavior to the behaviors collection on a constructed . - - Examples of operation behaviors in WCF include the and the . - - For more information and an example, see the reference topic. - -### Using Configuration to Create Behaviors - - Service and endpoint, and contract behaviors can by designed to be specified in code or using attributes; only service and endpoint behaviors can be configured using application or Web configuration files. Exposing behaviors using attributes allows developers to specify a behavior at compilation-time that cannot be added, removed, or modified at run time. This is often suitable for behaviors that are always required for the correct operation of a service (for example, the transaction-related parameters to the attribute). Exposing behaviors using configuration allows developers to leave the specification and configuration of those behaviors to those who deploy the service. This is suitable for behaviors that are optional components or other deployment-specific configuration, such as whether metadata is exposed for the service or the particular authorization configuration for a service. - + ServiceHost host = new ServiceHost(/* Parameters */); + host.Description.Behaviors.Add(/* Service Behavior */); + ``` + +3. Implementing a custom that extends configuration. This enables the use of the service behavior from application configuration files. + + Examples of service behaviors in WCF include the attribute, the , and the behavior. + +#### Contract Behaviors + + Contract behaviors, which implement the interface, are used to extend both the client and service runtime across a contract. + + There are two mechanisms for adding contract behaviors to a contract. The first mechanism is to create a custom attribute to be used on the contract interface. When a contract interface is passed to either a or a , WCF examines the attributes on the interface. If any attributes are implementations of , those are added to the behaviors collection on the created for that interface. + + You can also implement the on the custom contract behavior attribute. In this case, the behavior is as follows when applied to: + + •A contract interface. In this case, the behavior is applied to all contracts of that type in any endpoint and WCF ignores the value of the property. + + •A service class. In this case, the behavior is applied only to endpoints the contract of which is the value of the property. + + •A callback class. In this case, the behavior is applied to the duplex client's endpoint and WCF ignores the value of the property. + + The second mechanism is to add the behavior to the behaviors collection on a . + + Examples of contract behaviors in WCF include the attribute. For more information and an example, see the reference topic. + +#### Endpoint Behaviors + + Endpoint behaviors, which implement , are the primary mechanism by which you modify the entire service or client runtime for a specific endpoint. + + There are two mechanisms for adding endpoint behaviors to a service. + +1. Add the behavior to the property. + +2. Implement a custom that extends configuration. + + For more information and an example, see the reference topic. + +#### Operation Behaviors + + Operation behaviors, which implement the interface, are used to extend both the client and service runtime for each operation. + + There are two mechanisms for adding operation behaviors to an operation. The first mechanism is to create a custom attribute to be used on the method that models the operation. When an operation is added to either a or a , WCF adds any attributes to the behaviors collection on the created for that operation. + + The second mechanism is by directly adding the behavior to the behaviors collection on a constructed . + + Examples of operation behaviors in WCF include the and the . + + For more information and an example, see the reference topic. + +### Using Configuration to Create Behaviors + + Service and endpoint, and contract behaviors can by designed to be specified in code or using attributes; only service and endpoint behaviors can be configured using application or Web configuration files. Exposing behaviors using attributes allows developers to specify a behavior at compilation-time that cannot be added, removed, or modified at runtime. This is often suitable for behaviors that are always required for the correct operation of a service (for example, the transaction-related parameters to the attribute). Exposing behaviors using configuration allows developers to leave the specification and configuration of those behaviors to those who deploy the service. This is suitable for behaviors that are optional components or other deployment-specific configuration, such as whether metadata is exposed for the service or the particular authorization configuration for a service. + > [!NOTE] -> You can also use behaviors that support configuration to enforce company application policies by inserting them into the machine.config configuration file and locking those items down. For a description and an example, see [How to: Lock Down Endpoints in the Enterprise](how-to-lock-down-endpoints-in-the-enterprise.md). - - To expose a behavior using configuration, a developer must create a derived class of and then register that extension with configuration. - - The following code example shows how an implements : - +> You can also use behaviors that support configuration to enforce company application policies by inserting them into the machine.config configuration file and locking those items down. For a description and an example, see [How to: Lock Down Endpoints in the Enterprise](how-to-lock-down-endpoints-in-the-enterprise.md). + + To expose a behavior using configuration, a developer must create a derived class of and then register that extension with configuration. + + The following code example shows how an implements : + ```csharp -// BehaviorExtensionElement members -public override Type BehaviorType -{ - get { return typeof(EndpointBehaviorMessageInspector); } -} - -protected override object CreateBehavior() -{ - return new EndpointBehaviorMessageInspector(); -} -``` - - In order for the configuration system to load a custom , it must be registered as an extension. The following code example shows the configuration file for the preceding endpoint behavior: - -```xml - - - +// BehaviorExtensionElement members +public override Type BehaviorType +{ + get { return typeof(EndpointBehaviorMessageInspector); } +} + +protected override object CreateBehavior() +{ + return new EndpointBehaviorMessageInspector(); +} +``` + + In order for the configuration system to load a custom , it must be registered as an extension. The following code example shows the configuration file for the preceding endpoint behavior: + +```xml + + + - - - - - - + + + + + + - - - - - - - - - - - - - - - - - + contract="Microsoft.WCF.Documentation.ISampleService" + /> + + + + + + + + + + + + + + + + + - - - - -``` - - Where `Microsoft.WCF.Documentation.EndpointBehaviorMessageInspector` is the behavior extension type and `HostApplication` is the name of the assembly into which that class has been compiled. - -### Evaluation Order - - The and the are responsible for building the runtime from the programming model and description. Behaviors, as previously described, contribute to that build process at the service, endpoint, contract, and operation. - - The applies behaviors in the following order: - -1. Service - -2. Contract - -3. Endpoint - -4. Operation - - Within any collection of behaviors, no order is guaranteed. - - The applies behaviors in the following order: - -1. Contract - -2. Endpoint - -3. Operation - - Within any collection of behaviors, again, no order is guaranteed. - -### Adding Behaviors Programmatically - - Properties of the in the service application must not be modified subsequent to the method on . Some members, like the property and the `AddServiceEndpoint` methods on and , throw an exception if modified past that point. Others permit you to modify them, but the result is undefined. - - Similarly, on the client the values must not be modified after the call to on the . The property throws an exception if modified past that point, but the other client description values can be modified without error. The result, however, is undefined. - - Whether for the service or client, it is recommended that you modify the description prior to calling . - -### Inheritance Rules for Behavior Attributes - - All four types of behaviors can be populated using attributes – service behaviors and contract behaviors. Because attributes are defined on managed objects and members, and managed objects and members support inheritance, it is necessary to define how behavior attributes work in the context of inheritance. - - At a high level, the rule is that for a particular scope (for example, service, contract, or operation), all behavior attributes in the inheritance hierarchy for that scope are applied. If there are two behavior attributes of the same type, only the most-derived type is used. - -#### Service Behaviors - - For a given service class, all service behavior attributes on that class, and on parents of that class, are applied. If the same type of attribute is applied at multiple places in the inheritance hierarchy, the most-derived type is used. - -```csharp -[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)] -[AspNetCompatibilityRequirementsAttribute( - AspNetCompatibilityRequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] -public class A { /* … */ } - -[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] -public class B : A { /* … */} -``` - - For example, in the preceding case, the service B ends up with an of , an mode of , and a of . The is , because attribute on service B is on "more derived" than that on service A. - -#### Contract Behaviors - - For a given contract, all contract behavior attributes on that interface and on parents of that interface, are applied. If the same type of attribute is applied at multiple places in the inheritance hierarchy, the most-derived type is used. - -#### Operation Behaviors - - If a given operation does not override an existing abstract or virtual operation, no inheritance rules apply. - + name="endpointMessageInspector" + type="Microsoft.WCF.Documentation.EndpointBehaviorMessageInspector, HostApplication, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" + /> + + + + +``` + + Where `Microsoft.WCF.Documentation.EndpointBehaviorMessageInspector` is the behavior extension type and `HostApplication` is the name of the assembly into which that class has been compiled. + +### Evaluation Order + + The and the are responsible for building the runtime from the programming model and description. Behaviors, as previously described, contribute to that build process at the service, endpoint, contract, and operation. + + The applies behaviors in the following order: + +1. Service + +2. Contract + +3. Endpoint + +4. Operation + + Within any collection of behaviors, no order is guaranteed. + + The applies behaviors in the following order: + +1. Contract + +2. Endpoint + +3. Operation + + Within any collection of behaviors, again, no order is guaranteed. + +### Adding Behaviors Programmatically + + Properties of the in the service application must not be modified subsequent to the method on . Some members, like the property and the `AddServiceEndpoint` methods on and , throw an exception if modified past that point. Others permit you to modify them, but the result is undefined. + + Similarly, on the client the values must not be modified after the call to on the . The property throws an exception if modified past that point, but the other client description values can be modified without error. The result, however, is undefined. + + Whether for the service or client, it is recommended that you modify the description prior to calling . + +### Inheritance Rules for Behavior Attributes + + All four types of behaviors can be populated using attributes – service behaviors and contract behaviors. Because attributes are defined on managed objects and members, and managed objects and members support inheritance, it is necessary to define how behavior attributes work in the context of inheritance. + + At a high level, the rule is that for a particular scope (for example, service, contract, or operation), all behavior attributes in the inheritance hierarchy for that scope are applied. If there are two behavior attributes of the same type, only the most-derived type is used. + +#### Service Behaviors + + For a given service class, all service behavior attributes on that class, and on parents of that class, are applied. If the same type of attribute is applied at multiple places in the inheritance hierarchy, the most-derived type is used. + +```csharp +[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)] +[AspNetCompatibilityRequirementsAttribute( + AspNetCompatibilityRequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] +public class A { /* … */ } + +[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] +public class B : A { /* … */} +``` + + For example, in the preceding case, the service B ends up with an of , an mode of , and a of . The is , because attribute on service B is on "more derived" than that on service A. + +#### Contract Behaviors + + For a given contract, all contract behavior attributes on that interface and on parents of that interface, are applied. If the same type of attribute is applied at multiple places in the inheritance hierarchy, the most-derived type is used. + +#### Operation Behaviors + + If a given operation does not override an existing abstract or virtual operation, no inheritance rules apply. + If an operation does override an existing operation, then all operation behavior attributes on that operation and on parents of that operation, are applied. If the same type of attribute is applied at multiple places in the inheritance hierarchy, the most-derived type is used. diff --git a/docs/framework/wcf/extending/creating-user-defined-bindings.md b/docs/framework/wcf/extending/creating-user-defined-bindings.md index d2bfd60dd65bc..1ebf1b1f18927 100644 --- a/docs/framework/wcf/extending/creating-user-defined-bindings.md +++ b/docs/framework/wcf/extending/creating-user-defined-bindings.md @@ -2,127 +2,127 @@ description: "Learn more about: Creating User-Defined Bindings" title: "Creating User-Defined Bindings" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "user-defined bindings [WCF]" ms.assetid: c4960675-d701-4bc9-b400-36a752fdd08b --- # Creating User-Defined Bindings -There are several ways to create bindings not provided by the system: - -- Create a custom binding, based on the class, which is a container that you fill with binding elements. The custom binding is then added to a service endpoint. You can create the custom binding either programmatically or in an application configuration file. To use a binding element from an application configuration file, the binding element must extend . For more information about custom bindings, see [Custom Bindings](custom-bindings.md) and . - -- You can create a class that derives from a standard binding. For example, you can derive a class from and override method to obtain the binding elements and insert a custom binding element or establish a particular value for security. - -- You can create a new type to completely control the entire binding implementation. - -## The Order of Binding Elements - - Each binding element represents a processing step when sending or receiving messages. At run time, binding elements create the channels and listeners necessary to build outgoing and incoming channel stacks. - - There are three main types of binding elements: Protocol Binding Elements, Encoding Binding Elements and Transport Binding Elements. - - Protocol Binding Elements – These elements represent higher-level processing steps that act on messages. Channels and listeners created by these binding elements can add, remove, or modify the message content. A given binding may have an arbitrary number of protocol binding elements, each inheriting from . Windows Communication Foundation (WCF) includes several protocol binding elements, including the and the . - - Encoding Binding Element – These elements represent transformations between a message and an encoding ready for transmission on the wire. Typical WCF bindings include exactly one encoding binding element. Examples of encoding binding elements include the , the , and the . If an encoding binding element is not specified for a binding, a default encoding is used. The default is text when the transport is HTTP and binary otherwise. - - Transport Binding Element – These elements represent the transmission of an encoding message on a transport protocol. Typical WCF bindings include exactly one transport binding element, which inherits from . Examples of transport binding elements include the , the , and the . - - When creating new bindings, the order of the added binding elements is important. Always add binding elements in the following order: - -|Layer|Options|Required| -|-----------|-------------|--------------| -|Transaction Flow||No| -|Reliability||No| -|Security||No| -|Composite Duplex||No| -|Encoding|Text, Binary, MTOM, Custom|Yes\*| -|Transport|TCP, Named Pipes, HTTP, HTTPS, MSMQ, Custom|Yes| - -\*Because an encoding is required for each binding, if an encoding is not specified, WCF adds a default encoding for you. The default is Text/XML for the HTTP and HTTPS transports, and Binary otherwise. - -## Creating a new Binding Element - - In addition to the types derived from that are provided by WCF, you can create your own binding elements. This lets you customize the way the stack of bindings is created and the components that go in it by creating your own that can be composed with the other system-provided types in the stack. - - For example, if you implement a `LoggingBindingElement` that provides the ability to log the message to a database, you must place it above a transport channel in the channel stack. In this case, the application creates a custom binding that composed the `LoggingBindingElement` with `TcpTransportBindingElement`, as in the following example. - -```csharp -Binding customBinding = new CustomBinding( +There are several ways to create bindings not provided by the system: + +- Create a custom binding, based on the class, which is a container that you fill with binding elements. The custom binding is then added to a service endpoint. You can create the custom binding either programmatically or in an application configuration file. To use a binding element from an application configuration file, the binding element must extend . For more information about custom bindings, see [Custom Bindings](custom-bindings.md) and . + +- You can create a class that derives from a standard binding. For example, you can derive a class from and override method to obtain the binding elements and insert a custom binding element or establish a particular value for security. + +- You can create a new type to completely control the entire binding implementation. + +## The Order of Binding Elements + + Each binding element represents a processing step when sending or receiving messages. At runtime, binding elements create the channels and listeners necessary to build outgoing and incoming channel stacks. + + There are three main types of binding elements: Protocol Binding Elements, Encoding Binding Elements and Transport Binding Elements. + + Protocol Binding Elements – These elements represent higher-level processing steps that act on messages. Channels and listeners created by these binding elements can add, remove, or modify the message content. A given binding may have an arbitrary number of protocol binding elements, each inheriting from . Windows Communication Foundation (WCF) includes several protocol binding elements, including the and the . + + Encoding Binding Element – These elements represent transformations between a message and an encoding ready for transmission on the wire. Typical WCF bindings include exactly one encoding binding element. Examples of encoding binding elements include the , the , and the . If an encoding binding element is not specified for a binding, a default encoding is used. The default is text when the transport is HTTP and binary otherwise. + + Transport Binding Element – These elements represent the transmission of an encoding message on a transport protocol. Typical WCF bindings include exactly one transport binding element, which inherits from . Examples of transport binding elements include the , the , and the . + + When creating new bindings, the order of the added binding elements is important. Always add binding elements in the following order: + +|Layer|Options|Required| +|-----------|-------------|--------------| +|Transaction Flow||No| +|Reliability||No| +|Security||No| +|Composite Duplex||No| +|Encoding|Text, Binary, MTOM, Custom|Yes\*| +|Transport|TCP, Named Pipes, HTTP, HTTPS, MSMQ, Custom|Yes| + +\*Because an encoding is required for each binding, if an encoding is not specified, WCF adds a default encoding for you. The default is Text/XML for the HTTP and HTTPS transports, and Binary otherwise. + +## Creating a new Binding Element + + In addition to the types derived from that are provided by WCF, you can create your own binding elements. This lets you customize the way the stack of bindings is created and the components that go in it by creating your own that can be composed with the other system-provided types in the stack. + + For example, if you implement a `LoggingBindingElement` that provides the ability to log the message to a database, you must place it above a transport channel in the channel stack. In this case, the application creates a custom binding that composed the `LoggingBindingElement` with `TcpTransportBindingElement`, as in the following example. + +```csharp +Binding customBinding = new CustomBinding( new LoggingBindingElement(), - new TcpTransportBindingElement() -); -``` - - How you write your new binding element depends on its exact functionality. One of the samples, [Transport: UDP](../samples/transport-udp.md), provides a detailed description of how to implement one kind of binding element. - -## Creating a New Binding - - A user-created binding element can be used in two ways. The previous section illustrates the first way: through a custom binding. A custom binding allows the user to create their own binding based on an arbitrary set of binding elements, including user-created ones. - - If you use the binding in more than one application, create your own binding and extend the . This avoids manually creating a custom binding every time you want to use it. A user-defined binding allows you to define the binding’s behavior and include user-defined binding elements. And it is *pre-packaged*: you do not have to rebuild the binding every time you use it. - - At a minimum, a user-defined binding must implement the method and the property. - - The method returns a new that contains the binding elements for the binding. The collection is ordered, and should contain the protocol binding elements first, followed by the encoding binding element, followed by the transport binding element. When using the WCF system-provided binding elements, you must follow the binding element ordering rules specified in [Custom Bindings](custom-bindings.md). This collection should never reference objects referenced within the user-defined binding class; consequently, binding authors must return a `Clone()` of the on each call to . - - The property represents the URI scheme for the transport protocol in use on the binding. For example, the *WSHttpBinding* and the *NetTcpBinding* return "http" and "net.tcp" from their respective properties. - - For a complete list of optional methods and properties for user-defined bindings, see . - -### Example - - This example implements profile binding in `SampleProfileUdpBinding`, which derives from . The `SampleProfileUdpBinding` contains up to four binding elements within it: one user-created `UdpTransportBindingElement`; and three system-provided: `TextMessageEncodingBindingElement`, `CompositeDuplexBindingElement`, and `ReliableSessionBindingElement`. - + new TcpTransportBindingElement() +); +``` + + How you write your new binding element depends on its exact functionality. One of the samples, [Transport: UDP](../samples/transport-udp.md), provides a detailed description of how to implement one kind of binding element. + +## Creating a New Binding + + A user-created binding element can be used in two ways. The previous section illustrates the first way: through a custom binding. A custom binding allows the user to create their own binding based on an arbitrary set of binding elements, including user-created ones. + + If you use the binding in more than one application, create your own binding and extend the . This avoids manually creating a custom binding every time you want to use it. A user-defined binding allows you to define the binding’s behavior and include user-defined binding elements. And it is *pre-packaged*: you do not have to rebuild the binding every time you use it. + + At a minimum, a user-defined binding must implement the method and the property. + + The method returns a new that contains the binding elements for the binding. The collection is ordered, and should contain the protocol binding elements first, followed by the encoding binding element, followed by the transport binding element. When using the WCF system-provided binding elements, you must follow the binding element ordering rules specified in [Custom Bindings](custom-bindings.md). This collection should never reference objects referenced within the user-defined binding class; consequently, binding authors must return a `Clone()` of the on each call to . + + The property represents the URI scheme for the transport protocol in use on the binding. For example, the *WSHttpBinding* and the *NetTcpBinding* return "http" and "net.tcp" from their respective properties. + + For a complete list of optional methods and properties for user-defined bindings, see . + +### Example + + This example implements profile binding in `SampleProfileUdpBinding`, which derives from . The `SampleProfileUdpBinding` contains up to four binding elements within it: one user-created `UdpTransportBindingElement`; and three system-provided: `TextMessageEncodingBindingElement`, `CompositeDuplexBindingElement`, and `ReliableSessionBindingElement`. + ```csharp -public override BindingElementCollection CreateBindingElements() +public override BindingElementCollection CreateBindingElements() { - BindingElementCollection bindingElements = new BindingElementCollection(); - if (ReliableSessionEnabled) - { - bindingElements.Add(session); - bindingElements.Add(compositeDuplex); - } - bindingElements.Add(encoding); - bindingElements.Add(transport); - return bindingElements.Clone(); -} -``` - -## Security Restrictions with Duplex Contracts - - Not all binding elements are compatible with each other. In particular, there are some restrictions on security binding elements when used with duplex contracts. - -### One-Shot Security - - You can implement "one-shot" security, where all the necessary security credentials are sent in a single message, by setting the `negotiateServiceCredential` attribute of the \ configuration element to `false`. - - One-shot authentication does not work with duplex contracts. - - For Request-Reply contracts, one-shot authentication works only if the binding stack below the security binding element supports creating or instances. - - For one-way contracts, one-shot authentication works if the binding stack below the security binding element supports creating , , or instances. - -### Cookie-mode Security Context Tokens - - Cookie mode security context tokens cannot be used with duplex contracts. - - For Request-Reply contracts, cookie-mode security context tokens work only if the binding stack below the security binding element supports creating or instances. - - For one-way contracts, cookie-mode security context tokens works if the binding stack below the security binding element supports creating or instances. - -### Session-mode Security Context Tokens - - Session mode SCT works for duplex contracts if the binding stack below the security binding element supports creating or instances. - - Session mode SCT works for Request-Reply contracts if the binding stack below the security binding element supports creating , , or , instances. - - Session mode SCT works for 1-way contracts if the binding stack below the security binding element supports creating , , or instances. - -## Deriving from a Standard Binding - - Instead of creating an entirely new binding class, it may be possible for you to extend one of the existing system-provided bindings. Much like the preceding case, you must override the method and the property. - + BindingElementCollection bindingElements = new BindingElementCollection(); + if (ReliableSessionEnabled) + { + bindingElements.Add(session); + bindingElements.Add(compositeDuplex); + } + bindingElements.Add(encoding); + bindingElements.Add(transport); + return bindingElements.Clone(); +} +``` + +## Security Restrictions with Duplex Contracts + + Not all binding elements are compatible with each other. In particular, there are some restrictions on security binding elements when used with duplex contracts. + +### One-Shot Security + + You can implement "one-shot" security, where all the necessary security credentials are sent in a single message, by setting the `negotiateServiceCredential` attribute of the \ configuration element to `false`. + + One-shot authentication does not work with duplex contracts. + + For Request-Reply contracts, one-shot authentication works only if the binding stack below the security binding element supports creating or instances. + + For one-way contracts, one-shot authentication works if the binding stack below the security binding element supports creating , , or instances. + +### Cookie-mode Security Context Tokens + + Cookie mode security context tokens cannot be used with duplex contracts. + + For Request-Reply contracts, cookie-mode security context tokens work only if the binding stack below the security binding element supports creating or instances. + + For one-way contracts, cookie-mode security context tokens works if the binding stack below the security binding element supports creating or instances. + +### Session-mode Security Context Tokens + + Session mode SCT works for duplex contracts if the binding stack below the security binding element supports creating or instances. + + Session mode SCT works for Request-Reply contracts if the binding stack below the security binding element supports creating , , or , instances. + + Session mode SCT works for 1-way contracts if the binding stack below the security binding element supports creating , , or instances. + +## Deriving from a Standard Binding + + Instead of creating an entirely new binding class, it may be possible for you to extend one of the existing system-provided bindings. Much like the preceding case, you must override the method and the property. + ## See also - diff --git a/docs/framework/wcf/extending/custom-stream-upgrades.md b/docs/framework/wcf/extending/custom-stream-upgrades.md index 3797b19594c0b..52da8c9c87fb1 100644 --- a/docs/framework/wcf/extending/custom-stream-upgrades.md +++ b/docs/framework/wcf/extending/custom-stream-upgrades.md @@ -6,92 +6,92 @@ ms.assetid: e3da85c8-57f3-4e32-a4cb-50123f30fea6 --- # Custom Stream Upgrades -Stream-oriented transports such as TCP and Named Pipes operate on a continuous stream of bytes between the client and server. This stream is realized by a object. In a stream upgrade, the client wants to add an optional protocol layer to the channel stack, and asks the other end of the communication channel to do so. The stream upgrade consists in replacing the original object with an upgraded one. - - For example, you can build a compression stream directly on top of the transport stream. In this case the original transport is replaced with one that wraps the compression around the original one. - - You can apply multiple stream upgrades, each wrapping the preceding one. - -## How Stream Upgrades Work - - There are four components to the stream upgrade process. - -1. An upgrade stream *Initiator* begins the process: at run-time it can initiate a request to the other end of its connection to upgrade the channel transport layer. - -2. An upgrade stream *Acceptor* carries out the upgrade: at run-time it receives the upgrade request from the other machine, and if possible, accepts the upgrade. - -3. An upgrade *Provider* creates the *Initiator* on the client and the *Acceptor* on the server. - -4. A stream upgrade *Binding Element* is added to the bindings on the service and the client, and creates the provider at run time. - - Note that in the case of multiple upgrades, the Initiator and Acceptor encapsulate state machines to enforce which upgrade transitions are valid for each Initiation. - -## How to Implement a Stream Upgrade - - Windows Communication Foundation (WCF) provides four `abstract` classes that you can implement: - -- - -- - -- - -- - - To implement a custom stream upgrade, do the following. This procedure implements a minimal stream upgrade process on both the client and server machines. - -1. Create a class that implements . - - 1. Override the method to take in the stream to be upgraded, and return the upgraded stream. This method works synchronously; there are analogous methods to initiate the upgrade asynchronously. - - 2. Override the method to check for additional upgrades. - -2. Create a class that implements . - - 1. Override the method to take in the stream to be upgraded, and return the upgraded stream. This method works synchronously; there are analogous methods to accept the upgrade asynchronously. - - 2. Override the method to determine if the upgrade requested is supported by this upgrade acceptor at this point in the upgrade process. - -3. Create a class the implements . Override the and the methods to return instances of the acceptor and initiator defined in steps 2 and 1. - -4. Create a class that implements . - - 1. Override the method on the client and the method on the service. - - 2. Override the method on the client and the method on the service to add the upgrade Binding Element to . - -5. Add the new stream upgrade binding element to bindings on the server and client machines. - -## Security Upgrades - - Adding a security upgrade is a specialized version of the general stream upgrade process. - - WCF already provides two binding elements for upgrading stream security. The configuration of transport-level security is encapsulated by the and the which can be configured and added to a custom binding. These binding elements extend the class that builds the client and server stream upgrade providers. These binding elements have methods that create the specialized security stream upgrade provider classes, which are not `public`, so for these two cases all you need to do is to add the binding element to the binding. - - For security scenarios not met by the above two binding elements, three security-related `abstract` classes are derived from the above initiator, acceptor and provider base classes: - -1. - -2. - -3. - - The process of implementing a security stream upgrade is the same as before, with the difference that you would derive from these three classes. Override the additional properties in these classes to supply security information to the runtime. - -## Multiple Upgrades - - To create additional upgrade requests repeat the above process: create additional extensions of and binding elements. Add the binding elements to the binding. The additional binding elements are processed sequentially, starting with the first binding element added to the binding. In and each upgrade provider can determine how to layer itself on any pre-existing upgrade binding parameters. It should then replace the existing upgrade binding parameter with a new composite upgrade binding parameter. - - Alternatively, one upgrade provider can support multiple upgrades. For example, you might want to implement a custom stream upgrade provider that supports both security and compression. Do the following steps: - -1. Subclass to write the provider class that creates the Initiator and Acceptor. - -2. Subclass the making sure to override the method to return the content types for the compression stream and the secure stream in order. - -3. Subclass the that understands the custom content types in its method. - -4. The stream will be upgraded after each call to and . - +Stream-oriented transports such as TCP and Named Pipes operate on a continuous stream of bytes between the client and server. This stream is realized by a object. In a stream upgrade, the client wants to add an optional protocol layer to the channel stack, and asks the other end of the communication channel to do so. The stream upgrade consists in replacing the original object with an upgraded one. + + For example, you can build a compression stream directly on top of the transport stream. In this case the original transport is replaced with one that wraps the compression around the original one. + + You can apply multiple stream upgrades, each wrapping the preceding one. + +## How Stream Upgrades Work + + There are four components to the stream upgrade process. + +1. An upgrade stream *Initiator* begins the process: at runtime it can initiate a request to the other end of its connection to upgrade the channel transport layer. + +2. An upgrade stream *Acceptor* carries out the upgrade: at runtime it receives the upgrade request from the other machine, and if possible, accepts the upgrade. + +3. An upgrade *Provider* creates the *Initiator* on the client and the *Acceptor* on the server. + +4. A stream upgrade *Binding Element* is added to the bindings on the service and the client, and creates the provider at runtime. + + Note that in the case of multiple upgrades, the Initiator and Acceptor encapsulate state machines to enforce which upgrade transitions are valid for each Initiation. + +## How to Implement a Stream Upgrade + + Windows Communication Foundation (WCF) provides four `abstract` classes that you can implement: + +- + +- + +- + +- + + To implement a custom stream upgrade, do the following. This procedure implements a minimal stream upgrade process on both the client and server machines. + +1. Create a class that implements . + + 1. Override the method to take in the stream to be upgraded, and return the upgraded stream. This method works synchronously; there are analogous methods to initiate the upgrade asynchronously. + + 2. Override the method to check for additional upgrades. + +2. Create a class that implements . + + 1. Override the method to take in the stream to be upgraded, and return the upgraded stream. This method works synchronously; there are analogous methods to accept the upgrade asynchronously. + + 2. Override the method to determine if the upgrade requested is supported by this upgrade acceptor at this point in the upgrade process. + +3. Create a class the implements . Override the and the methods to return instances of the acceptor and initiator defined in steps 2 and 1. + +4. Create a class that implements . + + 1. Override the method on the client and the method on the service. + + 2. Override the method on the client and the method on the service to add the upgrade Binding Element to . + +5. Add the new stream upgrade binding element to bindings on the server and client machines. + +## Security Upgrades + + Adding a security upgrade is a specialized version of the general stream upgrade process. + + WCF already provides two binding elements for upgrading stream security. The configuration of transport-level security is encapsulated by the and the which can be configured and added to a custom binding. These binding elements extend the class that builds the client and server stream upgrade providers. These binding elements have methods that create the specialized security stream upgrade provider classes, which are not `public`, so for these two cases all you need to do is to add the binding element to the binding. + + For security scenarios not met by the above two binding elements, three security-related `abstract` classes are derived from the above initiator, acceptor and provider base classes: + +1. + +2. + +3. + + The process of implementing a security stream upgrade is the same as before, with the difference that you would derive from these three classes. Override the additional properties in these classes to supply security information to the runtime. + +## Multiple Upgrades + + To create additional upgrade requests repeat the above process: create additional extensions of and binding elements. Add the binding elements to the binding. The additional binding elements are processed sequentially, starting with the first binding element added to the binding. In and each upgrade provider can determine how to layer itself on any pre-existing upgrade binding parameters. It should then replace the existing upgrade binding parameter with a new composite upgrade binding parameter. + + Alternatively, one upgrade provider can support multiple upgrades. For example, you might want to implement a custom stream upgrade provider that supports both security and compression. Do the following steps: + +1. Subclass to write the provider class that creates the Initiator and Acceptor. + +2. Subclass the making sure to override the method to return the content types for the compression stream and the secure stream in order. + +3. Subclass the that understands the custom content types in its method. + +4. The stream will be upgraded after each call to and . + ## See also - diff --git a/docs/framework/wcf/extending/extending-clients.md b/docs/framework/wcf/extending/extending-clients.md index 7a034860ed6b5..7a841aa60c908 100644 --- a/docs/framework/wcf/extending/extending-clients.md +++ b/docs/framework/wcf/extending/extending-clients.md @@ -2,118 +2,118 @@ description: "Learn more about: Extending Clients" title: "Extending Clients" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "proxy extensions [WCF]" ms.assetid: 1328c61c-06e5-455f-9ebd-ceefb59d3867 --- # Extending Clients -In a calling application, the service model layer is responsible for translating method invocations in application code into outbound messages, pushing them to the underlying channels, translating results back into return values and out parameters in application code, and returning the results back to the caller. Service model extensions modify or implement execution or communication behavior and features involving client or dispatcher functionality, custom behaviors, message and parameter interception, and other extensibility functionality. - - This topic describes how to use the and classes in a Windows Communication Foundation (WCF) client application to modify the default execution behavior of a WCF client or to intercept or modify messages, parameters, or return values prior to or subsequent to sending or retrieving them from the channel layer. For more information about extending the service runtime, see [Extending Dispatchers](extending-dispatchers.md). For more information about the behaviors that modify and insert customization objects into the client runtime, see [Configuring and Extending the Runtime with Behaviors](configuring-and-extending-the-runtime-with-behaviors.md). - -## Clients - - On a client, a WCF client object or client channel converts method invocations into outgoing messages and incoming messages to operation results that are returned to the calling application. (For more information about client types, see [WCF Client Architecture](../feature-details/client-architecture.md).) - - WCF client types have runtime types that handle this endpoint- and operation-level functionality. When an application calls an operation, the translates the outbound objects into a message, processes interceptors, confirms that the outbound call conforms to the target contract, and hands the outbound message to the , which is responsible for creating and managing outbound channels (and inbound channels in the case of duplex services), handling extra outbound message processing (such as header modification), processing message interceptors in both directions, and routing inbound duplex calls to the appropriate client-side object. Both the and provide similar services when messages (including faults) are returned to the client. - - These two runtime classes are the main extension to customize the processing of WCF client objects and channels. The class allows users to intercept and extend client execution across all messages in the contract. The class allows users to intercept and extend client execution for all messages in a given operation. - - Modifying the properties or inserting customizations are done by using contract, endpoint, and operation behaviors. For more information about how to use these types of behaviors to perform client runtime customizations, see [Configuring and Extending the Runtime with Behaviors](configuring-and-extending-the-runtime-with-behaviors.md). - -## Scenarios - - There a number of reasons to extend the client system, including: - -- Custom Message Validation. A user may want to enforce that a message is valid for a certain schema. This can be done by implementing the interface and assigning the implementation to the property. For examples, see [How to: Inspect or Modify Messages on the Client](how-to-inspect-or-modify-messages-on-the-client.md) and [How to: Inspect or Modify Messages on the Client](how-to-inspect-or-modify-messages-on-the-client.md). - -- Custom Message Logging. A user may want to inspect and log some set of application messages that flow through an endpoint. This can also be accomplished with the message interceptor interfaces. - -- Custom Message Transformations. Rather than modifying application code, the user may want to apply certain transformations to the message in the runtime (for example, for versioning). This can be accomplished, again, with the message interceptor interfaces. - -- Custom Data Model. A user may want to have a data or serialization model other than those supported by default in WCF (namely, , , and objects). This can be done by implementing the message formatter interfaces. For more information, see and the property. - -- Custom Parameter Validation. A user may want to enforce that typed parameters are valid (as opposed to XML). This can be done using the parameter inspector interfaces. For an example, see [How to: Inspect or Modify Parameters](how-to-inspect-or-modify-parameters.md) or [Client Validation](../samples/client-validation.md). - -### Using the ClientRuntime Class - - The class is an extensibility point to which you can add extension objects that intercept messages and extend client behavior. Interception objects can process all messages in a particular contract, process only messages for particular operations, perform custom channel initialization, and implement other custom client application behavior. - -- The property returns the dispatch run-time object for service-initiated callback clients. - -- The property accepts a custom operation selector object. - -- The property enables the addition of a channel initializer that can inspect or modify the client channel. - -- The property gets a collection of objects to which you can add custom message interceptors that provide functionality specific to the messages of that operation. - -- The property enables an application to turn off some automatic addressing headers to directly control addressing. - -- The property sets the value of the destination of the message at the transport level to support intermediaries and other scenarios. - -- The property gets a collection of objects to which you can add custom message interceptors for all messages traveling through a WCF client. - - In addition, there are a number of other properties that retrieve the contract information: - -- - -- - -- - - If the WCF client is a duplex WCF client, the following properties also retrieve the callback WCF client information: - -- - -- - - To extend WCF client execution across an entire WCF client, review the properties available on the class to see whether modifying a property or implementing an interface and adding it to a property creates the functionality you are seeking. Once you have chosen a particular extension to build, insert your extension into the appropriate property by implementing a client behavior that provides access to the class when invoked. - - You can insert custom extension objects into a collection using an operation behavior (an object that implements ), a contract behavior (an object that implements ), or an endpoint behavior (an object that implements ). The installing behavior object is added to the appropriate collection of behaviors either programmatically, declaratively (by implementing a custom attribute), or by implementing a custom object to enable the behavior to be inserted using an application configuration file. For details, see [Configuring and Extending the Runtime with Behaviors](configuring-and-extending-the-runtime-with-behaviors.md). - - For examples that demonstrate interception across a WCF client, see [How to: Inspect or Modify Messages on the Client](how-to-inspect-or-modify-messages-on-the-client.md). - -### Using the ClientOperation Class - - The class is the location for client run-time modifications and insertion point for custom extensions that are scoped to only one service operation. (To modify client run-time behavior for all messages in a contract, use the class.) - - Use the property to locate the object that represents a particular service operation. The following properties enable you to insert custom objects into the WCF client system: - -- Use the property to insert a custom implementation for an operation or modify the current formatter. - -- Use the property to insert a custom implementation or to modify the current one. - - The following properties enable you to modify the system in interaction with the formatter and custom parameter inspectors: - -- Use the property to control the serialization of an outbound message. - -- Use the property to control the deserialization of an inbound message. - -- Use the property to control the WS-Addressing action of the request message. - -- Use the and to specify which WCF client methods are associated with an asynchronous operation. - -- Use the property to get a collection that contains the types that can appear in SOAP faults as the detail type. - -- Use the and properties to control whether a session is initiated or is torn down, respectively, when the operation is called. - -- Use the property to control whether the operation is a one-way operation. - -- Use the property to obtain the containing object. - -- Use the property to get the name of the operation. - -- Use the property to control which method is mapped to the operation. - - To extend WCF client execution across only one service operation, review the properties available on the class to see whether modifying a property or implementing an interface and adding it to a property creates the functionality you are seeking. Once you have chosen a particular extension to build, insert your extension into the appropriate property by implementing a client behavior that provides access to the class when invoked. Inside that behavior you can then modify the property to fit your requirements. - - Typically, implementing an operation behavior (an object that implements the interface) suffices, but you can also use endpoint behaviors and contract behaviors to accomplish the same thing by locating the for a particular operation and attaching the behavior there. For details, see [Configuring and Extending the Runtime with Behaviors](configuring-and-extending-the-runtime-with-behaviors.md). - - To use your custom behavior from configuration, install your behavior using a custom behavior configuration section handler. You can also install your behavior by creating a custom attribute. - - For examples that demonstrate interception across a WCF client, see [How to: Inspect or Modify Parameters](how-to-inspect-or-modify-parameters.md). - +In a calling application, the service model layer is responsible for translating method invocations in application code into outbound messages, pushing them to the underlying channels, translating results back into return values and out parameters in application code, and returning the results back to the caller. Service model extensions modify or implement execution or communication behavior and features involving client or dispatcher functionality, custom behaviors, message and parameter interception, and other extensibility functionality. + + This topic describes how to use the and classes in a Windows Communication Foundation (WCF) client application to modify the default execution behavior of a WCF client or to intercept or modify messages, parameters, or return values prior to or subsequent to sending or retrieving them from the channel layer. For more information about extending the service runtime, see [Extending Dispatchers](extending-dispatchers.md). For more information about the behaviors that modify and insert customization objects into the client runtime, see [Configuring and Extending the Runtime with Behaviors](configuring-and-extending-the-runtime-with-behaviors.md). + +## Clients + + On a client, a WCF client object or client channel converts method invocations into outgoing messages and incoming messages to operation results that are returned to the calling application. (For more information about client types, see [WCF Client Architecture](../feature-details/client-architecture.md).) + + WCF client types have runtime types that handle this endpoint- and operation-level functionality. When an application calls an operation, the translates the outbound objects into a message, processes interceptors, confirms that the outbound call conforms to the target contract, and hands the outbound message to the , which is responsible for creating and managing outbound channels (and inbound channels in the case of duplex services), handling extra outbound message processing (such as header modification), processing message interceptors in both directions, and routing inbound duplex calls to the appropriate client-side object. Both the and provide similar services when messages (including faults) are returned to the client. + + These two runtime classes are the main extension to customize the processing of WCF client objects and channels. The class allows users to intercept and extend client execution across all messages in the contract. The class allows users to intercept and extend client execution for all messages in a given operation. + + Modifying the properties or inserting customizations are done by using contract, endpoint, and operation behaviors. For more information about how to use these types of behaviors to perform client runtime customizations, see [Configuring and Extending the Runtime with Behaviors](configuring-and-extending-the-runtime-with-behaviors.md). + +## Scenarios + + There a number of reasons to extend the client system, including: + +- Custom Message Validation. A user may want to enforce that a message is valid for a certain schema. This can be done by implementing the interface and assigning the implementation to the property. For examples, see [How to: Inspect or Modify Messages on the Client](how-to-inspect-or-modify-messages-on-the-client.md) and [How to: Inspect or Modify Messages on the Client](how-to-inspect-or-modify-messages-on-the-client.md). + +- Custom Message Logging. A user may want to inspect and log some set of application messages that flow through an endpoint. This can also be accomplished with the message interceptor interfaces. + +- Custom Message Transformations. Rather than modifying application code, the user may want to apply certain transformations to the message in the runtime (for example, for versioning). This can be accomplished, again, with the message interceptor interfaces. + +- Custom Data Model. A user may want to have a data or serialization model other than those supported by default in WCF (namely, , , and objects). This can be done by implementing the message formatter interfaces. For more information, see and the property. + +- Custom Parameter Validation. A user may want to enforce that typed parameters are valid (as opposed to XML). This can be done using the parameter inspector interfaces. For an example, see [How to: Inspect or Modify Parameters](how-to-inspect-or-modify-parameters.md) or [Client Validation](../samples/client-validation.md). + +### Using the ClientRuntime Class + + The class is an extensibility point to which you can add extension objects that intercept messages and extend client behavior. Interception objects can process all messages in a particular contract, process only messages for particular operations, perform custom channel initialization, and implement other custom client application behavior. + +- The property returns the dispatch runtime object for service-initiated callback clients. + +- The property accepts a custom operation selector object. + +- The property enables the addition of a channel initializer that can inspect or modify the client channel. + +- The property gets a collection of objects to which you can add custom message interceptors that provide functionality specific to the messages of that operation. + +- The property enables an application to turn off some automatic addressing headers to directly control addressing. + +- The property sets the value of the destination of the message at the transport level to support intermediaries and other scenarios. + +- The property gets a collection of objects to which you can add custom message interceptors for all messages traveling through a WCF client. + + In addition, there are a number of other properties that retrieve the contract information: + +- + +- + +- + + If the WCF client is a duplex WCF client, the following properties also retrieve the callback WCF client information: + +- + +- + + To extend WCF client execution across an entire WCF client, review the properties available on the class to see whether modifying a property or implementing an interface and adding it to a property creates the functionality you are seeking. Once you have chosen a particular extension to build, insert your extension into the appropriate property by implementing a client behavior that provides access to the class when invoked. + + You can insert custom extension objects into a collection using an operation behavior (an object that implements ), a contract behavior (an object that implements ), or an endpoint behavior (an object that implements ). The installing behavior object is added to the appropriate collection of behaviors either programmatically, declaratively (by implementing a custom attribute), or by implementing a custom object to enable the behavior to be inserted using an application configuration file. For details, see [Configuring and Extending the Runtime with Behaviors](configuring-and-extending-the-runtime-with-behaviors.md). + + For examples that demonstrate interception across a WCF client, see [How to: Inspect or Modify Messages on the Client](how-to-inspect-or-modify-messages-on-the-client.md). + +### Using the ClientOperation Class + + The class is the location for client runtime modifications and insertion point for custom extensions that are scoped to only one service operation. (To modify client runtime behavior for all messages in a contract, use the class.) + + Use the property to locate the object that represents a particular service operation. The following properties enable you to insert custom objects into the WCF client system: + +- Use the property to insert a custom implementation for an operation or modify the current formatter. + +- Use the property to insert a custom implementation or to modify the current one. + + The following properties enable you to modify the system in interaction with the formatter and custom parameter inspectors: + +- Use the property to control the serialization of an outbound message. + +- Use the property to control the deserialization of an inbound message. + +- Use the property to control the WS-Addressing action of the request message. + +- Use the and to specify which WCF client methods are associated with an asynchronous operation. + +- Use the property to get a collection that contains the types that can appear in SOAP faults as the detail type. + +- Use the and properties to control whether a session is initiated or is torn down, respectively, when the operation is called. + +- Use the property to control whether the operation is a one-way operation. + +- Use the property to obtain the containing object. + +- Use the property to get the name of the operation. + +- Use the property to control which method is mapped to the operation. + + To extend WCF client execution across only one service operation, review the properties available on the class to see whether modifying a property or implementing an interface and adding it to a property creates the functionality you are seeking. Once you have chosen a particular extension to build, insert your extension into the appropriate property by implementing a client behavior that provides access to the class when invoked. Inside that behavior you can then modify the property to fit your requirements. + + Typically, implementing an operation behavior (an object that implements the interface) suffices, but you can also use endpoint behaviors and contract behaviors to accomplish the same thing by locating the for a particular operation and attaching the behavior there. For details, see [Configuring and Extending the Runtime with Behaviors](configuring-and-extending-the-runtime-with-behaviors.md). + + To use your custom behavior from configuration, install your behavior using a custom behavior configuration section handler. You can also install your behavior by creating a custom attribute. + + For examples that demonstrate interception across a WCF client, see [How to: Inspect or Modify Parameters](how-to-inspect-or-modify-parameters.md). + ## See also - diff --git a/docs/framework/wcf/extending/extending-dispatchers.md b/docs/framework/wcf/extending/extending-dispatchers.md index b88467561db66..ce7ac154f6a0a 100644 --- a/docs/framework/wcf/extending/extending-dispatchers.md +++ b/docs/framework/wcf/extending/extending-dispatchers.md @@ -58,7 +58,7 @@ There a number of reasons to extend the dispatcher: - Custom Error Handling. Users can control how both local errors are processed and how faults are communicated back to clients. This can be implemented using the interfaces. -- Custom Authorization Behaviors. Users can implement custom access control by extending the Contract or Operation run-time pieces and adding security checks based upon the tokens present in the message. This can be accomplished using either the message interceptor or parameter interceptor interfaces. For examples, see [Security Extensibility](../samples/security-extensibility.md). +- Custom Authorization Behaviors. Users can implement custom access control by extending the Contract or Operation runtime pieces and adding security checks based upon the tokens present in the message. This can be accomplished using either the message interceptor or parameter interceptor interfaces. For examples, see [Security Extensibility](../samples/security-extensibility.md). > [!CAUTION] > Because altering security properties has the potential to compromise the security of WCF applications, it is strongly recommended that you undertake security-related modifications with care and test thoroughly prior to deployment. @@ -103,7 +103,7 @@ Duplex clients (clients that implement a callback contract specified by a duplex ### Using the DispatchOperation Class -The class is the location for run-time modifications and the insertion point for custom extensions that are scoped to only one service operation. (To modify service run-time behavior for all messages in a contract, use the class.) +The class is the location for runtime modifications and the insertion point for custom extensions that are scoped to only one service operation. (To modify service runtime behavior for all messages in a contract, use the class.) Install modifications using a custom service behavior object. diff --git a/docs/framework/wcf/extending/index.md b/docs/framework/wcf/extending/index.md index e71624a1394ff..e1bf664b7a343 100644 --- a/docs/framework/wcf/extending/index.md +++ b/docs/framework/wcf/extending/index.md @@ -2,7 +2,7 @@ description: "Learn more about: Extending WCF" title: "Extending WCF" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "WCF, extensibility" - "extensibility [WCF]" - "Windows Communication Foundation, extensibility" @@ -10,48 +10,48 @@ ms.assetid: c145e2f6-f402-41f5-8b5a-eee03978737b --- # Extending WCF -Windows Communication Foundation (WCF) allows you to modify and extend run time components to precisely control and extend service-based applications. The topics in this section go in depth about the extensibility architecture. For more information about basic programming, see [Basic WCF Programming](../basic-wcf-programming.md). - -## In This Section - - [Extending ServiceHost and the Service Model Layer](extending-servicehost-and-the-service-model-layer.md) - The service model layer is responsible for pulling incoming messages out of the underlying channels, translating them into method invocations in application code, and sending the results back to the caller. Service model extensions modify or implement execution or communication behavior and features involving dispatcher functionality, custom behaviors, message and parameter interception, and other extensibility functionality. - - [Extending Bindings](extending-bindings.md) - Bindings are objects that describe the communication details required to connect to an endpoint. Binding extensions or custom bindings implement custom communication functionality required to support application features. - - [Extending the Channel Layer](extending-the-channel-layer.md) - The channel layer sits beneath the service model layer and is responsible for the exchange of messages between clients and services. Channel extensions can implement new protocol functionality, such as security. Channel extensions also transport functionality, such as implementing a new network transport to carry SOAP messages. - - [Extending Security](extending-security.md) - Security in WCF consists of transfer security (integrity, confidentiality, and authentication), access control (authorization) and auditing. The classes found in the `IdentityModel` namespace are used by WCF for access control. Understanding the security architecture allows you to create custom claim types to accommodate custom access control systems. - - [Extending the Metadata System](extending-the-metadata-system.md) - The WCF metadata system is a group of classes and interfaces that represent metadata required to implement service-based applications. Modify or extend the classes or implement and configure the interfaces to export and import custom metadata such as Web Services Description Language (WSDL) extensions or custom WS-PolicyAttachments assertions. - - [Extending Encoders and Serializers](extending-encoders-and-serializers.md) - Encoders and serializers translate data from one form to another. The topics in this section discuss how to extend the supplied classes to meet special requirements. - -## Reference - - - - - - - - - - - - - - - -## Related Sections - - [Basic WCF Programming](../basic-wcf-programming.md) - - [WCF Feature Details](../feature-details/index.md) - +Windows Communication Foundation (WCF) allows you to modify and extend runtime components to precisely control and extend service-based applications. The topics in this section go in depth about the extensibility architecture. For more information about basic programming, see [Basic WCF Programming](../basic-wcf-programming.md). + +## In This Section + + [Extending ServiceHost and the Service Model Layer](extending-servicehost-and-the-service-model-layer.md) + The service model layer is responsible for pulling incoming messages out of the underlying channels, translating them into method invocations in application code, and sending the results back to the caller. Service model extensions modify or implement execution or communication behavior and features involving dispatcher functionality, custom behaviors, message and parameter interception, and other extensibility functionality. + + [Extending Bindings](extending-bindings.md) + Bindings are objects that describe the communication details required to connect to an endpoint. Binding extensions or custom bindings implement custom communication functionality required to support application features. + + [Extending the Channel Layer](extending-the-channel-layer.md) + The channel layer sits beneath the service model layer and is responsible for the exchange of messages between clients and services. Channel extensions can implement new protocol functionality, such as security. Channel extensions also transport functionality, such as implementing a new network transport to carry SOAP messages. + + [Extending Security](extending-security.md) + Security in WCF consists of transfer security (integrity, confidentiality, and authentication), access control (authorization) and auditing. The classes found in the `IdentityModel` namespace are used by WCF for access control. Understanding the security architecture allows you to create custom claim types to accommodate custom access control systems. + + [Extending the Metadata System](extending-the-metadata-system.md) + The WCF metadata system is a group of classes and interfaces that represent metadata required to implement service-based applications. Modify or extend the classes or implement and configure the interfaces to export and import custom metadata such as Web Services Description Language (WSDL) extensions or custom WS-PolicyAttachments assertions. + + [Extending Encoders and Serializers](extending-encoders-and-serializers.md) + Encoders and serializers translate data from one form to another. The topics in this section discuss how to extend the supplied classes to meet special requirements. + +## Reference + + + + + + + + + + + + + + + +## Related Sections + + [Basic WCF Programming](../basic-wcf-programming.md) + + [WCF Feature Details](../feature-details/index.md) + [Guidelines and Best Practices](../guidelines-and-best-practices.md) diff --git a/docs/framework/wcf/feature-details/access-control-mechanisms.md b/docs/framework/wcf/feature-details/access-control-mechanisms.md index e4ec145a5dd9e..f078824c1badf 100644 --- a/docs/framework/wcf/feature-details/access-control-mechanisms.md +++ b/docs/framework/wcf/feature-details/access-control-mechanisms.md @@ -2,62 +2,62 @@ description: "Learn more about: Access Control Mechanisms" title: "Access Control Mechanisms" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "WCF security" - "access control [WCF]" ms.assetid: 9d576122-3f55-4425-9acf-b23d0781e966 --- # Access Control Mechanisms -You can control access in several way with Windows Communication Foundation (WCF). This topic briefly discusses the various mechanisms and provides suggestions on when to use each; it is intended to help you select the correct mechanism to use. The access technologies are listed in order of complexity. The simplest is the ; the most complex is the Identity Model. - - In addition to these mechanisms, impersonation and delegation with WCF is explained in [Delegation and Impersonation](delegation-and-impersonation-with-wcf.md). - -## PrincipalPermissionAttribute - - The is used to restrict access to a service method. When the attribute is applied to a method, it can be used to demand a specific caller's identity or membership in a Windows group or ASP.NET role. If the client is authenticated using an X.509 certificate, it is given a primary identity that consists of the subject name plus the thumbprint of the certificate. - - Use the to control access to resources on the computer that the service is running on, and if the users of the service will always be part of the same Windows domain that the service is running on. You can easily create Windows groups that have specified levels of access (such as none, read-only, or read and write). - - For more information about using the attribute, see [How to: Restrict Access with the PrincipalPermissionAttribute Class](../how-to-restrict-access-with-the-principalpermissionattribute-class.md). For more information about identity, see [Service Identity and Authentication](service-identity-and-authentication.md). - -## ASP.NET Membership Provider - - A feature of ASP.NET is the membership provider. Even though the membership provider is not technically an access control mechanism, it allows controlling access to the service by limiting the set of possible identities that can access the service's endpoint. The membership feature includes a database that can be populated with user name/password combinations that enable users of a Web site to establish accounts with the site. To access a service that uses the membership provider, a user must log on with their user name and password. - +You can control access in several way with Windows Communication Foundation (WCF). This topic briefly discusses the various mechanisms and provides suggestions on when to use each; it is intended to help you select the correct mechanism to use. The access technologies are listed in order of complexity. The simplest is the ; the most complex is the Identity Model. + + In addition to these mechanisms, impersonation and delegation with WCF is explained in [Delegation and Impersonation](delegation-and-impersonation-with-wcf.md). + +## PrincipalPermissionAttribute + + The is used to restrict access to a service method. When the attribute is applied to a method, it can be used to demand a specific caller's identity or membership in a Windows group or ASP.NET role. If the client is authenticated using an X.509 certificate, it is given a primary identity that consists of the subject name plus the thumbprint of the certificate. + + Use the to control access to resources on the computer that the service is running on, and if the users of the service will always be part of the same Windows domain that the service is running on. You can easily create Windows groups that have specified levels of access (such as none, read-only, or read and write). + + For more information about using the attribute, see [How to: Restrict Access with the PrincipalPermissionAttribute Class](../how-to-restrict-access-with-the-principalpermissionattribute-class.md). For more information about identity, see [Service Identity and Authentication](service-identity-and-authentication.md). + +## ASP.NET Membership Provider + + A feature of ASP.NET is the membership provider. Even though the membership provider is not technically an access control mechanism, it allows controlling access to the service by limiting the set of possible identities that can access the service's endpoint. The membership feature includes a database that can be populated with user name/password combinations that enable users of a Web site to establish accounts with the site. To access a service that uses the membership provider, a user must log on with their user name and password. + > [!NOTE] -> You must first populate the database using the ASP.NET feature before a WCF service can use it for authorization purposes. - - You can also use the membership feature if you already have a membership database from an existing ASP.NET Web site and you want to enable the same users to use your service, authorized with the same user names and passwords. - - For more information about using the membership feature in a WCF service, see [How to: Use the ASP.NET Membership Provider](how-to-use-the-aspnet-membership-provider.md). - -## ASP.NET Role Provider - - Another feature of ASP.NET is the ability to manage authorization using roles. The ASP.NET role provider enables a developer to create roles for users and to assign each user to a role or roles. As with the membership provider, the roles and assignments are stored in a database, and can be populated using tools provided by a particular implementation of the ASP.NET role provider. As with the membership feature, WCF developers can use the information in the database to authorize service users by roles. They can, for example, use the role provider in combination with the `PrincipalPermissionAttribute` access control mechanism described above. - - You can also use the ASP.NET role provider if you have an existing ASP.NET role provider database and want to use the same set of rules and user assignments in your WCF service. - - For more information about using the role provider feature, see [How to: Use the ASP.NET Role Provider with a Service](how-to-use-the-aspnet-role-provider-with-a-service.md). - -## Authorization Manager - - Another feature combines the Authorization Manager (AzMan) with the ASP.NET role provider to authorize clients. When ASP.NET hosts a Web service, AzMan can be integrated into the application so that authorization to the service is done through AzMan. ASP.NET role manager provides an API that enables you to manage application roles, add and remove users from roles, and check role membership, but it does not allow you to query whether a user is authorized to perform a named task or operation. AzMan allows you to define individual operations and combine them into tasks. With AZMan, in addition to role checks, you can also check whether a user can perform a task. Role assignment and task authorization can be configured outside of the application or performed programmatically within the application. The AzMan administration Microsoft Management Console (MMC) snap-in allows administrators to change the tasks a role can perform at run time and to manage each user's membership of roles. - - You can also use AzMan and the ASP.NET role provider if you already have access to an existing AzMan installation and want to authorize your service users using the features of the AzMan/role provider combination. - - For more information about AzMan and the ASP.NET role provider, see [How To: Use Authorization Manager (AzMan) with ASP.NET 2.0](/previous-versions/msp-n-p/ff649313(v=pandp.10)). For more information about using AzMan and the role provider for WCF services, see [How to: Use the ASP.NET Authorization Manager Role Provider with a Service](how-to-use-the-aspnet-authorization-manager-role-provider-with-a-service.md). - -## Identity Model - - The Identity Model is a set of APIs that enable you to manage claims and policies to authorize clients. With the Identity Model, you can examine every claim contained in credentials that the caller used to authenticate itself to the service, compare the claims to the set of policies for the service, and grant or deny access based on the comparison. - - Use the Identity Model if you need fine control and the ability to set specific criteria before granting access. For example, when using the , the criterion is simply that the identity of the user is authenticated and belongs to a specific role. In contrast, using the Identity Model, you can create a policy that states the user must be over 18 years of age and possesses a valid driver's license before being allowed to view a document. - - One example where you can benefit from the Identity Model claim-based access control is when using federation credentials in the issued token scenario. For more information about federation and issued tokens, see [Federation and Issued Tokens](federation-and-issued-tokens.md). - - For more information about the Identity Model, see [Managing Claims and Authorization with the Identity Model](managing-claims-and-authorization-with-the-identity-model.md). - +> You must first populate the database using the ASP.NET feature before a WCF service can use it for authorization purposes. + + You can also use the membership feature if you already have a membership database from an existing ASP.NET Web site and you want to enable the same users to use your service, authorized with the same user names and passwords. + + For more information about using the membership feature in a WCF service, see [How to: Use the ASP.NET Membership Provider](how-to-use-the-aspnet-membership-provider.md). + +## ASP.NET Role Provider + + Another feature of ASP.NET is the ability to manage authorization using roles. The ASP.NET role provider enables a developer to create roles for users and to assign each user to a role or roles. As with the membership provider, the roles and assignments are stored in a database, and can be populated using tools provided by a particular implementation of the ASP.NET role provider. As with the membership feature, WCF developers can use the information in the database to authorize service users by roles. They can, for example, use the role provider in combination with the `PrincipalPermissionAttribute` access control mechanism described above. + + You can also use the ASP.NET role provider if you have an existing ASP.NET role provider database and want to use the same set of rules and user assignments in your WCF service. + + For more information about using the role provider feature, see [How to: Use the ASP.NET Role Provider with a Service](how-to-use-the-aspnet-role-provider-with-a-service.md). + +## Authorization Manager + + Another feature combines the Authorization Manager (AzMan) with the ASP.NET role provider to authorize clients. When ASP.NET hosts a Web service, AzMan can be integrated into the application so that authorization to the service is done through AzMan. ASP.NET role manager provides an API that enables you to manage application roles, add and remove users from roles, and check role membership, but it does not allow you to query whether a user is authorized to perform a named task or operation. AzMan allows you to define individual operations and combine them into tasks. With AZMan, in addition to role checks, you can also check whether a user can perform a task. Role assignment and task authorization can be configured outside of the application or performed programmatically within the application. The AzMan administration Microsoft Management Console (MMC) snap-in allows administrators to change the tasks a role can perform at runtime and to manage each user's membership of roles. + + You can also use AzMan and the ASP.NET role provider if you already have access to an existing AzMan installation and want to authorize your service users using the features of the AzMan/role provider combination. + + For more information about AzMan and the ASP.NET role provider, see [How To: Use Authorization Manager (AzMan) with ASP.NET 2.0](/previous-versions/msp-n-p/ff649313(v=pandp.10)). For more information about using AzMan and the role provider for WCF services, see [How to: Use the ASP.NET Authorization Manager Role Provider with a Service](how-to-use-the-aspnet-authorization-manager-role-provider-with-a-service.md). + +## Identity Model + + The Identity Model is a set of APIs that enable you to manage claims and policies to authorize clients. With the Identity Model, you can examine every claim contained in credentials that the caller used to authenticate itself to the service, compare the claims to the set of policies for the service, and grant or deny access based on the comparison. + + Use the Identity Model if you need fine control and the ability to set specific criteria before granting access. For example, when using the , the criterion is simply that the identity of the user is authenticated and belongs to a specific role. In contrast, using the Identity Model, you can create a policy that states the user must be over 18 years of age and possesses a valid driver's license before being allowed to view a document. + + One example where you can benefit from the Identity Model claim-based access control is when using federation credentials in the issued token scenario. For more information about federation and issued tokens, see [Federation and Issued Tokens](federation-and-issued-tokens.md). + + For more information about the Identity Model, see [Managing Claims and Authorization with the Identity Model](managing-claims-and-authorization-with-the-identity-model.md). + ## See also - diff --git a/docs/framework/wcf/feature-details/bindings-and-security.md b/docs/framework/wcf/feature-details/bindings-and-security.md index 595a34f09b486..51136cb539a9c 100644 --- a/docs/framework/wcf/feature-details/bindings-and-security.md +++ b/docs/framework/wcf/feature-details/bindings-and-security.md @@ -15,7 +15,7 @@ The system-provided bindings included with Windows Communication Foundation (WCF For an overview of WCF security, see [Security Overview](security-overview.md). For more information about programming WCF using bindings, see [Programming WCF Security](programming-wcf-security.md). -If you have already selected a binding, you can find out more about the run-time behaviors that are associated with security in [Security Behaviors](security-behaviors-in-wcf.md). +If you have already selected a binding, you can find out more about the runtime behaviors that are associated with security in [Security Behaviors](security-behaviors-in-wcf.md). Some security functions are not programmable using the system-provided bindings. For more control using a custom binding, see [Security Capabilities with Custom Bindings](security-capabilities-with-custom-bindings.md). diff --git a/docs/framework/wcf/feature-details/client-architecture.md b/docs/framework/wcf/feature-details/client-architecture.md index e45adc60e448f..3c6077999ce22 100644 --- a/docs/framework/wcf/feature-details/client-architecture.md +++ b/docs/framework/wcf/feature-details/client-architecture.md @@ -6,58 +6,58 @@ ms.assetid: 02624403-0d77-41cb-9a86-ab55e98c7966 --- # Client Architecture -Applications use Windows Communication Foundation (WCF) client objects to invoke service operations. This topic discusses WCF client objects, WCF client channels, and their relationships to the underlying channel architecture. For a basic overview of WCF client objects, see [WCF Client Overview](../wcf-client-overview.md). For more information about the channel layer, see [Extending the Channel Layer](../extending/extending-the-channel-layer.md). - -## Overview - - The service model run time creates WCF clients, which are composed of the following: - -- An automatically generated client implementation of a service contract, which turns calls from your application code into outgoing messages, and turns response messages into output parameters and return values that your application can retrieve. - -- An implementation of a control interface () that groups together various interfaces and provides access to control functionality, most notably the ability to close the client session and dispose the channel. - -- A client channel that is built based on the configuration settings specified by the used binding. - - Applications can create such clients on demand, either through a or by creating an instance of a derived class as it is generated by the [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md). These ready-built client classes encapsulate and delegate to a client channel implementation that is dynamically constructed by a . Therefore, the client channel and the channel factory that produces them are the focal point of interest for this discussion. - -## Client Objects and Client Channels - - The base interface of WCF clients is the interface, which exposes core client functionality as well as the basic communication object functionality of , the context functionality of , and the extensible behavior of . - - The interface, however, does not define a service contract itself. Those are declared by the service contract interface (typically generated from service metadata using a tool like the [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md)). WCF client types extend both and the target service contract interface to enable applications to call operations directly and also have access to client-side run-time functionality. Creating an WCF client provides WCF objects with the information necessary to create a run time that can connect and interact with the configured service endpoint. - - As mentioned earlier, the two WCF client types must be configured before you can use them. The simplest WCF client types are objects that derive from (or if the service contract is a duplex contract). You can create these types by using a constructor, configured programmatically, or by using a configuration file, and then called directly to invoke service operations. For a basic overview of objects, see [WCF Client Overview](../wcf-client-overview.md). - - The second type is generated at run time from a call to the method. Applications concerned with tight control of the communication specifics typically use this client type, called a *client channel object*, because it enables more direct interaction than the underlying client run-time and channel system. - -## Channel Factories - - The class that is responsible for creating the underlying run time that supports client invocations is the class. Both WCF client objects and WCF client channel objects use a object to create instances; the derived client object encapsulates the handling of the channel factory, but for a number of scenarios it is perfectly reasonable to use the channel factory directly. The common scenario for this is if you want to repeatedly create new client channels from an existing factory. If you are using a client object, you can obtain the underlying channel factory from a WCF client object by calling the property. - - The important thing to remember about channel factories is that they create new instances of client channels for the configuration provided to them prior to calling . Once you call (or , , or any operation on a WCF client object), you cannot modify the channel factory and expect to get channels to different service instances, even if you are merely changing the target endpoint address. If you want to create a client object or client channel with a different configuration, you must create a new channel factory first. - - For more information about various issues using WCF client objects and WCF client channels, see [Accessing Services Using a WCF Client](accessing-services-using-a-client.md). - - The following two sections describe the creation and use of WCF client channel objects. - -#### Creating a New WCF Client Channel Object - - To illustrate the use of a client channel, assume the following service contract has been generated. - - [!code-csharp[C_GeneratedCodeFiles#12](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_generatedcodefiles/cs/proxycode.cs#12)] - - To connect to an `ISampleService` service, use the generated contract interface directly with a channel factory (). Once you create and configure a channel factory for a particular contract, you can call the method to return client channel objects that you can use to communicate with an `ISampleService` service. - - When using the class with a service contract interface, you must cast to the interface to explicitly open, close, or abort the channel. To make it easier to work with, the Svcutil.exe tool also generates a helper interface that implements both the service contract interface and to enable you to interact with the client channel infrastructure without having to cast. The following code shows the definition of a helper client channel that implements the preceding service contract. - - [!code-csharp[C_GeneratedCodeFiles#13](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_generatedcodefiles/cs/proxycode.cs#13)] - -#### Creating a New WCF Client Channel Object - - To use a client channel to connect to an `ISampleService` service, use the generated contract interface (or the helper version) directly with a channel factory, passing the type of the contract interface as the type parameter. Once a channel factory for a particular contract has been created and configured, you can call the method to return client channel objects that you can use to communicate with an `ISampleService` service. - - When created, the client channel objects implement and the contract interface. Therefore, you can use them directly to call operations that interact with a service that supports that contract. - - The difference between using client objects and client channel objects is merely one of control and ease of use for developers. Many developers who are comfortable working with classes and objects will prefer to use the WCF client object instead of the WCF client channel. - +Applications use Windows Communication Foundation (WCF) client objects to invoke service operations. This topic discusses WCF client objects, WCF client channels, and their relationships to the underlying channel architecture. For a basic overview of WCF client objects, see [WCF Client Overview](../wcf-client-overview.md). For more information about the channel layer, see [Extending the Channel Layer](../extending/extending-the-channel-layer.md). + +## Overview + + The service model runtime creates WCF clients, which are composed of the following: + +- An automatically generated client implementation of a service contract, which turns calls from your application code into outgoing messages, and turns response messages into output parameters and return values that your application can retrieve. + +- An implementation of a control interface () that groups together various interfaces and provides access to control functionality, most notably the ability to close the client session and dispose the channel. + +- A client channel that is built based on the configuration settings specified by the used binding. + + Applications can create such clients on demand, either through a or by creating an instance of a derived class as it is generated by the [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md). These ready-built client classes encapsulate and delegate to a client channel implementation that is dynamically constructed by a . Therefore, the client channel and the channel factory that produces them are the focal point of interest for this discussion. + +## Client Objects and Client Channels + + The base interface of WCF clients is the interface, which exposes core client functionality as well as the basic communication object functionality of , the context functionality of , and the extensible behavior of . + + The interface, however, does not define a service contract itself. Those are declared by the service contract interface (typically generated from service metadata using a tool like the [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md)). WCF client types extend both and the target service contract interface to enable applications to call operations directly and also have access to client-side runtime functionality. Creating an WCF client provides WCF objects with the information necessary to create a runtime that can connect and interact with the configured service endpoint. + + As mentioned earlier, the two WCF client types must be configured before you can use them. The simplest WCF client types are objects that derive from (or if the service contract is a duplex contract). You can create these types by using a constructor, configured programmatically, or by using a configuration file, and then called directly to invoke service operations. For a basic overview of objects, see [WCF Client Overview](../wcf-client-overview.md). + + The second type is generated at runtime from a call to the method. Applications concerned with tight control of the communication specifics typically use this client type, called a *client channel object*, because it enables more direct interaction than the underlying client runtime and channel system. + +## Channel Factories + + The class that is responsible for creating the underlying runtime that supports client invocations is the class. Both WCF client objects and WCF client channel objects use a object to create instances; the derived client object encapsulates the handling of the channel factory, but for a number of scenarios it is perfectly reasonable to use the channel factory directly. The common scenario for this is if you want to repeatedly create new client channels from an existing factory. If you are using a client object, you can obtain the underlying channel factory from a WCF client object by calling the property. + + The important thing to remember about channel factories is that they create new instances of client channels for the configuration provided to them prior to calling . Once you call (or , , or any operation on a WCF client object), you cannot modify the channel factory and expect to get channels to different service instances, even if you are merely changing the target endpoint address. If you want to create a client object or client channel with a different configuration, you must create a new channel factory first. + + For more information about various issues using WCF client objects and WCF client channels, see [Accessing Services Using a WCF Client](accessing-services-using-a-client.md). + + The following two sections describe the creation and use of WCF client channel objects. + +#### Creating a New WCF Client Channel Object + + To illustrate the use of a client channel, assume the following service contract has been generated. + + [!code-csharp[C_GeneratedCodeFiles#12](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_generatedcodefiles/cs/proxycode.cs#12)] + + To connect to an `ISampleService` service, use the generated contract interface directly with a channel factory (). Once you create and configure a channel factory for a particular contract, you can call the method to return client channel objects that you can use to communicate with an `ISampleService` service. + + When using the class with a service contract interface, you must cast to the interface to explicitly open, close, or abort the channel. To make it easier to work with, the Svcutil.exe tool also generates a helper interface that implements both the service contract interface and to enable you to interact with the client channel infrastructure without having to cast. The following code shows the definition of a helper client channel that implements the preceding service contract. + + [!code-csharp[C_GeneratedCodeFiles#13](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_generatedcodefiles/cs/proxycode.cs#13)] + +#### Creating a New WCF Client Channel Object + + To use a client channel to connect to an `ISampleService` service, use the generated contract interface (or the helper version) directly with a channel factory, passing the type of the contract interface as the type parameter. Once a channel factory for a particular contract has been created and configured, you can call the method to return client channel objects that you can use to communicate with an `ISampleService` service. + + When created, the client channel objects implement and the contract interface. Therefore, you can use them directly to call operations that interact with a service that supports that contract. + + The difference between using client objects and client channel objects is merely one of control and ease of use for developers. Many developers who are comfortable working with classes and objects will prefer to use the WCF client object instead of the WCF client channel. + For an example, see [How to: Use the ChannelFactory](how-to-use-the-channelfactory.md). diff --git a/docs/framework/wcf/feature-details/configuring-discovery-in-a-configuration-file.md b/docs/framework/wcf/feature-details/configuring-discovery-in-a-configuration-file.md index 7f9a9e476af68..a123061c7e323 100644 --- a/docs/framework/wcf/feature-details/configuring-discovery-in-a-configuration-file.md +++ b/docs/framework/wcf/feature-details/configuring-discovery-in-a-configuration-file.md @@ -185,7 +185,7 @@ There are four major groups of configuration settings used in discovery. This to ## Standard Endpoint Configuration - Standard endpoints are predefined endpoints that have default values for one or more properties (address, binding, or contract) or one or more property values that cannot change. .NET 4 ships with 3 discovery related standard endpoints: , , and . The is a standard endpoint that is pre-configured for discovery operations over a UDP multicast binding. The is a standard endpoint that is pre-configured to send announcement messages over a UDP binding. The is a standard endpoint that uses discovery to find the endpoint address of a discovered service dynamically at run time. Standard bindings are specified with an `` element that contains kind attribute that specified the type of standard endpoint to add. The following example shows how to add a and a . + Standard endpoints are predefined endpoints that have default values for one or more properties (address, binding, or contract) or one or more property values that cannot change. .NET 4 ships with 3 discovery related standard endpoints: , , and . The is a standard endpoint that is pre-configured for discovery operations over a UDP multicast binding. The is a standard endpoint that is pre-configured to send announcement messages over a UDP binding. The is a standard endpoint that uses discovery to find the endpoint address of a discovered service dynamically at runtime. Standard bindings are specified with an `` element that contains kind attribute that specified the type of standard endpoint to add. The following example shows how to add a and a . ```xml diff --git a/docs/framework/wcf/feature-details/configuring-serialization-in-a-workflow-service.md b/docs/framework/wcf/feature-details/configuring-serialization-in-a-workflow-service.md index 0c9943b40cb1f..6a45d362237f1 100644 --- a/docs/framework/wcf/feature-details/configuring-serialization-in-a-workflow-service.md +++ b/docs/framework/wcf/feature-details/configuring-serialization-in-a-workflow-service.md @@ -6,42 +6,42 @@ ms.topic: how-to --- # Configuring Serialization in a Workflow Service -Workflow services are Windows Communication Foundation (WCF) services and so have the option of using either the (the default) or the . When writing non-workflow services the type of serializer to use is specified on the service or operation contract. When creating WCF workflow services you don't specify these contracts in code, but rather they are generated at run time by contract inference. For more information about contract inference, see [Using Contracts in Workflow](using-contracts-in-workflow.md). The serializer is specified using the property. This can be set in the designer as shown in the following illustration. - - ![Setting the SerializerOption property in the Properties Window.](./media/configuring-serialization-in-a-workflow-service/setting-serializer-property.png) - - The serializer can also be set in code as shown in the following example, - -```csharp -Receive approveExpense = new Receive - { - OperationName = "ApproveExpense", - CanCreateInstance = true, - ServiceContractName = "FinanceService", - SerializerOption = SerializerOption.DataContractSerializer, - Content = ReceiveContent.Create(new OutArgument(expense)) - }; -``` - +Workflow services are Windows Communication Foundation (WCF) services and so have the option of using either the (the default) or the . When writing non-workflow services the type of serializer to use is specified on the service or operation contract. When creating WCF workflow services you don't specify these contracts in code, but rather they are generated at runtime by contract inference. For more information about contract inference, see [Using Contracts in Workflow](using-contracts-in-workflow.md). The serializer is specified using the property. This can be set in the designer as shown in the following illustration. + + ![Setting the SerializerOption property in the Properties Window.](./media/configuring-serialization-in-a-workflow-service/setting-serializer-property.png) + + The serializer can also be set in code as shown in the following example, + +```csharp +Receive approveExpense = new Receive + { + OperationName = "ApproveExpense", + CanCreateInstance = true, + ServiceContractName = "FinanceService", + SerializerOption = SerializerOption.DataContractSerializer, + Content = ReceiveContent.Create(new OutArgument(expense)) + }; +``` + Known types can be specified on Workflow services as well. For more information about Known Types, see [Data Contract Known Types](data-contract-known-types.md). Known types can be specified in the designer or in code. To specify known types in the designer, click the ellipsis button next to the KnownTypes property in the **Properties Window** for a activity as shown in the following illustration. - - ![Screenshot of the KnownTypes property dialog box.](./media/configuring-serialization-in-a-workflow-service/known-types-properties.png) - - This displays the Type Collections Editor that allows you to search for and specify known types. - - ![Screenshot of the Type Collections Editor.](./media/configuring-serialization-in-a-workflow-service/type-collection-editor.gif) - - Click the **Add new type** link and use the drop down to select or search for a type to add to the known types collection. To specify known types in code use the property as shown in the following example. - + + ![Screenshot of the KnownTypes property dialog box.](./media/configuring-serialization-in-a-workflow-service/known-types-properties.png) + + This displays the Type Collections Editor that allows you to search for and specify known types. + + ![Screenshot of the Type Collections Editor.](./media/configuring-serialization-in-a-workflow-service/type-collection-editor.gif) + + Click the **Add new type** link and use the drop down to select or search for a type to add to the known types collection. To specify known types in code use the property as shown in the following example. + ```csharp -Receive approveExpense = new Receive - { - OperationName = "ApproveExpense", - CanCreateInstance = true, - ServiceContractName = "FinanceService", - SerializerOption = SerializerOption.DataContractSerializer, - Content = ReceiveContent.Create(new OutArgument(expense)) - }; - approveExpense.KnownTypes.Add(typeof(Travel)); - approveExpense.KnownTypes.Add(typeof(Meal)); +Receive approveExpense = new Receive + { + OperationName = "ApproveExpense", + CanCreateInstance = true, + ServiceContractName = "FinanceService", + SerializerOption = SerializerOption.DataContractSerializer, + Content = ReceiveContent.Create(new OutArgument(expense)) + }; + approveExpense.KnownTypes.Add(typeof(Travel)); + approveExpense.KnownTypes.Add(typeof(Meal)); ``` diff --git a/docs/framework/wcf/feature-details/contracts.md b/docs/framework/wcf/feature-details/contracts.md index 6945cd865c203..ee5ac4181a6c9 100644 --- a/docs/framework/wcf/feature-details/contracts.md +++ b/docs/framework/wcf/feature-details/contracts.md @@ -2,7 +2,7 @@ description: "Learn more about: Contracts" title: "Contracts" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "WCF [WCF], contracts" - "contracts [WCF]" - "Windows Communication Foundation [WCF], contracts" @@ -10,60 +10,60 @@ ms.assetid: c8364183-4ac1-480b-804a-c5e6c59a5d7d --- # Contracts -This section shows you how to define and implement Windows Communication Foundation (WCF)contracts. A service contract specifies what an endpoint communicates to the outside world. At a more concrete level, it is a statement about a set of specific messages organized into basic message exchange patterns (MEPs), such as request/reply, one-way, and duplex. If a service contract is a logically related set of message exchanges, a service operation is a single message exchange. For example, a `Hello` operation must obviously accept one message (so the caller can announce the greeting) and may or may not return a message (depending upon the courtesy of the operation). - - For more information about contracts and other core WCF concepts, see [Fundamental Windows Communication Foundation Concepts](../fundamental-concepts.md). This topic focuses on understanding service contracts. For more information about how to build clients that use service contracts to connect to services, see [WCF Client Overview](../wcf-client-overview.md). For more information about client channels, the client architecture, and other client issues, see [Clients](clients.md). - -## Overview - - This topic provides a high-level conceptual orientation to designing and implementing WCF services. Subtopics provide more detailed information about the specifics of designing and implementation. Before designing and implementing your WCF application, it is recommended that you: - -- Understand what a service contract is, how it works, and how to create one. - -- Understand that contracts state minimum requirements that run-time configuration or the hosting environment may not support. - -## Service Contracts - - A service contract is a statement that provides information about: - -- The grouping of operations in a service. - -- The signature of the operations in terms of messages exchanged. - -- The data types of these messages. - -- The location of the operations. - -- The specific protocols and serialization formats that are used to support successful communication with the service. - - For example, a purchase order contract might have a `CreateOrder` operation that accepts an input of order information types and returns success or failure information, including an order identifier. It might also have a `GetOrderStatus` operation that accepts an order identifier and returns order status information. A service contract of this sort would specify: - -- That the purchase order contract consisted of `CreateOrder` and `GetOrderStatus` operations. - -- That the operations have specified input messages and output messages. - -- The data that these messages can carry. - -- Categorical statements about the communication infrastructure necessary to successfully process the messages. For example, these details include whether and what forms of security are required to establish successful communication. - - To convey this kind of information to applications on other platforms (including non-Microsoft platforms), XML service contracts are publicly expressed in standard XML formats, such as [Web Services Description Language (WSDL)](https://www.w3.org/TR/2001/NOTE-wsdl-20010315) and [XML Schema (XSD)](https://www.w3.org/XML/Schema), among others. Developers for many platforms can use this public contract information to create applications that can communicate with the service, both because they understand the language of the specification and because those languages are designed to enable interoperation by describing the public forms, formats, and protocols that the service supports. For more information about how WCF handles this kind of information, see [Metadata](metadata.md). - - Contracts can be expressed many ways, however, and while WSDL and XSD are excellent languages to describe services in an accessible way, they are difficult languages to use directly—in any case, they are merely descriptions of a service, not service contract implementations. Therefore, WCF applications use managed attributes, interfaces, and classes both to define the structure of and to implement a service. - - The resulting contract defined in managed types can be converted (also called *exported*) as metadata—WSDL and XSD—when needed by clients or other service implementers, especially on other platforms. The result is a straightforward programming model that can be described using public metadata to any client application. The details of the underlying SOAP messages, such as the transportation and security-related information, can be left to WCF, which automatically performs the necessary conversions to and from the service contract type system to the XML type system. - - For more information about designing contracts, see [Designing Service Contracts](../designing-service-contracts.md). For more information about implementing contracts, see [Implementing Service Contracts](../implementing-service-contracts.md). - - In addition, WCF also provides the ability to develop service contracts entirely at the message level. For more information about developing service contracts at the message level, see [Using Message Contracts](using-message-contracts.md). For more information about developing services in non-SOAP XML, see [Interoperability with POX Applications](interoperability-with-pox-applications.md). - -### Understanding the Hierarchy of Requirements - - A service contract groups the operations; specifies the MEP, message types, and data types those messages carry; and indicates categories of run-time behavior an implementation must have to support the contract (for example, it may require that messages be encrypted and signed). The service contract itself, however, does not specify precisely how these requirements are met, only that they must be. What type of encryption or how a message is signed is up to the implementation and configuration of a compliant service. - - Notice the way that the contract requires certain things of the service contract implementation and the run-time configuration to add behavior. The set of requirements that must be met to expose a service for use builds on the preceding set of requirements. If a contract makes requirements of the implementation, an implementation can require yet more of the configuration and bindings that enable the service to run. Finally, the host application must also support any requirements that the service configuration and bindings add. - - This additive requirement process is important to keep in mind while designing, implementing, configuring, and hosting your Windows Communication Foundation (WCF) service application. For example, the contract can specify that it needs to support a session. If so, then you must configure the binding to support that contractual requirement, or the service implementation will not work. Or if your service requires Integrated Windows authentication and is hosted in Internet Information Services (IIS), the Web application in which the service resides must have Integrated Windows authentication turned on and anonymous support turned off. For more information about the features and impact of the different service host application types, see [Hosting](hosting.md). - +This section shows you how to define and implement Windows Communication Foundation (WCF)contracts. A service contract specifies what an endpoint communicates to the outside world. At a more concrete level, it is a statement about a set of specific messages organized into basic message exchange patterns (MEPs), such as request/reply, one-way, and duplex. If a service contract is a logically related set of message exchanges, a service operation is a single message exchange. For example, a `Hello` operation must obviously accept one message (so the caller can announce the greeting) and may or may not return a message (depending upon the courtesy of the operation). + + For more information about contracts and other core WCF concepts, see [Fundamental Windows Communication Foundation Concepts](../fundamental-concepts.md). This topic focuses on understanding service contracts. For more information about how to build clients that use service contracts to connect to services, see [WCF Client Overview](../wcf-client-overview.md). For more information about client channels, the client architecture, and other client issues, see [Clients](clients.md). + +## Overview + + This topic provides a high-level conceptual orientation to designing and implementing WCF services. Subtopics provide more detailed information about the specifics of designing and implementation. Before designing and implementing your WCF application, it is recommended that you: + +- Understand what a service contract is, how it works, and how to create one. + +- Understand that contracts state minimum requirements that runtime configuration or the hosting environment may not support. + +## Service Contracts + + A service contract is a statement that provides information about: + +- The grouping of operations in a service. + +- The signature of the operations in terms of messages exchanged. + +- The data types of these messages. + +- The location of the operations. + +- The specific protocols and serialization formats that are used to support successful communication with the service. + + For example, a purchase order contract might have a `CreateOrder` operation that accepts an input of order information types and returns success or failure information, including an order identifier. It might also have a `GetOrderStatus` operation that accepts an order identifier and returns order status information. A service contract of this sort would specify: + +- That the purchase order contract consisted of `CreateOrder` and `GetOrderStatus` operations. + +- That the operations have specified input messages and output messages. + +- The data that these messages can carry. + +- Categorical statements about the communication infrastructure necessary to successfully process the messages. For example, these details include whether and what forms of security are required to establish successful communication. + + To convey this kind of information to applications on other platforms (including non-Microsoft platforms), XML service contracts are publicly expressed in standard XML formats, such as [Web Services Description Language (WSDL)](https://www.w3.org/TR/2001/NOTE-wsdl-20010315) and [XML Schema (XSD)](https://www.w3.org/XML/Schema), among others. Developers for many platforms can use this public contract information to create applications that can communicate with the service, both because they understand the language of the specification and because those languages are designed to enable interoperation by describing the public forms, formats, and protocols that the service supports. For more information about how WCF handles this kind of information, see [Metadata](metadata.md). + + Contracts can be expressed many ways, however, and while WSDL and XSD are excellent languages to describe services in an accessible way, they are difficult languages to use directly—in any case, they are merely descriptions of a service, not service contract implementations. Therefore, WCF applications use managed attributes, interfaces, and classes both to define the structure of and to implement a service. + + The resulting contract defined in managed types can be converted (also called *exported*) as metadata—WSDL and XSD—when needed by clients or other service implementers, especially on other platforms. The result is a straightforward programming model that can be described using public metadata to any client application. The details of the underlying SOAP messages, such as the transportation and security-related information, can be left to WCF, which automatically performs the necessary conversions to and from the service contract type system to the XML type system. + + For more information about designing contracts, see [Designing Service Contracts](../designing-service-contracts.md). For more information about implementing contracts, see [Implementing Service Contracts](../implementing-service-contracts.md). + + In addition, WCF also provides the ability to develop service contracts entirely at the message level. For more information about developing service contracts at the message level, see [Using Message Contracts](using-message-contracts.md). For more information about developing services in non-SOAP XML, see [Interoperability with POX Applications](interoperability-with-pox-applications.md). + +### Understanding the Hierarchy of Requirements + + A service contract groups the operations; specifies the MEP, message types, and data types those messages carry; and indicates categories of runtime behavior an implementation must have to support the contract (for example, it may require that messages be encrypted and signed). The service contract itself, however, does not specify precisely how these requirements are met, only that they must be. What type of encryption or how a message is signed is up to the implementation and configuration of a compliant service. + + Notice the way that the contract requires certain things of the service contract implementation and the runtime configuration to add behavior. The set of requirements that must be met to expose a service for use builds on the preceding set of requirements. If a contract makes requirements of the implementation, an implementation can require yet more of the configuration and bindings that enable the service to run. Finally, the host application must also support any requirements that the service configuration and bindings add. + + This additive requirement process is important to keep in mind while designing, implementing, configuring, and hosting your Windows Communication Foundation (WCF) service application. For example, the contract can specify that it needs to support a session. If so, then you must configure the binding to support that contractual requirement, or the service implementation will not work. Or if your service requires Integrated Windows authentication and is hosted in Internet Information Services (IIS), the Web application in which the service resides must have Integrated Windows authentication turned on and anonymous support turned off. For more information about the features and impact of the different service host application types, see [Hosting](hosting.md). + ## See also - [Endpoints: Addresses, Bindings, and Contracts](endpoints-addresses-bindings-and-contracts.md) diff --git a/docs/framework/wcf/feature-details/custom-filters.md b/docs/framework/wcf/feature-details/custom-filters.md index eee4480c7b5ec..3c6b5fc5dd537 100644 --- a/docs/framework/wcf/feature-details/custom-filters.md +++ b/docs/framework/wcf/feature-details/custom-filters.md @@ -6,79 +6,79 @@ ms.assetid: 97cf247d-be0a-4057-bba9-3be5c45029d5 --- # Custom Filters -Custom filters allow you to define matching logic that cannot be accomplished using the system-provided message filters. For example, you might create a custom filter that hashes a particular message element and then examines the value to determine whether the filter should return true or false. - -## Implementation - - A custom filter is an implementation of the abstract base class. When implementing your custom filter, the constructor can optionally accept a single string parameter. This parameter contains the configuration information that is passed to the MessageFilter constructor in order to provide any values or configuration that the filter needs at run time in order to perform matches. For example, this might be used to provide a value that the filter looks for within the message being evaluated. The following example demonstrates a basic implementation of a custom message filter that accepts a string parameter: - -```csharp -public class MyMessageFilter: MessageFilter -{ - string filterData; - public MyMessageFilter(string filterData) - { - if(string.IsNullOrEmpty(filterData) - throw new ArgumentNullException("filterData"); - this.filterData=filterData; - } - public override bool Match(System.ServiceModel.Channels.Message message) - { - ... - return retValue; - } - public override bool Match(System.ServiceModel.Channels.MessageBuffer buffer) - { - ... - return retValue; - } -} -``` - +Custom filters allow you to define matching logic that cannot be accomplished using the system-provided message filters. For example, you might create a custom filter that hashes a particular message element and then examines the value to determine whether the filter should return true or false. + +## Implementation + + A custom filter is an implementation of the abstract base class. When implementing your custom filter, the constructor can optionally accept a single string parameter. This parameter contains the configuration information that is passed to the MessageFilter constructor in order to provide any values or configuration that the filter needs at runtime in order to perform matches. For example, this might be used to provide a value that the filter looks for within the message being evaluated. The following example demonstrates a basic implementation of a custom message filter that accepts a string parameter: + +```csharp +public class MyMessageFilter: MessageFilter +{ + string filterData; + public MyMessageFilter(string filterData) + { + if(string.IsNullOrEmpty(filterData) + throw new ArgumentNullException("filterData"); + this.filterData=filterData; + } + public override bool Match(System.ServiceModel.Channels.Message message) + { + ... + return retValue; + } + public override bool Match(System.ServiceModel.Channels.MessageBuffer buffer) + { + ... + return retValue; + } +} +``` + > [!NOTE] -> In an actual implementation, the Match method(s) contains logic that will examine the message to determine if this message filter should return **true** or **false**. - -### Performance - - When implementing a custom filter, it is important to take into consideration the maximum length of time required for the filter to complete the evaluation of a message. Since a message may be evaluated against multiple filters before a match is found, it is important to ensure that the client request does not time out before all filters can be evaluated. Therefore a custom filter should contain only the code necessary to evaluate the contents or attributes of a message in order to determine if it matches the filter criteria. - - In general, you should avoid the following when implementing a custom filter: - -- IO, such as saving data to disk or to a database. - -- Unnecessary processing, such as looping over multiple records in a document. - -- Blocking operations, such as calls that involve obtaining a lock on shared resources or performing lookups against a database. - - Before using a custom filter in a production environment, you should run performance tests to determine the average length of time that the filter takes to evaluate a message. When combined with the average processing time of the other filters used in the filter table, this will allow you to accurately determine the maximum timeout value that should be specified by the client application. - -## Usage - - In order to use your custom filter with the Routing Service, you must add it to the filter table by specifying a new filter entry of type "Custom," the fully qualified type name of the message filter, and the name of your assembly. As with other MessageFilters, you can specify the string filterData that will be passed to your custom filter’s constructor. - - The following examples demonstrate using a custom filter with the Routing Service: - -```xml - - - +> In an actual implementation, the Match method(s) contains logic that will examine the message to determine if this message filter should return **true** or **false**. + +### Performance + + When implementing a custom filter, it is important to take into consideration the maximum length of time required for the filter to complete the evaluation of a message. Since a message may be evaluated against multiple filters before a match is found, it is important to ensure that the client request does not time out before all filters can be evaluated. Therefore a custom filter should contain only the code necessary to evaluate the contents or attributes of a message in order to determine if it matches the filter criteria. + + In general, you should avoid the following when implementing a custom filter: + +- IO, such as saving data to disk or to a database. + +- Unnecessary processing, such as looping over multiple records in a document. + +- Blocking operations, such as calls that involve obtaining a lock on shared resources or performing lookups against a database. + + Before using a custom filter in a production environment, you should run performance tests to determine the average length of time that the filter takes to evaluate a message. When combined with the average processing time of the other filters used in the filter table, this will allow you to accurately determine the maximum timeout value that should be specified by the client application. + +## Usage + + In order to use your custom filter with the Routing Service, you must add it to the filter table by specifying a new filter entry of type "Custom," the fully qualified type name of the message filter, and the name of your assembly. As with other MessageFilters, you can specify the string filterData that will be passed to your custom filter’s constructor. + + The following examples demonstrate using a custom filter with the Routing Service: + +```xml + + + - - - - - - -
-
-
-``` - -```csharp -RoutingConfiguration rc = new RoutingConfiguration(); -List endpointList = new List(); -endpointList.Add(client); -rc.FilterTable.Add(new MyMessageFilter("CustomData"), endpointList); + CustomAssembly" filterData="custom data" /> +
+ + + + + +
+
+
+``` + +```csharp +RoutingConfiguration rc = new RoutingConfiguration(); +List endpointList = new List(); +endpointList.Add(client); +rc.FilterTable.Add(new MyMessageFilter("CustomData"), endpointList); ``` diff --git a/docs/framework/wcf/feature-details/data-transfer-architectural-overview.md b/docs/framework/wcf/feature-details/data-transfer-architectural-overview.md index 640e7c251aa26..3c8d4384fd647 100644 --- a/docs/framework/wcf/feature-details/data-transfer-architectural-overview.md +++ b/docs/framework/wcf/feature-details/data-transfer-architectural-overview.md @@ -2,295 +2,295 @@ description: "Learn more about: Data Transfer Architectural Overview" title: "Data Transfer Architectural Overview" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" -helpviewer_keywords: +helpviewer_keywords: - "data transfer [WCF], architectural overview" ms.assetid: 343c2ca2-af53-4936-a28c-c186b3524ee9 --- # Data Transfer Architectural Overview -Windows Communication Foundation (WCF) can be thought of as a messaging infrastructure. It can receive messages, process them, and dispatch them to user code for further action, or it can construct messages from data given by user code and deliver them to a destination. This topic, which is intended for advanced developers, describes the architecture for handling messages and the contained data. For a simpler, task-oriented view of how to send and receive data, see [Specifying Data Transfer in Service Contracts](specifying-data-transfer-in-service-contracts.md). - +Windows Communication Foundation (WCF) can be thought of as a messaging infrastructure. It can receive messages, process them, and dispatch them to user code for further action, or it can construct messages from data given by user code and deliver them to a destination. This topic, which is intended for advanced developers, describes the architecture for handling messages and the contained data. For a simpler, task-oriented view of how to send and receive data, see [Specifying Data Transfer in Service Contracts](specifying-data-transfer-in-service-contracts.md). + > [!NOTE] -> This topic discusses WCF implementation details that are not visible by examining the WCF object model. Two words of caution are in order with regard to documented implementation details. First, the descriptions are simplified; actual implementation may be more complex due to optimizations or other reasons. Second, you should never rely on specific implementation details, even documented ones, because these may change without notice from version to version or even in a servicing release. - -## Basic Architecture - - At the core of WCF message-handling capabilities is the class, which is described in detail in [Using the Message Class](using-the-message-class.md). The run-time components of WCF can be divided into two major parts: the channel stack and the service framework, with the class being the connection point. - - The channel stack is responsible for converting between a valid instance and some action that corresponds to the sending or receiving of message data. On the sending side, the channel stack takes a valid instance and, after some processing, performs some action that logically corresponds to sending the message. The action may be sending TCP or HTTP packets, queuing the message in Message Queuing, writing the message to a database, saving it to a file share, or any other action, depending on the implementation. The most common action is sending the message over a network protocol. On the receive side, the opposite happens—an action is detected (which may be TCP or HTTP packets arriving or any other action), and, after processing, the channel stack converts this action into a valid instance. - - You can use WCF by using the class and the channel stack directly. However, doing so is difficult and time-consuming. Additionally, the object provides no metadata support, so you cannot generate strongly typed WCF clients if you use WCF in this manner. - - Therefore, WCF includes a service framework that provides an easy-to-use programming model that you can use to construct and receive `Message` objects. The service framework maps services to .NET Framework types through the notion of service contracts, and dispatches messages to user operations that are simply .NET Framework methods marked with the attribute (for more details, see [Designing Service Contracts](../designing-service-contracts.md)). These methods may have parameters and return values. On the service side, the service framework converts incoming instances into parameters and converts return values into outgoing instances. On the client side, it does the opposite. For example, consider the `FindAirfare` operation below. - +> This topic discusses WCF implementation details that are not visible by examining the WCF object model. Two words of caution are in order with regard to documented implementation details. First, the descriptions are simplified; actual implementation may be more complex due to optimizations or other reasons. Second, you should never rely on specific implementation details, even documented ones, because these may change without notice from version to version or even in a servicing release. + +## Basic Architecture + + At the core of WCF message-handling capabilities is the class, which is described in detail in [Using the Message Class](using-the-message-class.md). The runtime components of WCF can be divided into two major parts: the channel stack and the service framework, with the class being the connection point. + + The channel stack is responsible for converting between a valid instance and some action that corresponds to the sending or receiving of message data. On the sending side, the channel stack takes a valid instance and, after some processing, performs some action that logically corresponds to sending the message. The action may be sending TCP or HTTP packets, queuing the message in Message Queuing, writing the message to a database, saving it to a file share, or any other action, depending on the implementation. The most common action is sending the message over a network protocol. On the receive side, the opposite happens—an action is detected (which may be TCP or HTTP packets arriving or any other action), and, after processing, the channel stack converts this action into a valid instance. + + You can use WCF by using the class and the channel stack directly. However, doing so is difficult and time-consuming. Additionally, the object provides no metadata support, so you cannot generate strongly typed WCF clients if you use WCF in this manner. + + Therefore, WCF includes a service framework that provides an easy-to-use programming model that you can use to construct and receive `Message` objects. The service framework maps services to .NET Framework types through the notion of service contracts, and dispatches messages to user operations that are simply .NET Framework methods marked with the attribute (for more details, see [Designing Service Contracts](../designing-service-contracts.md)). These methods may have parameters and return values. On the service side, the service framework converts incoming instances into parameters and converts return values into outgoing instances. On the client side, it does the opposite. For example, consider the `FindAirfare` operation below. + [!code-csharp[c_DataArchitecture#1](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_dataarchitecture/cs/source.cs#1)] - [!code-vb[c_DataArchitecture#1](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_dataarchitecture/vb/source.vb#1)] - - Suppose `FindAirfare` is called on the client. The service framework on the client converts the `FromCity` and `ToCity` parameters into an outgoing instance and passes it to the channel stack to be sent. - - On the service side, when a instance arrives from the channel stack, the service framework extracts the relevant data from the message to populate the `FromCity` and `ToCity` parameters and then calls the service-side `FindAirfare` method. When the method returns, the service framework takes the returned integer value and the `IsDirectFlight` output parameter and creates a object instance that contains this information. It then passes the `Message` instance to the channel stack to be sent back to the client. - - On the client side, a instance that contains the response message emerges from the channel stack. The service framework extracts the return value and the `IsDirectFlight` value and returns these to the caller of the client. - -## Message Class - - The class is intended to be an abstract representation of a message, but its design is strongly tied to the SOAP message. A contains three major pieces of information: a message body, message headers, and message properties. - -## Message Body - - The message body is intended to represent the actual data payload of the message. The message body is always represented as an XML Infoset. This does not mean that all messages created or received in WCF must be in XML format. It is up to the channel stack to decide how to interpret the message body. It may emit it as XML, convert it to some other format, or even omit it entirely. Of course, with most of the bindings WCF supplies, the message body is represented as XML content in the body section of a SOAP envelope. - - It is important to realize that the `Message` class does not necessarily contain a buffer with XML data representing the body. Logically, `Message` contains an XML Infoset, but this Infoset may be dynamically constructed and may never physically exist in memory. - -### Putting Data into the Message Body - - There is no uniform mechanism to put data into a message body. The class has an abstract method, , which takes an . Each subclass of the class is responsible for overriding this method and writing out its own contents. The message body logically contains the XML Infoset that `OnWriteBodyContent` produces. For example, consider the following `Message` subclass. - + [!code-vb[c_DataArchitecture#1](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_dataarchitecture/vb/source.vb#1)] + + Suppose `FindAirfare` is called on the client. The service framework on the client converts the `FromCity` and `ToCity` parameters into an outgoing instance and passes it to the channel stack to be sent. + + On the service side, when a instance arrives from the channel stack, the service framework extracts the relevant data from the message to populate the `FromCity` and `ToCity` parameters and then calls the service-side `FindAirfare` method. When the method returns, the service framework takes the returned integer value and the `IsDirectFlight` output parameter and creates a object instance that contains this information. It then passes the `Message` instance to the channel stack to be sent back to the client. + + On the client side, a instance that contains the response message emerges from the channel stack. The service framework extracts the return value and the `IsDirectFlight` value and returns these to the caller of the client. + +## Message Class + + The class is intended to be an abstract representation of a message, but its design is strongly tied to the SOAP message. A contains three major pieces of information: a message body, message headers, and message properties. + +## Message Body + + The message body is intended to represent the actual data payload of the message. The message body is always represented as an XML Infoset. This does not mean that all messages created or received in WCF must be in XML format. It is up to the channel stack to decide how to interpret the message body. It may emit it as XML, convert it to some other format, or even omit it entirely. Of course, with most of the bindings WCF supplies, the message body is represented as XML content in the body section of a SOAP envelope. + + It is important to realize that the `Message` class does not necessarily contain a buffer with XML data representing the body. Logically, `Message` contains an XML Infoset, but this Infoset may be dynamically constructed and may never physically exist in memory. + +### Putting Data into the Message Body + + There is no uniform mechanism to put data into a message body. The class has an abstract method, , which takes an . Each subclass of the class is responsible for overriding this method and writing out its own contents. The message body logically contains the XML Infoset that `OnWriteBodyContent` produces. For example, consider the following `Message` subclass. + [!code-csharp[c_DataArchitecture#2](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_dataarchitecture/cs/source.cs#2)] - [!code-vb[c_DataArchitecture#2](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_dataarchitecture/vb/source.vb#2)] - - Physically, an `AirfareRequestMessage` instance contains only two strings ("fromCity" and "toCity"). However, logically the message contains the following XML infoset: - -```xml - - Tokyo - London - -``` - - Of course, you would normally not create messages in this manner, because you can use the service framework to create a message like the preceding one from operation contract parameters. Additionally, the class has static `CreateMessage` methods that you can use to create messages with common types of content: an empty message, a message that contains an object serialized to XML with the , a message that contains a SOAP fault, a message that contains XML represented by an , and so on. - -### Getting Data from a Message Body - - You can extract the data stored in a message body in two main ways: - -- You can get the entire message body at one time by calling the method and passing in an XML writer. The complete message body is written out to this writer. Getting the entire message body at one time is also called *writing a message*. Writing is done primarily by the channel stack when sending messages—some part of the channel stack will usually get access to the entire message body, encode it, and send it. - -- Another way to get information out of the message body is to call and get an XML reader. The message body can then be accessed sequentially as needed by calling methods on the reader. Getting the message body piece-by-piece is also called *reading a message*. Reading the message is primarily used by the service framework when receiving messages. For example, when the is in use, the service framework will get an XML reader over the body and pass it to the deserialization engine, which will then start reading the message element-by-element and constructing the corresponding object graph. - - A message body can be retrieved only once. This makes it possible to work with forward-only streams. For example, you can write an override that reads from a and returns the results as an XML Infoset. You will never need to "rewind" to the beginning of the file. - - The `WriteBodyContents` and `GetReaderAtBodyContents` methods simply check that the message body has never been retrieved before, and then call `OnWriteBodyContents` or `OnGetReaderAtBodyContents`, respectively. - -## Message Usage in WCF - - Most messages can be classified as either *outgoing* (those that are created by the service framework to be sent by the channel stack) or *incoming* (those that arrive from the channel stack and are interpreted by the service framework). Furthermore, the channel stack can operate in either buffered or streaming mode. The service framework may also expose a streamed or nonstreamed programming model. This leads to the cases listed in the following table, along with simplified details of their implementation. - -|Message type|Body data in message|Write (OnWriteBodyContents) implementation|Read (OnGetReaderAtBodyContents) Implementation| -|------------------|--------------------------|--------------------------------------------------|-------------------------------------------------------| -|Outgoing, created from nonstreamed programming model|The data needed to write the message (for example, an object and the instance needed to serialize it)*|Custom logic to write out the message based on the stored data (for example, call `WriteObject` on the `DataContractSerializer` if that is the serializer in use)*|Call `OnWriteBodyContents`, buffer the results, return an XML reader over the buffer| -|Outgoing, created from streamed programming model|The `Stream` with the data to be written*|Write out data from the stored stream using the mechanism*|Call `OnWriteBodyContents`, buffer the results, return an XML reader over the buffer| -|Incoming from streaming channel stack|A `Stream` object that represents the data coming in over the network with an over it|Write out the contents from the stored `XmlReader` using `WriteNode`|Returns the stored `XmlReader`| -|Incoming from nonstreaming channel stack|A buffer that contains body data with an `XmlReader` over it|Writes out the contents from the stored `XmlReader` using `WriteNode`|Returns the stored lang| - - \* These items are not implemented directly in `Message` subclasses, but in subclasses of the class. For more information about the , see [Using the Message Class](using-the-message-class.md). - -## Message Headers - - A message may contain headers. A header logically consists of an XML Infoset that is associated with a name, a namespace, and a few other properties. Message headers are accessed using the `Headers` property on . Each header is represented by a class. Normally, message headers are mapped to SOAP message headers when using a channel stack configured to work with SOAP messages. - - Putting information into a message header and extracting information from it is similar to using the message body. The process is somewhat simplified because streaming is not supported. It is possible to access the contents of the same header more than once, and headers can be accessed in arbitrary order, forcing headers to always be buffered. There is no general-purpose mechanism available to get an XML reader over a header, but there is a `MessageHeader` subclass internal to WCF that represents a readable header with such a capability. This type of `MessageHeader` is created by the channel stack when a message with custom application headers comes in. This enables the service framework to use a deserialization engine, such as the , to interpret these headers. - - For more information, see [Using the Message Class](using-the-message-class.md). - -## Message Properties - - A message may contain properties. A *property* is any .NET Framework object that is associated with a string name. Properties are accessed through the `Properties` property on `Message`. - - Unlike the message body and message headers (which normally map to the SOAP body and SOAP headers, respectively), message properties are normally not sent or received along with the messages. Message properties exist primarily as a communication mechanism to pass data about the message between the various channels in the channel stack, and between the channel stack and the service model. - - For example, the HTTP transport channel included as part of WCF is capable of producing various HTTP status codes, such as "404 (Not Found)" and "500 (Internal Server Error)," when it sends replies to clients. Before sending a reply message, it checks to see whether the `Properties` of the `Message` contain a property called "httpResponse" that contains an object of type . If such a property is found, it will look at the property and use that status code. If it is not found, the default "200 (OK)" code is used. - - For more information, see [Using the Message Class](using-the-message-class.md). - -### The Message as a Whole - - So far, we have discussed methods for accessing the various parts of the message in isolation. However, the class also provides methods to work with the entire message as a whole. For example, the `WriteMessage` method writes out the entire message to an XML writer. - - For this to be possible, a mapping must be defined between the entire `Message` instance and an XML Infoset. Such a mapping, in fact, exists: WCF uses the SOAP standard to define this mapping. When a `Message` instance is written out as an XML Infoset, the resulting Infoset is the valid SOAP envelope that contains the message. Thus, `WriteMessage` would normally perform the following steps: - -1. Write the SOAP envelope element opening tag. - -2. Write the SOAP header element opening tag, write out all of the headers, and close the header element. - -3. Write the SOAP body element opening tag. - -4. Call `WriteBodyContents` or an equivalent method to write out the body. - -5. Close the body and envelope elements. - - The preceding steps are closely tied to the SOAP standard. This is complicated by the fact that multiple versions of SOAP exist, for example, it is impossible to write out the SOAP envelope element correctly without knowing the SOAP version in use. Also, in some cases, it may be desirable to turn off this complex SOAP-specific mapping completely. - - For these purposes, a `Version` property is provided on `Message`. It can be set to the SOAP version to use when writing out the message, or it can be set to `None` to prevent any SOAP-specific mappings. If the `Version` property is set to `None`, methods that work with the entire message act as if the message consisted of its body only, for example, `WriteMessage` would simply call `WriteBodyContents` instead of performing the multiple steps listed above. It is expected that on incoming messages, `Version` will be auto-detected and set correctly. - -## The Channel Stack - -### Channels - - As stated before, the channel stack is responsible for converting outgoing instances into some action (such as sending packets over the network), or converting some action (such as receiving network packets) into incoming `Message` instances. - - The channel stack is composed of one or more channels ordered in a sequence. An outgoing `Message` instance is passed to the first channel in the stack (also called the *topmost channel*), which passes it to the next channel down in stack, and so on. The message terminates in the last channel, which is called the *transport channel*. Incoming messages originate in the transport channel and are passed from channel to channel up the stack. From the topmost channel, the message is usually passed into the service framework. While this is the usual pattern for application messages, some channels may work slightly differently, for example, they may send their own infrastructure messages without being passed a message from a channel above. - - Channels may operate on the message in various ways as it passes through the stack. The most common operation is adding a header to an outgoing message and reading headers on an incoming message. For example, a channel may compute the digital signature of a message and add it as a header. A channel may also inspect this digital signature header on incoming messages and block messages that do not have a valid signature from making their way up the channel stack. Channels also often set or inspect message properties. The message body is usually not modified, although this is allowed, for example, the WCF security channel can encrypt the message body. - -### Transport Channels and Message Encoders - - The bottommost channel in the stack is responsible for actually transforming an outgoing , as modified by other channels, into some action. On the receive side, this is the channel that converts some action into a `Message` that other channels process. - - As stated previously, the actions may be varied: sending or receiving network packets over various protocols, reading or writing the message in a database, or queuing or dequeuing the message in a Message Queuing queue, to provide but a few examples. All these actions have one thing in common: they require a transformation between the WCF`Message` instance and an actual group of bytes that can be sent, received, read, written, queued, or dequeued. The process of converting a `Message` into a group of bytes is called *encoding*, and the reverse process of creating a `Message` from a group of bytes is called *decoding*. - - Most transport channels use components called *message encoders* to accomplish the encoding and decoding work. A message encoder is a subclass of the class. `MessageEncoder` includes various `ReadMessage` and `WriteMessage` method overloads to convert between `Message` and groups of bytes. - - On the sending side, a buffering transport channel passes the `Message` object that it received from a channel above it to `WriteMessage`. It gets back an array of bytes, which it then uses to perform its action (such as packaging these bytes as valid TCP packets and sending them to the correct destination). A streaming transport channel first creates a `Stream` (for example, over the outgoing TCP connection), and then passes both the `Stream` and the `Message` it needs to send to the appropriate `WriteMessage` overload, which writes out the message. - - On the receiving side, a buffering transport channel extracts incoming bytes (for example, from incoming TCP packets) into an array and calls `ReadMessage` to get a `Message` object that it can pass further up the channel stack. A streaming transport channel creates a `Stream` object (for example, a network stream over the incoming TCP connection) and passes that to `ReadMessage` to get back a `Message` object. - - The separation between the transport channels and the message encoder is not mandatory; it is possible to write a transport channel that does not use a message encoder. However, the advantage of this separation is ease of composition. As long as a transport channel uses only the base , it can work with any WCF or third-party message encoder. Likewise, the same encoder can normally be used in any transport channel. - -### Message Encoder Operation - - To describe the typical operation of an encoder, it is useful to consider the following four cases. - -|Operation|Comment| -|---------------|-------------| -|Encoding, Buffered|In buffered mode, the encoder normally creates a variable-size buffer and then creates an XML writer over it. It then calls on the message being encoded, which writes out the headers and then the body using , as explained in the preceding section about `Message` in this topic. The contents of the buffer (represented as an array of bytes) are then returned for the transport channel to use.| -|Encoding, Streamed|In streamed mode, the operation is similar to the above, but simpler. There is no need for a buffer. An XML writer is normally created over the stream and is called on the `Message` to write it out to this writer.| -|Decoding, Buffered|When decoding in buffered mode, a special `Message` subclass that contains the buffered data is normally created. The headers of the message are read, and an XML reader positioned on the message body is created. This is the reader that will be returned with .| -|Decoding, Streamed|When decoding in streamed mode, a special Message subclass is normally created. The stream is advanced just enough to read all the headers and position it on the message body. An XML reader is then created over the stream. This is the reader that will be returned with .| - - Encoders can perform other functions as well. For example, the encoders can pool XML readers and writers. It is expensive to create a new XML reader or writer every time one is needed. Therefore, encoders normally maintain a pool of readers and a pool of writers of configurable size. In the descriptions of encoder operation described previously, whenever the phrase "create an XML reader/writer" is used, it normally means "take one from the pool, or create one if one is not available." The encoder (and the `Message` subclasses it creates while decoding) contain logic to return readers and writers to the pools once they are no longer needed (for example, when the `Message` is closed). - - WCF provides three message encoders, although it is possible to create additional custom types. The supplied types are Text, Binary, and Message Transmission Optimization Mechanism (MTOM). These are described in detail in [Choosing a Message Encoder](choosing-a-message-encoder.md). - -### The IStreamProvider Interface - - When writing an outgoing message that contains a streamed body to an XML writer, the uses a sequence of calls similar to the following in its implementation: - -- Write any necessary information preceding the stream (for example, the opening XML tag). - -- Write the stream. - -- Write any information following the stream (for example, the closing XML tag). - - This works well with encodings that are similar to the textual XML encoding. However, some encodings do not place XML Infoset information (for example, tags for starting and ending XML elements) together with the data contained within elements. For example, in the MTOM encoding, the message is split into multiple parts. One part contains the XML Infoset, which may contain references to other parts for actual element contents. The XML Infoset is normally small compared to the streamed contents, so it makes sense to buffer the Infoset, write it out, and then write the contents in a streamed way. This means that by the time the closing element tag is written, the stream should not have been written out yet. - - For this purpose, the interface is used. The interface has a method that returns the stream to be written. The correct way to write out a streamed message body in is as follows: - -1. Write any necessary information preceding the stream (for example, the opening XML tag). - -2. Call the `WriteValue` overload on the that takes an , with an `IStreamProvider` implementation that returns the stream to be written. - -3. Write any information following the stream (for example, the closing XML tag). - - With this approach, the XML writer has a choice of when to call and write out the streamed data. For example, the textual and binary XML writers will call it immediately and write out the streamed contents in-between the start and end tags. The MTOM writer may decide to call later, when it is ready to write the appropriate part of the message. - -## Representing Data in the Service Framework - - As stated in the "Basic Architecture" section of this topic, the service framework is the part of WCF that, among other things, is responsible for converting between a user-friendly programming model for message data and actual `Message` instances. Normally, a message exchange is represented in the service framework as a .NET Framework method marked with the attribute. The method can take in some parameters and can return a return value or out parameters (or both). On the service side, the input parameters represent the incoming message, and the return value and out parameters represent the outgoing message. On the client side, the reverse is true. The programming model for describing messages using parameters and the return value is described in detail in [Specifying Data Transfer in Service Contracts](specifying-data-transfer-in-service-contracts.md). However, this section will provide a brief overview. - -## Programming Models - - The WCF service framework supports five different programming models for describing messages: - -### 1. The Empty Message - - This is the simplest case. To describe an empty incoming message, do not use any input parameters. - + [!code-vb[c_DataArchitecture#2](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_dataarchitecture/vb/source.vb#2)] + + Physically, an `AirfareRequestMessage` instance contains only two strings ("fromCity" and "toCity"). However, logically the message contains the following XML infoset: + +```xml + + Tokyo + London + +``` + + Of course, you would normally not create messages in this manner, because you can use the service framework to create a message like the preceding one from operation contract parameters. Additionally, the class has static `CreateMessage` methods that you can use to create messages with common types of content: an empty message, a message that contains an object serialized to XML with the , a message that contains a SOAP fault, a message that contains XML represented by an , and so on. + +### Getting Data from a Message Body + + You can extract the data stored in a message body in two main ways: + +- You can get the entire message body at one time by calling the method and passing in an XML writer. The complete message body is written out to this writer. Getting the entire message body at one time is also called *writing a message*. Writing is done primarily by the channel stack when sending messages—some part of the channel stack will usually get access to the entire message body, encode it, and send it. + +- Another way to get information out of the message body is to call and get an XML reader. The message body can then be accessed sequentially as needed by calling methods on the reader. Getting the message body piece-by-piece is also called *reading a message*. Reading the message is primarily used by the service framework when receiving messages. For example, when the is in use, the service framework will get an XML reader over the body and pass it to the deserialization engine, which will then start reading the message element-by-element and constructing the corresponding object graph. + + A message body can be retrieved only once. This makes it possible to work with forward-only streams. For example, you can write an override that reads from a and returns the results as an XML Infoset. You will never need to "rewind" to the beginning of the file. + + The `WriteBodyContents` and `GetReaderAtBodyContents` methods simply check that the message body has never been retrieved before, and then call `OnWriteBodyContents` or `OnGetReaderAtBodyContents`, respectively. + +## Message Usage in WCF + + Most messages can be classified as either *outgoing* (those that are created by the service framework to be sent by the channel stack) or *incoming* (those that arrive from the channel stack and are interpreted by the service framework). Furthermore, the channel stack can operate in either buffered or streaming mode. The service framework may also expose a streamed or nonstreamed programming model. This leads to the cases listed in the following table, along with simplified details of their implementation. + +|Message type|Body data in message|Write (OnWriteBodyContents) implementation|Read (OnGetReaderAtBodyContents) Implementation| +|------------------|--------------------------|--------------------------------------------------|-------------------------------------------------------| +|Outgoing, created from nonstreamed programming model|The data needed to write the message (for example, an object and the instance needed to serialize it)*|Custom logic to write out the message based on the stored data (for example, call `WriteObject` on the `DataContractSerializer` if that is the serializer in use)*|Call `OnWriteBodyContents`, buffer the results, return an XML reader over the buffer| +|Outgoing, created from streamed programming model|The `Stream` with the data to be written*|Write out data from the stored stream using the mechanism*|Call `OnWriteBodyContents`, buffer the results, return an XML reader over the buffer| +|Incoming from streaming channel stack|A `Stream` object that represents the data coming in over the network with an over it|Write out the contents from the stored `XmlReader` using `WriteNode`|Returns the stored `XmlReader`| +|Incoming from nonstreaming channel stack|A buffer that contains body data with an `XmlReader` over it|Writes out the contents from the stored `XmlReader` using `WriteNode`|Returns the stored lang| + + \* These items are not implemented directly in `Message` subclasses, but in subclasses of the class. For more information about the , see [Using the Message Class](using-the-message-class.md). + +## Message Headers + + A message may contain headers. A header logically consists of an XML Infoset that is associated with a name, a namespace, and a few other properties. Message headers are accessed using the `Headers` property on . Each header is represented by a class. Normally, message headers are mapped to SOAP message headers when using a channel stack configured to work with SOAP messages. + + Putting information into a message header and extracting information from it is similar to using the message body. The process is somewhat simplified because streaming is not supported. It is possible to access the contents of the same header more than once, and headers can be accessed in arbitrary order, forcing headers to always be buffered. There is no general-purpose mechanism available to get an XML reader over a header, but there is a `MessageHeader` subclass internal to WCF that represents a readable header with such a capability. This type of `MessageHeader` is created by the channel stack when a message with custom application headers comes in. This enables the service framework to use a deserialization engine, such as the , to interpret these headers. + + For more information, see [Using the Message Class](using-the-message-class.md). + +## Message Properties + + A message may contain properties. A *property* is any .NET Framework object that is associated with a string name. Properties are accessed through the `Properties` property on `Message`. + + Unlike the message body and message headers (which normally map to the SOAP body and SOAP headers, respectively), message properties are normally not sent or received along with the messages. Message properties exist primarily as a communication mechanism to pass data about the message between the various channels in the channel stack, and between the channel stack and the service model. + + For example, the HTTP transport channel included as part of WCF is capable of producing various HTTP status codes, such as "404 (Not Found)" and "500 (Internal Server Error)," when it sends replies to clients. Before sending a reply message, it checks to see whether the `Properties` of the `Message` contain a property called "httpResponse" that contains an object of type . If such a property is found, it will look at the property and use that status code. If it is not found, the default "200 (OK)" code is used. + + For more information, see [Using the Message Class](using-the-message-class.md). + +### The Message as a Whole + + So far, we have discussed methods for accessing the various parts of the message in isolation. However, the class also provides methods to work with the entire message as a whole. For example, the `WriteMessage` method writes out the entire message to an XML writer. + + For this to be possible, a mapping must be defined between the entire `Message` instance and an XML Infoset. Such a mapping, in fact, exists: WCF uses the SOAP standard to define this mapping. When a `Message` instance is written out as an XML Infoset, the resulting Infoset is the valid SOAP envelope that contains the message. Thus, `WriteMessage` would normally perform the following steps: + +1. Write the SOAP envelope element opening tag. + +2. Write the SOAP header element opening tag, write out all of the headers, and close the header element. + +3. Write the SOAP body element opening tag. + +4. Call `WriteBodyContents` or an equivalent method to write out the body. + +5. Close the body and envelope elements. + + The preceding steps are closely tied to the SOAP standard. This is complicated by the fact that multiple versions of SOAP exist, for example, it is impossible to write out the SOAP envelope element correctly without knowing the SOAP version in use. Also, in some cases, it may be desirable to turn off this complex SOAP-specific mapping completely. + + For these purposes, a `Version` property is provided on `Message`. It can be set to the SOAP version to use when writing out the message, or it can be set to `None` to prevent any SOAP-specific mappings. If the `Version` property is set to `None`, methods that work with the entire message act as if the message consisted of its body only, for example, `WriteMessage` would simply call `WriteBodyContents` instead of performing the multiple steps listed above. It is expected that on incoming messages, `Version` will be auto-detected and set correctly. + +## The Channel Stack + +### Channels + + As stated before, the channel stack is responsible for converting outgoing instances into some action (such as sending packets over the network), or converting some action (such as receiving network packets) into incoming `Message` instances. + + The channel stack is composed of one or more channels ordered in a sequence. An outgoing `Message` instance is passed to the first channel in the stack (also called the *topmost channel*), which passes it to the next channel down in stack, and so on. The message terminates in the last channel, which is called the *transport channel*. Incoming messages originate in the transport channel and are passed from channel to channel up the stack. From the topmost channel, the message is usually passed into the service framework. While this is the usual pattern for application messages, some channels may work slightly differently, for example, they may send their own infrastructure messages without being passed a message from a channel above. + + Channels may operate on the message in various ways as it passes through the stack. The most common operation is adding a header to an outgoing message and reading headers on an incoming message. For example, a channel may compute the digital signature of a message and add it as a header. A channel may also inspect this digital signature header on incoming messages and block messages that do not have a valid signature from making their way up the channel stack. Channels also often set or inspect message properties. The message body is usually not modified, although this is allowed, for example, the WCF security channel can encrypt the message body. + +### Transport Channels and Message Encoders + + The bottommost channel in the stack is responsible for actually transforming an outgoing , as modified by other channels, into some action. On the receive side, this is the channel that converts some action into a `Message` that other channels process. + + As stated previously, the actions may be varied: sending or receiving network packets over various protocols, reading or writing the message in a database, or queuing or dequeuing the message in a Message Queuing queue, to provide but a few examples. All these actions have one thing in common: they require a transformation between the WCF`Message` instance and an actual group of bytes that can be sent, received, read, written, queued, or dequeued. The process of converting a `Message` into a group of bytes is called *encoding*, and the reverse process of creating a `Message` from a group of bytes is called *decoding*. + + Most transport channels use components called *message encoders* to accomplish the encoding and decoding work. A message encoder is a subclass of the class. `MessageEncoder` includes various `ReadMessage` and `WriteMessage` method overloads to convert between `Message` and groups of bytes. + + On the sending side, a buffering transport channel passes the `Message` object that it received from a channel above it to `WriteMessage`. It gets back an array of bytes, which it then uses to perform its action (such as packaging these bytes as valid TCP packets and sending them to the correct destination). A streaming transport channel first creates a `Stream` (for example, over the outgoing TCP connection), and then passes both the `Stream` and the `Message` it needs to send to the appropriate `WriteMessage` overload, which writes out the message. + + On the receiving side, a buffering transport channel extracts incoming bytes (for example, from incoming TCP packets) into an array and calls `ReadMessage` to get a `Message` object that it can pass further up the channel stack. A streaming transport channel creates a `Stream` object (for example, a network stream over the incoming TCP connection) and passes that to `ReadMessage` to get back a `Message` object. + + The separation between the transport channels and the message encoder is not mandatory; it is possible to write a transport channel that does not use a message encoder. However, the advantage of this separation is ease of composition. As long as a transport channel uses only the base , it can work with any WCF or third-party message encoder. Likewise, the same encoder can normally be used in any transport channel. + +### Message Encoder Operation + + To describe the typical operation of an encoder, it is useful to consider the following four cases. + +|Operation|Comment| +|---------------|-------------| +|Encoding, Buffered|In buffered mode, the encoder normally creates a variable-size buffer and then creates an XML writer over it. It then calls on the message being encoded, which writes out the headers and then the body using , as explained in the preceding section about `Message` in this topic. The contents of the buffer (represented as an array of bytes) are then returned for the transport channel to use.| +|Encoding, Streamed|In streamed mode, the operation is similar to the above, but simpler. There is no need for a buffer. An XML writer is normally created over the stream and is called on the `Message` to write it out to this writer.| +|Decoding, Buffered|When decoding in buffered mode, a special `Message` subclass that contains the buffered data is normally created. The headers of the message are read, and an XML reader positioned on the message body is created. This is the reader that will be returned with .| +|Decoding, Streamed|When decoding in streamed mode, a special Message subclass is normally created. The stream is advanced just enough to read all the headers and position it on the message body. An XML reader is then created over the stream. This is the reader that will be returned with .| + + Encoders can perform other functions as well. For example, the encoders can pool XML readers and writers. It is expensive to create a new XML reader or writer every time one is needed. Therefore, encoders normally maintain a pool of readers and a pool of writers of configurable size. In the descriptions of encoder operation described previously, whenever the phrase "create an XML reader/writer" is used, it normally means "take one from the pool, or create one if one is not available." The encoder (and the `Message` subclasses it creates while decoding) contain logic to return readers and writers to the pools once they are no longer needed (for example, when the `Message` is closed). + + WCF provides three message encoders, although it is possible to create additional custom types. The supplied types are Text, Binary, and Message Transmission Optimization Mechanism (MTOM). These are described in detail in [Choosing a Message Encoder](choosing-a-message-encoder.md). + +### The IStreamProvider Interface + + When writing an outgoing message that contains a streamed body to an XML writer, the uses a sequence of calls similar to the following in its implementation: + +- Write any necessary information preceding the stream (for example, the opening XML tag). + +- Write the stream. + +- Write any information following the stream (for example, the closing XML tag). + + This works well with encodings that are similar to the textual XML encoding. However, some encodings do not place XML Infoset information (for example, tags for starting and ending XML elements) together with the data contained within elements. For example, in the MTOM encoding, the message is split into multiple parts. One part contains the XML Infoset, which may contain references to other parts for actual element contents. The XML Infoset is normally small compared to the streamed contents, so it makes sense to buffer the Infoset, write it out, and then write the contents in a streamed way. This means that by the time the closing element tag is written, the stream should not have been written out yet. + + For this purpose, the interface is used. The interface has a method that returns the stream to be written. The correct way to write out a streamed message body in is as follows: + +1. Write any necessary information preceding the stream (for example, the opening XML tag). + +2. Call the `WriteValue` overload on the that takes an , with an `IStreamProvider` implementation that returns the stream to be written. + +3. Write any information following the stream (for example, the closing XML tag). + + With this approach, the XML writer has a choice of when to call and write out the streamed data. For example, the textual and binary XML writers will call it immediately and write out the streamed contents in-between the start and end tags. The MTOM writer may decide to call later, when it is ready to write the appropriate part of the message. + +## Representing Data in the Service Framework + + As stated in the "Basic Architecture" section of this topic, the service framework is the part of WCF that, among other things, is responsible for converting between a user-friendly programming model for message data and actual `Message` instances. Normally, a message exchange is represented in the service framework as a .NET Framework method marked with the attribute. The method can take in some parameters and can return a return value or out parameters (or both). On the service side, the input parameters represent the incoming message, and the return value and out parameters represent the outgoing message. On the client side, the reverse is true. The programming model for describing messages using parameters and the return value is described in detail in [Specifying Data Transfer in Service Contracts](specifying-data-transfer-in-service-contracts.md). However, this section will provide a brief overview. + +## Programming Models + + The WCF service framework supports five different programming models for describing messages: + +### 1. The Empty Message + + This is the simplest case. To describe an empty incoming message, do not use any input parameters. + [!code-csharp[C_DataArchitecture#3](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_dataarchitecture/cs/source.cs#3)] - [!code-vb[C_DataArchitecture#3](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_dataarchitecture/vb/source.vb#3)] - - To describe an empty outgoing message, use a void return value and do not use any out parameters: - + [!code-vb[C_DataArchitecture#3](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_dataarchitecture/vb/source.vb#3)] + + To describe an empty outgoing message, use a void return value and do not use any out parameters: + [!code-csharp[C_DataArchitecture#4](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_dataarchitecture/cs/source.cs#4)] - [!code-vb[C_DataArchitecture#4](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_dataarchitecture/vb/source.vb#4)] - - Note that this is different from a one-way operation contract: - + [!code-vb[C_DataArchitecture#4](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_dataarchitecture/vb/source.vb#4)] + + Note that this is different from a one-way operation contract: + [!code-csharp[C_DataArchitecture#5](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_dataarchitecture/cs/source.cs#5)] - [!code-vb[C_DataArchitecture#5](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_dataarchitecture/vb/source.vb#5)] - - In the `SetDesiredTemperature` example, a two-way message exchange pattern is described. A message is returned from the operation, but it is empty. It is possible to return a fault from the operation. In the "Set Lightbulb" example, the message exchange pattern is one-way, so there is no outgoing message to describe. The service cannot communicate any status back to the client in this case. - -### 2. Using the Message Class Directly - - It is possible to use the class (or one of its subclasses) directly in an operation contract. In this case, the service framework just passes the `Message` from the operation to the channel stack and vice versa, with no further processing. - - There are two main use cases for using `Message` directly. You can use this for advanced scenarios, when none of the other programming models gives you enough flexibility to describe your message. For example, you might want to use files on disk to describe a message, with the file’s properties becoming message headers and the file’s contents becoming the message body. You can then create something similar to the following. - + [!code-vb[C_DataArchitecture#5](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_dataarchitecture/vb/source.vb#5)] + + In the `SetDesiredTemperature` example, a two-way message exchange pattern is described. A message is returned from the operation, but it is empty. It is possible to return a fault from the operation. In the "Set Lightbulb" example, the message exchange pattern is one-way, so there is no outgoing message to describe. The service cannot communicate any status back to the client in this case. + +### 2. Using the Message Class Directly + + It is possible to use the class (or one of its subclasses) directly in an operation contract. In this case, the service framework just passes the `Message` from the operation to the channel stack and vice versa, with no further processing. + + There are two main use cases for using `Message` directly. You can use this for advanced scenarios, when none of the other programming models gives you enough flexibility to describe your message. For example, you might want to use files on disk to describe a message, with the file’s properties becoming message headers and the file’s contents becoming the message body. You can then create something similar to the following. + [!code-csharp[C_DataArchitecture#6](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_dataarchitecture/cs/source.cs#6)] - [!code-vb[C_DataArchitecture#6](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_dataarchitecture/vb/source.vb#6)] - - The second common use for `Message` in an operation contract is when a service does not care about the particular message contents and acts on the message as on a black box. For example, you might have a service that forwards messages to multiple other recipients. The contract can be written as follows. - + [!code-vb[C_DataArchitecture#6](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_dataarchitecture/vb/source.vb#6)] + + The second common use for `Message` in an operation contract is when a service does not care about the particular message contents and acts on the message as on a black box. For example, you might have a service that forwards messages to multiple other recipients. The contract can be written as follows. + [!code-csharp[C_DataArchitecture#7](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_dataarchitecture/cs/source.cs#7)] - [!code-vb[C_DataArchitecture#7](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_dataarchitecture/vb/source.vb#7)] - - The Action="*" line effectively turns off message dispatching and ensures that all messages sent to the `IForwardingService` contract make their way to the `ForwardMessage` operation. (Normally, the dispatcher would examine the message’s "Action" header to determine which operation it is intended for. Action="\*" means "all possible values of the Action header".) The combination of Action="\*" and using Message as a parameter is known as the "universal contract" because it is able to receive all possible messages. To be able to send all possible messages, use Message as the return value and set `ReplyAction` to "\*". This will prevent the service framework from adding its own Action header, enabling you to control this header using the `Message` object you return. - -### 3. Message Contracts - - WCF provides a declarative programming model for describing messages, called *message contracts*. This model is described in detail in [Using Message Contracts](using-message-contracts.md). Essentially, the entire message is represented by a single .NET Framework type that uses attributes like the and to describe which parts of the message contract class should map to which part of the message. - - Message contracts provide a lot of control over the resulting `Message` instances (although obviously not as much control as using the `Message` class directly). For example, message bodies are often composed of multiple pieces of information, each represented by its own XML element. These elements can either occur directly in the body (*bare* mode) or can be *wrapped* in an encompassing XML element. Using the message contract programming model enables you to make the bare-versus-wrapped decision and control the name of the wrapper name and namespace. - - The following code example of a message contract demonstrates these features. - + [!code-vb[C_DataArchitecture#7](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_dataarchitecture/vb/source.vb#7)] + + The Action="*" line effectively turns off message dispatching and ensures that all messages sent to the `IForwardingService` contract make their way to the `ForwardMessage` operation. (Normally, the dispatcher would examine the message’s "Action" header to determine which operation it is intended for. Action="\*" means "all possible values of the Action header".) The combination of Action="\*" and using Message as a parameter is known as the "universal contract" because it is able to receive all possible messages. To be able to send all possible messages, use Message as the return value and set `ReplyAction` to "\*". This will prevent the service framework from adding its own Action header, enabling you to control this header using the `Message` object you return. + +### 3. Message Contracts + + WCF provides a declarative programming model for describing messages, called *message contracts*. This model is described in detail in [Using Message Contracts](using-message-contracts.md). Essentially, the entire message is represented by a single .NET Framework type that uses attributes like the and to describe which parts of the message contract class should map to which part of the message. + + Message contracts provide a lot of control over the resulting `Message` instances (although obviously not as much control as using the `Message` class directly). For example, message bodies are often composed of multiple pieces of information, each represented by its own XML element. These elements can either occur directly in the body (*bare* mode) or can be *wrapped* in an encompassing XML element. Using the message contract programming model enables you to make the bare-versus-wrapped decision and control the name of the wrapper name and namespace. + + The following code example of a message contract demonstrates these features. + [!code-csharp[C_DataArchitecture#9](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_dataarchitecture/cs/source.cs#9)] - [!code-vb[C_DataArchitecture#9](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_dataarchitecture/vb/source.vb#9)] - - Items marked to be serialized (with the , , or other related attributes) must be serializable to participate in a message contract. For more information, see the "Serialization" section later in this topic. - -### 4. Parameters - - Often, a developer who wants to describe an operation that acts on multiple pieces of data does not need the degree of control that message contracts provide. For example, when creating new services, one does not usually want to make the bare-versus-wrapped decision and decide on the wrapper element name. Making these decisions often requires deep knowledge of Web services and SOAP. - - The WCF service framework can automatically pick the best and most interoperable SOAP representation for sending or receiving multiple related pieces of information, without forcing these choices on the user. This is accomplished by simply describing these pieces of information as parameters or return values of an operation contract. For example, consider the following operation contract. - + [!code-vb[C_DataArchitecture#9](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_dataarchitecture/vb/source.vb#9)] + + Items marked to be serialized (with the , , or other related attributes) must be serializable to participate in a message contract. For more information, see the "Serialization" section later in this topic. + +### 4. Parameters + + Often, a developer who wants to describe an operation that acts on multiple pieces of data does not need the degree of control that message contracts provide. For example, when creating new services, one does not usually want to make the bare-versus-wrapped decision and decide on the wrapper element name. Making these decisions often requires deep knowledge of Web services and SOAP. + + The WCF service framework can automatically pick the best and most interoperable SOAP representation for sending or receiving multiple related pieces of information, without forcing these choices on the user. This is accomplished by simply describing these pieces of information as parameters or return values of an operation contract. For example, consider the following operation contract. + [!code-csharp[C_DataArchitecture#11](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_dataarchitecture/cs/source.cs#11)] - [!code-vb[C_DataArchitecture#11](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_dataarchitecture/vb/source.vb#11)] - - The service framework automatically decides to put all three pieces of information (`customerID`, `item`, and `quantity`) into the message body and wrap them in a wrapper element named `SubmitOrderRequest`. - - Describing the information to be sent or received as a simple list of operation contract parameters is the recommended approach, unless special reasons exist to move to the more-complex message contract or `Message`-based programming models. - -### 5. Stream - - Using `Stream` or one of its subclasses in an operation contract or as a sole message body part in a message contract can be considered a separate programming model from the ones described above. Using `Stream` in this way is the only way to guarantee that your contract will be usable in a streamed fashion, short of writing your own streaming-compatible `Message` subclass. For more information, see [Large Data and Streaming](large-data-and-streaming.md). - - When `Stream` or one of its subclasses is used in this way, the serializer is not invoked. For outgoing messages, a special streaming `Message` subclass is created and the stream is written out as described in the section on the interface. For incoming messages, the service framework creates a `Stream` subclass over the incoming message and provides it to the operation. - -## Programming Model Restrictions - - The programming models described above cannot be arbitrarily combined. For example, if an operation accepts a message contract type, the message contract must be its only input parameter. Furthermore, the operation must then either return an empty message (return type of void) or another message contract. These programming model restrictions are described in the topics for each specific programming model: [Using Message Contracts](using-message-contracts.md), [Using the Message Class](using-the-message-class.md), and [Large Data and Streaming](large-data-and-streaming.md). - -## Message Formatters - - The programming models described above are supported by plugging in components called *message formatters* into the service framework. Message formatters are types that implement the or interface, or both, for use in clients and service WCF clients, respectively. - - Message formatters are normally plugged in by behaviors. For example, the plugs in the data contract message formatter. This is done on the service side by setting to the correct formatter in the method, or on the client side by setting to the correct formatter in the method. - - The following tables lists the methods that a message formatter may implement. - -|Interface|Method|Action| -|---------------|------------|------------| -|||Converts an incoming `Message` to operation parameters| -|||Creates an outgoing `Message` from operation return value/out parameters| -|||Creates an outgoing `Message` from operation parameters| -|||Converts an incoming `Message` to a return value/out parameters| - -## Serialization - - Whenever you use message contracts or parameters to describe message contents, you must use serialization to convert between .NET Framework types and XML Infoset representation. Serialization is used in other places in WCF, for example, has a Generic method that you can use to read the entire body of the message deserialized into an object. - - WCF supports two serialization technologies "out of the box" for serializing and deserializing parameters and message parts: the and the `XmlSerializer`. Additionally, you can write custom serializers. However, other parts of WCF (such as the Generic `GetBody` method or SOAP fault serialization) may be restricted to use only the subclasses ( and , but not the ), or may even be hard-coded to use only the . - - The `XmlSerializer` is the serialization engine used in ASP.NET Web services. The `DataContractSerializer` is the new serialization engine that understands the new data contract programming model. `DataContractSerializer` is the default choice, and the choice to use the `XmlSerializer` can be made on a per-operation basis using the attribute. - - and are the operation behaviors responsible for plugging in the message formatters for the `DataContractSerializer` and the `XmlSerializer`, respectively. The behavior can actually operate with any serializer that derives from , including the (described in detail in Using Stand-Alone Serialization). The behavior calls one of the `CreateSerializer` virtual method overloads to obtain the serializer. To plug in a different serializer, create a new subclass and override both `CreateSerializer` overloads. - + [!code-vb[C_DataArchitecture#11](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_dataarchitecture/vb/source.vb#11)] + + The service framework automatically decides to put all three pieces of information (`customerID`, `item`, and `quantity`) into the message body and wrap them in a wrapper element named `SubmitOrderRequest`. + + Describing the information to be sent or received as a simple list of operation contract parameters is the recommended approach, unless special reasons exist to move to the more-complex message contract or `Message`-based programming models. + +### 5. Stream + + Using `Stream` or one of its subclasses in an operation contract or as a sole message body part in a message contract can be considered a separate programming model from the ones described above. Using `Stream` in this way is the only way to guarantee that your contract will be usable in a streamed fashion, short of writing your own streaming-compatible `Message` subclass. For more information, see [Large Data and Streaming](large-data-and-streaming.md). + + When `Stream` or one of its subclasses is used in this way, the serializer is not invoked. For outgoing messages, a special streaming `Message` subclass is created and the stream is written out as described in the section on the interface. For incoming messages, the service framework creates a `Stream` subclass over the incoming message and provides it to the operation. + +## Programming Model Restrictions + + The programming models described above cannot be arbitrarily combined. For example, if an operation accepts a message contract type, the message contract must be its only input parameter. Furthermore, the operation must then either return an empty message (return type of void) or another message contract. These programming model restrictions are described in the topics for each specific programming model: [Using Message Contracts](using-message-contracts.md), [Using the Message Class](using-the-message-class.md), and [Large Data and Streaming](large-data-and-streaming.md). + +## Message Formatters + + The programming models described above are supported by plugging in components called *message formatters* into the service framework. Message formatters are types that implement the or interface, or both, for use in clients and service WCF clients, respectively. + + Message formatters are normally plugged in by behaviors. For example, the plugs in the data contract message formatter. This is done on the service side by setting to the correct formatter in the method, or on the client side by setting to the correct formatter in the method. + + The following tables lists the methods that a message formatter may implement. + +|Interface|Method|Action| +|---------------|------------|------------| +|||Converts an incoming `Message` to operation parameters| +|||Creates an outgoing `Message` from operation return value/out parameters| +|||Creates an outgoing `Message` from operation parameters| +|||Converts an incoming `Message` to a return value/out parameters| + +## Serialization + + Whenever you use message contracts or parameters to describe message contents, you must use serialization to convert between .NET Framework types and XML Infoset representation. Serialization is used in other places in WCF, for example, has a Generic method that you can use to read the entire body of the message deserialized into an object. + + WCF supports two serialization technologies "out of the box" for serializing and deserializing parameters and message parts: the and the `XmlSerializer`. Additionally, you can write custom serializers. However, other parts of WCF (such as the Generic `GetBody` method or SOAP fault serialization) may be restricted to use only the subclasses ( and , but not the ), or may even be hard-coded to use only the . + + The `XmlSerializer` is the serialization engine used in ASP.NET Web services. The `DataContractSerializer` is the new serialization engine that understands the new data contract programming model. `DataContractSerializer` is the default choice, and the choice to use the `XmlSerializer` can be made on a per-operation basis using the attribute. + + and are the operation behaviors responsible for plugging in the message formatters for the `DataContractSerializer` and the `XmlSerializer`, respectively. The behavior can actually operate with any serializer that derives from , including the (described in detail in Using Stand-Alone Serialization). The behavior calls one of the `CreateSerializer` virtual method overloads to obtain the serializer. To plug in a different serializer, create a new subclass and override both `CreateSerializer` overloads. + ## See also - [Specifying Data Transfer in Service Contracts](specifying-data-transfer-in-service-contracts.md) diff --git a/docs/framework/wcf/feature-details/diagnosing-transactional-applications.md b/docs/framework/wcf/feature-details/diagnosing-transactional-applications.md index 2dc45480c4e2d..22df07ddf7ba5 100644 --- a/docs/framework/wcf/feature-details/diagnosing-transactional-applications.md +++ b/docs/framework/wcf/feature-details/diagnosing-transactional-applications.md @@ -6,119 +6,119 @@ ms.assetid: 4a993492-1088-4d10-871b-0c09916af05f --- # Diagnosing Transactional Applications -This topic describes how to use the Windows Communication Foundation (WCF) management and diagnostics feature to troubleshoot a transactional application. - -## Performance Counters - - WCF provides a standard set of performance counters for you to measure your transactional application's performance. For more information, see [Performance Counters](../diagnostics/performance-counters/index.md). - - Performance counters are scoped to three different levels: service, endpoint, and operation, as described in the following tables. - -### Service Performance Counters - -|Performance counter|Description| -|-------------------------|-----------------| -|Transactions Flowed|The number of transactions that flowed to operations in this service. This counter is incremented any time a transaction is present in the message that is sent to the service.| -|Transactions Flowed Per Second|The number of transactions that flowed to operations in this service within each second. This counter is incremented any time a transaction is present in the message that is sent to the service.| -|Transacted Operations Committed|The number of transacted operations performed, whose transaction has completed with the outcome committed in this service. Work done under such operations is fully committed. Resources are updated in accordance with the work done in the operation.| -|Transacted Operations Committed Per Second|The number of transacted operations performed, whose transaction has completed with the outcome committed in this service within each second. Work done under such operations is fully committed. Resources are updated in accordance with the work done in the operation.| -|Transacted Operations Aborted|The number of transacted operations performed, whose transaction has completed with the outcome aborted in this service. Work done under such operations is rolled back. Resources are reverted to their previous state.| -|Transacted Operations Aborted Per Second|The number of transacted operations performed, whose transaction has completed with the outcome aborted in this service within each second. Work done under such operations is rolled back. Resources are reverted to their previous state.| -|Transacted Operations In Doubt|The number of transacted operations performed, whose transaction has completed with an outcome in doubt in this service. Work done with an outcome in doubt is in an indeterminate state. Resources are held pending outcome.| -|Transacted Operations In Doubt Per Second|The number of transacted operations performed, whose transaction has completed with an outcome in doubt in this service within each second. Work done with an outcome in doubt is in an indeterminate state. Resources are held pending outcome.| - -### Endpoint Performance Counters - -|Performance counter|Description| -|-------------------------|-----------------| -|Transactions Flowed|The number of transactions that flowed to operations at this endpoint. This counter is incremented any time a transaction is present in the message that is sent to the endpoint.| -|Transactions Flowed Per Second|The number of transactions that flowed to operations at this endpoint within each second. This counter is incremented any time a transaction is present in the message that is sent to the endpoint.| - -### Operation Performance Counters - -|Performance counter|Description| -|-------------------------|-----------------| -|Transactions Flowed|The number of transactions that flowed to operations at this endpoint. This counter is incremented any time a transaction is present in the message that is sent to the endpoint.| -|Transactions Flowed Per Second|The number of transactions that flowed to operations at this endpoint within each second. This counter is incremented any time a transaction is present in the message that is sent to the endpoint.| - -## Windows Management Instrumentation - - WCF exposes inspection data of a service at run time through a WCF Windows Management Instrumentation (WMI) provider. For more information about accessing WMI data, see [Using Windows Management Instrumentation for Diagnostics](../diagnostics/wmi/index.md). - - A number of read-only WMI properties indicate the applied transaction settings for a service. The following tables list all of these settings. - - On a service, the `ServiceBehaviorAttribute` has the following properties. - -|Name|Type|Description| -|----------|----------|-----------------| -|ReleaseServiceInstanceOnTransactionComplete|Boolean|Specifies whether the service object is recycled when the current transaction completes.| -|TransactionAutoCompleteOnSessionClose|Boolean|Specifies whether pending transactions are completed when the current session closes.| -|TransactionIsolationLevel|A string that contains a valid value of the enumeration.|Specifies the transaction isolation level that this service supports.| -|TransactionTimeout||Specifies the period within which a transaction must complete.| - - The `ServiceTimeoutsBehavior` has the following property. - -|Name|Type|Description| -|----------|----------|-----------------| -|TransactionTimeout||Specifies the period within which a transaction must complete.| - - On a binding, the `TransactionFlowBindingElement` has the following properties. - -|Name|Type|Description| -|----------|----------|-----------------| -|TransactionProtocol|A string that contains a valid value of the type.|Specifies the transaction protocol to use in flowing a transaction.| -|TransactionFlow|Boolean|Specifies whether incoming transaction flow is enabled.| - - On an operation, the `OperationBehaviorAttribute` has the following properties: - -|Name|Type|Description| -|----------|----------|-----------------| -|TransactionAutoComplete|Boolean|Specifies whether to automatically commit the current transaction if no unhandled exceptions occur.| -|TransactionScopeRequired|Boolean|Specifies whether the operation requires a transaction.| - - On an operation, the `TransactionFlowAttribute` has the following properties. - -|Name|Type|Description| -|----------|----------|-----------------| -|TransactionFlowOption|A string that contains a valid value of the enumeration.|Specifies the extent to which transaction flow is required.| - -## Tracing - - Traces enable you to monitor and analyze faults in your transactional applications. You can enable tracing using the following ways: - -- Standard WCF tracing - - This type of tracing is the same as tracing any WCF application. For more information, see [Configuring Tracing](../diagnostics/tracing/configuring-tracing.md). - -- WS-AtomicTransaction tracing - - WS-AtomicTransaction tracing can be enabled by using the [WS-AtomicTransaction Configuration Utility (wsatConfig.exe)](../ws-atomictransaction-configuration-utility-wsatconfig-exe.md). Such tracing provides insight into the state of transactions and participants within a system. To also enable internal Service Model tracing, you can set the `HKLM\SOFTWARE\Microsoft\WSAT\3.0\ServiceModelDiagnosticTracing` registry key to a valid value of the enumeration. You can enable message logging in the same way as other WCF applications. - -- `System.Transactions` tracing - - When using the OleTransactions protocol, protocol messages cannot be traced. The tracing support the infrastructure provides (which uses OleTransactions) allows users to view events that occurred to the transactions. To enable tracing for a application, include the following code in the `App.config` configuration file. - - ```xml - - - - - - - - - - - - - - ``` - - This also enables WCF tracing, as WCF also utilizes the infrastructure. - +This topic describes how to use the Windows Communication Foundation (WCF) management and diagnostics feature to troubleshoot a transactional application. + +## Performance Counters + + WCF provides a standard set of performance counters for you to measure your transactional application's performance. For more information, see [Performance Counters](../diagnostics/performance-counters/index.md). + + Performance counters are scoped to three different levels: service, endpoint, and operation, as described in the following tables. + +### Service Performance Counters + +|Performance counter|Description| +|-------------------------|-----------------| +|Transactions Flowed|The number of transactions that flowed to operations in this service. This counter is incremented any time a transaction is present in the message that is sent to the service.| +|Transactions Flowed Per Second|The number of transactions that flowed to operations in this service within each second. This counter is incremented any time a transaction is present in the message that is sent to the service.| +|Transacted Operations Committed|The number of transacted operations performed, whose transaction has completed with the outcome committed in this service. Work done under such operations is fully committed. Resources are updated in accordance with the work done in the operation.| +|Transacted Operations Committed Per Second|The number of transacted operations performed, whose transaction has completed with the outcome committed in this service within each second. Work done under such operations is fully committed. Resources are updated in accordance with the work done in the operation.| +|Transacted Operations Aborted|The number of transacted operations performed, whose transaction has completed with the outcome aborted in this service. Work done under such operations is rolled back. Resources are reverted to their previous state.| +|Transacted Operations Aborted Per Second|The number of transacted operations performed, whose transaction has completed with the outcome aborted in this service within each second. Work done under such operations is rolled back. Resources are reverted to their previous state.| +|Transacted Operations In Doubt|The number of transacted operations performed, whose transaction has completed with an outcome in doubt in this service. Work done with an outcome in doubt is in an indeterminate state. Resources are held pending outcome.| +|Transacted Operations In Doubt Per Second|The number of transacted operations performed, whose transaction has completed with an outcome in doubt in this service within each second. Work done with an outcome in doubt is in an indeterminate state. Resources are held pending outcome.| + +### Endpoint Performance Counters + +|Performance counter|Description| +|-------------------------|-----------------| +|Transactions Flowed|The number of transactions that flowed to operations at this endpoint. This counter is incremented any time a transaction is present in the message that is sent to the endpoint.| +|Transactions Flowed Per Second|The number of transactions that flowed to operations at this endpoint within each second. This counter is incremented any time a transaction is present in the message that is sent to the endpoint.| + +### Operation Performance Counters + +|Performance counter|Description| +|-------------------------|-----------------| +|Transactions Flowed|The number of transactions that flowed to operations at this endpoint. This counter is incremented any time a transaction is present in the message that is sent to the endpoint.| +|Transactions Flowed Per Second|The number of transactions that flowed to operations at this endpoint within each second. This counter is incremented any time a transaction is present in the message that is sent to the endpoint.| + +## Windows Management Instrumentation + + WCF exposes inspection data of a service at runtime through a WCF Windows Management Instrumentation (WMI) provider. For more information about accessing WMI data, see [Using Windows Management Instrumentation for Diagnostics](../diagnostics/wmi/index.md). + + A number of read-only WMI properties indicate the applied transaction settings for a service. The following tables list all of these settings. + + On a service, the `ServiceBehaviorAttribute` has the following properties. + +|Name|Type|Description| +|----------|----------|-----------------| +|ReleaseServiceInstanceOnTransactionComplete|Boolean|Specifies whether the service object is recycled when the current transaction completes.| +|TransactionAutoCompleteOnSessionClose|Boolean|Specifies whether pending transactions are completed when the current session closes.| +|TransactionIsolationLevel|A string that contains a valid value of the enumeration.|Specifies the transaction isolation level that this service supports.| +|TransactionTimeout||Specifies the period within which a transaction must complete.| + + The `ServiceTimeoutsBehavior` has the following property. + +|Name|Type|Description| +|----------|----------|-----------------| +|TransactionTimeout||Specifies the period within which a transaction must complete.| + + On a binding, the `TransactionFlowBindingElement` has the following properties. + +|Name|Type|Description| +|----------|----------|-----------------| +|TransactionProtocol|A string that contains a valid value of the type.|Specifies the transaction protocol to use in flowing a transaction.| +|TransactionFlow|Boolean|Specifies whether incoming transaction flow is enabled.| + + On an operation, the `OperationBehaviorAttribute` has the following properties: + +|Name|Type|Description| +|----------|----------|-----------------| +|TransactionAutoComplete|Boolean|Specifies whether to automatically commit the current transaction if no unhandled exceptions occur.| +|TransactionScopeRequired|Boolean|Specifies whether the operation requires a transaction.| + + On an operation, the `TransactionFlowAttribute` has the following properties. + +|Name|Type|Description| +|----------|----------|-----------------| +|TransactionFlowOption|A string that contains a valid value of the enumeration.|Specifies the extent to which transaction flow is required.| + +## Tracing + + Traces enable you to monitor and analyze faults in your transactional applications. You can enable tracing using the following ways: + +- Standard WCF tracing + + This type of tracing is the same as tracing any WCF application. For more information, see [Configuring Tracing](../diagnostics/tracing/configuring-tracing.md). + +- WS-AtomicTransaction tracing + + WS-AtomicTransaction tracing can be enabled by using the [WS-AtomicTransaction Configuration Utility (wsatConfig.exe)](../ws-atomictransaction-configuration-utility-wsatconfig-exe.md). Such tracing provides insight into the state of transactions and participants within a system. To also enable internal Service Model tracing, you can set the `HKLM\SOFTWARE\Microsoft\WSAT\3.0\ServiceModelDiagnosticTracing` registry key to a valid value of the enumeration. You can enable message logging in the same way as other WCF applications. + +- `System.Transactions` tracing + + When using the OleTransactions protocol, protocol messages cannot be traced. The tracing support the infrastructure provides (which uses OleTransactions) allows users to view events that occurred to the transactions. To enable tracing for a application, include the following code in the `App.config` configuration file. + + ```xml + + + + + + + + + + + + + + ``` + + This also enables WCF tracing, as WCF also utilizes the infrastructure. + ## See also - [Administration and Diagnostics](../diagnostics/index.md) diff --git a/docs/framework/wcf/feature-details/distributed-application-security.md b/docs/framework/wcf/feature-details/distributed-application-security.md index 4738fdef6c061..c795218a229df 100644 --- a/docs/framework/wcf/feature-details/distributed-application-security.md +++ b/docs/framework/wcf/feature-details/distributed-application-security.md @@ -2,102 +2,102 @@ description: "Learn more about: Distributed Application Security" title: "Distributed Application Security" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "distributed application security [WCF]" - "security [WCF], transfer" ms.assetid: 53928a10-e474-46d0-ab90-5f98f8d7b668 --- # Distributed Application Security -Windows Communication Foundation (WCF) security is broken into three major functional areas: transfer security, access control, and auditing. Transfer security provides integrity, confidentiality, and authentication. Transfer security is provided by one of the following: transport security, message security, or `TransportWithMessageCredential`. - - For an overview of WCF message security, see [Security Overview](security-overview.md). For more information about the other two pieces of WCF security, see [Authorization](authorization-in-wcf.md) and [Auditing](auditing-security-events.md). - -## Transfer Security Scenarios - - Common scenarios that employ WCF transfer security include the following: - -- Secure transfer using Windows. A WCF client and service are deployed in a Windows domain (or a Windows forest). The messages contain personal data, so requirements include mutual authentication of the client and service, message integrity, and message confidentiality. In addition, proof is required that a particular transaction occurred, for example, the receiver of the message should record the signature information. - -- Secure transfer using `UserName` and HTTPS. A WCF client and service need to be developed to work across the Internet. The client credentials authenticate against a database of user name/password pairs. The service is deployed at an HTTPS address using a trusted Secure Sockets Layer (SSL) certificate. Because the messages travel over the Internet, the client and service need to be mutually authenticated, and the messages' confidentiality and integrity must be preserved during transfer. - -- Secure transfer using certificates. A WCF client and service need to be developed to work over the public internet. The client and service both have certificates that can be used to secure the messages. The client and service use the Internet to communicate with each other and to perform high-value transactions that require message integrity, confidentiality, and mutual authentication. - -## Integrity, Confidentiality, and Authentication - - Three functions—integrity, confidentiality and authentication—are together called transfer security. Transfer security provides the functions that help to mitigate the threats to a distributed application. The following table briefly describes the three functions that make up transfer security. - -|Function|Description| -|--------------|-----------------| -|Integrity|*Integrity* is the assurance that data is complete and accurate, especially after it has traversed from one point to another, and possibly been read by many actors. Integrity must be maintained to prevent tampering with the data, and is usually achieved by digital signing of a message.| -|Confidentiality|*Confidentiality* is the assurance that a message has not been read by anyone other than the intended reader. For example, a credit card number must be kept confidential as it is sent over the Internet. Confidentiality is often provided by the encryption of data using a public key/private key scheme.| -|Authentication|*Authentication* is the verification of a claimed identity. For example, when using a bank account, it is imperative that only the actual owner of the account be allowed to withdraw funds. Authentication can be provided by a variety of means. One common method is the user/password system. A second is the use of an X.509 certificate that is provided by a third party.| - -## Security Modes - - WCF has several modes of transfer security, which are described in the following table. - -|Mode|Description| -|----------|-----------------| -|None|No security is provided at the transport layer or at the message layer. None of the predefined bindings use this mode by default except the [\](../../configure-apps/file-schema/wcf/basichttpbinding.md) element or, when using code, the class.| -|Transport|Uses a secure transport such as HTTPS for integrity, confidentiality, and mutual authentication.| -|Message|Uses SOAP-message security for integrity, confidentiality, and mutual authentication. SOAP messages are secured according to the WS-Security standards.| -|Mixed Mode|Uses transport security for integrity, confidentiality, and server authentication. Uses message security (WS-Security and other standards) for client authentication.

(This enumeration for this mode is `TransportWithMessageCredential`.)| -|Both|Performs protection and authentication at both levels. This mode is available only in the [\](../../configure-apps/file-schema/wcf/netmsmqbinding.md) element.| - -## Credentials and Transfer Security - - A *credential* is data that is presented to establish either a claimed identity or capabilities. Presenting a credential involves presenting both the data and proof of possession of the data. WCF supports a variety of credential types at both the transport and message security levels. You can specify a type of credential for a WCF binding. - - In many countries or regions, a driver’s license is an example of a credential. A license contains data representing one's identity and capabilities. It contains proof of possession in the form of the possessor's picture. The license is issued by a trusted authority, usually a governmental licensing department. The license is sealed, and can contain a hologram, showing that it has not been tampered with or counterfeited. - - As an example, consider two types of credentials supported in WCF: user name and (X.509) certificate credentials. - - For the user name credential, the user name represents the claimed identity and the password presents the proof of possession. The trusted authority in this case is the system that validates the user name and password. - - In the certificate credential, the subject name, subject alternative name, or specific fields within the certificate can be used to represent the claimed identity and/or capabilities. Proof of possession of the data in the credential is established by using the associated private key to generate a signature. - - For more information about programming transfer security and specifying credentials, see [Bindings and Security](bindings-and-security.md) and [Security Behaviors](security-behaviors-in-wcf.md). - -### Transport Client Credential Types - - The following table shows the possible values used when creating an application that uses transfer security. You can use these values in either code or binding settings. - -|Setting|Description| -|-------------|-----------------| -|None|Specifies that the client does not need to present any credential. This translates to an anonymous client.| -|Basic|Specifies basic authentication. For more information, see RFC2617, "[HTTP Authentication: Basic and Digest Authentication](https://schemas.xmlsoap.org/ws/2004/10/discovery/ws-discovery.pdf)."| -|Digest|Specifies digest authentication. For more information, see RFC2617, "[HTTP Authentication: Basic and Digest Authentication](https://schemas.xmlsoap.org/ws/2004/10/discovery/ws-discovery.pdf)."| -|Ntlm|Specifies Windows authentication using SSPI negotiation on a Windows domain.

SSPI negotiation results in using either the Kerberos protocol or NT LanMan (NTLM).| -|Windows|Specifies Windows authentication using SSPI on a Windows domain. SSPI picks from either the Kerberos protocol or NTLM as authentication service.

SSPI tries Kerberos protocol first; if that fails, it then uses NTLM.| -|Certificate|Performs client authentication using a certificate, typically X.509.| - -### Message Client Credential Types - - The following table shows the possible values used when creating an application that uses message security. You can use these values in either code or binding settings. - -|Setting|Description| -|-------------|-----------------| -|None|Allows the service to interact with anonymous clients.| -|Windows|Allows SOAP message exchanges to occur under the authenticated context of a Windows credential. Uses SSPI negotiation mechanism to pick from either the Kerberos protocol or NTLM as an authentication service.| -|Username|Allows the service to require that the client be authenticated with a user name credential. Note that WCF does not allow any cryptographic operations with the user name, such as generating a signature or encrypting data. As such, WCF enforces that the transport is secured when using user name credentials.| -|Certificate|Allows the service to require that the client be authenticated using a certificate.| -|CardSpace|Allows the service to require that the client be authenticated using an CardSpace.| - -### Programming Credentials - - For each of the client credential types, the WCF programming model allows you to specify the credential values and credential validators by using service behaviors and channel behaviors. - - WCF security has two types of credentials: service credential behaviors and channel credential behaviors. Credential behaviors in WCF specify the actual data, namely, credentials used to meet the security requirements expressed through bindings. In WCF, a client class is the run-time component that converts between operation invocation and messages. All clients inherit from the class. The property on the base class allows you to specify various values of client credentials. - - In WCF, service behaviors are attributes applied to the class implementing a service contract (interface) to programmatically control the service. The class allows you to specify certificates for service credential and client validation settings for various client credential types. - -### Negotiation Model for Message Security - - The message security mode allows you to perform transfer security so that the service credential is configured at the client out of band. For example, if you are using a certificate stored in the Windows certificate store, you must use a tool such as a Microsoft Management Console (MMC) snap-in. - - The message security mode also allows you to perform transfer security so that the service credential is exchanged with the client as part of an initial negotiation. To enable negotiation, set the property to `true`. - +Windows Communication Foundation (WCF) security is broken into three major functional areas: transfer security, access control, and auditing. Transfer security provides integrity, confidentiality, and authentication. Transfer security is provided by one of the following: transport security, message security, or `TransportWithMessageCredential`. + + For an overview of WCF message security, see [Security Overview](security-overview.md). For more information about the other two pieces of WCF security, see [Authorization](authorization-in-wcf.md) and [Auditing](auditing-security-events.md). + +## Transfer Security Scenarios + + Common scenarios that employ WCF transfer security include the following: + +- Secure transfer using Windows. A WCF client and service are deployed in a Windows domain (or a Windows forest). The messages contain personal data, so requirements include mutual authentication of the client and service, message integrity, and message confidentiality. In addition, proof is required that a particular transaction occurred, for example, the receiver of the message should record the signature information. + +- Secure transfer using `UserName` and HTTPS. A WCF client and service need to be developed to work across the Internet. The client credentials authenticate against a database of user name/password pairs. The service is deployed at an HTTPS address using a trusted Secure Sockets Layer (SSL) certificate. Because the messages travel over the Internet, the client and service need to be mutually authenticated, and the messages' confidentiality and integrity must be preserved during transfer. + +- Secure transfer using certificates. A WCF client and service need to be developed to work over the public internet. The client and service both have certificates that can be used to secure the messages. The client and service use the Internet to communicate with each other and to perform high-value transactions that require message integrity, confidentiality, and mutual authentication. + +## Integrity, Confidentiality, and Authentication + + Three functions—integrity, confidentiality and authentication—are together called transfer security. Transfer security provides the functions that help to mitigate the threats to a distributed application. The following table briefly describes the three functions that make up transfer security. + +|Function|Description| +|--------------|-----------------| +|Integrity|*Integrity* is the assurance that data is complete and accurate, especially after it has traversed from one point to another, and possibly been read by many actors. Integrity must be maintained to prevent tampering with the data, and is usually achieved by digital signing of a message.| +|Confidentiality|*Confidentiality* is the assurance that a message has not been read by anyone other than the intended reader. For example, a credit card number must be kept confidential as it is sent over the Internet. Confidentiality is often provided by the encryption of data using a public key/private key scheme.| +|Authentication|*Authentication* is the verification of a claimed identity. For example, when using a bank account, it is imperative that only the actual owner of the account be allowed to withdraw funds. Authentication can be provided by a variety of means. One common method is the user/password system. A second is the use of an X.509 certificate that is provided by a third party.| + +## Security Modes + + WCF has several modes of transfer security, which are described in the following table. + +|Mode|Description| +|----------|-----------------| +|None|No security is provided at the transport layer or at the message layer. None of the predefined bindings use this mode by default except the [\](../../configure-apps/file-schema/wcf/basichttpbinding.md) element or, when using code, the class.| +|Transport|Uses a secure transport such as HTTPS for integrity, confidentiality, and mutual authentication.| +|Message|Uses SOAP-message security for integrity, confidentiality, and mutual authentication. SOAP messages are secured according to the WS-Security standards.| +|Mixed Mode|Uses transport security for integrity, confidentiality, and server authentication. Uses message security (WS-Security and other standards) for client authentication.

(This enumeration for this mode is `TransportWithMessageCredential`.)| +|Both|Performs protection and authentication at both levels. This mode is available only in the [\](../../configure-apps/file-schema/wcf/netmsmqbinding.md) element.| + +## Credentials and Transfer Security + + A *credential* is data that is presented to establish either a claimed identity or capabilities. Presenting a credential involves presenting both the data and proof of possession of the data. WCF supports a variety of credential types at both the transport and message security levels. You can specify a type of credential for a WCF binding. + + In many countries or regions, a driver’s license is an example of a credential. A license contains data representing one's identity and capabilities. It contains proof of possession in the form of the possessor's picture. The license is issued by a trusted authority, usually a governmental licensing department. The license is sealed, and can contain a hologram, showing that it has not been tampered with or counterfeited. + + As an example, consider two types of credentials supported in WCF: user name and (X.509) certificate credentials. + + For the user name credential, the user name represents the claimed identity and the password presents the proof of possession. The trusted authority in this case is the system that validates the user name and password. + + In the certificate credential, the subject name, subject alternative name, or specific fields within the certificate can be used to represent the claimed identity and/or capabilities. Proof of possession of the data in the credential is established by using the associated private key to generate a signature. + + For more information about programming transfer security and specifying credentials, see [Bindings and Security](bindings-and-security.md) and [Security Behaviors](security-behaviors-in-wcf.md). + +### Transport Client Credential Types + + The following table shows the possible values used when creating an application that uses transfer security. You can use these values in either code or binding settings. + +|Setting|Description| +|-------------|-----------------| +|None|Specifies that the client does not need to present any credential. This translates to an anonymous client.| +|Basic|Specifies basic authentication. For more information, see RFC2617, "[HTTP Authentication: Basic and Digest Authentication](https://schemas.xmlsoap.org/ws/2004/10/discovery/ws-discovery.pdf)."| +|Digest|Specifies digest authentication. For more information, see RFC2617, "[HTTP Authentication: Basic and Digest Authentication](https://schemas.xmlsoap.org/ws/2004/10/discovery/ws-discovery.pdf)."| +|Ntlm|Specifies Windows authentication using SSPI negotiation on a Windows domain.

SSPI negotiation results in using either the Kerberos protocol or NT LanMan (NTLM).| +|Windows|Specifies Windows authentication using SSPI on a Windows domain. SSPI picks from either the Kerberos protocol or NTLM as authentication service.

SSPI tries Kerberos protocol first; if that fails, it then uses NTLM.| +|Certificate|Performs client authentication using a certificate, typically X.509.| + +### Message Client Credential Types + + The following table shows the possible values used when creating an application that uses message security. You can use these values in either code or binding settings. + +|Setting|Description| +|-------------|-----------------| +|None|Allows the service to interact with anonymous clients.| +|Windows|Allows SOAP message exchanges to occur under the authenticated context of a Windows credential. Uses SSPI negotiation mechanism to pick from either the Kerberos protocol or NTLM as an authentication service.| +|Username|Allows the service to require that the client be authenticated with a user name credential. Note that WCF does not allow any cryptographic operations with the user name, such as generating a signature or encrypting data. As such, WCF enforces that the transport is secured when using user name credentials.| +|Certificate|Allows the service to require that the client be authenticated using a certificate.| +|CardSpace|Allows the service to require that the client be authenticated using an CardSpace.| + +### Programming Credentials + + For each of the client credential types, the WCF programming model allows you to specify the credential values and credential validators by using service behaviors and channel behaviors. + + WCF security has two types of credentials: service credential behaviors and channel credential behaviors. Credential behaviors in WCF specify the actual data, namely, credentials used to meet the security requirements expressed through bindings. In WCF, a client class is the runtime component that converts between operation invocation and messages. All clients inherit from the class. The property on the base class allows you to specify various values of client credentials. + + In WCF, service behaviors are attributes applied to the class implementing a service contract (interface) to programmatically control the service. The class allows you to specify certificates for service credential and client validation settings for various client credential types. + +### Negotiation Model for Message Security + + The message security mode allows you to perform transfer security so that the service credential is configured at the client out of band. For example, if you are using a certificate stored in the Windows certificate store, you must use a tool such as a Microsoft Management Console (MMC) snap-in. + + The message security mode also allows you to perform transfer security so that the service credential is exchanged with the client as part of an initial negotiation. To enable negotiation, set the property to `true`. + ## See also - [Endpoint Creation Overview](../endpoint-creation-overview.md) diff --git a/docs/framework/wcf/feature-details/durable-duplex-correlation.md b/docs/framework/wcf/feature-details/durable-duplex-correlation.md index c8812de64651f..0d3384a78a086 100644 --- a/docs/framework/wcf/feature-details/durable-duplex-correlation.md +++ b/docs/framework/wcf/feature-details/durable-duplex-correlation.md @@ -117,7 +117,7 @@ host2.Open(); Console.WriteLine("Service2 waiting at: {0}", baseAddress2); ``` - The workflow that implements this workflow service begins with a activity. This receive activity initializes the callback correlation for this service, delays for a period of time to simulate long-running work, and then calls back into the first service using the callback context that was passed in the first call into the service. The following example represents the workflow that is returned from a call to `GetWF2`. The activity has a placeholder address of `http://www.contoso.com`; the actual address used at run time is the supplied callback address. + The workflow that implements this workflow service begins with a activity. This receive activity initializes the callback correlation for this service, delays for a period of time to simulate long-running work, and then calls back into the first service using the callback context that was passed in the first call into the service. The following example represents the workflow that is returned from a call to `GetWF2`. The activity has a placeholder address of `http://www.contoso.com`; the actual address used at runtime is the supplied callback address. ```csharp Variable ItemsCallbackHandle = new Variable(); diff --git a/docs/framework/wcf/feature-details/exporting-and-importing-metadata.md b/docs/framework/wcf/feature-details/exporting-and-importing-metadata.md index ccdcab6629bdb..dc599486ba9f9 100644 --- a/docs/framework/wcf/feature-details/exporting-and-importing-metadata.md +++ b/docs/framework/wcf/feature-details/exporting-and-importing-metadata.md @@ -2,74 +2,74 @@ description: "Learn more about: Exporting and Importing Metadata" title: "Exporting and Importing Metadata" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "metadata [WCF], exporting and importing" ms.assetid: 614a75bb-e0b0-4c95-b6d8-02cb5e5ddb38 --- # Exporting and Importing Metadata -In Windows Communication Foundation (WCF), exporting metadata is the process of describing service endpoints and projecting them into a parallel, standardized representation that clients can use to understand how to use the service. Importing service metadata is the process of generating instances or parts from service metadata. - -## Exporting Metadata +In Windows Communication Foundation (WCF), exporting metadata is the process of describing service endpoints and projecting them into a parallel, standardized representation that clients can use to understand how to use the service. Importing service metadata is the process of generating instances or parts from service metadata. + +## Exporting Metadata + + To export metadata from instances, use an implementation of the abstract class. The type is the implementation of the abstract class included with WCF. + + The type generates Web Services Description Language (WSDL) metadata with attached policy expressions encapsulated in a instance. You can use a instance to iteratively export metadata for objects and objects. You can also export a collection of objects and associate them with a specific service name. - To export metadata from instances, use an implementation of the abstract class. The type is the implementation of the abstract class included with WCF. - - The type generates Web Services Description Language (WSDL) metadata with attached policy expressions encapsulated in a instance. You can use a instance to iteratively export metadata for objects and objects. You can also export a collection of objects and associate them with a specific service name. - > [!NOTE] -> You can only use the `WsdlExporter` to export metadata from `ContractDescription` instances that contain common language runtime (CLR) type information, such as a `ContractDescription` instance created using the `ContractDescription.GetContract` method or created as part of the `ServiceDescription` for a `ServiceHost` instance. You cannot use the `WsdlExporter` to export metadata from `ContractDescription` instances imported from service metadata or constructed without type information. - -## Importing Metadata - -### Importing WSDL Documents - - To import service metadata in WCF, use an implementation of the abstract class. The type is the implementation of the abstract class included with WCF. The type imports WSDL metadata with attached policies bundled in a object. - - The type gives you control over how to import the metadata. You can import all of the endpoints, all of the bindings, or all of the contracts. You can import all of the endpoints associated with a specific WSDL service, binding, or port type. You can also import the endpoint for a specific WSDL port, the binding for a specific WSDL binding or the contract for a specific WSDL port type. - - The also exposes a property that allows you to specify a set of contracts that do not need to be imported. The uses the contracts in the property instead of importing a contract with the same qualified name from the metadata. - -### Importing Policies - - The type collects the policy expressions attached to the message, operation, and endpoint policy subjects and then uses the implementations in the collection to import the policy expressions. - - The policy import logic automatically handles policy references to policy expressions in the same WSDL document and is identified with a `wsu:Id` or `xml:id` attribute. The policy import logic protects applications against circular policy references by limiting the size of a policy expression to 4096 nodes, where a node is a one of the following elements: `wsp:Policy`, `wsp:All`, `wsp:ExactlyOne`, `wsp:policyReference`. - - The policy import logic also automatically normalizes policy expressions. Nested policy expressions and the `wsp:Optional` attribute are not normalized. The amount of normalization processing done is limited to 4096 steps, where each step yields a policy assertion, or a child element of a `wsp:ExactlyOne` element. - - The type tries up to 32 combinations of policy alternatives attached to the different WSDL policy subjects. If no combination imports cleanly, the first combination is used to construct a partial custom binding. - -## Error Handling - - Both the and the types expose an `Errors` property that can contain a collection of error and warning messages encountered during the export and import processes, respectively, that can be used when implementing tools. - - The type generally throws an exception for an exception caught during the import process and adds a corresponding error to its `Errors` property. The , , , and methods, however, do not throw these exceptions, so you must check the `Errors` property to determine if any issues occurred when calling these methods. - - The type rethrows any exceptions caught during the export process. These exceptions are not captured as errors in the `Errors` property. Once the throws an exception, it is in a faulted state and cannot be reused. The does add warnings to its `Errors` property when an operation cannot be exported because it uses wildcard actions and when duplicate binding names are encountered. - -## In This Section - - [How to: Import Metadata into Service Endpoints](how-to-import-metadata-into-service-endpoints.md) - Describes how to import downloaded metadata into description objects. - - [How to: Export Metadata from Service Endpoints](how-to-export-metadata-from-service-endpoints.md) - Describes how to export description objects into metadata. - - [ServiceDescription and WSDL Reference](servicedescription-and-wsdl-reference.md) - Describes the mapping between the description objects and WSDL. - - [How to: Use Svcutil.exe to Export Metadata from Compiled Service Code](how-to-use-svcutil-exe-to-export-metadata-from-compiled-service-code.md) - Describes the use of Svcutil.exe to export metadata for services, contracts, and data types in compiled assemblies. - - [Data Contract Schema Reference](data-contract-schema-reference.md) - Describes the subset of the XML Schema (XSD) used by to describe common language run-time (CLR) types for XML serialization. - -## Reference - - - - - +> You can only use the `WsdlExporter` to export metadata from `ContractDescription` instances that contain common language runtime (CLR) type information, such as a `ContractDescription` instance created using the `ContractDescription.GetContract` method or created as part of the `ServiceDescription` for a `ServiceHost` instance. You cannot use the `WsdlExporter` to export metadata from `ContractDescription` instances imported from service metadata or constructed without type information. + +## Importing Metadata + +### Importing WSDL Documents + + To import service metadata in WCF, use an implementation of the abstract class. The type is the implementation of the abstract class included with WCF. The type imports WSDL metadata with attached policies bundled in a object. + + The type gives you control over how to import the metadata. You can import all of the endpoints, all of the bindings, or all of the contracts. You can import all of the endpoints associated with a specific WSDL service, binding, or port type. You can also import the endpoint for a specific WSDL port, the binding for a specific WSDL binding or the contract for a specific WSDL port type. + + The also exposes a property that allows you to specify a set of contracts that do not need to be imported. The uses the contracts in the property instead of importing a contract with the same qualified name from the metadata. + +### Importing Policies + + The type collects the policy expressions attached to the message, operation, and endpoint policy subjects and then uses the implementations in the collection to import the policy expressions. + + The policy import logic automatically handles policy references to policy expressions in the same WSDL document and is identified with a `wsu:Id` or `xml:id` attribute. The policy import logic protects applications against circular policy references by limiting the size of a policy expression to 4096 nodes, where a node is a one of the following elements: `wsp:Policy`, `wsp:All`, `wsp:ExactlyOne`, `wsp:policyReference`. + + The policy import logic also automatically normalizes policy expressions. Nested policy expressions and the `wsp:Optional` attribute are not normalized. The amount of normalization processing done is limited to 4096 steps, where each step yields a policy assertion, or a child element of a `wsp:ExactlyOne` element. + + The type tries up to 32 combinations of policy alternatives attached to the different WSDL policy subjects. If no combination imports cleanly, the first combination is used to construct a partial custom binding. + +## Error Handling + + Both the and the types expose an `Errors` property that can contain a collection of error and warning messages encountered during the export and import processes, respectively, that can be used when implementing tools. + + The type generally throws an exception for an exception caught during the import process and adds a corresponding error to its `Errors` property. The , , , and methods, however, do not throw these exceptions, so you must check the `Errors` property to determine if any issues occurred when calling these methods. + + The type rethrows any exceptions caught during the export process. These exceptions are not captured as errors in the `Errors` property. Once the throws an exception, it is in a faulted state and cannot be reused. The does add warnings to its `Errors` property when an operation cannot be exported because it uses wildcard actions and when duplicate binding names are encountered. + +## In This Section + + [How to: Import Metadata into Service Endpoints](how-to-import-metadata-into-service-endpoints.md) + Describes how to import downloaded metadata into description objects. + + [How to: Export Metadata from Service Endpoints](how-to-export-metadata-from-service-endpoints.md) + Describes how to export description objects into metadata. + + [ServiceDescription and WSDL Reference](servicedescription-and-wsdl-reference.md) + Describes the mapping between the description objects and WSDL. + + [How to: Use Svcutil.exe to Export Metadata from Compiled Service Code](how-to-use-svcutil-exe-to-export-metadata-from-compiled-service-code.md) + Describes the use of Svcutil.exe to export metadata for services, contracts, and data types in compiled assemblies. + + [Data Contract Schema Reference](data-contract-schema-reference.md) + Describes the subset of the XML Schema (XSD) used by to describe common language runtime (CLR) types for XML serialization. + +## Reference + + + + + ## See also - [Exporting Custom Metadata for a WCF Extension](../extending/exporting-custom-metadata-for-a-wcf-extension.md) diff --git a/docs/framework/wcf/feature-details/federation.md b/docs/framework/wcf/feature-details/federation.md index 78372392c2bef..fc813a44112b3 100644 --- a/docs/framework/wcf/feature-details/federation.md +++ b/docs/framework/wcf/feature-details/federation.md @@ -2,301 +2,301 @@ description: "Learn more about: Federation" title: "Federation" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" -helpviewer_keywords: +helpviewer_keywords: - "WCF, federation" - "federation [WCF]" ms.assetid: 2f1e646f-8361-48d4-9d5d-1b961f31ede4 --- # Federation -This topic provides a brief overview of the concept of federated security. It also describes Windows Communication Foundation (WCF) support for deploying federated security architectures. For a sample application that demonstrates federation, see [Federation Sample](../samples/federation-sample.md). - -## Definition of Federated Security - - Federated security allows for clean separation between the service a client is accessing and the associated authentication and authorization procedures. Federated security also enables collaboration across multiple systems, networks, and organizations in different trust realms. - - WCF provides support for building and deploying distributed systems that employ federated security. - -### Elements of a Federated Security Architecture - - The federated security architecture has three key elements, as described in the following table. - -|Element|Description| -|-------------|-----------------| -|Domain/realm|A single unit of security administration or trust. A typical domain might include a single organization.| -|Federation|A collection of domains that have established trust. The level of trust may vary, but typically includes authentication and almost always includes authorization. A typical federation might include a number of organizations that have established trust for shared access to a set of resources.| -|Security Token Service (STS)|A Web service that issues security tokens; that is, it makes assertions based on evidence that it trusts, to whomever trusts it. This forms the basis of trust brokering between domains.| - -### Example Scenario - - The following illustration shows an example of federated security: - - ![Diagram showing a typical federated security scenario.](./media/federation/typical-federated-security-scenario.gif) - - This scenario includes two organizations: A and B. Organization B has a Web resource (a Web service) that some users in organization A find valuable. - +This topic provides a brief overview of the concept of federated security. It also describes Windows Communication Foundation (WCF) support for deploying federated security architectures. For a sample application that demonstrates federation, see [Federation Sample](../samples/federation-sample.md). + +## Definition of Federated Security + + Federated security allows for clean separation between the service a client is accessing and the associated authentication and authorization procedures. Federated security also enables collaboration across multiple systems, networks, and organizations in different trust realms. + + WCF provides support for building and deploying distributed systems that employ federated security. + +### Elements of a Federated Security Architecture + + The federated security architecture has three key elements, as described in the following table. + +|Element|Description| +|-------------|-----------------| +|Domain/realm|A single unit of security administration or trust. A typical domain might include a single organization.| +|Federation|A collection of domains that have established trust. The level of trust may vary, but typically includes authentication and almost always includes authorization. A typical federation might include a number of organizations that have established trust for shared access to a set of resources.| +|Security Token Service (STS)|A Web service that issues security tokens; that is, it makes assertions based on evidence that it trusts, to whomever trusts it. This forms the basis of trust brokering between domains.| + +### Example Scenario + + The following illustration shows an example of federated security: + + ![Diagram showing a typical federated security scenario.](./media/federation/typical-federated-security-scenario.gif) + + This scenario includes two organizations: A and B. Organization B has a Web resource (a Web service) that some users in organization A find valuable. + > [!NOTE] -> This section uses the terms *resource*, *service*, and *Web service* interchangeably. - - Typically, organization B requires that a user from organization A provide some valid form of authentication before accessing the service. In addition, the organization may also require that the user be authorized to access the specific resource in question. One way to address this problem and enable users in organization A to access the resource in organization B is as follows: - -- Users from organization A register their credentials (a user name and password) with organization B. - -- During the resource access, users from organization A present their credentials to organization B and are authenticated before accessing the resource. - - This approach has three significant drawbacks: - -- Organization B has to manage the credentials for users from organization A in addition to managing the credentials of its local users. - -- Users in organization A need to maintain an additional set of credentials (that is, remember an additional user name and password) apart from the credentials they normally use to gain access to resources within organization A. This usually encourages the practice of using the same user name and password at multiple service sites, which is a weak security measure. - -- The architecture does not scale as more organizations perceive the resource at organization B as being of some value. - - An alternative approach, which addresses the previously mentioned drawbacks, is to employ federated security. In this approach, organizations A and B establish a trust relationship and employ Security Token Service (STS) to enable brokering of the established trust. - - In a federated security architecture, users from organization A know that if they want to access the Web service in organization B that they must present a valid security token from the STS at organization B, which authenticates and authorizes their access to the specific service. - - On contacting the STS B, the users receive another level of indirection from the policy associated with the STS. They must present a valid security token from the STS A (that is, the client trust realm) before the STS B can issue them a security token. This is a corollary of the trust relationship established between the two organizations and implies that organization B does not have to manage identities for users from organization A. In practice, STS B typically has a null `issuerAddress` and `issuerMetadataAddress`. For more information, see [How to: Configure a Local Issuer](how-to-configure-a-local-issuer.md). In that case, the client consults a local policy to locate STS A. This configuration is called *home realm federation* and it scales better because STS B does not have to maintain information about STS A. - - The users then contact the STS at organization A and obtain a security token by presenting authentication credentials that they normally use to gain access to any other resource within organization A. This also alleviates the problem of users having to maintain multiple sets of credentials or using the same set of credentials at multiple service sites. - - Once the users obtain a security token from the STS A, they present the token to the STS B. Organization B proceeds to perform authorization of the users' requests and issues a security token to the users from its own set of security tokens. The users can then present their token to the resource at organization B and access the service. - -## Support for Federated Security in WCF - - WCF provides turnkey support for deploying federated security architectures through the [\](../../configure-apps/file-schema/wcf/wsfederationhttpbinding.md). - - The [\](../../configure-apps/file-schema/wcf/wsfederationhttpbinding.md) element provides for a secure, reliable, interoperable binding that entails the use of HTTP as the underlying transport mechanism for request-reply communication style, employing text and XML as the wire format for encoding. - - The use of [\](../../configure-apps/file-schema/wcf/wsfederationhttpbinding.md) in a federated security scenario can be decoupled into two logically independent phases, as described in the following sections. - -### Phase 1: Design Phase - - During the design phase, the client uses the [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md) to read the policy the service endpoint exposes and to collect the service's authentication and authorization requirements. The appropriate proxies are constructed to create the following federated security communication pattern at the client: - -- Obtain a security token from the STS in the client trust realm. - -- Present the token to the STS in the service trust realm. - -- Obtain a security token from the STS in the service trust realm. - -- Present the token to the service to access the service. - -### Phase 2: Run-Time Phase - - During the run-time phase, the client instantiates an object of the WCF client class and makes a call using the WCF client. The underlying framework of WCF handles the previously mentioned steps in the federated security communication pattern and enables the client to seamlessly consume the service. - -## Sample Implementation Using WCF - - The following illustration shows a sample implementation for a federated security architecture using native support from WCF. - - ![Diagram showing a sample Federation security implementation.](./media/federation/federated-security-implementation.gif) - -### Example MyService - - The service `MyService` exposes a single endpoint through `MyServiceEndpoint`. The following illustration shows the address, binding, and contract associated with the endpoint. - - ![Diagram showing the MyServiceEndpoint details.](./media/federation/myserviceendpoint-details.gif) - - The service endpoint `MyServiceEndpoint` uses the [\](../../configure-apps/file-schema/wcf/wsfederationhttpbinding.md) and requires a valid Security Assertions Markup Language (SAML) token with an `accessAuthorized` claim issued by STS B. This is declaratively specified in the service configuration. - -```xml - - +> This section uses the terms *resource*, *service*, and *Web service* interchangeably. + + Typically, organization B requires that a user from organization A provide some valid form of authentication before accessing the service. In addition, the organization may also require that the user be authorized to access the specific resource in question. One way to address this problem and enable users in organization A to access the resource in organization B is as follows: + +- Users from organization A register their credentials (a user name and password) with organization B. + +- During the resource access, users from organization A present their credentials to organization B and are authenticated before accessing the resource. + + This approach has three significant drawbacks: + +- Organization B has to manage the credentials for users from organization A in addition to managing the credentials of its local users. + +- Users in organization A need to maintain an additional set of credentials (that is, remember an additional user name and password) apart from the credentials they normally use to gain access to resources within organization A. This usually encourages the practice of using the same user name and password at multiple service sites, which is a weak security measure. + +- The architecture does not scale as more organizations perceive the resource at organization B as being of some value. + + An alternative approach, which addresses the previously mentioned drawbacks, is to employ federated security. In this approach, organizations A and B establish a trust relationship and employ Security Token Service (STS) to enable brokering of the established trust. + + In a federated security architecture, users from organization A know that if they want to access the Web service in organization B that they must present a valid security token from the STS at organization B, which authenticates and authorizes their access to the specific service. + + On contacting the STS B, the users receive another level of indirection from the policy associated with the STS. They must present a valid security token from the STS A (that is, the client trust realm) before the STS B can issue them a security token. This is a corollary of the trust relationship established between the two organizations and implies that organization B does not have to manage identities for users from organization A. In practice, STS B typically has a null `issuerAddress` and `issuerMetadataAddress`. For more information, see [How to: Configure a Local Issuer](how-to-configure-a-local-issuer.md). In that case, the client consults a local policy to locate STS A. This configuration is called *home realm federation* and it scales better because STS B does not have to maintain information about STS A. + + The users then contact the STS at organization A and obtain a security token by presenting authentication credentials that they normally use to gain access to any other resource within organization A. This also alleviates the problem of users having to maintain multiple sets of credentials or using the same set of credentials at multiple service sites. + + Once the users obtain a security token from the STS A, they present the token to the STS B. Organization B proceeds to perform authorization of the users' requests and issues a security token to the users from its own set of security tokens. The users can then present their token to the resource at organization B and access the service. + +## Support for Federated Security in WCF + + WCF provides turnkey support for deploying federated security architectures through the [\](../../configure-apps/file-schema/wcf/wsfederationhttpbinding.md). + + The [\](../../configure-apps/file-schema/wcf/wsfederationhttpbinding.md) element provides for a secure, reliable, interoperable binding that entails the use of HTTP as the underlying transport mechanism for request-reply communication style, employing text and XML as the wire format for encoding. + + The use of [\](../../configure-apps/file-schema/wcf/wsfederationhttpbinding.md) in a federated security scenario can be decoupled into two logically independent phases, as described in the following sections. + +### Phase 1: Design Phase + + During the design phase, the client uses the [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md) to read the policy the service endpoint exposes and to collect the service's authentication and authorization requirements. The appropriate proxies are constructed to create the following federated security communication pattern at the client: + +- Obtain a security token from the STS in the client trust realm. + +- Present the token to the STS in the service trust realm. + +- Obtain a security token from the STS in the service trust realm. + +- Present the token to the service to access the service. + +### Phase 2: Run-Time Phase + + During the runtime phase, the client instantiates an object of the WCF client class and makes a call using the WCF client. The underlying framework of WCF handles the previously mentioned steps in the federated security communication pattern and enables the client to seamlessly consume the service. + +## Sample Implementation Using WCF + + The following illustration shows a sample implementation for a federated security architecture using native support from WCF. + + ![Diagram showing a sample Federation security implementation.](./media/federation/federated-security-implementation.gif) + +### Example MyService + + The service `MyService` exposes a single endpoint through `MyServiceEndpoint`. The following illustration shows the address, binding, and contract associated with the endpoint. + + ![Diagram showing the MyServiceEndpoint details.](./media/federation/myserviceendpoint-details.gif) + + The service endpoint `MyServiceEndpoint` uses the [\](../../configure-apps/file-schema/wcf/wsfederationhttpbinding.md) and requires a valid Security Assertions Markup Language (SAML) token with an `accessAuthorized` claim issued by STS B. This is declaratively specified in the service configuration. + +```xml + + - - - - - - - - - - - + behaviorConfiguration='MyServiceBehavior'> + + + + + + + + + + + - - - - - - - - - - - + address= +"http://localhost/FederationSample/STS-B/STS.svc/mex" /> + + + +
+
+ + + + + + - - - - - - -``` - +operationRequirementType="FederationSample.MyServiceOperationRequirement, MyService" /> + + + + + + +``` + > [!NOTE] -> A subtle point should be noted about the claims required by `MyService`. The second figure indicates that `MyService` requires a SAML token with the `accessAuthorized` claim. To be more precise, this specifies the claim type that `MyService` requires. The fully-qualified name of this claim type is `http://tempuri.org:accessAuthorized` (along with the associated namespace), which is used in the service configuration file. The value of this claim indicates the presence of this claim and is assumed to be set to `true` by STS B. - - At run time, this policy is enforced by the `MyServiceOperationRequirement` class that is implemented as part of the `MyService`. - +> A subtle point should be noted about the claims required by `MyService`. The second figure indicates that `MyService` requires a SAML token with the `accessAuthorized` claim. To be more precise, this specifies the claim type that `MyService` requires. The fully-qualified name of this claim type is `http://tempuri.org:accessAuthorized` (along with the associated namespace), which is used in the service configuration file. The value of this claim indicates the presence of this claim and is assumed to be set to `true` by STS B. + + At runtime, this policy is enforced by the `MyServiceOperationRequirement` class that is implemented as part of the `MyService`. + [!code-csharp[C_Federation#0](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_federation/cs/source.cs#0)] - [!code-vb[C_Federation#0](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_federation/vb/source.vb#0)] + [!code-vb[C_Federation#0](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_federation/vb/source.vb#0)] [!code-csharp[C_Federation#1](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_federation/cs/source.cs#1)] -[!code-vb[C_Federation#1](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_federation/vb/source.vb#1)] - -#### STS B - - The following illustration shows the STS B. As stated earlier, a security token service (STS) is also a Web service and can have its associated endpoints, policy, and so on. - - ![Diagram showing security token service B.](./media/federation/myservice-security-token-service-b.gif) - - STS B exposes a single endpoint, called `STSEndpoint` that can be use to request security tokens. Specifically, STS B issues SAML tokens with the `accessAuthorized` claim, which can be presented at the `MyService` service site for accessing the service. However, STS B requires users to present a valid SAML token issued by STS A that contains the `userAuthenticated` claim. This is declaratively specified in the STS configuration. - -```xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -``` - +[!code-vb[C_Federation#1](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_federation/vb/source.vb#1)] + +#### STS B + + The following illustration shows the STS B. As stated earlier, a security token service (STS) is also a Web service and can have its associated endpoints, policy, and so on. + + ![Diagram showing security token service B.](./media/federation/myservice-security-token-service-b.gif) + + STS B exposes a single endpoint, called `STSEndpoint` that can be use to request security tokens. Specifically, STS B issues SAML tokens with the `accessAuthorized` claim, which can be presented at the `MyService` service site for accessing the service. However, STS B requires users to present a valid SAML token issued by STS A that contains the `userAuthenticated` claim. This is declaratively specified in the STS configuration. + +```xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +``` + > [!NOTE] -> Again, the `userAuthenticated` claim is the claim type that is required by STS B. The fully-qualified name of this claim type is `http://tempuri.org:userAuthenticated` (along with the associated namespace), which is used in the STS configuration file. The value of this claim indicates the presence of this claim and is assumed to be set to `true` by STS A. - - At run time, the `STS_B_OperationRequirement` class enforces this policy, which is implemented as part of STS B. - +> Again, the `userAuthenticated` claim is the claim type that is required by STS B. The fully-qualified name of this claim type is `http://tempuri.org:userAuthenticated` (along with the associated namespace), which is used in the STS configuration file. The value of this claim indicates the presence of this claim and is assumed to be set to `true` by STS A. + + At runtime, the `STS_B_OperationRequirement` class enforces this policy, which is implemented as part of STS B. + [!code-csharp[C_Federation#2](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_federation/cs/source.cs#2)] - [!code-vb[C_Federation#2](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_federation/vb/source.vb#2)] - - If the access check is clear, STS B issues a SAML token with the `accessAuthorized` claim. - + [!code-vb[C_Federation#2](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_federation/vb/source.vb#2)] + + If the access check is clear, STS B issues a SAML token with the `accessAuthorized` claim. + [!code-csharp[C_Federation#3](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_federation/cs/source.cs#3)] - [!code-vb[C_Federation#3](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_federation/vb/source.vb#3)] - -#### STS A - - The following illustration shows the STS A. - - ![Federation](media/sts-b.gif "STS_B") - - Similar to the STS B, the STS A is also a Web service that issues security tokens and exposes a single endpoint for this purpose. However, it uses a different binding (`wsHttpBinding`) and requires users to present a valid CardSpace with an `emailAddress` claim. In response, it issues SAML tokens with the `userAuthenticated` claim. This is declaratively specified in the service configuration. - -```xml - - - - - + [!code-vb[C_Federation#3](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_federation/vb/source.vb#3)] + +#### STS A + + The following illustration shows the STS A. + + ![Federation](media/sts-b.gif "STS_B") + + Similar to the STS B, the STS A is also a Web service that issues security tokens and exposes a single endpoint for this purpose. However, it uses a different binding (`wsHttpBinding`) and requires users to present a valid CardSpace with an `emailAddress` claim. In response, it issues SAML tokens with the `userAuthenticated` claim. This is declaratively specified in the service configuration. + +```xml + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - -``` - - At run time, the `STS_A_OperationRequirement` class enforces this policy, which is implemented as part of STS A. - + storeName="My" /> + + + + + + + + + + + + + + + + + + + + + + + + + +``` + + At runtime, the `STS_A_OperationRequirement` class enforces this policy, which is implemented as part of STS A. + [!code-csharp[C_Federation#4](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_federation/cs/source.cs#4)] - [!code-vb[C_Federation#4](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_federation/vb/source.vb#4)] - - If the access is `true`, STS A issues a SAML token with `userAuthenticated` claim. - + [!code-vb[C_Federation#4](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_federation/vb/source.vb#4)] + + If the access is `true`, STS A issues a SAML token with `userAuthenticated` claim. + [!code-csharp[C_Federation#5](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_federation/cs/source.cs#5)] - [!code-vb[C_Federation#5](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_federation/vb/source.vb#5)] - -### Client at Organization A - - The following illustration shows the client at organization A, along with the steps involved in making a `MyService` service call. The other functional components are also included for completeness. - - ![Diagram showing the steps in a MyService service call.](./media/federation/federation-myservice-service-call-process.gif) - -## Summary - - Federated security provides a clean division of responsibility and helps to build secure, scalable service architectures. As a platform for building and deploying distributed applications, WCF provides native support for implementing federated security. - + [!code-vb[C_Federation#5](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_federation/vb/source.vb#5)] + +### Client at Organization A + + The following illustration shows the client at organization A, along with the steps involved in making a `MyService` service call. The other functional components are also included for completeness. + + ![Diagram showing the steps in a MyService service call.](./media/federation/federation-myservice-service-call-process.gif) + +## Summary + + Federated security provides a clean division of responsibility and helps to build secure, scalable service architectures. As a platform for building and deploying distributed applications, WCF provides native support for implementing federated security. + ## See also - [Security](security.md) diff --git a/docs/framework/wcf/feature-details/hosting-in-windows-process-activation-service.md b/docs/framework/wcf/feature-details/hosting-in-windows-process-activation-service.md index cd014740b920b..e368a90e469e0 100644 --- a/docs/framework/wcf/feature-details/hosting-in-windows-process-activation-service.md +++ b/docs/framework/wcf/feature-details/hosting-in-windows-process-activation-service.md @@ -44,7 +44,7 @@ The Windows Process Activation Service (WAS) manages the activation and lifetime ## The WAS Runtime - Applications are organized into sites for the purposes of addressing and management. At run time, applications are also grouped together into application pools. An application pool can house many different applications from many different sites. All of the applications inside an application pool share a common set of run-time characteristics. For example, they all run under the same version of the common language runtime (CLR) and they all share a common process identity. Each application pool corresponds to an instance of a worker process (w3wp.exe). Each managed application running inside of a shared application pool is isolated from other applications by means of a CLR AppDomain. + Applications are organized into sites for the purposes of addressing and management. At runtime, applications are also grouped together into application pools. An application pool can house many different applications from many different sites. All of the applications inside an application pool share a common set of runtime characteristics. For example, they all run under the same version of the common language runtime (CLR) and they all share a common process identity. Each application pool corresponds to an instance of a worker process (w3wp.exe). Each managed application running inside of a shared application pool is isolated from other applications by means of a CLR AppDomain. ## See also diff --git a/docs/framework/wcf/feature-details/how-to-call-operations-asynchronously-using-a-channel-factory.md b/docs/framework/wcf/feature-details/how-to-call-operations-asynchronously-using-a-channel-factory.md index 44ab000865b11..d753bed65fb51 100644 --- a/docs/framework/wcf/feature-details/how-to-call-operations-asynchronously-using-a-channel-factory.md +++ b/docs/framework/wcf/feature-details/how-to-call-operations-asynchronously-using-a-channel-factory.md @@ -39,7 +39,7 @@ This topic covers how a client can access a service operation asynchronously whe ## Example - The service that is used with the client code that is used in the preceding procedure implements the `ICalculator` interface as shown in the following code. On the service side, the `Add` and `Subtract` operations of the contract are invoked synchronously by the Windows Communication Foundation (WCF) run time, even though the preceding client steps are invoked asynchronously on the client. The `Multiply` and `Divide` operations are used to invoke the service asynchronously on the service side, even if the client invokes them synchronously. This example sets the property to `true`. This property setting, in combination with the implementation of the .NET Framework asynchronous pattern, tells the runtime to invoke the operation asynchronously. + The service that is used with the client code that is used in the preceding procedure implements the `ICalculator` interface as shown in the following code. On the service side, the `Add` and `Subtract` operations of the contract are invoked synchronously by the Windows Communication Foundation (WCF) runtime, even though the preceding client steps are invoked asynchronously on the client. The `Multiply` and `Divide` operations are used to invoke the service asynchronously on the service side, even if the client invokes them synchronously. This example sets the property to `true`. This property setting, in combination with the implementation of the .NET Framework asynchronous pattern, tells the runtime to invoke the operation asynchronously. [!code-csharp[C_How_To_CF_Async#4](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_how_to_cf_async/cs/service.cs#4)] [!code-vb[C_How_To_CF_Async#4](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_how_to_cf_async/vb/service.vb#4)] diff --git a/docs/framework/wcf/feature-details/how-to-configure-tracking-with-workflowservicehost.md b/docs/framework/wcf/feature-details/how-to-configure-tracking-with-workflowservicehost.md index d6c067cbc03ab..16f4af74b3dc0 100644 --- a/docs/framework/wcf/feature-details/how-to-configure-tracking-with-workflowservicehost.md +++ b/docs/framework/wcf/feature-details/how-to-configure-tracking-with-workflowservicehost.md @@ -25,7 +25,7 @@ This topic explains how to configure tracking for a [!INCLUDE[netfx_current_long > [!NOTE] > The preceding configuration sample is using simplified configuration. For more information, see [Simplified Configuration](../simplified-configuration.md). - The preceding configuration sample adds a and specifies a tracking profile name. Tracking profiles are created in a `` element within a `` element. The tracking profile contains tracking queries that permit a tracking participant to subscribe to workflow events that are emitted when the state of a workflow instance changes at run time. The following example shows how to create a tracking profile. + The preceding configuration sample adds a and specifies a tracking profile name. Tracking profiles are created in a `` element within a `` element. The tracking profile contains tracking queries that permit a tracking participant to subscribe to workflow events that are emitted when the state of a workflow instance changes at runtime. The following example shows how to create a tracking profile. ```xml diff --git a/docs/framework/wcf/feature-details/how-to-host-a-wcf-service-in-iis.md b/docs/framework/wcf/feature-details/how-to-host-a-wcf-service-in-iis.md index b8f221f04b95f..d001d938b78fd 100644 --- a/docs/framework/wcf/feature-details/how-to-host-a-wcf-service-in-iis.md +++ b/docs/framework/wcf/feature-details/how-to-host-a-wcf-service-in-iis.md @@ -56,7 +56,7 @@ This topic outlines the basic steps required to create a Windows Communication F [!code-csharp[c_HowTo_HostInIIS#12](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_howto_hostiniis/cs/source.cs#12)] [!code-vb[c_HowTo_HostInIIS#12](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_howto_hostiniis/vb/source.vb#12)] -10. Create a file named "Web.config" in the application directory and add the following configuration code into the file. At run time, the WCF infrastructure uses the information to construct an endpoint that client applications can communicate with. +10. Create a file named "Web.config" in the application directory and add the following configuration code into the file. At runtime, the WCF infrastructure uses the information to construct an endpoint that client applications can communicate with. [!code-xml[c_HowTo_HostInIIS#100](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_howto_hostiniis/common/web.config#100)] diff --git a/docs/framework/wcf/feature-details/how-to-register-and-configure-a-service-moniker.md b/docs/framework/wcf/feature-details/how-to-register-and-configure-a-service-moniker.md index 144e6bb988ae1..d5d189af6a949 100644 --- a/docs/framework/wcf/feature-details/how-to-register-and-configure-a-service-moniker.md +++ b/docs/framework/wcf/feature-details/how-to-register-and-configure-a-service-moniker.md @@ -28,7 +28,7 @@ Before using the Windows Communication Foundation (WCF) service moniker within a 5. Use the Global Assembly Cache (Gacutil.exe) tool to add the assembly to the global assembly cache. > [!NOTE] - > Signing the assembly and adding it to the Global Assembly Cache are optional steps, but they can simplify the process of loading the assembly from the correct location at run time. + > Signing the assembly and adding it to the Global Assembly Cache are optional steps, but they can simplify the process of loading the assembly from the correct location at runtime. ## Configure the COM application and the moniker with the required binding configuration diff --git a/docs/framework/wcf/feature-details/how-to-use-filters.md b/docs/framework/wcf/feature-details/how-to-use-filters.md index ebf24d6fcf00f..fc83eef66a4ca 100644 --- a/docs/framework/wcf/feature-details/how-to-use-filters.md +++ b/docs/framework/wcf/feature-details/how-to-use-filters.md @@ -6,322 +6,322 @@ ms.assetid: f2c7255f-c376-460e-aa20-14071f1666e5 --- # How To: Use Filters -This topic outlines the basic steps required to create a routing configuration that uses multiple filters. In this example, messages are routed to two implementations of a calculator service, regularCalc and roundingCalc. Both implementations support the same operations; however one service rounds all calculations to the nearest integer value before returning. A client application must be able to indicate whether to use the rounding version of the service; if no service preference is expressed then the message is load balanced between the two services. The operations exposed by both services are: - -- Add - -- Subtract - -- Multiply - -- Divide - - Because both services implement the same operations, you cannot use the Action filter, because the action specified in the message will not be unique. Instead you must do additional work to ensure that the messages are routed to the appropriate endpoints. - -### Determine Unique Data - -1. Because both service implementations handle the same operations, and are essentially identical other than the data that they return, the base data contained in messages sent from client applications is not unique enough to allow you to determine how to route the request. But if the client application adds a unique header value to the message, then you can use this value to determine how the message should be routed. - - For this example, if the client application needs the message to be processed by the rounding calculator, it adds a custom header by using the following code: - - ```csharp +This topic outlines the basic steps required to create a routing configuration that uses multiple filters. In this example, messages are routed to two implementations of a calculator service, regularCalc and roundingCalc. Both implementations support the same operations; however one service rounds all calculations to the nearest integer value before returning. A client application must be able to indicate whether to use the rounding version of the service; if no service preference is expressed then the message is load balanced between the two services. The operations exposed by both services are: + +- Add + +- Subtract + +- Multiply + +- Divide + + Because both services implement the same operations, you cannot use the Action filter, because the action specified in the message will not be unique. Instead you must do additional work to ensure that the messages are routed to the appropriate endpoints. + +### Determine Unique Data + +1. Because both service implementations handle the same operations, and are essentially identical other than the data that they return, the base data contained in messages sent from client applications is not unique enough to allow you to determine how to route the request. But if the client application adds a unique header value to the message, then you can use this value to determine how the message should be routed. + + For this example, if the client application needs the message to be processed by the rounding calculator, it adds a custom header by using the following code: + + ```csharp messageHeadersElement.Add(MessageHeader.CreateHeader("RoundingCalculator", - "http://my.custom.namespace/", "rounding")); - ``` - - You can now use the XPath filter to inspect messages for this header, and route messages containing the header to the roundCalc service. - -2. Additionally the Routing Service exposes two virtual service endpoints that can be used with the EndpointName, EndpointAddress, or PrefixEndpointAddress filters to uniquely route incoming messages to a specific calculator implementation based on the endpoint to which the client application submits the request. - -### Define Endpoints - -1. When defining the endpoints used by the Routing Service, you should first determine the shape of the channel used by your clients and services. In this scenario both the destination services use a request-reply pattern, so the is used. The following example defines the service endpoints exposed by the Routing Service. - - ```xml - - - - - - - - - - - - - - - - - - ``` - - With this configuration, the Routing Service exposes three separate endpoints. Depending on run-time choices, the client application sends messages to one of these addresses. Messages arriving at one of the "virtual" service endpoints ("rounding/calculator" or "regular/calculator") are forwarded to the corresponding calculator implementation. If the client application doesn’t send the request to a particular endpoint, the message is addressed to the general endpoint. Regardless of the endpoint chosen, the client application may also choose to include the custom header to indicate that the message should be forwarded to the rounding calculator implementation. - -2. The following example defines the client (destination) endpoints that the Routing Service routes messages to. - - ```xml - - - - - - ``` - - These endpoints are used in the filter table to indicate the destination endpoint the message is sent to when it matches a specific filter. - -### Define Filters - -1. To route messages based on the "RoundingCalculator" custom header that the client application adds to the message, define a filter that uses an XPath query to check for the presence of this header. Because this header is defined by using a custom namespace, also add a namespace entry that defines a custom namespace prefix of "custom" that is used in the XPath query. The following example defines the necessary routing section, namespace table, and XPath filter. - - ```xml - - - - - - - - + "http://my.custom.namespace/", "rounding")); + ``` + + You can now use the XPath filter to inspect messages for this header, and route messages containing the header to the roundCalc service. + +2. Additionally the Routing Service exposes two virtual service endpoints that can be used with the EndpointName, EndpointAddress, or PrefixEndpointAddress filters to uniquely route incoming messages to a specific calculator implementation based on the endpoint to which the client application submits the request. + +### Define Endpoints + +1. When defining the endpoints used by the Routing Service, you should first determine the shape of the channel used by your clients and services. In this scenario both the destination services use a request-reply pattern, so the is used. The following example defines the service endpoints exposed by the Routing Service. + + ```xml + + + + + + + + + + + + + + + + + + ``` + + With this configuration, the Routing Service exposes three separate endpoints. Depending on runtime choices, the client application sends messages to one of these addresses. Messages arriving at one of the "virtual" service endpoints ("rounding/calculator" or "regular/calculator") are forwarded to the corresponding calculator implementation. If the client application doesn’t send the request to a particular endpoint, the message is addressed to the general endpoint. Regardless of the endpoint chosen, the client application may also choose to include the custom header to indicate that the message should be forwarded to the rounding calculator implementation. + +2. The following example defines the client (destination) endpoints that the Routing Service routes messages to. + + ```xml + + + + + + ``` + + These endpoints are used in the filter table to indicate the destination endpoint the message is sent to when it matches a specific filter. + +### Define Filters + +1. To route messages based on the "RoundingCalculator" custom header that the client application adds to the message, define a filter that uses an XPath query to check for the presence of this header. Because this header is defined by using a custom namespace, also add a namespace entry that defines a custom namespace prefix of "custom" that is used in the XPath query. The following example defines the necessary routing section, namespace table, and XPath filter. + + ```xml + + + + + + + + - - - ``` - - This **MessageFilter** looks for a RoundingCalculator header in the message that contains a value of "rounding". This header is set by the client to indicate that the message should be routed to the roundingCalc service. - + filterData="/s12:Envelope/s12:Header/custom:RoundingCalculator = 'rounding'"/> + + + ``` + + This **MessageFilter** looks for a RoundingCalculator header in the message that contains a value of "rounding". This header is set by the client to indicate that the message should be routed to the roundingCalc service. + > [!NOTE] > The s12 namespace prefix is defined by default in the namespace table, and represents the namespace `http://www.w3.org/2003/05/soap-envelope`. - -2. You must also define filters that look for messages received on the two virtual endpoints. The first virtual endpoint is the "regular/calculator" endpoint. The client can send requests to this endpoint to indicate that the message should be routed to the regularCalc service. The following configuration defines a filter that uses the to determine if the message arrived through an endpoint with the name specified in filterData. - - ```xml - - - ``` - - If a message is received by the service endpoint named "calculatorEndpoint", this filter evaluates to `true`. - -3. Next, define a filter that looks for messages sent to the address of the roundingEndpoint. The client can send requests to this endpoint to indicate that the message should be routed to the roundingCalc service. The following configuration defines a filter that uses the to determine if the message arrived at the "rounding/calculator" endpoint. - - ```xml - - - ``` - - If a message is received at an address that begins with `http://localhost/routingservice/router/rounding/` then this filter evaluates to **true**. Because the base address used by this configuration is `http://localhost/routingservice/router` and the address specified for the roundingEndpoint is "rounding/calculator", the full address used to communicate with this endpoint is `http://localhost/routingservice/router/rounding/calculator`, which matches this filter. - + +2. You must also define filters that look for messages received on the two virtual endpoints. The first virtual endpoint is the "regular/calculator" endpoint. The client can send requests to this endpoint to indicate that the message should be routed to the regularCalc service. The following configuration defines a filter that uses the to determine if the message arrived through an endpoint with the name specified in filterData. + + ```xml + + + ``` + + If a message is received by the service endpoint named "calculatorEndpoint", this filter evaluates to `true`. + +3. Next, define a filter that looks for messages sent to the address of the roundingEndpoint. The client can send requests to this endpoint to indicate that the message should be routed to the roundingCalc service. The following configuration defines a filter that uses the to determine if the message arrived at the "rounding/calculator" endpoint. + + ```xml + + + ``` + + If a message is received at an address that begins with `http://localhost/routingservice/router/rounding/` then this filter evaluates to **true**. Because the base address used by this configuration is `http://localhost/routingservice/router` and the address specified for the roundingEndpoint is "rounding/calculator", the full address used to communicate with this endpoint is `http://localhost/routingservice/router/rounding/calculator`, which matches this filter. + > [!NOTE] - > The PrefixEndpointAddress filter does not evaluate the host name when performing a match, because a single host can be referred to by using a variety of host names that may all be valid ways of referring to the host from the client application. For example, all of the following may refer to the same host: + > The PrefixEndpointAddress filter does not evaluate the host name when performing a match, because a single host can be referred to by using a variety of host names that may all be valid ways of referring to the host from the client application. For example, all of the following may refer to the same host: > - > - localhost - > - 127.0.0.1 - > - `www.contoso.com` - > - ContosoWeb01 - -4. The final filter must support the routing of messages that arrive at the general endpoint without the custom header. For this scenario, the messages should alternate between the regularCalc and roundingCalc services. To support the "round robin" routing of these messages, use a custom filter that allows one filter instance to match for each message processed. The following defines two instances of a RoundRobinMessageFilter, which are grouped together to indicate that they should alternate between each other. - - ```xml - - - - ``` - - During run time, this filter type alternates between all defined filter instances of this type that are configured as the same group into one collection. This causes messages processed by this custom filter to alternate between returning `true` for `RoundRobinFilter1` and `RoundRobinFilter2`. - -### Define Filter Tables - -1. To associate the filters with specific client endpoints, you must place them within a filter table. This example scenario also uses filter priority settings, which is an optional setting that allows you to indicate the order in which filters are processed. If no filter priority is specified, all filters are evaluated simultaneously. - + > - localhost + > - 127.0.0.1 + > - `www.contoso.com` + > - ContosoWeb01 + +4. The final filter must support the routing of messages that arrive at the general endpoint without the custom header. For this scenario, the messages should alternate between the regularCalc and roundingCalc services. To support the "round robin" routing of these messages, use a custom filter that allows one filter instance to match for each message processed. The following defines two instances of a RoundRobinMessageFilter, which are grouped together to indicate that they should alternate between each other. + + ```xml + + + + ``` + + During runtime, this filter type alternates between all defined filter instances of this type that are configured as the same group into one collection. This causes messages processed by this custom filter to alternate between returning `true` for `RoundRobinFilter1` and `RoundRobinFilter2`. + +### Define Filter Tables + +1. To associate the filters with specific client endpoints, you must place them within a filter table. This example scenario also uses filter priority settings, which is an optional setting that allows you to indicate the order in which filters are processed. If no filter priority is specified, all filters are evaluated simultaneously. + > [!NOTE] - > While specifying a filter priority allows you to control the order in which filters are processed, it can adversely affect the performance of the Routing Service. When possible, construct filter logic so that the use of filter priorities is not required. - - The following defines the filter table and adds the "XPathFilter" defined earlier to the table with a priority of 2. This entry also specifies that if the `XPathFilter` matches the message, the message will be routed to the `roundingCalcEndpoint`. - - ```xml - - ... - ... - - - - - - - -
-
-
- ``` - - When specifying a filter priority, the highest priority filters are evaluated first. If one or more filters at a specific priority level match, no filters at lower priority levels will be evaluated. For this scenario, 2 is the highest priority specified and this is the only filter entry at this level. - -2. Filter entries were defined to check to see if a message is received on a specific endpoint by inspecting the endpoint name or the address prefix. The following entries add both of these filter entries to the filter table and associate them with the destination endpoints that the message will be routed to. These filters are set to a priority of 1 to indicate that they should only run if the previous XPath filter did not match the message. - - ```xml - - - - - ``` - - Because these filters have a filter priority of 1, they will only be evaluated if the filter at priority level 2 does not match the message. Also, because both filters have the same priority level they will be evaluated simultaneously. Because both filters are mutually exclusive, it is possible for only one or the other to match a message. - -3. If a message does not match any of the previous filters, then the message was received through the generic service endpoint and contained no header information that indicates where to route it. These messages are to be handled by the custom filter, which load balances them between the two calculator services. The following example demonstrates how to add the filter entries to the filter table; each filter is associated with one of the two destination endpoints. - - ```xml - - - - - ``` - - Because these entries specify a priority of 0, they will only be evaluated if no filter of a higher priority matches the message. Also, since both are of the same priority, they are evaluated simultaneously. - - As mentioned previously, the custom filter used by these filter definitions only evaluates one or the other as `true` for each message received. Because only two filters are defined using this filter, with the same specified group setting, the effect is that the Routing Service alternates between sending to the regularCalcEndpoint and the RoundingCalcEndpoint. - -4. To evaluate messages against the filters, the filter table must first be associated with the service endpoints that will be used to receive messages. The following example demonstrates how to associate the routing table with the service endpoints by using the routing behavior: - - ```xml - - - - - - - - - ``` - -## Example - - The following is a complete listing of the configuration file. - -```xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
-
-
-
-``` - + > While specifying a filter priority allows you to control the order in which filters are processed, it can adversely affect the performance of the Routing Service. When possible, construct filter logic so that the use of filter priorities is not required. + + The following defines the filter table and adds the "XPathFilter" defined earlier to the table with a priority of 2. This entry also specifies that if the `XPathFilter` matches the message, the message will be routed to the `roundingCalcEndpoint`. + + ```xml + + ... + ... + + + + + + + +
+
+
+ ``` + + When specifying a filter priority, the highest priority filters are evaluated first. If one or more filters at a specific priority level match, no filters at lower priority levels will be evaluated. For this scenario, 2 is the highest priority specified and this is the only filter entry at this level. + +2. Filter entries were defined to check to see if a message is received on a specific endpoint by inspecting the endpoint name or the address prefix. The following entries add both of these filter entries to the filter table and associate them with the destination endpoints that the message will be routed to. These filters are set to a priority of 1 to indicate that they should only run if the previous XPath filter did not match the message. + + ```xml + + + + + ``` + + Because these filters have a filter priority of 1, they will only be evaluated if the filter at priority level 2 does not match the message. Also, because both filters have the same priority level they will be evaluated simultaneously. Because both filters are mutually exclusive, it is possible for only one or the other to match a message. + +3. If a message does not match any of the previous filters, then the message was received through the generic service endpoint and contained no header information that indicates where to route it. These messages are to be handled by the custom filter, which load balances them between the two calculator services. The following example demonstrates how to add the filter entries to the filter table; each filter is associated with one of the two destination endpoints. + + ```xml + + + + + ``` + + Because these entries specify a priority of 0, they will only be evaluated if no filter of a higher priority matches the message. Also, since both are of the same priority, they are evaluated simultaneously. + + As mentioned previously, the custom filter used by these filter definitions only evaluates one or the other as `true` for each message received. Because only two filters are defined using this filter, with the same specified group setting, the effect is that the Routing Service alternates between sending to the regularCalcEndpoint and the RoundingCalcEndpoint. + +4. To evaluate messages against the filters, the filter table must first be associated with the service endpoints that will be used to receive messages. The following example demonstrates how to associate the routing table with the service endpoints by using the routing behavior: + + ```xml + + + + + + + + + ``` + +## Example + + The following is a complete listing of the configuration file. + +```xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+
+``` + ## See also - [Routing Services](../samples/routing-services.md) diff --git a/docs/framework/wcf/feature-details/index.md b/docs/framework/wcf/feature-details/index.md index de5e8d1652faa..17dfe48ffa5e9 100644 --- a/docs/framework/wcf/feature-details/index.md +++ b/docs/framework/wcf/feature-details/index.md @@ -1,8 +1,8 @@ --- title: "WCF Feature Details" -description: Learn in detail about the extensive control that WCF offers over the messaging functions of an application. +description: Learn in detail about the extensive control that WCF offers over the messaging functions of an application. ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "features [WCF]" - "WCF, features" - "Windows Communication Foundation, features" @@ -10,74 +10,74 @@ ms.assetid: 9b4368ca-0bd3-40dc-a539-bcd5779cee5f --- # WCF Feature Details -Windows Communication Foundation (WCF) allows extensive control over the messaging functions of an application. The topics in this section go into detail about the available features. For more information about basic programming, see [Basic WCF Programming](../basic-wcf-programming.md). - -## In This Section - - [Workflow Services](workflow-services.md) - Describes how to create and configure workflow services. - - [Endpoints: Addresses, Bindings, and Contracts](endpoints-addresses-bindings-and-contracts.md) - Describes how to control multiple aspects of your service. - - [Data Transfer and Serialization](data-transfer-and-serialization.md) - Describes how serialization of data can be tailored for interoperation or future compatibility. - - [Sessions, Instancing, and Concurrency](sessions-instancing-and-concurrency.md) - Describes the instancing and session modes of WCF and how to select the right mode for your application. - - [Transports](transports.md) - Describes how to configure the transport layer, the lowest level of the channel stack. - - [Queues and Reliable Sessions](queues-and-reliable-sessions.md) - Describes queues, which store messages from a sending application on behalf of a receiving application and later forward these messages to the receiving application. - - [Transactions](transactions-in-wcf.md) - Explains how to create transacted operations that can be rolled back if needed. - - [Security](security.md) - Describes how WCF security helps you to create applications that have confidentiality and integrity. Authentication and authorization are also available, as are auditing features. - - [Peer-to-Peer Networking](peer-to-peer-networking.md) - Details how to create peer services and clients. - - [Metadata](metadata.md) - Describes metadata architecture and formats. - - [Clients](clients.md) - Describes how to create a variety of clients that access services. - - [Hosting](hosting.md) - Describes hosting. A service can be hosted by another application, or it can be self-hosted. - - [Interoperability and Integration](interoperability-and-integration.md) - Describes how to use WCF to extend your existing logic rather than having to rewrite it if you have a substantial investment in component-based application logic hosted in COM+. - - [WCF Web HTTP Programming Model](wcf-web-http-programming-model.md) - Describes the WCF Web Programming Model that allows developers to expose WCF service operations to non-SOAP endpoints. - - [WCF Syndication](wcf-syndication.md) - Describes support to easily expose syndication feeds from a WCF service. - - [AJAX Integration and JSON Support](ajax-integration-and-json-support.md) - Describes support for ASP.NET Asynchronous JavaScript and XML (AJAX) and the JavaScript Object Notation (JSON) data format to allow WCF services to expose operations to AJAX clients. - - [WCF Discovery](wcf-discovery.md) - Describes support to enable services to be discoverable at run time in an interoperable way using the WS-Discovery protocol. - - [Routing](routing.md) - Describes the routing service. - -## Reference - - - - - - - - - -## Related Sections +Windows Communication Foundation (WCF) allows extensive control over the messaging functions of an application. The topics in this section go into detail about the available features. For more information about basic programming, see [Basic WCF Programming](../basic-wcf-programming.md). + +## In This Section + + [Workflow Services](workflow-services.md) + Describes how to create and configure workflow services. + + [Endpoints: Addresses, Bindings, and Contracts](endpoints-addresses-bindings-and-contracts.md) + Describes how to control multiple aspects of your service. + + [Data Transfer and Serialization](data-transfer-and-serialization.md) + Describes how serialization of data can be tailored for interoperation or future compatibility. + + [Sessions, Instancing, and Concurrency](sessions-instancing-and-concurrency.md) + Describes the instancing and session modes of WCF and how to select the right mode for your application. + + [Transports](transports.md) + Describes how to configure the transport layer, the lowest level of the channel stack. + + [Queues and Reliable Sessions](queues-and-reliable-sessions.md) + Describes queues, which store messages from a sending application on behalf of a receiving application and later forward these messages to the receiving application. + + [Transactions](transactions-in-wcf.md) + Explains how to create transacted operations that can be rolled back if needed. + + [Security](security.md) + Describes how WCF security helps you to create applications that have confidentiality and integrity. Authentication and authorization are also available, as are auditing features. + + [Peer-to-Peer Networking](peer-to-peer-networking.md) + Details how to create peer services and clients. + + [Metadata](metadata.md) + Describes metadata architecture and formats. + + [Clients](clients.md) + Describes how to create a variety of clients that access services. + + [Hosting](hosting.md) + Describes hosting. A service can be hosted by another application, or it can be self-hosted. + + [Interoperability and Integration](interoperability-and-integration.md) + Describes how to use WCF to extend your existing logic rather than having to rewrite it if you have a substantial investment in component-based application logic hosted in COM+. + + [WCF Web HTTP Programming Model](wcf-web-http-programming-model.md) + Describes the WCF Web Programming Model that allows developers to expose WCF service operations to non-SOAP endpoints. + + [WCF Syndication](wcf-syndication.md) + Describes support to easily expose syndication feeds from a WCF service. + + [AJAX Integration and JSON Support](ajax-integration-and-json-support.md) + Describes support for ASP.NET Asynchronous JavaScript and XML (AJAX) and the JavaScript Object Notation (JSON) data format to allow WCF services to expose operations to AJAX clients. + + [WCF Discovery](wcf-discovery.md) + Describes support to enable services to be discoverable at runtime in an interoperable way using the WS-Discovery protocol. + + [Routing](routing.md) + Describes the routing service. + +## Reference + + + + + + + + + +## Related Sections [Basic WCF Programming](../basic-wcf-programming.md) diff --git a/docs/framework/wcf/feature-details/integrating-with-com-applications-overview.md b/docs/framework/wcf/feature-details/integrating-with-com-applications-overview.md index 2da91906e7d2d..eac957468a662 100644 --- a/docs/framework/wcf/feature-details/integrating-with-com-applications-overview.md +++ b/docs/framework/wcf/feature-details/integrating-with-com-applications-overview.md @@ -21,7 +21,7 @@ In common with other WCF clients, when using the moniker, applications specify t - WSDL contract – the contract is supplied in the form of a WSDL document. -- MEX contract – the contract is retrieved at run time from a Metadata Exchange (MEX) endpoint. +- MEX contract – the contract is retrieved at runtime from a Metadata Exchange (MEX) endpoint. ## Parameters Supported by the Service Moniker diff --git a/docs/framework/wcf/feature-details/large-data-and-streaming.md b/docs/framework/wcf/feature-details/large-data-and-streaming.md index 3342e8bf4e1e4..b66d4d131cfec 100644 --- a/docs/framework/wcf/feature-details/large-data-and-streaming.md +++ b/docs/framework/wcf/feature-details/large-data-and-streaming.md @@ -6,248 +6,248 @@ ms.assetid: ab2851f5-966b-4549-80ab-c94c5c0502d2 --- # Large Data and Streaming -Windows Communication Foundation (WCF) is an XML-based communications infrastructure. Because XML data is commonly encoded in the standard text format defined in the [XML 1.0 specification](https://www.w3.org/TR/REC-xml/), connected systems developers and architects are typically concerned about the wire footprint (or size) of messages sent across the network, and the text-based encoding of XML poses special challenges for the efficient transfer of binary data. - -## Basic Considerations - - To provide background information about the following information for WCF, this section highlights some general concerns and considerations for encodings, binary data, and streaming that generally apply to connected systems infrastructures. - -### Encoding Data: Text vs. Binary - - Commonly expressed developer concerns include the perception that XML has significant overhead when compared to binary formats due to the repetitive nature of start tags and end tags, that the encoding of numerical values is considered to be significantly larger because they are expressed in text values, and that binary data cannot be expressed efficiently because it must be specially encoded for embedding into a text format. - - While many of these and similar concerns are valid, the actual difference between XML-text encoded messages in an XML Web services environment and binary-encoded messages in a legacy remote procedure call (RPC) environment is often much less significant than the initial consideration might suggest. - - While XML-text encoded messages are transparent and "human readable", binary messages are often fairly obscure in comparison and difficult to decode without tools. This difference in legibility leads one to overlook that binary messages also often carry inline metadata in the payload, which adds overhead just as with XML text messages. This is specifically true for binary formats that aim to provide loose-coupling and dynamic invocation capabilities. - - However, binary formats commonly carry such descriptive metadata information in a "header," which also declares the data layout for the following data records. The payload then follows this common metadata block declaration with minimal further overhead. In contrast, XML encloses each data item in an element or attribute so that the enclosing metadata is repetitively included for each serialized payload object. As a result, the size of a single serialized payload object is similar when comparing text to binary representations as some descriptive metadata must be expressed for both, but the binary format benefits from the shared metadata description with each additional payload object that is transferred due to the lower overall overhead. - - Still, for certain data types, such as numbers, there might be a disadvantage to using fixed-size, binary numerical representations, such as a 128-bit decimal type instead of plain text, as the plain text representation might be several bytes smaller. Text data also might have size benefits from the typically more flexible XML text encoding choices, while some binary formats might default to 16-bit or even 32-bit Unicode, which does not apply to the .NET Binary XML Format. - - As a result, deciding between text or binary is not quite as easy as assuming that binary messages are always smaller than XML-text messages. - - A clear advantage of XML-text messages is that they are standards-based and offer the broadest choice of interoperability options and platform support. For more information, see the "Encodings" section later in this topic. - -### Binary Content - - One area where binary encodings are superior to text-based encodings in terms of the resulting message size are large binary data items such as pictures, videos, sound clips, or any other form of opaque, binary data that must be exchanged between services and their consumers. To fit these types of data into XML text, the common approach is to encode them using the Base64 encoding. - - In a Base64-encoded string, each character represents 6-bits of the original 8-bit data, which results in a 4:3 encoding-overhead ratio for Base64, not counting extra formatting characters (carriage return/line feed) that are commonly added by convention. While the significance of the differences between XML and binary encodings typically depends on the scenario, a size gain of more than 33% when transmitting a 500-MB payload is usually not acceptable. - - To avoid this encoding overhead, the Message Transmission Optimization Mechanism (MTOM) standard allows for externalizing large data elements that are contained in a message and carrying them with the message as binary data without any special encoding. With MTOM, messages are exchanged in a similar fashion to Simple Mail Transfer Protocol (SMTP) email messages with attachments or embedded content (pictures and other embedded content); MTOM messages are packaged as multipart/related MIME sequences with the root part being the actual SOAP message. - - An MTOM SOAP message is modified from its un-encoded version so that special element tags that refer to the respective MIME parts take the place of the original elements in the message that contained binary data. As a result, the SOAP message refers to binary content by pointing to the MIME parts sent with it, but otherwise just carries XML text data. Because this model is closely aligned with the well-established SMTP model, there is broad tooling support to encode and decode MTOM messages on many platforms, which makes it an extremely interoperable choice. - - Still, as with Base64, MTOM also comes with some necessary overhead for the MIME format, so that advantages of using MTOM are only seen when the size of a binary data element exceeds about 1 KB. Due to the overhead, MTOM-encoded messages might be larger than messages that use Base64 encoding for binary data, if the binary payload remains under that threshold. For more information, see the "Encodings" section later in this topic. - -### Large Data Content - - Wire-footprint aside, the previously mentioned 500-MB payload also poses a great local challenge at for the service and the client. By default, WCF processes messages in *buffered mode*. This means that the entire content of a message is present in memory before it is sent or after it is received. While that is a good strategy for most scenarios, and necessary for messaging features such as digital signatures and reliable delivery, large messages could exhaust a system's resources. - - The strategy to deal with large payloads is streaming. While messages, especially those expressed in XML, are commonly thought of as being relatively compact data packages, a message might be multiple gigabytes in size and resemble a continuous data stream more than a data package. When data is transferred in streaming mode instead of buffered mode, the sender makes the contents of the message body available to the recipient in the form of a stream and the message infrastructure continuously forwards the data from sender to receiver as it becomes available. - - The most common scenario in which such large data content transfers occur are transfers of binary data objects that: - -- Cannot be easily broken up into a message sequence. - -- Must be delivered in a timely manner. - -- Are not available in their entirety when the transfer is initiated. - - For data that does not have these constraints, it is typically better to send sequences of messages within the scope of a session than one large message. For more information, see the "Streaming Data" section later in this topic. - - When sending large amounts of data you will need to set the `maxAllowedContentLength` IIS setting (for more information see [Configuring IIS Request Limits](/iis/configuration/system.webServer/security/requestFiltering/requestLimits/)) and the `maxReceivedMessageSize` binding setting (for example [System.ServiceModel.BasicHttpBinding.MaxReceivedMessageSize](xref:System.ServiceModel.HttpBindingBase.MaxReceivedMessageSize%2A) or ). The `maxAllowedContentLength` property defaults to 28.6 MB and the `maxReceivedMessageSize` property defaults to 64KB. - -## Encodings - - An *encoding* defines a set of rules about how to present messages on the wire. An *encoder* implements such an encoding and is responsible, on the sender side, for turning an in-memory into a byte stream or byte buffer that can be sent across the network. On the receiver side, the encoder turns a sequence of bytes into an in-memory message. - - WCF includes three encoders and allows you to write and plug in your own encoders, if necessary. - - Each of the standard bindings includes a preconfigured encoder, whereby the bindings with the Net* prefix use the binary encoder (by including the class) while the and classes use the text message encoder (by means of the class) by default. - -|Encoder binding element|Description| -|-----------------------------|-----------------| -||The text message encoder is the default encoder for all HTTP-based bindings and the appropriate choice for all custom bindings where interoperability is the highest concern. This encoder reads and writes standard SOAP 1.1/SOAP 1.2 text messages with no special handling for binary data. If the property of a message is set to , the SOAP envelope wrapper is omitted from the output and only the message body content is serialized.| -||The MTOM message encoder is a text encoder that implements special handling for binary data and is not used by default in any of the standard bindings because it is strictly a case-by-case optimization utility. If the message contains binary data that exceeds a threshold where MTOM encoding yields a benefit, the data is externalized into a MIME part following the message envelope. See Enabling MTOM later in this section.| -||The binary message encoder is the default encoder for the Net* bindings and the appropriate choice whenever both communicating parties are based on WCF. The binary message encoder uses the .NET Binary XML Format, a Microsoft-specific binary representation for XML Information Sets (Infosets) that generally yields a smaller footprint than the equivalent XML 1.0 representation and encodes binary data as a byte stream.| - - Text message encoding is typically the best choice for any communication path that requires interoperability, while binary message encoding is the best choice for any other communication path. Binary message encoding typically yields smaller message sizes compared to text for a single message and progressively even smaller message sizes over the duration of a communication session. Unlike text encoding, binary encoding does not have to use special handling for binary data, such as using Base64, but represents bytes as bytes. - - If your solution does not require interoperability, but you still want to use HTTP transport, you can compose the into a custom binding that uses the class for the transport. If a number of clients on your service require interoperability, it is recommended that you expose parallel endpoints that each has the appropriate transport and encoding choices for the respective clients enabled. - -### Enabling MTOM - - When interoperability is a requirement and large binary data must be sent, then MTOM message encoding is the alternative encoding strategy that you can enable on the standard or bindings by setting the respective `MessageEncoding` property to or by composing the into a . The following example code, extracted from the [MTOM Encoding](../samples/mtom-encoding.md) sample demonstrates how to enable MTOM in configuration. - -```xml - - … - - - - - - … - -``` - - As mentioned earlier, the decision to use MTOM encoding depends on the data volume you are sending. Also, because MTOM is enabled at the binding level, enabling MTOM affects all operations on a given endpoint. - - Because the MTOM encoder always emits an MTOM-encoded MIME/multi-part message regardless of whether binary data ends up being externalized, you should generally only enable MTOM for endpoints that exchange messages with more than 1 KB of binary data. Also, the service contracts designed for use with MTOM-enabled endpoints should, when possible, be constrained to specifying such data transfer operations. Related control functionality should reside on a separate contract. This "MTOM-only" rule applies only to messages sent through an MTOM-enabled endpoint; the MTOM-encoder can decode and parse incoming non-MTOM messages as well. - - Using the MTOM encoder conforms with all other WCF features. Note that it may not be possible to observe this rule in all cases, such as when session support is required. - -### Programming Model - - Regardless of which of the three built-in encoders you use in your application, the programming experience is identical with regards to transferring binary data. The difference is in how WCF handles the data based on their data types. - +Windows Communication Foundation (WCF) is an XML-based communications infrastructure. Because XML data is commonly encoded in the standard text format defined in the [XML 1.0 specification](https://www.w3.org/TR/REC-xml/), connected systems developers and architects are typically concerned about the wire footprint (or size) of messages sent across the network, and the text-based encoding of XML poses special challenges for the efficient transfer of binary data. + +## Basic Considerations + + To provide background information about the following information for WCF, this section highlights some general concerns and considerations for encodings, binary data, and streaming that generally apply to connected systems infrastructures. + +### Encoding Data: Text vs. Binary + + Commonly expressed developer concerns include the perception that XML has significant overhead when compared to binary formats due to the repetitive nature of start tags and end tags, that the encoding of numerical values is considered to be significantly larger because they are expressed in text values, and that binary data cannot be expressed efficiently because it must be specially encoded for embedding into a text format. + + While many of these and similar concerns are valid, the actual difference between XML-text encoded messages in an XML Web services environment and binary-encoded messages in a legacy remote procedure call (RPC) environment is often much less significant than the initial consideration might suggest. + + While XML-text encoded messages are transparent and "human readable", binary messages are often fairly obscure in comparison and difficult to decode without tools. This difference in legibility leads one to overlook that binary messages also often carry inline metadata in the payload, which adds overhead just as with XML text messages. This is specifically true for binary formats that aim to provide loose-coupling and dynamic invocation capabilities. + + However, binary formats commonly carry such descriptive metadata information in a "header," which also declares the data layout for the following data records. The payload then follows this common metadata block declaration with minimal further overhead. In contrast, XML encloses each data item in an element or attribute so that the enclosing metadata is repetitively included for each serialized payload object. As a result, the size of a single serialized payload object is similar when comparing text to binary representations as some descriptive metadata must be expressed for both, but the binary format benefits from the shared metadata description with each additional payload object that is transferred due to the lower overall overhead. + + Still, for certain data types, such as numbers, there might be a disadvantage to using fixed-size, binary numerical representations, such as a 128-bit decimal type instead of plain text, as the plain text representation might be several bytes smaller. Text data also might have size benefits from the typically more flexible XML text encoding choices, while some binary formats might default to 16-bit or even 32-bit Unicode, which does not apply to the .NET Binary XML Format. + + As a result, deciding between text or binary is not quite as easy as assuming that binary messages are always smaller than XML-text messages. + + A clear advantage of XML-text messages is that they are standards-based and offer the broadest choice of interoperability options and platform support. For more information, see the "Encodings" section later in this topic. + +### Binary Content + + One area where binary encodings are superior to text-based encodings in terms of the resulting message size are large binary data items such as pictures, videos, sound clips, or any other form of opaque, binary data that must be exchanged between services and their consumers. To fit these types of data into XML text, the common approach is to encode them using the Base64 encoding. + + In a Base64-encoded string, each character represents 6-bits of the original 8-bit data, which results in a 4:3 encoding-overhead ratio for Base64, not counting extra formatting characters (carriage return/line feed) that are commonly added by convention. While the significance of the differences between XML and binary encodings typically depends on the scenario, a size gain of more than 33% when transmitting a 500-MB payload is usually not acceptable. + + To avoid this encoding overhead, the Message Transmission Optimization Mechanism (MTOM) standard allows for externalizing large data elements that are contained in a message and carrying them with the message as binary data without any special encoding. With MTOM, messages are exchanged in a similar fashion to Simple Mail Transfer Protocol (SMTP) email messages with attachments or embedded content (pictures and other embedded content); MTOM messages are packaged as multipart/related MIME sequences with the root part being the actual SOAP message. + + An MTOM SOAP message is modified from its un-encoded version so that special element tags that refer to the respective MIME parts take the place of the original elements in the message that contained binary data. As a result, the SOAP message refers to binary content by pointing to the MIME parts sent with it, but otherwise just carries XML text data. Because this model is closely aligned with the well-established SMTP model, there is broad tooling support to encode and decode MTOM messages on many platforms, which makes it an extremely interoperable choice. + + Still, as with Base64, MTOM also comes with some necessary overhead for the MIME format, so that advantages of using MTOM are only seen when the size of a binary data element exceeds about 1 KB. Due to the overhead, MTOM-encoded messages might be larger than messages that use Base64 encoding for binary data, if the binary payload remains under that threshold. For more information, see the "Encodings" section later in this topic. + +### Large Data Content + + Wire-footprint aside, the previously mentioned 500-MB payload also poses a great local challenge at for the service and the client. By default, WCF processes messages in *buffered mode*. This means that the entire content of a message is present in memory before it is sent or after it is received. While that is a good strategy for most scenarios, and necessary for messaging features such as digital signatures and reliable delivery, large messages could exhaust a system's resources. + + The strategy to deal with large payloads is streaming. While messages, especially those expressed in XML, are commonly thought of as being relatively compact data packages, a message might be multiple gigabytes in size and resemble a continuous data stream more than a data package. When data is transferred in streaming mode instead of buffered mode, the sender makes the contents of the message body available to the recipient in the form of a stream and the message infrastructure continuously forwards the data from sender to receiver as it becomes available. + + The most common scenario in which such large data content transfers occur are transfers of binary data objects that: + +- Cannot be easily broken up into a message sequence. + +- Must be delivered in a timely manner. + +- Are not available in their entirety when the transfer is initiated. + + For data that does not have these constraints, it is typically better to send sequences of messages within the scope of a session than one large message. For more information, see the "Streaming Data" section later in this topic. + + When sending large amounts of data you will need to set the `maxAllowedContentLength` IIS setting (for more information see [Configuring IIS Request Limits](/iis/configuration/system.webServer/security/requestFiltering/requestLimits/)) and the `maxReceivedMessageSize` binding setting (for example [System.ServiceModel.BasicHttpBinding.MaxReceivedMessageSize](xref:System.ServiceModel.HttpBindingBase.MaxReceivedMessageSize%2A) or ). The `maxAllowedContentLength` property defaults to 28.6 MB and the `maxReceivedMessageSize` property defaults to 64KB. + +## Encodings + + An *encoding* defines a set of rules about how to present messages on the wire. An *encoder* implements such an encoding and is responsible, on the sender side, for turning an in-memory into a byte stream or byte buffer that can be sent across the network. On the receiver side, the encoder turns a sequence of bytes into an in-memory message. + + WCF includes three encoders and allows you to write and plug in your own encoders, if necessary. + + Each of the standard bindings includes a preconfigured encoder, whereby the bindings with the Net* prefix use the binary encoder (by including the class) while the and classes use the text message encoder (by means of the class) by default. + +|Encoder binding element|Description| +|-----------------------------|-----------------| +||The text message encoder is the default encoder for all HTTP-based bindings and the appropriate choice for all custom bindings where interoperability is the highest concern. This encoder reads and writes standard SOAP 1.1/SOAP 1.2 text messages with no special handling for binary data. If the property of a message is set to , the SOAP envelope wrapper is omitted from the output and only the message body content is serialized.| +||The MTOM message encoder is a text encoder that implements special handling for binary data and is not used by default in any of the standard bindings because it is strictly a case-by-case optimization utility. If the message contains binary data that exceeds a threshold where MTOM encoding yields a benefit, the data is externalized into a MIME part following the message envelope. See Enabling MTOM later in this section.| +||The binary message encoder is the default encoder for the Net* bindings and the appropriate choice whenever both communicating parties are based on WCF. The binary message encoder uses the .NET Binary XML Format, a Microsoft-specific binary representation for XML Information Sets (Infosets) that generally yields a smaller footprint than the equivalent XML 1.0 representation and encodes binary data as a byte stream.| + + Text message encoding is typically the best choice for any communication path that requires interoperability, while binary message encoding is the best choice for any other communication path. Binary message encoding typically yields smaller message sizes compared to text for a single message and progressively even smaller message sizes over the duration of a communication session. Unlike text encoding, binary encoding does not have to use special handling for binary data, such as using Base64, but represents bytes as bytes. + + If your solution does not require interoperability, but you still want to use HTTP transport, you can compose the into a custom binding that uses the class for the transport. If a number of clients on your service require interoperability, it is recommended that you expose parallel endpoints that each has the appropriate transport and encoding choices for the respective clients enabled. + +### Enabling MTOM + + When interoperability is a requirement and large binary data must be sent, then MTOM message encoding is the alternative encoding strategy that you can enable on the standard or bindings by setting the respective `MessageEncoding` property to or by composing the into a . The following example code, extracted from the [MTOM Encoding](../samples/mtom-encoding.md) sample demonstrates how to enable MTOM in configuration. + +```xml + + … + + + + + + … + +``` + + As mentioned earlier, the decision to use MTOM encoding depends on the data volume you are sending. Also, because MTOM is enabled at the binding level, enabling MTOM affects all operations on a given endpoint. + + Because the MTOM encoder always emits an MTOM-encoded MIME/multi-part message regardless of whether binary data ends up being externalized, you should generally only enable MTOM for endpoints that exchange messages with more than 1 KB of binary data. Also, the service contracts designed for use with MTOM-enabled endpoints should, when possible, be constrained to specifying such data transfer operations. Related control functionality should reside on a separate contract. This "MTOM-only" rule applies only to messages sent through an MTOM-enabled endpoint; the MTOM-encoder can decode and parse incoming non-MTOM messages as well. + + Using the MTOM encoder conforms with all other WCF features. Note that it may not be possible to observe this rule in all cases, such as when session support is required. + +### Programming Model + + Regardless of which of the three built-in encoders you use in your application, the programming experience is identical with regards to transferring binary data. The difference is in how WCF handles the data based on their data types. + ```csharp -[DataContract] -class MyData -{ - [DataMember] - byte[] binaryBuffer; - [DataMember] - string someStringData; +[DataContract] +class MyData +{ + [DataMember] + byte[] binaryBuffer; + [DataMember] + string someStringData; } -``` - - When using MTOM, the preceding data contract is serialized according to the following rules: - -- If `binaryBuffer` is not `null` and individually contains enough data to justify the MTOM externalization overhead (MIME headers, and so on) when compared to Base64 encoding, the data is externalized and carried with the message as a binary MIME part. If the threshold is not exceeded, the data is encoded as Base64. - -- The string (and all other types that are not binary) is always represented as a string inside the message body, regardless of size. - - The effect on the MTOM encoding is the same whether you use an explicit data contract, as shown in the preceding example, use a parameter list in an operation, have nested data contracts, or transfer a data contract object inside a collection. Byte arrays are always candidates for optimization and are optimized if the optimization thresholds are being met. - +``` + + When using MTOM, the preceding data contract is serialized according to the following rules: + +- If `binaryBuffer` is not `null` and individually contains enough data to justify the MTOM externalization overhead (MIME headers, and so on) when compared to Base64 encoding, the data is externalized and carried with the message as a binary MIME part. If the threshold is not exceeded, the data is encoded as Base64. + +- The string (and all other types that are not binary) is always represented as a string inside the message body, regardless of size. + + The effect on the MTOM encoding is the same whether you use an explicit data contract, as shown in the preceding example, use a parameter list in an operation, have nested data contracts, or transfer a data contract object inside a collection. Byte arrays are always candidates for optimization and are optimized if the optimization thresholds are being met. + > [!NOTE] -> You should not be using derived types inside of data contracts. Stream data should be communicated using the streaming model, explained in the following "Streaming Data" section. - -## Streaming Data - - When you have a large amount of data to transfer, the streaming transfer mode in WCF is a feasible alternative to the default behavior of buffering and processing messages in memory in their entirety. - - As mentioned earlier, enable streaming only for large messages (with text or binary content) if the data cannot be segmented, if the message must be delivered in a timely fashion, or if the data is not yet fully available when the transfer is initiated. - -### Restrictions - - You cannot use a significant number of WCF features when streaming is enabled: - -- Digital signatures for the message body cannot be performed because they require computing a hash over the entire message contents. With streaming, the content is not fully available when the message headers are constructed and sent and, therefore, a digital signature cannot be computed. - -- Encryption depends on digital signatures to verify that the data has been reconstructed correctly. - -- Reliable sessions must buffer sent messages on the client for redelivery if a message gets lost in transfer and must hold messages on the service before handing them to the service implementation to preserve message order in case messages are received out-of-sequence. - - Because of these functional constraints, you can use only transport-level security options for streaming and you cannot turn on reliable sessions. Streaming is only available with the following system-defined bindings: - -- - -- - -- - -- - - Because the underlying transports of and have inherent reliable delivery and connection-based session support, unlike HTTP, these two bindings are only minimally affected by these constraints, in practice. - - Streaming is not available with the Message Queuing (MSMQ) transport and so cannot be used with the or the class. The Message Queuing transport only supports buffered data transfers with a constrained message size, while all other transports do not have any practical message size limit for the vast majority of scenarios. - - Streaming is also not available when using the Peer Channel transport, so is not available with the . - -#### Streaming and Sessions - - You may get unexpected behavior when streaming calls with a session-based binding. All streaming calls are made through a single channel (the datagram channel) that does not support sessions even if the binding being used is configured to use sessions. If multiple clients make streaming calls to the same service object over a session-based binding and the service object's concurrency mode is set to single and its instance context mode is set to PerSession, all calls must go through the datagram channel and so only one call is processed at a time. One or more clients may then time out. You can work around this issue by either setting the service object's Instance Context Mode to PerCall or Concurrency to Multiple. - +> You should not be using derived types inside of data contracts. Stream data should be communicated using the streaming model, explained in the following "Streaming Data" section. + +## Streaming Data + + When you have a large amount of data to transfer, the streaming transfer mode in WCF is a feasible alternative to the default behavior of buffering and processing messages in memory in their entirety. + + As mentioned earlier, enable streaming only for large messages (with text or binary content) if the data cannot be segmented, if the message must be delivered in a timely fashion, or if the data is not yet fully available when the transfer is initiated. + +### Restrictions + + You cannot use a significant number of WCF features when streaming is enabled: + +- Digital signatures for the message body cannot be performed because they require computing a hash over the entire message contents. With streaming, the content is not fully available when the message headers are constructed and sent and, therefore, a digital signature cannot be computed. + +- Encryption depends on digital signatures to verify that the data has been reconstructed correctly. + +- Reliable sessions must buffer sent messages on the client for redelivery if a message gets lost in transfer and must hold messages on the service before handing them to the service implementation to preserve message order in case messages are received out-of-sequence. + + Because of these functional constraints, you can use only transport-level security options for streaming and you cannot turn on reliable sessions. Streaming is only available with the following system-defined bindings: + +- + +- + +- + +- + + Because the underlying transports of and have inherent reliable delivery and connection-based session support, unlike HTTP, these two bindings are only minimally affected by these constraints, in practice. + + Streaming is not available with the Message Queuing (MSMQ) transport and so cannot be used with the or the class. The Message Queuing transport only supports buffered data transfers with a constrained message size, while all other transports do not have any practical message size limit for the vast majority of scenarios. + + Streaming is also not available when using the Peer Channel transport, so is not available with the . + +#### Streaming and Sessions + + You may get unexpected behavior when streaming calls with a session-based binding. All streaming calls are made through a single channel (the datagram channel) that does not support sessions even if the binding being used is configured to use sessions. If multiple clients make streaming calls to the same service object over a session-based binding and the service object's concurrency mode is set to single and its instance context mode is set to PerSession, all calls must go through the datagram channel and so only one call is processed at a time. One or more clients may then time out. You can work around this issue by either setting the service object's Instance Context Mode to PerCall or Concurrency to Multiple. + > [!NOTE] -> MaxConcurrentSessions has no effect in this case because there is only one "session" available. - -### Enabling Streaming - - You can enable streaming in the following ways: - -- Send and accept requests in streaming mode, and accept and return responses in buffered mode (). - -- Send and accept requests in buffered mode, and accept and return responses in streamed mode (). - -- Send and receive requests and responses in streamed mode in both directions. (). - - You can disable streaming by setting the transfer mode to , which is the default setting on all bindings. The following code shows how to set the transfer mode in configuration. - -```xml - - … - - - - - - … - -``` - - When you instantiate your binding in code, you must set the respective `TransferMode` property of the binding (or the transport binding element if you are composing a custom binding) to one of the previously mentioned values. - - You can turn on streaming for requests and replies or for both directions independently at either side of the communicating parties without affecting functionality. However, you should always assume that the transferred data size is so significant that enabling streaming is justified on both endpoints of a communication link. For cross-platform communication where one of the endpoints is not implemented with WCF, the ability to use streaming depends on the platform's streaming capabilities. Another rare exception might be a memory-consumption driven scenario where a client or service must minimize its working set and can only afford small buffer sizes. - -### Enabling Asynchronous Streaming - - To enable asynchronous streaming, add the endpoint behavior to the service host and set its property to `true`. We have also added the capability of true asynchronous streaming on the send side. This improves scalability of the service in scenarios where it is streaming messages to multiple clients some of which are slow in reading possibly due to network congestion or are not reading at all. In these scenarios we now do not block individual threads on the service per client. This ensures that the service is able to process many more clients thereby improving the scalability of the service. - -### Programming Model for Streamed Transfers - - The programming model for streaming is straightforward. For receiving streamed data, specify an operation contract that has a single typed input parameter. For returning streamed data, return a reference. - +> MaxConcurrentSessions has no effect in this case because there is only one "session" available. + +### Enabling Streaming + + You can enable streaming in the following ways: + +- Send and accept requests in streaming mode, and accept and return responses in buffered mode (). + +- Send and accept requests in buffered mode, and accept and return responses in streamed mode (). + +- Send and receive requests and responses in streamed mode in both directions. (). + + You can disable streaming by setting the transfer mode to , which is the default setting on all bindings. The following code shows how to set the transfer mode in configuration. + +```xml + + … + + + + + + … + +``` + + When you instantiate your binding in code, you must set the respective `TransferMode` property of the binding (or the transport binding element if you are composing a custom binding) to one of the previously mentioned values. + + You can turn on streaming for requests and replies or for both directions independently at either side of the communicating parties without affecting functionality. However, you should always assume that the transferred data size is so significant that enabling streaming is justified on both endpoints of a communication link. For cross-platform communication where one of the endpoints is not implemented with WCF, the ability to use streaming depends on the platform's streaming capabilities. Another rare exception might be a memory-consumption driven scenario where a client or service must minimize its working set and can only afford small buffer sizes. + +### Enabling Asynchronous Streaming + + To enable asynchronous streaming, add the endpoint behavior to the service host and set its property to `true`. We have also added the capability of true asynchronous streaming on the send side. This improves scalability of the service in scenarios where it is streaming messages to multiple clients some of which are slow in reading possibly due to network congestion or are not reading at all. In these scenarios we now do not block individual threads on the service per client. This ensures that the service is able to process many more clients thereby improving the scalability of the service. + +### Programming Model for Streamed Transfers + + The programming model for streaming is straightforward. For receiving streamed data, specify an operation contract that has a single typed input parameter. For returning streamed data, return a reference. + ```csharp -[ServiceContract(Namespace="http://Microsoft.ServiceModel.Samples")] -public interface IStreamedService -{ - [OperationContract] - Stream Echo(Stream data); - [OperationContract] - Stream RequestInfo(string query); - [OperationContract(OneWay=true)] - void ProvideInfo(Stream data); -} -``` - - The operation `Echo` in the preceding example receives and returns a stream and should therefore be used on a binding with . For the operation `RequestInfo`, is best suited, because it only returns a . The one-way operation is best suited for . - - Note that adding a second parameter to the following `Echo` or `ProvideInfo` operations causes the service model to revert back to a buffered strategy and use the run-time serialization representation of the stream. Only operations with a single input stream parameter are compatible with end-to-end request streaming. - - This rule similarly applies to message contracts. As shown in the following message contract, you can have only a single body member in your message contract that is a stream. If you want to communicate additional information with the stream, this information must be a carried in message headers. The message body is exclusively reserved for the stream content. - +[ServiceContract(Namespace="http://Microsoft.ServiceModel.Samples")] +public interface IStreamedService +{ + [OperationContract] + Stream Echo(Stream data); + [OperationContract] + Stream RequestInfo(string query); + [OperationContract(OneWay=true)] + void ProvideInfo(Stream data); +} +``` + + The operation `Echo` in the preceding example receives and returns a stream and should therefore be used on a binding with . For the operation `RequestInfo`, is best suited, because it only returns a . The one-way operation is best suited for . + + Note that adding a second parameter to the following `Echo` or `ProvideInfo` operations causes the service model to revert back to a buffered strategy and use the runtime serialization representation of the stream. Only operations with a single input stream parameter are compatible with end-to-end request streaming. + + This rule similarly applies to message contracts. As shown in the following message contract, you can have only a single body member in your message contract that is a stream. If you want to communicate additional information with the stream, this information must be a carried in message headers. The message body is exclusively reserved for the stream content. + ```csharp -[MessageContract] -public class UploadStreamMessage -{ - [MessageHeader] - public string appRef; - [MessageBodyMember] - public Stream data; +[MessageContract] +public class UploadStreamMessage +{ + [MessageHeader] + public string appRef; + [MessageBodyMember] + public Stream data; } -``` - - Streamed transfers end and the message is closed when the stream reaches the end of file (EOF). When sending a message (returning a value or invoking an operation), you can pass a and the WCF infrastructure subsequently pulls all the data from that stream until the stream has been completely read and reached EOF. To transfer streamed data for the source that no such pre-built derived class exists, construct such a class, overlay that class over your stream source, and use that as the argument or return value. - - When receiving a message, WCF constructs a stream over the Base64-encoded message body content (or the respective MIME part if using MTOM) and the stream reaches EOF when the content has been read. - - Transport-level streaming also works with any other message contract type (parameter lists, data contract arguments, and explicit message contract), but because the serialization and deserialization of such typed messages requires buffering by the serializer, using such contract variants is not advisable. - -### Special Security Considerations for Large Data - - All bindings allow you to constrain the size of incoming messages to prevent denial-of-service attacks. The , for example, exposes a [System.ServiceModel.BasicHttpBinding.MaxReceivedMessageSize](xref:System.ServiceModel.HttpBindingBase.MaxReceivedMessageSize%2A) property that bounds the size of the incoming message, and so also bounds the maximum amount of memory that is accessed when processing the message. This unit is set in bytes with a default value of 65,536 bytes. - - A security threat that is specific to the large data streaming scenario provokes a denial of service by causing data to be buffered when the receiver expects it to be streamed. For example, WCF always buffers the SOAP headers of a message, and so an attacker may construct a large malicious message that consists entirely of headers to force the data to be buffered. When streaming is enabled, the `MaxReceivedMessageSize` may be set to an extremely large value, because the receiver never expects the entire message to be buffered in memory at once. If WCF is forced to buffer the message, a memory overflow occurs. - - Therefore, restricting the maximum incoming message size is not enough in this case. The `MaxBufferSize` property is required to constrain the memory that WCF buffers. It is important to set this to a safe value (or keep it at the default value) when streaming. For example, suppose your service must receive files up to 4 GB in size and store them on the local disk. Suppose also that your memory is constrained in such a way that you can only buffer 64 KB of data at a time. Then you would set the `MaxReceivedMessageSize` to 4 GB and `MaxBufferSize` to 64 KB. Also, in your service implementation, you must ensure that you read only from the incoming stream in 64-KB chunks and do not read the next chunk before the previous one has been written to disk and discarded from memory. - - It is also important to understand that this quota only limits the buffering done by WCF and cannot protect you against any buffering that you do in your own service or client implementation. For more information about additional security considerations, see [Security Considerations for Data](security-considerations-for-data.md). - +``` + + Streamed transfers end and the message is closed when the stream reaches the end of file (EOF). When sending a message (returning a value or invoking an operation), you can pass a and the WCF infrastructure subsequently pulls all the data from that stream until the stream has been completely read and reached EOF. To transfer streamed data for the source that no such pre-built derived class exists, construct such a class, overlay that class over your stream source, and use that as the argument or return value. + + When receiving a message, WCF constructs a stream over the Base64-encoded message body content (or the respective MIME part if using MTOM) and the stream reaches EOF when the content has been read. + + Transport-level streaming also works with any other message contract type (parameter lists, data contract arguments, and explicit message contract), but because the serialization and deserialization of such typed messages requires buffering by the serializer, using such contract variants is not advisable. + +### Special Security Considerations for Large Data + + All bindings allow you to constrain the size of incoming messages to prevent denial-of-service attacks. The , for example, exposes a [System.ServiceModel.BasicHttpBinding.MaxReceivedMessageSize](xref:System.ServiceModel.HttpBindingBase.MaxReceivedMessageSize%2A) property that bounds the size of the incoming message, and so also bounds the maximum amount of memory that is accessed when processing the message. This unit is set in bytes with a default value of 65,536 bytes. + + A security threat that is specific to the large data streaming scenario provokes a denial of service by causing data to be buffered when the receiver expects it to be streamed. For example, WCF always buffers the SOAP headers of a message, and so an attacker may construct a large malicious message that consists entirely of headers to force the data to be buffered. When streaming is enabled, the `MaxReceivedMessageSize` may be set to an extremely large value, because the receiver never expects the entire message to be buffered in memory at once. If WCF is forced to buffer the message, a memory overflow occurs. + + Therefore, restricting the maximum incoming message size is not enough in this case. The `MaxBufferSize` property is required to constrain the memory that WCF buffers. It is important to set this to a safe value (or keep it at the default value) when streaming. For example, suppose your service must receive files up to 4 GB in size and store them on the local disk. Suppose also that your memory is constrained in such a way that you can only buffer 64 KB of data at a time. Then you would set the `MaxReceivedMessageSize` to 4 GB and `MaxBufferSize` to 64 KB. Also, in your service implementation, you must ensure that you read only from the incoming stream in 64-KB chunks and do not read the next chunk before the previous one has been written to disk and discarded from memory. + + It is also important to understand that this quota only limits the buffering done by WCF and cannot protect you against any buffering that you do in your own service or client implementation. For more information about additional security considerations, see [Security Considerations for Data](security-considerations-for-data.md). + > [!NOTE] -> The decision to use either buffered or streamed transfers is a local decision of the endpoint. For HTTP transports, the transfer mode does not propagate across a connection or to proxy servers and other intermediaries. Setting the transfer mode is not reflected in the description of the service interface. After generating a WCF client to a service, you must edit the configuration file for services intended to be used with streamed transfers to set the mode. For TCP and named pipe transports, the transfer mode is propagated as a policy assertion. - +> The decision to use either buffered or streamed transfers is a local decision of the endpoint. For HTTP transports, the transfer mode does not propagate across a connection or to proxy servers and other intermediaries. Setting the transfer mode is not reflected in the description of the service interface. After generating a WCF client to a service, you must edit the configuration file for services intended to be used with streamed transfers to set the mode. For TCP and named pipe transports, the transfer mode is propagated as a policy assertion. + ## See also - [How to: Enable Streaming](how-to-enable-streaming.md) diff --git a/docs/framework/wcf/feature-details/managing-claims-and-authorization-with-the-identity-model.md b/docs/framework/wcf/feature-details/managing-claims-and-authorization-with-the-identity-model.md index 3c54cdc8131a8..73d6c3d8ffbd5 100644 --- a/docs/framework/wcf/feature-details/managing-claims-and-authorization-with-the-identity-model.md +++ b/docs/framework/wcf/feature-details/managing-claims-and-authorization-with-the-identity-model.md @@ -106,7 +106,7 @@ Authorization is the process of determining which entities have permission to ch ### The Origin of Claims - Claims can come from a variety of sources. One common source of claims is credentials presented by a user, for example as part of a message sent to a Web service. The system validates such claims, and they become part of a set of claims associated with the user. Other system components may also be sources of claims, including, but not limited to, the operating system, the network stack, the run-time environment, or the application. In addition, remote services may also be a source of claims. + Claims can come from a variety of sources. One common source of claims is credentials presented by a user, for example as part of a message sent to a Web service. The system validates such claims, and they become part of a set of claims associated with the user. Other system components may also be sources of claims, including, but not limited to, the operating system, the network stack, the runtime environment, or the application. In addition, remote services may also be a source of claims. ### Authorization Policies diff --git a/docs/framework/wcf/feature-details/metadata-architecture-overview.md b/docs/framework/wcf/feature-details/metadata-architecture-overview.md index 96f0541528066..789dd9bf59aa2 100644 --- a/docs/framework/wcf/feature-details/metadata-architecture-overview.md +++ b/docs/framework/wcf/feature-details/metadata-architecture-overview.md @@ -2,92 +2,92 @@ description: "Learn more about: Metadata Architecture Overview" title: "Metadata Architecture Overview" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "metadata [WCF], overview" ms.assetid: 1d37645e-086d-4d68-a358-f3c5b6e8205e --- # Metadata Architecture Overview -Windows Communication Foundation (WCF) provides a rich infrastructure for exporting, publishing, retrieving, and importing service metadata. WCF services use metadata to describe how to interact with the service's endpoints so that tools, such as Svcutil.exe, can automatically generate client code for accessing the service. - - Most of the types that make up the WCF metadata infrastructure reside in the namespace. - - WCF uses the class to describe endpoints in a service. You can use WCF to generate metadata for service endpoints or import service metadata to generate instances. - - WCF represents the metadata for a service as an instance of the type, the structure of which is strongly tied to the metadata serialization format defined in WS-MetadataExchange. The type bundles the actual service metadata, such as Web Services Description Language (WSDL) documents, XML schema documents, or WS-Policy expressions, as a collection of instances. Each instance contains a specific metadata dialect and an identifier. A can contain the following items in its property: - -- Raw metadata. - -- A instance. - -- A instance. - - A instances point to another metadata exchange (MEX) endpoint and instances point to a metadata document using an HTTP URL. WCF supports using WSDL documents to describe service endpoints, service contracts, bindings, message exchange patterns, messages and fault messages implemented by a service. Data types used by the service are described in WSDL documents using XML schema. For more information, see [Schema Import and Export](schema-import-and-export.md). You can use WCF to export and import WSDL extensions for service behavior, contract behaviors, and binding elements that extend the functionality of a service. For more information, see [Exporting Custom Metadata for a WCF Extension](../extending/exporting-custom-metadata-for-a-wcf-extension.md). - -## Exporting Service Metadata - - In WCF, *metadata export* is the process of describing service endpoints and projecting them into a parallel, standardized representation that clients can use to understand how to use the service. To export metadata from instances, use an implementation of the abstract class. A implementation generates metadata that is encapsulated in a instance. - - The class provides a framework for generating policy expressions that describe the capabilities and requirements of an endpoint binding and its associated operations, messages, and faults. These policy expressions are captured in a instance. A implementation can then attach these policy expressions to the metadata it generates. - - The calls into each that implements the interface in the binding of a when generating a object for the implementation to use. You can export new policy assertions by implementing the interface on your custom implementations of the type. - - The type is the implementation of the abstract class included with WCF. The type generates WSDL metadata with attached policy expressions. - - To export custom WSDL metadata or WSDL extensions for endpoint behaviors, contract behaviors, or binding elements in a service endpoint, you can implement the interface. The looks at a instance for binding elements, operation behaviors, contract behaviors, and endpoint behaviors that implement the interface when generating the WSDL document. - -## Publishing Service Metadata - - WCF services publish metadata by exposing one or more metadata endpoints. Publishing service metadata makes service metadata available using standardized protocols, such as MEX and HTTP/GET requests. Metadata endpoints are similar to other service endpoints in that they have an address, a binding, and a contract. You can add metadata endpoints to a service host in configuration or in code. - - To publish metadata endpoints for a WCF service, you must first add an instance of the service behavior to the service. Adding a instance to your service augments your service with the ability to publish metadata by exposing one or more metadata endpoints. Once you add the service behavior you can then expose metadata endpoints that support the MEX protocol or metadata endpoints that respond to HTTP/GET requests. - - To add metadata endpoints that use the MEX protocol, add service endpoints to your service host that use the service contract named IMetadataExchange.WCF defines the interface that has this service contract name. WS-MetadataExchange endpoints, or MEX endpoints, can use one of the four default bindings exposed by the static factory methods on the class to match the default bindings used by WCF tools, such as Svcutil.exe. You can also configure MEX metadata endpoints using a custom binding. - - The uses a to export metadata for all service endpoints in your service. For more information about exporting metadata from a service, see [Exporting and Importing Metadata](exporting-and-importing-metadata.md). - - The augments your service host by adding a instance as an extension to your service host. The provides the implementation for the metadata publishing protocols. You can also use the to get the service's metadata at run time by accessing the property. - +Windows Communication Foundation (WCF) provides a rich infrastructure for exporting, publishing, retrieving, and importing service metadata. WCF services use metadata to describe how to interact with the service's endpoints so that tools, such as Svcutil.exe, can automatically generate client code for accessing the service. + + Most of the types that make up the WCF metadata infrastructure reside in the namespace. + + WCF uses the class to describe endpoints in a service. You can use WCF to generate metadata for service endpoints or import service metadata to generate instances. + + WCF represents the metadata for a service as an instance of the type, the structure of which is strongly tied to the metadata serialization format defined in WS-MetadataExchange. The type bundles the actual service metadata, such as Web Services Description Language (WSDL) documents, XML schema documents, or WS-Policy expressions, as a collection of instances. Each instance contains a specific metadata dialect and an identifier. A can contain the following items in its property: + +- Raw metadata. + +- A instance. + +- A instance. + + A instances point to another metadata exchange (MEX) endpoint and instances point to a metadata document using an HTTP URL. WCF supports using WSDL documents to describe service endpoints, service contracts, bindings, message exchange patterns, messages and fault messages implemented by a service. Data types used by the service are described in WSDL documents using XML schema. For more information, see [Schema Import and Export](schema-import-and-export.md). You can use WCF to export and import WSDL extensions for service behavior, contract behaviors, and binding elements that extend the functionality of a service. For more information, see [Exporting Custom Metadata for a WCF Extension](../extending/exporting-custom-metadata-for-a-wcf-extension.md). + +## Exporting Service Metadata + + In WCF, *metadata export* is the process of describing service endpoints and projecting them into a parallel, standardized representation that clients can use to understand how to use the service. To export metadata from instances, use an implementation of the abstract class. A implementation generates metadata that is encapsulated in a instance. + + The class provides a framework for generating policy expressions that describe the capabilities and requirements of an endpoint binding and its associated operations, messages, and faults. These policy expressions are captured in a instance. A implementation can then attach these policy expressions to the metadata it generates. + + The calls into each that implements the interface in the binding of a when generating a object for the implementation to use. You can export new policy assertions by implementing the interface on your custom implementations of the type. + + The type is the implementation of the abstract class included with WCF. The type generates WSDL metadata with attached policy expressions. + + To export custom WSDL metadata or WSDL extensions for endpoint behaviors, contract behaviors, or binding elements in a service endpoint, you can implement the interface. The looks at a instance for binding elements, operation behaviors, contract behaviors, and endpoint behaviors that implement the interface when generating the WSDL document. + +## Publishing Service Metadata + + WCF services publish metadata by exposing one or more metadata endpoints. Publishing service metadata makes service metadata available using standardized protocols, such as MEX and HTTP/GET requests. Metadata endpoints are similar to other service endpoints in that they have an address, a binding, and a contract. You can add metadata endpoints to a service host in configuration or in code. + + To publish metadata endpoints for a WCF service, you must first add an instance of the service behavior to the service. Adding a instance to your service augments your service with the ability to publish metadata by exposing one or more metadata endpoints. Once you add the service behavior you can then expose metadata endpoints that support the MEX protocol or metadata endpoints that respond to HTTP/GET requests. + + To add metadata endpoints that use the MEX protocol, add service endpoints to your service host that use the service contract named IMetadataExchange.WCF defines the interface that has this service contract name. WS-MetadataExchange endpoints, or MEX endpoints, can use one of the four default bindings exposed by the static factory methods on the class to match the default bindings used by WCF tools, such as Svcutil.exe. You can also configure MEX metadata endpoints using a custom binding. + + The uses a to export metadata for all service endpoints in your service. For more information about exporting metadata from a service, see [Exporting and Importing Metadata](exporting-and-importing-metadata.md). + + The augments your service host by adding a instance as an extension to your service host. The provides the implementation for the metadata publishing protocols. You can also use the to get the service's metadata at runtime by accessing the property. + > [!CAUTION] -> If you add a MEX endpoint in your application configuration file and then attempt to add the to your service host in code you get the following exception: +> If you add a MEX endpoint in your application configuration file and then attempt to add the to your service host in code you get the following exception: > -> System.InvalidOperationException: The contract name 'IMetadataExchange' could not be found in the list of contracts implemented by the service Service1. Add a ServiceMetadataBehavior to the configuration file or to the ServiceHost directly to enable support for this contract. +> System.InvalidOperationException: The contract name 'IMetadataExchange' could not be found in the list of contracts implemented by the service Service1. Add a ServiceMetadataBehavior to the configuration file or to the ServiceHost directly to enable support for this contract. > -> You can work around this issue by either adding the in the configuration file or adding both the endpoint and in code. +> You can work around this issue by either adding the in the configuration file or adding both the endpoint and in code. > -> For an example of adding in an application configuration file, see the [Getting Started](../samples/getting-started-sample.md). For an example of adding in code, see the [Self-Host](../samples/self-host.md) sample. +> For an example of adding in an application configuration file, see the [Getting Started](../samples/getting-started-sample.md). For an example of adding in code, see the [Self-Host](../samples/self-host.md) sample. > [!CAUTION] -> When publishing metadata for a service that exposes two different service contracts in which each contain an operation of the same name an exception is thrown. For example, if you have a service that exposes a service contract called ICarService that has an operation Get(Car c) and the same service exposes a service contract called IBookService that has an operation Get(Book b), an exception is thrown or an error message is displayed when generating the service's metadata. To work around this issue do one of the following: +> When publishing metadata for a service that exposes two different service contracts in which each contain an operation of the same name an exception is thrown. For example, if you have a service that exposes a service contract called ICarService that has an operation Get(Car c) and the same service exposes a service contract called IBookService that has an operation Get(Book b), an exception is thrown or an error message is displayed when generating the service's metadata. To work around this issue do one of the following: > > - Rename one of the operations. -> - Set the to a different name. -> - Set one of the operations' namespaces to a different namespace using the property. - -## Retrieving Service Metadata - - WCF can retrieve service metadata using standardized protocols such as WS-MetadataExchange and HTTP. Both of these protocols are supported by the type. You retrieve service metadata using the type by providing an address and an optional binding. The binding used by a instance can be one of the default bindings from the static class, a user-supplied binding, or a binding loaded from an endpoint configuration for the `IMetadataExchange` contract. The can also resolve HTTP URL references to metadata using the type. - - By default, a instance is tied to a single instance. You can change or replace the instance used by a by overriding the virtual method. Similarly, you can change or replace the instance used by a to make HTTP/GET requests by overriding the virtual method. - - You can retrieve service metadata using WS-MetadataExchange or HTTP/GET requests by using the Svcutil.exe tool and passing the **/target:metadata** switch and an address. Svcutil.exe downloads the metadata at the specified address and saves the files to disk. Svcutil.exe uses a instance internally and loads an MEX endpoint configuration (from the application configuration file) whose name matches the scheme of the address passed to Svcutil.exe, if one exists. Otherwise, Svcutil.exe defaults to using one of the bindings defined by the static factory type. - -## Importing Service Metadata - - In WCF, metadata import is the process of generating an abstract representation of a service or its component parts from its metadata. For example, WCF can import instances, instances or instances from a WSDL document for a service. To import service metadata in WCF, use an implementation of the abstract class. Types that derive from the class implement support for importing metadata formats that take advantage of the WS-Policy import logic in WCF. - - A implementation collects the policy expressions attached to the service metadata in a object. The then processes the policies as part of importing the metadata by calling the implementations of the interface in the property. - - You can add support for importing new policy assertions to a by adding your own implementation of the interface to the collection on a instance. Alternatively, you can register your policy import extension in your client application configuration file. - - The type is the implementation of the abstract class included with WCF. The type imports WSDL metadata with attached policies that are bundled in a object. - - You can add support for importing WSDL extensions by implementing the interface and then adding your implementation to the property on your instance. The can also load implementations of the interface registered in your client application configuration file. - -## Dynamic Bindings - - You can dynamically update the binding that you use to create a channel to a service endpoint in the event that the binding for the endpoint changes or you want to create a channel to an endpoint that uses the same contract but has a different binding. You can use the static class to retrieve and import metadata at run time for service endpoints that implement a specific contract. You can then use the imported objects to create a client or channel factory to the desired endpoint. - +> - Set the to a different name. +> - Set one of the operations' namespaces to a different namespace using the property. + +## Retrieving Service Metadata + + WCF can retrieve service metadata using standardized protocols such as WS-MetadataExchange and HTTP. Both of these protocols are supported by the type. You retrieve service metadata using the type by providing an address and an optional binding. The binding used by a instance can be one of the default bindings from the static class, a user-supplied binding, or a binding loaded from an endpoint configuration for the `IMetadataExchange` contract. The can also resolve HTTP URL references to metadata using the type. + + By default, a instance is tied to a single instance. You can change or replace the instance used by a by overriding the virtual method. Similarly, you can change or replace the instance used by a to make HTTP/GET requests by overriding the virtual method. + + You can retrieve service metadata using WS-MetadataExchange or HTTP/GET requests by using the Svcutil.exe tool and passing the **/target:metadata** switch and an address. Svcutil.exe downloads the metadata at the specified address and saves the files to disk. Svcutil.exe uses a instance internally and loads an MEX endpoint configuration (from the application configuration file) whose name matches the scheme of the address passed to Svcutil.exe, if one exists. Otherwise, Svcutil.exe defaults to using one of the bindings defined by the static factory type. + +## Importing Service Metadata + + In WCF, metadata import is the process of generating an abstract representation of a service or its component parts from its metadata. For example, WCF can import instances, instances or instances from a WSDL document for a service. To import service metadata in WCF, use an implementation of the abstract class. Types that derive from the class implement support for importing metadata formats that take advantage of the WS-Policy import logic in WCF. + + A implementation collects the policy expressions attached to the service metadata in a object. The then processes the policies as part of importing the metadata by calling the implementations of the interface in the property. + + You can add support for importing new policy assertions to a by adding your own implementation of the interface to the collection on a instance. Alternatively, you can register your policy import extension in your client application configuration file. + + The type is the implementation of the abstract class included with WCF. The type imports WSDL metadata with attached policies that are bundled in a object. + + You can add support for importing WSDL extensions by implementing the interface and then adding your implementation to the property on your instance. The can also load implementations of the interface registered in your client application configuration file. + +## Dynamic Bindings + + You can dynamically update the binding that you use to create a channel to a service endpoint in the event that the binding for the endpoint changes or you want to create a channel to an endpoint that uses the same contract but has a different binding. You can use the static class to retrieve and import metadata at runtime for service endpoints that implement a specific contract. You can then use the imported objects to create a client or channel factory to the desired endpoint. + ## See also - diff --git a/docs/framework/wcf/feature-details/middle-tier-client-applications.md b/docs/framework/wcf/feature-details/middle-tier-client-applications.md index e692adedad6fd..827534debf7e3 100644 --- a/docs/framework/wcf/feature-details/middle-tier-client-applications.md +++ b/docs/framework/wcf/feature-details/middle-tier-client-applications.md @@ -6,32 +6,32 @@ ms.assetid: f9714a64-d0ae-4a98-bca0-5d370fdbd631 --- # Middle-Tier Client Applications -This topic discusses various issues specific to middle-tier client applications that use Windows Communication Foundation (WCF). - -## Increasing Middle-Tier Client Performance - - Compared to previous communications technologies, such as Web services using ASP.NET, the creation of a WCF client instance can be more complex due to the rich feature set of WCF. For example, when a object is opened it can establish a secure session with the service, a procedure that increases the startup time for the client instance. Typically, these additional feature capabilities do not affect client applications greatly since the WCF client makes several calls, and then closes. - - Middle-tier client applications, however, can create many WCF client objects quickly and, as a result, experience increased initialization requirements. There are two main approaches to increasing the performance of middle-tier applications when calling services: - -- Cache the WCF client object and reuse it for subsequent calls where possible. - -- Create a object and then use that object to create new WCF client channel objects for each call. - - Issues to consider when using these approaches include: - -- If the service is maintaining a client-specific state by using a session, then you cannot reuse the middle-tier WCF client with multiple-client tier requests because the service's state is tied to that of the middle-tier client. - -- If the service must perform authentication on a per-client basis, you must create a new client for each incoming request on the middle tier instead of reusing the middle-tier WCF client (or WCF client channel object) because the client credentials of the middle tier cannot be modified after the WCF client (or ) has been created. - -- While channels and clients created by the channels are thread-safe, they might not support writing more than one message to the wire concurrently. If you are sending large messages, particularly if streaming, the send operation might block waiting for another send to complete. This causes two sorts of problems: a lack of concurrency and the possibility of deadlock if the flow of control returns to the service reusing the channel (that is, the shared client calls a service whose code path results in a callback to the shared client). This is true regardless of the type of WCF client you reuse. - -- You must handle faulted channels regardless of whether you share the channel. When channels are reused, however, a faulting channel can take down more than one pending request or send. - - For an example that demonstrates best practices for reusing a client for multiple requests, see [Data Binding in an ASP.NET Client](../samples/data-binding-in-an-aspnet-client.md). - - In addition, you can increase the startup performance for those clients that use data types that are serializable using the generate and compile serialization code for those data types at run time, which can result in slow start-up performance. The [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md) can improve start-up performance for these applications by generating the necessary serialization code from the compiled assemblies for the application. For more information, see [How to: Improve the Startup Time of WCF Client Applications using the XmlSerializer](startup-time-of-wcf-client-applications-using-the-xmlserializer.md). - +This topic discusses various issues specific to middle-tier client applications that use Windows Communication Foundation (WCF). + +## Increasing Middle-Tier Client Performance + + Compared to previous communications technologies, such as Web services using ASP.NET, the creation of a WCF client instance can be more complex due to the rich feature set of WCF. For example, when a object is opened it can establish a secure session with the service, a procedure that increases the startup time for the client instance. Typically, these additional feature capabilities do not affect client applications greatly since the WCF client makes several calls, and then closes. + + Middle-tier client applications, however, can create many WCF client objects quickly and, as a result, experience increased initialization requirements. There are two main approaches to increasing the performance of middle-tier applications when calling services: + +- Cache the WCF client object and reuse it for subsequent calls where possible. + +- Create a object and then use that object to create new WCF client channel objects for each call. + + Issues to consider when using these approaches include: + +- If the service is maintaining a client-specific state by using a session, then you cannot reuse the middle-tier WCF client with multiple-client tier requests because the service's state is tied to that of the middle-tier client. + +- If the service must perform authentication on a per-client basis, you must create a new client for each incoming request on the middle tier instead of reusing the middle-tier WCF client (or WCF client channel object) because the client credentials of the middle tier cannot be modified after the WCF client (or ) has been created. + +- While channels and clients created by the channels are thread-safe, they might not support writing more than one message to the wire concurrently. If you are sending large messages, particularly if streaming, the send operation might block waiting for another send to complete. This causes two sorts of problems: a lack of concurrency and the possibility of deadlock if the flow of control returns to the service reusing the channel (that is, the shared client calls a service whose code path results in a callback to the shared client). This is true regardless of the type of WCF client you reuse. + +- You must handle faulted channels regardless of whether you share the channel. When channels are reused, however, a faulting channel can take down more than one pending request or send. + + For an example that demonstrates best practices for reusing a client for multiple requests, see [Data Binding in an ASP.NET Client](../samples/data-binding-in-an-aspnet-client.md). + + In addition, you can increase the startup performance for those clients that use data types that are serializable using the generate and compile serialization code for those data types at runtime, which can result in slow start-up performance. The [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md) can improve start-up performance for these applications by generating the necessary serialization code from the compiled assemblies for the application. For more information, see [How to: Improve the Startup Time of WCF Client Applications using the XmlSerializer](startup-time-of-wcf-client-applications-using-the-xmlserializer.md). + ## See also - [Accessing Services Using a WCF Client](accessing-services-using-a-client.md) diff --git a/docs/framework/wcf/feature-details/partial-trust-feature-compatibility.md b/docs/framework/wcf/feature-details/partial-trust-feature-compatibility.md index f6e260b767fd8..2ab68d2924738 100644 --- a/docs/framework/wcf/feature-details/partial-trust-feature-compatibility.md +++ b/docs/framework/wcf/feature-details/partial-trust-feature-compatibility.md @@ -16,7 +16,7 @@ WCF supports a subset of features in applications running under either of the fo - Internet Zone permissions - Attempting to use WCF in partially-trusted applications with more restrictive permissions may result in security exceptions at run time. + Attempting to use WCF in partially-trusted applications with more restrictive permissions may result in security exceptions at runtime. ## Contracts @@ -56,7 +56,7 @@ WCF supports a subset of features in applications running under either of the fo ### Security - Partially-trusted applications can use WCF's transport-level security features for securing their communication. Message-level security is not supported. Configuring a binding to use message-level security results in an exception at run time. + Partially-trusted applications can use WCF's transport-level security features for securing their communication. Message-level security is not supported. Configuring a binding to use message-level security results in an exception at runtime. ### Unsupported Bindings @@ -168,7 +168,7 @@ WCF supports a subset of features in applications running under either of the fo - Performance counters - Use of WCF features that are not supported in a partial trust environment may result in exceptions at run time. + Use of WCF features that are not supported in a partial trust environment may result in exceptions at runtime. ## Unlisted Features diff --git a/docs/framework/wcf/feature-details/publishing-metadata.md b/docs/framework/wcf/feature-details/publishing-metadata.md index 8f8ae5acc4b37..a3756568fea60 100644 --- a/docs/framework/wcf/feature-details/publishing-metadata.md +++ b/docs/framework/wcf/feature-details/publishing-metadata.md @@ -2,48 +2,48 @@ title: "Publishing Metadata" description: Learn how WCF services publish metadata by publishing one or more metadata endpoints, making the metadata available using standard protocols. ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "metadata [WCF], publishing" ms.assetid: 3a56831a-cabc-45c0-bd02-12e2e9bd7313 --- # Publishing Metadata -Windows Communication Foundation (WCF) services publish metadata by publishing one or more metadata endpoints. Publishing service metadata makes the metadata available using standardized protocols, such as WS-MetadataExchange (MEX) and HTTP/GET requests. Metadata endpoints are similar to other service endpoints in that they have an address, a binding, and a contract, and they can be added to a service host through configuration or imperative code. - -## Publishing Metadata Endpoints - - To publish metadata endpoints for a WCF service, you first must add the service behavior to the service. Adding a instance allows your service to expose metadata endpoints. Once you add the service behavior, you can then expose metadata endpoints that support the MEX protocol or that respond to HTTP/GET requests. - - The uses a to export metadata for all service endpoints in your service. For more information about exporting metadata from a service, see [Exporting and Importing Metadata](exporting-and-importing-metadata.md). - - The adds a instance as an extension to your service host. The provides the implementation for the metadata publishing protocols. You can also use the to get the service's metadata at run time by accessing the property. - -### MEX Metadata Endpoints - - To add metadata endpoints that use the MEX protocol, add service endpoints to your service host that use the `IMetadataExchange` service contract. WCF includes an interface with this service contract name that you can use as part of the WCF programming model. WS-MetadataExchange endpoints, or MEX endpoints, can use one of the four default bindings that the static factory methods expose on the class to match the default bindings used by WCF tools such as Svcutil.exe. You can also configure MEX metadata endpoints using your own custom binding. - -### HTTP GET Metadata Endpoints - - To add a metadata endpoint to your service that responds to HTTP/GET requests, set the property on the to `true`. You can also configure a metadata endpoint that uses HTTPS by setting the property on the to `true`. - -## In This Section - - [How to: Publish Metadata for a Service Using a Configuration File](how-to-publish-metadata-for-a-service-using-a-configuration-file.md) - Demonstrates how to configure a WCF service to publish metadata so that clients can retrieve the metadata using a WS-MetadataExchange or an HTTP/GET request using the `?wsdl` query string. - - [How to: Publish Metadata for a Service Using Code](how-to-publish-metadata-for-a-service-using-code.md) - Demonstrates how to enable metadata publishing for a WCF service in code so that clients can retrieve the metadata using a WS-MetadataExchange or an HTTP/GET request using the `?wsdl` query string. - -## Reference - - - - - - - - - +Windows Communication Foundation (WCF) services publish metadata by publishing one or more metadata endpoints. Publishing service metadata makes the metadata available using standardized protocols, such as WS-MetadataExchange (MEX) and HTTP/GET requests. Metadata endpoints are similar to other service endpoints in that they have an address, a binding, and a contract, and they can be added to a service host through configuration or imperative code. + +## Publishing Metadata Endpoints + + To publish metadata endpoints for a WCF service, you first must add the service behavior to the service. Adding a instance allows your service to expose metadata endpoints. Once you add the service behavior, you can then expose metadata endpoints that support the MEX protocol or that respond to HTTP/GET requests. + + The uses a to export metadata for all service endpoints in your service. For more information about exporting metadata from a service, see [Exporting and Importing Metadata](exporting-and-importing-metadata.md). + + The adds a instance as an extension to your service host. The provides the implementation for the metadata publishing protocols. You can also use the to get the service's metadata at runtime by accessing the property. + +### MEX Metadata Endpoints + + To add metadata endpoints that use the MEX protocol, add service endpoints to your service host that use the `IMetadataExchange` service contract. WCF includes an interface with this service contract name that you can use as part of the WCF programming model. WS-MetadataExchange endpoints, or MEX endpoints, can use one of the four default bindings that the static factory methods expose on the class to match the default bindings used by WCF tools such as Svcutil.exe. You can also configure MEX metadata endpoints using your own custom binding. + +### HTTP GET Metadata Endpoints + + To add a metadata endpoint to your service that responds to HTTP/GET requests, set the property on the to `true`. You can also configure a metadata endpoint that uses HTTPS by setting the property on the to `true`. + +## In This Section + + [How to: Publish Metadata for a Service Using a Configuration File](how-to-publish-metadata-for-a-service-using-a-configuration-file.md) + Demonstrates how to configure a WCF service to publish metadata so that clients can retrieve the metadata using a WS-MetadataExchange or an HTTP/GET request using the `?wsdl` query string. + + [How to: Publish Metadata for a Service Using Code](how-to-publish-metadata-for-a-service-using-code.md) + Demonstrates how to enable metadata publishing for a WCF service in code so that clients can retrieve the metadata using a WS-MetadataExchange or an HTTP/GET request using the `?wsdl` query string. + +## Reference + + + + + + + + + ## See also - [Exporting and Importing Metadata](exporting-and-importing-metadata.md) diff --git a/docs/framework/wcf/feature-details/retrieving-metadata.md b/docs/framework/wcf/feature-details/retrieving-metadata.md index 2aec65fa750d9..94588310f489e 100644 --- a/docs/framework/wcf/feature-details/retrieving-metadata.md +++ b/docs/framework/wcf/feature-details/retrieving-metadata.md @@ -2,35 +2,35 @@ description: "Learn more about: Retrieving Metadata" title: "Retrieving Metadata" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "metadata [WCF], retrieving" ms.assetid: 18d8ba4c-af0f-4827-a50b-4202d767bacc --- # Retrieving Metadata -Metadata retrieval is the process of requesting and retrieving metadata from a metadata endpoint, such as a WS-MetadataExchange (MEX) metadata endpoint or an HTTP/GET metadata endpoint. - -## Retrieving Metadata from the Command Line Using Svcutil.exe - - You can retrieve service metadata using WS-MetadataExchange or HTTP/GET requests by using the [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md) tool and passing the `/target:metadata` switch and an address. Svcutil.exe downloads the metadata at the specified address and saves the file to disk. Svcutil.exe uses a instance internally and loads from configuration the endpoint configuration whose name matches the scheme of the address passed to Svcutil.exe as input. - -## Retrieving Metadata Programmatically Using the MetadataExchangeClient - - Windows Communication Foundation (WCF) can retrieve service metadata using standardized protocols such as WS-MetadataExchange and HTTP/GET requests. Both of these protocols are supported by the type. You retrieve service metadata using the type by providing an address for the metadata endpoint and an optional binding. The binding used by a instance can be one of the default bindings from the static class, a user-supplied binding, or a binding loaded from an endpoint configuration for the `IMetadataExchange` contract. The can also resolve HTTP URL references to metadata using the type. - - By default, a instance is tied to a single instance. You can change or replace the instance used by a by overriding the virtual method. Similarly, you can change or replace the instance used by a to make HTTP/GET requests by overriding the virtual method. - -## In This Section - - [How to: Use Svcutil.exe to Download Metadata Documents](how-to-use-svcutil-exe-to-download-metadata-documents.md) - Demonstrates how to use Svcutil.exe to download metadata documents. - - [How to: Use MetadataResolver to Obtain Binding Metadata Dynamically](how-to-use-metadataresolver-to-obtain-binding-metadata-dynamically.md) - Demonstrates how to use the to obtain binding metadata dynamically at run time. - - [How to: Use MetadataExchangeClient to Retrieve Metadata](how-to-use-metadataexchangeclient-to-retrieve-metadata.md) - Demonstrates how to use the class to download metadata files into a object that contains objects to write to files or for other uses. - +Metadata retrieval is the process of requesting and retrieving metadata from a metadata endpoint, such as a WS-MetadataExchange (MEX) metadata endpoint or an HTTP/GET metadata endpoint. + +## Retrieving Metadata from the Command Line Using Svcutil.exe + + You can retrieve service metadata using WS-MetadataExchange or HTTP/GET requests by using the [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md) tool and passing the `/target:metadata` switch and an address. Svcutil.exe downloads the metadata at the specified address and saves the file to disk. Svcutil.exe uses a instance internally and loads from configuration the endpoint configuration whose name matches the scheme of the address passed to Svcutil.exe as input. + +## Retrieving Metadata Programmatically Using the MetadataExchangeClient + + Windows Communication Foundation (WCF) can retrieve service metadata using standardized protocols such as WS-MetadataExchange and HTTP/GET requests. Both of these protocols are supported by the type. You retrieve service metadata using the type by providing an address for the metadata endpoint and an optional binding. The binding used by a instance can be one of the default bindings from the static class, a user-supplied binding, or a binding loaded from an endpoint configuration for the `IMetadataExchange` contract. The can also resolve HTTP URL references to metadata using the type. + + By default, a instance is tied to a single instance. You can change or replace the instance used by a by overriding the virtual method. Similarly, you can change or replace the instance used by a to make HTTP/GET requests by overriding the virtual method. + +## In This Section + + [How to: Use Svcutil.exe to Download Metadata Documents](how-to-use-svcutil-exe-to-download-metadata-documents.md) + Demonstrates how to use Svcutil.exe to download metadata documents. + + [How to: Use MetadataResolver to Obtain Binding Metadata Dynamically](how-to-use-metadataresolver-to-obtain-binding-metadata-dynamically.md) + Demonstrates how to use the to obtain binding metadata dynamically at runtime. + + [How to: Use MetadataExchangeClient to Retrieve Metadata](how-to-use-metadataexchangeclient-to-retrieve-metadata.md) + Demonstrates how to use the class to download metadata files into a object that contains objects to write to files or for other uses. + ## See also - diff --git a/docs/framework/wcf/feature-details/routing-introduction.md b/docs/framework/wcf/feature-details/routing-introduction.md index bd198c75aebab..f7cde9118a68d 100644 --- a/docs/framework/wcf/feature-details/routing-introduction.md +++ b/docs/framework/wcf/feature-details/routing-introduction.md @@ -13,9 +13,9 @@ This topic is intended for those new to the Routing Service and covers basic con The Routing Service is implemented as a WCF service that exposes one or more service endpoints that receive messages from client applications and route the messages to one or more destination endpoints. The service provides a , which is applied to the service endpoints exposed by the service. This behavior is used to configure various aspects of how the service operates. For ease of configuration when using a configuration file, the parameters are specified on the **RoutingBehavior**. In code-based scenarios, these parameters would be specified as part of a object, which can then be passed to a **RoutingBehavior**. -When starting, this behavior adds the , which is used to perform SOAP processing of messages, to the client endpoints. This allows the Routing Service to transmit messages to endpoints that require a different **MessageVersion** than the endpoint the message was received over. The **RoutingBehavior** also registers a service extension, the , which provides an accessibility point for modifying the Routing Service configuration at run time. +When starting, this behavior adds the , which is used to perform SOAP processing of messages, to the client endpoints. This allows the Routing Service to transmit messages to endpoints that require a different **MessageVersion** than the endpoint the message was received over. The **RoutingBehavior** also registers a service extension, the , which provides an accessibility point for modifying the Routing Service configuration at runtime. -The **RoutingConfiguration** class provides a consistent means of configuring and updating the configuration of the Routing Service. It contains parameters that act as the settings for the Routing Service and is used to configure the **RoutingBehavior** when the service starts, or is passed to the **RoutingExtension** to modify routing configuration at run time. +The **RoutingConfiguration** class provides a consistent means of configuring and updating the configuration of the Routing Service. It contains parameters that act as the settings for the Routing Service and is used to configure the **RoutingBehavior** when the service starts, or is passed to the **RoutingExtension** to modify routing configuration at runtime. The routing logic used to perform content-based routing of messages is defined by grouping multiple objects together into filter tables ( objects). Incoming messages are evaluated against the message filters contained in the filter table, and for each **MessageFilter** that matches the message, forwarded to a destination endpoint. The filter table that should be used to route messages is specified by using either the **RoutingBehavior** in configuration or through code by using the **RoutingConfiguration** object. @@ -248,9 +248,9 @@ rc.SoapProcessingEnabled = false; ### Dynamic Configuration -When you add additional client endpoints, or need to modify the filters that are used to route messages, you must have a way to update the configuration dynamically at run time to prevent interrupting the service to the endpoints currently receiving messages through the Routing Service. Modifying a configuration file or the code of the host application is not always sufficient, because either method requires recycling the application, which would lead to the potential loss of any messages currently in transit and the potential for downtime while waiting on the service to restart. +When you add additional client endpoints, or need to modify the filters that are used to route messages, you must have a way to update the configuration dynamically at runtime to prevent interrupting the service to the endpoints currently receiving messages through the Routing Service. Modifying a configuration file or the code of the host application is not always sufficient, because either method requires recycling the application, which would lead to the potential loss of any messages currently in transit and the potential for downtime while waiting on the service to restart. -You can only modify the **RoutingConfiguration** programmatically. While you can initially configure the service by using a configuration file, you can only modify the configuration at run time by constructing a new **RoutingConfiguration** and passing it as a parameter to the method exposed by the service extension. Any messages currently in transit continue to be routed using the previous configuration, while messages received after the call to **ApplyConfiguration** use the new configuration. The following example demonstrates creating an instance of the Routing Service and then subsequently modifying the configuration. +You can only modify the **RoutingConfiguration** programmatically. While you can initially configure the service by using a configuration file, you can only modify the configuration at runtime by constructing a new **RoutingConfiguration** and passing it as a parameter to the method exposed by the service extension. Any messages currently in transit continue to be routed using the previous configuration, while messages received after the call to **ApplyConfiguration** use the new configuration. The following example demonstrates creating an instance of the Routing Service and then subsequently modifying the configuration. ```csharp RoutingConfiguration routingConfig = new RoutingConfiguration(); diff --git a/docs/framework/wcf/feature-details/routing-scenarios.md b/docs/framework/wcf/feature-details/routing-scenarios.md index 4004efe513282..a2da33f231513 100644 --- a/docs/framework/wcf/feature-details/routing-scenarios.md +++ b/docs/framework/wcf/feature-details/routing-scenarios.md @@ -7,76 +7,76 @@ helpviewer_keywords: --- # Routing Scenarios -While the Routing Service is highly customizable, it can be a challenge to design efficient routing logic when creating a new configuration from scratch. However, there are several common scenarios that most Routing Service configurations follow. While these scenarios may not apply directly to your specific configuration, understanding how the Routing Service can be configured to handle these scenarios will aid you in understanding the Routing Service. - -## Common Scenarios - - The most basic use of the Routing Service is to aggregate multiple destination endpoints to reduce the number of endpoints exposed to the client applications, and then use message filters to route each message to the correct destination. Messages may be routed based on logical or physical processing requirements, such as a message type that must be processed by a specific service, or based on arbitrary business needs such as providing priority processing of messages from a specific source. The following table lists some of the common scenarios and when they are encountered: - -|Scenario|Use when| -|--------------|--------------| -|Service versioning|You need to support multiple versions of a service or may deploy an updated service in the future| -|Service data partitioning|You must partition a service across multiple hosts| -|Dynamic update|You must dynamically reconfigure routing logic at run time to handle changing service deployments| -|Multicast|You must send one message to multiple endpoints| -|Protocol bridging|You receive messages over one transport protocol, and the destination endpoint uses a different protocol| -|Error Handling|You need to provide resilience to network outages and communication failures| - +While the Routing Service is highly customizable, it can be a challenge to design efficient routing logic when creating a new configuration from scratch. However, there are several common scenarios that most Routing Service configurations follow. While these scenarios may not apply directly to your specific configuration, understanding how the Routing Service can be configured to handle these scenarios will aid you in understanding the Routing Service. + +## Common Scenarios + + The most basic use of the Routing Service is to aggregate multiple destination endpoints to reduce the number of endpoints exposed to the client applications, and then use message filters to route each message to the correct destination. Messages may be routed based on logical or physical processing requirements, such as a message type that must be processed by a specific service, or based on arbitrary business needs such as providing priority processing of messages from a specific source. The following table lists some of the common scenarios and when they are encountered: + +|Scenario|Use when| +|--------------|--------------| +|Service versioning|You need to support multiple versions of a service or may deploy an updated service in the future| +|Service data partitioning|You must partition a service across multiple hosts| +|Dynamic update|You must dynamically reconfigure routing logic at runtime to handle changing service deployments| +|Multicast|You must send one message to multiple endpoints| +|Protocol bridging|You receive messages over one transport protocol, and the destination endpoint uses a different protocol| +|Error Handling|You need to provide resilience to network outages and communication failures| + > [!NOTE] -> While many of the scenarios presented are specific to certain business needs or processing requirements, planning to support dynamic updates and utilizing error handling can often be considered as best practices as they allow you to modify routing logic at run time and recover from transient network and communication failures. - -### Service Versioning - - When introducing a new version of a service, you must often maintain the previous version until all clients have transitioned to the new service. This is especially critical if the service is a long-running process that takes days, weeks, or even months to complete. Usually this requires implementing a new endpoint address for the new service while maintaining the original endpoint for the previous version. - - By using the Routing Service, you can expose one endpoint to receive messages from client applications and then route each message to the correct service version based on the message content. The most basic implementation involves adding a custom header to the message that indicates the version of the service that the message is to be processed by. The Routing Service can use the XPathMessageFilter to inspect each message for the presence of the custom header and route the message to the appropriate destination endpoint. - +> While many of the scenarios presented are specific to certain business needs or processing requirements, planning to support dynamic updates and utilizing error handling can often be considered as best practices as they allow you to modify routing logic at runtime and recover from transient network and communication failures. + +### Service Versioning + + When introducing a new version of a service, you must often maintain the previous version until all clients have transitioned to the new service. This is especially critical if the service is a long-running process that takes days, weeks, or even months to complete. Usually this requires implementing a new endpoint address for the new service while maintaining the original endpoint for the previous version. + + By using the Routing Service, you can expose one endpoint to receive messages from client applications and then route each message to the correct service version based on the message content. The most basic implementation involves adding a custom header to the message that indicates the version of the service that the message is to be processed by. The Routing Service can use the XPathMessageFilter to inspect each message for the presence of the custom header and route the message to the appropriate destination endpoint. + For the steps used to create a service versioning configuration, see [How To: Service Versioning](how-to-service-versioning.md). - -### Service Data Partitioning - When designing a distributed environment, it is often desirable to spread processing load across multiple computers in order to provide high availability, decrease processing load on individual computers, or to provide dedicated resources for a specific subset of messages. While the Routing Service does not replace a dedicated load balancing solution, its ability to perform content based routing can be used to route otherwise similar messages to specific destinations. For example, you may have a requirement to process messages from a specific client separately from messages received from other clients. - - For the steps used to create a service data partitioning configuration, see [How To: Service Data Partitioning](how-to-service-data-partitioning.md). - -### Dynamic Routing +### Service Data Partitioning + + When designing a distributed environment, it is often desirable to spread processing load across multiple computers in order to provide high availability, decrease processing load on individual computers, or to provide dedicated resources for a specific subset of messages. While the Routing Service does not replace a dedicated load balancing solution, its ability to perform content based routing can be used to route otherwise similar messages to specific destinations. For example, you may have a requirement to process messages from a specific client separately from messages received from other clients. + + For the steps used to create a service data partitioning configuration, see [How To: Service Data Partitioning](how-to-service-data-partitioning.md). + +### Dynamic Routing + + Often it is desirable to modify the routing configuration to satisfy changing business needs, such as adding a route to a newer version of a service, changing routing criteria, or changing the destination endpoint a specific message that the filter routes to. The Routing Service allows you to do this through the , which allows you to provide a new RoutingConfiguration during runtime. The new configuration takes effect immediately, but only affects any new sessions processed by the Routing Service. - Often it is desirable to modify the routing configuration to satisfy changing business needs, such as adding a route to a newer version of a service, changing routing criteria, or changing the destination endpoint a specific message that the filter routes to. The Routing Service allows you to do this through the , which allows you to provide a new RoutingConfiguration during run time. The new configuration takes effect immediately, but only affects any new sessions processed by the Routing Service. - For the steps used to implement dynamic routing, see [How To: Dynamic Update](how-to-dynamic-update.md). - -### Multicast - - When routing messages, usually you routing each message to one specific destination endpoint. However, you may occasionally need to route a copy of the message to multiple destination endpoints. To perform multicast routing, the following conditions must be true: - -- The channel shape must not be request-reply (though it may be one-way or duplex), because request-reply mandates that only one reply can be received by the client application in response to the request. - -- Multiple filters must return **true** when evaluating the message. - - If these conditions are met, each destination endpoint that is associated with a filter that returns true will receive a copy of the message. - -### Protocol Bridging + +### Multicast + + When routing messages, usually you routing each message to one specific destination endpoint. However, you may occasionally need to route a copy of the message to multiple destination endpoints. To perform multicast routing, the following conditions must be true: + +- The channel shape must not be request-reply (though it may be one-way or duplex), because request-reply mandates that only one reply can be received by the client application in response to the request. + +- Multiple filters must return **true** when evaluating the message. + + If these conditions are met, each destination endpoint that is associated with a filter that returns true will receive a copy of the message. + +### Protocol Bridging When routing messages between dissimilar SOAP protocols, the Routing Service uses WCF APIs to convert the message from one protocol to the other. This occurs automatically when the service endpoint(s) exposed by the Routing Service use a different protocol than the client endpoint(s) that messages are routed to. It is possible to disable this behavior if the protocols in use are not standard; however, you must then provide your own bridging code. - -### Error Handling - In a distributed environment, it is not uncommon to encounter transient network or communication failures. Without an intermediary service such as the Routing Service, the burden of handling such failures falls on the client application. If the client application does not include specific logic to retry in the event of network or communication failures and knowledge of alternate locations, the user may encounter scenarios where a message must be submitted multiple times before it is successfully processed by the destination service. This can lead to customer dissatisfaction with the application, as it may be perceived as unreliable. - - The Routing Service attempts to remedy this scenario by providing robust error handling capabilities for messages that encounter network or communication-related failures. By creating a list of possible destination endpoints and associating this list with each message filter, you remove the single point of failure incurred by having only one possible destination. In the event of a failure, the Routing Service will attempt to deliver the message to the next endpoint in the list until the message has been delivered, a non-communication failure occurs, or all endpoints have been exhausted. - +### Error Handling + + In a distributed environment, it is not uncommon to encounter transient network or communication failures. Without an intermediary service such as the Routing Service, the burden of handling such failures falls on the client application. If the client application does not include specific logic to retry in the event of network or communication failures and knowledge of alternate locations, the user may encounter scenarios where a message must be submitted multiple times before it is successfully processed by the destination service. This can lead to customer dissatisfaction with the application, as it may be perceived as unreliable. + + The Routing Service attempts to remedy this scenario by providing robust error handling capabilities for messages that encounter network or communication-related failures. By creating a list of possible destination endpoints and associating this list with each message filter, you remove the single point of failure incurred by having only one possible destination. In the event of a failure, the Routing Service will attempt to deliver the message to the next endpoint in the list until the message has been delivered, a non-communication failure occurs, or all endpoints have been exhausted. + For the steps used to configure error handling, see [How To: Error Handling](how-to-error-handling.md). - -### In This Section - - [How To: Service Versioning](how-to-service-versioning.md) - - [How To: Service Data Partitioning](how-to-service-data-partitioning.md) - - [How To: Dynamic Update](how-to-dynamic-update.md) - - [How To: Error Handling](how-to-error-handling.md) - + +### In This Section + + [How To: Service Versioning](how-to-service-versioning.md) + + [How To: Service Data Partitioning](how-to-service-data-partitioning.md) + + [How To: Dynamic Update](how-to-dynamic-update.md) + + [How To: Error Handling](how-to-error-handling.md) + ## See also - [Routing Introduction](routing-introduction.md) diff --git a/docs/framework/wcf/feature-details/routing-service.md b/docs/framework/wcf/feature-details/routing-service.md index 99cc3f4dcce0e..71d14d8a77531 100644 --- a/docs/framework/wcf/feature-details/routing-service.md +++ b/docs/framework/wcf/feature-details/routing-service.md @@ -38,7 +38,7 @@ Content-based routing is the ability to route a message based on one or more val To implement content-based routing, the Routing Service relies on implementations that are used to match specific values within the messages to be routed. If a **MessageFilter** matches a message, the message is routed to the destination endpoint associated with the **MessageFilter**. Message filters are grouped together into filter tables () to construct complex routing logic. For example, a filter table might contain five mutually exclusive message filters that cause messages to be routed to only one of the five destination endpoints. -The Routing Service allows you to configure the logic that is used to perform content-based routing, as well as dynamically update the routing logic at run time. +The Routing Service allows you to configure the logic that is used to perform content-based routing, as well as dynamically update the routing logic at runtime. Through the grouping of message filters into filter tables, routing logic can be constructed that allows you to handle multiple routing scenarios such as: @@ -63,7 +63,7 @@ When providing a service for multiple clients, you may have a service level agre ## Dynamic Configuration -To support mission-critical systems, where messages must be processed without any service interruptions, it is vital that you be able to modify the configuration of components within the system at run time. To support this need, the Routing Service provides an implementation, the , which allows dynamic updating of the Routing Service configuration at run time. +To support mission-critical systems, where messages must be processed without any service interruptions, it is vital that you be able to modify the configuration of components within the system at runtime. To support this need, the Routing Service provides an implementation, the , which allows dynamic updating of the Routing Service configuration at runtime. For more information about dynamic configuration of the Routing Service, see [Routing Introduction](routing-introduction.md). diff --git a/docs/framework/wcf/feature-details/routing.md b/docs/framework/wcf/feature-details/routing.md index 5eac3cf30c4cc..cf365582a91da 100644 --- a/docs/framework/wcf/feature-details/routing.md +++ b/docs/framework/wcf/feature-details/routing.md @@ -2,7 +2,7 @@ description: "Learn more about: Routing" title: "Routing" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "routing [WCF]" - "WCF [WCF], routing" - "Windows communication Foundation [WCF], routing" @@ -10,24 +10,24 @@ ms.assetid: bd56516c-420d-4c4e-97f9-f72d28d149a9 --- # Routing -The topics in this section cover the Routing Service. The Routing Service is a generic configurable SOAP intermediary that lets you configure content-based routing, set up protocol bridging, handle communication errors, and dynamically update routing logic at run time. - -## In This Section - - [Routing Service](routing-service.md) - Provides an overview of the features of the Routing Service. - - [Routing Service](routing-service.md) - Describes the features of the Routing Service. - - [Routing Introduction](routing-introduction.md) - Discusses configuration of the Routing Service. - - [Routing Contracts](routing-contracts.md) - Describes the message patterns that the Routing Service can process. - - [Message Filters](message-filters.md) - Discusses how message filters are used for content-based routing. - - [Routing Scenarios](routing-scenarios.md) +The topics in this section cover the Routing Service. The Routing Service is a generic configurable SOAP intermediary that lets you configure content-based routing, set up protocol bridging, handle communication errors, and dynamically update routing logic at runtime. + +## In This Section + + [Routing Service](routing-service.md) + Provides an overview of the features of the Routing Service. + + [Routing Service](routing-service.md) + Describes the features of the Routing Service. + + [Routing Introduction](routing-introduction.md) + Discusses configuration of the Routing Service. + + [Routing Contracts](routing-contracts.md) + Describes the message patterns that the Routing Service can process. + + [Message Filters](message-filters.md) + Discusses how message filters are used for content-based routing. + + [Routing Scenarios](routing-scenarios.md) Describes common routing scenarios. diff --git a/docs/framework/wcf/feature-details/security-behaviors-in-wcf.md b/docs/framework/wcf/feature-details/security-behaviors-in-wcf.md index 23d0ea9750a6e..d344fd674b6e6 100644 --- a/docs/framework/wcf/feature-details/security-behaviors-in-wcf.md +++ b/docs/framework/wcf/feature-details/security-behaviors-in-wcf.md @@ -6,7 +6,7 @@ ms.custom: sfi-ropc-nochange --- # Security Behaviors in WCF -In Windows Communication Foundation (WCF), behaviors modify run-time behavior at the service level or at the endpoint level. (For more information about behaviors in general, see [Specifying Service Run-Time Behavior](../specifying-service-run-time-behavior.md).) *Security behaviors* allow control over credentials, authentication, authorization, and auditing logs. You can use behaviors either by programming or through configuration. +In Windows Communication Foundation (WCF), behaviors modify runtime behavior at the service level or at the endpoint level. (For more information about behaviors in general, see [Specifying Service Run-Time Behavior](../specifying-service-run-time-behavior.md).) *Security behaviors* allow control over credentials, authentication, authorization, and auditing logs. You can use behaviors either by programming or through configuration. This article focuses on configuring the following behaviors related to security functions: diff --git a/docs/framework/wcf/feature-details/security-considerations-for-data.md b/docs/framework/wcf/feature-details/security-considerations-for-data.md index 9c1a52cec2712..44c96d57d4d2e 100644 --- a/docs/framework/wcf/feature-details/security-considerations-for-data.md +++ b/docs/framework/wcf/feature-details/security-considerations-for-data.md @@ -300,9 +300,9 @@ Another security concern with the `NetDataContractSerializer` is a denial of ser The security model is similar to that of the . A few threats, however, are unique to the . -The generates *serialization assemblies* at run time that contain code that actually serializes and deserializes; these assemblies are created in a temporary files directory. If some other process or user has access rights to that directory, they may overwrite the serialization/deserialization code with arbitrary code. The then runs this code using its security context, instead of the serialization/deserialization code. Make sure the permissions are set correctly on the temporary files directory to prevent this from happening. +The generates *serialization assemblies* at runtime that contain code that actually serializes and deserializes; these assemblies are created in a temporary files directory. If some other process or user has access rights to that directory, they may overwrite the serialization/deserialization code with arbitrary code. The then runs this code using its security context, instead of the serialization/deserialization code. Make sure the permissions are set correctly on the temporary files directory to prevent this from happening. -The also has a mode in which it uses pre-generated serialization assemblies instead of generating them at run time. This mode is triggered whenever the can find a suitable serialization assembly. The checks whether or not the serialization assembly was signed by the same key that was used to sign the assembly that contains the types being serialized. This offers protection from malicious assemblies being disguised as serialization assemblies. However, if the assembly that contains your serializable types is not signed, the cannot perform this check and uses any assembly with the correct name. This makes running malicious code possible. Always sign the assemblies that contain your serializable types, or tightly control access to your application’s directory and the global assembly cache to prevent the introduction of malicious assemblies. +The also has a mode in which it uses pre-generated serialization assemblies instead of generating them at runtime. This mode is triggered whenever the can find a suitable serialization assembly. The checks whether or not the serialization assembly was signed by the same key that was used to sign the assembly that contains the types being serialized. This offers protection from malicious assemblies being disguised as serialization assemblies. However, if the assembly that contains your serializable types is not signed, the cannot perform this check and uses any assembly with the correct name. This makes running malicious code possible. Always sign the assemblies that contain your serializable types, or tightly control access to your application’s directory and the global assembly cache to prevent the introduction of malicious assemblies. The can be subject to a denial of service attack. The does not have a `MaxItemsInObjectGraph` quota (as is available on the ). Thus, it deserializes an arbitrary amount of objects, limited only by the message size. @@ -358,7 +358,7 @@ A few other concerns regarding object state management are worth mentioning: ## Schema Import -Normally, the process of importing schema to generate types happens only at design time, for example, when using the [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md) on a Web service to generate a client class. However, in more advanced scenarios, you may process schema at run time. Be aware that doing so can expose you to denial-of-service risks. Some schema may take a long time to be imported. Never use the schema import component in such scenarios if schemas are possibly coming from an untrusted source. +Normally, the process of importing schema to generate types happens only at design time, for example, when using the [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md) on a Web service to generate a client class. However, in more advanced scenarios, you may process schema at runtime. Be aware that doing so can expose you to denial-of-service risks. Some schema may take a long time to be imported. Never use the schema import component in such scenarios if schemas are possibly coming from an untrusted source. ## Threats Specific to ASP.NET AJAX Integration diff --git a/docs/framework/wcf/feature-details/security-considerations-with-metadata.md b/docs/framework/wcf/feature-details/security-considerations-with-metadata.md index d5cdf2c37b382..21352ddcba6a7 100644 --- a/docs/framework/wcf/feature-details/security-considerations-with-metadata.md +++ b/docs/framework/wcf/feature-details/security-considerations-with-metadata.md @@ -6,40 +6,40 @@ ms.assetid: e78ef8ab-4f63-4656-ab93-b1deab2666d5 --- # Security Considerations with Metadata -When using the metadata features in Windows Communication Foundation (WCF), consider the security implications of publishing, retrieving, and using service metadata. - -## When to Publish Metadata - - WCF services do not publish metadata by default. To publish metadata for a WCF service you must explicitly enable metadata publishing by adding metadata endpoints to your service (see [Publishing Metadata](publishing-metadata.md)). Leaving metadata publishing disabled reduces the attack surface for your service and lowers the risk of unintentional information disclosure. Not all services must publish metadata. If you do not have to publish metadata, consider leaving it turned off. Note that you can still generate metadata and client code directly from your service assemblies using the [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md). For more information about using Svcutil.exe to export metadata, see [How to: Use Svcutil.exe to Export Metadata from Compiled Service Code](how-to-use-svcutil-exe-to-export-metadata-from-compiled-service-code.md). - -## Publishing Metadata Using a Secure Binding - - The default metadata bindings that WCF provides are not secure and they allow anonymous access to the metadata. The service metadata that a WCF service publishes contains a detailed description about the service and may intentionally or unintentionally contain sensitive information. For example, service metadata may contain information about infrastructure operations that was not intended to be broadcast publicly. To protect service metadata from unauthorized access, you can use a secure binding for your metadata endpoint. Metadata endpoints respond to HTTP/GET requests that can use Secure Sockets Layer (SSL) to secure the metadata. For more information, see [How to: Secure Metadata Endpoints](how-to-secure-metadata-endpoints.md). - - Securing your metadata endpoints also provides a way for requesters to securely retrieve service metadata without the risk of tampering or spoofing. - -## Using Only Trusted Metadata - - You can use service metadata to automatically construct the run-time components required to call the service. You can also use metadata at design time to develop a client application or at run time to dynamically update the binding a client uses to call a service. - - Service metadata can be tampered with or spoofed when retrieved in an insecure manner. Tampered metadata can redirect your client to a malicious service, contain compromised security settings, or contain malicious XML structures. Metadata documents can be large and are frequently saved to the file system. To protect against tampering and spoofing, use a secure binding to request service metadata when one is available. - -## Using Safe Techniques for Processing Metadata - - Service metadata is frequently retrieved from a service over a network using standardized protocols such as WS-MetadataExchange (MEX). Many metadata formats include referencing mechanisms for pointing to additional metadata. The type automatically processes references for you in Web Services Description Language (WSDL) documents, XML Schema, and MEX documents. The size of the object created from the retrieved metadata is directly proportional to the value for the instance that is used and the `MaxReceivedMessageSize` value for the binding being used by that instance. Set these quotas to appropriate values as dictated by your scenario. - - In WCF, service metadata is processed as XML. When processing XML documents, applications should protect themselves against malicious XML structures. Use the with appropriate quotas when processing XML and also set the property to . - - The metadata system in WCF is extensible and metadata extensions can be registered in your application configuration file (see [Extending the Metadata System](../extending/extending-the-metadata-system.md)). Metadata extensions can run arbitrary code, so you should protect your application configuration file with appropriate access control lists (ACLs) and register only trusted metadata extension implementations. - -## Validating Generated Clients - - When generating client code from metadata retrieved from a source that is not trusted, validate the generated client code to ensure that the generated client conforms to your client applications security policies. You can use a validating behavior to check settings on your client binding or visually inspect code generated by tools. For an example of how to implement a client that validates behaviors, see [Client Validation](../samples/client-validation.md). - -## Protecting Application Configuration Files - - A service's application configuration file may control how and if metadata is published. It is a good idea to protect the application configuration file with appropriate access control lists (ACLs) to ensure an attacker cannot modify such settings. - +When using the metadata features in Windows Communication Foundation (WCF), consider the security implications of publishing, retrieving, and using service metadata. + +## When to Publish Metadata + + WCF services do not publish metadata by default. To publish metadata for a WCF service you must explicitly enable metadata publishing by adding metadata endpoints to your service (see [Publishing Metadata](publishing-metadata.md)). Leaving metadata publishing disabled reduces the attack surface for your service and lowers the risk of unintentional information disclosure. Not all services must publish metadata. If you do not have to publish metadata, consider leaving it turned off. Note that you can still generate metadata and client code directly from your service assemblies using the [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md). For more information about using Svcutil.exe to export metadata, see [How to: Use Svcutil.exe to Export Metadata from Compiled Service Code](how-to-use-svcutil-exe-to-export-metadata-from-compiled-service-code.md). + +## Publishing Metadata Using a Secure Binding + + The default metadata bindings that WCF provides are not secure and they allow anonymous access to the metadata. The service metadata that a WCF service publishes contains a detailed description about the service and may intentionally or unintentionally contain sensitive information. For example, service metadata may contain information about infrastructure operations that was not intended to be broadcast publicly. To protect service metadata from unauthorized access, you can use a secure binding for your metadata endpoint. Metadata endpoints respond to HTTP/GET requests that can use Secure Sockets Layer (SSL) to secure the metadata. For more information, see [How to: Secure Metadata Endpoints](how-to-secure-metadata-endpoints.md). + + Securing your metadata endpoints also provides a way for requesters to securely retrieve service metadata without the risk of tampering or spoofing. + +## Using Only Trusted Metadata + + You can use service metadata to automatically construct the runtime components required to call the service. You can also use metadata at design time to develop a client application or at runtime to dynamically update the binding a client uses to call a service. + + Service metadata can be tampered with or spoofed when retrieved in an insecure manner. Tampered metadata can redirect your client to a malicious service, contain compromised security settings, or contain malicious XML structures. Metadata documents can be large and are frequently saved to the file system. To protect against tampering and spoofing, use a secure binding to request service metadata when one is available. + +## Using Safe Techniques for Processing Metadata + + Service metadata is frequently retrieved from a service over a network using standardized protocols such as WS-MetadataExchange (MEX). Many metadata formats include referencing mechanisms for pointing to additional metadata. The type automatically processes references for you in Web Services Description Language (WSDL) documents, XML Schema, and MEX documents. The size of the object created from the retrieved metadata is directly proportional to the value for the instance that is used and the `MaxReceivedMessageSize` value for the binding being used by that instance. Set these quotas to appropriate values as dictated by your scenario. + + In WCF, service metadata is processed as XML. When processing XML documents, applications should protect themselves against malicious XML structures. Use the with appropriate quotas when processing XML and also set the property to . + + The metadata system in WCF is extensible and metadata extensions can be registered in your application configuration file (see [Extending the Metadata System](../extending/extending-the-metadata-system.md)). Metadata extensions can run arbitrary code, so you should protect your application configuration file with appropriate access control lists (ACLs) and register only trusted metadata extension implementations. + +## Validating Generated Clients + + When generating client code from metadata retrieved from a source that is not trusted, validate the generated client code to ensure that the generated client conforms to your client applications security policies. You can use a validating behavior to check settings on your client binding or visually inspect code generated by tools. For an example of how to implement a client that validates behaviors, see [Client Validation](../samples/client-validation.md). + +## Protecting Application Configuration Files + + A service's application configuration file may control how and if metadata is published. It is a good idea to protect the application configuration file with appropriate access control lists (ACLs) to ensure an attacker cannot modify such settings. + ## See also - [How to: Secure Metadata Endpoints](how-to-secure-metadata-endpoints.md) diff --git a/docs/framework/wcf/feature-details/securitybindingelement-authentication-modes.md b/docs/framework/wcf/feature-details/securitybindingelement-authentication-modes.md index 88afef52bb1f6..eef351b18fa14 100644 --- a/docs/framework/wcf/feature-details/securitybindingelement-authentication-modes.md +++ b/docs/framework/wcf/feature-details/securitybindingelement-authentication-modes.md @@ -56,7 +56,7 @@ Windows Communication Foundation (WCF) provides several modes by which clients a ### AnonymousForSslNegotiated - With this authentication mode, the client is anonymous and the service is authenticated using an X.509 certificate that is negotiated at run time. The security binding element is a returned by the method when a value of `false` is passed for the first parameter. Alternatively, set the `authenticationMode` attribute to `AnonymousForSslNegotiated`. + With this authentication mode, the client is anonymous and the service is authenticated using an X.509 certificate that is negotiated at runtime. The security binding element is a returned by the method when a value of `false` is passed for the first parameter. Alternatively, set the `authenticationMode` attribute to `AnonymousForSslNegotiated`. ### CertificateOverTransport diff --git a/docs/framework/wcf/feature-details/service-identity-and-authentication.md b/docs/framework/wcf/feature-details/service-identity-and-authentication.md index 0ce521a840120..dec1f860e365d 100644 --- a/docs/framework/wcf/feature-details/service-identity-and-authentication.md +++ b/docs/framework/wcf/feature-details/service-identity-and-authentication.md @@ -10,103 +10,103 @@ helpviewer_keywords: --- # Service Identity and Authentication -A service's *endpoint identity* is a value generated from the service Web Services Description Language (WSDL). This value, propagated to any client, is used to authenticate the service. After the client initiates a communication to an endpoint and the service authenticates itself to the client, the client compares the endpoint identity value with the actual value the endpoint authentication process returned. If they match, the client is assured it has contacted the expected service endpoint. This functions as a protection against *phishing* by preventing a client from being redirected to an endpoint hosted by a malicious service. - - For a sample application that demonstrates identity setting, see [Service Identity Sample](../samples/service-identity-sample.md). For more information about endpoints and endpoint addresses, see [Addresses](endpoint-addresses.md). - +A service's *endpoint identity* is a value generated from the service Web Services Description Language (WSDL). This value, propagated to any client, is used to authenticate the service. After the client initiates a communication to an endpoint and the service authenticates itself to the client, the client compares the endpoint identity value with the actual value the endpoint authentication process returned. If they match, the client is assured it has contacted the expected service endpoint. This functions as a protection against *phishing* by preventing a client from being redirected to an endpoint hosted by a malicious service. + + For a sample application that demonstrates identity setting, see [Service Identity Sample](../samples/service-identity-sample.md). For more information about endpoints and endpoint addresses, see [Addresses](endpoint-addresses.md). + > [!NOTE] -> When you use NT LanMan (NTLM) for authentication, the service identity is not checked because, under NTLM, the client is unable to authenticate the server. NTLM is used when computers are part of a Windows workgroup, or when running an older version of Windows that does not support Kerberos authentication. - - When the client initiates a secure channel to send a message to a service over it, the Windows Communication Foundation (WCF) infrastructure authenticates the service, and only sends the message if the service identity matches the identity specified in the endpoint address the client uses. - - Identity processing consists of the following stages: - -- At design time, the client developer determines the service's identity from the endpoint's metadata (exposed through WSDL). - -- At run time, the client application checks the claims of the service's security credentials before sending any messages to the service. - - Identity processing on the client is analogous to client authentication on the service. A secure service does not execute code until the client's credentials have been authenticated. Likewise, the client does not send messages to the service until the service's credentials have been authenticated based on what is known in advance from the service's metadata. - - The property of the class represents the identity of the service called by the client. The service publishes the in its metadata. When the client developer runs the [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md) against the service endpoint, the generated configuration contains the value of the service's property. The WCF infrastructure (if configured with security) verifies that the service possesses the identity specified. - +> When you use NT LanMan (NTLM) for authentication, the service identity is not checked because, under NTLM, the client is unable to authenticate the server. NTLM is used when computers are part of a Windows workgroup, or when running an older version of Windows that does not support Kerberos authentication. + + When the client initiates a secure channel to send a message to a service over it, the Windows Communication Foundation (WCF) infrastructure authenticates the service, and only sends the message if the service identity matches the identity specified in the endpoint address the client uses. + + Identity processing consists of the following stages: + +- At design time, the client developer determines the service's identity from the endpoint's metadata (exposed through WSDL). + +- At runtime, the client application checks the claims of the service's security credentials before sending any messages to the service. + + Identity processing on the client is analogous to client authentication on the service. A secure service does not execute code until the client's credentials have been authenticated. Likewise, the client does not send messages to the service until the service's credentials have been authenticated based on what is known in advance from the service's metadata. + + The property of the class represents the identity of the service called by the client. The service publishes the in its metadata. When the client developer runs the [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md) against the service endpoint, the generated configuration contains the value of the service's property. The WCF infrastructure (if configured with security) verifies that the service possesses the identity specified. + > [!IMPORTANT] -> The metadata contains the expected identity of the service, so it is recommended that you expose the service metadata through secure means, for example, by creating an HTTPS endpoint for the service. For more information, see [How to: Secure Metadata Endpoints](how-to-secure-metadata-endpoints.md). - -## Identity Types - - A service can provide six types of identities. Each identity type corresponds to an element that can be contained inside the `` element in configuration. The type used depends on the scenario and the service's security requirements. The following table describes each identity type. - -|Identity type|Description|Typical scenario| -|-------------------|-----------------|----------------------| -|Domain Name System (DNS)|Use this element with X.509 certificates or Windows accounts. It compares the DNS name specified in the credential with the value specified in this element.|A DNS check enables you to use certificates with DNS or subject names. If a certificate is reissued with the same DNS or subject name, then the identity check is still valid. When a certificate is reissued, it gets a new RSA key but retains the same DNS or subject name. This means that clients do not have to update their identity information about the service.| -|Certificate. The default when `ClientCredentialType` is set to Certificate.|This element specifies a Base64-encoded X.509 certificate value to compare with the client.

Also use this element when using a CardSpace as a credential to authenticate the service.|This element restricts authentication to a single certificate based upon its thumbprint value. This enables stricter authentication because thumbprint values are unique. This comes with one caveat: If the certificate is reissued with the same Subject name, it also has a new Thumbprint. Therefore, clients are not able to validate the service unless the new thumbprint is known. For more information about finding a certificate's thumbprint, see [How to: Retrieve the Thumbprint of a Certificate](how-to-retrieve-the-thumbprint-of-a-certificate.md).| -|Certificate Reference|Identical to the Certificate option described previously. However, this element enables you to specify a certificate name and store location from which to retrieve the certificate.|Same as the Certificate scenario described previously.

The benefit is that the certificate store location can change.| -|RSA|This element specifies an RSA key value to compare with the client. This is similar to the certificate option but rather than using the certificate's thumbprint, the certificate's RSA key is used instead.|An RSA check enables you to specifically restrict authentication to a single certificate based upon its RSA key. This enables stricter authentication of a specific RSA key at the expense of the service, which no longer works with existing clients if the RSA key value changes.| -|User principal name (UPN). The default when the `ClientCredentialType` is set to Windows and the service process is not running under one of the system accounts.|This element specifies the UPN that the service is running under. See the Kerberos Protocol and Identity section of [Overriding the Identity of a Service for Authentication](../extending/overriding-the-identity-of-a-service-for-authentication.md).|This ensures that the service is running under a specific Windows user account. The user account can be either the current logged-on user or the service running under a particular user account.

This setting takes advantage of Windows Kerberos security if the service is running under a domain account within an Active Directory environment.| -|Service principal name (SPN). The default when the `ClientCredentialType` is set to Windows and the service process is running under one of the system accounts—LocalService, LocalSystem, or NetworkService.|This element specifies the SPN associated with the service's account. See the Kerberos Protocol and Identity section of [Overriding the Identity of a Service for Authentication](../extending/overriding-the-identity-of-a-service-for-authentication.md).|This ensures that the SPN and the specific Windows account associated with the SPN identify the service.

You can use the Setspn.exe tool to associate a machine account for the service's user account.

This setting takes advantage of Windows Kerberos security if the service is running under one of the system accounts or under a domain account that has an associated SPN name with it and the computer is a member of a domain within an Active Directory environment.| - -## Specifying Identity at the Service - - Typically, you do not have to set the identity on a service because the selection of a client credential type dictates the type of identity exposed in the service metadata. For more information about how to override or specify service identity, see [Overriding the Identity of a Service for Authentication](../extending/overriding-the-identity-of-a-service-for-authentication.md). - -## Using the \ Element in Configuration - - If you change the client credential type in the binding previously shown to `Certificate`, then the generated WSDL contains a Base64 serialized X.509 certificate for the identity value as shown in the following code. This is the default for all client credential types other than Windows. - - You can change the value of the default service identity or change the type of the identity by using the `` element in configuration or by setting the identity in code. The following configuration code sets a domain name system (DNS) identity with the value `contoso.com`. - -## Setting Identity Programmatically - - Your service does not have to explicitly specify an identity, because WCF automatically determines it. However, WCF allows you to specify an identity on an endpoint, if required. The following code adds a new service endpoint with a specific DNS identity. - +> The metadata contains the expected identity of the service, so it is recommended that you expose the service metadata through secure means, for example, by creating an HTTPS endpoint for the service. For more information, see [How to: Secure Metadata Endpoints](how-to-secure-metadata-endpoints.md). + +## Identity Types + + A service can provide six types of identities. Each identity type corresponds to an element that can be contained inside the `` element in configuration. The type used depends on the scenario and the service's security requirements. The following table describes each identity type. + +|Identity type|Description|Typical scenario| +|-------------------|-----------------|----------------------| +|Domain Name System (DNS)|Use this element with X.509 certificates or Windows accounts. It compares the DNS name specified in the credential with the value specified in this element.|A DNS check enables you to use certificates with DNS or subject names. If a certificate is reissued with the same DNS or subject name, then the identity check is still valid. When a certificate is reissued, it gets a new RSA key but retains the same DNS or subject name. This means that clients do not have to update their identity information about the service.| +|Certificate. The default when `ClientCredentialType` is set to Certificate.|This element specifies a Base64-encoded X.509 certificate value to compare with the client.

Also use this element when using a CardSpace as a credential to authenticate the service.|This element restricts authentication to a single certificate based upon its thumbprint value. This enables stricter authentication because thumbprint values are unique. This comes with one caveat: If the certificate is reissued with the same Subject name, it also has a new Thumbprint. Therefore, clients are not able to validate the service unless the new thumbprint is known. For more information about finding a certificate's thumbprint, see [How to: Retrieve the Thumbprint of a Certificate](how-to-retrieve-the-thumbprint-of-a-certificate.md).| +|Certificate Reference|Identical to the Certificate option described previously. However, this element enables you to specify a certificate name and store location from which to retrieve the certificate.|Same as the Certificate scenario described previously.

The benefit is that the certificate store location can change.| +|RSA|This element specifies an RSA key value to compare with the client. This is similar to the certificate option but rather than using the certificate's thumbprint, the certificate's RSA key is used instead.|An RSA check enables you to specifically restrict authentication to a single certificate based upon its RSA key. This enables stricter authentication of a specific RSA key at the expense of the service, which no longer works with existing clients if the RSA key value changes.| +|User principal name (UPN). The default when the `ClientCredentialType` is set to Windows and the service process is not running under one of the system accounts.|This element specifies the UPN that the service is running under. See the Kerberos Protocol and Identity section of [Overriding the Identity of a Service for Authentication](../extending/overriding-the-identity-of-a-service-for-authentication.md).|This ensures that the service is running under a specific Windows user account. The user account can be either the current logged-on user or the service running under a particular user account.

This setting takes advantage of Windows Kerberos security if the service is running under a domain account within an Active Directory environment.| +|Service principal name (SPN). The default when the `ClientCredentialType` is set to Windows and the service process is running under one of the system accounts—LocalService, LocalSystem, or NetworkService.|This element specifies the SPN associated with the service's account. See the Kerberos Protocol and Identity section of [Overriding the Identity of a Service for Authentication](../extending/overriding-the-identity-of-a-service-for-authentication.md).|This ensures that the SPN and the specific Windows account associated with the SPN identify the service.

You can use the Setspn.exe tool to associate a machine account for the service's user account.

This setting takes advantage of Windows Kerberos security if the service is running under one of the system accounts or under a domain account that has an associated SPN name with it and the computer is a member of a domain within an Active Directory environment.| + +## Specifying Identity at the Service + + Typically, you do not have to set the identity on a service because the selection of a client credential type dictates the type of identity exposed in the service metadata. For more information about how to override or specify service identity, see [Overriding the Identity of a Service for Authentication](../extending/overriding-the-identity-of-a-service-for-authentication.md). + +## Using the \ Element in Configuration + + If you change the client credential type in the binding previously shown to `Certificate`, then the generated WSDL contains a Base64 serialized X.509 certificate for the identity value as shown in the following code. This is the default for all client credential types other than Windows. + + You can change the value of the default service identity or change the type of the identity by using the `` element in configuration or by setting the identity in code. The following configuration code sets a domain name system (DNS) identity with the value `contoso.com`. + +## Setting Identity Programmatically + + Your service does not have to explicitly specify an identity, because WCF automatically determines it. However, WCF allows you to specify an identity on an endpoint, if required. The following code adds a new service endpoint with a specific DNS identity. + [!code-csharp[C_Identity#5](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_identity/cs/source.cs#5)] - [!code-vb[C_Identity#5](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_identity/vb/source.vb#5)] - -## Specifying Identity at the Client - - At design time, a client developer typically uses the [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md) to generate client configuration. The generated configuration file (intended for use by the client) contains the server's identity. For example, the following code is generated from a service that specifies a DNS identity, as shown in the preceding example. Note that the client's endpoint identity value matches that of the service. In this case, when the client receives the Windows (Kerberos) credentials for the service, it expects the value to be `contoso.com`. - - If, instead of Windows, the service specifies a certificate as the client credential type, then the certificate's DNS property is expected to be the value `contoso.com`. (Or if the DNS property is `null`, the certificate's subject name must be `contoso.com`.) - -#### Using a Specific Value for Identity - - The following client configuration file shows how the service's identity is expected to be a specific value. In the following example, the client can communicate with two endpoints. The first is identified with a certificate thumbprint and the second with a certificate RSA key. That is, a certificate that contains only a public key/private key pair, but is not issued by a trusted authority. - -## Identity Checking at Run Time - - At design time, a client developer determines the server's identity through its metadata. At run time, the identity check is performed before calling any endpoints on the service. - - The identity value is tied to the type of authentication specified by metadata; in other words, the type of credentials used for the service. - - If the channel is configured to authenticate using message- or transport-level Secure Sockets Layer (SSL) with X.509 certificates for authentication, the following identity values are valid: - -- DNS. WCF ensures that the certificate provided during the SSL handshake contains a DNS or `CommonName` (CN) attribute equal to the value specified in the DNS identity on the client. Note that these checks are done in addition to determining the validity of the server certificate. By default, WCF validates that the server certificate is issued by a trusted root authority. - -- Certificate. During the SSL handshake, WCF ensures that the remote endpoint provides the exact certificate value specified in the identity. - -- Certificate Reference. Same as Certificate. - -- RSA. During the SSL handshake, WCF ensures that the remote endpoint provides the exact RSA key specified in the identity. - - If the service authenticates using message- or transport-level SSL with a Windows credential for authentication, and negotiates the credential, the following identity values are valid: - -- DNS. The negotiation passes the service's SPN so that the DNS name can be checked. The SPN is in the form `host/`. - -- SPN. An explicit service SPN is returned, for example, `host/myservice`. - -- UPN. The UPN of the service account. The UPN is in the form `username`@`domain`. For example, when the service is running in a user account, it may be `username@contoso.com`. - - Specifying the identity programmatically (using the property) is optional. If no identity is specified, and the client credential type is Windows, the default is SPN with the value set to the hostname part of the service endpoint address prefixed with the "host/" literal. If no identity is specified, and the client credential type is a certificate, the default is `Certificate`. This applies to both message- and transport-level security. - -## Identity and Custom Bindings - - Because the identity of a service depends on the binding type used, ensure that an appropriate identity is exposed when creating a custom binding. For example, in the following code example, the identity exposed is not compatible with the security type, because the identity for the secure conversation bootstrap binding does not match the identity for the binding on the endpoint. The secure conversation binding sets the DNS identity, while the sets the UPN or SPN identity. - + [!code-vb[C_Identity#5](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_identity/vb/source.vb#5)] + +## Specifying Identity at the Client + + At design time, a client developer typically uses the [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md) to generate client configuration. The generated configuration file (intended for use by the client) contains the server's identity. For example, the following code is generated from a service that specifies a DNS identity, as shown in the preceding example. Note that the client's endpoint identity value matches that of the service. In this case, when the client receives the Windows (Kerberos) credentials for the service, it expects the value to be `contoso.com`. + + If, instead of Windows, the service specifies a certificate as the client credential type, then the certificate's DNS property is expected to be the value `contoso.com`. (Or if the DNS property is `null`, the certificate's subject name must be `contoso.com`.) + +#### Using a Specific Value for Identity + + The following client configuration file shows how the service's identity is expected to be a specific value. In the following example, the client can communicate with two endpoints. The first is identified with a certificate thumbprint and the second with a certificate RSA key. That is, a certificate that contains only a public key/private key pair, but is not issued by a trusted authority. + +## Identity Checking at Run Time + + At design time, a client developer determines the server's identity through its metadata. At runtime, the identity check is performed before calling any endpoints on the service. + + The identity value is tied to the type of authentication specified by metadata; in other words, the type of credentials used for the service. + + If the channel is configured to authenticate using message- or transport-level Secure Sockets Layer (SSL) with X.509 certificates for authentication, the following identity values are valid: + +- DNS. WCF ensures that the certificate provided during the SSL handshake contains a DNS or `CommonName` (CN) attribute equal to the value specified in the DNS identity on the client. Note that these checks are done in addition to determining the validity of the server certificate. By default, WCF validates that the server certificate is issued by a trusted root authority. + +- Certificate. During the SSL handshake, WCF ensures that the remote endpoint provides the exact certificate value specified in the identity. + +- Certificate Reference. Same as Certificate. + +- RSA. During the SSL handshake, WCF ensures that the remote endpoint provides the exact RSA key specified in the identity. + + If the service authenticates using message- or transport-level SSL with a Windows credential for authentication, and negotiates the credential, the following identity values are valid: + +- DNS. The negotiation passes the service's SPN so that the DNS name can be checked. The SPN is in the form `host/`. + +- SPN. An explicit service SPN is returned, for example, `host/myservice`. + +- UPN. The UPN of the service account. The UPN is in the form `username`@`domain`. For example, when the service is running in a user account, it may be `username@contoso.com`. + + Specifying the identity programmatically (using the property) is optional. If no identity is specified, and the client credential type is Windows, the default is SPN with the value set to the hostname part of the service endpoint address prefixed with the "host/" literal. If no identity is specified, and the client credential type is a certificate, the default is `Certificate`. This applies to both message- and transport-level security. + +## Identity and Custom Bindings + + Because the identity of a service depends on the binding type used, ensure that an appropriate identity is exposed when creating a custom binding. For example, in the following code example, the identity exposed is not compatible with the security type, because the identity for the secure conversation bootstrap binding does not match the identity for the binding on the endpoint. The secure conversation binding sets the DNS identity, while the sets the UPN or SPN identity. + [!code-csharp[C_Identity#8](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_identity/cs/source.cs#8)] - [!code-vb[C_Identity#8](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_identity/vb/source.vb#8)] - - For more information about how to stack binding elements correctly for a custom binding, see [Creating User-Defined Bindings](../extending/creating-user-defined-bindings.md). For more information about creating a custom binding with the , see [How to: Create a SecurityBindingElement for a Specified Authentication Mode](how-to-create-a-securitybindingelement-for-a-specified-authentication-mode.md). - + [!code-vb[C_Identity#8](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_identity/vb/source.vb#8)] + + For more information about how to stack binding elements correctly for a custom binding, see [Creating User-Defined Bindings](../extending/creating-user-defined-bindings.md). For more information about creating a custom binding with the , see [How to: Create a SecurityBindingElement for a Specified Authentication Mode](how-to-create-a-securitybindingelement-for-a-specified-authentication-mode.md). + ## See also - [How to: Create a Custom Binding Using the SecurityBindingElement](how-to-create-a-custom-binding-using-the-securitybindingelement.md) diff --git a/docs/framework/wcf/feature-details/standard-endpoints.md b/docs/framework/wcf/feature-details/standard-endpoints.md index 690789779fbe2..aaad53d506643 100644 --- a/docs/framework/wcf/feature-details/standard-endpoints.md +++ b/docs/framework/wcf/feature-details/standard-endpoints.md @@ -168,7 +168,7 @@ serviceHost.AddServiceEndpoint(new CustomEndpoint()); A standard endpoint that is used by services to send announcement messages over a UDP binding. - A standard endpoint that uses WS-Discovery to find the endpoint address dynamically at run time. + A standard endpoint that uses WS-Discovery to find the endpoint address dynamically at runtime. A standard endpoint for metadata exchange. diff --git a/docs/framework/wcf/feature-details/startup-time-of-wcf-client-applications-using-the-xmlserializer.md b/docs/framework/wcf/feature-details/startup-time-of-wcf-client-applications-using-the-xmlserializer.md index e22a2010e2a36..262b77657f96a 100644 --- a/docs/framework/wcf/feature-details/startup-time-of-wcf-client-applications-using-the-xmlserializer.md +++ b/docs/framework/wcf/feature-details/startup-time-of-wcf-client-applications-using-the-xmlserializer.md @@ -7,83 +7,83 @@ ms.assetid: 21093451-0bc3-4b1a-9a9d-05f7f71fa7d0 --- # How to: Improve the Startup Time of WCF Client Applications using the XmlSerializer -Services and client applications that use data types that are serializable using the generate and compile serialization code for those data types at run time, which can result in slow start-up performance. - +Services and client applications that use data types that are serializable using the generate and compile serialization code for those data types at runtime, which can result in slow start-up performance. + > [!NOTE] -> Pre-generated serialization code can only be used in client applications and not in services. - - The [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md) can improve start-up performance for these applications by generating the necessary serialization code from the compiled assemblies for the application. Svcutil.exe generates serialization code for all data types used in service contracts in the compiled application assembly that can be serialized using the . Service and operation contracts that use the are marked with the . - -### To generate XmlSerializer serialization code - -1. Compile your service or client code into one or more assemblies. - -2. Open an SDK command prompt. - -3. At the command prompt, launch the Svcutil.exe tool using the following format. - - ```console - svcutil.exe /t:xmlSerializer * - ``` - - The `assemblyPath` argument specifies the path to an assembly that contains service contract types. Svcutil.exe generates serialization code for all data types used in service contracts in the compiled application assembly that can be serialized using the . - - Svcutil.exe can only generate C# serialization code. One source code file is generated for each input assembly. You cannot use the **/language** switch to change the language of the generated code. - - To specify the path to dependent assemblies, use the **/reference** option. - -4. Make the generated serialization code available to your application by using one of the following options: - - 1. Compile the generated serialization code into a separate assembly with the name [*original assembly*].XmlSerializers.dll (for example, MyApp.XmlSerializers.dll). Your application must be able to load the assembly, which must be signed with the same key as the original assembly. If you recompile the original assembly, you must regenerate the serialization assembly. - - 2. Compile the generated serialization code into a separate assembly and use the on the service contract that uses the . Set the or properties to point to the compiled serialization assembly. - - 3. Compile the generated serialization code into your application assembly and add the to the service contract that uses the . Do not set the or properties. The default serialization assembly is assumed to be the current assembly. - -### To generate XmlSerializer serialization code in Visual Studio - -1. Create the WCF service and client projects in Visual Studio. Then, add a service reference to the client project. - -2. Add an to the service contract in the *reference.cs* file in the client app project under **serviceReference** -> **reference.svcmap**. Note that you need to show all files in **Solution Explorer** to see these files. - -3. Build the client app. - -4. Use the [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md) to create a pre-generated serializer *.cs* file by using the command: - - ```console - svcutil.exe /t:xmlSerializer * - ``` - - The assemblyPath argument specifies the path to the WCF client assembly. - - Such as: - - ```console - svcutil.exe /t:xmlSerializer wcfclient.exe - ``` - - The *WCFClient.XmlSerializers.dll.cs* file will be generated. - -5. Compile the pre-generated serialization assembly. - - Based on the example in the previous step, the compile command would be the following: - - ```console - csc /r:wcfclient.exe /out:WCFClient.XmlSerializers.dll /t:library WCFClient.XmlSerializers.dll.cs - ``` - - Make sure the generated *WCFClient.XmlSerializers.dll* is in the same directory as the client app, which is *WCFClient.exe* in this case. - -6. Run the client app as usual. The pre-generated serialization assembly will be used. - -## Example - - The following command generates serialization types for `XmlSerializer` types that any service contracts in the assembly use. - -```console -svcutil /t:xmlserializer myContractLibrary.exe -``` - +> Pre-generated serialization code can only be used in client applications and not in services. + + The [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md) can improve start-up performance for these applications by generating the necessary serialization code from the compiled assemblies for the application. Svcutil.exe generates serialization code for all data types used in service contracts in the compiled application assembly that can be serialized using the . Service and operation contracts that use the are marked with the . + +### To generate XmlSerializer serialization code + +1. Compile your service or client code into one or more assemblies. + +2. Open an SDK command prompt. + +3. At the command prompt, launch the Svcutil.exe tool using the following format. + + ```console + svcutil.exe /t:xmlSerializer * + ``` + + The `assemblyPath` argument specifies the path to an assembly that contains service contract types. Svcutil.exe generates serialization code for all data types used in service contracts in the compiled application assembly that can be serialized using the . + + Svcutil.exe can only generate C# serialization code. One source code file is generated for each input assembly. You cannot use the **/language** switch to change the language of the generated code. + + To specify the path to dependent assemblies, use the **/reference** option. + +4. Make the generated serialization code available to your application by using one of the following options: + + 1. Compile the generated serialization code into a separate assembly with the name [*original assembly*].XmlSerializers.dll (for example, MyApp.XmlSerializers.dll). Your application must be able to load the assembly, which must be signed with the same key as the original assembly. If you recompile the original assembly, you must regenerate the serialization assembly. + + 2. Compile the generated serialization code into a separate assembly and use the on the service contract that uses the . Set the or properties to point to the compiled serialization assembly. + + 3. Compile the generated serialization code into your application assembly and add the to the service contract that uses the . Do not set the or properties. The default serialization assembly is assumed to be the current assembly. + +### To generate XmlSerializer serialization code in Visual Studio + +1. Create the WCF service and client projects in Visual Studio. Then, add a service reference to the client project. + +2. Add an to the service contract in the *reference.cs* file in the client app project under **serviceReference** -> **reference.svcmap**. Note that you need to show all files in **Solution Explorer** to see these files. + +3. Build the client app. + +4. Use the [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md) to create a pre-generated serializer *.cs* file by using the command: + + ```console + svcutil.exe /t:xmlSerializer * + ``` + + The assemblyPath argument specifies the path to the WCF client assembly. + + Such as: + + ```console + svcutil.exe /t:xmlSerializer wcfclient.exe + ``` + + The *WCFClient.XmlSerializers.dll.cs* file will be generated. + +5. Compile the pre-generated serialization assembly. + + Based on the example in the previous step, the compile command would be the following: + + ```console + csc /r:wcfclient.exe /out:WCFClient.XmlSerializers.dll /t:library WCFClient.XmlSerializers.dll.cs + ``` + + Make sure the generated *WCFClient.XmlSerializers.dll* is in the same directory as the client app, which is *WCFClient.exe* in this case. + +6. Run the client app as usual. The pre-generated serialization assembly will be used. + +## Example + + The following command generates serialization types for `XmlSerializer` types that any service contracts in the assembly use. + +```console +svcutil /t:xmlserializer myContractLibrary.exe +``` + ## See also - [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md) diff --git a/docs/framework/wcf/feature-details/streaming-message-transfer.md b/docs/framework/wcf/feature-details/streaming-message-transfer.md index 690d9b7258c29..a22ea5a97806e 100644 --- a/docs/framework/wcf/feature-details/streaming-message-transfer.md +++ b/docs/framework/wcf/feature-details/streaming-message-transfer.md @@ -6,46 +6,46 @@ ms.assetid: 72a47a51-e5e7-4b76-b24a-299d51e0ae5a --- # Streaming Message Transfer -Windows Communication Foundation (WCF) transports support two modes for transferring messages: - -- Buffered transfers hold the entire message in a memory buffer until the transfer is complete. A buffered message must be completely delivered before a receiver can read it. - -- Streamed transfers expose the message as a stream. The receiver starts processing the message before it is completely delivered. - -- Streamed transfers can improve the scalability of a service by eliminating the requirement for large memory buffers. Whether changing the transfer mode improves scalability depends on the size of the messages being transferred. Large message sizes favor using streamed transfers. - - By default, the HTTP, TCP/IP, and named pipe transports use buffered transfers. This document describes how to switch these transports from a buffered to streamed transfer mode and the consequences of doing so. - -## Enabling Streamed Transfers - - Selecting between buffered and streamed transfer modes is done on the binding element of the transport. The binding element has a property that can be set to `Buffered`, `Streamed`, `StreamedRequest`, or `StreamedResponse`. Setting the transfer mode to `Streamed` enables streaming communication in both directions. Setting the transfer mode to `StreamedRequest` or `StreamedResponse` enables streaming communication in the indicated direction only. - - The , , and bindings expose the property. For other transports, you must create a custom binding to set the transfer mode. - - The decision to use either buffered or streamed transfers is a local decision of the endpoint. For HTTP transports, the transfer mode does not propagate across a connection, or to servers and other intermediaries. Setting the transfer mode is not reflected in the description of the service interface. After generating a client class for a service, you must edit the configuration file for services intended to be used with streamed transfers to set the mode. For TCP and named pipe transports, the transfer mode is propagated as a policy assertion. - - For code samples, see [How to: Enable Streaming](how-to-enable-streaming.md). - -## Enabling Asynchronous Streaming - - To enable asynchronous streaming, add the endpoint behavior to the service host and set its property to `true`. - - This version of WCF also added the capability of true asynchronous streaming on the send side. This improves scalability of the service in scenarios where it is streaming messages to multiple clients some of which are slow in reading; possibly due to network congestion or are not reading at all. In these scenarios WCF no longer blocks individual threads on the service per client. This ensures that the service is able to process many more clients thereby improving the scalability of the service. - -## Restrictions on Streamed Transfers - - Using the streamed transfer mode causes the run time to enforce additional restrictions. - - Operations that occur across a streamed transport can have a contract with at most one input or output parameter. That parameter corresponds to the entire body of the message and must be a , a derived type of , or an implementation. Having a return value for an operation is equivalent to having an output parameter. - - Some WCF features, such as reliable messaging, transactions, and SOAP message-level security, rely on buffering messages for transmissions. Using these features may reduce or eliminate the performance benefits gained by using streaming. To secure a streamed transport, use transport-level security only or use transport-level security plus authentication-only message security. - - SOAP headers are always buffered, even when the transfer mode is set to streamed. The headers for a message must not exceed the size of the `MaxBufferSize` transport quota. For more information about this setting, see [Transport Quotas](transport-quotas.md). - -## Differences Between Buffered and Streamed Transfers - - Changing the transfer mode from buffered to streamed also changes the native channel shape of the TCP and named pipe transports. For buffered transfers, the native channel shape is . For streamed transfers, the native channels are and . Changing the transfer mode in an existing application that uses these transports directly (that is, not through a service contract) requires changing the expected channel shape for channel factories and listeners. - +Windows Communication Foundation (WCF) transports support two modes for transferring messages: + +- Buffered transfers hold the entire message in a memory buffer until the transfer is complete. A buffered message must be completely delivered before a receiver can read it. + +- Streamed transfers expose the message as a stream. The receiver starts processing the message before it is completely delivered. + +- Streamed transfers can improve the scalability of a service by eliminating the requirement for large memory buffers. Whether changing the transfer mode improves scalability depends on the size of the messages being transferred. Large message sizes favor using streamed transfers. + + By default, the HTTP, TCP/IP, and named pipe transports use buffered transfers. This document describes how to switch these transports from a buffered to streamed transfer mode and the consequences of doing so. + +## Enabling Streamed Transfers + + Selecting between buffered and streamed transfer modes is done on the binding element of the transport. The binding element has a property that can be set to `Buffered`, `Streamed`, `StreamedRequest`, or `StreamedResponse`. Setting the transfer mode to `Streamed` enables streaming communication in both directions. Setting the transfer mode to `StreamedRequest` or `StreamedResponse` enables streaming communication in the indicated direction only. + + The , , and bindings expose the property. For other transports, you must create a custom binding to set the transfer mode. + + The decision to use either buffered or streamed transfers is a local decision of the endpoint. For HTTP transports, the transfer mode does not propagate across a connection, or to servers and other intermediaries. Setting the transfer mode is not reflected in the description of the service interface. After generating a client class for a service, you must edit the configuration file for services intended to be used with streamed transfers to set the mode. For TCP and named pipe transports, the transfer mode is propagated as a policy assertion. + + For code samples, see [How to: Enable Streaming](how-to-enable-streaming.md). + +## Enabling Asynchronous Streaming + + To enable asynchronous streaming, add the endpoint behavior to the service host and set its property to `true`. + + This version of WCF also added the capability of true asynchronous streaming on the send side. This improves scalability of the service in scenarios where it is streaming messages to multiple clients some of which are slow in reading; possibly due to network congestion or are not reading at all. In these scenarios WCF no longer blocks individual threads on the service per client. This ensures that the service is able to process many more clients thereby improving the scalability of the service. + +## Restrictions on Streamed Transfers + + Using the streamed transfer mode causes the runtime to enforce additional restrictions. + + Operations that occur across a streamed transport can have a contract with at most one input or output parameter. That parameter corresponds to the entire body of the message and must be a , a derived type of , or an implementation. Having a return value for an operation is equivalent to having an output parameter. + + Some WCF features, such as reliable messaging, transactions, and SOAP message-level security, rely on buffering messages for transmissions. Using these features may reduce or eliminate the performance benefits gained by using streaming. To secure a streamed transport, use transport-level security only or use transport-level security plus authentication-only message security. + + SOAP headers are always buffered, even when the transfer mode is set to streamed. The headers for a message must not exceed the size of the `MaxBufferSize` transport quota. For more information about this setting, see [Transport Quotas](transport-quotas.md). + +## Differences Between Buffered and Streamed Transfers + + Changing the transfer mode from buffered to streamed also changes the native channel shape of the TCP and named pipe transports. For buffered transfers, the native channel shape is . For streamed transfers, the native channels are and . Changing the transfer mode in an existing application that uses these transports directly (that is, not through a service contract) requires changing the expected channel shape for channel factories and listeners. + ## See also - [How to: Enable Streaming](how-to-enable-streaming.md) diff --git a/docs/framework/wcf/feature-details/supported-deployment-scenarios.md b/docs/framework/wcf/feature-details/supported-deployment-scenarios.md index 82c99ab337374..9fb8b6e550e49 100644 --- a/docs/framework/wcf/feature-details/supported-deployment-scenarios.md +++ b/docs/framework/wcf/feature-details/supported-deployment-scenarios.md @@ -16,7 +16,7 @@ WCF supports a subset of features in applications running under either of the fo - Internet Zone permissions -Attempting to use WCF in partially trusted applications with more restrictive permissions may result in security exceptions at run time. +Attempting to use WCF in partially trusted applications with more restrictive permissions may result in security exceptions at runtime. For more information about the features supported in these permission sets, see [Partial Trust Feature Compatibility](partial-trust-feature-compatibility.md). diff --git a/docs/framework/wcf/feature-details/transport-security-overview.md b/docs/framework/wcf/feature-details/transport-security-overview.md index ee3427d96a6b8..2e51e7d974adc 100644 --- a/docs/framework/wcf/feature-details/transport-security-overview.md +++ b/docs/framework/wcf/feature-details/transport-security-overview.md @@ -2,135 +2,135 @@ title: "Transport Security Overview" description: Learn about the major transport security mechanisms in the WCF system-provided bindings. These security mechanisms depend on the binding and transport used. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 00959326-aa9d-44d0-af61-54933d4adc7f --- # Transport Security Overview -Transport security mechanisms in Windows Communication Foundation (WCF) depend on the binding and transport being used. For example, when using the class, the transport is HTTP, and the primary mechanism for securing the transport is Secure Sockets Layer (SSL) over HTTP, commonly called HTTPS. This topic discusses the major transport security mechanisms used in the WCF system-provided bindings. - +Transport security mechanisms in Windows Communication Foundation (WCF) depend on the binding and transport being used. For example, when using the class, the transport is HTTP, and the primary mechanism for securing the transport is Secure Sockets Layer (SSL) over HTTP, commonly called HTTPS. This topic discusses the major transport security mechanisms used in the WCF system-provided bindings. + > [!NOTE] -> When SSL security is used with .NET Framework 3.5 and later an WCF client uses both the intermediate certificates in its certificate store and the intermediate certificates received during SSL negotiation to perform certificate chain validation on the service's certificate. .NET Framework 3.0 only uses the intermediate certificates installed in the local certificate store. - +> When SSL security is used with .NET Framework 3.5 and later an WCF client uses both the intermediate certificates in its certificate store and the intermediate certificates received during SSL negotiation to perform certificate chain validation on the service's certificate. .NET Framework 3.0 only uses the intermediate certificates installed in the local certificate store. + > [!WARNING] -> When transport security is used, the property may be overwritten. To prevent this from happening set the to . is a service behavior that can be set on the service description. - -## BasicHttpBinding +> When transport security is used, the property may be overwritten. To prevent this from happening set the to . is a service behavior that can be set on the service description. + +## BasicHttpBinding + + By default, the class does not provide security. This binding is designed for interoperability with Web service providers that do not implement security. However, you can switch on security by setting the property to any value except . To enable transport security, set the property to . + +### Interoperation with IIS - By default, the class does not provide security. This binding is designed for interoperability with Web service providers that do not implement security. However, you can switch on security by setting the property to any value except . To enable transport security, set the property to . - -### Interoperation with IIS + The class is primarily used to interoperate with existing Web services, and many of those services are hosted by Internet Information Services (IIS). Consequently, the transport security for this binding is designed for seamless interoperation with IIS sites. This is done by setting the security mode to and then setting the client credential type. The credential type values correspond to IIS directory security mechanisms. The following code shows the mode being set and the credential type set to Windows. You can use this configuration when both client and server are on the same Windows domain. - The class is primarily used to interoperate with existing Web services, and many of those services are hosted by Internet Information Services (IIS). Consequently, the transport security for this binding is designed for seamless interoperation with IIS sites. This is done by setting the security mode to and then setting the client credential type. The credential type values correspond to IIS directory security mechanisms. The following code shows the mode being set and the credential type set to Windows. You can use this configuration when both client and server are on the same Windows domain. - [!code-csharp[c_ProgrammingSecurity#10](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_programmingsecurity/cs/source.cs#10)] - [!code-vb[c_ProgrammingSecurity#10](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_programmingsecurity/vb/source.vb#10)] - - Or, in configuration: - -```xml - - - - - - - - - -``` - - The following sections discuss other client credential types. - -#### Basic - - This corresponds to the Basic authentication method in IIS. When using this mode, the IIS server must be configured with Windows user accounts and appropriate NTFS file system permissions. For more information about IIS 6.0, see [Enabling Basic Authentication and Configuring the Realm Name](/previous-versions/windows/it-pro/windows-server-2003/cc785293(v=ws.10)). For more information about IIS 7.0, see [Configure Basic Authentication (IIS 7)](/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/cc772009(v=ws.10)). - -#### Certificate - - IIS has an option to require clients to log on with a certificate. The feature also enables IIS to map a client certificate to a Windows account. For more information about IIS 6.0, see [Enabling Client Certificates in IIS 6.0](/previous-versions/windows/it-pro/windows-server-2003/cc727994(v=ws.10)). For more information about IIS 7.0, see [Configuring Server Certificates in IIS 7](/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/cc732230(v=ws.10)). - -#### Digest - - Digest authentication is similar to Basic authentication, but offers the advantage of sending the credentials as a hash, instead of in clear text. For more information about IIS 6.0, see [Digest Authentication in IIS 6.0](/previous-versions/windows/it-pro/windows-server-2003/cc782661(v=ws.10)). For more information about IIS 7.0, see [Configure Digest Authentication (IIS 7)](/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/cc754104(v=ws.10)). - -#### Windows + [!code-vb[c_ProgrammingSecurity#10](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_programmingsecurity/vb/source.vb#10)] + + Or, in configuration: + +```xml + + + + + + + + + +``` + + The following sections discuss other client credential types. + +#### Basic + + This corresponds to the Basic authentication method in IIS. When using this mode, the IIS server must be configured with Windows user accounts and appropriate NTFS file system permissions. For more information about IIS 6.0, see [Enabling Basic Authentication and Configuring the Realm Name](/previous-versions/windows/it-pro/windows-server-2003/cc785293(v=ws.10)). For more information about IIS 7.0, see [Configure Basic Authentication (IIS 7)](/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/cc772009(v=ws.10)). + +#### Certificate + + IIS has an option to require clients to log on with a certificate. The feature also enables IIS to map a client certificate to a Windows account. For more information about IIS 6.0, see [Enabling Client Certificates in IIS 6.0](/previous-versions/windows/it-pro/windows-server-2003/cc727994(v=ws.10)). For more information about IIS 7.0, see [Configuring Server Certificates in IIS 7](/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/cc732230(v=ws.10)). + +#### Digest + + Digest authentication is similar to Basic authentication, but offers the advantage of sending the credentials as a hash, instead of in clear text. For more information about IIS 6.0, see [Digest Authentication in IIS 6.0](/previous-versions/windows/it-pro/windows-server-2003/cc782661(v=ws.10)). For more information about IIS 7.0, see [Configure Digest Authentication (IIS 7)](/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/cc754104(v=ws.10)). + +#### Windows This corresponds to integrated Windows authentication in IIS. When set to this value, the server is also expected to exist on a Windows domain that uses the Kerberos protocol as its domain controller. If the server is not on a Kerberos-backed domain, or if the Kerberos system fails, you can use the NT LAN Manager (NTLM) value described in the next section. For more information about IIS 6.0, see [Integrated Windows Authentication in IIS 6.0](/previous-versions/windows/it-pro/windows-server-2003/cc738016(v=ws.10)). For more information about IIS 7.0, see [Configuring Server Certificates in IIS 7](/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/cc732230(v=ws.10)). - -#### NTLM + +#### NTLM This enables the server to use NTLM for authentication if the Kerberos protocol fails. For more information about configuring IIS in IIS 6.0, see [Forcing NTLM Authentication](/previous-versions/windows/it-pro/windows-server-2003/cc786486(v=ws.10)). For IIS 7.0, the Windows authentication includes NTLM authentication. For more information, see [Configuring Server Certificates in IIS 7](/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/cc732230(v=ws.10)). - -## WsHttpBinding - - The class is designed for interoperation with services that implement WS-* specifications. The transport security for this binding is Secure Sockets Layer (SSL) over HTTP, or HTTPS. To create an WCF application that uses SSL, use IIS to host the application. Alternatively, if you are creating a self-hosted application, use the HttpCfg.exe tool to bind an X.509 certificate to a specific port on a computer. The port number is specified as part of the WCF application as an endpoint address. When using transport mode, the endpoint address must include the HTTPS protocol or an exception will be thrown at run time. For more information, see [HTTP Transport Security](http-transport-security.md). - - For client authentication, set the property of the class to one of the enumeration values. The enumeration values are identical to the client credential types for and are designed to be hosted with IIS services. - - The following example shows the binding being used with a client credential type of Windows. - + +## WsHttpBinding + + The class is designed for interoperation with services that implement WS-* specifications. The transport security for this binding is Secure Sockets Layer (SSL) over HTTP, or HTTPS. To create an WCF application that uses SSL, use IIS to host the application. Alternatively, if you are creating a self-hosted application, use the HttpCfg.exe tool to bind an X.509 certificate to a specific port on a computer. The port number is specified as part of the WCF application as an endpoint address. When using transport mode, the endpoint address must include the HTTPS protocol or an exception will be thrown at runtime. For more information, see [HTTP Transport Security](http-transport-security.md). + + For client authentication, set the property of the class to one of the enumeration values. The enumeration values are identical to the client credential types for and are designed to be hosted with IIS services. + + The following example shows the binding being used with a client credential type of Windows. + [!code-csharp[c_ProgrammingSecurity#11](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_programmingsecurity/cs/source.cs#11)] - [!code-vb[c_ProgrammingSecurity#11](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_programmingsecurity/vb/source.vb#11)] - -## WSDualHttpBinding - - This binding provides only message-level security, not transport-level security. - -## NetTcpBinding - - The class uses TCP for message transport. Security for the transport mode is provided by implementing Transport Layer Security (TLS) over TCP. The TLS implementation is provided by the operating system. - - You can also specify the client's credential type by setting the property of the class to one of the values, as shown in the following code. - + [!code-vb[c_ProgrammingSecurity#11](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_programmingsecurity/vb/source.vb#11)] + +## WSDualHttpBinding + + This binding provides only message-level security, not transport-level security. + +## NetTcpBinding + + The class uses TCP for message transport. Security for the transport mode is provided by implementing Transport Layer Security (TLS) over TCP. The TLS implementation is provided by the operating system. + + You can also specify the client's credential type by setting the property of the class to one of the values, as shown in the following code. + [!code-csharp[c_ProgrammingSecurity#12](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_programmingsecurity/cs/source.cs#12)] - [!code-vb[c_ProgrammingSecurity#12](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_programmingsecurity/vb/source.vb#12)] - -#### Client + [!code-vb[c_ProgrammingSecurity#12](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_programmingsecurity/vb/source.vb#12)] + +#### Client + + On the client, you must specify a certificate using the method of the class. - On the client, you must specify a certificate using the method of the class. - > [!NOTE] -> If you are using Windows security, a certificate is not required. - - The following code uses the thumbprint of the certificate, which uniquely identifies it. For more information about certificates, see [Working with Certificates](working-with-certificates.md). - +> If you are using Windows security, a certificate is not required. + + The following code uses the thumbprint of the certificate, which uniquely identifies it. For more information about certificates, see [Working with Certificates](working-with-certificates.md). + [!code-csharp[c_ProgrammingSecurity#13](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_programmingsecurity/cs/source.cs#13)] - [!code-vb[c_ProgrammingSecurity#13](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_programmingsecurity/vb/source.vb#13)] - - Alternatively, specify the certificate in the client's configuration using a [\](../../configure-apps/file-schema/wcf/clientcredentials.md) element in the behaviors section. - -```xml - - - + [!code-vb[c_ProgrammingSecurity#13](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_programmingsecurity/vb/source.vb#13)] + + Alternatively, specify the certificate in the client's configuration using a [\](../../configure-apps/file-schema/wcf/clientcredentials.md) element in the behaviors section. + +```xml + + + - - - + X509FindType="FindByThumbPrint"> + + + -``` - -## NetNamedPipeBinding +``` + +## NetNamedPipeBinding + + The class is designed for efficient intra-machine communication; that is, for processes running on the same computer, although named pipe channels can be created between two computers on the same network. This binding provides only transport-level security. When creating applications using this binding, the endpoint addresses must include "net.pipe" as the protocol of the endpoint address. + +## WSFederationHttpBinding + + When using transport security, this binding uses SSL over HTTP, known as HTTPS with an issued token (). For more information about federation applications, see [Federation and Issued Tokens](federation-and-issued-tokens.md). + +## NetPeerTcpBinding - The class is designed for efficient intra-machine communication; that is, for processes running on the same computer, although named pipe channels can be created between two computers on the same network. This binding provides only transport-level security. When creating applications using this binding, the endpoint addresses must include "net.pipe" as the protocol of the endpoint address. - -## WSFederationHttpBinding + The class is a secure transport that is designed for efficient communication using the peer-to-peer networking feature. As indicated by the name of the class and binding, TCP is the protocol. When the security mode is set to Transport, the binding implements TLS over TCP. For more information about the peer-to-peer feature, see [Peer-to-Peer Networking](peer-to-peer-networking.md). - When using transport security, this binding uses SSL over HTTP, known as HTTPS with an issued token (). For more information about federation applications, see [Federation and Issued Tokens](federation-and-issued-tokens.md). - -## NetPeerTcpBinding +## MsmqIntegrationBinding and NetMsmqBinding - The class is a secure transport that is designed for efficient communication using the peer-to-peer networking feature. As indicated by the name of the class and binding, TCP is the protocol. When the security mode is set to Transport, the binding implements TLS over TCP. For more information about the peer-to-peer feature, see [Peer-to-Peer Networking](peer-to-peer-networking.md). - -## MsmqIntegrationBinding and NetMsmqBinding + For a complete discussion of transport security with Message Queuing (previously called MSMQ), see [Securing Messages Using Transport Security](securing-messages-using-transport-security.md). - For a complete discussion of transport security with Message Queuing (previously called MSMQ), see [Securing Messages Using Transport Security](securing-messages-using-transport-security.md). - ## See also - [Programming WCF Security](programming-wcf-security.md) diff --git a/docs/framework/wcf/feature-details/troubleshooting-queued-messaging.md b/docs/framework/wcf/feature-details/troubleshooting-queued-messaging.md index 3a3b2c2699edd..f4720d8be1da9 100644 --- a/docs/framework/wcf/feature-details/troubleshooting-queued-messaging.md +++ b/docs/framework/wcf/feature-details/troubleshooting-queued-messaging.md @@ -116,7 +116,7 @@ System.ServiceModel.MsmqPoisonMessageException: The transport channel detected a ---> System.ServiceModel.ProtocolException: An incoming MSMQ message contained invalid or unexpected .NET Message Framing information in its body. The message cannot be received. Ensure that the sender is using a compatible service contract with a matching SessionMode. ``` -The system dead-letter queue, as well as any custom dead-letter queue, is particularly susceptible to this issue if an application sends both queued session messages and queued datagram messages from the same computer. If a message cannot be sent successfully, it is moved to the dead-letter queue. Under these circumstances, it is possible to have both session and datagram messages in the dead-letter queue. There is no way to separate both types of messages at run time when reading from a queue, therefore, applications should not send both queued session messages and queued datagram messages from the same computer. +The system dead-letter queue, as well as any custom dead-letter queue, is particularly susceptible to this issue if an application sends both queued session messages and queued datagram messages from the same computer. If a message cannot be sent successfully, it is moved to the dead-letter queue. Under these circumstances, it is possible to have both session and datagram messages in the dead-letter queue. There is no way to separate both types of messages at runtime when reading from a queue, therefore, applications should not send both queued session messages and queued datagram messages from the same computer. ### MSMQ Integration: Specific Troubleshooting diff --git a/docs/framework/wcf/feature-details/using-servicethrottlingbehavior-to-control-wcf-service-performance.md b/docs/framework/wcf/feature-details/using-servicethrottlingbehavior-to-control-wcf-service-performance.md index 3960172dd95f8..2cfa790a87ee6 100644 --- a/docs/framework/wcf/feature-details/using-servicethrottlingbehavior-to-control-wcf-service-performance.md +++ b/docs/framework/wcf/feature-details/using-servicethrottlingbehavior-to-control-wcf-service-performance.md @@ -2,28 +2,28 @@ description: "Learn more about: Using ServiceThrottlingBehavior to Control WCF Service Performance" title: "Using ServiceThrottlingBehavior to Control WCF Service Performance" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "behavior [WCF], service performance" ms.assetid: f9dc120c-dc24-49d5-930e-b22f5bc73423 --- # Using ServiceThrottlingBehavior to Control WCF Service Performance -The class exposes properties that you can use to limit how many instances or sessions are created at the application level. Using this behavior, you can fine-tune the performance of your Windows Communication Foundation (WCF) application. - -## Controlling Service Instances and Concurrent Calls - - Use the property to specify the maximum number of messages actively processing across a class, and the property to specify the maximum number of objects in the service. - - Because determining the settings for these properties usually takes place after real-world experience running the application against loads, the settings for the properties is typically specified in an application configuration file using the [\](../../configure-apps/file-schema/wcf/servicethrottling.md) element. - - The following code example shows the use of the class from an application configuration file that sets the , , and properties to 1 as a trivial example. Real-world experience determines the optimal settings for any particular application. - - [!code-xml[ServiceThrottlingBehavior#3](../../../../samples/snippets/csharp/VS_Snippets_CFX/servicethrottlingbehavior/cs/hostapplication.exe.config#3)] - - The exact run-time behavior depends upon the values of the and properties, which control how many messages can execute inside an operation at once and the lifetimes of the service relative to incoming channel sessions, respectively. - - For details, see , and . - +The class exposes properties that you can use to limit how many instances or sessions are created at the application level. Using this behavior, you can fine-tune the performance of your Windows Communication Foundation (WCF) application. + +## Controlling Service Instances and Concurrent Calls + + Use the property to specify the maximum number of messages actively processing across a class, and the property to specify the maximum number of objects in the service. + + Because determining the settings for these properties usually takes place after real-world experience running the application against loads, the settings for the properties is typically specified in an application configuration file using the [\](../../configure-apps/file-schema/wcf/servicethrottling.md) element. + + The following code example shows the use of the class from an application configuration file that sets the , , and properties to 1 as a trivial example. Real-world experience determines the optimal settings for any particular application. + + [!code-xml[ServiceThrottlingBehavior#3](../../../../samples/snippets/csharp/VS_Snippets_CFX/servicethrottlingbehavior/cs/hostapplication.exe.config#3)] + + The exact runtime behavior depends upon the values of the and properties, which control how many messages can execute inside an operation at once and the lifetimes of the service relative to incoming channel sessions, respectively. + + For details, see , and . + ## See also - diff --git a/docs/framework/wcf/feature-details/wcf-discovery-object-model.md b/docs/framework/wcf/feature-details/wcf-discovery-object-model.md index 800277c9aa12f..09bff82ee4cba 100644 --- a/docs/framework/wcf/feature-details/wcf-discovery-object-model.md +++ b/docs/framework/wcf/feature-details/wcf-discovery-object-model.md @@ -6,142 +6,142 @@ ms.assetid: 8365a152-eacd-4779-9130-bbc48fa5c5d9 --- # WCF Discovery Object Model -WCF Discovery consists of a set of types that provide a unified programming model that allows you to write services that are discoverable at run time and clients that find and use these services. - -## Making a Service Discoverable and Finding Services - - To make a WCF service discoverable, add a to the of the service host and add a discovery endpoint. If a service is configured to send announcement messages (by adding an ) the announcement is sent when the service host is opened and closed. - - A client that wants to listen for service announcement messages hosts an announcement service and adds one or more announcement endpoints. The announcement service receives announcement messages and raises announcement events. - - A client uses the class to search for available services. The client application instantiates the class, passing in a discovery endpoint that specifies where to send discovery messages. The client calls the method, which sends a `Probe` request. Services listening for discovery messages receive this `Probe` request. If the service matches the criteria specified in the `Probe`, it sends a `ProbeMatch` message back to the client. - -## Object Model - - The WCF Discovery API defines the following classes: - -- - -- - -- - -- - -- - -- - -- - -- - -- - -- - -- - -- - -- - -- - -- - -- - -- - -- - -- - -- - -- - -- - -## AnnouncementClient - - The class provides synchronous and asynchronous methods for sending announcement messages. There are two types of announcement messages, Hello and Bye. A Hello message is sent to indicate that a service has become available and a Bye message is sent to indicate that an existing service has become unavailable. The developer creates an instance, passing an instance of as a constructor parameter. - -## AnnouncementEndpoint - - represents a standard endpoint with a fixed announcement contract. It is used by a service or client to send and receive announcement messages. By default, the class is set to use the WS_Discovery 11 protocol version. - -## AnnouncementService - - is a system-provided implementation of an announcement service that receives and processes announcement messages. When a Hello or Bye message is received, the instance calls the appropriate virtual method or , which raises announcement events. - -## DiscoveryClient - - The class is used by a client application to find and resolve available services. It provides synchronous and asynchronous methods for finding and resolving services based on the specified and respectively. The developer creates a instance and provides an instance of as a constructor parameter. - - To find a service, the developer invokes the synchronous or asynchronous `Find` method, which provides a instance that contains the search criteria to use. The creates a `Probe` message with the appropriate headers, and sends the find request. Because there can be more than one outstanding `Find` request at any time, the client correlates the received responses and validates the response. It then delivers the results to the caller of the `Find` operation using . - - To resolve a known service, the developer invokes the synchronous or asynchronous `Resolve` method that provides an instance of that contains the of the known service. The creates the `Resolve` message with the appropriate headers and sends the resolve request. The received response is correlated against the outstanding resolve requests and the result is delivered to the caller of the `Resolve` operation using . - - If a discovery proxy is present on the network and the sends the discovery request in a multicast fashion, the discovery proxy can respond with the multicast suppression Hello message. The raises the `ProxyAvailable` event when it receives Hello messages in response to outstanding `Find` or `Resolve` requests. The `ProxyAvailable` event contains the about the discovery proxy. It is up to the developer to use this information to switch from Ad hoc to Managed mode. - -## DiscoveryEndpoint - - represents a standard endpoint with a fixed discovery contract. It is used by a service or client to send or receive discovery messages. By default, is set to use mode and the WSDiscovery11 WS-Discovery version. - -## DiscoveryMessageSequenceGenerator - - is used to generate a when the service is sending out Discovery or Announcement messages. - -## DiscoveryService - - The abstract class provides a framework for receiving and processing `Probe` and `Resolve` messages. When a `Probe` message is received, creates an instance of based on the incoming message and invokes the virtual method. When a `Resolve` message is received, invokes the virtual method. You can inherit from this class to provide a custom Discovery Service implementation. - -## DiscoveryProxy - - The abstract class provides a framework for receiving and processing discovery and announcement messages. You inherit from this class when you are implementing a custom discovery proxy. When a `Probe` message is received over multicast, the class calls the `BeginShouldRedirectFind` virtual method to determine whether a multicast suppression message should to be sent. If the developer decides not to send a multicast suppression message or if the `Probe` message was received over unicast, it creates an instance of the class based on the incoming message and invokes the `OnBeginFind` virtual method. When a `Resolve` message is received over multicast, The class calls the `ShouldRedirectResolve` virtual method to determine whether a multicast suppression message should to be sent. If the developer decides not to send a multicast suppression message or if the `Resolve` message was received over unicast, it creates an instance of the class based on the incoming message and invokes the `OnBeginResolve` virtual method. When a Hello or Bye message is received, calls the appropriate virtual method (`OnBeginOnlineAnnouncement` or `OnBeingOfflineAnnouncement`), which raises announcement events. - -## DiscoveryVersion - - The class represents the discovery protocol version to use. - -## EndpointDiscoveryBehavior - - The class is used to control the discoverability of an endpoint, specify the extensions, additional contract type names. and the scopes associated with that endpoint. This behavior is added to an application endpoint to configure its . When is added to the service host, all the application endpoints hosted by the service host by default become discoverable. The developer can turn off discovery for a specific endpoint by setting the property to `false`. - -## EndpointDiscoveryMetadata - - The class provides a version-independent representation of an endpoint published by the service. It contains endpoint addresses, listen URIs, contract type names, scopes, metadata version and extensions specified by the service developer. The sent by the client during a `Probe` operation is matched against the . If the criteria matches, then the is returned to the client. The endpoint address in is matched against the endpoint address of . If the criteria matches, then the is returned to the client. - -## FindCriteria - - The class is a version-independent class used to specify the criteria used when finding a service. It fully supports the WS-Discovery-defined criteria for matching services. It also has extensions that developers can use to specify custom values that can be used during the matching process. The developer can provide the termination criteria for the `Find` operation by specifying the , which specifies the total number of services the developer is looking for or that specifies the , which is the value that specifies how long the client waits for responses. - -## FindRequestContext - - The class is instantiated by the discovery service based on the `Probe` message it receives when a client initiates a `Find` operation. It contains an instance of that was specified by the client. - -## FindResponse - - The class is returned to the caller of with the responses of the `Find` operation. It is also present in . It contains a collection of , which is the collection of discovered endpoints and a dictionary of and . - -## ResolveCriteria - - The class is a version-independent class used to specify the criteria used when resolving an already known service. It contains the endpoint address of the known service. The developer can provide the termination criteria for the resolve operation by specifying the , which specifies how long the client waits for responses. - -## ResolveResponse - - The is returned to the caller of the method with the response of the `Resolve` operation. It is also present in . It contains an instance of , which is the discovered endpoints and an instance of . - -## ServiceDiscoveryBehavior - - The class allows the developer to add the discovery feature to a service. You add this behavior to the . The class iterates over the application endpoints added to the service host and creates a collection of from the discoverable endpoints. All endpoints are discoverable by default. The discoverability of a particular endpoint can be controlled by adding the to that particular endpoint. If announcement endpoints are added to then the announcement of all discoverable endpoints is sent over each of the announcement endpoints when the service host is opened or closed. - -## UdpAnnouncementEndpoint - - The class is a standard announcement endpoint that is pre-configured for announcement over a UDP multicast binding. By default, is set to use the WSApril2005 WS_Discovery version. - -## UdpDiscoveryEndpoint +WCF Discovery consists of a set of types that provide a unified programming model that allows you to write services that are discoverable at runtime and clients that find and use these services. + +## Making a Service Discoverable and Finding Services + + To make a WCF service discoverable, add a to the of the service host and add a discovery endpoint. If a service is configured to send announcement messages (by adding an ) the announcement is sent when the service host is opened and closed. + + A client that wants to listen for service announcement messages hosts an announcement service and adds one or more announcement endpoints. The announcement service receives announcement messages and raises announcement events. + + A client uses the class to search for available services. The client application instantiates the class, passing in a discovery endpoint that specifies where to send discovery messages. The client calls the method, which sends a `Probe` request. Services listening for discovery messages receive this `Probe` request. If the service matches the criteria specified in the `Probe`, it sends a `ProbeMatch` message back to the client. + +## Object Model + + The WCF Discovery API defines the following classes: + +- + +- + +- + +- + +- + +- + +- + +- + +- + +- + +- + +- + +- + +- + +- + +- + +- + +- + +- + +- + +- + +- + +## AnnouncementClient + + The class provides synchronous and asynchronous methods for sending announcement messages. There are two types of announcement messages, Hello and Bye. A Hello message is sent to indicate that a service has become available and a Bye message is sent to indicate that an existing service has become unavailable. The developer creates an instance, passing an instance of as a constructor parameter. + +## AnnouncementEndpoint + + represents a standard endpoint with a fixed announcement contract. It is used by a service or client to send and receive announcement messages. By default, the class is set to use the WS_Discovery 11 protocol version. + +## AnnouncementService + + is a system-provided implementation of an announcement service that receives and processes announcement messages. When a Hello or Bye message is received, the instance calls the appropriate virtual method or , which raises announcement events. + +## DiscoveryClient + + The class is used by a client application to find and resolve available services. It provides synchronous and asynchronous methods for finding and resolving services based on the specified and respectively. The developer creates a instance and provides an instance of as a constructor parameter. + + To find a service, the developer invokes the synchronous or asynchronous `Find` method, which provides a instance that contains the search criteria to use. The creates a `Probe` message with the appropriate headers, and sends the find request. Because there can be more than one outstanding `Find` request at any time, the client correlates the received responses and validates the response. It then delivers the results to the caller of the `Find` operation using . + + To resolve a known service, the developer invokes the synchronous or asynchronous `Resolve` method that provides an instance of that contains the of the known service. The creates the `Resolve` message with the appropriate headers and sends the resolve request. The received response is correlated against the outstanding resolve requests and the result is delivered to the caller of the `Resolve` operation using . + + If a discovery proxy is present on the network and the sends the discovery request in a multicast fashion, the discovery proxy can respond with the multicast suppression Hello message. The raises the `ProxyAvailable` event when it receives Hello messages in response to outstanding `Find` or `Resolve` requests. The `ProxyAvailable` event contains the about the discovery proxy. It is up to the developer to use this information to switch from Ad hoc to Managed mode. + +## DiscoveryEndpoint + + represents a standard endpoint with a fixed discovery contract. It is used by a service or client to send or receive discovery messages. By default, is set to use mode and the WSDiscovery11 WS-Discovery version. + +## DiscoveryMessageSequenceGenerator + + is used to generate a when the service is sending out Discovery or Announcement messages. + +## DiscoveryService + + The abstract class provides a framework for receiving and processing `Probe` and `Resolve` messages. When a `Probe` message is received, creates an instance of based on the incoming message and invokes the virtual method. When a `Resolve` message is received, invokes the virtual method. You can inherit from this class to provide a custom Discovery Service implementation. + +## DiscoveryProxy + + The abstract class provides a framework for receiving and processing discovery and announcement messages. You inherit from this class when you are implementing a custom discovery proxy. When a `Probe` message is received over multicast, the class calls the `BeginShouldRedirectFind` virtual method to determine whether a multicast suppression message should to be sent. If the developer decides not to send a multicast suppression message or if the `Probe` message was received over unicast, it creates an instance of the class based on the incoming message and invokes the `OnBeginFind` virtual method. When a `Resolve` message is received over multicast, The class calls the `ShouldRedirectResolve` virtual method to determine whether a multicast suppression message should to be sent. If the developer decides not to send a multicast suppression message or if the `Resolve` message was received over unicast, it creates an instance of the class based on the incoming message and invokes the `OnBeginResolve` virtual method. When a Hello or Bye message is received, calls the appropriate virtual method (`OnBeginOnlineAnnouncement` or `OnBeingOfflineAnnouncement`), which raises announcement events. + +## DiscoveryVersion + + The class represents the discovery protocol version to use. + +## EndpointDiscoveryBehavior + + The class is used to control the discoverability of an endpoint, specify the extensions, additional contract type names. and the scopes associated with that endpoint. This behavior is added to an application endpoint to configure its . When is added to the service host, all the application endpoints hosted by the service host by default become discoverable. The developer can turn off discovery for a specific endpoint by setting the property to `false`. + +## EndpointDiscoveryMetadata + + The class provides a version-independent representation of an endpoint published by the service. It contains endpoint addresses, listen URIs, contract type names, scopes, metadata version and extensions specified by the service developer. The sent by the client during a `Probe` operation is matched against the . If the criteria matches, then the is returned to the client. The endpoint address in is matched against the endpoint address of . If the criteria matches, then the is returned to the client. + +## FindCriteria + + The class is a version-independent class used to specify the criteria used when finding a service. It fully supports the WS-Discovery-defined criteria for matching services. It also has extensions that developers can use to specify custom values that can be used during the matching process. The developer can provide the termination criteria for the `Find` operation by specifying the , which specifies the total number of services the developer is looking for or that specifies the , which is the value that specifies how long the client waits for responses. + +## FindRequestContext + + The class is instantiated by the discovery service based on the `Probe` message it receives when a client initiates a `Find` operation. It contains an instance of that was specified by the client. + +## FindResponse + + The class is returned to the caller of with the responses of the `Find` operation. It is also present in . It contains a collection of , which is the collection of discovered endpoints and a dictionary of and . + +## ResolveCriteria + + The class is a version-independent class used to specify the criteria used when resolving an already known service. It contains the endpoint address of the known service. The developer can provide the termination criteria for the resolve operation by specifying the , which specifies how long the client waits for responses. + +## ResolveResponse + + The is returned to the caller of the method with the response of the `Resolve` operation. It is also present in . It contains an instance of , which is the discovered endpoints and an instance of . + +## ServiceDiscoveryBehavior + + The class allows the developer to add the discovery feature to a service. You add this behavior to the . The class iterates over the application endpoints added to the service host and creates a collection of from the discoverable endpoints. All endpoints are discoverable by default. The discoverability of a particular endpoint can be controlled by adding the to that particular endpoint. If announcement endpoints are added to then the announcement of all discoverable endpoints is sent over each of the announcement endpoints when the service host is opened or closed. + +## UdpAnnouncementEndpoint + + The class is a standard announcement endpoint that is pre-configured for announcement over a UDP multicast binding. By default, is set to use the WSApril2005 WS_Discovery version. + +## UdpDiscoveryEndpoint The class is a standard discovery endpoint that is pre-configured for discovery over a UDP multicast binding. By default, is set to use the WSDiscovery11 WS-Discovery version and mode. diff --git a/docs/framework/wcf/feature-details/wcf-discovery.md b/docs/framework/wcf/feature-details/wcf-discovery.md index 8c9a3db89cede..ef2d0a7f69445 100644 --- a/docs/framework/wcf/feature-details/wcf-discovery.md +++ b/docs/framework/wcf/feature-details/wcf-discovery.md @@ -2,7 +2,7 @@ description: "Learn more about: WCF Discovery" title: "WCF Discovery" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "WCF [WCF], discovery" - "Windows Communication Foundation [WCF], discovery" - "discovery [WCF]" @@ -10,27 +10,27 @@ ms.assetid: 462c4913-f388-45a9-9042-28ae96a4e735 --- # WCF Discovery -Windows Communication Foundation (WCF) provides support to enable services to be discoverable at run time in an interoperable way using the WS-Discovery protocol. WCF services can announce their availability to the network using a multicast message or to a discovery proxy server. Client applications can search the network or a discovery proxy server to find services that meet a set of criteria. The topics in this section provide an overview and describe the programming model for this feature in detail. - -## In This Section - - [WCF Discovery Overview](wcf-discovery-overview.md) - Provides an overview of WS-Discovery support provided by WCF. - - [WCF Discovery Object Model](wcf-discovery-object-model.md) - Describes the classes in the object model and extensibility of WS-Discovery support. - - [How to: Programmatically Add Discoverability to a WCF Service and Client](how-to-programmatically-add-discoverability-to-a-wcf-service-and-client.md) - Shows how to make a Windows Communication Foundation (WCF) service discoverable. - - [Implementing a Discovery Proxy](implementing-a-discovery-proxy.md) - Describes the steps required to implement a discovery proxy, a discoverable service that registers with the discovery proxy, and a client that uses the discovery proxy to find the discoverable service. - - [Discovery Versioning](discovery-versioning.md) - Provides a brief overview of a prototype implementation of some new discovery features. It also gives an overview on how to select the discovery version to use. - - [Configuring Discovery in a Configuration File](configuring-discovery-in-a-configuration-file.md) - Shows how to configure Discovery in configuration. - - [Using the Discovery Client Channel](using-the-discovery-client-channel.md) +Windows Communication Foundation (WCF) provides support to enable services to be discoverable at runtime in an interoperable way using the WS-Discovery protocol. WCF services can announce their availability to the network using a multicast message or to a discovery proxy server. Client applications can search the network or a discovery proxy server to find services that meet a set of criteria. The topics in this section provide an overview and describe the programming model for this feature in detail. + +## In This Section + + [WCF Discovery Overview](wcf-discovery-overview.md) + Provides an overview of WS-Discovery support provided by WCF. + + [WCF Discovery Object Model](wcf-discovery-object-model.md) + Describes the classes in the object model and extensibility of WS-Discovery support. + + [How to: Programmatically Add Discoverability to a WCF Service and Client](how-to-programmatically-add-discoverability-to-a-wcf-service-and-client.md) + Shows how to make a Windows Communication Foundation (WCF) service discoverable. + + [Implementing a Discovery Proxy](implementing-a-discovery-proxy.md) + Describes the steps required to implement a discovery proxy, a discoverable service that registers with the discovery proxy, and a client that uses the discovery proxy to find the discoverable service. + + [Discovery Versioning](discovery-versioning.md) + Provides a brief overview of a prototype implementation of some new discovery features. It also gives an overview on how to select the discovery version to use. + + [Configuring Discovery in a Configuration File](configuring-discovery-in-a-configuration-file.md) + Shows how to configure Discovery in configuration. + + [Using the Discovery Client Channel](using-the-discovery-client-channel.md) Shows how to use a Discovery Client Channel when writing a WCF client application. diff --git a/docs/framework/wcf/fundamental-concepts.md b/docs/framework/wcf/fundamental-concepts.md index 028a9b9f5a77e..f754889d1bf0e 100644 --- a/docs/framework/wcf/fundamental-concepts.md +++ b/docs/framework/wcf/fundamental-concepts.md @@ -50,24 +50,24 @@ WCF supports several messaging patterns, including request-reply, one-way, and d Other concepts and terms used in the WCF documentation include the following: -**Message** +**Message** A self-contained unit of data that can consist of several parts, including a body and headers. -**Service** +**Service** A construct that exposes one or more endpoints, with each endpoint exposing one or more service operations. -**Endpoint** +**Endpoint** A construct at which messages are sent or received (or both). It comprises a location (an address) that defines where messages can be sent, a specification of the communication mechanism (a binding) that describes how messages should be sent, and a definition for a set of messages that can be sent or received (or both) at that location (a service contract) that describes what message can be sent. A WCF service is exposed to the world as a collection of endpoints. -**Application endpoint** +**Application endpoint** An endpoint exposed by the application and that corresponds to a service contract implemented by the application. -**Infrastructure endpoint** +**Infrastructure endpoint** An endpoint that is exposed by the infrastructure to facilitate functionality that is needed or provided by the service that does not relate to a service contract. For example, a service might have an infrastructure endpoint that provides metadata information. -**Address** +**Address** Specifies the location where messages are received. It is specified as a Uniform Resource Identifier (URI). The URI schema part names the transport mechanism to use to reach the address, such as HTTP and TCP. The hierarchical part of the URI contains a unique location whose format is dependent on the transport mechanism. The endpoint address enables you to create unique endpoint addresses for each endpoint in a service or, under certain conditions, to share an address across endpoints. The following example shows an address using the HTTPS protocol with a non-default port: @@ -76,82 +76,82 @@ The endpoint address enables you to create unique endpoint addresses for each en HTTPS://cohowinery:8005/ServiceModelSamples/CalculatorService ``` -**Binding** +**Binding** Defines how an endpoint communicates to the world. It is constructed of a set of components called binding elements that "stack" one on top of the other to create the communication infrastructure. At the very least, a binding defines the transport (such as HTTP or TCP) and the encoding being used (such as text or binary). A binding can contain binding elements that specify details like the security mechanisms used to secure messages, or the message pattern used by an endpoint. For more information, see [Configuring Services](configuring-services.md). -**Binding element** +**Binding element** Represents a particular piece of the binding, such as a transport, an encoding, an implementation of an infrastructure-level protocol (such as WS-ReliableMessaging), or any other component of the communication stack. -**Behaviors** - A component that controls various run-time aspects of a service, an endpoint, a particular operation, or a client. Behaviors are grouped according to scope: common behaviors affect all endpoints globally, service behaviors affect only service-related aspects, endpoint behaviors affect only endpoint-related properties, and operation-level behaviors affect particular operations. For example, one service behavior is throttling, which specifies how a service reacts when an excess of messages threaten to overwhelm its handling capabilities. An endpoint behavior, on the other hand, controls only aspects that are relevant to endpoints, such as how and where to find a security credential. +**Behaviors** + A component that controls various runtime aspects of a service, an endpoint, a particular operation, or a client. Behaviors are grouped according to scope: common behaviors affect all endpoints globally, service behaviors affect only service-related aspects, endpoint behaviors affect only endpoint-related properties, and operation-level behaviors affect particular operations. For example, one service behavior is throttling, which specifies how a service reacts when an excess of messages threaten to overwhelm its handling capabilities. An endpoint behavior, on the other hand, controls only aspects that are relevant to endpoints, such as how and where to find a security credential. -**System-provided bindings** +**System-provided bindings** WCF includes a number of system-provided bindings. These are collections of binding elements that are optimized for specific scenarios. For example, the is designed for interoperability with services that implement various WS-\* specifications. These predefined bindings save time by presenting only those options that can be correctly applied to the specific scenario. If a predefined binding does not meet your requirements, you can create your own custom binding. -**Configuration versus coding** +**Configuration versus coding** Control of an application can be done either through coding, through configuration, or through a combination of both. Configuration has the advantage of allowing someone other than the developer (for example, a network administrator) to set client and service parameters after the code is written and without having to recompile. Configuration not only enables you to set values like endpoint addresses, but also allows further control by enabling you to add endpoints, bindings, and behaviors. Coding allows the developer to retain strict control over all components of the service or client, and any settings done through the configuration can be inspected and if needed overridden by the code. -**Service operation** +**Service operation** A procedure defined in a service's code that implements the functionality for an operation. This operation is exposed to clients as methods on a WCF client. The method can return a value, and can take an optional number of arguments, or take no arguments, and return no response. For example, an operation that functions as a simple "Hello" can be used as a notification of a client's presence and to begin a series of operations. -**Service contract** +**Service contract** Ties together multiple related operations into a single functional unit. The contract can define service-level settings, such as the namespace of the service, a corresponding callback contract, and other such settings. In most cases, the contract is defined by creating an interface in the programming language of your choice and applying the attribute to the interface. The actual service code results by implementing the interface. -**Operation contract** +**Operation contract** An operation contract defines the parameters and return type of an operation. When creating an interface that defines the service contract, you signify an operation contract by applying the attribute to each method definition that is part of the contract. The operations can be modeled as taking a single message and returning a single message, or as taking a set of types and returning a type. In the latter case, the system will determine the format for the messages that need to be exchanged for that operation. -**Message contract** +**Message contract** Describes the format of a message. For example, it declares whether message elements should go in headers versus the body, what level of security should be applied to what elements of the message, and so on. -**Fault contract** +**Fault contract** Can be associated with a service operation to denote errors that can be returned to the caller. An operation can have zero or more faults associated with it. These errors are SOAP faults that are modeled as exceptions in the programming model. -**Data contract** +**Data contract** The descriptions in metadata of the data types that a service uses. This enables others to interoperate with the service. The data types can be used in any part of a message, for example, as parameters or return types. If the service is using only simple types, there is no need to explicitly use data contracts. -**Hosting** +**Hosting** A service must be hosted in some process. A _host_ is an application that controls the lifetime of the service. Services can be self-hosted or managed by an existing hosting process. -**Self-hosted service** +**Self-hosted service** A service that runs within a process application that the developer created. The developer controls its lifetime, sets the properties of the service, opens the service (which sets it into a listening mode), and closes the service. -**Hosting process** +**Hosting process** An application that is designed to host services. These include Internet Information Services (IIS), Windows Activation Services (WAS), and Windows Services. In these hosted scenarios, the host controls the lifetime of the service. For example, using IIS you can set up a virtual directory that contains the service assembly and configuration file. When a message is received, IIS starts the service and controls its lifetime. -**Instancing** +**Instancing** A service has an instancing model. There are three instancing models: "single," in which a single CLR object services all the clients; "per call," in which a new CLR object is created to handle each client call; and "per session," in which a set of CLR objects is created, one for each separate session. The choice of an instancing model depends on the application requirements and the expected usage pattern of the service. -**Client application** +**Client application** A program that exchanges messages with one or more endpoints. The client application begins by creating an instance of a WCF client and calling methods of the WCF client. It is important to note that a single application can be both a client and a service. -**Channel** +**Channel** A concrete implementation of a binding element. The binding represents the configuration, and the channel is the implementation associated with that configuration. Therefore, there is a channel associated with each binding element. Channels stack on top of each other to create the concrete implementation of the binding: the channel stack. -**WCF client** +**WCF client** A client-application construct that exposes the service operations as methods (in the .NET Framework programming language of your choice, such as Visual Basic or Visual C#). Any application can host a WCF client, including an application that hosts a service. Therefore, it is possible to create a service that includes WCF clients of other services. A WCF client can be automatically generated by using the [ServiceModel Metadata Utility Tool (Svcutil.exe)](servicemodel-metadata-utility-tool-svcutil-exe.md) and pointing it at a running service that publishes metadata. -**Metadata** +**Metadata** In a service, describes the characteristics of the service that an external entity needs to understand to communicate with the service. Metadata can be consumed by the [ServiceModel Metadata Utility Tool (Svcutil.exe)](servicemodel-metadata-utility-tool-svcutil-exe.md) to generate a WCF client and accompanying configuration that a client application can use to interact with the service. The metadata exposed by the service includes XML schema documents, which define the data contract of the service, and WSDL documents, which describe the methods of the service. When enabled, metadata for the service is automatically generated by WCF by inspecting the service and its endpoints. To publish metadata from a service, you must explicitly enable the metadata behavior. -**Security** +**Security** In WCF, includes confidentiality (encryption of messages to prevent eavesdropping), integrity (the means for detection of tampering with the message), authentication (the means for validation of servers and clients), and authorization (the control of access to resources). These functions are provided by either leveraging existing security mechanisms, such as TLS over HTTP (also known as HTTPS), or by implementing one or more of the various WS-\* security specifications. -**Transport security mode** +**Transport security mode** Specifies that confidentiality, integrity, and authentication are provided by the transport layer mechanisms (such as HTTPS). When using a transport like HTTPS, this mode has the advantage of being efficient in its performance, and well understood because of its prevalence on the Internet. The disadvantage is that this kind of security is applied separately on each hop in the communication path, making the communication susceptible to a "man in the middle" attack. -**Message security mode** +**Message security mode** Specifies that security is provided by implementing one or more of the security specifications, such as the specification named [Web Services Security: SOAP Message Security](http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0.pdf). Each message contains the necessary mechanisms to provide security during its transit, and to enable the receivers to detect tampering and to decrypt the messages. In this sense, the security is encapsulated within every message, providing end-to-end security across multiple hops. Because security information becomes part of the message, it is also possible to include multiple kinds of credentials with the message (these are referred to as _claims_). This approach also has the advantage of enabling the message to travel securely over any transport, including multiple transports between its origin and destination. The disadvantage of this approach is the complexity of the cryptographic mechanisms employed, resulting in performance implications. -**Transport with message credential security mode** +**Transport with message credential security mode** Specifies the use of the transport layer to provide confidentiality, authentication, and integrity of the messages, while each of the messages can contain multiple credentials (claims) required by the receivers of the message. -**WS-\*** +**WS-\*** Shorthand for the growing set of Web Service (WS) specifications, such as WS-Security, WS-ReliableMessaging, and so on, that are implemented in WCF. ## See also diff --git a/docs/framework/wcf/getting-started-tutorial.md b/docs/framework/wcf/getting-started-tutorial.md index 8bdc9e3bde9f9..7c4351500de4d 100644 --- a/docs/framework/wcf/getting-started-tutorial.md +++ b/docs/framework/wcf/getting-started-tutorial.md @@ -1,6 +1,6 @@ --- title: "Tutorial: Get started with Windows Communication Foundation applications" -description: These tutorials provides an introduction for creating WCF applications. +description: These tutorials provides an introduction for creating WCF applications. ms.date: 01/25/2019 helpviewer_keywords: - "WCF [WCF], get started" @@ -34,7 +34,7 @@ The first three tutorials describe how to define a WCF service contract, how to - [Tutorial: Host and run a basic service](how-to-host-and-run-a-basic-wcf-service.md) - Configure an endpoint for the service and host the service in a console application. For a service to become active, you must configure it and host it within a run-time environment. This run-time environment creates the service and controls its context and lifetime. + Configure an endpoint for the service and host the service in a console application. For a service to become active, you must configure it and host it within a runtime environment. This runtime environment creates the service and controls its context and lifetime. The next two tutorials describe how to create, configure, and use a client application to call the operations the service exposes. Services publish metadata that define the information a client application needs to communicate with the service. Visual Studio automates the process of accessing this metadata and uses it to construct the client application for the service. If you decide not to use Visual Studio, you can use the [ServiceModel Metadata Utility tool (*Svcutil.exe*)](servicemodel-metadata-utility-tool-svcutil-exe.md) instead. diff --git a/docs/framework/wcf/glossary.md b/docs/framework/wcf/glossary.md index 034d00a8e279d..58bd7d5b15876 100644 --- a/docs/framework/wcf/glossary.md +++ b/docs/framework/wcf/glossary.md @@ -18,7 +18,7 @@ The following terms are defined for Windows Communication Foundation documentati |----------|----------------| |address|Specifies the location where messages are received. It is specified as a Uniform Resource Identifier (URI). The URI schema part names the transport mechanism to use to reach the address, such as HTTP and TCP. The hierarchical part of the URI contains a unique location whose format is dependent on the transport mechanism.| |application endpoint|An endpoint exposed by the application and that corresponds to a service contract implemented by the application.| -|behavior|A behavior is a component that controls various run-time aspects of a service, an endpoint, a particular operation, or a client. Behaviors are grouped according to scope: common behaviors affect all endpoints globally, service behaviors affect only service-related aspects, endpoint behaviors affect only endpoint-related properties, and operation-level behaviors affect particular operations.| +|behavior|A behavior is a component that controls various runtime aspects of a service, an endpoint, a particular operation, or a client. Behaviors are grouped according to scope: common behaviors affect all endpoints globally, service behaviors affect only service-related aspects, endpoint behaviors affect only endpoint-related properties, and operation-level behaviors affect particular operations.| |binding|Defines which communication protocols are used to communicate with WCF services. It is constructed of a set of components called binding elements that stack one on top of the other to create the communication infrastructure. See endpoint.| |channel|A concrete implementation of a binding element. The binding represents the configuration, and the channel is the implementation associated with that configuration. Therefore, there is a channel associated with each binding element. Channels stack on top of each other to create the concrete implementation of the binding: the channel stack.| |claims-based security|Allows authorized access to protected resources based on claims.| @@ -27,7 +27,7 @@ The following terms are defined for Windows Communication Foundation documentati |configuration|Configuration has the advantage of allowing someone other than the developer (for example, a network administrator) to set client and service parameters after the code is written and without having to recompile. Configuration not only enables you to set values like endpoint addresses, but also allows further control by enabling you to add endpoints, bindings, and behaviors. Control of an application can be done either through configuration, through coding, or through a combination of both.| |contract|A contract is a specification of support for the particular type of contract that it is. A service contract, for example, is a specification for a group of operations. In WCF, contracts have a hierarchy that is mirrored in the description objects located in the System.ServiceModel.Description namespace. A service contract is the largest contract scope in WCF. Each service operation in a service contract has an operation contract, which specifies the messages -- including fault messages -- the operation can exchange, and in which direction. Each message in an operation has a message contract, a specification for the structure of the SOAP message envelope, and each message contract has a data contract, which specifies the data structures contained in the messages.| |data contract|The data types a service uses must be described in metadata to enable others to interoperate with the service. The descriptions of the data types are known as the data contract, and the types can be used in any part of a message, for example, as parameters or return types. If the service is using only simple types, there is no need to explicitly use data contracts.| -|declarative application|An application that is described sufficiently to be created at run time without running imperative instructions.| +|declarative application|An application that is described sufficiently to be created at runtime without running imperative instructions.| |endpoint|Consists of an address, a binding, and a contract used for communicating with a WCF service.| |endpoint address|Enables you to create unique endpoint addresses for each endpoint in a service, or under certain conditions share an address across endpoints.| |fault contract|A fault contract can be associated with a service operation to denote errors that can be returned to the caller. An operation can have zero or more faults associated with it. These errors are SOAP faults that are modeled as exceptions in the programming model. The exception is converted into a SOAP fault that can then be sent to the client.| diff --git a/docs/framework/wcf/hosting-services.md b/docs/framework/wcf/hosting-services.md index a8fea49689a05..86cbe836f22c0 100644 --- a/docs/framework/wcf/hosting-services.md +++ b/docs/framework/wcf/hosting-services.md @@ -8,9 +8,9 @@ ms.assetid: 192be927-6be2-4fda-98f0-e513c4881acc --- # Hosting services -To become active, a service must be hosted within a run-time environment that creates it and controls its context and lifetime. Windows Communication Foundation (WCF) services are designed to run in any Windows process that supports managed code. +To become active, a service must be hosted within a runtime environment that creates it and controls its context and lifetime. Windows Communication Foundation (WCF) services are designed to run in any Windows process that supports managed code. -WCF provides a unified programming model for building service-oriented applications. This programming model remains consistent and is independent of the run-time environment in which the service is deployed. In practice, this means that the code for your services looks much the same whatever the hosting option. +WCF provides a unified programming model for building service-oriented applications. This programming model remains consistent and is independent of the runtime environment in which the service is deployed. In practice, this means that the code for your services looks much the same whatever the hosting option. These hosting options range from running inside a console application to server environments such as a Windows service running within a worker process managed by Internet Information Services (IIS) or by Windows Process Activation Service (WAS). Developers choose the hosting environment that satisfies the service's deployment requirements. These requirements might derive from the platform on which the application is deployed, the transport on which it must send and receive messages, or on the type of process recycling and other process management required to ensure adequate availability, or on some other management or reliability requirements. The next section provides information and guidance on hosting options. diff --git a/docs/framework/wcf/privacy-information.md b/docs/framework/wcf/privacy-information.md index f81e10b40d19f..4c18a7afd56de 100644 --- a/docs/framework/wcf/privacy-information.md +++ b/docs/framework/wcf/privacy-information.md @@ -101,7 +101,7 @@ Microsoft is committed to protecting end user privacy. When you build an applica ### Tracing - The diagnostics feature of the WCF infrastructure logs messages that pass through the transport and service model layers, and the activities and events associated with these messages. This feature is turned off by default. It is enabled using the application’s configuration file and the tracing behavior may be modified using the WCF WMI provider at run time. When enabled, the tracing infrastructure emits a diagnostic trace that contains messages, activities, and processing events to configured listeners. The format and location of the output are determined by the administrator’s listener configuration choices, but is typically an XML formatted file. The administrator is responsible for setting the access control list (ACL) on the trace files. In particular, when hosted by Windows Activation System (WAS), the administrator should make sure the files are not served from the public virtual root directory if that is not desired. + The diagnostics feature of the WCF infrastructure logs messages that pass through the transport and service model layers, and the activities and events associated with these messages. This feature is turned off by default. It is enabled using the application’s configuration file and the tracing behavior may be modified using the WCF WMI provider at runtime. When enabled, the tracing infrastructure emits a diagnostic trace that contains messages, activities, and processing events to configured listeners. The format and location of the output are determined by the administrator’s listener configuration choices, but is typically an XML formatted file. The administrator is responsible for setting the access control list (ACL) on the trace files. In particular, when hosted by Windows Activation System (WAS), the administrator should make sure the files are not served from the public virtual root directory if that is not desired. There are two types of tracing: Message logging and Service Model diagnostic tracing, described in the following section. Each type is configured through its own trace source: and . Both of these logging trace sources capture data that is local to the application. diff --git a/docs/framework/wcf/samples/channels-extensibility.md b/docs/framework/wcf/samples/channels-extensibility.md index c53d980eac325..d0e68e5803e43 100644 --- a/docs/framework/wcf/samples/channels-extensibility.md +++ b/docs/framework/wcf/samples/channels-extensibility.md @@ -26,4 +26,4 @@ Demonstrates how to limit the amount of memory used to buffer large messages sen Demonstrates how to build a custom protocol channel to use HTTP cookies for session management. [Custom Message Interceptor](custom-message-interceptor.md) -Demonstrates how to implement a custom binding element that creates channel factories and channel listeners to intercept all incoming and outgoing messages at a particular point in the run-time stack. +Demonstrates how to implement a custom binding element that creates channel factories and channel listeners to intercept all incoming and outgoing messages at a particular point in the runtime stack. diff --git a/docs/framework/wcf/samples/configuration-sample.md b/docs/framework/wcf/samples/configuration-sample.md index afb2b618d3d3f..3531e46e3cfa6 100644 --- a/docs/framework/wcf/samples/configuration-sample.md +++ b/docs/framework/wcf/samples/configuration-sample.md @@ -20,7 +20,7 @@ To enable discovery, a few changes must be made in the application configuration - A discovery endpoint must be added to the `` element. This is a standard endpoint. This is a system endpoint that the runtime associates with the discovery service. The discovery service listens for messages on this endpoint. -- A `` behavior is added to the `` section. This enables the service to be discovered at run time and uses the discovery endpoint mentioned previously to listen for discovery `Probe` and `Resolve` messages. With these two additions, the service is discoverable at the discovery endpoint specified. +- A `` behavior is added to the `` section. This enables the service to be discovered at runtime and uses the discovery endpoint mentioned previously to listen for discovery `Probe` and `Resolve` messages. With these two additions, the service is discoverable at the discovery endpoint specified. The following config snippet shows a service with an application endpoint and a discovery endpoint defined: diff --git a/docs/framework/wcf/samples/custom-message-encoder-custom-text-encoder.md b/docs/framework/wcf/samples/custom-message-encoder-custom-text-encoder.md index 1113566dcc9a9..fa26f45068443 100644 --- a/docs/framework/wcf/samples/custom-message-encoder-custom-text-encoder.md +++ b/docs/framework/wcf/samples/custom-message-encoder-custom-text-encoder.md @@ -179,7 +179,7 @@ public class CustomTextMessageEncoderFactory : MessageEncoderFactory ## Message Encoding Binding Element -The binding elements allow the configuration of the WCF run-time stack. To use the custom message encoder in a WCF application, a binding element is required that creates the message encoder factory with the appropriate settings at the appropriate level in the run-time stack. +The binding elements allow the configuration of the WCF runtime stack. To use the custom message encoder in a WCF application, a binding element is required that creates the message encoder factory with the appropriate settings at the appropriate level in the runtime stack. The `CustomTextMessageBindingElement` derives from the base class and inherits from the class. This allows other WCF components to recognize this binding element as being a message encoding binding element. The implementation of returns an instance of the matching message encoder factory with appropriate settings. diff --git a/docs/framework/wcf/samples/custom-message-interceptor.md b/docs/framework/wcf/samples/custom-message-interceptor.md index 2fbe75925be22..59ca044120d06 100644 --- a/docs/framework/wcf/samples/custom-message-interceptor.md +++ b/docs/framework/wcf/samples/custom-message-interceptor.md @@ -6,9 +6,9 @@ ms.assetid: 73f20972-53f8-475a-8bfe-c133bfa225b0 --- # Custom Message Interceptor -The [MessageInterceptor sample](https://github.com/dotnet/samples/tree/main/framework/wcf) demonstrates the use of the channel extensibility model. In particular, it shows how to implement a custom binding element that creates channel factories and channel listeners to intercept all incoming and outgoing messages at a particular point in the run-time stack. The sample also includes a client and server that demonstrate the use of these custom factories. +The [MessageInterceptor sample](https://github.com/dotnet/samples/tree/main/framework/wcf) demonstrates the use of the channel extensibility model. In particular, it shows how to implement a custom binding element that creates channel factories and channel listeners to intercept all incoming and outgoing messages at a particular point in the runtime stack. The sample also includes a client and server that demonstrate the use of these custom factories. -In this sample, both the client and the service are console programs (.exe). The client and service both make use of a common library (.dll) that contains the custom binding element and its associated run-time objects. +In this sample, both the client and the service are console programs (.exe). The client and service both make use of a common library (.dll) that contains the custom binding element and its associated runtime objects. > [!NOTE] > The setup procedure and build instructions for this sample are located at the end of this topic. @@ -47,7 +47,7 @@ class InterceptingChannelListener : ListenerFactoryBase ## Adding a Binding Element -The sample defines a custom binding element: `InterceptingBindingElement`. `InterceptingBindingElement` takes a `ChannelMessageInterceptor` as an input, and uses this `ChannelMessageInterceptor` to manipulate messages that pass through it. This is the only class that must be public. The factory, listener, and channels can all be internal implementations of the public run-time interfaces. +The sample defines a custom binding element: `InterceptingBindingElement`. `InterceptingBindingElement` takes a `ChannelMessageInterceptor` as an input, and uses this `ChannelMessageInterceptor` to manipulate messages that pass through it. This is the only class that must be public. The factory, listener, and channels can all be internal implementations of the public runtime interfaces. ```csharp public class InterceptingBindingElement : BindingElement @@ -102,7 +102,7 @@ You can access it from configuration as follows: ``` -The client and server both use this newly created configuration section to insert the custom factories into the lowest-level of their run-time channel stacks (above the transport level). +The client and server both use this newly created configuration section to insert the custom factories into the lowest-level of their runtime channel stacks (above the transport level). ```xml diff --git a/docs/framework/wcf/samples/custom-service-host.md b/docs/framework/wcf/samples/custom-service-host.md index 2f47f95ddcdea..2b5b2ee9f4f93 100644 --- a/docs/framework/wcf/samples/custom-service-host.md +++ b/docs/framework/wcf/samples/custom-service-host.md @@ -6,7 +6,7 @@ ms.assetid: fe16ff50-7156-4499-9c32-13d8a79dc100 --- # Custom Service Host -The [CustomServiceHost sample](https://github.com/dotnet/samples/tree/main/framework/wcf) demonstrates how to use a custom derivative of the class to alter the run-time behavior of a service. This approach provides a reusable alternative to configuring a large number of services in a common way. The sample also demonstrates how to use the class to use a custom ServiceHost in the Internet Information Services (IIS) or Windows Process Activation Service (WAS) hosting environment. +The [CustomServiceHost sample](https://github.com/dotnet/samples/tree/main/framework/wcf) demonstrates how to use a custom derivative of the class to alter the runtime behavior of a service. This approach provides a reusable alternative to configuring a large number of services in a common way. The sample also demonstrates how to use the class to use a custom ServiceHost in the Internet Information Services (IIS) or Windows Process Activation Service (WAS) hosting environment. ## About the scenario @@ -19,7 +19,7 @@ Enabling metadata publishing for a large number of services involves adding the ## Implementing a custom ServiceHost -The class exposes several useful virtual methods that inheritors can override to alter the run-time behavior of a service. For example, the `ApplyConfiguration`() method reads service configuration information from the configuration store and alters the host's accordingly. The default implementation reads configuration from the application's configuration file. Custom implementations can override `ApplyConfiguration`() to further alter the using imperative code or even replace the default configuration store entirely. For example, to read a service's endpoint configuration from a database instead of the application's configuration file. +The class exposes several useful virtual methods that inheritors can override to alter the runtime behavior of a service. For example, the `ApplyConfiguration`() method reads service configuration information from the configuration store and alters the host's accordingly. The default implementation reads configuration from the application's configuration file. Custom implementations can override `ApplyConfiguration`() to further alter the using imperative code or even replace the default configuration store entirely. For example, to read a service's endpoint configuration from a database instead of the application's configuration file. In this sample, we want to build a custom ServiceHost that adds the ServiceMetadataBehavior (which enables metadata publishing) even if this behavior is not explicitly added in the service's configuration file. To accomplish this, create a new class that inherits from and overrides `ApplyConfiguration`(). @@ -146,7 +146,7 @@ Here we have added an additional `Factory` attribute to the `@ServiceHost` direc ## Running the sample -Although this sample does provide a fully functional client and service implementation, the point of the sample is to illustrate how to alter a service's run-time behavior by means of a custom host., do the following steps: +Although this sample does provide a fully functional client and service implementation, the point of the sample is to illustrate how to alter a service's runtime behavior by means of a custom host., do the following steps: ### Observe the effect of the custom host diff --git a/docs/framework/wcf/samples/extensibility.md b/docs/framework/wcf/samples/extensibility.md index 978b442d5282c..0f80743d8ca19 100644 --- a/docs/framework/wcf/samples/extensibility.md +++ b/docs/framework/wcf/samples/extensibility.md @@ -44,7 +44,7 @@ Demonstrates how extensibility points can consume custom message data formats. demonstrates how to replace the message filters that Windows Communication Foundation (WCF) uses to dispatch messages to endpoints. [Custom Service Host](custom-service-host.md) -Demonstrates how to use a custom derivative of the class to alter the run-time behavior of a service. +Demonstrates how to use a custom derivative of the class to alter the runtime behavior of a service. [DataContract Surrogate](datacontract-surrogate.md) Demonstrates how processes like serialization, deserialization, schema export, and schema import can be customized using a data contract surrogate class. diff --git a/docs/framework/wcf/samples/fault-contract.md b/docs/framework/wcf/samples/fault-contract.md index 517b34b420a0c..542f6f1fc917c 100644 --- a/docs/framework/wcf/samples/fault-contract.md +++ b/docs/framework/wcf/samples/fault-contract.md @@ -94,7 +94,7 @@ catch (FaultException e) } ``` -By default, the details of unexpected exceptions are not sent to the client to prevent details of the service implementation from escaping the secure boundary of the service. `FaultContract` provides a way to describe faults in a contract and mark certain types of exceptions as appropriate for transmission to the client. `FaultException` provides the run-time mechanism for sending faults to consumers. +By default, the details of unexpected exceptions are not sent to the client to prevent details of the service implementation from escaping the secure boundary of the service. `FaultContract` provides a way to describe faults in a contract and mark certain types of exceptions as appropriate for transmission to the client. `FaultException` provides the runtime mechanism for sending faults to consumers. However, it is useful to see the internal details of a service failure when debugging. To turn off the secure behavior previously described, you can indicate that the details of every unhandled exception on the server should be included in the fault that is sent to the client. This is accomplished by setting to `true`. You can either set it in code, or in configuration as shown in the following sample. diff --git a/docs/framework/wcf/samples/getting-started-sample.md b/docs/framework/wcf/samples/getting-started-sample.md index 16d4c817d9973..85b82c9a99288 100644 --- a/docs/framework/wcf/samples/getting-started-sample.md +++ b/docs/framework/wcf/samples/getting-started-sample.md @@ -28,7 +28,7 @@ On Windows Vista, the service is hosted in the Windows Activation Service (WAS). The service and client specify access details in configuration file settings, which provide flexibility at the time of deployment. This includes an endpoint definition that specifies an address, binding, and contract. The binding specifies transport and security details for how the service is to be accessed. -The service configures a run-time behavior to publish its metadata. +The service configures a runtime behavior to publish its metadata. The service implements a contract that defines a request-reply communication pattern. The contract is defined by the `ICalculator` interface, which exposes math operations (add, subtract, multiply, and divide). The client makes requests to a given math operation and the service replies with the result. The service implements an `ICalculator` contract that is defined in the following code. diff --git a/docs/framework/wcf/samples/instancing-initialization.md b/docs/framework/wcf/samples/instancing-initialization.md index 186384feda350..33a51672b9e5c 100644 --- a/docs/framework/wcf/samples/instancing-initialization.md +++ b/docs/framework/wcf/samples/instancing-initialization.md @@ -13,7 +13,7 @@ The [Initialization sample](https://github.com/dotnet/samples/tree/main/framewor ## Extensibility Points -The first step in creating a Windows Communication Foundation (WCF) extension is to decide the extensibility point to use. In WCF, the term *EndpointDispatcher* refers to a run-time component responsible for converting incoming messages into method invocations on the user's service and for converting return values from that method to an outgoing message. A WCF service creates an EndpointDispatcher for each endpoint. +The first step in creating a Windows Communication Foundation (WCF) extension is to decide the extensibility point to use. In WCF, the term *EndpointDispatcher* refers to a runtime component responsible for converting incoming messages into method invocations on the user's service and for converting return values from that method to an outgoing message. A WCF service creates an EndpointDispatcher for each endpoint. The EndpointDispatcher offers endpoint scope (for all messages received or sent by the service) extensibility using the class. This class allows you to customize various properties that control the behavior of the EndpointDispatcher. This sample focuses on the property that points to the object that provides the instances of the service class. diff --git a/docs/framework/wcf/samples/knownassemblyattribute.md b/docs/framework/wcf/samples/knownassemblyattribute.md index eacc85f0e7895..527a45b02615f 100644 --- a/docs/framework/wcf/samples/knownassemblyattribute.md +++ b/docs/framework/wcf/samples/knownassemblyattribute.md @@ -184,7 +184,7 @@ class Client } ``` -The definition of the service contract is marked with the `KnownAssembly` attribute. This attribute contains the name of a library of types, which all become known at run time by both the service and the client. +The definition of the service contract is marked with the `KnownAssembly` attribute. This attribute contains the name of a library of types, which all become known at runtime by both the service and the client. The `KnownAssembly` attribute implements `IContractBehavior` in order to define a `DataContractSerializer` with a `DataContractResolver` defined for each of the operation behaviors. The `DataContractResolver` reflects over the assembly when it is created, and creates the dictionary with the mapping between types and names to be used when serializing and deserializing the different types. In that way, the `ResolveType` and `ResolveName` types must look up the data required in the dictionary. @@ -317,7 +317,7 @@ public class ComplexNumberWithMagnitude : ComplexNumber } ``` -Note that `ComplexNumber` does not need to statically know the `ComplexNumberWithMagnitude` type, because it becomes known at run time. +Note that `ComplexNumber` does not need to statically know the `ComplexNumberWithMagnitude` type, because it becomes known at runtime. When the sample is built and executed, this is the expected output obtained in the client: diff --git a/docs/framework/wcf/samples/management.md b/docs/framework/wcf/samples/management.md index 4ad6046bd7e76..68b1253f78aa2 100644 --- a/docs/framework/wcf/samples/management.md +++ b/docs/framework/wcf/samples/management.md @@ -38,4 +38,4 @@ Demonstrates how to enable tracing and message logging. Demonstrates how to use a custom behavior to validate services on a machine to ensure they meet specific criteria. [WMI Provider](wmi-provider.md) -Demonstrates how to gather data from WCF services at run time by using the Windows Management Instrumentation (WMI) provider that is built into WCF. +Demonstrates how to gather data from WCF services at runtime by using the Windows Management Instrumentation (WMI) provider that is built into WCF. diff --git a/docs/framework/wcf/samples/pii-security-lockdown.md b/docs/framework/wcf/samples/pii-security-lockdown.md index 1155b4304e845..1f7dfea98fbc8 100644 --- a/docs/framework/wcf/samples/pii-security-lockdown.md +++ b/docs/framework/wcf/samples/pii-security-lockdown.md @@ -42,7 +42,7 @@ More information about encrypting sections of configuration files can be found b In Web-hosted scenarios, it is possible to have services in subdirectories of services. In these situations, configuration values for the service in the subdirectory are calculated by examining values in Machine.config and successively merging with any Web.config files in parent directories moving down the directory tree and finally merging the Web.config file in the directory that contains the service. The default behavior for most configuration elements is to allow configuration files in subdirectories to override the values set in parent directories. In certain situations it may be desirable to prevent configuration files in subdirectories from overriding values set in parent directory configuration. -The .NET Framework provides a way to lock configuration file elements so that configurations that override locked configuration elements throw run-time exceptions. +The .NET Framework provides a way to lock configuration file elements so that configurations that override locked configuration elements throw runtime exceptions. A configuration element can be locked by specifying the `lockItem` attribute for a node in the configuration file, for example, to lock the CalculatorServiceBehavior node in the configuration file so that calculator services in nested configuration files cannot change the behavior, the following configuration can be used. diff --git a/docs/framework/wcf/samples/pooling.md b/docs/framework/wcf/samples/pooling.md index d6c37bae2963d..513f1a99a5d57 100644 --- a/docs/framework/wcf/samples/pooling.md +++ b/docs/framework/wcf/samples/pooling.md @@ -13,7 +13,7 @@ The [Pooling sample](https://github.com/dotnet/samples/tree/main/framework/wcf) The first step in creating a WCF extension is to decide the extensibility point to use. -In WCF the term *dispatcher* refers to a run-time component responsible for converting incoming messages into method invocations on the user's service and for converting return values from that method to an outgoing message. A WCF service creates a dispatcher for each endpoint. A WCF client must use a dispatcher if the contract associated with that client is a duplex contract. +In WCF the term *dispatcher* refers to a runtime component responsible for converting incoming messages into method invocations on the user's service and for converting return values from that method to an outgoing message. A WCF service creates a dispatcher for each endpoint. A WCF client must use a dispatcher if the contract associated with that client is a duplex contract. The channel and endpoint dispatchers offer channel-and contract-wide extensibility by exposing various properties that control the behavior of the dispatcher. The property also enables you to inspect, modify, or customize the dispatching process. This sample focuses on the property that points to the object that provides the instances of the service class. diff --git a/docs/framework/wcf/samples/service-description.md b/docs/framework/wcf/samples/service-description.md index 3361899c2dd8e..316602b3ff23b 100644 --- a/docs/framework/wcf/samples/service-description.md +++ b/docs/framework/wcf/samples/service-description.md @@ -6,7 +6,7 @@ ms.assetid: 7034b5d6-d608-45f3-b57d-ec135f83ff24 --- # Service Description -The [ServiceDescription sample](https://github.com/dotnet/samples/tree/main/framework/wcf) demonstrates how a service can retrieve its service description information at run time. The sample is based on the [Getting Started](getting-started-sample.md), with an additional service operation defined to return descriptive information about the service. The information that is returned lists the base addresses and endpoints for the service. The service provides this information using the , , and classes. +The [ServiceDescription sample](https://github.com/dotnet/samples/tree/main/framework/wcf) demonstrates how a service can retrieve its service description information at runtime. The sample is based on the [Getting Started](getting-started-sample.md), with an additional service operation defined to return descriptive information about the service. The information that is returned lists the base addresses and endpoints for the service. The service provides this information using the , , and classes. In this sample, the client is a console application (.exe) and the service is hosted by Internet Information Services (IIS). diff --git a/docs/framework/wcf/samples/service-identity-sample.md b/docs/framework/wcf/samples/service-identity-sample.md index 72a27b3503811..3150fd3868094 100644 --- a/docs/framework/wcf/samples/service-identity-sample.md +++ b/docs/framework/wcf/samples/service-identity-sample.md @@ -6,7 +6,7 @@ ms.assetid: 79fa8c1c-85bb-4b67-bc67-bfaf721303f8 --- # Service Identity Sample -This service identity sample demonstrates how to set the identity for a service. At design time, a client can retrieve the identity using the service's metadata and then at run time the client can authenticate the service's identity. The concept of service identity is to allow a client to authenticate a service before calling any of its operations, thereby protecting the client from unauthenticated calls. On a secure connection the service also authenticates a client's credentials before allowing it access, but this is not the focus of this sample. See the samples in [Client](client.md) that show server authentication. +This service identity sample demonstrates how to set the identity for a service. At design time, a client can retrieve the identity using the service's metadata and then at runtime the client can authenticate the service's identity. The concept of service identity is to allow a client to authenticate a service before calling any of its operations, thereby protecting the client from unauthenticated calls. On a secure connection the service also authenticates a client's credentials before allowing it access, but this is not the focus of this sample. See the samples in [Client](client.md) that show server authentication. > [!NOTE] > The setup procedure and build instructions for this sample are located at the end of this topic. diff --git a/docs/framework/wcf/samples/services.md b/docs/framework/wcf/samples/services.md index 56782157188ff..111c5e8b75518 100644 --- a/docs/framework/wcf/samples/services.md +++ b/docs/framework/wcf/samples/services.md @@ -53,7 +53,7 @@ Demonstrates a service that hosts multiple endpoints at a single `ListenUri`. Demonstrates how to send extra information on a WCF call using headers. - [Service Description](service-description.md)\ -Demonstrates how a service can retrieve its service description information at run time. +Demonstrates how a service can retrieve its service description information at runtime. - [ConcurrencyMode.Reentrant](concurrencymode-reentrant.md)\ Demonstrates how to use the Reentrant concurrency mode on a service implementation. diff --git a/docs/framework/wcf/samples/using-the-wcf-moniker-with-com-clients.md b/docs/framework/wcf/samples/using-the-wcf-moniker-with-com-clients.md index 5da2d4f936f30..6d5417797f310 100644 --- a/docs/framework/wcf/samples/using-the-wcf-moniker-with-com-clients.md +++ b/docs/framework/wcf/samples/using-the-wcf-moniker-with-com-clients.md @@ -34,7 +34,7 @@ The sample demonstrates the three alternative approaches for using the moniker: - WSDL contract – The contract is supplied in the form of a WSDL document. -- Metadata Exchange contract – The contract is retrieved at run time from a Metadata Exchange (MEX) endpoint. +- Metadata Exchange contract – The contract is retrieved at runtime from a Metadata Exchange (MEX) endpoint. ## Typed Contract diff --git a/docs/framework/wcf/samples/windows-service-host.md b/docs/framework/wcf/samples/windows-service-host.md index 09b1352e94f37..8c37af8e03eb1 100644 --- a/docs/framework/wcf/samples/windows-service-host.md +++ b/docs/framework/wcf/samples/windows-service-host.md @@ -16,7 +16,7 @@ The [WindowsService sample](https://github.com/dotnet/samples/tree/main/framewor After building this service, it must be installed with the Installutil.exe utility like any other Windows Service. If you are going to make changes to the service, you must first uninstall it with `installutil /u`. The Setup.bat and Cleanup.bat files included in this sample are the commands to install and start up the Windows Service, and to shut down and uninstall the Windows Service. The WCF service can only respond to clients if the Windows Service is running. If you stop the Windows Service by using the Services applet from **Control Panel** and run the client, a exception occurs when a client attempts to access the service. If you restart the Windows Service and rerun the client, communication succeeds. -The service code includes an installer class, a WCF service implementation class which implements the ICalculator contract, and a Windows Service class that acts as the run-time host. The installer class, which inherits from , allows the program to be installed as an NT service by the Installutil.exe tool. The service implementation class, `WcfCalculatorService`, is an WCF service that implements a basic service contract. This WCF service is hosted inside a Windows Service class called `WindowsCalculatorService`. To qualify as a Windows Service, the class inherits from and implements the and methods. In , a object is created for the `WcfCalculatorService` type and opened. In , the ServiceHost is closed by calling the method of the object. The host's base address is configured using the [\](../../configure-apps/file-schema/wcf/add-of-baseaddresses.md) element, which is a child of [\](../../configure-apps/file-schema/wcf/baseaddresses.md), which is a child of the [\](../../configure-apps/file-schema/wcf/host.md) element, which is a child of the [\](../../configure-apps/file-schema/wcf/service.md) element. +The service code includes an installer class, a WCF service implementation class which implements the ICalculator contract, and a Windows Service class that acts as the runtime host. The installer class, which inherits from , allows the program to be installed as an NT service by the Installutil.exe tool. The service implementation class, `WcfCalculatorService`, is an WCF service that implements a basic service contract. This WCF service is hosted inside a Windows Service class called `WindowsCalculatorService`. To qualify as a Windows Service, the class inherits from and implements the and methods. In , a object is created for the `WcfCalculatorService` type and opened. In , the ServiceHost is closed by calling the method of the object. The host's base address is configured using the [\](../../configure-apps/file-schema/wcf/add-of-baseaddresses.md) element, which is a child of [\](../../configure-apps/file-schema/wcf/baseaddresses.md), which is a child of the [\](../../configure-apps/file-schema/wcf/host.md) element, which is a child of the [\](../../configure-apps/file-schema/wcf/service.md) element. The endpoint that is defined uses the base address and a [\](../../configure-apps/file-schema/wcf/wshttpbinding.md). The following sample shows the configuration of the base address as well as the endpoint that exposes the CalculatorService. diff --git a/docs/framework/wcf/samples/wmi-provider.md b/docs/framework/wcf/samples/wmi-provider.md index af2279130ac2d..3aae39f9bca5c 100644 --- a/docs/framework/wcf/samples/wmi-provider.md +++ b/docs/framework/wcf/samples/wmi-provider.md @@ -6,11 +6,11 @@ ms.assetid: 462f0db3-f4a4-4a4b-ac26-41fc25c670a4 --- # WMI Provider -The [WMIProvider sample](https://github.com/dotnet/samples/tree/main/framework/wcf) demonstrates how to gather data from Windows Communication Foundation (WCF) services at run time by using the Windows Management Instrumentation (WMI) provider that is built into WCF. Also, this sample demonstrates how to add a user-defined WMI object to a service. The sample activates the WMI provider for the [Getting Started](getting-started-sample.md) and demonstrates how to gather data from the `ICalculator` service at run time. +The [WMIProvider sample](https://github.com/dotnet/samples/tree/main/framework/wcf) demonstrates how to gather data from Windows Communication Foundation (WCF) services at runtime by using the Windows Management Instrumentation (WMI) provider that is built into WCF. Also, this sample demonstrates how to add a user-defined WMI object to a service. The sample activates the WMI provider for the [Getting Started](getting-started-sample.md) and demonstrates how to gather data from the `ICalculator` service at runtime. WMI is Microsoft's implementation of the Web-Based Enterprise Management (WBEM) standard. For more information about the WMI SDK, see [Windows Management Instrumentation](/windows/desktop/WmiSdk/wmi-start-page). WBEM is an industry standard for how applications expose management instrumentation to external management tools. -WCF implements a WMI provider, a component that exposes instrumentation at run time through a WBEM-compatible interface. Management tools can connect to the services through the interface at run time. WCF exposes attributes of services such as addresses, bindings, behaviors, and listeners. +WCF implements a WMI provider, a component that exposes instrumentation at runtime through a WBEM-compatible interface. Management tools can connect to the services through the interface at runtime. WCF exposes attributes of services such as addresses, bindings, behaviors, and listeners. The built-in WMI provider is activated in the configuration file of the application. This is done through the `wmiProviderEnabled` attribute of the [\](../../configure-apps/file-schema/wcf/diagnostics.md) in the [\](../../configure-apps/file-schema/wcf/system-servicemodel.md) section, as shown in the following sample configuration: diff --git a/docs/framework/wcf/securing-services.md b/docs/framework/wcf/securing-services.md index 53b0c3ff30f31..3776315eb0245 100644 --- a/docs/framework/wcf/securing-services.md +++ b/docs/framework/wcf/securing-services.md @@ -2,7 +2,7 @@ description: "Learn more about: Securing Services" title: "Securing Services" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "configuration [WCF], securing services" - "WCF security" - "WCF, security" @@ -10,104 +10,104 @@ ms.assetid: f0ecc6f7-f4b5-42a4-9cb1-b02e28e26620 --- # Securing Services -Security of a Windows Communication Foundation (WCF) service consists of two primary requirements: transfer security and authorization. (A third requirement, auditing of security events, is described in [Auditing](./feature-details/auditing-security-events.md).) In brief, transfer security includes authentication (verifying the identity of both the service and the client), confidentiality (message encryption), and integrity (digital signing to detect tampering). Authorization is the control of access to resources, for example, allowing only privileged users to read a file. Using features of WCF, the two primary requirements are easily implemented. - +Security of a Windows Communication Foundation (WCF) service consists of two primary requirements: transfer security and authorization. (A third requirement, auditing of security events, is described in [Auditing](./feature-details/auditing-security-events.md).) In brief, transfer security includes authentication (verifying the identity of both the service and the client), confidentiality (message encryption), and integrity (digital signing to detect tampering). Authorization is the control of access to resources, for example, allowing only privileged users to read a file. Using features of WCF, the two primary requirements are easily implemented. + With the exception of the class (or the [\](../configure-apps/file-schema/wcf/basichttpbinding.md) element in configuration), transfer security is enabled by default for all of the predefined bindings. The topics in this section cover two basic scenarios: implementing transfer security and authorization on an intranet service hosted on Internet Information Services (IIS), and implementing transfer security and authorization on a service hosted on IIS. - -## Security Basics - - Security relies on *credentials*. A credential proves that an entity is who it claims to be. (An *entity* can be a person, a software process, a company, or anything that can be authorized.) For example, a client of a service makes a *claim* of *identity*, and the credential proves that claim in some manner. In a typical scenario, an exchange of credentials occurs. First, a service makes a claim of its identity and proves it to the client with a credential. Conversely, the client makes a claim of identity and presents a credential to the service. If both parties trust the other's credentials, then a *secure context* can be established in which all messages are exchanged in confidentiality, and all messages are signed to protect their integrity. After the service establishes the client's identity, it can then match the claims in the credential to a *role* or *membership* in a group. In either case, using the role or the group to which the client belongs, the service *authorizes* the client to perform a limited set of operations based on the role or group privileges. - -## Windows Security Mechanisms - - If the client and the service computer are both on a Windows domain that requires both to log on to the network, the credentials are provided by Windows infrastructure. In that case, the credentials are established when a computer user logs on to the network. Every user and every computer on the network must be validated as belonging to the trusted set of users and computers. On a Windows system, every such user and computer is also known as a *security principal*. - - On a Windows domain backed by a *Kerberos* controller, the Kerberos controller uses a scheme based on granting tickets to each security principal. The tickets the controller grants are trusted by other ticket granters in the system. Whenever an entity tries to perform some operation or access a *resource* (such as a file or directory on a machine), the ticket is examined for its validity and, if it passes, the principal is granted another ticket for the operation. This method of granting tickets is more efficient than the alternative of trying to validate the principal for every operation. - - An older, less-secure mechanism used on Windows domains is NT LAN Manager (NTLM). In cases where Kerberos cannot be used (typically outside of a Windows domain, such as in a workgroup), NTLM can be used as an alternative. NTLM is also available as a security option for IIS. - - On a Windows system, authorization works by assigning each computer and user to a set of roles and groups. For example, every Windows computer must be set up and controlled by a person (or group of people) in the role of the *administrator*. Another role is that of the *user*, which has a much more constrained set of permissions. In addition to the role, users are assigned to groups. A group allows multiple users to perform in the same role. In practice, therefore, a Windows machine is administered by assigning users to groups. For example, several users can be assigned to the group of users of a computer, and a much more constrained set of users can be assigned to the group of administrators. On a local machine, an administrator can also create new groups and assign other users (or even other groups) to the group. - - On a computer running Windows, every folder in a directory can be protected. That is, you can select a folder and control who can access the files, and whether or not they can copy the file, or (in the most privileged case) change a file, delete a file, or add files to the folder. This is known as access control, and the mechanism for it is known as the access control list (ACL). When creating the ACL, you can assign access privileges to any group or groups, as well as individual members of a domain. - - The WCF infrastructure is designed to use these Windows security mechanisms. Therefore, if you are creating a service that is deployed on an intranet, and whose clients are restricted to members of the Windows domain, security is easily implemented. Only valid users can log on to the domain. After users are logged on, the Kerberos controller enables each user to establish secure contexts with any other computer or application. On a local machine, groups can be easily created, and when protecting specific folders, those groups can be used to assign access privileges on the computer. - -## Implementing Windows Security on Intranet Services - - To secure an application that runs exclusively on a Windows domain, you can use the default security settings of either the or the binding. By default, anyone on the same Windows domain can access WCF services. Because those users have logged on to the network, they are trusted. The messages between a service and a client are encrypted for confidentiality and signed for integrity. For more information about how to create a service that uses Windows security, see [How to: Secure a Service with Windows Credentials](how-to-secure-a-service-with-windows-credentials.md). - -### Authorization Using the PrincipalPermissionAttribute Class - - If you need to restrict the access of resources on a computer, the easiest way is to use the class. This attribute enables you to restrict the invocation of service operations by demanding that the user be in a specified Windows group or role, or to be a specific user. For more information, see [How to: Restrict Access with the PrincipalPermissionAttribute Class](how-to-restrict-access-with-the-principalpermissionattribute-class.md). - -### Impersonation - - Impersonation is another mechanism that you can use to control access to resources. By default, a service hosted by IIS will run under the identity of the ASPNET account. The ASPNET account can access only the resources for which it has permission. However, it is possible to set the ACL for a folder to exclude the ASPNET service account, but allow certain other identities to access the folder. The question then becomes how to allow those users to access the folder if the ASPNET account is not allowed to do so. The answer is to use impersonation, whereby the service is allowed to use the credentials of the client to access a particular resource. Another example is when accessing a SQL Server database to which only certain users have permission. For more information about using impersonation, see [How to: Impersonate a Client on a Service](how-to-impersonate-a-client-on-a-service.md) and [Delegation and Impersonation](./feature-details/delegation-and-impersonation-with-wcf.md). - -## Security on the Internet - - Security on the Internet consists of the same requirements as security on an intranet. A service needs to present its credentials to prove its authenticity, and clients need to prove their identity to the service. Once a client's identity is proven, the service can control how much access the client has to resources. However, due to the heterogeneous nature of the Internet, the credentials presented differ from those used on a Windows domain. Whereas a Kerberos controller handles the authentication of users on a domain with tickets for credentials, on the Internet, services and clients rely on any one of several different ways to present credentials. The objective of this topic, however, is to present a common approach that enables you to create a WCF service that is accessible on the Internet. - -### Using IIS and ASP.NET - - The requirements of Internet security, and the mechanisms to solve those problems, are not new. IIS is Microsoft's Web server for the Internet and has many security features that address those problems; in addition, ASP.NET includes security features that WCF services can use. To take advantage of these security features, host an WCF service on IIS. - -#### Using ASP.NET Membership and Role Providers - - ASP.NET includes a membership and role provider. The provider is a database of user name/password pairs for authenticating callers that also allows you to specify each caller's access privileges. With WCF, you can easily use a pre-existing membership and role provider through configuration. For a sample application that demonstrates this, see the [Membership and Role Provider](./samples/membership-and-role-provider.md) sample. - -### Credentials Used by IIS - - Unlike a Windows domain backed by a Kerberos controller, the Internet is an environment without a single controller to manage the millions of users logging on at any time. Instead, credentials on the Internet most often are in the form of X.509 certificates (also known as Secure Sockets Layer, or SSL, certificates). These certificates are typically issued by a *certification authority*, which can be a third-party company that vouches for the authenticity of the certificate and the person it has been issued to. To expose your service on the Internet, you must also supply such a trusted certificate to authenticate your service. - - The question arises at this point, how do you get such a certificate? One approach is to go to a third-party certification authority, such as Authenticode or VeriSign, when you are ready to deploy your service, and purchase a certificate for your service. However, if you are in the development phase with WCF and not yet ready to commit to purchasing a certificate, tools and techniques exist for creating X.509 certificates that you can use to simulate a production deployment. For more information, see [Working with Certificates](./feature-details/working-with-certificates.md). - -## Security Modes - - Programming WCF security entails a few critical decision points. One of the most basic is the choice of *security mode*. The two major security modes are *transport mode* and *message mode*. - - A third mode, which combines the semantics of both major modes, is *transport with message credentials mode*. - - The security mode determines how messages are secured, and each choice has advantages and disadvantages, as explained below. For more information about setting the security mode, see [How to: Set the Security Mode](how-to-set-the-security-mode.md). - -#### Transport Mode - - There are several layers between the network and the application. One of these is the *transport* layer*,* which manages the transfer of messages between endpoints. For the present purpose, it is only required that you understand that WCF uses several transport protocols, each of which can secure the transfer of messages. (For more information about transports, see [Transports](./feature-details/transports.md).) - - A commonly used protocol is HTTP; another is TCP. Each of these protocols can secure message transfer by a mechanism (or mechanisms) particular to the protocol. For example, the HTTP protocol is secured using SSL over HTTP, commonly abbreviated as "HTTPS." Thus, when you select the transport mode for security, you are choosing to use the mechanism as dictated by the protocol. For example, if you select the class and set its security mode to Transport, you are selecting SSL over HTTP (HTTPS) as the security mechanism. The advantage of the transport mode is that it is more efficient than message mode because security is integrated at a comparatively low level. When using transport mode, the security mechanism must be implemented according to the specification for the transport, and thus messages can flow securely only from point-to-point over the transport. - -#### Message Mode - - In contrast, message mode provides security by including the security data as part of every message. Using XML and SOAP security headers, the credentials and other data needed to ensure the integrity and confidentiality of the message are included with every message. Every message includes security data, so it results in a toll on performance because each message must be individually processed. (In transport mode, once the transport layer is secured, all messages flow freely.) However, message security has one advantage over transport security: it is more flexible. That is, the security requirements are not determined by the transport. You can use any type of client credential to secure the message. (In transport mode, the transport protocol determines the type of client credential that you can use.) - -#### Transport with Message Credentials - - The third mode combines the best of both transport and message security. In this mode, transport security is used to efficiently ensure the confidentiality and integrity of every message. At the same time, every message includes its credential data, which allows the message to be authenticated. With authentication, authorization can also be implemented. By authenticating a sender, access to resources can be granted (or denied) according to the sender's identity. - -## Specifying the Client Credential Type and Credential Value - - After you have selected a security mode, you may also want to specify a client credential type. The client credential type specifies what type a client must use to authenticate itself to the server. - - Not all scenarios require a client credential type, however. Using SSL over HTTP (HTTPS), a service authenticates itself to the client. As part of this authentication, the service's certificate is sent to the client in a process called *negotiation*. The SSL-secured transport ensures that all messages are confidential. - - If you are creating a service that requires that the client be authenticated, your choice of a client credential type depends on the transport and mode selected. For example, using the HTTP transport and choosing transport mode gives you several choices, such as Basic, Digest, and others. (For more information about these credential types, see [Understanding HTTP Authentication](./feature-details/understanding-http-authentication.md).) - - If you are creating a service on a Windows domain that will be available only to other users of the network, the easiest to use is the Windows client credential type. However, you may also need to provide a service with a certificate. This is shown in [How to: Specify Client Credential Values](how-to-specify-client-credential-values.md). - -#### Credential Values - - A *credential value* is the actual credential the service uses. Once you have specified a credential type, you may also need to configure your service with the actual credentials. If you have selected Windows (and the service will run on a Windows domain), then you do not specify an actual credential value. - -## Identity - - In WCF, the term *identity* has different meanings to the server and the client. In brief, when running a service, an identity is assigned to the security context after authentication. To view the actual identity, check the and properties of the class. For more information, see [How to: Examine the Security Context](how-to-examine-the-security-context.md). - - In contrast, on the client, identity is used to validate the service. At design time, a client developer can set the [\](../configure-apps/file-schema/wcf/identity.md) element to a value obtained from the service. At run time, the client checks the value of the element against the actual identity of the service. If the check fails, the client terminates the communication. The value can be a user principal name (UPN) if the service runs under a particular user's identity or a service principal name (SPN) if the service runs under a machine account. For more information, see [Service Identity and Authentication](./feature-details/service-identity-and-authentication.md). The credential could also be a certificate, or a field found on a certificate that identifies the certificate. - -## Protection Levels - - The `ProtectionLevel` property occurs on several attribute classes (such as the and the classes). The protection level is a value that specifies whether the messages (or message parts) that support a service are signed, signed and encrypted, or sent without signatures or encryption. For more information about the property, see [Understanding Protection Level](understanding-protection-level.md), and for programming examples, see [How to: Set the ProtectionLevel Property](how-to-set-the-protectionlevel-property.md). For more information about designing a service contract with the `ProtectionLevel` in context, see [Designing Service Contracts](designing-service-contracts.md). - + +## Security Basics + + Security relies on *credentials*. A credential proves that an entity is who it claims to be. (An *entity* can be a person, a software process, a company, or anything that can be authorized.) For example, a client of a service makes a *claim* of *identity*, and the credential proves that claim in some manner. In a typical scenario, an exchange of credentials occurs. First, a service makes a claim of its identity and proves it to the client with a credential. Conversely, the client makes a claim of identity and presents a credential to the service. If both parties trust the other's credentials, then a *secure context* can be established in which all messages are exchanged in confidentiality, and all messages are signed to protect their integrity. After the service establishes the client's identity, it can then match the claims in the credential to a *role* or *membership* in a group. In either case, using the role or the group to which the client belongs, the service *authorizes* the client to perform a limited set of operations based on the role or group privileges. + +## Windows Security Mechanisms + + If the client and the service computer are both on a Windows domain that requires both to log on to the network, the credentials are provided by Windows infrastructure. In that case, the credentials are established when a computer user logs on to the network. Every user and every computer on the network must be validated as belonging to the trusted set of users and computers. On a Windows system, every such user and computer is also known as a *security principal*. + + On a Windows domain backed by a *Kerberos* controller, the Kerberos controller uses a scheme based on granting tickets to each security principal. The tickets the controller grants are trusted by other ticket granters in the system. Whenever an entity tries to perform some operation or access a *resource* (such as a file or directory on a machine), the ticket is examined for its validity and, if it passes, the principal is granted another ticket for the operation. This method of granting tickets is more efficient than the alternative of trying to validate the principal for every operation. + + An older, less-secure mechanism used on Windows domains is NT LAN Manager (NTLM). In cases where Kerberos cannot be used (typically outside of a Windows domain, such as in a workgroup), NTLM can be used as an alternative. NTLM is also available as a security option for IIS. + + On a Windows system, authorization works by assigning each computer and user to a set of roles and groups. For example, every Windows computer must be set up and controlled by a person (or group of people) in the role of the *administrator*. Another role is that of the *user*, which has a much more constrained set of permissions. In addition to the role, users are assigned to groups. A group allows multiple users to perform in the same role. In practice, therefore, a Windows machine is administered by assigning users to groups. For example, several users can be assigned to the group of users of a computer, and a much more constrained set of users can be assigned to the group of administrators. On a local machine, an administrator can also create new groups and assign other users (or even other groups) to the group. + + On a computer running Windows, every folder in a directory can be protected. That is, you can select a folder and control who can access the files, and whether or not they can copy the file, or (in the most privileged case) change a file, delete a file, or add files to the folder. This is known as access control, and the mechanism for it is known as the access control list (ACL). When creating the ACL, you can assign access privileges to any group or groups, as well as individual members of a domain. + + The WCF infrastructure is designed to use these Windows security mechanisms. Therefore, if you are creating a service that is deployed on an intranet, and whose clients are restricted to members of the Windows domain, security is easily implemented. Only valid users can log on to the domain. After users are logged on, the Kerberos controller enables each user to establish secure contexts with any other computer or application. On a local machine, groups can be easily created, and when protecting specific folders, those groups can be used to assign access privileges on the computer. + +## Implementing Windows Security on Intranet Services + + To secure an application that runs exclusively on a Windows domain, you can use the default security settings of either the or the binding. By default, anyone on the same Windows domain can access WCF services. Because those users have logged on to the network, they are trusted. The messages between a service and a client are encrypted for confidentiality and signed for integrity. For more information about how to create a service that uses Windows security, see [How to: Secure a Service with Windows Credentials](how-to-secure-a-service-with-windows-credentials.md). + +### Authorization Using the PrincipalPermissionAttribute Class + + If you need to restrict the access of resources on a computer, the easiest way is to use the class. This attribute enables you to restrict the invocation of service operations by demanding that the user be in a specified Windows group or role, or to be a specific user. For more information, see [How to: Restrict Access with the PrincipalPermissionAttribute Class](how-to-restrict-access-with-the-principalpermissionattribute-class.md). + +### Impersonation + + Impersonation is another mechanism that you can use to control access to resources. By default, a service hosted by IIS will run under the identity of the ASPNET account. The ASPNET account can access only the resources for which it has permission. However, it is possible to set the ACL for a folder to exclude the ASPNET service account, but allow certain other identities to access the folder. The question then becomes how to allow those users to access the folder if the ASPNET account is not allowed to do so. The answer is to use impersonation, whereby the service is allowed to use the credentials of the client to access a particular resource. Another example is when accessing a SQL Server database to which only certain users have permission. For more information about using impersonation, see [How to: Impersonate a Client on a Service](how-to-impersonate-a-client-on-a-service.md) and [Delegation and Impersonation](./feature-details/delegation-and-impersonation-with-wcf.md). + +## Security on the Internet + + Security on the Internet consists of the same requirements as security on an intranet. A service needs to present its credentials to prove its authenticity, and clients need to prove their identity to the service. Once a client's identity is proven, the service can control how much access the client has to resources. However, due to the heterogeneous nature of the Internet, the credentials presented differ from those used on a Windows domain. Whereas a Kerberos controller handles the authentication of users on a domain with tickets for credentials, on the Internet, services and clients rely on any one of several different ways to present credentials. The objective of this topic, however, is to present a common approach that enables you to create a WCF service that is accessible on the Internet. + +### Using IIS and ASP.NET + + The requirements of Internet security, and the mechanisms to solve those problems, are not new. IIS is Microsoft's Web server for the Internet and has many security features that address those problems; in addition, ASP.NET includes security features that WCF services can use. To take advantage of these security features, host an WCF service on IIS. + +#### Using ASP.NET Membership and Role Providers + + ASP.NET includes a membership and role provider. The provider is a database of user name/password pairs for authenticating callers that also allows you to specify each caller's access privileges. With WCF, you can easily use a pre-existing membership and role provider through configuration. For a sample application that demonstrates this, see the [Membership and Role Provider](./samples/membership-and-role-provider.md) sample. + +### Credentials Used by IIS + + Unlike a Windows domain backed by a Kerberos controller, the Internet is an environment without a single controller to manage the millions of users logging on at any time. Instead, credentials on the Internet most often are in the form of X.509 certificates (also known as Secure Sockets Layer, or SSL, certificates). These certificates are typically issued by a *certification authority*, which can be a third-party company that vouches for the authenticity of the certificate and the person it has been issued to. To expose your service on the Internet, you must also supply such a trusted certificate to authenticate your service. + + The question arises at this point, how do you get such a certificate? One approach is to go to a third-party certification authority, such as Authenticode or VeriSign, when you are ready to deploy your service, and purchase a certificate for your service. However, if you are in the development phase with WCF and not yet ready to commit to purchasing a certificate, tools and techniques exist for creating X.509 certificates that you can use to simulate a production deployment. For more information, see [Working with Certificates](./feature-details/working-with-certificates.md). + +## Security Modes + + Programming WCF security entails a few critical decision points. One of the most basic is the choice of *security mode*. The two major security modes are *transport mode* and *message mode*. + + A third mode, which combines the semantics of both major modes, is *transport with message credentials mode*. + + The security mode determines how messages are secured, and each choice has advantages and disadvantages, as explained below. For more information about setting the security mode, see [How to: Set the Security Mode](how-to-set-the-security-mode.md). + +#### Transport Mode + + There are several layers between the network and the application. One of these is the *transport* layer*,* which manages the transfer of messages between endpoints. For the present purpose, it is only required that you understand that WCF uses several transport protocols, each of which can secure the transfer of messages. (For more information about transports, see [Transports](./feature-details/transports.md).) + + A commonly used protocol is HTTP; another is TCP. Each of these protocols can secure message transfer by a mechanism (or mechanisms) particular to the protocol. For example, the HTTP protocol is secured using SSL over HTTP, commonly abbreviated as "HTTPS." Thus, when you select the transport mode for security, you are choosing to use the mechanism as dictated by the protocol. For example, if you select the class and set its security mode to Transport, you are selecting SSL over HTTP (HTTPS) as the security mechanism. The advantage of the transport mode is that it is more efficient than message mode because security is integrated at a comparatively low level. When using transport mode, the security mechanism must be implemented according to the specification for the transport, and thus messages can flow securely only from point-to-point over the transport. + +#### Message Mode + + In contrast, message mode provides security by including the security data as part of every message. Using XML and SOAP security headers, the credentials and other data needed to ensure the integrity and confidentiality of the message are included with every message. Every message includes security data, so it results in a toll on performance because each message must be individually processed. (In transport mode, once the transport layer is secured, all messages flow freely.) However, message security has one advantage over transport security: it is more flexible. That is, the security requirements are not determined by the transport. You can use any type of client credential to secure the message. (In transport mode, the transport protocol determines the type of client credential that you can use.) + +#### Transport with Message Credentials + + The third mode combines the best of both transport and message security. In this mode, transport security is used to efficiently ensure the confidentiality and integrity of every message. At the same time, every message includes its credential data, which allows the message to be authenticated. With authentication, authorization can also be implemented. By authenticating a sender, access to resources can be granted (or denied) according to the sender's identity. + +## Specifying the Client Credential Type and Credential Value + + After you have selected a security mode, you may also want to specify a client credential type. The client credential type specifies what type a client must use to authenticate itself to the server. + + Not all scenarios require a client credential type, however. Using SSL over HTTP (HTTPS), a service authenticates itself to the client. As part of this authentication, the service's certificate is sent to the client in a process called *negotiation*. The SSL-secured transport ensures that all messages are confidential. + + If you are creating a service that requires that the client be authenticated, your choice of a client credential type depends on the transport and mode selected. For example, using the HTTP transport and choosing transport mode gives you several choices, such as Basic, Digest, and others. (For more information about these credential types, see [Understanding HTTP Authentication](./feature-details/understanding-http-authentication.md).) + + If you are creating a service on a Windows domain that will be available only to other users of the network, the easiest to use is the Windows client credential type. However, you may also need to provide a service with a certificate. This is shown in [How to: Specify Client Credential Values](how-to-specify-client-credential-values.md). + +#### Credential Values + + A *credential value* is the actual credential the service uses. Once you have specified a credential type, you may also need to configure your service with the actual credentials. If you have selected Windows (and the service will run on a Windows domain), then you do not specify an actual credential value. + +## Identity + + In WCF, the term *identity* has different meanings to the server and the client. In brief, when running a service, an identity is assigned to the security context after authentication. To view the actual identity, check the and properties of the class. For more information, see [How to: Examine the Security Context](how-to-examine-the-security-context.md). + + In contrast, on the client, identity is used to validate the service. At design time, a client developer can set the [\](../configure-apps/file-schema/wcf/identity.md) element to a value obtained from the service. At runtime, the client checks the value of the element against the actual identity of the service. If the check fails, the client terminates the communication. The value can be a user principal name (UPN) if the service runs under a particular user's identity or a service principal name (SPN) if the service runs under a machine account. For more information, see [Service Identity and Authentication](./feature-details/service-identity-and-authentication.md). The credential could also be a certificate, or a field found on a certificate that identifies the certificate. + +## Protection Levels + + The `ProtectionLevel` property occurs on several attribute classes (such as the and the classes). The protection level is a value that specifies whether the messages (or message parts) that support a service are signed, signed and encrypted, or sent without signatures or encryption. For more information about the property, see [Understanding Protection Level](understanding-protection-level.md), and for programming examples, see [How to: Set the ProtectionLevel Property](how-to-set-the-protectionlevel-property.md). For more information about designing a service contract with the `ProtectionLevel` in context, see [Designing Service Contracts](designing-service-contracts.md). + ## See also - diff --git a/docs/framework/wcf/servicemodel-metadata-utility-tool-svcutil-exe.md b/docs/framework/wcf/servicemodel-metadata-utility-tool-svcutil-exe.md index ab857e6c56e99..f0f6dfce82a07 100644 --- a/docs/framework/wcf/servicemodel-metadata-utility-tool-svcutil-exe.md +++ b/docs/framework/wcf/servicemodel-metadata-utility-tool-svcutil-exe.md @@ -165,7 +165,7 @@ By default, Svcutil.exe uses the bindings defined in the generate and compile serialization code for those data types at run time, which can result in slow start-up performance. +Services and client applications that use data types that are serializable using the generate and compile serialization code for those data types at runtime, which can result in slow start-up performance. > [!NOTE] > Pre-generated serialization code can only be used in client applications and not in services. diff --git a/docs/framework/wcf/specifying-client-run-time-behavior.md b/docs/framework/wcf/specifying-client-run-time-behavior.md index 1b785e09fd25d..27101c77d84c3 100644 --- a/docs/framework/wcf/specifying-client-run-time-behavior.md +++ b/docs/framework/wcf/specifying-client-run-time-behavior.md @@ -2,46 +2,46 @@ description: "Learn more about: Specifying Client Run-Time Behavior" title: "Specifying Client Run-Time Behavior" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" -helpviewer_keywords: +helpviewer_keywords: - "behaviors [WCF], system-provided client" ms.assetid: d16d3405-be70-4edb-8f62-b5f614ddeca5 --- # Specifying Client Run-Time Behavior -Windows Communication Foundation (WCF) clients, like Windows Communication Foundation (WCF) services, can be configured to modify the run-time behavior to suit the client application. Three attributes are available for specifying client run-time behavior. Duplex client callback objects can use the and attributes to modify their run-time behavior. The other attribute, , can be used to separate the logical destination from the immediate network destination. In addition, duplex client callback types can use some of the service-side behaviors. For more information, see [Specifying Service Run-Time Behavior](specifying-service-run-time-behavior.md). - -## Using the CallbackBehaviorAttribute +Windows Communication Foundation (WCF) clients, like Windows Communication Foundation (WCF) services, can be configured to modify the runtime behavior to suit the client application. Three attributes are available for specifying client runtime behavior. Duplex client callback objects can use the and attributes to modify their runtime behavior. The other attribute, , can be used to separate the logical destination from the immediate network destination. In addition, duplex client callback types can use some of the service-side behaviors. For more information, see [Specifying Service Run-Time Behavior](specifying-service-run-time-behavior.md). + +## Using the CallbackBehaviorAttribute + + You can configure or extend the execution behavior of a callback contract implementation in a client application by using the class. This attribute performs a similar function for the callback class as the class, with the exception of instancing behavior and transaction settings. + + The class must be applied to the class that implements the callback contract. If applied to a nonduplex contract implementation, an exception is thrown at runtime. The following code example shows a class on a callback object that uses the object to determine the thread to marshal to, the property to enforce message validation, and the property to return exceptions as objects to the service for debugging purposes. - You can configure or extend the execution behavior of a callback contract implementation in a client application by using the class. This attribute performs a similar function for the callback class as the class, with the exception of instancing behavior and transaction settings. - - The class must be applied to the class that implements the callback contract. If applied to a nonduplex contract implementation, an exception is thrown at run time. The following code example shows a class on a callback object that uses the object to determine the thread to marshal to, the property to enforce message validation, and the property to return exceptions as objects to the service for debugging purposes. - [!code-csharp[CallbackBehaviorAttribute#3](../../../samples/snippets/csharp/VS_Snippets_CFX/callbackbehaviorattribute/cs/client.cs#3)] - [!code-vb[CallbackBehaviorAttribute#3](../../../samples/snippets/visualbasic/VS_Snippets_CFX/callbackbehaviorattribute/vb/client.vb#3)] - -## Using CallbackDebugBehavior to Enable the Flow of Managed Exception Information - - You can enable the flow of managed exception information in a client callback object back to the service for debugging purposes by setting the property to `true` either programmatically or from an application configuration file. - - Returning managed exception information to services can be a security risk because exception details expose information about the internal client implementation that unauthorized services could use. In addition, although the properties can also be set programmatically, it can be easy to forget to disable when deploying. - - Because of the security issues involved, it is strongly recommended that: - -- You use an application configuration file to set the value of the property to `true`. - -- You do so only in controlled debugging scenarios. - - The following code example shows a client configuration file that instructs WCF to return managed exception information from a client callback object in SOAP messages. - - [!code-xml[SCA.CallbackContract#4](../../../samples/snippets/csharp/VS_Snippets_CFX/sca.callbackcontract/cs/client.exe.config#4)] - -## Using the ClientViaBehavior Behavior - - You can use the behavior to specify the Uniform Resource Identifier for which the transport channel should be created. Use this behavior when the immediate network destination is not the intended processor of the message. This enables multiple-hop conversations when the calling application does not necessarily know the ultimate destination or when the destination `Via` header is not an address. - + [!code-vb[CallbackBehaviorAttribute#3](../../../samples/snippets/visualbasic/VS_Snippets_CFX/callbackbehaviorattribute/vb/client.vb#3)] + +## Using CallbackDebugBehavior to Enable the Flow of Managed Exception Information + + You can enable the flow of managed exception information in a client callback object back to the service for debugging purposes by setting the property to `true` either programmatically or from an application configuration file. + + Returning managed exception information to services can be a security risk because exception details expose information about the internal client implementation that unauthorized services could use. In addition, although the properties can also be set programmatically, it can be easy to forget to disable when deploying. + + Because of the security issues involved, it is strongly recommended that: + +- You use an application configuration file to set the value of the property to `true`. + +- You do so only in controlled debugging scenarios. + + The following code example shows a client configuration file that instructs WCF to return managed exception information from a client callback object in SOAP messages. + + [!code-xml[SCA.CallbackContract#4](../../../samples/snippets/csharp/VS_Snippets_CFX/sca.callbackcontract/cs/client.exe.config#4)] + +## Using the ClientViaBehavior Behavior + + You can use the behavior to specify the Uniform Resource Identifier for which the transport channel should be created. Use this behavior when the immediate network destination is not the intended processor of the message. This enables multiple-hop conversations when the calling application does not necessarily know the ultimate destination or when the destination `Via` header is not an address. + ## See also - [Specifying Service Run-Time Behavior](specifying-service-run-time-behavior.md) diff --git a/docs/framework/wcf/specifying-service-run-time-behavior.md b/docs/framework/wcf/specifying-service-run-time-behavior.md index 634d38e03fe83..aa5f9885cb263 100644 --- a/docs/framework/wcf/specifying-service-run-time-behavior.md +++ b/docs/framework/wcf/specifying-service-run-time-behavior.md @@ -2,128 +2,128 @@ description: "Learn more about: Specifying Service Run-Time Behavior" title: "Specifying Service Run-Time Behavior" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 5c5450ea-6af1-4b75-a267-613d0ac54707 --- # Specifying Service Run-Time Behavior -Once you have designed a service contract ([Designing Service Contracts](designing-service-contracts.md)) and implemented your service contract ([Implementing Service Contracts](implementing-service-contracts.md)) you can configure the operation behavior of the service runtime. This topic discusses system-provided service and operation behaviors and describes where to find more information to create new behaviors. While some behaviors are applied as attributes, many are applied using an application configuration file or programmatically. For more information about configuring your service application, see [Configuring Services](configuring-services.md). - -## Overview - - The contract defines the inputs, outputs, data types, and capabilities of a service of that type. Implementing a service contract creates a class that, when configured with a binding at an address, fulfills the contract it implements. Contractual, binding, and address information are all known by the client; without them, the client cannot make use of the service. - - However, operation specifics, such as threading issues or instance management, are opaque to clients. Once you have implemented your service contract, you can configure a large number of operation characteristics by using *behaviors*. Behaviors are objects that modify the Windows Communication Foundation (WCF) runtime by either setting a runtime property or by inserting a customization type into the runtime. For more information about modifying the runtime by creating user-defined behaviors, see [Extending ServiceHost and the Service Model Layer](./extending/extending-servicehost-and-the-service-model-layer.md). - - The and attributes are the most widely useful behaviors and expose the most commonly requested operation features. Because they are attributes, you apply them to the service or operation implementation. Other behaviors, such as the or , are typically applied using an application configuration file, although you can use them programmatically. - - This topic provides an overview of the and attributes, describes the various scopes at which behaviors can operate, and provides a quick description of many of the system-provided behaviors at the various scopes that may be of interest to WCF developers. - -## ServiceBehaviorAttribute and OperationBehaviorAttribute - - The most important behaviors are the and attributes, which you can use to control: - -- Instance lifetimes - -- Concurrency and synchronization support - -- Configuration behavior - -- Transaction behavior - -- Serialization behavior - -- Metadata transformation - -- Session lifetime - -- Address filtering and header processing - -- Impersonation - -- To use these attributes, mark the service or operation implementation with the attribute appropriate to that scope and set the properties. For example, the following code example shows an operation implementation that uses the property to require that callers of this operation support impersonation. - +Once you have designed a service contract ([Designing Service Contracts](designing-service-contracts.md)) and implemented your service contract ([Implementing Service Contracts](implementing-service-contracts.md)) you can configure the operation behavior of the service runtime. This topic discusses system-provided service and operation behaviors and describes where to find more information to create new behaviors. While some behaviors are applied as attributes, many are applied using an application configuration file or programmatically. For more information about configuring your service application, see [Configuring Services](configuring-services.md). + +## Overview + + The contract defines the inputs, outputs, data types, and capabilities of a service of that type. Implementing a service contract creates a class that, when configured with a binding at an address, fulfills the contract it implements. Contractual, binding, and address information are all known by the client; without them, the client cannot make use of the service. + + However, operation specifics, such as threading issues or instance management, are opaque to clients. Once you have implemented your service contract, you can configure a large number of operation characteristics by using *behaviors*. Behaviors are objects that modify the Windows Communication Foundation (WCF) runtime by either setting a runtime property or by inserting a customization type into the runtime. For more information about modifying the runtime by creating user-defined behaviors, see [Extending ServiceHost and the Service Model Layer](./extending/extending-servicehost-and-the-service-model-layer.md). + + The and attributes are the most widely useful behaviors and expose the most commonly requested operation features. Because they are attributes, you apply them to the service or operation implementation. Other behaviors, such as the or , are typically applied using an application configuration file, although you can use them programmatically. + + This topic provides an overview of the and attributes, describes the various scopes at which behaviors can operate, and provides a quick description of many of the system-provided behaviors at the various scopes that may be of interest to WCF developers. + +## ServiceBehaviorAttribute and OperationBehaviorAttribute + + The most important behaviors are the and attributes, which you can use to control: + +- Instance lifetimes + +- Concurrency and synchronization support + +- Configuration behavior + +- Transaction behavior + +- Serialization behavior + +- Metadata transformation + +- Session lifetime + +- Address filtering and header processing + +- Impersonation + +- To use these attributes, mark the service or operation implementation with the attribute appropriate to that scope and set the properties. For example, the following code example shows an operation implementation that uses the property to require that callers of this operation support impersonation. + [!code-csharp[OperationBehaviorAttribute_Impersonation#1](../../../samples/snippets/csharp/VS_Snippets_CFX/operationbehaviorattribute_impersonation/cs/services.cs#1)] - [!code-vb[OperationBehaviorAttribute_Impersonation#1](../../../samples/snippets/visualbasic/VS_Snippets_CFX/operationbehaviorattribute_impersonation/vb/services.vb#1)] - - Many of the properties require additional support from the binding. For example, an operation that requires a transaction from the client must be configured to use a binding that supports flowed transactions. - -### Well-Known Singleton Services - - You can use the and attributes to control certain lifetimes, both of the and of the service objects that implement the operations. - - For example, the property controls how often the is released, and the and properties control when the service object is released. - - However, you can also create a service object yourself and create the service host using that object. To do so, you must also set the property to or an exception is thrown when the service host is opened. - + [!code-vb[OperationBehaviorAttribute_Impersonation#1](../../../samples/snippets/visualbasic/VS_Snippets_CFX/operationbehaviorattribute_impersonation/vb/services.vb#1)] + + Many of the properties require additional support from the binding. For example, an operation that requires a transaction from the client must be configured to use a binding that supports flowed transactions. + +### Well-Known Singleton Services + + You can use the and attributes to control certain lifetimes, both of the and of the service objects that implement the operations. + + For example, the property controls how often the is released, and the and properties control when the service object is released. + + However, you can also create a service object yourself and create the service host using that object. To do so, you must also set the property to or an exception is thrown when the service host is opened. + Use the constructor to create such a service. It provides an alternative to implementing a custom when you wish to provide a specific object instance for use by a singleton service. You can use this overload when your service implementation type is difficult to construct (for example, if it does not implement a parameterless public constructor). - - Note that when an object is provided to this constructor, some features related to the Windows Communication Foundation (WCF) instancing behavior work differently. For example, calling has no effect when a well-known object instance is provided. Similarly, any other instance release mechanism is ignored. The class always behaves as if the property is set to for all operations. - -## Other Service, Endpoint, Contract, and Operation Behaviors - - Service behaviors, such as the attribute, operate across an entire service. For example, if you set the property to you must handle thread synchronization issues inside each operation in that service yourself. Endpoint behaviors operate across an endpoint; many of the system-provided endpoint behaviors are for client functionality. Contract behaviors operate at the contract level, and operation behaviors modify operation delivery. - - Many of these behaviors are implemented on attributes, and you make use of them as you do the and attributes—by applying them to the appropriate service class or operation implementation. Other behaviors, such as the or objects, are typically applied using an application configuration file, although they can also be used programmatically. - - For example, the publication of metadata is configured by using the object. The following application configuration file shows the most common usage. - - [!code-xml[ServiceMetadataBehavior#1](../../../samples/snippets/csharp/VS_Snippets_CFX/servicemetadatabehavior/cs/hostapplication.exe.config#1)] - - The following sections describe many of the most useful system-provided behaviors that you can use to modify the runtime delivery of your service or client. See the reference topic to determine how to use each one. - -### Service Behaviors - - The following behaviors operate on services. - -- . Applied to a WCF service to indicate whether that service can be run in ASP.NET Compatibility Mode. - -- . Controls how the service authorizes client claims. - -- . Configures a service credential. Use this class to specify the credential for the service, such as an X.509 certificate. - -- . Enables debugging and Help information features for a WCF service. - -- . Controls the publication of service metadata and associated information. - -- . Specifies the audit behavior of security events. - -- . Configures run-time throughput settings that enable you to tune service performance. - -### Endpoint Behaviors - - The following behaviors operate on endpoints. Many of these behaviors are used in client applications. - -- . Configures a callback service implementation in a duplex client application. - -- . Enables service debugging for a WCF callback object. - -- . Allows the user to configure client and service credentials as well as service credential authentication settings for use on the client. - -- . Used by clients to specify the Uniform Resource Identifier (URI) for which the transport channel should be created. - -- . Instructs WCF to disable the `MustUnderstand` processing. - -- . Instructs the runtime to use a synchronous receive process for channels. - -- . Optimizes the receive operations for transports that support transactional receives. - -### Contract Behaviors - - . Specifies the feature requirements that bindings must provide to the service or client implementation. - -### Operation Behaviors - - The following operation behaviors specify serialization and transaction controls for operations. - -- . Represents the run-time behavior of the . - -- . Controls run-time behavior of the `XmlSerializer` and associates it with an operation. - -- . Specifies the level in which a service operation accepts a transaction header. - + + Note that when an object is provided to this constructor, some features related to the Windows Communication Foundation (WCF) instancing behavior work differently. For example, calling has no effect when a well-known object instance is provided. Similarly, any other instance release mechanism is ignored. The class always behaves as if the property is set to for all operations. + +## Other Service, Endpoint, Contract, and Operation Behaviors + + Service behaviors, such as the attribute, operate across an entire service. For example, if you set the property to you must handle thread synchronization issues inside each operation in that service yourself. Endpoint behaviors operate across an endpoint; many of the system-provided endpoint behaviors are for client functionality. Contract behaviors operate at the contract level, and operation behaviors modify operation delivery. + + Many of these behaviors are implemented on attributes, and you make use of them as you do the and attributes—by applying them to the appropriate service class or operation implementation. Other behaviors, such as the or objects, are typically applied using an application configuration file, although they can also be used programmatically. + + For example, the publication of metadata is configured by using the object. The following application configuration file shows the most common usage. + + [!code-xml[ServiceMetadataBehavior#1](../../../samples/snippets/csharp/VS_Snippets_CFX/servicemetadatabehavior/cs/hostapplication.exe.config#1)] + + The following sections describe many of the most useful system-provided behaviors that you can use to modify the runtime delivery of your service or client. See the reference topic to determine how to use each one. + +### Service Behaviors + + The following behaviors operate on services. + +- . Applied to a WCF service to indicate whether that service can be run in ASP.NET Compatibility Mode. + +- . Controls how the service authorizes client claims. + +- . Configures a service credential. Use this class to specify the credential for the service, such as an X.509 certificate. + +- . Enables debugging and Help information features for a WCF service. + +- . Controls the publication of service metadata and associated information. + +- . Specifies the audit behavior of security events. + +- . Configures runtime throughput settings that enable you to tune service performance. + +### Endpoint Behaviors + + The following behaviors operate on endpoints. Many of these behaviors are used in client applications. + +- . Configures a callback service implementation in a duplex client application. + +- . Enables service debugging for a WCF callback object. + +- . Allows the user to configure client and service credentials as well as service credential authentication settings for use on the client. + +- . Used by clients to specify the Uniform Resource Identifier (URI) for which the transport channel should be created. + +- . Instructs WCF to disable the `MustUnderstand` processing. + +- . Instructs the runtime to use a synchronous receive process for channels. + +- . Optimizes the receive operations for transports that support transactional receives. + +### Contract Behaviors + + . Specifies the feature requirements that bindings must provide to the service or client implementation. + +### Operation Behaviors + + The following operation behaviors specify serialization and transaction controls for operations. + +- . Represents the runtime behavior of the . + +- . Controls runtime behavior of the `XmlSerializer` and associates it with an operation. + +- . Specifies the level in which a service operation accepts a transaction header. + ## See also - [Configuring Services](configuring-services.md) diff --git a/docs/framework/wcf/using-sessions.md b/docs/framework/wcf/using-sessions.md index 669ff16651e0b..a7665c6896ddd 100644 --- a/docs/framework/wcf/using-sessions.md +++ b/docs/framework/wcf/using-sessions.md @@ -2,153 +2,153 @@ description: "Learn more about: Using Sessions" title: "Using Sessions" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" -helpviewer_keywords: +helpviewer_keywords: - "sessions [WCF]" ms.assetid: 864ba12f-3331-4359-a359-6d6d387f1035 --- # Using Sessions -In Windows Communication Foundation (WCF) applications, a *session* correlates a group of messages into a conversation. WCF sessions are different than the session object available in ASP.NET applications, support different behaviors, and are controlled in different ways. This topic describes the features that sessions enable in WCF applications and how to use them. - -## Sessions in Windows Communication Foundation Applications - - When a service contract specifies that it requires a session, that contract is specifying that all calls (that is, the underlying message exchanges that support the calls) must be part of the same conversation. If a contract specifies that it allows sessions but does not require one, clients can connect and either establish a session or not establish a session. If the session ends and a message is sent through the same channel an exception is thrown. - - WCF sessions have the following main conceptual features: - -- They are explicitly initiated and terminated by the calling application (the WCF client). - -- Messages delivered during a session are processed in the order in which they are received. - -- Sessions correlate a group of messages into a conversation. Different types of correlation are possible. For instance, one session-based channel may correlate messages based on a shared network connection while another session-based channel may correlate messages based on a shared tag in the message body. The features that can be derived from the session depend on the nature of the correlation. - -- There is no general data store associated with a WCF session. - - If you are familiar with the class in ASP.NET applications and the functionality it provides, you might notice the following differences between that kind of session and WCF sessions: - -- ASP.NET sessions are always server-initiated. - -- ASP.NET sessions are implicitly unordered. - -- ASP.NET sessions provide a general data storage mechanism across requests. - - This topic describes: - -- The default execution behavior when using session-based bindings in the service model layer. - -- The types of features that the WCF session-based, system-provided bindings provide. - -- How to create a contract that declares a session requirement. - -- How to understand and control the creation and termination of the session and the relationship of the session to the service instance. - -## Default Execution Behavior Using Sessions - - A binding that attempts to initiate a session is called a *session-based* binding. Service contracts specify that they require, permit, or refuse session-based bindings by setting the property on the service contract interface (or class) to one of the enumeration values. By default, the value of this property is , which means that if a client uses a session-based binding with a WCF service implementation, the service establishes and uses the session provided. - - When a WCF service accepts a client session, the following features are enabled by default: - -1. All calls between a WCF client object are handled by the same service instance. - -2. Different session-based bindings provide additional features. - -## System-Provided Session Types - - A session-based binding supports the default association of a service instance with a particular session. However, different session-based bindings support different features in addition to enabling the session-based instancing control previously described. - - WCF provides the following types of session-based application behavior: - -- The supports security-based sessions, in which both ends of communication have agreed upon a specific secure conversation. For more information, see [Securing Services](securing-services.md). For example, the binding, which contains support for both security sessions and reliable sessions, by default uses only a secure session that encrypts and digitally signs messages. - -- The binding supports TCP/IP-based sessions to ensure that all messages are correlated by the connection at the socket level. - -- The element, which implements the WS-ReliableMessaging specification, provides support for reliable sessions in which messages can be configured to be delivered in order and exactly once, ensuring messages are received even when messages travel across multiple nodes during the conversation. For more information, see [Reliable Sessions](./feature-details/reliable-sessions.md). - -- The binding provides MSMQ datagram sessions. For more information, see [Queues in WCF](./feature-details/queues-in-wcf.md). - - Setting the property does not specify the type of session the contract requires, only that it requires one. - -## Creating a Contract That Requires a Session - - Creating a contract that requires a session states that the group of operations that the service contract declares must all be executed within the same session and that messages must be delivered in order. To assert the level of session support that a service contract requires, set the property on your service contract interface or class to the value of the enumeration to specify whether the contract: - -- Requires a session. - -- Allows a client to establish a session. - -- Prohibits a session. - - Setting the property does not, however, specify the type of session-based behavior the contract requires. It instructs WCF to confirm at run time that the configured binding (which creates the communication channel) for the service does, does not, or can establish a session when implementing a service. Again, the binding can satisfy that requirement with any type of session-based behavior it chooses—security, transport, reliable, or some combination. The exact behavior depends on the value selected. If the configured binding of the service does not conform to the value of , an exception is thrown. Bindings and the channels they create that support sessions are said to be session-based. - - The following service contract specifies that all operations in the `ICalculatorSession` must be exchanged within a session. None of the operations returns a value to the caller except the `Equals` method. However, the `Equals` method takes no parameters and, therefore, can only return a non-zero value inside a session in which data has already been passed to the other operations. This contract requires a session to function properly. Without a session associated with a specific client, the service instance has no way of knowing what previous data this client has sent. - +In Windows Communication Foundation (WCF) applications, a *session* correlates a group of messages into a conversation. WCF sessions are different than the session object available in ASP.NET applications, support different behaviors, and are controlled in different ways. This topic describes the features that sessions enable in WCF applications and how to use them. + +## Sessions in Windows Communication Foundation Applications + + When a service contract specifies that it requires a session, that contract is specifying that all calls (that is, the underlying message exchanges that support the calls) must be part of the same conversation. If a contract specifies that it allows sessions but does not require one, clients can connect and either establish a session or not establish a session. If the session ends and a message is sent through the same channel an exception is thrown. + + WCF sessions have the following main conceptual features: + +- They are explicitly initiated and terminated by the calling application (the WCF client). + +- Messages delivered during a session are processed in the order in which they are received. + +- Sessions correlate a group of messages into a conversation. Different types of correlation are possible. For instance, one session-based channel may correlate messages based on a shared network connection while another session-based channel may correlate messages based on a shared tag in the message body. The features that can be derived from the session depend on the nature of the correlation. + +- There is no general data store associated with a WCF session. + + If you are familiar with the class in ASP.NET applications and the functionality it provides, you might notice the following differences between that kind of session and WCF sessions: + +- ASP.NET sessions are always server-initiated. + +- ASP.NET sessions are implicitly unordered. + +- ASP.NET sessions provide a general data storage mechanism across requests. + + This topic describes: + +- The default execution behavior when using session-based bindings in the service model layer. + +- The types of features that the WCF session-based, system-provided bindings provide. + +- How to create a contract that declares a session requirement. + +- How to understand and control the creation and termination of the session and the relationship of the session to the service instance. + +## Default Execution Behavior Using Sessions + + A binding that attempts to initiate a session is called a *session-based* binding. Service contracts specify that they require, permit, or refuse session-based bindings by setting the property on the service contract interface (or class) to one of the enumeration values. By default, the value of this property is , which means that if a client uses a session-based binding with a WCF service implementation, the service establishes and uses the session provided. + + When a WCF service accepts a client session, the following features are enabled by default: + +1. All calls between a WCF client object are handled by the same service instance. + +2. Different session-based bindings provide additional features. + +## System-Provided Session Types + + A session-based binding supports the default association of a service instance with a particular session. However, different session-based bindings support different features in addition to enabling the session-based instancing control previously described. + + WCF provides the following types of session-based application behavior: + +- The supports security-based sessions, in which both ends of communication have agreed upon a specific secure conversation. For more information, see [Securing Services](securing-services.md). For example, the binding, which contains support for both security sessions and reliable sessions, by default uses only a secure session that encrypts and digitally signs messages. + +- The binding supports TCP/IP-based sessions to ensure that all messages are correlated by the connection at the socket level. + +- The element, which implements the WS-ReliableMessaging specification, provides support for reliable sessions in which messages can be configured to be delivered in order and exactly once, ensuring messages are received even when messages travel across multiple nodes during the conversation. For more information, see [Reliable Sessions](./feature-details/reliable-sessions.md). + +- The binding provides MSMQ datagram sessions. For more information, see [Queues in WCF](./feature-details/queues-in-wcf.md). + + Setting the property does not specify the type of session the contract requires, only that it requires one. + +## Creating a Contract That Requires a Session + + Creating a contract that requires a session states that the group of operations that the service contract declares must all be executed within the same session and that messages must be delivered in order. To assert the level of session support that a service contract requires, set the property on your service contract interface or class to the value of the enumeration to specify whether the contract: + +- Requires a session. + +- Allows a client to establish a session. + +- Prohibits a session. + + Setting the property does not, however, specify the type of session-based behavior the contract requires. It instructs WCF to confirm at runtime that the configured binding (which creates the communication channel) for the service does, does not, or can establish a session when implementing a service. Again, the binding can satisfy that requirement with any type of session-based behavior it chooses—security, transport, reliable, or some combination. The exact behavior depends on the value selected. If the configured binding of the service does not conform to the value of , an exception is thrown. Bindings and the channels they create that support sessions are said to be session-based. + + The following service contract specifies that all operations in the `ICalculatorSession` must be exchanged within a session. None of the operations returns a value to the caller except the `Equals` method. However, the `Equals` method takes no parameters and, therefore, can only return a non-zero value inside a session in which data has already been passed to the other operations. This contract requires a session to function properly. Without a session associated with a specific client, the service instance has no way of knowing what previous data this client has sent. + [!code-csharp[S_Service_Session#1](../../../samples/snippets/csharp/VS_Snippets_CFX/s_service_session/cs/service.cs#1)] - [!code-vb[S_Service_Session#1](../../../samples/snippets/visualbasic/VS_Snippets_CFX/s_service_session/vb/service.vb#1)] - - If a service allows a session, then a session is established and used if the client initiates one; otherwise, no session is established. - -## Sessions and Service Instances - - If you use the default instancing behavior in WCF, all calls between a WCF client object are handled by the same service instance. Therefore, at the application level, you can think of a session as enabling application behavior similar to local call behavior. For example, when you create a local object: - -- A constructor is called. - -- All subsequent calls made to the WCF client object reference are processed by the same object instance. - -- A destructor is called when the object reference is destroyed. - - Sessions enable a similar behavior between clients and services as long as the default service instance behavior is used. If a service contract requires or supports sessions, one or more contract operations can be marked as initiating or terminating a session by setting the and properties. - - *Initiating operations* are those that must be called as the first operation of a new session. Non-initiating operations can be called only after at least one initiating operation has been called. You can therefore create a kind of session constructor for your service by declaring initiating operations designed to take input from clients appropriate to the beginning of the service instance. (The state is associated with the session, however, and not the service object.) - - *Terminating operations*, conversely, are those that must be called as the last message in an existing session. In the default case, WCF recycles the service object and its context after the session with which the service was associated is closed. You can, therefore, create a kind of destructor by declaring terminating operations designed to perform a function appropriate to the end of the service instance. - + [!code-vb[S_Service_Session#1](../../../samples/snippets/visualbasic/VS_Snippets_CFX/s_service_session/vb/service.vb#1)] + + If a service allows a session, then a session is established and used if the client initiates one; otherwise, no session is established. + +## Sessions and Service Instances + + If you use the default instancing behavior in WCF, all calls between a WCF client object are handled by the same service instance. Therefore, at the application level, you can think of a session as enabling application behavior similar to local call behavior. For example, when you create a local object: + +- A constructor is called. + +- All subsequent calls made to the WCF client object reference are processed by the same object instance. + +- A destructor is called when the object reference is destroyed. + + Sessions enable a similar behavior between clients and services as long as the default service instance behavior is used. If a service contract requires or supports sessions, one or more contract operations can be marked as initiating or terminating a session by setting the and properties. + + *Initiating operations* are those that must be called as the first operation of a new session. Non-initiating operations can be called only after at least one initiating operation has been called. You can therefore create a kind of session constructor for your service by declaring initiating operations designed to take input from clients appropriate to the beginning of the service instance. (The state is associated with the session, however, and not the service object.) + + *Terminating operations*, conversely, are those that must be called as the last message in an existing session. In the default case, WCF recycles the service object and its context after the session with which the service was associated is closed. You can, therefore, create a kind of destructor by declaring terminating operations designed to perform a function appropriate to the end of the service instance. + > [!NOTE] -> Although the default behavior bears a resemblance to local constructors and destructors, it is only a resemblance. Any WCF service operation can be an initiating or terminating operation, or both at the same time. In addition, in the default case, initiating operations can be called any number of times in any order; no additional sessions are created once the session is established and associated with an instance unless you explicitly control the lifetime of the service instance (by manipulating the object). Finally, the state is associated with the session and not the service object. - - For example, the `ICalculatorSession` contract used in the preceding example requires that the WCF client object first call the `Clear` operation prior to any other operation and that the session with this WCF client object should terminate when it calls the `Equals` operation. The following code example shows a contract that enforces these requirements. `Clear` must be called first to initiate a session, and that session ends when `Equals` is called. - +> Although the default behavior bears a resemblance to local constructors and destructors, it is only a resemblance. Any WCF service operation can be an initiating or terminating operation, or both at the same time. In addition, in the default case, initiating operations can be called any number of times in any order; no additional sessions are created once the session is established and associated with an instance unless you explicitly control the lifetime of the service instance (by manipulating the object). Finally, the state is associated with the session and not the service object. + + For example, the `ICalculatorSession` contract used in the preceding example requires that the WCF client object first call the `Clear` operation prior to any other operation and that the session with this WCF client object should terminate when it calls the `Equals` operation. The following code example shows a contract that enforces these requirements. `Clear` must be called first to initiate a session, and that session ends when `Equals` is called. + [!code-csharp[SCA.IsInitiatingIsTerminating#1](../../../samples/snippets/csharp/VS_Snippets_CFX/sca.isinitiatingisterminating/cs/service.cs#1)] - [!code-vb[SCA.IsInitiatingIsTerminating#1](../../../samples/snippets/visualbasic/VS_Snippets_CFX/sca.isinitiatingisterminating/vb/service.vb#1)] - - Services do not start sessions with clients. In WCF client applications, a direct relationship exists between the lifetime of the session-based channel and the lifetime of the session itself. As such, clients create new sessions by creating new session-based channels and tear down existing sessions by closing session-based channels gracefully. A client starts a session with a service endpoint by calling one of the following: - -- on the channel returned by a call to . - -- on the WCF client object generated by the [ServiceModel Metadata Utility Tool (Svcutil.exe)](servicemodel-metadata-utility-tool-svcutil-exe.md). - -- An initiating operation on either type of WCF client object (by default, all operations are initiating). When the first operation is called, the WCF client object automatically opens the channel and initiates a session. - - Typically a client ends a session with a service endpoint by calling one of the following: - -- on the channel returned by a call to . - -- on the WCF client object generated by Svcutil.exe. - -- A terminating operation on either type of WCF client object (by default, no operations are terminating; the contract must explicitly specify a terminating operation). When the first operation is called, the WCF client object automatically opens the channel and initiates a session. - - For examples, see [How to: Create a Service That Requires Sessions](./feature-details/how-to-create-a-service-that-requires-sessions.md) as well as the [Default Service Behavior](./samples/default-service-behavior.md) and [Instancing](./samples/instancing.md) samples. - - For more information about clients and sessions, see [Accessing Services Using a WCF Client](./feature-details/accessing-services-using-a-client.md). - -## Sessions Interact with InstanceContext Settings - - There is an interaction between the enumeration in a contract and the property, which controls the association between channels and specific service objects. For more information, see [Sessions, Instancing, and Concurrency](./feature-details/sessions-instancing-and-concurrency.md). - -### Sharing InstanceContext Objects + [!code-vb[SCA.IsInitiatingIsTerminating#1](../../../samples/snippets/visualbasic/VS_Snippets_CFX/sca.isinitiatingisterminating/vb/service.vb#1)] + + Services do not start sessions with clients. In WCF client applications, a direct relationship exists between the lifetime of the session-based channel and the lifetime of the session itself. As such, clients create new sessions by creating new session-based channels and tear down existing sessions by closing session-based channels gracefully. A client starts a session with a service endpoint by calling one of the following: + +- on the channel returned by a call to . + +- on the WCF client object generated by the [ServiceModel Metadata Utility Tool (Svcutil.exe)](servicemodel-metadata-utility-tool-svcutil-exe.md). + +- An initiating operation on either type of WCF client object (by default, all operations are initiating). When the first operation is called, the WCF client object automatically opens the channel and initiates a session. + + Typically a client ends a session with a service endpoint by calling one of the following: + +- on the channel returned by a call to . + +- on the WCF client object generated by Svcutil.exe. + +- A terminating operation on either type of WCF client object (by default, no operations are terminating; the contract must explicitly specify a terminating operation). When the first operation is called, the WCF client object automatically opens the channel and initiates a session. + + For examples, see [How to: Create a Service That Requires Sessions](./feature-details/how-to-create-a-service-that-requires-sessions.md) as well as the [Default Service Behavior](./samples/default-service-behavior.md) and [Instancing](./samples/instancing.md) samples. + + For more information about clients and sessions, see [Accessing Services Using a WCF Client](./feature-details/accessing-services-using-a-client.md). + +## Sessions Interact with InstanceContext Settings + + There is an interaction between the enumeration in a contract and the property, which controls the association between channels and specific service objects. For more information, see [Sessions, Instancing, and Concurrency](./feature-details/sessions-instancing-and-concurrency.md). + +### Sharing InstanceContext Objects You can also control which session-based channel or call is associated with which object by performing that association yourself. - -## Sessions and Streaming - When you have a large amount of data to transfer, the streaming transfer mode in WCF is a feasible alternative to the default behavior of buffering and processing messages in memory in their entirety. You may get unexpected behavior when streaming calls with a session-based binding. All streaming calls are made through a single channel (the datagram channel) that does not support sessions even if the binding being used is configured to use sessions. If multiple clients make streaming calls to the same service object over a session-based binding, and the service object's concurrency mode is set to single and its instance context mode is set to `PerSession`, all calls must go through the datagram channel and so only one call is processed at a time. One or more clients may then time out. You can work around this issue by either setting the service object's `InstanceContextMode` to `PerCall` or Concurrency to multiple. - +## Sessions and Streaming + + When you have a large amount of data to transfer, the streaming transfer mode in WCF is a feasible alternative to the default behavior of buffering and processing messages in memory in their entirety. You may get unexpected behavior when streaming calls with a session-based binding. All streaming calls are made through a single channel (the datagram channel) that does not support sessions even if the binding being used is configured to use sessions. If multiple clients make streaming calls to the same service object over a session-based binding, and the service object's concurrency mode is set to single and its instance context mode is set to `PerSession`, all calls must go through the datagram channel and so only one call is processed at a time. One or more clients may then time out. You can work around this issue by either setting the service object's `InstanceContextMode` to `PerCall` or Concurrency to multiple. + > [!NOTE] -> MaxConcurrentSessions have no effect in this case because there is only one "session" available. - +> MaxConcurrentSessions have no effect in this case because there is only one "session" available. + ## See also - diff --git a/docs/framework/wcf/wcf-client-overview.md b/docs/framework/wcf/wcf-client-overview.md index c5b8cf19b7892..b4004d9be7148 100644 --- a/docs/framework/wcf/wcf-client-overview.md +++ b/docs/framework/wcf/wcf-client-overview.md @@ -2,182 +2,182 @@ title: "WCF Client Overview" description: Learn about what client applications do, how to configure, create, and use a WCF client, and how to secure client applications. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" -helpviewer_keywords: +helpviewer_keywords: - "clients [WCF], architecture" ms.assetid: f60d9bc5-8ade-4471-8ecf-5a07a936c82d --- # WCF client overview -This section describes what client applications do, how to configure, create, and use a Windows Communication Foundation (WCF) client, and how to secure client applications. - -## Using WCF Client Objects - - A client application is a managed application that uses a WCF client to communicate with another application. Creating a client application for a WCF service requires the following steps: - -1. Obtain the service contract, bindings, and address information for a service endpoint. - -2. Create a WCF client using that information. - -3. Call operations. - -4. Close the WCF client object. - -The following sections discuss these steps and provide brief introductions to the following issues: - -- Handling errors. - -- Configuring and securing clients. - -- Creating callback objects for duplex services. - -- Calling services asynchronously. - -- Calling services using client channels. - -## Obtain the Service Contract, Bindings, and Addresses - - In WCF, services and clients model contracts using managed attributes, interfaces, and methods. To connect to a service in a client application, you need to obtain the type information for the service contract. Typically, you obtain type information for the service contract by using the [ServiceModel Metadata Utility Tool (Svcutil.exe)](servicemodel-metadata-utility-tool-svcutil-exe.md). The utility downloads metadata from the service, converts it to a managed source code file in the language of your choice, and creates a client application configuration file that you can use to configure your WCF client object. For example, if you are going to create a WCF client object to invoke a `MyCalculatorService`, and you know that the metadata for that service is published at `http://computerName/MyCalculatorService/Service.svc?wsdl`, then the following code example shows how to use Svcutil.exe to obtain a `ClientCode.vb` file that contains the service contract in managed code. - -```console -svcutil /language:vb /out:ClientCode.vb /config:app.config http://computerName/MyCalculatorService/Service.svc?wsdl -``` - - You can either compile this contract code into the client application or into another assembly that the client application can then use to create a WCF client object. You can use the configuration file to configure the client object to properly connect to the service . - - For an example of this process, see [How to: Create a Client](how-to-create-a-wcf-client.md). For more complete information about contracts, see [Contracts](./feature-details/contracts.md). - -## Create a WCF Client Object - - A WCF client is a local object that represents a WCF service in a form that the client can use to communicate with the remote service. WCF client types implement the target service contract, so when you create one and configure it, you can then use the client object directly to invoke service operations. The WCF run time converts the method calls into messages, sends them to the service, listens for the reply, and returns those values to the WCF client object as return values or `out` or `ref` parameters. - - You can also use WCF client channel objects to connect with and use services. For details, see [WCF Client Architecture](./feature-details/client-architecture.md). - -#### Creating a New WCF Object - - To illustrate the use of a class, assume the following simple service contract has been generated from a service application. - +This section describes what client applications do, how to configure, create, and use a Windows Communication Foundation (WCF) client, and how to secure client applications. + +## Using WCF Client Objects + + A client application is a managed application that uses a WCF client to communicate with another application. Creating a client application for a WCF service requires the following steps: + +1. Obtain the service contract, bindings, and address information for a service endpoint. + +2. Create a WCF client using that information. + +3. Call operations. + +4. Close the WCF client object. + +The following sections discuss these steps and provide brief introductions to the following issues: + +- Handling errors. + +- Configuring and securing clients. + +- Creating callback objects for duplex services. + +- Calling services asynchronously. + +- Calling services using client channels. + +## Obtain the Service Contract, Bindings, and Addresses + + In WCF, services and clients model contracts using managed attributes, interfaces, and methods. To connect to a service in a client application, you need to obtain the type information for the service contract. Typically, you obtain type information for the service contract by using the [ServiceModel Metadata Utility Tool (Svcutil.exe)](servicemodel-metadata-utility-tool-svcutil-exe.md). The utility downloads metadata from the service, converts it to a managed source code file in the language of your choice, and creates a client application configuration file that you can use to configure your WCF client object. For example, if you are going to create a WCF client object to invoke a `MyCalculatorService`, and you know that the metadata for that service is published at `http://computerName/MyCalculatorService/Service.svc?wsdl`, then the following code example shows how to use Svcutil.exe to obtain a `ClientCode.vb` file that contains the service contract in managed code. + +```console +svcutil /language:vb /out:ClientCode.vb /config:app.config http://computerName/MyCalculatorService/Service.svc?wsdl +``` + + You can either compile this contract code into the client application or into another assembly that the client application can then use to create a WCF client object. You can use the configuration file to configure the client object to properly connect to the service . + + For an example of this process, see [How to: Create a Client](how-to-create-a-wcf-client.md). For more complete information about contracts, see [Contracts](./feature-details/contracts.md). + +## Create a WCF Client Object + + A WCF client is a local object that represents a WCF service in a form that the client can use to communicate with the remote service. WCF client types implement the target service contract, so when you create one and configure it, you can then use the client object directly to invoke service operations. The WCF runtime converts the method calls into messages, sends them to the service, listens for the reply, and returns those values to the WCF client object as return values or `out` or `ref` parameters. + + You can also use WCF client channel objects to connect with and use services. For details, see [WCF Client Architecture](./feature-details/client-architecture.md). + +#### Creating a New WCF Object + + To illustrate the use of a class, assume the following simple service contract has been generated from a service application. + > [!NOTE] -> If you are using Visual Studio to create your WCF client, objects are loaded automatically into the object browser when you add a service reference to your project. - - [!code-csharp[C_GeneratedCodeFiles#12](../../../samples/snippets/csharp/VS_Snippets_CFX/c_generatedcodefiles/cs/proxycode.cs#12)] - - If you are not using Visual Studio, examine the generated contract code to find the type that extends and the service contract interface `ISampleService`. In this case, that type looks like the following code: - - [!code-csharp[C_GeneratedCodeFiles#14](../../../samples/snippets/csharp/VS_Snippets_CFX/c_generatedcodefiles/cs/proxycode.cs#14)] - - This class can be created as a local object using one of the constructors, configured, and then used to connect to a service of the type `ISampleService`. - - It is recommended that you create your WCF client object first, and then use it and close it inside a single try/catch block. Don't use the `using` statement (`Using` in Visual Basic) because it can mask exceptions in certain failure modes. For more information, see the following sections as well as [Use Close and Abort to release WCF client resources](./samples/use-close-abort-release-wcf-client-resources.md). - -### Contracts, Bindings, and Addresses - - Before you can create a WCF client object, you must configure the client object. Specifically, it must have a service *endpoint* to use. An endpoint is the combination of a service contract, a binding, and an address. (For more information about endpoints, see [Endpoints: Addresses, Bindings, and Contracts](./feature-details/endpoints-addresses-bindings-and-contracts.md).) Typically, this information is located in the [\](../configure-apps/file-schema/wcf/endpoint-of-client.md) element in a client application configuration file, such as the one the Svcutil.exe tool generates, and is loaded automatically when you create your client object. Both WCF client types also have overloads that enable you to programmatically specify this information. - - For example, a generated configuration file for an `ISampleService` used in the preceding examples contains the following endpoint information. - - [!code-xml[C_GeneratedCodeFiles#19](../../../samples/snippets/csharp/VS_Snippets_CFX/c_generatedcodefiles/common/client.exe.config#19)] - - This configuration file specifies a target endpoint in the `` element. For more information about using multiple target endpoints, see the or the constructors. - -## Calling Operations - - Once you have a client object created and configured, create a try/catch block, call operations in the same way that you would if the object were local, and close the WCF client object. When the client application calls the first operation, WCF automatically opens the underlying channel, and the underlying channel is closed when the object is recycled. (Alternatively, you can also explicitly open and close the channel prior to or subsequent to calling other operations.) - - For example, if you have the following service contract: - -```csharp -namespace Microsoft.ServiceModel.Samples -{ - using System; - using System.ServiceModel; - - [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")] - public interface ICalculator - { - [OperationContract] - double Add(double n1, double n2); - [OperationContract] - double Subtract(double n1, double n2); - [OperationContract] - double Multiply(double n1, double n2); - [OperationContract] - double Divide(double n1, double n2); - } -} -``` - -```vb -Namespace Microsoft.ServiceModel.Samples - - Imports System - Imports System.ServiceModel - - If you are using Visual Studio to create your WCF client, objects are loaded automatically into the object browser when you add a service reference to your project. + + [!code-csharp[C_GeneratedCodeFiles#12](../../../samples/snippets/csharp/VS_Snippets_CFX/c_generatedcodefiles/cs/proxycode.cs#12)] + + If you are not using Visual Studio, examine the generated contract code to find the type that extends and the service contract interface `ISampleService`. In this case, that type looks like the following code: + + [!code-csharp[C_GeneratedCodeFiles#14](../../../samples/snippets/csharp/VS_Snippets_CFX/c_generatedcodefiles/cs/proxycode.cs#14)] + + This class can be created as a local object using one of the constructors, configured, and then used to connect to a service of the type `ISampleService`. + + It is recommended that you create your WCF client object first, and then use it and close it inside a single try/catch block. Don't use the `using` statement (`Using` in Visual Basic) because it can mask exceptions in certain failure modes. For more information, see the following sections as well as [Use Close and Abort to release WCF client resources](./samples/use-close-abort-release-wcf-client-resources.md). + +### Contracts, Bindings, and Addresses + + Before you can create a WCF client object, you must configure the client object. Specifically, it must have a service *endpoint* to use. An endpoint is the combination of a service contract, a binding, and an address. (For more information about endpoints, see [Endpoints: Addresses, Bindings, and Contracts](./feature-details/endpoints-addresses-bindings-and-contracts.md).) Typically, this information is located in the [\](../configure-apps/file-schema/wcf/endpoint-of-client.md) element in a client application configuration file, such as the one the Svcutil.exe tool generates, and is loaded automatically when you create your client object. Both WCF client types also have overloads that enable you to programmatically specify this information. + + For example, a generated configuration file for an `ISampleService` used in the preceding examples contains the following endpoint information. + + [!code-xml[C_GeneratedCodeFiles#19](../../../samples/snippets/csharp/VS_Snippets_CFX/c_generatedcodefiles/common/client.exe.config#19)] + + This configuration file specifies a target endpoint in the `` element. For more information about using multiple target endpoints, see the or the constructors. + +## Calling Operations + + Once you have a client object created and configured, create a try/catch block, call operations in the same way that you would if the object were local, and close the WCF client object. When the client application calls the first operation, WCF automatically opens the underlying channel, and the underlying channel is closed when the object is recycled. (Alternatively, you can also explicitly open and close the channel prior to or subsequent to calling other operations.) + + For example, if you have the following service contract: + +```csharp +namespace Microsoft.ServiceModel.Samples +{ + using System; + using System.ServiceModel; + + [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")] + public interface ICalculator + { + [OperationContract] + double Add(double n1, double n2); + [OperationContract] + double Subtract(double n1, double n2); + [OperationContract] + double Multiply(double n1, double n2); + [OperationContract] + double Divide(double n1, double n2); + } +} +``` + +```vb +Namespace Microsoft.ServiceModel.Samples + + Imports System + Imports System.ServiceModel + + _ - Public Interface ICalculator + Public Interface ICalculator _ - Function Add(n1 As Double, n2 As Double) As Double + Function Add(n1 As Double, n2 As Double) As Double _ - Function Subtract(n1 As Double, n2 As Double) As Double + Function Subtract(n1 As Double, n2 As Double) As Double _ - Function Multiply(n1 As Double, n2 As Double) As Double + Function Multiply(n1 As Double, n2 As Double) As Double _ - Function Divide(n1 As Double, n2 As Double) As Double -End Interface -``` - - You can call operations by creating a WCF client object and calling its methods, as the following code example demonstrates. The opening, calling, and closing of the WCF client object occurs within a single try/catch block. For more information, see [Accessing Services Using a WCF Client](./feature-details/accessing-services-using-a-client.md) and [Use Close and Abort to release WCF client resources](./samples/use-close-abort-release-wcf-client-resources.md). - - [!code-csharp[C_GeneratedCodeFiles#20](../../../samples/snippets/csharp/VS_Snippets_CFX/c_generatedcodefiles/cs/proxycode.cs#20)] - -## Handling Errors - - Exceptions can occur in a client application when opening the underlying client channel (whether explicitly or automatically by calling an operation), using the client or channel object to call operations, or when closing the underlying client channel. It is recommended at a minimum that applications expect to handle possible and exceptions in addition to any objects thrown as a result of SOAP faults returned by operations. SOAP faults specified in the operation contract are raised to client applications as a where the type parameter is the detail type of the SOAP fault. For more information about handling error conditions in a client application, see [Sending and Receiving Faults](sending-and-receiving-faults.md). For a complete sample the shows how to handle errors in a client, see [Expected Exceptions](./samples/expected-exceptions.md). - -## Configuring and Securing Clients - - Configuring a client starts with the required loading of target endpoint information for the client or channel object, usually from a configuration file, although you can also load this information programmatically using the client constructors and properties. However, additional configuration steps are required to enable certain client behavior and for many security scenarios. - - For example, security requirements for service contracts are declared in the service contract interface, and if Svcutil.exe created a configuration file, that file usually contains a binding that is capable of supporting the security requirements of the service. In some cases, however, more security configuration may be required, such as configuring client credentials. For complete information about the configuration of security for WCF clients, see [Securing Clients](securing-clients.md). - - In addition, some custom modifications can be enabled in client applications, such as custom run-time behaviors. For more information about how to configure a custom client behavior, see [Configuring Client Behaviors](configuring-client-behaviors.md). - -## Creating Callback Objects for Duplex Services - - Duplex services specify a callback contract that the client application must implement in order to provide a callback object for the service to call according to the requirements of the contract. Although callback objects are not full services (for example, you cannot initiate a channel with a callback object), for the purposes of implementation and configuration they can be thought of as a kind of service. - - Clients of duplex services must: - -- Implement a callback contract class. - -- Create an instance of the callback contract implementation class and use it to create the object that you pass to the WCF client constructor. - -- Invoke operations and handle operation callbacks. - - Duplex WCF client objects function like their nonduplex counterparts, with the exception that they expose the functionality necessary to support callbacks, including the configuration of the callback service. - - For example, you can control various aspects of callback object runtime behavior by using properties of the attribute on the callback class. Another example is the use of the class to enable the return of exception information to services that call the callback object. For more information, see [Duplex Services](./feature-details/duplex-services.md). For a complete sample, see [Duplex](./samples/duplex.md). - - On Windows XP computers running Internet Information Services (IIS) 5.1, duplex clients must specify a client base address using the class or an exception is thrown. The following code example shows how to do this in code. - + Function Divide(n1 As Double, n2 As Double) As Double +End Interface +``` + + You can call operations by creating a WCF client object and calling its methods, as the following code example demonstrates. The opening, calling, and closing of the WCF client object occurs within a single try/catch block. For more information, see [Accessing Services Using a WCF Client](./feature-details/accessing-services-using-a-client.md) and [Use Close and Abort to release WCF client resources](./samples/use-close-abort-release-wcf-client-resources.md). + + [!code-csharp[C_GeneratedCodeFiles#20](../../../samples/snippets/csharp/VS_Snippets_CFX/c_generatedcodefiles/cs/proxycode.cs#20)] + +## Handling Errors + + Exceptions can occur in a client application when opening the underlying client channel (whether explicitly or automatically by calling an operation), using the client or channel object to call operations, or when closing the underlying client channel. It is recommended at a minimum that applications expect to handle possible and exceptions in addition to any objects thrown as a result of SOAP faults returned by operations. SOAP faults specified in the operation contract are raised to client applications as a where the type parameter is the detail type of the SOAP fault. For more information about handling error conditions in a client application, see [Sending and Receiving Faults](sending-and-receiving-faults.md). For a complete sample the shows how to handle errors in a client, see [Expected Exceptions](./samples/expected-exceptions.md). + +## Configuring and Securing Clients + + Configuring a client starts with the required loading of target endpoint information for the client or channel object, usually from a configuration file, although you can also load this information programmatically using the client constructors and properties. However, additional configuration steps are required to enable certain client behavior and for many security scenarios. + + For example, security requirements for service contracts are declared in the service contract interface, and if Svcutil.exe created a configuration file, that file usually contains a binding that is capable of supporting the security requirements of the service. In some cases, however, more security configuration may be required, such as configuring client credentials. For complete information about the configuration of security for WCF clients, see [Securing Clients](securing-clients.md). + + In addition, some custom modifications can be enabled in client applications, such as custom runtime behaviors. For more information about how to configure a custom client behavior, see [Configuring Client Behaviors](configuring-client-behaviors.md). + +## Creating Callback Objects for Duplex Services + + Duplex services specify a callback contract that the client application must implement in order to provide a callback object for the service to call according to the requirements of the contract. Although callback objects are not full services (for example, you cannot initiate a channel with a callback object), for the purposes of implementation and configuration they can be thought of as a kind of service. + + Clients of duplex services must: + +- Implement a callback contract class. + +- Create an instance of the callback contract implementation class and use it to create the object that you pass to the WCF client constructor. + +- Invoke operations and handle operation callbacks. + + Duplex WCF client objects function like their nonduplex counterparts, with the exception that they expose the functionality necessary to support callbacks, including the configuration of the callback service. + + For example, you can control various aspects of callback object runtime behavior by using properties of the attribute on the callback class. Another example is the use of the class to enable the return of exception information to services that call the callback object. For more information, see [Duplex Services](./feature-details/duplex-services.md). For a complete sample, see [Duplex](./samples/duplex.md). + + On Windows XP computers running Internet Information Services (IIS) 5.1, duplex clients must specify a client base address using the class or an exception is thrown. The following code example shows how to do this in code. + [!code-csharp[S_DualHttp#8](../../../samples/snippets/csharp/VS_Snippets_CFX/s_dualhttp/cs/program.cs#8)] - [!code-vb[S_DualHttp#8](../../../samples/snippets/visualbasic/VS_Snippets_CFX/s_dualhttp/vb/module1.vb#8)] - - The following code shows how to do this in a configuration file - - [!code-csharp[S_DualHttp#134](../../../samples/snippets/csharp/VS_Snippets_CFX/s_dualhttp/cs/program.cs#134)] - -## Calling Services Asynchronously - - How operations are called is entirely up to the client developer. This is because the messages that make up an operation can be mapped to either synchronous or asynchronous methods when expressed in managed code. Therefore, if you want to build a client that calls operations asynchronously, you can use Svcutil.exe to generate asynchronous client code using the `/async` option. For more information, see [How to: Call Service Operations Asynchronously](./feature-details/how-to-call-wcf-service-operations-asynchronously.md). - -## Calling Services Using WCF Client Channels - - WCF client types extend , which itself derives from interface to expose the underlying channel system. You can invoke services by using the target service contract with the class. For details, see [WCF Client Architecture](./feature-details/client-architecture.md). - + [!code-vb[S_DualHttp#8](../../../samples/snippets/visualbasic/VS_Snippets_CFX/s_dualhttp/vb/module1.vb#8)] + + The following code shows how to do this in a configuration file + + [!code-csharp[S_DualHttp#134](../../../samples/snippets/csharp/VS_Snippets_CFX/s_dualhttp/cs/program.cs#134)] + +## Calling Services Asynchronously + + How operations are called is entirely up to the client developer. This is because the messages that make up an operation can be mapped to either synchronous or asynchronous methods when expressed in managed code. Therefore, if you want to build a client that calls operations asynchronously, you can use Svcutil.exe to generate asynchronous client code using the `/async` option. For more information, see [How to: Call Service Operations Asynchronously](./feature-details/how-to-call-wcf-service-operations-asynchronously.md). + +## Calling Services Using WCF Client Channels + + WCF client types extend , which itself derives from interface to expose the underlying channel system. You can invoke services by using the target service contract with the class. For details, see [WCF Client Architecture](./feature-details/client-architecture.md). + ## See also - diff --git a/docs/framework/whats-new/index.md b/docs/framework/whats-new/index.md index 8dce626ae2a20..7c739c98a36b8 100644 --- a/docs/framework/whats-new/index.md +++ b/docs/framework/whats-new/index.md @@ -663,13 +663,13 @@ In addition, a major focus in .NET Framework 4.7.1 is improved accessibility, wh **Support for configuration builders** -Configuration builders allow developers to inject and build configuration settings for applications dynamically at run time. Custom configuration builders can be used to modify existing data in a configuration section or to build a configuration section entirely from scratch. Without configuration builders, .config files are static, and their settings are defined some time before an application is launched. +Configuration builders allow developers to inject and build configuration settings for applications dynamically at runtime. Custom configuration builders can be used to modify existing data in a configuration section or to build a configuration section entirely from scratch. Without configuration builders, .config files are static, and their settings are defined some time before an application is launched. To create a custom configuration builder, you derive your builder from the abstract class and override its and . You also define your builders in your .config file. For more information, see the "Configuration Builders" section in the [.NET Framework 4.7.1 ASP.NET and Configuration Features](https://devblogs.microsoft.com/dotnet/net-framework-4-7-1-asp-net-and-configuration-features/) blog post. -**Run-time feature detection** +**Runtime feature detection** -The class provides a mechanism for determine whether a predefined feature is supported on a given .NET implementation at compile time or run time. At compile time, a compiler can check whether a specified field exists to determine whether the feature is supported; if so, it can emit code that takes advantage of that feature. At run time, an application can call the method before emitting code at run time. For more information, see [Add helper method to describe features supported by the runtime](https://github.com/dotnet/corefx/issues/17116). +The class provides a mechanism for determine whether a predefined feature is supported on a given .NET implementation at compile time or runtime. At compile time, a compiler can check whether a specified field exists to determine whether the feature is supported; if so, it can emit code that takes advantage of that feature. At runtime, an application can call the method before emitting code at runtime. For more information, see [Add helper method to describe features supported by the runtime](https://github.com/dotnet/corefx/issues/17116). **Value tuple types are serializable** diff --git a/docs/framework/whats-new/whats-obsolete.md b/docs/framework/whats-new/whats-obsolete.md index e87f2847a9ba5..be444031a0539 100644 --- a/docs/framework/whats-new/whats-obsolete.md +++ b/docs/framework/whats-new/whats-obsolete.md @@ -23,7 +23,7 @@ ms.assetid: d356a43a-73df-4ae2-a457-b9628074c7cd In addition to indicating that a type or a type member is obsolete, defines how the compiler handles source code that includes that type or member. The compiler can compile the code but emit a warning message, or it can treat the use of the type or member as an error. In the first case, the code can successfully compile, but a warning message indicates that the type or member is obsolete. In the second case, compilation fails. -Even if compilation produces an error instead of a warning message, does not affect run-time behavior. That is, applications that use the type or member and that have compiled successfully will always run successfully. Only the attempt to recompile an application that uses the type or member fails. +Even if compilation produces an error instead of a warning message, does not affect runtime behavior. That is, applications that use the type or member and that have compiled successfully will always run successfully. Only the attempt to recompile an application that uses the type or member fails. ## How to handle obsolete types and members diff --git a/docs/framework/windows-workflow-foundation/activity-authoring-options-in-wf.md b/docs/framework/windows-workflow-foundation/activity-authoring-options-in-wf.md index b60f8985fbe48..c56eb9e38e7b1 100644 --- a/docs/framework/windows-workflow-foundation/activity-authoring-options-in-wf.md +++ b/docs/framework/windows-workflow-foundation/activity-authoring-options-in-wf.md @@ -6,35 +6,35 @@ ms.topic: "reference" --- # Activity Authoring Options in WF -[!INCLUDE[netfx_current_long](../../../includes/netfx-current-long-md.md)] provides several options for creating custom activities. The correct method to use for authoring a given activity depends on what run-time features are required. - -## Deciding Which Base Activity Class to Use for Authoring Custom Activities - - The following table lists the features available in the custom activity base classes. - -|Base activity class|Features available| -|-------------------------|------------------------| -||Composes groups of system-provided and custom activities into a composite activity.| -||Implements imperative functionality by providing an method that can be overridden. Also provides access to tracking, variables, and arguments..| -||Provides all of the features of , plus aborting activity execution, canceling child activity execution, using bookmarks, and scheduling activities, activity actions, and functions.| -||Provides a DOM-like approach to constructing activities that interfaces with the WF designer and the run-time machinery through , allowing new activities to be created without defining new types.| - -## Authoring Activities using Activity - - Activities that derive from compose functionality by assembling other existing activities. These activities can be existing custom activities and activities from the [!INCLUDE[netfx_current_long](../../../includes/netfx-current-long-md.md)] activity library. Assembling these activities is the most basic way to create custom functionality. This approach is most typically taken when using a visual design environment for authoring workflows. - -## Authoring Activities using CodeActivity or AsyncCodeActivity - - Activities that derive from or can implement imperative functionality by overriding the method with custom imperative code. The custom code is executed when the activity is executed by the runtime. While activities created in this way have access to custom functionality, they do not have access to all of the features of the runtime, such as full access to the execution environment, the ability to schedule child activities, bookmark creation, or support for a Cancel or Abort method. When a executes, it has access to a reduced version of the execution environment (through the or class). Activities created using have access to argument and variable resolution, extensions, and tracking. Asynchronous activity scheduling can be done using . - -## Authoring Activities using NativeActivity - - Activities that derive from , like those that derive from , create imperative functionality by overriding , but also have access to all of the functionality of the workflow runtime through the that gets passed into the method. This context has support for scheduling and canceling child activities, executing and objects, flowing transactions into a workflow, invoking asynchronous processes, canceling and aborting execution, access to execution properties and extensions, and bookmarks (handles for resuming paused workflows). - -## Authoring Activities using DynamicActivity - - Unlike the other three types of activity, new functionality is not created by deriving new types from (the class is sealed), but instead, by assembling functionality into the and properties using an activity document object model (DOM). - -## Authoring Activities that Return a Result +[!INCLUDE[netfx_current_long](../../../includes/netfx-current-long-md.md)] provides several options for creating custom activities. The correct method to use for authoring a given activity depends on what runtime features are required. + +## Deciding Which Base Activity Class to Use for Authoring Custom Activities + + The following table lists the features available in the custom activity base classes. + +|Base activity class|Features available| +|-------------------------|------------------------| +||Composes groups of system-provided and custom activities into a composite activity.| +||Implements imperative functionality by providing an method that can be overridden. Also provides access to tracking, variables, and arguments..| +||Provides all of the features of , plus aborting activity execution, canceling child activity execution, using bookmarks, and scheduling activities, activity actions, and functions.| +||Provides a DOM-like approach to constructing activities that interfaces with the WF designer and the runtime machinery through , allowing new activities to be created without defining new types.| + +## Authoring Activities using Activity + + Activities that derive from compose functionality by assembling other existing activities. These activities can be existing custom activities and activities from the [!INCLUDE[netfx_current_long](../../../includes/netfx-current-long-md.md)] activity library. Assembling these activities is the most basic way to create custom functionality. This approach is most typically taken when using a visual design environment for authoring workflows. + +## Authoring Activities using CodeActivity or AsyncCodeActivity + + Activities that derive from or can implement imperative functionality by overriding the method with custom imperative code. The custom code is executed when the activity is executed by the runtime. While activities created in this way have access to custom functionality, they do not have access to all of the features of the runtime, such as full access to the execution environment, the ability to schedule child activities, bookmark creation, or support for a Cancel or Abort method. When a executes, it has access to a reduced version of the execution environment (through the or class). Activities created using have access to argument and variable resolution, extensions, and tracking. Asynchronous activity scheduling can be done using . + +## Authoring Activities using NativeActivity + + Activities that derive from , like those that derive from , create imperative functionality by overriding , but also have access to all of the functionality of the workflow runtime through the that gets passed into the method. This context has support for scheduling and canceling child activities, executing and objects, flowing transactions into a workflow, invoking asynchronous processes, canceling and aborting execution, access to execution properties and extensions, and bookmarks (handles for resuming paused workflows). + +## Authoring Activities using DynamicActivity + + Unlike the other three types of activity, new functionality is not created by deriving new types from (the class is sealed), but instead, by assembling functionality into the and properties using an activity document object model (DOM). + +## Authoring Activities that Return a Result Many activities must return a result after their execution. Although it is possible to always define a custom on an activity for this purpose, it is suggested to instead use , or derive from or . Each of these base classes has an named Result that your activity can use for its return value. Activities that return a result should only be used if only one result needs to be returned from an activity; if multiple results need to be returned, separate members should be used instead. diff --git a/docs/framework/windows-workflow-foundation/authoring-workflows-activities-and-expressions-using-imperative-code.md b/docs/framework/windows-workflow-foundation/authoring-workflows-activities-and-expressions-using-imperative-code.md index 69fd17e3d805a..5738e5aa0eb55 100644 --- a/docs/framework/windows-workflow-foundation/authoring-workflows-activities-and-expressions-using-imperative-code.md +++ b/docs/framework/windows-workflow-foundation/authoring-workflows-activities-and-expressions-using-imperative-code.md @@ -6,185 +6,185 @@ ms.assetid: cefc9cfc-2882-4eb9-8c94-7a6da957f2b2 --- # Authoring Workflows, Activities, and Expressions Using Imperative Code -A workflow definition is a tree of configured activity objects. This tree of activities can be defined many ways, including by hand-editing XAML or by using the Workflow Designer to produce XAML. Use of XAML, however, is not a requirement. Workflow definitions can also be created programmatically. This topic provides an overview of creating workflow definitions, activities, and expressions by using code. For examples of working with XAML workflows using code, see [Serializing Workflows and Activities to and from XAML](serializing-workflows-and-activities-to-and-from-xaml.md). - -## Creating Workflow Definitions - - A workflow definition can be created by instantiating an instance of an activity type and configuring the activity object’s properties. For activities that do not contain child activities, this can be accomplished using a few lines of code. - - [!code-csharp[CFX_WorkflowApplicationExample#47](~/samples/snippets/csharp/VS_Snippets_CFX/cfx_workflowapplicationexample/cs/program.cs#47)] - +A workflow definition is a tree of configured activity objects. This tree of activities can be defined many ways, including by hand-editing XAML or by using the Workflow Designer to produce XAML. Use of XAML, however, is not a requirement. Workflow definitions can also be created programmatically. This topic provides an overview of creating workflow definitions, activities, and expressions by using code. For examples of working with XAML workflows using code, see [Serializing Workflows and Activities to and from XAML](serializing-workflows-and-activities-to-and-from-xaml.md). + +## Creating Workflow Definitions + + A workflow definition can be created by instantiating an instance of an activity type and configuring the activity object’s properties. For activities that do not contain child activities, this can be accomplished using a few lines of code. + + [!code-csharp[CFX_WorkflowApplicationExample#47](~/samples/snippets/csharp/VS_Snippets_CFX/cfx_workflowapplicationexample/cs/program.cs#47)] + > [!NOTE] -> The examples in this topic use to run the sample workflows. For more information about invoking workflows, passing arguments, and the different hosting choices that are available, see [Using WorkflowInvoker and WorkflowApplication](using-workflowinvoker-and-workflowapplication.md). - - In this example, a workflow that consists of a single activity is created. The activity’s argument is set, and the workflow is invoked. If an activity contains child activities, the method of construction is similar. The following example uses a activity that contains two activities. - - [!code-csharp[CFX_WorkflowApplicationExample#48](~/samples/snippets/csharp/VS_Snippets_CFX/cfx_workflowapplicationexample/cs/program.cs#48)] - -### Using Object Initializers - - The examples in this topic use object initialization syntax. Object initialization syntax can be a useful way to create workflow definitions in code because it provides a hierarchical view of the activities in the workflow and shows the relationship between the activities. There is no requirement to use object initialization syntax when you programmatically create workflows. The following example is functionally equivalent to the previous example. - - [!code-csharp[CFX_WorkflowApplicationExample#49](~/samples/snippets/csharp/VS_Snippets_CFX/cfx_workflowapplicationexample/cs/program.cs#49)] - - For more information about object initializers, see [How to: Initialize Objects without Calling a Constructor (C# Programming Guide)](../../csharp/programming-guide/classes-and-structs/how-to-initialize-objects-by-using-an-object-initializer.md) and [How to: Declare an Object by Using an Object Initializer](../../visual-basic/programming-guide/language-features/objects-and-classes/how-to-declare-an-object-by-using-an-object-initializer.md). - -### Working with Variables, Literal Values, and Expressions - - When creating a workflow definition using code, be aware of what code executes as part of the creation of the workflow definition and what code executes as part of the execution of an instance of that workflow. For example, the following workflow is intended to generate a random number and write it to the console. - - [!code-csharp[CFX_WorkflowApplicationExample#50](~/samples/snippets/csharp/VS_Snippets_CFX/cfx_workflowapplicationexample/cs/program.cs#50)] - - When this workflow definition code is executed, the call to `Random.Next` is made and the result is stored in the workflow definition as a literal value. Many instances of this workflow can be invoked, and all would display the same number. To have the random number generation occur during workflow execution, an expression must be used that is evaluated each time the workflow runs. In the following example, a Visual Basic expression is used with a . - - [!code-csharp[CFX_WorkflowApplicationExample#51](~/samples/snippets/csharp/VS_Snippets_CFX/cfx_workflowapplicationexample/cs/program.cs#51)] - - The expression in the previous example could also be implemented using a and a C# expression. - -```csharp -new Assign -{ - To = n, - Value = new CSharpValue("new Random().Next(1, 101)") -} -``` - - C# expressions must be compiled before the workflow containing them is invoked. If the C# expressions are not compiled, a is thrown when the workflow is invoked with a message similar to the following: ``Expression Activity type 'CSharpValue`1' requires compilation in order to run. Please ensure that the workflow has been compiled.`` In most scenarios involving workflows created in Visual Studio the C# expressions are compiled automatically, but in some scenarios, such as code workflows, the C# expressions must be manually compiled. For an example of how to compile C# expressions, see the [Using C# expressions in code workflows](csharp-expressions.md#CodeWorkflows) section of the [C# Expressions](csharp-expressions.md) topic. - - A represents an expression in Visual Basic syntax that can be used as an r-value in an expression, and a represents an expression in C# syntax that can be used as an r-value in an expression. These expressions are evaluated each time the containing activity is executed. The result of the expression is assigned to the workflow variable `n`, and these results are used by the next activity in the workflow. To access the value of the workflow variable `n` at run time, the is required. This can be accessed by using the following lambda expression. - +> The examples in this topic use to run the sample workflows. For more information about invoking workflows, passing arguments, and the different hosting choices that are available, see [Using WorkflowInvoker and WorkflowApplication](using-workflowinvoker-and-workflowapplication.md). + + In this example, a workflow that consists of a single activity is created. The activity’s argument is set, and the workflow is invoked. If an activity contains child activities, the method of construction is similar. The following example uses a activity that contains two activities. + + [!code-csharp[CFX_WorkflowApplicationExample#48](~/samples/snippets/csharp/VS_Snippets_CFX/cfx_workflowapplicationexample/cs/program.cs#48)] + +### Using Object Initializers + + The examples in this topic use object initialization syntax. Object initialization syntax can be a useful way to create workflow definitions in code because it provides a hierarchical view of the activities in the workflow and shows the relationship between the activities. There is no requirement to use object initialization syntax when you programmatically create workflows. The following example is functionally equivalent to the previous example. + + [!code-csharp[CFX_WorkflowApplicationExample#49](~/samples/snippets/csharp/VS_Snippets_CFX/cfx_workflowapplicationexample/cs/program.cs#49)] + + For more information about object initializers, see [How to: Initialize Objects without Calling a Constructor (C# Programming Guide)](../../csharp/programming-guide/classes-and-structs/how-to-initialize-objects-by-using-an-object-initializer.md) and [How to: Declare an Object by Using an Object Initializer](../../visual-basic/programming-guide/language-features/objects-and-classes/how-to-declare-an-object-by-using-an-object-initializer.md). + +### Working with Variables, Literal Values, and Expressions + + When creating a workflow definition using code, be aware of what code executes as part of the creation of the workflow definition and what code executes as part of the execution of an instance of that workflow. For example, the following workflow is intended to generate a random number and write it to the console. + + [!code-csharp[CFX_WorkflowApplicationExample#50](~/samples/snippets/csharp/VS_Snippets_CFX/cfx_workflowapplicationexample/cs/program.cs#50)] + + When this workflow definition code is executed, the call to `Random.Next` is made and the result is stored in the workflow definition as a literal value. Many instances of this workflow can be invoked, and all would display the same number. To have the random number generation occur during workflow execution, an expression must be used that is evaluated each time the workflow runs. In the following example, a Visual Basic expression is used with a . + + [!code-csharp[CFX_WorkflowApplicationExample#51](~/samples/snippets/csharp/VS_Snippets_CFX/cfx_workflowapplicationexample/cs/program.cs#51)] + + The expression in the previous example could also be implemented using a and a C# expression. + +```csharp +new Assign +{ + To = n, + Value = new CSharpValue("new Random().Next(1, 101)") +} +``` + + C# expressions must be compiled before the workflow containing them is invoked. If the C# expressions are not compiled, a is thrown when the workflow is invoked with a message similar to the following: ``Expression Activity type 'CSharpValue`1' requires compilation in order to run. Please ensure that the workflow has been compiled.`` In most scenarios involving workflows created in Visual Studio the C# expressions are compiled automatically, but in some scenarios, such as code workflows, the C# expressions must be manually compiled. For an example of how to compile C# expressions, see the [Using C# expressions in code workflows](csharp-expressions.md#CodeWorkflows) section of the [C# Expressions](csharp-expressions.md) topic. + + A represents an expression in Visual Basic syntax that can be used as an r-value in an expression, and a represents an expression in C# syntax that can be used as an r-value in an expression. These expressions are evaluated each time the containing activity is executed. The result of the expression is assigned to the workflow variable `n`, and these results are used by the next activity in the workflow. To access the value of the workflow variable `n` at runtime, the is required. This can be accessed by using the following lambda expression. + > [!NOTE] -> Note that both of these code are examples are using C# as the programming language, but one uses a and one uses a . and can be used in both Visual Basic and C# projects. By default, expressions created in the workflow designer match the language of the hosting project. When creating workflows in code, the desired language is at the discretion of the workflow author. - - In these examples the result of the expression is assigned to the workflow variable `n`, and these results are used by the next activity in the workflow. To access the value of the workflow variable `n` at run time, the is required. This can be accessed by using the following lambda expression. - - [!code-csharp[CFX_WorkflowApplicationExample#52](~/samples/snippets/csharp/VS_Snippets_CFX/cfx_workflowapplicationexample/cs/program.cs#52)] - - For more information about lambda expressions, see [Lambda Expressions (C# reference)](../../csharp/language-reference/operators/lambda-expressions.md) or [Lambda Expressions (Visual Basic)](../../visual-basic/programming-guide/language-features/procedures/lambda-expressions.md). - - Lambda expressions are not serializable to XAML format. If an attempt to serialize a workflow with lambda expressions is made, a is thrown with the following message: "This workflow contains lambda expressions specified in code. These expressions are not XAML serializable. In order to make your workflow XAML-serializable, either use VisualBasicValue/VisualBasicReference or ExpressionServices.Convert(lambda). This will convert your lambda expressions into expression activities." To make this expression compatible with XAML, use and , as shown in the following example. - - [!code-csharp[CFX_WorkflowApplicationExample#53](~/samples/snippets/csharp/VS_Snippets_CFX/cfx_workflowapplicationexample/cs/program.cs#53)] - - A could also be used. Note that no lambda expression is required when using a Visual Basic expression. - - [!code-csharp[CFX_WorkflowApplicationExample#54](~/samples/snippets/csharp/VS_Snippets_CFX/cfx_workflowapplicationexample/cs/program.cs#54)] - - At run time, Visual Basic expressions are compiled into LINQ expressions. Both of the previous examples are serializable to XAML, but if the serialized XAML is intended to be viewed and edited in the workflow designer, use for your expressions. Serialized workflows that use `ExpressionServices.Convert` can be opened in the designer, but the value of the expression will be blank. For more information about serializing workflows to XAML, see [Serializing Workflows and Activities to and from XAML](serializing-workflows-and-activities-to-and-from-xaml.md). - -#### Literal Expressions and Reference Types - - Literal expressions are represented in workflows by the activity. The following activities are functionally equivalent. - -```csharp -new WriteLine -{ - Text = "Hello World." -}, -new WriteLine -{ - Text = new Literal("Hello World.") -} -``` - - It is invalid to initialize a literal expression with any reference type except . In the following example, an activity's property is initialized with a literal expression using a `List`. - -```csharp -new Assign -{ - To = new OutArgument>(items), - Value = new InArgument>(new List()) -}, -``` - - When the workflow containing this activity is validated, the following validation error is returned: "Literal only supports value types and the immutable type System.String. The type System.Collections.Generic.List\`1[System.String] cannot be used as a literal." If the workflow is invoked, an is thrown that contains the text of the validation error. This is a validation error because creating a literal expression with a reference type does not create a new instance of the reference type for each instance of the workflow. To resolve this, replace the literal expression with one that creates and returns a new instance of the reference type. - -```csharp -new Assign -{ - To = new OutArgument>(items), - Value = new InArgument>(new VisualBasicValue>("New List(Of String)")) -}, -``` - - For more information about expressions, see [Expressions](expressions.md). - -#### Invoking Methods on Objects using Expressions and the InvokeMethod Activity - - The activity can be used to invoke static and instance methods of classes in the .NET Framework. In a previous example in this topic, a random number was generated using the class. - - [!code-csharp[CFX_WorkflowApplicationExample#51](~/samples/snippets/csharp/VS_Snippets_CFX/cfx_workflowapplicationexample/cs/program.cs#51)] - - The activity could also have been used to call the method of the class. - -```csharp -new InvokeMethod -{ - TargetObject = new InArgument(new VisualBasicValue("New Random()")), - MethodName = "Next", +> Note that both of these code are examples are using C# as the programming language, but one uses a and one uses a . and can be used in both Visual Basic and C# projects. By default, expressions created in the workflow designer match the language of the hosting project. When creating workflows in code, the desired language is at the discretion of the workflow author. + + In these examples the result of the expression is assigned to the workflow variable `n`, and these results are used by the next activity in the workflow. To access the value of the workflow variable `n` at runtime, the is required. This can be accessed by using the following lambda expression. + + [!code-csharp[CFX_WorkflowApplicationExample#52](~/samples/snippets/csharp/VS_Snippets_CFX/cfx_workflowapplicationexample/cs/program.cs#52)] + + For more information about lambda expressions, see [Lambda Expressions (C# reference)](../../csharp/language-reference/operators/lambda-expressions.md) or [Lambda Expressions (Visual Basic)](../../visual-basic/programming-guide/language-features/procedures/lambda-expressions.md). + + Lambda expressions are not serializable to XAML format. If an attempt to serialize a workflow with lambda expressions is made, a is thrown with the following message: "This workflow contains lambda expressions specified in code. These expressions are not XAML serializable. In order to make your workflow XAML-serializable, either use VisualBasicValue/VisualBasicReference or ExpressionServices.Convert(lambda). This will convert your lambda expressions into expression activities." To make this expression compatible with XAML, use and , as shown in the following example. + + [!code-csharp[CFX_WorkflowApplicationExample#53](~/samples/snippets/csharp/VS_Snippets_CFX/cfx_workflowapplicationexample/cs/program.cs#53)] + + A could also be used. Note that no lambda expression is required when using a Visual Basic expression. + + [!code-csharp[CFX_WorkflowApplicationExample#54](~/samples/snippets/csharp/VS_Snippets_CFX/cfx_workflowapplicationexample/cs/program.cs#54)] + + At runtime, Visual Basic expressions are compiled into LINQ expressions. Both of the previous examples are serializable to XAML, but if the serialized XAML is intended to be viewed and edited in the workflow designer, use for your expressions. Serialized workflows that use `ExpressionServices.Convert` can be opened in the designer, but the value of the expression will be blank. For more information about serializing workflows to XAML, see [Serializing Workflows and Activities to and from XAML](serializing-workflows-and-activities-to-and-from-xaml.md). + +#### Literal Expressions and Reference Types + + Literal expressions are represented in workflows by the activity. The following activities are functionally equivalent. + +```csharp +new WriteLine +{ + Text = "Hello World." +}, +new WriteLine +{ + Text = new Literal("Hello World.") +} +``` + + It is invalid to initialize a literal expression with any reference type except . In the following example, an activity's property is initialized with a literal expression using a `List`. + +```csharp +new Assign +{ + To = new OutArgument>(items), + Value = new InArgument>(new List()) +}, +``` + + When the workflow containing this activity is validated, the following validation error is returned: "Literal only supports value types and the immutable type System.String. The type System.Collections.Generic.List\`1[System.String] cannot be used as a literal." If the workflow is invoked, an is thrown that contains the text of the validation error. This is a validation error because creating a literal expression with a reference type does not create a new instance of the reference type for each instance of the workflow. To resolve this, replace the literal expression with one that creates and returns a new instance of the reference type. + +```csharp +new Assign +{ + To = new OutArgument>(items), + Value = new InArgument>(new VisualBasicValue>("New List(Of String)")) +}, +``` + + For more information about expressions, see [Expressions](expressions.md). + +#### Invoking Methods on Objects using Expressions and the InvokeMethod Activity + + The activity can be used to invoke static and instance methods of classes in the .NET Framework. In a previous example in this topic, a random number was generated using the class. + + [!code-csharp[CFX_WorkflowApplicationExample#51](~/samples/snippets/csharp/VS_Snippets_CFX/cfx_workflowapplicationexample/cs/program.cs#51)] + + The activity could also have been used to call the method of the class. + +```csharp +new InvokeMethod +{ + TargetObject = new InArgument(new VisualBasicValue("New Random()")), + MethodName = "Next", Parameters = - { - new InArgument(1), - new InArgument(101) - }, - Result = n -} -``` - - Since is not a static method, an instance of the class is supplied for the property. In this example a new instance is created using a Visual Basic expression, but it could also have been created previously and stored in a workflow variable. In this example, it would be simpler to use the activity instead of the activity. If the method call ultimately invoked by either the or activities is long running, has an advantage since it has a property. When this property is set to `true`, the invoked method will run asynchronously with regard to the workflow. If other activities are in parallel, they will not be blocked while the method is asynchronously executing. Also, if the method to be invoked has no return value, then is the appropriate way to invoke the method. - -## Arguments and Dynamic Activities - - A workflow definition is created in code by assembling activities into an activity tree and configuring any properties and arguments. Existing arguments can be bound, but new arguments cannot be added to activities. This includes workflow arguments passed to the root activity. In imperative code, workflow arguments are specified as properties on a new CLR type, and in XAML they are declared by using `x:Class` and `x:Member`. Because there is no new CLR type created when a workflow definition is created as a tree of in-memory objects, arguments cannot be added. However, arguments can be added to a . In this example, a is created that takes two integer arguments, adds them together, and returns the result. A is created for each argument, and the result of the operation is assigned to the argument of the . - - [!code-csharp[CFX_WorkflowApplicationExample#55](~/samples/snippets/csharp/VS_Snippets_CFX/cfx_workflowapplicationexample/cs/program.cs#55)] - - For more information about dynamic activities, see [Creating an Activity at Runtime](creating-an-activity-at-runtime-with-dynamicactivity.md). - -## Compiled Activities - - Dynamic activities are one way to define an activity that contains arguments using code, but activities can also be created in code and compiled into types. Simple activities can be created that derive from , and asynchronous activities that derive from . These activities can have arguments, return values, and define their logic using imperative code. For examples of creating these types of activities, see [CodeActivity Base Class](workflow-activity-authoring-using-the-codeactivity-class.md) and [Creating Asynchronous Activities](creating-asynchronous-activities-in-wf.md). - - Activities that derive from can define their logic using imperative code and they can also contain child activities that define the logic. They also have full access to the features of the runtime such as creating bookmarks. For examples of creating a -based activity, see [NativeActivity Base Class](nativeactivity-base-class.md), [How to: Create an Activity](how-to-create-an-activity.md), and the [Custom Composite using Native Activity](./samples/custom-composite-using-native-activity.md) sample. - - Activities that derive from define their logic solely through the use of child activities. These activities are typically created by using the workflow designer, but can also be defined by using code. In the following example, a `Square` activity is defined that derives from `Activity`. The `Square` activity has a single named `Value`, and defines its logic by specifying a activity using the property. The activity contains a activity and an activity. Together, these three activities implement the logic of the `Square` activity. - -```csharp -class Square : Activity -{ - [RequiredArgument] - public InArgument Value { get; set; } - - public Square() - { - this.Implementation = () => new Sequence - { - Activities = - { - new WriteLine - { - Text = new InArgument((env) => "Squaring the value: " + this.Value.Get(env)) - }, - new Assign - { - To = new OutArgument((env) => this.Result.Get(env)), - Value = new InArgument((env) => this.Value.Get(env) * this.Value.Get(env)) - } - } - }; - } -} -``` - - In the following example, a workflow definition consisting of a single `Square` activity is invoked using . - -```csharp -Dictionary inputs = new Dictionary {{ "Value", 5}}; -int result = WorkflowInvoker.Invoke(new Square(), inputs); -Console.WriteLine("Result: {0}", result); -``` - - When the workflow is invoked, the following output is displayed to the console: - - **Squaring the value: 5** + { + new InArgument(1), + new InArgument(101) + }, + Result = n +} +``` + + Since is not a static method, an instance of the class is supplied for the property. In this example a new instance is created using a Visual Basic expression, but it could also have been created previously and stored in a workflow variable. In this example, it would be simpler to use the activity instead of the activity. If the method call ultimately invoked by either the or activities is long running, has an advantage since it has a property. When this property is set to `true`, the invoked method will run asynchronously with regard to the workflow. If other activities are in parallel, they will not be blocked while the method is asynchronously executing. Also, if the method to be invoked has no return value, then is the appropriate way to invoke the method. + +## Arguments and Dynamic Activities + + A workflow definition is created in code by assembling activities into an activity tree and configuring any properties and arguments. Existing arguments can be bound, but new arguments cannot be added to activities. This includes workflow arguments passed to the root activity. In imperative code, workflow arguments are specified as properties on a new CLR type, and in XAML they are declared by using `x:Class` and `x:Member`. Because there is no new CLR type created when a workflow definition is created as a tree of in-memory objects, arguments cannot be added. However, arguments can be added to a . In this example, a is created that takes two integer arguments, adds them together, and returns the result. A is created for each argument, and the result of the operation is assigned to the argument of the . + + [!code-csharp[CFX_WorkflowApplicationExample#55](~/samples/snippets/csharp/VS_Snippets_CFX/cfx_workflowapplicationexample/cs/program.cs#55)] + + For more information about dynamic activities, see [Creating an Activity at Runtime](creating-an-activity-at-runtime-with-dynamicactivity.md). + +## Compiled Activities + + Dynamic activities are one way to define an activity that contains arguments using code, but activities can also be created in code and compiled into types. Simple activities can be created that derive from , and asynchronous activities that derive from . These activities can have arguments, return values, and define their logic using imperative code. For examples of creating these types of activities, see [CodeActivity Base Class](workflow-activity-authoring-using-the-codeactivity-class.md) and [Creating Asynchronous Activities](creating-asynchronous-activities-in-wf.md). + + Activities that derive from can define their logic using imperative code and they can also contain child activities that define the logic. They also have full access to the features of the runtime such as creating bookmarks. For examples of creating a -based activity, see [NativeActivity Base Class](nativeactivity-base-class.md), [How to: Create an Activity](how-to-create-an-activity.md), and the [Custom Composite using Native Activity](./samples/custom-composite-using-native-activity.md) sample. + + Activities that derive from define their logic solely through the use of child activities. These activities are typically created by using the workflow designer, but can also be defined by using code. In the following example, a `Square` activity is defined that derives from `Activity`. The `Square` activity has a single named `Value`, and defines its logic by specifying a activity using the property. The activity contains a activity and an activity. Together, these three activities implement the logic of the `Square` activity. + +```csharp +class Square : Activity +{ + [RequiredArgument] + public InArgument Value { get; set; } + + public Square() + { + this.Implementation = () => new Sequence + { + Activities = + { + new WriteLine + { + Text = new InArgument((env) => "Squaring the value: " + this.Value.Get(env)) + }, + new Assign + { + To = new OutArgument((env) => this.Result.Get(env)), + Value = new InArgument((env) => this.Value.Get(env) * this.Value.Get(env)) + } + } + }; + } +} +``` + + In the following example, a workflow definition consisting of a single `Square` activity is invoked using . + +```csharp +Dictionary inputs = new Dictionary {{ "Value", 5}}; +int result = WorkflowInvoker.Invoke(new Square(), inputs); +Console.WriteLine("Result: {0}", result); +``` + + When the workflow is invoked, the following output is displayed to the console: + + **Squaring the value: 5** **Result: 25** diff --git a/docs/framework/windows-workflow-foundation/creating-an-activity-at-runtime-with-dynamicactivity.md b/docs/framework/windows-workflow-foundation/creating-an-activity-at-runtime-with-dynamicactivity.md index bd370afd879de..e779f2192a7c3 100644 --- a/docs/framework/windows-workflow-foundation/creating-an-activity-at-runtime-with-dynamicactivity.md +++ b/docs/framework/windows-workflow-foundation/creating-an-activity-at-runtime-with-dynamicactivity.md @@ -1,98 +1,98 @@ --- title: "Creating an Activity at Runtime with DynamicActivity" -description: DynamicActivity is a concrete, sealed class with a public constructor. Use the class to assemble activity functionality at run time using an activity DOM. +description: DynamicActivity is a concrete, sealed class with a public constructor. Use the class to assemble activity functionality at runtime using an activity DOM. ms.date: "03/30/2017" ms.assetid: 1af85cc6-912d-449e-90c5-c5db3eca5ace --- # Creating an Activity at Runtime with DynamicActivity - is a concrete, sealed class with a public constructor. can be used to assemble activity functionality at run time using an activity DOM. - -## DynamicActivity Features - - has access to execution properties, arguments and variables, but no access to run-time services such as scheduling child activities or tracking. - - Top-level properties can be set using workflow objects. In imperative code, these arguments are created using CLR properties on a new type. In XAML, they are declared using `x:Class` and `x:Member` tags. - - Activities constructed using interface with the designer using . Activities created in the designer can be loaded dynamically using , as demonstrated in the following procedure. - -#### To create an activity at run time using imperative code - -1. OpenVisual Studio 2010. - -2. Select **File**, **New**, **Project**. Select **Workflow 4.0** under **Visual C#** in the **Project Types** window, and select the **v2010** node. Select **Sequential Workflow Console Application** in the **Templates** window. Name the new project DynamicActivitySample. - -3. Right-click Workflow1.xaml in the HelloActivity project and select **Delete**. - -4. Open Program.cs. Add the following directive to the top of the file. - - ```csharp - using System.Collections.Generic; - ``` - -5. Replace the contents of the `Main` method with the following code, which creates a activity that contains a single activity and assigns it to the property of a new dynamic activity. - - ```csharp - //Define the input argument for the activity - var textOut = new InArgument(); - //Create the activity, property, and implementation - Activity dynamicWorkflow = new DynamicActivity() - { + is a concrete, sealed class with a public constructor. can be used to assemble activity functionality at runtime using an activity DOM. + +## DynamicActivity Features + + has access to execution properties, arguments and variables, but no access to runtime services such as scheduling child activities or tracking. + + Top-level properties can be set using workflow objects. In imperative code, these arguments are created using CLR properties on a new type. In XAML, they are declared using `x:Class` and `x:Member` tags. + + Activities constructed using interface with the designer using . Activities created in the designer can be loaded dynamically using , as demonstrated in the following procedure. + +#### To create an activity at runtime using imperative code + +1. OpenVisual Studio 2010. + +2. Select **File**, **New**, **Project**. Select **Workflow 4.0** under **Visual C#** in the **Project Types** window, and select the **v2010** node. Select **Sequential Workflow Console Application** in the **Templates** window. Name the new project DynamicActivitySample. + +3. Right-click Workflow1.xaml in the HelloActivity project and select **Delete**. + +4. Open Program.cs. Add the following directive to the top of the file. + + ```csharp + using System.Collections.Generic; + ``` + +5. Replace the contents of the `Main` method with the following code, which creates a activity that contains a single activity and assigns it to the property of a new dynamic activity. + + ```csharp + //Define the input argument for the activity + var textOut = new InArgument(); + //Create the activity, property, and implementation + Activity dynamicWorkflow = new DynamicActivity() + { Properties = - { - new DynamicActivityProperty - { - Name = "Text", - Type = typeof(InArgument), - Value = textOut - } - }, - Implementation = () => new Sequence() - { + { + new DynamicActivityProperty + { + Name = "Text", + Type = typeof(InArgument), + Value = textOut + } + }, + Implementation = () => new Sequence() + { Activities = - { - new WriteLine() - { - Text = new InArgument(env => textOut.Get(env)) - } - } - } - }; - //Execute the activity with a parameter dictionary - WorkflowInvoker.Invoke(dynamicWorkflow, new Dictionary { { "Text", "Hello World!" } }); - Console.ReadLine(); - ``` - -6. Execute the application. A console window with the text "Hello World!" displays. - -#### To create an activity at run time using XAML - -1. Open Visual Studio 2010. - -2. Select **File**, **New**, **Project**. Select **Workflow 4.0** under **Visual C#** in the **Project Types** window, and select the **v2010** node. Select **Workflow Console Application** in the **Templates** window. Name the new project DynamicActivitySample. - -3. Open Workflow1.xaml in the HelloActivity project. Click the **Arguments** option at the bottom of the designer. Create a new `In` argument called `TextToWrite` of type `String`. - -4. Drag a **WriteLine** activity from the **Primitives** section of the toolbox onto the designer surface. Assign the value `TextToWrite` to the **Text** property of the activity. - -5. Open Program.cs. Add the following directive to the top of the file. - - ```csharp - using System.Activities.XamlIntegration; - ``` - -6. Replace the contents of the `Main` method with the following code. - - ```csharp - Activity act2 = ActivityXamlServices.Load(@"Workflow1.xaml"); - results = WorkflowInvoker.Invoke(act2, new Dictionary { { "TextToWrite", "HelloWorld!" } }); - Console.ReadLine(); - ``` - -7. Execute the application. A console window with the text "Hello World!" appears. - -8. Right-click the Workflow1.xaml file in the **Solution Explorer** and select **View Code**. Note that the activity class is created with `x:Class` and the property is created with `x:Property`. - + { + new WriteLine() + { + Text = new InArgument(env => textOut.Get(env)) + } + } + } + }; + //Execute the activity with a parameter dictionary + WorkflowInvoker.Invoke(dynamicWorkflow, new Dictionary { { "Text", "Hello World!" } }); + Console.ReadLine(); + ``` + +6. Execute the application. A console window with the text "Hello World!" displays. + +#### To create an activity at runtime using XAML + +1. Open Visual Studio 2010. + +2. Select **File**, **New**, **Project**. Select **Workflow 4.0** under **Visual C#** in the **Project Types** window, and select the **v2010** node. Select **Workflow Console Application** in the **Templates** window. Name the new project DynamicActivitySample. + +3. Open Workflow1.xaml in the HelloActivity project. Click the **Arguments** option at the bottom of the designer. Create a new `In` argument called `TextToWrite` of type `String`. + +4. Drag a **WriteLine** activity from the **Primitives** section of the toolbox onto the designer surface. Assign the value `TextToWrite` to the **Text** property of the activity. + +5. Open Program.cs. Add the following directive to the top of the file. + + ```csharp + using System.Activities.XamlIntegration; + ``` + +6. Replace the contents of the `Main` method with the following code. + + ```csharp + Activity act2 = ActivityXamlServices.Load(@"Workflow1.xaml"); + results = WorkflowInvoker.Invoke(act2, new Dictionary { { "TextToWrite", "HelloWorld!" } }); + Console.ReadLine(); + ``` + +7. Execute the application. A console window with the text "Hello World!" appears. + +8. Right-click the Workflow1.xaml file in the **Solution Explorer** and select **View Code**. Note that the activity class is created with `x:Class` and the property is created with `x:Property`. + ## See also - [Authoring Workflows, Activities, and Expressions Using Imperative Code](authoring-workflows-activities-and-expressions-using-imperative-code.md) diff --git a/docs/framework/windows-workflow-foundation/designing-and-implementing-custom-activities.md b/docs/framework/windows-workflow-foundation/designing-and-implementing-custom-activities.md index eb5febecbc478..ff586d689b50f 100644 --- a/docs/framework/windows-workflow-foundation/designing-and-implementing-custom-activities.md +++ b/docs/framework/windows-workflow-foundation/designing-and-implementing-custom-activities.md @@ -6,39 +6,39 @@ ms.assetid: 4e30e63d-6e33-4842-a7a4-ce807cef1fad --- # Designing and Implementing Custom Activities -Custom activities in [!INCLUDE[netfx_current_long](../../../includes/netfx-current-long-md.md)] are created by either assembling system-provided activities into composite activities or by creating new types that derive from , , or . This section describes how to create custom activities with either method. - +Custom activities in [!INCLUDE[netfx_current_long](../../../includes/netfx-current-long-md.md)] are created by either assembling system-provided activities into composite activities or by creating new types that derive from , , or . This section describes how to create custom activities with either method. + > [!IMPORTANT] -> Custom activities by default display within the workflow designer as a simple rectangle with the activity’s name. To provide a custom visual representation of your activity in the workflow designer you must also create a custom designer. For more information, see [Using Custom Activity Designers and Templates](using-custom-activity-designers-and-templates.md). - -## In This Section - - [Activity Authoring Options](activity-authoring-options-in-wf.md) - Discusses the authoring styles available in [!INCLUDE[netfx_current_long](../../../includes/netfx-current-long-md.md)]. - - [Using a custom activity](using-a-custom-activity.md) - Describes how to add a custom activity to a workflow project. - - [Creating Asynchronous Activities](creating-asynchronous-activities-in-wf.md) - Describes how to create asynchronous activities. - - [Configuring Activity Validation](configuring-activity-validation.md) - Describes how activity validation can be used to identify and report errors in an activity’s configuration prior to its execution. - - [Creating an Activity at Runtime](creating-an-activity-at-runtime-with-dynamicactivity.md) - Discusses how to create activities at run time using . - - [Workflow Execution Properties](workflow-execution-properties.md) - Describes how to use workflow execution properties to add context specific properties to an activity’s environment - - [Using Activity Delegates](using-activity-delegates.md) +> Custom activities by default display within the workflow designer as a simple rectangle with the activity’s name. To provide a custom visual representation of your activity in the workflow designer you must also create a custom designer. For more information, see [Using Custom Activity Designers and Templates](using-custom-activity-designers-and-templates.md). + +## In This Section + + [Activity Authoring Options](activity-authoring-options-in-wf.md) + Discusses the authoring styles available in [!INCLUDE[netfx_current_long](../../../includes/netfx-current-long-md.md)]. + + [Using a custom activity](using-a-custom-activity.md) + Describes how to add a custom activity to a workflow project. + + [Creating Asynchronous Activities](creating-asynchronous-activities-in-wf.md) + Describes how to create asynchronous activities. + + [Configuring Activity Validation](configuring-activity-validation.md) + Describes how activity validation can be used to identify and report errors in an activity’s configuration prior to its execution. + + [Creating an Activity at Runtime](creating-an-activity-at-runtime-with-dynamicactivity.md) + Discusses how to create activities at runtime using . + + [Workflow Execution Properties](workflow-execution-properties.md) + Describes how to use workflow execution properties to add context specific properties to an activity’s environment + + [Using Activity Delegates](using-activity-delegates.md) Discusses how to author and use activities that contain activity delegates. - - [Using Activity Extensions](using-activity-extensions.md) - Describes how to author and use activity extensions. - - [Consuming OData Feeds from a Workflow](consuming-odata-feeds-from-a-workflow.md) - Describes several methods for calling a WCF Data Service from a workflow. - - [Activity Definition Scoping and Visibility](activity-definition-scoping-and-visibility.md) + + [Using Activity Extensions](using-activity-extensions.md) + Describes how to author and use activity extensions. + + [Consuming OData Feeds from a Workflow](consuming-odata-feeds-from-a-workflow.md) + Describes several methods for calling a WCF Data Service from a workflow. + + [Activity Definition Scoping and Visibility](activity-definition-scoping-and-visibility.md) Describes the options and rules for defining data scoping and member visibility for activities. diff --git a/docs/framework/windows-workflow-foundation/exceptions-transactions-and-compensation.md b/docs/framework/windows-workflow-foundation/exceptions-transactions-and-compensation.md index c5f39538f9187..7fa85fd2e9e6b 100644 --- a/docs/framework/windows-workflow-foundation/exceptions-transactions-and-compensation.md +++ b/docs/framework/windows-workflow-foundation/exceptions-transactions-and-compensation.md @@ -8,7 +8,7 @@ ms.assetid: 694db4f9-7387-4b13-8f9f-b923b18c7490 --- # Exceptions, Transactions, and Compensation -WF provides several different mechanisms for handling run-time error conditions in workflows. Workflows can use a combination of exception handlers, transactions, cancellation, and compensation to handle and recover gracefully from error conditions. +WF provides several different mechanisms for handling runtime error conditions in workflows. Workflows can use a combination of exception handlers, transactions, cancellation, and compensation to handle and recover gracefully from error conditions. ## In This Section diff --git a/docs/framework/windows-workflow-foundation/feature-specifics.md b/docs/framework/windows-workflow-foundation/feature-specifics.md index ff3922580733b..d28fadccfb207 100644 --- a/docs/framework/windows-workflow-foundation/feature-specifics.md +++ b/docs/framework/windows-workflow-foundation/feature-specifics.md @@ -319,7 +319,7 @@ Furthermore, discovery messages are network protocol agnostic; you can use them ### Discovery Scenarios -A developer doesn't want to hard code endpoints, since it is unknown when my service will be available. Instead, the developer wants to choose a service at run time. More decoupling, robustness, and auto-configuration is needed between the components in the application. +A developer doesn't want to hard code endpoints, since it is unknown when my service will be available. Instead, the developer wants to choose a service at runtime. More decoupling, robustness, and auto-configuration is needed between the components in the application. ## Tracking diff --git a/docs/framework/windows-workflow-foundation/imperative-code-based-validation.md b/docs/framework/windows-workflow-foundation/imperative-code-based-validation.md index 76c515c597b04..72bad3356f4f0 100644 --- a/docs/framework/windows-workflow-foundation/imperative-code-based-validation.md +++ b/docs/framework/windows-workflow-foundation/imperative-code-based-validation.md @@ -6,48 +6,48 @@ ms.assetid: ae12537c-455e-42b1-82f4-cea4c46c023e --- # Imperative Code-Based Validation -Imperative code-based validation provides a simple way for an activity to provide validation about itself, and is available for activities that derive from , , and . Validation code that determines any validation errors or warnings is added to the activity. - +Imperative code-based validation provides a simple way for an activity to provide validation about itself, and is available for activities that derive from , , and . Validation code that determines any validation errors or warnings is added to the activity. + ## Using Code-Based Validation -Code-based validation is supported by activities that derive from , , and . Validation code can be placed in the override, and validation errors or warnings can be added to the metadata argument. In the following example, if the `Cost` is greater than the `Price`, a validation error is added to the metadata. - +Code-based validation is supported by activities that derive from , , and . Validation code can be placed in the override, and validation errors or warnings can be added to the metadata argument. In the following example, if the `Cost` is greater than the `Price`, a validation error is added to the metadata. + > [!NOTE] -> Note that `Cost` and `Price` are not arguments to the activity, but are properties that are set at design time. That is why their values can be validated in the override. The value of the data flowing through an argument cannot be validated at design time because the data does not flow until run time, but activity arguments can be validated to ensure that they are bound by using the `RequiredArgument` attribute and overload groups. This example code sees the `RequiredArgument` attribute for the `Description` argument, and if it is not bound then a validation error is generated. Required arguments are covered in [Required Arguments and Overload Groups](required-arguments-and-overload-groups.md). - -```csharp -public sealed class CreateProduct : CodeActivity -{ - public double Price { get; set; } - public double Cost { get; set; } - +> Note that `Cost` and `Price` are not arguments to the activity, but are properties that are set at design time. That is why their values can be validated in the override. The value of the data flowing through an argument cannot be validated at design time because the data does not flow until runtime, but activity arguments can be validated to ensure that they are bound by using the `RequiredArgument` attribute and overload groups. This example code sees the `RequiredArgument` attribute for the `Description` argument, and if it is not bound then a validation error is generated. Required arguments are covered in [Required Arguments and Overload Groups](required-arguments-and-overload-groups.md). + +```csharp +public sealed class CreateProduct : CodeActivity +{ + public double Price { get; set; } + public double Cost { get; set; } + // [RequiredArgument] attribute will generate a validation error - // if the Description argument is not set. - [RequiredArgument] - public InArgument Description { get; set; } - - protected override void CacheMetadata(CodeActivityMetadata metadata) - { - base.CacheMetadata(metadata); - // Determine when the activity has been configured in an invalid way. - if (this.Cost > this.Price) - { - // Add a validation error with a custom message. - metadata.AddValidationError("The Cost must be less than or equal to the Price."); - } - } - - protected override void Execute(CodeActivityContext context) - { - // Not needed for the sample. - } -} -``` - - By default, a validation error is added to the metadata when is called. To add a validation warning, use the overload that takes a , and specify that the represents a warning by setting the property. - - Validation occurs when a workflow is modified in the workflow designer and any validation errors or warnings are displayed in the workflow designer. Validation also occurs at run time when a workflow is invoked and if any validation errors occur, an is thrown by the default validation logic. For more information about invoking validation and accessing any validation warnings or errors, see [Invoking Activity Validation](invoking-activity-validation.md). - - Any exceptions that are thrown from are not treated as validation errors. These exceptions will escape from the call to and must be handled by the caller. - + // if the Description argument is not set. + [RequiredArgument] + public InArgument Description { get; set; } + + protected override void CacheMetadata(CodeActivityMetadata metadata) + { + base.CacheMetadata(metadata); + // Determine when the activity has been configured in an invalid way. + if (this.Cost > this.Price) + { + // Add a validation error with a custom message. + metadata.AddValidationError("The Cost must be less than or equal to the Price."); + } + } + + protected override void Execute(CodeActivityContext context) + { + // Not needed for the sample. + } +} +``` + + By default, a validation error is added to the metadata when is called. To add a validation warning, use the overload that takes a , and specify that the represents a warning by setting the property. + + Validation occurs when a workflow is modified in the workflow designer and any validation errors or warnings are displayed in the workflow designer. Validation also occurs at runtime when a workflow is invoked and if any validation errors occur, an is thrown by the default validation logic. For more information about invoking validation and accessing any validation warnings or errors, see [Invoking Activity Validation](invoking-activity-validation.md). + + Any exceptions that are thrown from are not treated as validation errors. These exceptions will escape from the call to and must be handled by the caller. + Code-based validation is useful for validating the activity that contains the code, but it does not have visibility into the other activities in the workflow. Declarative constraints validation provides the ability to validate the relationships between an activity and other activities in the workflow, and is covered in the [Declarative Constraints](declarative-constraints.md) topic. diff --git a/docs/framework/windows-workflow-foundation/invoking-activity-validation.md b/docs/framework/windows-workflow-foundation/invoking-activity-validation.md index 25454bf549c6e..b71b4cee785a1 100644 --- a/docs/framework/windows-workflow-foundation/invoking-activity-validation.md +++ b/docs/framework/windows-workflow-foundation/invoking-activity-validation.md @@ -6,301 +6,301 @@ ms.topic: "how-to" --- # Invoking Activity Validation -Activity validation provides a method to identify and report errors in any activity's configuration prior to its execution. Validation occurs when a workflow is modified in the workflow designer and any validation errors or warnings are displayed in the workflow designer. Validation also occurs at run time when a workflow is invoked and if any validation errors occur, an is thrown by the default validation logic. Windows Workflow Foundation (WF) provides the class that can be used by workflow application and tooling developers to explicitly validate an activity. This topic describes how to use to perform activity validation. - -## Using ActivityValidationServices - - has two overloads that are used to invoke an activity's validation logic. The first overload takes the root activity to be validated and returns a collection of validation errors and warnings. In the following example, a custom `Add` activity is used that has two required arguments. - -```csharp -public sealed class Add : CodeActivity -{ - [RequiredArgument] - public InArgument Operand1 { get; set; } - - [RequiredArgument] - public InArgument Operand2 { get; set; } - - protected override int Execute(CodeActivityContext context) - { - return Operand1.Get(context) + Operand2.Get(context); - } -} -``` - - The `Add` activity is used inside a , but its two required arguments are not bound, as shown in the following example. - -```csharp -Variable Operand1 = new Variable{ Default = 10 }; -Variable Operand2 = new Variable{ Default = 15 }; -Variable Result = new Variable(); - -Activity wf = new Sequence -{ - Variables = { Operand1, Operand2, Result }, +Activity validation provides a method to identify and report errors in any activity's configuration prior to its execution. Validation occurs when a workflow is modified in the workflow designer and any validation errors or warnings are displayed in the workflow designer. Validation also occurs at runtime when a workflow is invoked and if any validation errors occur, an is thrown by the default validation logic. Windows Workflow Foundation (WF) provides the class that can be used by workflow application and tooling developers to explicitly validate an activity. This topic describes how to use to perform activity validation. + +## Using ActivityValidationServices + + has two overloads that are used to invoke an activity's validation logic. The first overload takes the root activity to be validated and returns a collection of validation errors and warnings. In the following example, a custom `Add` activity is used that has two required arguments. + +```csharp +public sealed class Add : CodeActivity +{ + [RequiredArgument] + public InArgument Operand1 { get; set; } + + [RequiredArgument] + public InArgument Operand2 { get; set; } + + protected override int Execute(CodeActivityContext context) + { + return Operand1.Get(context) + Operand2.Get(context); + } +} +``` + + The `Add` activity is used inside a , but its two required arguments are not bound, as shown in the following example. + +```csharp +Variable Operand1 = new Variable{ Default = 10 }; +Variable Operand2 = new Variable{ Default = 15 }; +Variable Result = new Variable(); + +Activity wf = new Sequence +{ + Variables = { Operand1, Operand2, Result }, Activities = - { - new Add(), - new WriteLine - { - Text = new InArgument(env => "The result is " + Result.Get(env)) - } - } -}; -``` - - This workflow can be validated by calling . returns a collection of any validation errors or warnings contained by the activity and any children, as shown in the following example. - -```csharp -ValidationResults results = ActivityValidationServices.Validate(wf); - -if (results.Errors.Count == 0 && results.Warnings.Count == 0) -{ - Console.WriteLine("No warnings or errors"); -} -else -{ - foreach (ValidationError error in results.Errors) - { - Console.WriteLine("Error: {0}", error.Message); - } - foreach (ValidationError warning in results.Warnings) - { - Console.WriteLine("Warning: {0}", warning.Message); - } -} -``` - - When is called on this sample workflow, two validation errors are returned. - - **Error: Value for a required activity argument 'Operand2' was not supplied.** -**Error: Value for a required activity argument 'Operand1' was not supplied.** If this workflow was invoked, an would be thrown, as shown in the following example. - -```csharp -try -{ - WorkflowInvoker.Invoke(wf); -} -catch (Exception ex) -{ - Console.WriteLine(ex); -} -``` - - **System.Activities.InvalidWorkflowException:** + { + new Add(), + new WriteLine + { + Text = new InArgument(env => "The result is " + Result.Get(env)) + } + } +}; +``` + + This workflow can be validated by calling . returns a collection of any validation errors or warnings contained by the activity and any children, as shown in the following example. + +```csharp +ValidationResults results = ActivityValidationServices.Validate(wf); + +if (results.Errors.Count == 0 && results.Warnings.Count == 0) +{ + Console.WriteLine("No warnings or errors"); +} +else +{ + foreach (ValidationError error in results.Errors) + { + Console.WriteLine("Error: {0}", error.Message); + } + foreach (ValidationError warning in results.Warnings) + { + Console.WriteLine("Warning: {0}", warning.Message); + } +} +``` + + When is called on this sample workflow, two validation errors are returned. + + **Error: Value for a required activity argument 'Operand2' was not supplied.** +**Error: Value for a required activity argument 'Operand1' was not supplied.** If this workflow was invoked, an would be thrown, as shown in the following example. + +```csharp +try +{ + WorkflowInvoker.Invoke(wf); +} +catch (Exception ex) +{ + Console.WriteLine(ex); +} +``` + + **System.Activities.InvalidWorkflowException:** **The following errors were encountered while processing the workflow tree:** **'Add': Value for a required activity argument 'Operand2' was not supplied.** -**'Add': Value for a required activity argument 'Operand1' was not supplied.** For this example workflow to be valid, the two required arguments of the `Add` activity must be bound. In the following example, the two required arguments are bound to workflow variables along with the result value. In this example the argument is bound along with the two required arguments. The argument is not required to be bound and does not cause a validation error if it is not. It is the responsibility of the workflow author to bind if its value is used elsewhere in the workflow. - -```csharp -new Add -{ - Operand1 = Operand1, - Operand2 = Operand2, - Result = Result -} -``` - -### Validating Required Arguments on the Root Activity - - If the root activity of a workflow has arguments, these are not bound until the workflow is invoked and parameters are passed to the workflow. The following workflow passes validation, but an exception is thrown if the workflow is invoked without passing in the required arguments, as shown in the following example. - -```csharp -Activity wf = new Add(); - -ValidationResults results = ActivityValidationServices.Validate(wf); -// results has no errors or warnings, but when the workflow -// is invoked, an InvalidWorkflowException is thrown. -try -{ - WorkflowInvoker.Invoke(wf); -} -catch (Exception ex) -{ - Console.WriteLine(ex); -} -``` - - **System.ArgumentException: The root activity's argument settings are incorrect.** +**'Add': Value for a required activity argument 'Operand1' was not supplied.** For this example workflow to be valid, the two required arguments of the `Add` activity must be bound. In the following example, the two required arguments are bound to workflow variables along with the result value. In this example the argument is bound along with the two required arguments. The argument is not required to be bound and does not cause a validation error if it is not. It is the responsibility of the workflow author to bind if its value is used elsewhere in the workflow. + +```csharp +new Add +{ + Operand1 = Operand1, + Operand2 = Operand2, + Result = Result +} +``` + +### Validating Required Arguments on the Root Activity + + If the root activity of a workflow has arguments, these are not bound until the workflow is invoked and parameters are passed to the workflow. The following workflow passes validation, but an exception is thrown if the workflow is invoked without passing in the required arguments, as shown in the following example. + +```csharp +Activity wf = new Add(); + +ValidationResults results = ActivityValidationServices.Validate(wf); +// results has no errors or warnings, but when the workflow +// is invoked, an InvalidWorkflowException is thrown. +try +{ + WorkflowInvoker.Invoke(wf); +} +catch (Exception ex) +{ + Console.WriteLine(ex); +} +``` + + **System.ArgumentException: The root activity's argument settings are incorrect.** **Either fix the workflow definition or supply input values to fix these errors:** **'Add': Value for a required activity argument 'Operand2' was not supplied.** -**'Add': Value for a required activity argument 'Operand1' was not supplied.** After the correct arguments are passed, the workflow completes successfully, as shown in the following example. - -```csharp -Add wf = new Add(); - -ValidationResults results = ActivityValidationServices.Validate(wf); -// results has no errors or warnings, and the workflow completes -// successfully because the required arguments were passed. -try -{ - Dictionary wfparams = new Dictionary - { - { "Operand1", 10 }, - { "Operand2", 15 } - }; - - int result = WorkflowInvoker.Invoke(wf, wfparams); - Console.WriteLine("Result: {0}", result); -} -catch (Exception ex) -{ - Console.WriteLine(ex); -} -``` - +**'Add': Value for a required activity argument 'Operand1' was not supplied.** After the correct arguments are passed, the workflow completes successfully, as shown in the following example. + +```csharp +Add wf = new Add(); + +ValidationResults results = ActivityValidationServices.Validate(wf); +// results has no errors or warnings, and the workflow completes +// successfully because the required arguments were passed. +try +{ + Dictionary wfparams = new Dictionary + { + { "Operand1", 10 }, + { "Operand2", 15 } + }; + + int result = WorkflowInvoker.Invoke(wf, wfparams); + Console.WriteLine("Result: {0}", result); +} +catch (Exception ex) +{ + Console.WriteLine(ex); +} +``` + > [!NOTE] -> In this example, the root activity was declared as `Add` instead of `Activity` as in the previous example. This allows the `WorkflowInvoker.Invoke` method to return a single integer that represents the results of the `Add` activity instead of a dictionary of `out` arguments. The variable `wf` could also have been declared as `Activity`. - - When validating root arguments, it is the responsibility of the host application to ensure that all required arguments are passed when the workflow is invoked. - +> In this example, the root activity was declared as `Add` instead of `Activity` as in the previous example. This allows the `WorkflowInvoker.Invoke` method to return a single integer that represents the results of the `Add` activity instead of a dictionary of `out` arguments. The variable `wf` could also have been declared as `Activity`. + + When validating root arguments, it is the responsibility of the host application to ensure that all required arguments are passed when the workflow is invoked. + ### Invoking Imperative Code-Based Validation -Imperative code-based validation provides a simple way for an activity to provide validation about itself, and is available for activities that derive from , , and . Validation code that determines any validation errors or warnings is added to the activity. When validation is invoked on the activity, these warnings or errors are contained in the collection returned by the call to . In the following example, a `CreateProduct` activity is defined. If the `Cost` is greater than the `Price`, a validation error is added to the metadata in the override. - -```csharp -public sealed class CreateProduct : CodeActivity -{ - public double Price { get; set; } - public double Cost { get; set; } - +Imperative code-based validation provides a simple way for an activity to provide validation about itself, and is available for activities that derive from , , and . Validation code that determines any validation errors or warnings is added to the activity. When validation is invoked on the activity, these warnings or errors are contained in the collection returned by the call to . In the following example, a `CreateProduct` activity is defined. If the `Cost` is greater than the `Price`, a validation error is added to the metadata in the override. + +```csharp +public sealed class CreateProduct : CodeActivity +{ + public double Price { get; set; } + public double Cost { get; set; } + // [RequiredArgument] attribute will generate a validation error - // if the Description argument is not set. - [RequiredArgument] - public InArgument Description { get; set; } - - protected override void CacheMetadata(CodeActivityMetadata metadata) - { - base.CacheMetadata(metadata); - // Determine when the activity has been configured in an invalid way. - if (this.Cost > this.Price) - { - // Add a validation error with a custom message. - metadata.AddValidationError("The Cost must be less than or equal to the Price."); - } - } - - protected override void Execute(CodeActivityContext context) - { - // Not needed for the sample. - } -} -``` - - In this example, a workflow is configured using the `CreateProduct` activity. In this workflow, the `Cost` is greater than the `Price`, and the required `Description` argument is not set. When validation is invoked, the following errors are returned. - -```csharp -Activity wf = new Sequence -{ + // if the Description argument is not set. + [RequiredArgument] + public InArgument Description { get; set; } + + protected override void CacheMetadata(CodeActivityMetadata metadata) + { + base.CacheMetadata(metadata); + // Determine when the activity has been configured in an invalid way. + if (this.Cost > this.Price) + { + // Add a validation error with a custom message. + metadata.AddValidationError("The Cost must be less than or equal to the Price."); + } + } + + protected override void Execute(CodeActivityContext context) + { + // Not needed for the sample. + } +} +``` + + In this example, a workflow is configured using the `CreateProduct` activity. In this workflow, the `Cost` is greater than the `Price`, and the required `Description` argument is not set. When validation is invoked, the following errors are returned. + +```csharp +Activity wf = new Sequence +{ Activities = - { - new CreateProduct - { - Cost = 75.00, - Price = 55.00 - // Cost > Price and required Description argument not set. - }, - new WriteLine - { - Text = "Product added." - } - } -}; - -ValidationResults results = ActivityValidationServices.Validate(wf); - -if (results.Errors.Count == 0 && results.Warnings.Count == 0) -{ - Console.WriteLine("No warnings or errors"); -} -else -{ - foreach (ValidationError error in results.Errors) - { - Console.WriteLine("Error: {0}", error.Message); - } - foreach (ValidationError warning in results.Warnings) - { - Console.WriteLine("Warning: {0}", warning.Message); - } -} -``` - - **Error: The Cost must be less than or equal to the Price.** + { + new CreateProduct + { + Cost = 75.00, + Price = 55.00 + // Cost > Price and required Description argument not set. + }, + new WriteLine + { + Text = "Product added." + } + } +}; + +ValidationResults results = ActivityValidationServices.Validate(wf); + +if (results.Errors.Count == 0 && results.Warnings.Count == 0) +{ + Console.WriteLine("No warnings or errors"); +} +else +{ + foreach (ValidationError error in results.Errors) + { + Console.WriteLine("Error: {0}", error.Message); + } + foreach (ValidationError warning in results.Warnings) + { + Console.WriteLine("Warning: {0}", warning.Message); + } +} +``` + + **Error: The Cost must be less than or equal to the Price.** **Error: Value for a required activity argument 'Description' was not supplied.** > [!NOTE] -> Custom activity authors can provide validation logic in an activity's override. Any exceptions that are thrown from are not treated as validation errors. These exceptions will escape from the call to and must be handled by the caller. - -## Using ValidationSettings - - By default, all activities in the activity tree are evaluated when validation is invoked by . allows the validation to be customized in several different ways by configuring its three properties. specifies whether the validator should walk the entire activity tree or only apply validation logic to the supplied activity. The default for this value is `false`. specifies additional constraint mapping from a type to a list of constraints. For the base type of each activity in the activity tree being validated there is a lookup into . If a matching constraint list is found, all constraints in the list are evaluated for the activity. specifies whether the validator should evaluate all constraints or only those specified in . The default value is `false`. and are useful for workflow host authors to add additional validation for workflows, such as policy constraints for tools such as FxCop. For more information about constraints, see [Declarative Constraints](declarative-constraints.md). - - To use , configure the desired properties, and then pass it in the call to . In this example, a workflow that consists of a with a custom `Add` activity is validated. The `Add` activity has two required arguments. - -```csharp -public sealed class Add : CodeActivity -{ - [RequiredArgument] - public InArgument Operand1 { get; set; } - - [RequiredArgument] - public InArgument Operand2 { get; set; } - - protected override int Execute(CodeActivityContext context) - { - return Operand1.Get(context) + Operand2.Get(context); - } -} -``` - - The following `Add` activity is used in a , but its two required arguments are not bound. - -```csharp -Variable Operand1 = new Variable { Default = 10 }; -Variable Operand2 = new Variable { Default = 15 }; -Variable Result = new Variable(); - -Activity wf = new Sequence -{ - Variables = { Operand1, Operand2, Result }, +> Custom activity authors can provide validation logic in an activity's override. Any exceptions that are thrown from are not treated as validation errors. These exceptions will escape from the call to and must be handled by the caller. + +## Using ValidationSettings + + By default, all activities in the activity tree are evaluated when validation is invoked by . allows the validation to be customized in several different ways by configuring its three properties. specifies whether the validator should walk the entire activity tree or only apply validation logic to the supplied activity. The default for this value is `false`. specifies additional constraint mapping from a type to a list of constraints. For the base type of each activity in the activity tree being validated there is a lookup into . If a matching constraint list is found, all constraints in the list are evaluated for the activity. specifies whether the validator should evaluate all constraints or only those specified in . The default value is `false`. and are useful for workflow host authors to add additional validation for workflows, such as policy constraints for tools such as FxCop. For more information about constraints, see [Declarative Constraints](declarative-constraints.md). + + To use , configure the desired properties, and then pass it in the call to . In this example, a workflow that consists of a with a custom `Add` activity is validated. The `Add` activity has two required arguments. + +```csharp +public sealed class Add : CodeActivity +{ + [RequiredArgument] + public InArgument Operand1 { get; set; } + + [RequiredArgument] + public InArgument Operand2 { get; set; } + + protected override int Execute(CodeActivityContext context) + { + return Operand1.Get(context) + Operand2.Get(context); + } +} +``` + + The following `Add` activity is used in a , but its two required arguments are not bound. + +```csharp +Variable Operand1 = new Variable { Default = 10 }; +Variable Operand2 = new Variable { Default = 15 }; +Variable Result = new Variable(); + +Activity wf = new Sequence +{ + Variables = { Operand1, Operand2, Result }, Activities = - { - new Add(), - new WriteLine - { - Text = new InArgument(env => "The result is " + Result.Get(env)) - } - } -}; -``` - - For the following example, validation is performed with set to `true`, so only the root activity is validated. - -```csharp -ValidationSettings settings = new ValidationSettings -{ - SingleLevel = true -}; - -ValidationResults results = ActivityValidationServices.Validate(wf, settings); - -if (results.Errors.Count == 0 && results.Warnings.Count == 0) -{ - Console.WriteLine("No warnings or errors"); -} -else -{ - foreach (ValidationError error in results.Errors) - { - Console.WriteLine("Error: {0}", error.Message); - } - foreach (ValidationError warning in results.Warnings) - { - Console.WriteLine("Warning: {0}", warning.Message); - } -} -``` - - This code displays the following output: - + { + new Add(), + new WriteLine + { + Text = new InArgument(env => "The result is " + Result.Get(env)) + } + } +}; +``` + + For the following example, validation is performed with set to `true`, so only the root activity is validated. + +```csharp +ValidationSettings settings = new ValidationSettings +{ + SingleLevel = true +}; + +ValidationResults results = ActivityValidationServices.Validate(wf, settings); + +if (results.Errors.Count == 0 && results.Warnings.Count == 0) +{ + Console.WriteLine("No warnings or errors"); +} +else +{ + foreach (ValidationError error in results.Errors) + { + Console.WriteLine("Error: {0}", error.Message); + } + foreach (ValidationError warning in results.Warnings) + { + Console.WriteLine("Warning: {0}", warning.Message); + } +} +``` + + This code displays the following output: + **No warnings or errors** Even though the `Add` activity has required arguments that are not bound, validation is successful because only the root activity is evaluated. This type of validation is useful for validating only specific elements in an activity tree, such as validation of a property change of a single activity in a designer. Note that if this workflow is invoked, the full validation configured in the workflow is evaluated and an would be thrown. and configure only validation explicitly invoked by the host, and not the validation that occurs when a workflow is invoked. diff --git a/docs/framework/windows-workflow-foundation/overview.md b/docs/framework/windows-workflow-foundation/overview.md index 68267f4b3dc32..cfb92a488281f 100644 --- a/docs/framework/windows-workflow-foundation/overview.md +++ b/docs/framework/windows-workflow-foundation/overview.md @@ -6,39 +6,39 @@ ms.assetid: fc44adbe-1412-49ae-81af-0298be44aae6 --- # Windows Workflow Overview -A workflow is a set of elemental units called *activities* that are stored as a model that describes a real-world process. Workflows provide a way of describing the order of execution and dependent relationships between pieces of short- or long-running work. This work passes through the model from start to finish, and activities might be executed by people or by system functions. - -## Workflow Run-time Engine - - Every running workflow instance is created and maintained by an in-process run-time engine that the host process interacts with through one of the following: - -- A , which invokes the workflow like a method. - -- A for explicit control over the execution of a single workflow instance. - -- A for message-based interactions in multi-instance scenarios. - - Each of these classes wraps the core activity runtime represented as a responsible for activity execution. There can be several objects within an application domain running concurrently. - - Each of the preceding three host interaction objects is created from a tree of activities referred to as a workflow program. Using these types or a custom host that wraps , workflows can be executed inside any Windows process including console applications, forms-based applications, Windows Services, ASP.NET Web sites, and Windows Communication Foundation (WCF) services. - - ![Workflow components in the host process](./media/44c79d1d-178b-4487-87ed-3e33015a3842.gif "44c79d1d-178b-4487-87ed-3e33015a3842") -Workflow components in the host process - -## Interaction between Workflow Components - - The following diagram demonstrates how workflow components interact with one another. - - ![Diagram that shows how workflow components interact.](./media/overview/workflow-component-interatction.gif) - - In the preceding diagram, the method of the class is used to invoke several workflow instances. is used for lightweight workflows that do not need management from the host; workflows that need management from the host (such as resumption) must be executed using instead. It isn’t required to wait for one workflow instance to complete before invoking another; the runtime engine supports running multiple workflow instances simultaneously. The workflows invoked are as follows: - -- A activity that contains a child activity. A of the parent activity is bound to an of the child activity. For more information about on variables, arguments, and binding, see [Variables and Arguments](variables-and-arguments.md). - -- A custom activity called `ReadLine`. An of the `ReadLine` activity is returned to the calling method. - -- A custom activity that derives from the abstract class. The can access run-time features (such as tracking and properties) using the that is available as a parameter of the method. For more information about these run-time features, see [Workflow Tracking and Tracing](workflow-tracking-and-tracing.md) and [Workflow Execution Properties](workflow-execution-properties.md). - +A workflow is a set of elemental units called *activities* that are stored as a model that describes a real-world process. Workflows provide a way of describing the order of execution and dependent relationships between pieces of short- or long-running work. This work passes through the model from start to finish, and activities might be executed by people or by system functions. + +## Workflow Runtime Engine + + Every running workflow instance is created and maintained by an in-process runtime engine that the host process interacts with through one of the following: + +- A , which invokes the workflow like a method. + +- A for explicit control over the execution of a single workflow instance. + +- A for message-based interactions in multi-instance scenarios. + + Each of these classes wraps the core activity runtime represented as a responsible for activity execution. There can be several objects within an application domain running concurrently. + + Each of the preceding three host interaction objects is created from a tree of activities referred to as a workflow program. Using these types or a custom host that wraps , workflows can be executed inside any Windows process including console applications, forms-based applications, Windows Services, ASP.NET Web sites, and Windows Communication Foundation (WCF) services. + + ![Workflow components in the host process](./media/44c79d1d-178b-4487-87ed-3e33015a3842.gif "44c79d1d-178b-4487-87ed-3e33015a3842") +Workflow components in the host process + +## Interaction between Workflow Components + + The following diagram demonstrates how workflow components interact with one another. + + ![Diagram that shows how workflow components interact.](./media/overview/workflow-component-interatction.gif) + + In the preceding diagram, the method of the class is used to invoke several workflow instances. is used for lightweight workflows that do not need management from the host; workflows that need management from the host (such as resumption) must be executed using instead. It isn’t required to wait for one workflow instance to complete before invoking another; the runtime engine supports running multiple workflow instances simultaneously. The workflows invoked are as follows: + +- A activity that contains a child activity. A of the parent activity is bound to an of the child activity. For more information about on variables, arguments, and binding, see [Variables and Arguments](variables-and-arguments.md). + +- A custom activity called `ReadLine`. An of the `ReadLine` activity is returned to the calling method. + +- A custom activity that derives from the abstract class. The can access runtime features (such as tracking and properties) using the that is available as a parameter of the method. For more information about these runtime features, see [Workflow Tracking and Tracing](workflow-tracking-and-tracing.md) and [Workflow Execution Properties](workflow-execution-properties.md). + ## See also - [BizTalk Server 2006 or WF? Choosing the Right Workflow Tool for Your Project](/previous-versions/dotnet/articles/cc303238(v=msdn.10)) diff --git a/docs/framework/windows-workflow-foundation/programming.md b/docs/framework/windows-workflow-foundation/programming.md index d91bd1b6cb818..343caa8717ade 100644 --- a/docs/framework/windows-workflow-foundation/programming.md +++ b/docs/framework/windows-workflow-foundation/programming.md @@ -27,7 +27,7 @@ This section contains a set of primer topics that you should understand to becom Topics that describes how to use bookmarks and messaging activities. [Exceptions, Transactions, and Compensation](exceptions-transactions-and-compensation.md) - Topics that describe how to use exception handlers, transactions, and compensation to handle run-time errors. + Topics that describe how to use exception handlers, transactions, and compensation to handle runtime errors. [Hosting Workflows](hosting-workflows.md) Topics that describe the details for writing workflow host applications. diff --git a/docs/framework/windows-workflow-foundation/samples/external-ruleset-toolkit.md b/docs/framework/windows-workflow-foundation/samples/external-ruleset-toolkit.md index a5821f48e4f3d..c397f526be7c3 100644 --- a/docs/framework/windows-workflow-foundation/samples/external-ruleset-toolkit.md +++ b/docs/framework/windows-workflow-foundation/samples/external-ruleset-toolkit.md @@ -7,7 +7,7 @@ ms.assetid: a306d283-a031-475e-aa01-9ae86e7adcb0 # External Ruleset Toolkit -Normally when rules are used within a workflow application, the rules are part of the assembly. In some scenarios, you may want to maintain the RuleSets separately from the assembly so that they can be updated without rebuilding and deploying the workflow assembly. This sample allows you to manage and edit RuleSets in a database and access those RuleSets from a workflow at run time. This enables running workflow instances to automatically incorporate RuleSet changes. +Normally when rules are used within a workflow application, the rules are part of the assembly. In some scenarios, you may want to maintain the RuleSets separately from the assembly so that they can be updated without rebuilding and deploying the workflow assembly. This sample allows you to manage and edit RuleSets in a database and access those RuleSets from a workflow at runtime. This enables running workflow instances to automatically incorporate RuleSet changes. The [External RuleSet Toolkit sample](https://github.com/dotnet/samples/tree/main/framework/windows-workflow-foundation/scenario/ExternalRuleSetToolkit/CS) contains a Windows Forms-based tool that you can use to manage and edit RuleSet versions in a database. It also includes an activity and a host service for executing those rules. diff --git a/docs/framework/windows-workflow-foundation/samples/non-generic-foreach.md b/docs/framework/windows-workflow-foundation/samples/non-generic-foreach.md index f76ed2ded3408..6588ce6d10c88 100644 --- a/docs/framework/windows-workflow-foundation/samples/non-generic-foreach.md +++ b/docs/framework/windows-workflow-foundation/samples/non-generic-foreach.md @@ -8,13 +8,13 @@ ms.assetid: 576cd07a-d58d-4536-b514-77bad60bff38 [!INCLUDE[netfx_current_long](../../../../includes/netfx-current-long-md.md)] ships in its toolbox a set of Control Flow activities, including , which allows iterating through collections. - requires its property to be of type . This precludes users from iterating over data structures that implement interface (for example, ). The non-generic version of overcomes this requirement, at the expense of more run-time complexity for ensuring the compatibility of the types of the values in the collection. + requires its property to be of type . This precludes users from iterating over data structures that implement interface (for example, ). The non-generic version of overcomes this requirement, at the expense of more runtime complexity for ensuring the compatibility of the types of the values in the collection. The [NonGenericForEach sample](https://github.com/dotnet/samples/tree/main/framework/windows-workflow-foundation/scenario/ActivityLibrary/NonGenericForEach/CS) shows how to implement a non-generic activity and its designer. This activity can be used to iterate through . ## ForEach Activity - The C#/Visual Basic `foreach` statement enumerates the elements of a collection, executing an embedded statement for each element of the collection. The WF equivalent activities of `foreach` are and . The activity contains a list of values and a body. At run time, the list is iterated and the body is executed for each value in the list. + The C#/Visual Basic `foreach` statement enumerates the elements of a collection, executing an embedded statement for each element of the collection. The WF equivalent activities of `foreach` are and . The activity contains a list of values and a body. At runtime, the list is iterated and the body is executed for each value in the list. For most cases, the generic version of the activity should be the preferred solution, because it covers most of the scenarios in which it would be used, and provides type checking at compile time. The non-generic version can be used for iterating through types that implement the non-generic interface. diff --git a/docs/framework/windows-workflow-foundation/samples/non-generic-parallelforeach.md b/docs/framework/windows-workflow-foundation/samples/non-generic-parallelforeach.md index 644edbe6ee812..b5ccfbeaa4cf0 100644 --- a/docs/framework/windows-workflow-foundation/samples/non-generic-parallelforeach.md +++ b/docs/framework/windows-workflow-foundation/samples/non-generic-parallelforeach.md @@ -8,13 +8,13 @@ ms.assetid: de17e7a2-257b-48b3-91a1-860e2e9bf6e6 [!INCLUDE[netfx_current_long](../../../../includes/netfx-current-long-md.md)] ships in its toolbox a set of Control Flow activities, including , which allows iterating through collections. - requires its property to be of type . This precludes users from iterating over data structures that implement interface (for example, ). The non-generic version of overcomes this requirement, at the expense of more run-time complexity for ensuring the compatibility of the types of the values in the collection. + requires its property to be of type . This precludes users from iterating over data structures that implement interface (for example, ). The non-generic version of overcomes this requirement, at the expense of more runtime complexity for ensuring the compatibility of the types of the values in the collection. The [NonGenericParallelForEach sample](https://github.com/dotnet/samples/tree/main/framework/windows-workflow-foundation/scenario/ActivityLibrary/NonGenericParallelForEach/CS) shows how to implement a non-generic activity and its designer. This activity can be used to iterate through . ## ParallelForEach activity -The C#/Visual Basic `foreach` statement enumerates the elements of a collection, executing an embedded statement for each element of the collection. The WF equivalent activities are and . The activity contains a list of values and a body. At run time, the list is iterated and the body is executed for each value in the list. +The C#/Visual Basic `foreach` statement enumerates the elements of a collection, executing an embedded statement for each element of the collection. The WF equivalent activities are and . The activity contains a list of values and a body. At runtime, the list is iterated and the body is executed for each value in the list. has a , so that the activity could complete early if the evaluation of the returns `true`. The is evaluated after each iteration is completed. diff --git a/docs/framework/windows-workflow-foundation/samples/removing-the-view-state-the-designer-adds-to-an-xaml-file.md b/docs/framework/windows-workflow-foundation/samples/removing-the-view-state-the-designer-adds-to-an-xaml-file.md index 22992476c61c0..44852f0d10fce 100644 --- a/docs/framework/windows-workflow-foundation/samples/removing-the-view-state-the-designer-adds-to-an-xaml-file.md +++ b/docs/framework/windows-workflow-foundation/samples/removing-the-view-state-the-designer-adds-to-an-xaml-file.md @@ -6,7 +6,7 @@ ms.assetid: a801ce22-8699-483c-a392-7bb3834aae4f --- # Removing the view state the designer adds to an XAML file -The [ViewStateCleaningWriter sample](https://github.com/dotnet/samples/tree/main/framework/windows-workflow-foundation/basic/Designer/ViewStateCleaningWriter/cs) demonstrates how to create a class that derives from and removes view state from a XAML file. Windows Workflow Designer writes information into the XAML document, which is known as view state. View state refers to the information that is required at design time, such as layout positioning, that is not required at run time. Workflow Designer inserts this information into the XAML document as it is edited. Workflow Designer writes the view state into the XAML file with the `mc:Ignorable` attribute, so this information is not loaded when the runtime loads the XAML file. This sample demonstrates how to create a class that removes that view state information while processing XAML nodes. +The [ViewStateCleaningWriter sample](https://github.com/dotnet/samples/tree/main/framework/windows-workflow-foundation/basic/Designer/ViewStateCleaningWriter/cs) demonstrates how to create a class that derives from and removes view state from a XAML file. Windows Workflow Designer writes information into the XAML document, which is known as view state. View state refers to the information that is required at design time, such as layout positioning, that is not required at runtime. Workflow Designer inserts this information into the XAML document as it is edited. Workflow Designer writes the view state into the XAML file with the `mc:Ignorable` attribute, so this information is not loaded when the runtime loads the XAML file. This sample demonstrates how to create a class that removes that view state information while processing XAML nodes. ## Discussion diff --git a/docs/framework/windows-workflow-foundation/samples/scenario.md b/docs/framework/windows-workflow-foundation/samples/scenario.md index f486321e2683e..f11aa219a5f2a 100644 --- a/docs/framework/windows-workflow-foundation/samples/scenario.md +++ b/docs/framework/windows-workflow-foundation/samples/scenario.md @@ -6,14 +6,14 @@ ms.assetid: cb678fda-79aa-4495-833b-ef570539d4c3 --- # Scenario -This section contains examples of Windows Workflow Foundation (WF) scenarios. - +This section contains examples of Windows Workflow Foundation (WF) scenarios. + ## In This Section -[Activity Library](activity-library.md) - Contains samples that demonstrate scenarios using the built-in activity library. - -[Services](accessing-operationcontext.md) - Contains samples that demonstrate scenarios using workflow services activities. - -[WPF and WF Integration in XAML](wpf-and-wf-integration-in-xaml.md) - Demonstrates how to create an application that uses Windows Presentation Foundation (WPF) and Windows Workflow Foundation (WF) features in a single XAML document. To accomplish this, the sample uses Windows Workflow Foundation (WF) and XAML extensibility. - -[External Ruleset Toolkit](external-ruleset-toolkit.md) - Demonstrates how to manage and edit RuleSets in a database and access those RuleSets from a workflow at run time. +[Activity Library](activity-library.md) - Contains samples that demonstrate scenarios using the built-in activity library. + +[Services](accessing-operationcontext.md) - Contains samples that demonstrate scenarios using workflow services activities. + +[WPF and WF Integration in XAML](wpf-and-wf-integration-in-xaml.md) - Demonstrates how to create an application that uses Windows Presentation Foundation (WPF) and Windows Workflow Foundation (WF) features in a single XAML document. To accomplish this, the sample uses Windows Workflow Foundation (WF) and XAML extensibility. + +[External Ruleset Toolkit](external-ruleset-toolkit.md) - Demonstrates how to manage and edit RuleSets in a database and access those RuleSets from a workflow at runtime. diff --git a/docs/framework/windows-workflow-foundation/tracking-profiles.md b/docs/framework/windows-workflow-foundation/tracking-profiles.md index 8f79d6168289e..70cd08351588e 100644 --- a/docs/framework/windows-workflow-foundation/tracking-profiles.md +++ b/docs/framework/windows-workflow-foundation/tracking-profiles.md @@ -7,7 +7,7 @@ ms.assetid: 22682566-1cd9-4672-9791-fb3523638e18 # Tracking Profiles -Tracking profiles contain tracking queries that permit a tracking participant to subscribe to workflow events that are emitted when the state of a workflow instance changes at run time. +Tracking profiles contain tracking queries that permit a tracking participant to subscribe to workflow events that are emitted when the state of a workflow instance changes at runtime. ## Tracking Profiles diff --git a/docs/framework/windows-workflow-foundation/variables-and-arguments.md b/docs/framework/windows-workflow-foundation/variables-and-arguments.md index 67545b29668ca..0406301ee16d7 100644 --- a/docs/framework/windows-workflow-foundation/variables-and-arguments.md +++ b/docs/framework/windows-workflow-foundation/variables-and-arguments.md @@ -6,141 +6,141 @@ ms.assetid: d03dbe34-5b2e-4f21-8b57-693ee49611b8 --- # Variables and Arguments -In Windows Workflow Foundation (WF), variables represent the storage of data and arguments represent the flow of data into and out of an activity. An activity has a set of arguments and they make up the signature of the activity. Additionally, an activity can maintain a list of variables to which a developer can add or remove variables during the design of a workflow. An argument is bound using an expression that returns a value. - -## Variables - - Variables are storage locations for data. Variables are declared as part of the definition of a workflow. Variables take on values at run time and these values are stored as part of the state of a workflow instance. A variable definition specifies the type of the variable and optionally, the name. The following code shows how to declare a variable, assign a value to it using an activity, and then display its value to the console using a activity. - -```csharp -// Define a variable named "str" of type string. -Variable var = new Variable -{ - Name = "str" -}; - -// Declare the variable within a Sequence, assign -// a value to it, and then display it. -Activity wf = new Sequence() -{ - Variables = { var }, - Activities = - { - new Assign - { - To = var, - Value = "Hello World." - }, - new WriteLine - { - Text = var - } - } -}; - -WorkflowInvoker.Invoke(wf); -``` - - A default value expression can optionally be specified as part of a variable declaration. Variables also can have modifiers. For example, if a variable is read-only then the read-only modifier can be applied. In the following example, a read-only variable is created that has a default value assigned. - -```csharp -// Define a read-only variable with a default value. -Variable var = new Variable -{ - Default = "Hello World.", - Modifiers = VariableModifiers.ReadOnly -}; -``` - -## Variable Scoping - - The lifetime of a variable at run time is equal to the lifetime of the activity that declares it. When an activity completes, its variables are cleaned up and can no longer be referenced. - -## Arguments - - Activity authors use arguments to define the way data flows into and out of an activity. Each argument has a specified direction: , , or . - - The workflow runtime makes the following guarantees about the timing of data movement into and out of activities: - -1. When an activity starts executing, the values of all of its input and input/output arguments are calculated. For example, regardless of when is called, the value returned is the one calculated by the runtime prior to its invocation of `Execute`. - -2. When is called, the runtime sets the value immediately. - -3. Arguments can optionally have their specified. is a zero-based value that specifies the order in which the argument is evaluated. By default, the evaluation order of the argument is unspecified and is equal to the value. Set to a value greater or equal to zero to specify an evaluation order for this argument. Windows Workflow Foundation evaluates arguments with a specified evaluation order in ascending order. Note that arguments with an unspecified evaluation order are evaluated before those with a specified evaluation order. - - An activity author can use a strongly typed mechanism for exposing its arguments. This is accomplished by declaring properties of type , , and . This allows an activity author to establish a specific contract about the data going into and out of an activity. - -### Defining the Arguments on an Activity - - Arguments can be defined on an activity by specifying properties of type , , and . The following code shows how to define the arguments for a `Prompt` activity that takes in a string to display to the user and returns a string that contains the user's response. - -```csharp -public class Prompt : Activity -{ - public InArgument Text { get; set; } - public OutArgument Response { get; set; } - // Rest of activity definition omitted. -} -``` - +In Windows Workflow Foundation (WF), variables represent the storage of data and arguments represent the flow of data into and out of an activity. An activity has a set of arguments and they make up the signature of the activity. Additionally, an activity can maintain a list of variables to which a developer can add or remove variables during the design of a workflow. An argument is bound using an expression that returns a value. + +## Variables + + Variables are storage locations for data. Variables are declared as part of the definition of a workflow. Variables take on values at runtime and these values are stored as part of the state of a workflow instance. A variable definition specifies the type of the variable and optionally, the name. The following code shows how to declare a variable, assign a value to it using an activity, and then display its value to the console using a activity. + +```csharp +// Define a variable named "str" of type string. +Variable var = new Variable +{ + Name = "str" +}; + +// Declare the variable within a Sequence, assign +// a value to it, and then display it. +Activity wf = new Sequence() +{ + Variables = { var }, + Activities = + { + new Assign + { + To = var, + Value = "Hello World." + }, + new WriteLine + { + Text = var + } + } +}; + +WorkflowInvoker.Invoke(wf); +``` + + A default value expression can optionally be specified as part of a variable declaration. Variables also can have modifiers. For example, if a variable is read-only then the read-only modifier can be applied. In the following example, a read-only variable is created that has a default value assigned. + +```csharp +// Define a read-only variable with a default value. +Variable var = new Variable +{ + Default = "Hello World.", + Modifiers = VariableModifiers.ReadOnly +}; +``` + +## Variable Scoping + + The lifetime of a variable at runtime is equal to the lifetime of the activity that declares it. When an activity completes, its variables are cleaned up and can no longer be referenced. + +## Arguments + + Activity authors use arguments to define the way data flows into and out of an activity. Each argument has a specified direction: , , or . + + The workflow runtime makes the following guarantees about the timing of data movement into and out of activities: + +1. When an activity starts executing, the values of all of its input and input/output arguments are calculated. For example, regardless of when is called, the value returned is the one calculated by the runtime prior to its invocation of `Execute`. + +2. When is called, the runtime sets the value immediately. + +3. Arguments can optionally have their specified. is a zero-based value that specifies the order in which the argument is evaluated. By default, the evaluation order of the argument is unspecified and is equal to the value. Set to a value greater or equal to zero to specify an evaluation order for this argument. Windows Workflow Foundation evaluates arguments with a specified evaluation order in ascending order. Note that arguments with an unspecified evaluation order are evaluated before those with a specified evaluation order. + + An activity author can use a strongly typed mechanism for exposing its arguments. This is accomplished by declaring properties of type , , and . This allows an activity author to establish a specific contract about the data going into and out of an activity. + +### Defining the Arguments on an Activity + + Arguments can be defined on an activity by specifying properties of type , , and . The following code shows how to define the arguments for a `Prompt` activity that takes in a string to display to the user and returns a string that contains the user's response. + +```csharp +public class Prompt : Activity +{ + public InArgument Text { get; set; } + public OutArgument Response { get; set; } + // Rest of activity definition omitted. +} +``` + > [!NOTE] -> Activities that return a single value can derive from , , or . These activities have a well-defined named that contains the return value of the activity. - -### Using Variables and Arguments in Workflows - - The following example shows how variables and arguments are used in a workflow. The workflow is a sequence that declares three variables: `var1`, `var2`, and `var3`. The first activity in the workflow is an `Assign` activity that assigns the value of variable `var1` to the variable `var2`. This is followed by a `WriteLine` activity that prints the value of the `var2` variable. Next is another `Assign` activity that assigns the value of variable `var2` to the variable `var3`. Finally there is another `WriteLine` activity that prints the value of the `var3` variable. The first `Assign` activity uses `InArgument` and `OutArgument` objects that explicitly represent the bindings for the activity's arguments. `InArgument` is used for because the value is flowing into the activity through its argument, and `OutArgument` is used for because the value is flowing out of the argument into the variable. The second `Assign` activity accomplishes the same thing with more compact but equivalent syntax that uses implicit casts. The `WriteLine` activities also use the compact syntax. - -```csharp -// Declare three variables; the first one is given an initial value. -Variable var1 = new Variable() -{ - Default = "one" -}; -Variable var2 = new Variable(); -Variable var3 = new Variable(); - -// Define the workflow -Activity wf = new Sequence -{ - Variables = { var1, var2, var3 }, +> Activities that return a single value can derive from , , or . These activities have a well-defined named that contains the return value of the activity. + +### Using Variables and Arguments in Workflows + + The following example shows how variables and arguments are used in a workflow. The workflow is a sequence that declares three variables: `var1`, `var2`, and `var3`. The first activity in the workflow is an `Assign` activity that assigns the value of variable `var1` to the variable `var2`. This is followed by a `WriteLine` activity that prints the value of the `var2` variable. Next is another `Assign` activity that assigns the value of variable `var2` to the variable `var3`. Finally there is another `WriteLine` activity that prints the value of the `var3` variable. The first `Assign` activity uses `InArgument` and `OutArgument` objects that explicitly represent the bindings for the activity's arguments. `InArgument` is used for because the value is flowing into the activity through its argument, and `OutArgument` is used for because the value is flowing out of the argument into the variable. The second `Assign` activity accomplishes the same thing with more compact but equivalent syntax that uses implicit casts. The `WriteLine` activities also use the compact syntax. + +```csharp +// Declare three variables; the first one is given an initial value. +Variable var1 = new Variable() +{ + Default = "one" +}; +Variable var2 = new Variable(); +Variable var3 = new Variable(); + +// Define the workflow +Activity wf = new Sequence +{ + Variables = { var1, var2, var3 }, Activities = - { - new Assign() - { - Value = new InArgument(var1), - To = new OutArgument(var2) - }, - new WriteLine() { Text = var2 }, - new Assign() - { - Value = var2, - To = var3 - }, - new WriteLine() { Text = var3 } - } -}; - -WorkflowInvoker.Invoke(wf); -``` - -### Using Variables and Arguments in Code-Based Activities - - The previous examples show how to use arguments and variables in workflows and declarative activities. Arguments and variables are also used in code-based activities. Conceptually the usage is very similar. Variables represent data storage within the activity, and arguments represent the flow of data into or out of the activity, and are bound by the workflow author to other variables or arguments in the workflow that represent where the data flows to or from. To get or set the value of a variable or argument in an activity, an activity context must be used that represents the current execution environment of the activity. This is passed into the method of the activity by the workflow runtime. In this example, a custom `Add` activity is defined that has two arguments. To access the value of the arguments, the method is used and the context that was passed in by the workflow runtime is used. - -```csharp -public sealed class Add : CodeActivity -{ - [RequiredArgument] - public InArgument Operand1 { get; set; } - - [RequiredArgument] - public InArgument Operand2 { get; set; } - - protected override int Execute(CodeActivityContext context) - { - return Operand1.Get(context) + Operand2.Get(context); - } -} -``` - + { + new Assign() + { + Value = new InArgument(var1), + To = new OutArgument(var2) + }, + new WriteLine() { Text = var2 }, + new Assign() + { + Value = var2, + To = var3 + }, + new WriteLine() { Text = var3 } + } +}; + +WorkflowInvoker.Invoke(wf); +``` + +### Using Variables and Arguments in Code-Based Activities + + The previous examples show how to use arguments and variables in workflows and declarative activities. Arguments and variables are also used in code-based activities. Conceptually the usage is very similar. Variables represent data storage within the activity, and arguments represent the flow of data into or out of the activity, and are bound by the workflow author to other variables or arguments in the workflow that represent where the data flows to or from. To get or set the value of a variable or argument in an activity, an activity context must be used that represents the current execution environment of the activity. This is passed into the method of the activity by the workflow runtime. In this example, a custom `Add` activity is defined that has two arguments. To access the value of the arguments, the method is used and the context that was passed in by the workflow runtime is used. + +```csharp +public sealed class Add : CodeActivity +{ + [RequiredArgument] + public InArgument Operand1 { get; set; } + + [RequiredArgument] + public InArgument Operand2 { get; set; } + + protected override int Execute(CodeActivityContext context) + { + return Operand1.Get(context) + Operand2.Get(context); + } +} +``` + For more information about working with arguments, variables, and expressions in code, see [Authoring Workflows, Activities, and Expressions Using Imperative Code](authoring-workflows-activities-and-expressions-using-imperative-code.md) and [Required Arguments and Overload Groups](required-arguments-and-overload-groups.md). diff --git a/docs/framework/windows-workflow-foundation/wfc-exe-workflow-compiler-tool.md b/docs/framework/windows-workflow-foundation/wfc-exe-workflow-compiler-tool.md index 4f21a3f3e6664..b67dadfa43b50 100644 --- a/docs/framework/windows-workflow-foundation/wfc-exe-workflow-compiler-tool.md +++ b/docs/framework/windows-workflow-foundation/wfc-exe-workflow-compiler-tool.md @@ -1,8 +1,8 @@ --- title: "Wfc.exe (Workflow Command-line Compiler Tool)" -description: Understand wfc.exe, the Workflow command line compiler tool. +description: Understand wfc.exe, the Workflow command line compiler tool. ms.date: "10/10/2020" -helpviewer_keywords: +helpviewer_keywords: - "wfc [Workflow]" - "compiler tool" - "wfc.exe" @@ -22,10 +22,10 @@ The wfc.exe workflow command-line compiler tool works with old workflow markup f When workflows are compiled, the following procedures are performed as part of the compilation process: -- Validation is performed to ensure that the workflow activities validate based on the rules that the activities have set for themselves. If there are validation errors, the compiler returns a list of the errors. -- A partial class is generated from the markup definition that is input into the compiler. +- Validation is performed to ensure that the workflow activities validate based on the rules that the activities have set for themselves. If there are validation errors, the compiler returns a list of the errors. +- A partial class is generated from the markup definition that is input into the compiler. -- Code is generated to help with the run-time execution of the activities. Event subscriptions are generated, which help activities know when the activities they contain are finished executing. +- Code is generated to help with the runtime execution of the activities. Event subscriptions are generated, which help activities know when the activities they contain are finished executing. - The partial classes generated from the markup file and the partial classes from the code file are entered into the .NET Framework C# or Visual Basic compiler. The output of this process is the .NET assembly, WorkflowSample.dll. This can be deployed to run the workflow. ### Compiler options @@ -96,11 +96,11 @@ This section shows the options for the wfc.exe workflow command-line compiler. > This material discusses types and namespaces that are obsolete. A list of authorized types is usually defined in the *wfc.exe.config* file. During the validation phase of workflow compilation, a workflow source document is rejected if it or the companion rules file directly references any .NET Framework types not present in a list of authorized types. The list of authorized types is an XML document where each entry indicates an `Assembly`, a `Namespace`, a `TypeName`, and an Authorized {`True`|`False`} indicator. `AuthorizedType` corresponds to an entry in the list. Wildcard character designations, which can be used to include or exclude complete namespaces, are allowed. For example, `Type="System.*"` includes all types in , including types contained in child namespaces. - + The use of a list of authorized types is controlled by the option `'/checktypes'`. -```xml - +```xml + @@ -109,8 +109,8 @@ The use of a list of authorized types is controlled by the - - + + ``` > [!WARNING] diff --git a/docs/fundamentals/apicompat/diagnostic-ids.md b/docs/fundamentals/apicompat/diagnostic-ids.md index 4722a6a3543da..6314c73d56712 100644 --- a/docs/fundamentals/apicompat/diagnostic-ids.md +++ b/docs/fundamentals/apicompat/diagnostic-ids.md @@ -44,10 +44,10 @@ This reference article lists all the error codes generated by package validation | Diagnostic ID | Description |Recommended action| |----------------|-----------------|------------------------------------| | PKV001 | A compile-time asset for a compatible framework is missing. | Add the appropriate target framework to the project. | -| PKV002 | A run-time asset for a compatible framework and runtime is missing. | Add the appropriate asset for corresponding runtime to the package. | -| PKV003 | A run-time independent asset for a compatible framework is missing. | Add the appropriate run-time independent target framework to the project. | -| PKV004 | A compatible run-time asset for a compile-time asset is missing. | Add the appropriate run-time asset to the package. | -| PKV005 | A compatible run-time asset for a compile-time asset and a supported runtime identifier is missing. | Add the appropriate run-time asset to the package. | +| PKV002 | A runtime asset for a compatible framework and runtime is missing. | Add the appropriate asset for corresponding runtime to the package. | +| PKV003 | A runtime independent asset for a compatible framework is missing. | Add the appropriate runtime independent target framework to the project. | +| PKV004 | A compatible runtime asset for a compile-time asset is missing. | Add the appropriate runtime asset to the package. | +| PKV005 | A compatible runtime asset for a compile-time asset and a supported runtime identifier is missing. | Add the appropriate runtime asset to the package. | | PKV006 | The target framework is dropped in the latest version. | Add the appropriate target framework to the project. | | PKV007 | The target framework and runtime identifier pair is dropped in the latest version. | Add the appropriate target framework and RID to the project. | | CP0001 | A type, enum, record, or struct visible outside the assembly is missing in the compared assembly when required to be present. | Add the missing type to the assembly where it is missing. | diff --git a/docs/fundamentals/apicompat/overview.md b/docs/fundamentals/apicompat/overview.md index 2645fd691edd0..47a2023d6864c 100644 --- a/docs/fundamentals/apicompat/overview.md +++ b/docs/fundamentals/apicompat/overview.md @@ -9,7 +9,7 @@ ms.topic: overview Cross-platform compatibility has become a mainstream requirement for .NET library authors. However, without tooling to validate assemblies and packages, they might contain unintentional breaking changes. As a library author, you need to ensure that multi-targeted assemblies are compatible. For example, for a package that multi-targets for .NET 6 and .NET Standard 2.0, you must ensure that code compiled against the .NET Standard 2.0 binary can run against the .NET 6 binary. -You might think that a change is safe and compatible if source consuming that change continues to compile without changes. However, the changes can still cause problems at run time if the consumer wasn't recompiled. For example, adding an optional parameter to a method or changing the value of a constant can cause these kinds of compatibility issues. +You might think that a change is safe and compatible if source consuming that change continues to compile without changes. However, the changes can still cause problems at runtime if the consumer wasn't recompiled. For example, adding an optional parameter to a method or changing the value of a constant can cause these kinds of compatibility issues. The .NET SDK provides various ways you can compare versions built for different target frameworks. You can also validate a newer version against a baseline version to ensure no breaking changes have been introduced. Enable MSBuild tasks to validate your assemblies at compile time or your packages when you [pack](../../core/tools/dotnet-pack.md). Or, use the [Microsoft.DotNet.ApiCompat.Tool global tool](global-tool.md) to validate outside of MSBuild. diff --git a/docs/fundamentals/apicompat/package-validation/compatible-framework-in-package-validator.md b/docs/fundamentals/apicompat/package-validation/compatible-framework-in-package-validator.md index 555fe4d9a603c..10800d3955cc1 100644 --- a/docs/fundamentals/apicompat/package-validation/compatible-framework-in-package-validator.md +++ b/docs/fundamentals/apicompat/package-validation/compatible-framework-in-package-validator.md @@ -11,7 +11,7 @@ Packages containing compatible frameworks need to ensure that code compiled agai * .NET Standard 2.0 and .NET 7 * .NET 6 and .NET 7 -In both of these cases, consumers can build against .NET Standard 2.0 or .NET 6 and run on .NET 7. If your binaries aren't compatible between these frameworks, consumers could end up with compile-time or run-time errors. +In both of these cases, consumers can build against .NET Standard 2.0 or .NET 6 and run on .NET 7. If your binaries aren't compatible between these frameworks, consumers could end up with compile-time or runtime errors. Package validation catches these errors at pack time. Here's an example scenario: diff --git a/docs/fundamentals/apicompat/package-validation/compatible-framework-validator.md b/docs/fundamentals/apicompat/package-validation/compatible-framework-validator.md index cd5290c7e5077..d0662ac0dc955 100644 --- a/docs/fundamentals/apicompat/package-validation/compatible-framework-validator.md +++ b/docs/fundamentals/apicompat/package-validation/compatible-framework-validator.md @@ -1,6 +1,6 @@ --- title: Validating Different Runtimes -description: Learn about validating the run-time and compile-time assemblies applicable for supported target frameworks and runtimes. +description: Learn about validating the runtime and compile-time assemblies applicable for supported target frameworks and runtimes. ms.date: 09/29/2021 --- @@ -31,7 +31,7 @@ lib/net6.0/A.dll runtimes/unix/lib/net6.0/A.dll ``` -`lib\net6.0\A.dll` is always used at compile time, regardless of the underlying operating system. `lib\net6.0\A.dll` is also used at run time for non-Unix systems. However, `runtimes\unix\lib\net6.0\A.dll` is used at run time for Unix systems. +`lib\net6.0\A.dll` is always used at compile time, regardless of the underlying operating system. `lib\net6.0\A.dll` is also used at runtime for non-Unix systems. However, `runtimes\unix\lib\net6.0\A.dll` is used at runtime for Unix systems. When you try to pack this project, you get the following error: diff --git a/docs/fundamentals/code-analysis/overview.md b/docs/fundamentals/code-analysis/overview.md index 287238ca16612..ce7317402e62d 100644 --- a/docs/fundamentals/code-analysis/overview.md +++ b/docs/fundamentals/code-analysis/overview.md @@ -33,7 +33,7 @@ The following rules are enabled, by default, as errors or warnings in .NET 10. A | [CA1416](quality-rules/ca1416.md) | Interoperability | Warning | .NET 5 | Validate platform compatibility | | [CA1417](quality-rules/ca1417.md) | Interoperability | Warning | .NET 5 | Do not use `OutAttribute` on string parameters for P/Invokes | | [CA1418](quality-rules/ca1418.md) | Interoperability | Warning | .NET 6 | Use valid platform string | -| [CA1420](quality-rules/ca1420.md) | Interoperability | Warning | .NET 7 | Using features that require runtime marshalling when it's disabled will result in run-time exceptions | +| [CA1420](quality-rules/ca1420.md) | Interoperability | Warning | .NET 7 | Using features that require runtime marshalling when it's disabled will result in runtime exceptions | | [CA1422](quality-rules/ca1422.md) | Interoperability | Warning | .NET 7 | Validate platform compatibility | | [CA1831](quality-rules/ca1831.md) | Performance | Warning | .NET 5 | Use `AsSpan` instead of range-based indexers for string when appropriate | | [CA1856](quality-rules/ca1856.md) | Performance | Error | .NET 8 | Incorrect usage of `ConstantExpected` attribute | @@ -68,7 +68,7 @@ The following rules are enabled, by default, as errors or warnings in .NET 9. Ad | [CA1416](quality-rules/ca1416.md) | Interoperability | Warning | .NET 5 | Validate platform compatibility | | [CA1417](quality-rules/ca1417.md) | Interoperability | Warning | .NET 5 | Do not use `OutAttribute` on string parameters for P/Invokes | | [CA1418](quality-rules/ca1418.md) | Interoperability | Warning | .NET 6 | Use valid platform string | -| [CA1420](quality-rules/ca1420.md) | Interoperability | Warning | .NET 7 | Using features that require runtime marshalling when it's disabled will result in run-time exceptions | +| [CA1420](quality-rules/ca1420.md) | Interoperability | Warning | .NET 7 | Using features that require runtime marshalling when it's disabled will result in runtime exceptions | | [CA1422](quality-rules/ca1422.md) | Interoperability | Warning | .NET 7 | Validate platform compatibility | | [CA1831](quality-rules/ca1831.md) | Performance | Warning | .NET 5 | Use `AsSpan` instead of range-based indexers for string when appropriate | | [CA1856](quality-rules/ca1856.md) | Performance | Error | .NET 8 | Incorrect usage of `ConstantExpected` attribute | @@ -102,7 +102,7 @@ The following rules are enabled, by default, as errors or warnings in .NET 8. Ad | [CA1416](quality-rules/ca1416.md) | Interoperability | Warning | .NET 5 | Validate platform compatibility | | [CA1417](quality-rules/ca1417.md) | Interoperability | Warning | .NET 5 | Do not use `OutAttribute` on string parameters for P/Invokes | | [CA1418](quality-rules/ca1418.md) | Interoperability | Warning | .NET 6 | Use valid platform string | -| [CA1420](quality-rules/ca1420.md) | Interoperability | Warning | .NET 7 | Using features that require runtime marshalling when it's disabled will result in run-time exceptions | +| [CA1420](quality-rules/ca1420.md) | Interoperability | Warning | .NET 7 | Using features that require runtime marshalling when it's disabled will result in runtime exceptions | | [CA1422](quality-rules/ca1422.md) | Interoperability | Warning | .NET 7 | Validate platform compatibility | | [CA1831](quality-rules/ca1831.md) | Performance | Warning | .NET 5 | Use `AsSpan` instead of range-based indexers for string when appropriate | | [CA1856](quality-rules/ca1856.md) | Performance | Error | .NET 8 | Incorrect usage of `ConstantExpected` attribute | diff --git a/docs/fundamentals/code-analysis/quality-rules/ca1031.md b/docs/fundamentals/code-analysis/quality-rules/ca1031.md index ffde465e1c6ff..9e5cb94426798 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca1031.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca1031.md @@ -40,7 +40,7 @@ To fix a violation of this rule, catch a more specific exception, or rethrow the ## When to suppress warnings -Do not suppress a warning from this rule. Catching general exception types can hide run-time problems from the library user and can make debugging more difficult. +Do not suppress a warning from this rule. Catching general exception types can hide runtime problems from the library user and can make debugging more difficult. > [!NOTE] > Starting with .NET Framework 4, the common language runtime (CLR) no longer delivers corrupted state exceptions that occur in the operating system and managed code, such as access violations in Windows, to be handled by managed code. If you want to compile an application in .NET Framework 4 or later versions and maintain handling of corrupted state exceptions, you can apply the attribute to the method that handles the corrupted state exception. diff --git a/docs/fundamentals/code-analysis/quality-rules/ca1040.md b/docs/fundamentals/code-analysis/quality-rules/ca1040.md index de41a7afd87bb..66694ced5c7b4 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca1040.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca1040.md @@ -34,7 +34,7 @@ By default, this rule only looks at externally visible interfaces, but this is [ Interfaces define members that provide a behavior or usage contract. The functionality that is described by the interface can be adopted by any type, regardless of where the type appears in the inheritance hierarchy. A type implements an interface by providing implementations for the members of the interface. An empty interface does not define any members. Therefore, it does not define a contract that can be implemented. -If your design includes empty interfaces that types are expected to implement, you are probably using an interface as a marker or a way to identify a group of types. If this identification will occur at run time, the correct way to accomplish this is to use a custom attribute. Use the presence or absence of the attribute, or the properties of the attribute, to identify the target types. If the identification must occur at compile time, then it is acceptable to use an empty interface. +If your design includes empty interfaces that types are expected to implement, you are probably using an interface as a marker or a way to identify a group of types. If this identification will occur at runtime, the correct way to accomplish this is to use a custom attribute. Use the presence or absence of the attribute, or the properties of the attribute, to identify the target types. If the identification must occur at compile time, then it is acceptable to use an empty interface. ## How to fix violations diff --git a/docs/fundamentals/code-analysis/quality-rules/ca1416.md b/docs/fundamentals/code-analysis/quality-rules/ca1416.md index 02138466bc75d..0cc07f62d8cde 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca1416.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca1416.md @@ -113,7 +113,7 @@ The analyzer does not check target framework moniker (TFM) target platforms from ## How to fix violations -The recommended way to deal with violations is to make sure you only call platform-specific APIs when running on an appropriate platform. You can achieve this by excluding the code at build time using `#if` and multi-targeting, or by conditionally calling the code at run time. The analyzer recognizes the platform guards in the class and . +The recommended way to deal with violations is to make sure you only call platform-specific APIs when running on an appropriate platform. You can achieve this by excluding the code at build time using `#if` and multi-targeting, or by conditionally calling the code at runtime. The analyzer recognizes the platform guards in the class and . - Suppress violations by surrounding the call site with the standard platform guard methods or custom guard APIs annotated with or . diff --git a/docs/fundamentals/code-analysis/quality-rules/ca1420.md b/docs/fundamentals/code-analysis/quality-rules/ca1420.md index 6c4d78bdfb199..8690f66c82645 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca1420.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca1420.md @@ -26,7 +26,7 @@ A code feature is used that requires runtime marshalling, and runtime marshallin ## Rule description -Using features that require runtime marshalling when runtime marshalling is disabled will result in run-time exceptions. +Using features that require runtime marshalling when runtime marshalling is disabled will result in runtime exceptions. ## How to fix violations diff --git a/docs/fundamentals/code-analysis/quality-rules/ca1421.md b/docs/fundamentals/code-analysis/quality-rules/ca1421.md index f435929a83f2d..ab1dd3480b0f7 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca1421.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca1421.md @@ -27,7 +27,7 @@ A method uses runtime marshalling, and runtime marshalling is explicitly disable ## Rule description -If a method uses runtime marshalling when runtime marshalling is disabled, it can cause unexpected behavior differences at run time due to different expectations of a type's native layout. +If a method uses runtime marshalling when runtime marshalling is disabled, it can cause unexpected behavior differences at runtime due to different expectations of a type's native layout. ## How to fix violations diff --git a/docs/fundamentals/code-analysis/quality-rules/ca1502.md b/docs/fundamentals/code-analysis/quality-rules/ca1502.md index f6bc664c29b4c..ba41461fe7711 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca1502.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca1502.md @@ -47,7 +47,7 @@ To fix a violation of this rule, refactor the method to reduce its cyclomatic co ## When to suppress warnings -It is safe to suppress a warning from this rule if the complexity cannot easily be reduced and the method is easy to understand, test, and maintain. In particular, a method that contains a large `switch` (`Select` in Visual Basic) statement is a candidate for exclusion. The risk of destabilizing the code base late in the development cycle or introducing an unexpected change in run-time behavior in previously shipped code might outweigh the maintainability benefits of refactoring the code. +It is safe to suppress a warning from this rule if the complexity cannot easily be reduced and the method is easy to understand, test, and maintain. In particular, a method that contains a large `switch` (`Select` in Visual Basic) statement is a candidate for exclusion. The risk of destabilizing the code base late in the development cycle or introducing an unexpected change in runtime behavior in previously shipped code might outweigh the maintainability benefits of refactoring the code. > [!NOTE] > You might see false positive warnings from this rule if all of the following apply: diff --git a/docs/fundamentals/code-analysis/quality-rules/ca1508.md b/docs/fundamentals/code-analysis/quality-rules/ca1508.md index fa8698fe851f8..e71f42ee7f632 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca1508.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca1508.md @@ -23,7 +23,7 @@ ms.author: mavasani ## Cause -A method has conditional code that always evaluates to `true` or `false` at run time. This leads to dead code in the `false` branch of the condition. +A method has conditional code that always evaluates to `true` or `false` at runtime. This leads to dead code in the `false` branch of the condition. By default, this rule analyzes the entire codebase, but this is [configurable](#configure-code-to-analyze). @@ -54,7 +54,7 @@ public void M(int i, int j) } ``` -C# and VB compilers perform analysis of conditional checks involving compile-time _constant values_ that always evaluate to `true` or `false`. This analyzer performs data flow analysis of non-constant variables to determine redundant conditional checks involving _non-constant values_. In the preceding code, the analyzer determines that `i` and `j` are both `0` for all code paths that reach `i != j` check. Hence, this check will always evaluate to `false` at run time. The code inside the if statement is dead code and can be removed or refactored. Similarly, the analyzer tracks nullness of variables and reports redundant null checks. +C# and VB compilers perform analysis of conditional checks involving compile-time _constant values_ that always evaluate to `true` or `false`. This analyzer performs data flow analysis of non-constant variables to determine redundant conditional checks involving _non-constant values_. In the preceding code, the analyzer determines that `i` and `j` are both `0` for all code paths that reach `i != j` check. Hence, this check will always evaluate to `false` at runtime. The code inside the if statement is dead code and can be removed or refactored. Similarly, the analyzer tracks nullness of variables and reports redundant null checks. > [!NOTE] > This analyzer performs an expensive dataflow analysis of non-constant values. This can increase the overall compile time on certain code bases. diff --git a/docs/fundamentals/code-analysis/quality-rules/ca1801.md b/docs/fundamentals/code-analysis/quality-rules/ca1801.md index 1a48c1d74c9c2..f8dfce500fa43 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca1801.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca1801.md @@ -44,7 +44,7 @@ This rule does not examine the following kinds of methods: - Methods declared with the `extern` (`Declare` statement in Visual Basic) modifier. -This rule does not flag parameters that are named with the [discard](../../../csharp/fundamentals/functional/discards.md) symbol, for example, `_`, `_1`, and `_2`. This reduces warning noise on parameters that are needed for signature requirements, for example, a method used as a delegate, a parameter with special attributes, or a parameter whose value is implicitly accessed at run time by a framework but is not referenced in code. +This rule does not flag parameters that are named with the [discard](../../../csharp/fundamentals/functional/discards.md) symbol, for example, `_`, `_1`, and `_2`. This reduces warning noise on parameters that are needed for signature requirements, for example, a method used as a delegate, a parameter with special attributes, or a parameter whose value is implicitly accessed at runtime by a framework but is not referenced in code. > [!NOTE] > This rule has been deprecated in favor of [IDE0060](../style-rules/ide0060.md). For information about how to enforce the IDE0060 analyzer at build, see [code-style analysis](../overview.md#code-style-analysis). diff --git a/docs/fundamentals/code-analysis/quality-rules/ca1802.md b/docs/fundamentals/code-analysis/quality-rules/ca1802.md index a4d8f8e38600f..81ba6d3a487f7 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca1802.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca1802.md @@ -32,11 +32,11 @@ By default, this rule only looks at externally visible, static, readonly fields, ## Rule description -The value of a `static readonly` field is computed at run time when the static constructor for the declaring type is called. If the `static readonly` field is initialized when it is declared and a static constructor is not declared explicitly, the compiler emits a static constructor to initialize the field. +The value of a `static readonly` field is computed at runtime when the static constructor for the declaring type is called. If the `static readonly` field is initialized when it is declared and a static constructor is not declared explicitly, the compiler emits a static constructor to initialize the field. -The value of a `const` field is computed at compile time and stored in the metadata, which improves run-time performance when it is compared to a `static readonly` field. +The value of a `const` field is computed at compile time and stored in the metadata, which improves runtime performance when it is compared to a `static readonly` field. -Because the value assigned to the targeted field is computable at compile time, change the declaration to a `const` field so that the value is computed at compile time instead of at run time. +Because the value assigned to the targeted field is computable at compile time, change the declaration to a `const` field so that the value is computed at compile time instead of at runtime. ## How to fix violations diff --git a/docs/fundamentals/code-analysis/quality-rules/ca1822.md b/docs/fundamentals/code-analysis/quality-rules/ca1822.md index 02470374db88f..ba3816b03b8fe 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca1822.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca1822.md @@ -29,7 +29,7 @@ A member that does not access instance data is not marked as static (Shared in V ## Rule description -Members that do not access instance data or call instance methods can be marked as static (Shared in Visual Basic). After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. Emitting nonvirtual call sites will prevent a check at run time for each call that makes sure that the current object pointer is non-null. This can achieve a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue. +Members that do not access instance data or call instance methods can be marked as static (Shared in Visual Basic). After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. Emitting nonvirtual call sites will prevent a check at runtime for each call that makes sure that the current object pointer is non-null. This can achieve a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue. ## How to fix violations diff --git a/docs/fundamentals/code-analysis/quality-rules/ca1861.md b/docs/fundamentals/code-analysis/quality-rules/ca1861.md index 0f94c263ac64a..72ca378e2d784 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca1861.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca1861.md @@ -70,7 +70,7 @@ Private Function GetMessage() As String End Function ``` -Now, the value of the array is resolved at compile time rather than at run time, making code more performant. +Now, the value of the array is resolved at compile time rather than at runtime, making code more performant. ## When to suppress warnings diff --git a/docs/fundamentals/code-analysis/quality-rules/ca1863.md b/docs/fundamentals/code-analysis/quality-rules/ca1863.md index 00cf030693d4a..afcbc2b9d57a6 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca1863.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca1863.md @@ -24,7 +24,7 @@ Code calls instance as the argument to a formatting operation, rather than passing in the original format string. A instance parses the composite format string when it's created, which means the "hot path" of string formatting can execute much faster. +It's expensive to parse a format string at runtime. This rule locates places in your code where you can cache and use a instance as the argument to a formatting operation, rather than passing in the original format string. A instance parses the composite format string when it's created, which means the "hot path" of string formatting can execute much faster. ## How to fix violations diff --git a/docs/fundamentals/code-analysis/quality-rules/ca2008.md b/docs/fundamentals/code-analysis/quality-rules/ca2008.md index 14b8f88ef52ee..b07105f4c08d8 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca2008.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca2008.md @@ -33,7 +33,7 @@ The following .NET task creation and continuation methods have overloads that al - methods - methods -Always specify an explicit argument to avoid the default value, whose behavior is defined by the caller and may vary at run time. returns the scheduler associated with whatever is currently running on that thread. If there is no such task, it returns , which represents the thread pool. Using could lead to deadlocks or UI responsiveness issues in some situations, when it was intended to create the task on the thread pool, but instead it waits to get back onto the UI thread. +Always specify an explicit argument to avoid the default value, whose behavior is defined by the caller and may vary at runtime. returns the scheduler associated with whatever is currently running on that thread. If there is no such task, it returns , which represents the thread pool. Using could lead to deadlocks or UI responsiveness issues in some situations, when it was intended to create the task on the thread pool, but instead it waits to get back onto the UI thread. For further information and detailed examples, see [New TaskCreationOptions and TaskContinuationOptions in .NET Framework 4.5](https://devblogs.microsoft.com/pfxteam/new-taskcreationoptions-and-taskcontinuationoptions-in-net-4-5/). diff --git a/docs/fundamentals/code-analysis/quality-rules/ca2011.md b/docs/fundamentals/code-analysis/quality-rules/ca2011.md index 2bfd9f78f7f26..0d20242661df0 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca2011.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca2011.md @@ -25,7 +25,7 @@ A property was accidentally assigned a value within its own [set accessor](../.. ## Rule description -Assigning a property to itself in its [set accessor](../../../csharp/programming-guide/classes-and-structs/using-properties.md#the-set-accessor) leads to an infinite chain of recursive calls to the set accessor. This results in a at run time. Such a mistake is common when the property and the backing field to store the property value have similar names. Instead of assigning the value to the backing field, it was accidentally assigned to the property itself. +Assigning a property to itself in its [set accessor](../../../csharp/programming-guide/classes-and-structs/using-properties.md#the-set-accessor) leads to an infinite chain of recursive calls to the set accessor. This results in a at runtime. Such a mistake is common when the property and the backing field to store the property value have similar names. Instead of assigning the value to the backing field, it was accidentally assigned to the property itself. ## How to fix violations diff --git a/docs/fundamentals/code-analysis/quality-rules/ca2021.md b/docs/fundamentals/code-analysis/quality-rules/ca2021.md index 760fed0164a45..997c50cd98e17 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca2021.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca2021.md @@ -28,7 +28,7 @@ A call to and require compatible types to produce the expected result: -- The generic cast used by the sequence returned by throws an at run time on elements of incompatible types. +- The generic cast used by the sequence returned by throws an at runtime on elements of incompatible types. - The generic type check used by won't succeed with elements of incompatible types, resulting in an empty sequence. Widening and user-defined conversions aren't supported with generic types. @@ -83,4 +83,4 @@ Dim a1 = (Array.Empty(Of Integer)()).OfType(Of Object) ## When to suppress warnings -You shouldn't suppress warnings from this rule, as you'll either encounter run-time exceptions or unexpected behavior (empty sequences). +You shouldn't suppress warnings from this rule, as you'll either encounter runtime exceptions or unexpected behavior (empty sequences). diff --git a/docs/fundamentals/code-analysis/quality-rules/ca2023.md b/docs/fundamentals/code-analysis/quality-rules/ca2023.md index b81d013cd5d08..fa8a1f8d11838 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca2023.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca2023.md @@ -138,7 +138,7 @@ End Class ## When to suppress warnings -Don't suppress a warning from this rule. Invalid braces in message templates can cause run-time exceptions or incorrect log output. +Don't suppress a warning from this rule. Invalid braces in message templates can cause runtime exceptions or incorrect log output. ## Suppress a warning diff --git a/docs/fundamentals/code-analysis/quality-rules/ca2153.md b/docs/fundamentals/code-analysis/quality-rules/ca2153.md index 11f0672f77de5..ea21e1e2068af 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca2153.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca2153.md @@ -33,7 +33,7 @@ This warning triggers when catching CSEs with a general handler that catches all To resolve this warning, do one of the following: -- Remove the attribute. This reverts to the default run-time behavior where CSEs are not passed to catch handlers. +- Remove the attribute. This reverts to the default runtime behavior where CSEs are not passed to catch handlers. - Remove the general catch handler in preference of handlers that catch specific exception types. This may include CSEs, assuming the handler code can safely handle them (rare). diff --git a/docs/fundamentals/code-analysis/quality-rules/ca2214.md b/docs/fundamentals/code-analysis/quality-rules/ca2214.md index 3412e71842162..d2983162bd291 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca2214.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca2214.md @@ -30,7 +30,7 @@ The constructor of an unsealed type calls a virtual method defined in its class. ## Rule description -When a virtual method is called, the actual type that executes the method is not selected until run time. When a constructor calls a virtual method, it's possible that the constructor for the instance that invokes the method has not executed. This could lead to errors or unexpected behavior, if an overridden virtual method relies on initialization and other configuration in the constructor. +When a virtual method is called, the actual type that executes the method is not selected until runtime. When a constructor calls a virtual method, it's possible that the constructor for the instance that invokes the method has not executed. This could lead to errors or unexpected behavior, if an overridden virtual method relies on initialization and other configuration in the constructor. ## How to fix violations diff --git a/docs/fundamentals/code-analysis/quality-rules/ca2241.md b/docs/fundamentals/code-analysis/quality-rules/ca2241.md index c5d34a073e216..9bea5fad38088 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca2241.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca2241.md @@ -33,7 +33,7 @@ By default, this rule only analyzes calls to the three methods mentioned previou ## Rule description -The arguments to methods such as , , and consist of a format string followed by several instances. The format string consists of text and embedded format items of the form `{index[,alignment][:formatString]}`. 'index' is a zero-based integer that indicates which of the objects to format. If an object does not have a corresponding index in the format string, the object is ignored. If the object specified by 'index' does not exist, a is thrown at run time. +The arguments to methods such as , , and consist of a format string followed by several instances. The format string consists of text and embedded format items of the form `{index[,alignment][:formatString]}`. 'index' is a zero-based integer that indicates which of the objects to format. If an object does not have a corresponding index in the format string, the object is ignored. If the object specified by 'index' does not exist, a is thrown at runtime. ## How to fix violations diff --git a/docs/fundamentals/code-analysis/quality-rules/ca2248.md b/docs/fundamentals/code-analysis/quality-rules/ca2248.md index ac55e6defadd1..ad9eb1c25f55a 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca2248.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca2248.md @@ -25,7 +25,7 @@ The enum type passed as an argument to the `HasFlag` method call is different fr ## Rule description -The `Enum.HasFlag` method expects the `enum` argument to be of the same `enum` type as the instance on which the method is invoked. If these are different `enum` types, an unhandled exception will be thrown at run time. +The `Enum.HasFlag` method expects the `enum` argument to be of the same `enum` type as the instance on which the method is invoked. If these are different `enum` types, an unhandled exception will be thrown at runtime. ## How to fix violations @@ -42,7 +42,7 @@ public class C public void Method(MyEnum m) { - m.HasFlag(OtherEnum.A); // Enum types are different, this call will cause an `ArgumentException` to be thrown at run time + m.HasFlag(OtherEnum.A); // Enum types are different, this call will cause an `ArgumentException` to be thrown at runtime m.HasFlag(MyEnum.A); // Valid call } diff --git a/docs/fundamentals/code-analysis/quality-rules/ca2257.md b/docs/fundamentals/code-analysis/quality-rules/ca2257.md index 448ec562c9325..7cc37942f743c 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca2257.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca2257.md @@ -28,7 +28,7 @@ An interface member isn't explicitly implemented or marked `static`. ## Rule description -Since a type that implements `IDynamicInterfaceCastable` may not implement a dynamic interface in metadata, calls to an instance interface member that is not an explicit implementation defined on this type are likely to fail at run time. To avoid run-time errors, mark new interface members `static`. +Since a type that implements `IDynamicInterfaceCastable` may not implement a dynamic interface in metadata, calls to an instance interface member that is not an explicit implementation defined on this type are likely to fail at runtime. To avoid runtime errors, mark new interface members `static`. ## How to fix violations diff --git a/docs/fundamentals/code-analysis/quality-rules/ca2261.md b/docs/fundamentals/code-analysis/quality-rules/ca2261.md index 0a6d937e4ad65..ff1008587949f 100644 --- a/docs/fundamentals/code-analysis/quality-rules/ca2261.md +++ b/docs/fundamentals/code-analysis/quality-rules/ca2261.md @@ -23,7 +23,7 @@ A value of option isn't supported by the generic , since that might lead to returning an invalid `TResult`. This rule flags the use of with to surface the error at build time rather than run time. +The option isn't supported by the generic , since that might lead to returning an invalid `TResult`. This rule flags the use of with to surface the error at build time rather than runtime. ## How to fix violations @@ -47,4 +47,4 @@ Task t = new Task(() => 1); ## When to suppress errors -You shouldn't suppress warnings from this rule. If the task is faulted or canceled, `TResult` will be invalid and cause run-time errors. +You shouldn't suppress warnings from this rule. If the task is faulted or canceled, `TResult` will be invalid and cause runtime errors. diff --git a/docs/fundamentals/code-analysis/quality-rules/index.md b/docs/fundamentals/code-analysis/quality-rules/index.md index c3984cc884ae2..152e509a557f6 100644 --- a/docs/fundamentals/code-analysis/quality-rules/index.md +++ b/docs/fundamentals/code-analysis/quality-rules/index.md @@ -78,7 +78,7 @@ The following table lists code quality analysis rules. > | [CA1417: Do not use `OutAttribute` on string parameters for P/Invokes](ca1417.md) | String parameters passed by value with the `OutAttribute` can destabilize the runtime if the string is an interned string. | > | [CA1418: Use valid platform string](ca1418.md) | Platform compatibility analyzer requires a valid platform name and version. | > | [CA1419: Provide a parameterless constructor that is as visible as the containing type for concrete types derived from `System.Runtime.InteropServices.SafeHandle`](ca1419.md) | Providing a parameterless constructor that is as visible as the containing type for a type derived from `System.Runtime.InteropServices.SafeHandle` enables better performance and usage with source-generated interop solutions. | -> | [CA1420: Property, type, or attribute requires runtime marshalling](ca1420.md) | Using features that require runtime marshalling when runtime marshalling is disabled will result in run-time exceptions. | +> | [CA1420: Property, type, or attribute requires runtime marshalling](ca1420.md) | Using features that require runtime marshalling when runtime marshalling is disabled will result in runtime exceptions. | > | [CA1421: Method uses runtime marshalling when DisableRuntimeMarshallingAttribute is applied](ca1421.md) | A method uses runtime marshalling, and runtime marshalling is explicitly disabled. | > | [CA1422: Validate platform compatibility](ca1422.md) | Calling an API that's obsolete in a given OS (version) from a call site that's reachable from that OS (version) is not recommended. | > | [CA1501: Avoid excessive inheritance](ca1501.md) | A type is more than four levels deep in its inheritance hierarchy. Deeply nested type hierarchies can be difficult to follow, understand, and maintain. | @@ -86,7 +86,7 @@ The following table lists code quality analysis rules. > | [CA1505: Avoid unmaintainable code](ca1505.md) | A type or method has a low maintainability index value. A low maintainability index indicates that a type or method is probably difficult to maintain and would be a good candidate for redesign. | > | [CA1506: Avoid excessive class coupling](ca1506.md) | This rule measures class coupling by counting the number of unique type references that a type or method contains. | > | [CA1507: Use nameof in place of string](ca1507.md) | A string literal is used as an argument where a `nameof` expression could be used. | -> | [CA1508: Avoid dead conditional code](ca1508.md) | A method has conditional code that always evaluates to `true` or `false` at run time. This leads to dead code in the `false` branch of the condition. | +> | [CA1508: Avoid dead conditional code](ca1508.md) | A method has conditional code that always evaluates to `true` or `false` at runtime. This leads to dead code in the `false` branch of the condition. | > | [CA1509: Invalid entry in code metrics configuration file](ca1509.md) | Code metrics rules, such as [CA1501](ca1501.md), [CA1502](ca1502.md), [CA1505](ca1505.md) and [CA1506](ca1506.md), supplied a configuration file named `CodeMetricsConfig.txt` that has an invalid entry. | > | [CA1510: Use ArgumentNullException throw helper](ca1510.md) | Throw helpers are simpler and more efficient than `if` blocks that construct a new exception instance. | > | [CA1511: Use ArgumentException throw helper](ca1511.md) | Throw helpers are simpler and more efficient than `if` blocks that construct a new exception instance. | @@ -112,7 +112,7 @@ The following table lists code quality analysis rules. > | [CA1725: Parameter names should match base declaration](ca1725.md) | Consistent naming of parameters in an override hierarchy increases the usability of the method overrides. A parameter name in a derived method that differs from the name in the base declaration can cause confusion about whether the method is an override of the base method or a new overload of the method. | > | [CA1727: Use PascalCase for named placeholders](ca1727.md) | Use PascalCase for named placeholders in the logging message template. | > | [CA1801: Review unused parameters](ca1801.md) | A method signature includes a parameter that is not used in the method body. | -> | [CA1802: Use Literals Where Appropriate](ca1802.md) | A field is declared static and read-only (Shared and ReadOnly in Visual Basic), and is initialized by using a value that is computable at compile time. Because the value that is assigned to the targeted field is computable at compile time, change the declaration to a const (Const in Visual Basic) field so that the value is computed at compile time instead of at run time. | +> | [CA1802: Use Literals Where Appropriate](ca1802.md) | A field is declared static and read-only (Shared and ReadOnly in Visual Basic), and is initialized by using a value that is computable at compile time. Because the value that is assigned to the targeted field is computable at compile time, change the declaration to a const (Const in Visual Basic) field so that the value is computed at compile time instead of at runtime. | > | [CA1805: Do not initialize unnecessarily](ca1805.md) | The .NET runtime initializes all fields of reference types to their default values before running the constructor. In most cases, explicitly initializing a field to its default value is redundant, which adds to maintenance costs and might degrade performance (such as with increased assembly size). | > | [CA1806: Do not ignore method results](ca1806.md) | A new object is created but never used; or a method that creates and returns a new string is called and the new string is never used; or a COM or P/Invoke method returns an HRESULT or error code that is never used. | > | [CA1810: Initialize reference type static fields inline](ca1810.md) | When a type declares an explicit static constructor, the just-in-time (JIT) compiler adds a check to each static method and instance constructor of the type to make sure that the static constructor was previously called. Static constructor checks can decrease performance. | @@ -240,7 +240,7 @@ The following table lists code quality analysis rules. > | [CA2254: Template should be a static expression](ca2254.md) | The logging message template should not vary between calls. | > | [CA2255: The `ModuleInitializer` attribute should not be used in libraries](ca2255.md) | Module initializers are intended to be used by application code to ensure an application's components are initialized before the application code begins executing. | > | [CA2256: All members declared in parent interfaces must have an implementation in a DynamicInterfaceCastableImplementation-attributed interface](ca2256.md) | Types attributed with `DynamicInterfaceCastableImplementationAttribute` act as an interface implementation for a type that implements the `IDynamicInterfaceCastable` type. As a result, it must provide an implementation of all of the members defined in the inherited interfaces, because the type that implements `IDynamicInterfaceCastable` will not provide them otherwise. | -> | [CA2257: Members defined on an interface with `DynamicInterfaceCastableImplementationAttribute` should be `static`](ca2257.md) | Since a type that implements `IDynamicInterfaceCastable` might not implement a dynamic interface in metadata, calls to an instance interface member that is not an explicit implementation defined on this type are likely to fail at run time. Mark new interface members `static` to avoid run-time errors. | +> | [CA2257: Members defined on an interface with `DynamicInterfaceCastableImplementationAttribute` should be `static`](ca2257.md) | Since a type that implements `IDynamicInterfaceCastable` might not implement a dynamic interface in metadata, calls to an instance interface member that is not an explicit implementation defined on this type are likely to fail at runtime. Mark new interface members `static` to avoid runtime errors. | > | [CA2258: Providing a `DynamicInterfaceCastableImplementation` interface in Visual Basic is unsupported](ca2258.md) | Providing a functional `DynamicInterfaceCastableImplementationAttribute`-attributed interface requires the Default Interface Members feature, which is unsupported in Visual Basic. | > | [CA2259: Ensure `ThreadStatic` is only used with static fields](ca2259.md) | only affects `static` (`Shared` in Visual Basic) fields. When applied to instance fields, the attribute has no impact on behavior. | > | [CA2260: Implement generic math interfaces correctly](ca2260.md) | Generic math interfaces require the derived type itself to be used for the self-recurring type parameter. | @@ -355,7 +355,7 @@ The following table shows the type of information that is provided for each rule | Type | The TypeName for the rule. | | **Rule ID** | The unique identifier for the rule. RuleId and Category are used for in-source suppression of a warning. | | **Category** | The category of the rule, for example, security. | -| **Fix is breaking or non-breaking** | Whether the fix for a violation of the rule is a breaking change. Breaking change means that an assembly that has a dependency on the target that caused the violation will not recompile with the new fixed version or might fail at run time because of the change. When multiple fixes are available and at least one fix is a breaking change and one fix is not, both 'Breaking' and 'Non-breaking' are specified. | +| **Fix is breaking or non-breaking** | Whether the fix for a violation of the rule is a breaking change. Breaking change means that an assembly that has a dependency on the target that caused the violation will not recompile with the new fixed version or might fail at runtime because of the change. When multiple fixes are available and at least one fix is a breaking change and one fix is not, both 'Breaking' and 'Non-breaking' are specified. | | Cause | The specific managed code that causes the rule to generate a warning. | | Description | Discusses the issues that are behind the warning. | | How to fix violations | Explains how to change the source code to satisfy the rule and prevent it from generating a warning. | diff --git a/docs/fundamentals/code-analysis/quality-rules/interoperability-warnings.md b/docs/fundamentals/code-analysis/quality-rules/interoperability-warnings.md index 67077b819ca5d..d232eca10a39b 100644 --- a/docs/fundamentals/code-analysis/quality-rules/interoperability-warnings.md +++ b/docs/fundamentals/code-analysis/quality-rules/interoperability-warnings.md @@ -27,6 +27,6 @@ Portability rules support portability across different platforms. Interoperabili | [CA1417: Do not use `OutAttribute` on string parameters for P/Invokes](ca1417.md) | String parameters passed by value with the `OutAttribute` can destabilize the runtime if the string is an interned string. | | [CA1418: Use valid platform string](ca1418.md) | Platform compatibility analyzer requires a valid platform name and version. | | [CA1419: Provide a parameterless constructor that is as visible as the containing type for concrete types derived from 'System.Runtime.InteropServices.SafeHandle'](ca1419.md) | Providing a parameterless constructor that is as visible as the containing type for a type derived from `System.Runtime.InteropServices.SafeHandle` enables better performance and usage with source-generated interop solutions. | -| [CA1420: Property, type, or attribute requires runtime marshalling](ca1420.md) | Using features that require runtime marshalling when runtime marshalling is disabled will result in run-time exceptions. | +| [CA1420: Property, type, or attribute requires runtime marshalling](ca1420.md) | Using features that require runtime marshalling when runtime marshalling is disabled will result in runtime exceptions. | | [CA1421: Method uses runtime marshalling when DisableRuntimeMarshallingAttribute is applied](ca1421.md) | A method uses runtime marshalling, and runtime marshalling is explicitly disabled. | | [CA1422: Validate platform compatibility](ca1422.md) | Calling an API that's obsolete in a given OS (version) from a call site that's reachable from that OS (version) is not recommended. | diff --git a/docs/fundamentals/code-analysis/quality-rules/maintainability-warnings.md b/docs/fundamentals/code-analysis/quality-rules/maintainability-warnings.md index 5da85471d19d2..2365b9394a2f1 100644 --- a/docs/fundamentals/code-analysis/quality-rules/maintainability-warnings.md +++ b/docs/fundamentals/code-analysis/quality-rules/maintainability-warnings.md @@ -24,7 +24,7 @@ Maintainability rules support library and application maintenance. | [CA1505: Avoid unmaintainable code](ca1505.md) | A type or method has a low maintainability index value. A low maintainability index indicates that a type or method is probably difficult to maintain and would be a good candidate for redesign. | | [CA1506: Avoid excessive class coupling](ca1506.md) | This rule measures class coupling by counting the number of unique type references that a type or method contains. | | [CA1507: Use nameof in place of string](ca1507.md) | A string literal is used as an argument where a `nameof` expression could be used. | -| [CA1508: Avoid dead conditional code](ca1508.md) | A method has conditional code that always evaluates to `true` or `false` at run time. This leads to dead code in the `false` branch of the condition. | +| [CA1508: Avoid dead conditional code](ca1508.md) | A method has conditional code that always evaluates to `true` or `false` at runtime. This leads to dead code in the `false` branch of the condition. | | [CA1509: Invalid entry in code metrics configuration file](ca1509.md) | Code metrics rules, such as [CA1501](ca1501.md), [CA1502](ca1502.md), [CA1505](ca1505.md) and [CA1506](ca1506.md), supplied a configuration file named `CodeMetricsConfig.txt` that has an invalid entry. | | [CA1510: Use ArgumentNullException throw helper](ca1510.md) | Throw helpers are simpler and more efficient than `if` blocks that construct a new exception instance. | | [CA1511: Use ArgumentException throw helper](ca1511.md) | Throw helpers are simpler and more efficient than `if` blocks that construct a new exception instance. | diff --git a/docs/fundamentals/code-analysis/quality-rules/performance-warnings.md b/docs/fundamentals/code-analysis/quality-rules/performance-warnings.md index 0e88fd280368f..f090189a1c2ef 100644 --- a/docs/fundamentals/code-analysis/quality-rules/performance-warnings.md +++ b/docs/fundamentals/code-analysis/quality-rules/performance-warnings.md @@ -20,7 +20,7 @@ Performance rules support high-performance libraries and applications. | Rule | Description | |------|-------------| -| [CA1802: Use Literals Where Appropriate](ca1802.md) | A field is declared static and read-only (Shared and ReadOnly in Visual Basic), and is initialized with a value that is computable at compile time. Because the value that is assigned to the targeted field is computable at compile time, change the declaration to a const (Const in Visual Basic) field so that the value is computed at compile time instead of at run time. | +| [CA1802: Use Literals Where Appropriate](ca1802.md) | A field is declared static and read-only (Shared and ReadOnly in Visual Basic), and is initialized with a value that is computable at compile time. Because the value that is assigned to the targeted field is computable at compile time, change the declaration to a const (Const in Visual Basic) field so that the value is computed at compile time instead of at runtime. | | [CA1805: Do not initialize unnecessarily](ca1805.md) | The .NET runtime initializes all fields of reference types to their default values before running the constructor. In most cases, explicitly initializing a field to its default value is redundant, which adds to maintenance costs and may degrade performance (such as with increased assembly size). | | [CA1806: Do not ignore method results](ca1806.md) | A new object is created but never used, or a method that creates and returns a new string is called and the new string is never used, or a Component Object Model (COM) or P/Invoke method returns an HRESULT or error code that is never used. | | [CA1810: Initialize reference type static fields inline](ca1810.md) | When a type declares an explicit static constructor, the just-in-time (JIT) compiler adds a check to each static method and instance constructor of the type to make sure that the static constructor was previously called. Static constructor checks can decrease performance. | diff --git a/docs/fundamentals/code-analysis/quality-rules/usage-warnings.md b/docs/fundamentals/code-analysis/quality-rules/usage-warnings.md index fb8441a28d98b..1c425e8bb6525 100644 --- a/docs/fundamentals/code-analysis/quality-rules/usage-warnings.md +++ b/docs/fundamentals/code-analysis/quality-rules/usage-warnings.md @@ -56,7 +56,7 @@ Usage rules support proper usage of .NET. |[CA2254: Template should be a static expression](ca2254.md)|The logging message template should not vary between calls.| |[CA2255: The `ModuleInitializer` attribute should not be used in libraries](ca2255.md) | Module initializers are intended to be used by application code to ensure an application's components are initialized before the application code begins executing. | |[CA2256: All members declared in parent interfaces must have an implementation in a DynamicInterfaceCastableImplementation-attributed interface](ca2256.md) | Types attributed with `DynamicInterfaceCastableImplementationAttribute` act as an interface implementation for a type that implements the `IDynamicInterfaceCastable` type. As a result, it must provide an implementation of all of the members defined in the inherited interfaces, because the type that implements `IDynamicInterfaceCastable` will not provide them otherwise. | -|[CA2257: Members defined on an interface with 'DynamicInterfaceCastableImplementationAttribute' should be 'static'](ca2257.md) | Since a type that implements `IDynamicInterfaceCastable` may not implement a dynamic interface in metadata, calls to an instance interface member that is not an explicit implementation defined on this type are likely to fail at run time. Mark new interface members `static` to avoid run-time errors. | +|[CA2257: Members defined on an interface with 'DynamicInterfaceCastableImplementationAttribute' should be 'static'](ca2257.md) | Since a type that implements `IDynamicInterfaceCastable` may not implement a dynamic interface in metadata, calls to an instance interface member that is not an explicit implementation defined on this type are likely to fail at runtime. Mark new interface members `static` to avoid runtime errors. | |[CA2258: Providing a 'DynamicInterfaceCastableImplementation' interface in Visual Basic is unsupported](ca2258.md) | Providing a functional `DynamicInterfaceCastableImplementationAttribute`-attributed interface requires the Default Interface Members feature, which is unsupported in Visual Basic. | | [CA2259: Ensure `ThreadStatic` is only used with static fields](ca2259.md) | only affects `static` (`Shared` in Visual Basic) fields. When applied to instance fields, the attribute has no impact on behavior. | | [CA2260: Implement generic math interfaces correctly](ca2260.md) | Generic math interfaces require the derived type itself to be used for the self-recurring type parameter. | diff --git a/docs/fundamentals/code-analysis/style-rules/ide0060.md b/docs/fundamentals/code-analysis/style-rules/ide0060.md index 3b1fbe6d8512c..93f85f7a0b48c 100644 --- a/docs/fundamentals/code-analysis/style-rules/ide0060.md +++ b/docs/fundamentals/code-analysis/style-rules/ide0060.md @@ -29,7 +29,7 @@ dev_langs: This rule flags unused parameters. -This rule does not flag parameters that are named with the [discard](../../../csharp/fundamentals/functional/discards.md) symbol `_`. In addition, the rule ignores parameters that are named with the discard symbol followed by an integer, for example, `_1`. This behavior reduces warning noise on parameters that are needed for signature requirements, for example, a method used as a delegate, a parameter with special attributes, or a parameter whose value is implicitly accessed at run time by a framework but is not referenced in code. +This rule does not flag parameters that are named with the [discard](../../../csharp/fundamentals/functional/discards.md) symbol `_`. In addition, the rule ignores parameters that are named with the discard symbol followed by an integer, for example, `_1`. This behavior reduces warning noise on parameters that are needed for signature requirements, for example, a method used as a delegate, a parameter with special attributes, or a parameter whose value is implicitly accessed at runtime by a framework but is not referenced in code. ## Options diff --git a/docs/fundamentals/reflection/dynamically-loading-and-using-types.md b/docs/fundamentals/reflection/dynamically-loading-and-using-types.md index 64a91283bce27..54610c6a9f471 100644 --- a/docs/fundamentals/reflection/dynamically-loading-and-using-types.md +++ b/docs/fundamentals/reflection/dynamically-loading-and-using-types.md @@ -14,9 +14,9 @@ helpviewer_keywords: --- # Dynamically load and use types -Reflection provides infrastructure used by language compilers to implement implicit late binding. Binding is the process of locating the declaration (that is, the implementation) that corresponds to a uniquely specified type. When this process occurs at run time rather than at compile time, it's called late binding. Visual Basic allows you to use implicit late binding in your code; the Visual Basic compiler calls a helper method that uses reflection to obtain the object type. The arguments passed to the helper method cause the appropriate method to be invoked at run time. These arguments are the instance (an object) on which to invoke the method, the name of the invoked method (a string), and the arguments passed to the invoked method (an array of objects). +Reflection provides infrastructure used by language compilers to implement implicit late binding. Binding is the process of locating the declaration (that is, the implementation) that corresponds to a uniquely specified type. When this process occurs at runtime rather than at compile time, it's called late binding. Visual Basic allows you to use implicit late binding in your code; the Visual Basic compiler calls a helper method that uses reflection to obtain the object type. The arguments passed to the helper method cause the appropriate method to be invoked at runtime. These arguments are the instance (an object) on which to invoke the method, the name of the invoked method (a string), and the arguments passed to the invoked method (an array of objects). -In the following example, the Visual Basic compiler uses reflection implicitly to call a method on an object whose type is not known at compile time. A `HelloWorld` class has a `PrintHello` method that prints out "Hello World" concatenated with some text that's passed to the `PrintHello` method. The `PrintHello` method called in this example is actually a ; the Visual Basic code allows the `PrintHello` method to be invoked as if the type of the object (`helloObj`) were known at compile time (early binding) rather than at run time (late binding). +In the following example, the Visual Basic compiler uses reflection implicitly to call a method on an object whose type is not known at compile time. A `HelloWorld` class has a `PrintHello` method that prints out "Hello World" concatenated with some text that's passed to the `PrintHello` method. The `PrintHello` method called in this example is actually a ; the Visual Basic code allows the `PrintHello` method to be invoked as if the type of the object (`helloObj`) were known at compile time (early binding) rather than at runtime (late binding). ```vb Module Hello @@ -38,7 +38,7 @@ In addition to being used implicitly by compilers for late binding, reflection c The [common language runtime](../../standard/clr.md) supports multiple programming languages, and the binding rules of these languages differ. In the early-bound case, code generators can completely control this binding. However, in late binding through reflection, binding must be controlled by customized binding. The class provides custom control of member selection and invocation. -Using custom binding, you can load an assembly at run time, obtain information about types in that assembly, specify the type that you want, and then invoke methods or access fields or properties on that type. This technique is useful if you don't know an object's type at compile time, such as when the object type is dependent on user input. +Using custom binding, you can load an assembly at runtime, obtain information about types in that assembly, specify the type that you want, and then invoke methods or access fields or properties on that type. This technique is useful if you don't know an object's type at compile time, such as when the object type is dependent on user input. The following example demonstrates a simple custom binder that provides no argument type conversion. Code for `Simple_Type.dll` precedes the main example. Be sure to build `Simple_Type.dll` and then include a reference to it in the project at build time. diff --git a/docs/fundamentals/reflection/emitting-dynamic-methods-and-assemblies.md b/docs/fundamentals/reflection/emitting-dynamic-methods-and-assemblies.md index f805e6739fa7e..495bf1a8d14b6 100644 --- a/docs/fundamentals/reflection/emitting-dynamic-methods-and-assemblies.md +++ b/docs/fundamentals/reflection/emitting-dynamic-methods-and-assemblies.md @@ -1,6 +1,6 @@ --- title: "Emitting Dynamic Methods and Assemblies" -description: Emit dynamic methods and assemblies using the System.Reflection.Emit namespace, which allows a compiler or tool to emit metadata and CIL code at run time. +description: Emit dynamic methods and assemblies using the System.Reflection.Emit namespace, which allows a compiler or tool to emit metadata and CIL code at runtime. ms.date: 03/27/2024 helpviewer_keywords: - "reflection emit" @@ -11,15 +11,15 @@ helpviewer_keywords: --- # Emit dynamic methods and assemblies -This section describes a set of managed types in the namespace that allow a compiler or tool to emit metadata and common intermediate language (CIL) at run time and optionally generate a portable executable (PE) file on disk. Script engines and compilers are the primary users of this namespace. In this section, the functionality provided by the namespace is referred to as *reflection emit*. +This section describes a set of managed types in the namespace that allow a compiler or tool to emit metadata and common intermediate language (CIL) at runtime and optionally generate a portable executable (PE) file on disk. Script engines and compilers are the primary users of this namespace. In this section, the functionality provided by the namespace is referred to as *reflection emit*. Reflection emit provides the following capabilities: -- Define lightweight global methods at run time, using the class, and execute them using delegates. -- Define assemblies at run time and then run them and/or save them to disk. -- Define assemblies at run time, run them, and then unload them and allow garbage collection to reclaim their resources. -- Define modules in new assemblies at run time and then run and/or save them to disk. -- Define types in modules at run time, create instances of these types, and invoke their methods. +- Define lightweight global methods at runtime, using the class, and execute them using delegates. +- Define assemblies at runtime and then run them and/or save them to disk. +- Define assemblies at runtime, run them, and then unload them and allow garbage collection to reclaim their resources. +- Define modules in new assemblies at runtime and then run and/or save them to disk. +- Define types in modules at runtime, create instances of these types, and invoke their methods. - Define symbolic information for defined modules that can be used by tools such as debuggers and code profilers. In addition to the managed types in the namespace, there are unmanaged metadata interfaces that are described in [Metadata interfaces (.NET Framework)](../../framework/unmanaged-api/metadata/metadata-interfaces.md) and [Metadata interfaces (.NET)](../../core/unmanaged-api/metadata/interfaces/metadata-interfaces.md). Managed reflection emit provides stronger semantic error checking and a higher level of abstraction of the metadata than the unmanaged metadata interfaces. diff --git a/docs/fundamentals/reflection/how-to-examine-and-instantiate-generic-types-with-reflection.md b/docs/fundamentals/reflection/how-to-examine-and-instantiate-generic-types-with-reflection.md index c8202be21ec8e..078e339f2ed91 100644 --- a/docs/fundamentals/reflection/how-to-examine-and-instantiate-generic-types-with-reflection.md +++ b/docs/fundamentals/reflection/how-to-examine-and-instantiate-generic-types-with-reflection.md @@ -59,7 +59,7 @@ You can create a object that represents a constructed type by ## Construct an instance of a generic type -A generic type is like a template. You cannot create instances of it unless you specify real types for its generic type parameters. To do this at run time, using reflection, requires the method. +A generic type is like a template. You cannot create instances of it unless you specify real types for its generic type parameters. To do this at runtime, using reflection, requires the method. 1. Get a object that represents the generic type. The following code gets the generic type in two different ways: by using the method overload with a string describing the type, and by calling the method on the constructed type `Dictionary\` (`Dictionary(Of String, Example)` in Visual Basic). The method requires a generic type definition. diff --git a/docs/fundamentals/reflection/how-to-hook-up-a-delegate-using-reflection.md b/docs/fundamentals/reflection/how-to-hook-up-a-delegate-using-reflection.md index 0b4616478458d..deb6a4c4e55e5 100644 --- a/docs/fundamentals/reflection/how-to-hook-up-a-delegate-using-reflection.md +++ b/docs/fundamentals/reflection/how-to-hook-up-a-delegate-using-reflection.md @@ -34,7 +34,7 @@ When you use reflection to load and run assemblies, you can't use language featu [!code-csharp[HookUpDelegate#5](../../../samples/snippets/csharp/VS_Snippets_CLR/HookUpDelegate/cs/source.cs#5)] [!code-vb[HookUpDelegate#5](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HookUpDelegate/vb/source.vb#5)] -4. Get a object representing the method that handles the event. The complete program code in the Example section later in this article contains a method that matches the signature of the delegate, which handles the event, but you can also generate dynamic methods at run time. For details, see the accompanying procedure, for generating an event handler at run time by using a dynamic method. +4. Get a object representing the method that handles the event. The complete program code in the Example section later in this article contains a method that matches the signature of the delegate, which handles the event, but you can also generate dynamic methods at runtime. For details, see the accompanying procedure, for generating an event handler at runtime by using a dynamic method. [!code-csharp[HookUpDelegate#6](../../../samples/snippets/csharp/VS_Snippets_CLR/HookUpDelegate/cs/source.cs#6)] [!code-vb[HookUpDelegate#6](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HookUpDelegate/vb/source.vb#6)] @@ -54,9 +54,9 @@ When you use reflection to load and run assemblies, you can't use language featu [!code-csharp[HookUpDelegate#12](../../../samples/snippets/csharp/VS_Snippets_CLR/HookUpDelegate/cs/source.cs#12)] [!code-vb[HookUpDelegate#12](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HookUpDelegate/vb/source.vb#12)] -## Generate an event handler at run time by using a dynamic method +## Generate an event handler at runtime by using a dynamic method -1. Event-handler methods can be generated at run time, using lightweight dynamic methods and reflection emit. To construct an event handler, you need the return type and parameter types of the delegate. These can be obtained by examining the delegate's `Invoke` method. The following code uses the `GetDelegateReturnType` and `GetDelegateParameterTypes` methods to obtain this information. The code for these methods can be found in the Example section later in this article. +1. Event-handler methods can be generated at runtime, using lightweight dynamic methods and reflection emit. To construct an event handler, you need the return type and parameter types of the delegate. These can be obtained by examining the delegate's `Invoke` method. The following code uses the `GetDelegateReturnType` and `GetDelegateParameterTypes` methods to obtain this information. The code for these methods can be found in the Example section later in this article. It is not necessary to name a , so the empty string can be used. In the following code, the last argument associates the dynamic method with the current type, giving the delegate access to all the public and private members of the `Example` class. @@ -80,7 +80,7 @@ When you use reflection to load and run assemblies, you can't use language featu ## Example -The following code example shows how to hook up an existing method to an event using reflection, and also how to use the class to emit a method at run time and hook it up to an event. +The following code example shows how to hook up an existing method to an event using reflection, and also how to use the class to emit a method at runtime and hook it up to an event. [!code-csharp[HookUpDelegate#1](../../../samples/snippets/csharp/VS_Snippets_CLR/HookUpDelegate/cs/source.cs#1)] [!code-vb[HookUpDelegate#1](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HookUpDelegate/vb/source.vb#1)] diff --git a/docs/fundamentals/reflection/reflection.md b/docs/fundamentals/reflection/reflection.md index 5310af8a21176..a0c728aac884f 100644 --- a/docs/fundamentals/reflection/reflection.md +++ b/docs/fundamentals/reflection/reflection.md @@ -20,14 +20,14 @@ helpviewer_keywords: - "PropertyInfo class, reflection" - "type browsers" - "reflection" - - "discovering type information at run time" + - "discovering type information at runtime" - "type system, reflection" ms.assetid: d1a58e7f-fb39-4d50-bf84-e3b8f9bf9775 --- # Reflection in .NET -The classes in the namespace, together with , enable you to obtain information about loaded [assemblies](../../standard/assembly/index.md) and the types defined within them, such as [classes](../../standard/base-types/common-type-system.md#classes), [interfaces](../../standard/base-types/common-type-system.md#interfaces), and value types (that is, [structures](../../standard/base-types/common-type-system.md#structures) and [enumerations](../../standard/base-types/common-type-system.md#enumerations)). You can also use reflection to create type instances at run time, and to invoke and access them. +The classes in the namespace, together with , enable you to obtain information about loaded [assemblies](../../standard/assembly/index.md) and the types defined within them, such as [classes](../../standard/base-types/common-type-system.md#classes), [interfaces](../../standard/base-types/common-type-system.md#interfaces), and value types (that is, [structures](../../standard/base-types/common-type-system.md#structures) and [enumerations](../../standard/base-types/common-type-system.md#enumerations)). You can also use reflection to create type instances at runtime, and to invoke and access them. [Assemblies](../../standard/assembly/index.md) contain modules, modules contain types, and types contain members. Reflection provides objects that encapsulate assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object. You can then invoke the type's methods or access its fields and properties. Typical uses of reflection include the following: @@ -41,7 +41,7 @@ The classes in the namespace, together with to discover information such as a parameter's name, data type, whether a parameter is an input or output parameter, and the position of the parameter in a method signature. - Use to discover information about custom attributes when you are working in the or reflection-only context (.NET Framework). allows you to examine attributes without creating instances of them. -The classes of the namespace provide a specialized form of reflection that enables you to build types at run time. +The classes of the namespace provide a specialized form of reflection that enables you to build types at runtime. Reflection can also be used to create *type browsers*, which enable users to select types and then view the information about those types. diff --git a/docs/fundamentals/runtime-libraries/includes/system-drawing-common.md b/docs/fundamentals/runtime-libraries/includes/system-drawing-common.md index 20e4d0f623247..40e5838c17578 100644 --- a/docs/fundamentals/runtime-libraries/includes/system-drawing-common.md +++ b/docs/fundamentals/runtime-libraries/includes/system-drawing-common.md @@ -1,2 +1,2 @@ > [!NOTE] -> In .NET 6 and later versions, the [System.Drawing.Common package](https://www.nuget.org/packages/System.Drawing.Common/), which includes this type, is only supported on Windows operating systems. Use of this type in cross-platform apps causes compile-time warnings and run-time exceptions. For more information, see [System.Drawing.Common only supported on Windows](../../../core/compatibility/core-libraries/6.0/system-drawing-common-windows-only.md). +> In .NET 6 and later versions, the [System.Drawing.Common package](https://www.nuget.org/packages/System.Drawing.Common/), which includes this type, is only supported on Windows operating systems. Use of this type in cross-platform apps causes compile-time warnings and runtime exceptions. For more information, see [System.Drawing.Common only supported on Windows](../../../core/compatibility/core-libraries/6.0/system-drawing-common-windows-only.md). diff --git a/docs/fundamentals/runtime-libraries/system-collections-generic-hashset{t}.md b/docs/fundamentals/runtime-libraries/system-collections-generic-hashset{t}.md index 76149f4af9faf..2959874215da6 100644 --- a/docs/fundamentals/runtime-libraries/system-collections-generic-hashset{t}.md +++ b/docs/fundamentals/runtime-libraries/system-collections-generic-hashset{t}.md @@ -29,7 +29,7 @@ A collection is not sorted and can In addition to the listed set operations, the class also provides methods for determining set equality, overlap of sets, and whether a set is a subset or superset of another set. -**.NET Framework only:** For very large objects, you can increase the maximum capacity to 2 billion elements on a 64-bit system by setting the `enabled` attribute of the [``](../../framework/configure-apps/file-schema/runtime/gcallowverylargeobjects-element.md) configuration element to `true` in the run-time environment. +**.NET Framework only:** For very large objects, you can increase the maximum capacity to 2 billion elements on a 64-bit system by setting the `enabled` attribute of the [``](../../framework/configure-apps/file-schema/runtime/gcallowverylargeobjects-element.md) configuration element to `true` in the runtime environment. The class implements the interface. diff --git a/docs/fundamentals/runtime-libraries/system-collections-generic-list{t}.md b/docs/fundamentals/runtime-libraries/system-collections-generic-list{t}.md index 78d7bd44ce29c..14ae005daa7dc 100644 --- a/docs/fundamentals/runtime-libraries/system-collections-generic-list{t}.md +++ b/docs/fundamentals/runtime-libraries/system-collections-generic-list{t}.md @@ -25,7 +25,7 @@ The is not guaranteed to be sorted. Y Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based. -**.NET Framework only:** For very large objects, you can increase the maximum capacity to 2 billion elements on a 64-bit system by setting the `enabled` attribute of the [``](../../framework/configure-apps/file-schema/runtime/gcallowverylargeobjects-element.md) configuration element to `true` in the run-time environment. +**.NET Framework only:** For very large objects, you can increase the maximum capacity to 2 billion elements on a 64-bit system by setting the `enabled` attribute of the [``](../../framework/configure-apps/file-schema/runtime/gcallowverylargeobjects-element.md) configuration element to `true` in the runtime environment. accepts `null` as a valid value for reference types and allows duplicate elements. diff --git a/docs/fundamentals/runtime-libraries/system-convert.md b/docs/fundamentals/runtime-libraries/system-convert.md index 5d81a8614aa8b..4ea587fce0649 100644 --- a/docs/fundamentals/runtime-libraries/system-convert.md +++ b/docs/fundamentals/runtime-libraries/system-convert.md @@ -15,7 +15,7 @@ The static class contains methods that are primarily used ## Conversions to and from base types -A conversion method exists to convert every base type to every other base type. However, the actual call to a particular conversion method can produce one of five outcomes, depending on the value of the base type at run time and the target base type. These five outcomes are: +A conversion method exists to convert every base type to every other base type. However, the actual call to a particular conversion method can produce one of five outcomes, depending on the value of the base type at runtime and the target base type. These five outcomes are: - No conversion. This occurs when an attempt is made to convert from a type to itself (for example, by calling with an argument of type ). In this case, the method simply returns an instance of the original type. @@ -82,9 +82,9 @@ All the base type conversion methods and the The parameter can supply culture-specific formatting information to assist the conversion process. However, it is ignored by most of the base type conversion methods. It is used only by the following base type conversion methods. If a `null` argument is passed to these methods, the object that represents the current culture is used. -- By methods that convert a value to a numeric type. The parameter is used by the overload that has parameters of type and . It is also used by the overload that has parameters of type and if the object's run-time type is a . +- By methods that convert a value to a numeric type. The parameter is used by the overload that has parameters of type and . It is also used by the overload that has parameters of type and if the object's runtime type is a . -- By methods that convert a value to a date and time. The parameter is used by the overload that has parameters of type and . It is also used by the overload that has parameters of type and if the object's run-time type is a . +- By methods that convert a value to a date and time. The parameter is used by the overload that has parameters of type and . It is also used by the overload that has parameters of type and if the object's runtime type is a . - By the overloads that include an parameter and that convert either a numeric value to a string or a value to a string. diff --git a/docs/fundamentals/runtime-libraries/system-diagnostics-tracing-eventsource.md b/docs/fundamentals/runtime-libraries/system-diagnostics-tracing-eventsource.md index f4ad9cbd73c41..f5fa7671c8c6d 100644 --- a/docs/fundamentals/runtime-libraries/system-diagnostics-tracing-eventsource.md +++ b/docs/fundamentals/runtime-libraries/system-diagnostics-tracing-eventsource.md @@ -59,7 +59,7 @@ Traditionally, user-defined object > Abstract objects cannot define keywords, tasks, opcodes, channels, or events. > [!IMPORTANT] -> To avoid name collisions at run time when generating event metadata, don't explicitly implement interface methods when using interfaces with . +> To avoid name collisions at runtime when generating event metadata, don't explicitly implement interface methods when using interfaces with . The following example shows an implementation of that uses an interface. diff --git a/docs/fundamentals/runtime-libraries/system-dynamic-expandoobject.md b/docs/fundamentals/runtime-libraries/system-dynamic-expandoobject.md index fd0e86325ac74..6f1c543471a35 100644 --- a/docs/fundamentals/runtime-libraries/system-dynamic-expandoobject.md +++ b/docs/fundamentals/runtime-libraries/system-dynamic-expandoobject.md @@ -10,7 +10,7 @@ dev_langs: [!INCLUDE [context](includes/context.md)] -The class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like `sampleObject.sampleMember` instead of more complex syntax like `sampleObject.GetAttribute("sampleMember")`. +The class enables you to add and delete members of its instances at runtime and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like `sampleObject.sampleMember` instead of more complex syntax like `sampleObject.GetAttribute("sampleMember")`. The `ExpandoObject` class implements the standard Dynamic Language Runtime (DLR) interface , which enables you to share instances of the `ExpandoObject` class between languages that support the DLR interoperability model. For example, you can create an instance of the `ExpandoObject` class in C# and then pass it to an IronPython function. For more information, see [Dynamic Language Runtime Overview](../../framework/reflection-and-codedom/dynamic-language-runtime-overview.md) and [Introducing the ExpandoObject](/archive/blogs/csharpfaq/dynamic-in-c-4-0-introducing-the-expandoobject). @@ -111,7 +111,7 @@ The following code example demonstrates how you can create and use a method to p ## Enumerate and delete members -The `ExpandoObject` class implements the `IDictionary` interface. This enables enumeration of members added to the instance of the `ExpandoObject` class at run time. This can be useful if you do not know at compile time what members an instance might have. +The `ExpandoObject` class implements the `IDictionary` interface. This enables enumeration of members added to the instance of the `ExpandoObject` class at runtime. This can be useful if you do not know at compile time what members an instance might have. The following code example shows how you can cast an instance of the `ExpandoObject` class to the interface and enumerate the instance's members. diff --git a/docs/fundamentals/runtime-libraries/system-exception.md b/docs/fundamentals/runtime-libraries/system-exception.md index 5214b72a607e6..8883852349e70 100644 --- a/docs/fundamentals/runtime-libraries/system-exception.md +++ b/docs/fundamentals/runtime-libraries/system-exception.md @@ -15,7 +15,7 @@ The class is the base class for all exceptions. When an ## Errors and exceptions -Run-time errors can occur for a variety of reasons. However, not all errors should be handled as exceptions in your code. Here are some categories of errors that can occur at run time and the appropriate ways to respond to them. +Runtime errors can occur for a variety of reasons. However, not all errors should be handled as exceptions in your code. Here are some categories of errors that can occur at runtime and the appropriate ways to respond to them. - **Usage errors.** A usage error represents an error in program logic that can result in an exception. However, the error should be addressed not through exception handling but by modifying the faulty code. For example, the override of the method in the following example assumes that the `obj` argument must always be non-null. @@ -31,13 +31,13 @@ Run-time errors can occur for a variety of reasons. However, not all errors shou Instead of using exception handling for usage errors, you can use the method to identify usage errors in debug builds, and the method to identify usage errors in both debug and release builds. For more information, see [Assertions in Managed Code](/visualstudio/debugger/assertions-in-managed-code). -- **Program errors.** A program error is a run-time error that cannot necessarily be avoided by writing bug-free code. +- **Program errors.** A program error is a runtime error that cannot necessarily be avoided by writing bug-free code. In some cases, a program error may reflect an expected or routine error condition. In this case, you may want to avoid using exception handling to deal with the program error and instead retry the operation. For example, if the user is expected to input a date in a particular format, you can parse the date string by calling the method, which returns a value that indicates whether the parse operation succeeded, instead of using the method, which throws a exception if the date string cannot be converted to a value. Similarly, if a user tries to open a file that does not exist, you can first call the method to check whether the file exists and, if it does not, prompt the user whether they want to create it. In other cases, a program error reflects an unexpected error condition that can be handled in your code. For example, even if you've checked to ensure that a file exists, it may be deleted before you can open it, or it may be corrupted. In that case, trying to open the file by instantiating a object or calling the method may throw a exception. In these cases, you should use exception handling to recover from the error. -- **System failures.** A system failure is a run-time error that cannot be handled programmatically in a meaningful way. For example, any method can throw an exception if the common language runtime is unable to allocate additional memory. Ordinarily, system failures are not handled by using exception handling. Instead, you may be able to use an event such as and call the method to log exception information and notify the user of the failure before the application terminates. +- **System failures.** A system failure is a runtime error that cannot be handled programmatically in a meaningful way. For example, any method can throw an exception if the common language runtime is unable to allocate additional memory. Ordinarily, system failures are not handled by using exception handling. Instead, you may be able to use an event such as and call the method to log exception information and notify the user of the failure before the application terminates. ## Try/catch blocks diff --git a/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo.md b/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo.md index 8ff3fdd3a3fba..2f97b68973eb1 100644 --- a/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo.md +++ b/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo.md @@ -80,14 +80,14 @@ Some `CultureInfo` objects differ depending on the underlying platform. In parti ## Dynamic culture data -Except for the invariant culture, culture data is dynamic. This is true even for the predefined cultures. For example, countries or regions adopt new currencies, change their spellings of words, or change their preferred calendar, and culture definitions change to track this. Custom cultures are subject to change without notice, and any specific culture might be overridden by a custom replacement culture. Also, as discussed below, an individual user can override cultural preferences. Applications should always obtain culture data at run time. +Except for the invariant culture, culture data is dynamic. This is true even for the predefined cultures. For example, countries or regions adopt new currencies, change their spellings of words, or change their preferred calendar, and culture definitions change to track this. Custom cultures are subject to change without notice, and any specific culture might be overridden by a custom replacement culture. Also, as discussed below, an individual user can override cultural preferences. Applications should always obtain culture data at runtime. > [!CAUTION] > When saving data, your application should use the invariant culture, a binary format, or a specific culture-independent format. Data saved according to the current values associated with a particular culture, other than the invariant culture, might become unreadable or might change in meaning if that culture changes. ## The current culture and current UI culture -Every thread in a .NET application has a current culture and a current UI culture. The current culture determines the formatting conventions for dates, times, numbers, and currency values, the sort order of text, casing conventions, and the ways in which strings are compared. The current UI culture is used to retrieve culture-specific resources at run time. +Every thread in a .NET application has a current culture and a current UI culture. The current culture determines the formatting conventions for dates, times, numbers, and currency values, the sort order of text, casing conventions, and the ways in which strings are compared. The current UI culture is used to retrieve culture-specific resources at runtime. > [!NOTE] > For information on how the current and current UI culture is determined on a per-thread basis, see the [Culture and threads](#culture-and-threads) section. For information on how the current and current UI culture is determined on threads executing in a new application domain, and on threads that cross application domain boundaries, see the [Culture and application domains](#culture-and-application-domains) section. For information on how the current and current UI culture is determined on threads performing task-based asynchronous operations, see the [Culture and task-based asynchronous operations](#culture-and-task-based-asynchronous-operations) section. diff --git a/docs/fundamentals/runtime-libraries/system-globalization-datetimeformatinfo.md b/docs/fundamentals/runtime-libraries/system-globalization-datetimeformatinfo.md index 1b874c35ee4e6..007b44ba7e4ae 100644 --- a/docs/fundamentals/runtime-libraries/system-globalization-datetimeformatinfo.md +++ b/docs/fundamentals/runtime-libraries/system-globalization-datetimeformatinfo.md @@ -97,7 +97,7 @@ The culture-specific data for formatting date and time values provided by the class can be used to replace the data of an existing culture. -- Cascading changes to property values. A number of culture-related properties can change at run time, which, in turn, causes data to change. For example, the current culture can be changed either programmatically or through user action. When this happens, the object returned by the property changes to an object associated with the current culture. Similarly, a culture's calendar can change, which can result in changes to numerous property values. +- Cascading changes to property values. A number of culture-related properties can change at runtime, which, in turn, causes data to change. For example, the current culture can be changed either programmatically or through user action. When this happens, the object returned by the property changes to an object associated with the current culture. Similarly, a culture's calendar can change, which can result in changes to numerous property values. - User preferences. Users of your application might choose to override some of the values associated with the current system culture through the regional and language options in Control Panel. For example, users might choose to display the date in a different format. If the property is set to `true`, the properties of the object is also retrieved from the user settings. If the user settings are incompatible with the culture associated with the object (for example, if the selected calendar is not one of the calendars indicated by the property), the results of the methods and the values of the properties are undefined. diff --git a/docs/fundamentals/runtime-libraries/system-globalization-numberformatinfo.md b/docs/fundamentals/runtime-libraries/system-globalization-numberformatinfo.md index da4bacbe3efc7..ad3b49c7a7e30 100644 --- a/docs/fundamentals/runtime-libraries/system-globalization-numberformatinfo.md +++ b/docs/fundamentals/runtime-libraries/system-globalization-numberformatinfo.md @@ -94,7 +94,7 @@ The culture-specific data for formatting numeric values provided by the class can be used to replace the data of an existing culture. -- **Cascading changes to property values.** A number of culture-related properties can change at run time, which, in turn, causes data to change. For example, the current culture can be changed either programmatically or through user action. When this happens, the object returned by the property changes to an object associated with the current culture. +- **Cascading changes to property values.** A number of culture-related properties can change at runtime, which, in turn, causes data to change. For example, the current culture can be changed either programmatically or through user action. When this happens, the object returned by the property changes to an object associated with the current culture. - **User preferences.** Users of your application might override some of the values associated with the current system culture through the region and language options in Control Panel. For example, users might choose a different currency symbol or a different decimal separator symbol. If the property is set to `true` (its default value), the properties of the object are also retrieved from the user settings. diff --git a/docs/fundamentals/runtime-libraries/system-object-equals.md b/docs/fundamentals/runtime-libraries/system-object-equals.md index 88fe371f66256..c39b154fb3709 100644 --- a/docs/fundamentals/runtime-libraries/system-object-equals.md +++ b/docs/fundamentals/runtime-libraries/system-object-equals.md @@ -23,7 +23,7 @@ The type of comparison between the current instance and the `obj` parameter depe - If the current instance is a value type, the method tests for value equality. Value equality means the following: - - The two objects are of the same type. As the following example shows, a object that has a value of 12 does not equal an object that has a value of 12, because the two objects have different run-time types. + - The two objects are of the same type. As the following example shows, a object that has a value of 12 does not equal an object that has a value of 12, because the two objects have different runtime types. :::code language="csharp" source="./snippets/System/Object/Equals/csharp/equals_val1.cs" interactive="try-dotnet-method" id="Snippet3"::: :::code language="fsharp" source="./snippets/System/Object/Equals/fsharp/equals_val1.fs" id="Snippet3"::: @@ -136,7 +136,7 @@ The following example shows a `Point` class that overrides the method to determine whether the run-time types of the two objects are identical. If the method used a check of the form `obj is Point` in C# or `TryCast(obj, Point)` in Visual Basic, the check would return `true` in cases where `obj` is an instance of a derived class of `Point`, even though `obj` and the current instance are not of the same run-time type. Having verified that both objects are of the same type, the method casts `obj` to type `Point` and returns the result of comparing the instance fields of the two objects. +The `Point.Equals` method calls the method to determine whether the runtime types of the two objects are identical. If the method used a check of the form `obj is Point` in C# or `TryCast(obj, Point)` in Visual Basic, the check would return `true` in cases where `obj` is an instance of a derived class of `Point`, even though `obj` and the current instance are not of the same runtime type. Having verified that both objects are of the same type, the method casts `obj` to type `Point` and returns the result of comparing the instance fields of the two objects. In `Point3D.Equals`, the inherited `Point.Equals` method, which overrides , is invoked before anything else is done. Because `Point3D` is a sealed class (`NotInheritable` in Visual Basic), a check in the form `obj is Point` in C# or `TryCast(obj, Point)` in Visual Basic is adequate to ensure that `obj` is a `Point3D` object. If it is a `Point3D` object, it is cast to a `Point` object and passed to the base class implementation of . Only when the inherited `Point.Equals` method returns `true` does the method compare the `z` instance fields introduced in the derived class. @@ -152,4 +152,4 @@ Some languages such as C# and Visual Basic support operator overloading. When a :::code language="fsharp" source="./snippets/System/Object/Equals/fsharp/equals4.fs" id="Snippet1"::: :::code language="vb" source="./snippets/System/Object/Equals/vb/equals4.vb" id="Snippet1"::: -Because `Complex` is a value type, it cannot be derived from. Therefore, the override to method need not call to determine the precise run-time type of each object, but can instead use the `is` operator in C# or the `TypeOf` operator in Visual Basic to check the type of the `obj` parameter. +Because `Complex` is a value type, it cannot be derived from. Therefore, the override to method need not call to determine the precise runtime type of each object, but can instead use the `is` operator in C# or the `TypeOf` operator in Visual Basic to check the type of the `obj` parameter. diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod.md index b95e7c26a7e0f..a8a052f0a7c06 100644 --- a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod.md +++ b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod.md @@ -7,7 +7,7 @@ ms.date: 12/31/2023 [!INCLUDE [context](includes/context.md)] -You can use the class to generate and execute a method at run time, without having to generate a dynamic assembly and a dynamic type to contain the method. The executable code created by the just-in-time (JIT) compiler is reclaimed when the object is reclaimed. Dynamic methods are the most efficient way to generate and execute small amounts of code. +You can use the class to generate and execute a method at runtime, without having to generate a dynamic assembly and a dynamic type to contain the method. The executable code created by the just-in-time (JIT) compiler is reclaimed when the object is reclaimed. Dynamic methods are the most efficient way to generate and execute small amounts of code. A dynamic method can be anonymously hosted, or it can be logically associated with a module or with a type. diff --git a/docs/fundamentals/runtime-libraries/system-string-format.md b/docs/fundamentals/runtime-libraries/system-string-format.md index 9cfae849a28bb..8e863946de294 100644 --- a/docs/fundamentals/runtime-libraries/system-string-format.md +++ b/docs/fundamentals/runtime-libraries/system-string-format.md @@ -119,7 +119,7 @@ The following example is similar to the previous one, except that it left-aligns ## The Format method in brief -Each overload of the method uses the [composite formatting feature](../../standard/base-types/composite-formatting.md) to include zero-based indexed placeholders, called *format items*, in a composite format string. At run time, each format item is replaced with the string representation of the corresponding argument in a parameter list. If the value of the argument is `null`, the format item is replaced with . For example, the following call to the method includes a format string with three format items, {0}, {1}, and {2}, and an argument list with three items. +Each overload of the method uses the [composite formatting feature](../../standard/base-types/composite-formatting.md) to include zero-based indexed placeholders, called *format items*, in a composite format string. At runtime, each format item is replaced with the string representation of the corresponding argument in a parameter list. If the value of the argument is `null`, the format item is replaced with . For example, the following call to the method includes a format string with three format items, {0}, {1}, and {2}, and an argument list with three items. :::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/formatoverload1.cs" id="Snippet8"::: :::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/formatoverload1.fs" id="Snippet8"::: diff --git a/docs/fundamentals/runtime-libraries/system-string-intern.md b/docs/fundamentals/runtime-libraries/system-string-intern.md index a8c3aba960ec8..6ee271a92ca48 100644 --- a/docs/fundamentals/runtime-libraries/system-string-intern.md +++ b/docs/fundamentals/runtime-libraries/system-string-intern.md @@ -25,4 +25,4 @@ In the following example, the string `s1`, which has a value of "MyTest", is alr If you're trying to reduce the total amount of memory your application allocates, keep in mind that interning a string has two unwanted side effects. First, the memory allocated for interned objects is not likely to be released until the common language runtime (CLR) terminates. The reason is that the CLR's reference to the interned object can persist after your application, or even your application domain, terminates. Second, to intern a string, you must first create the string. The memory used by the object must still be allocated, even though the memory will eventually be garbage collected. -The enumeration member marks an assembly as not requiring string-literal interning. You can apply to an assembly using the attribute. Also, when you use [Ngen.exe (Native Image Generator)](../../framework/tools/ngen-exe-native-image-generator.md) to compile an assembly in advance of run time, strings are not interned across modules. +The enumeration member marks an assembly as not requiring string-literal interning. You can apply to an assembly using the attribute. Also, when you use [Ngen.exe (Native Image Generator)](../../framework/tools/ngen-exe-native-image-generator.md) to compile an assembly in advance of runtime, strings are not interned across modules. diff --git a/docs/fundamentals/runtime-libraries/system-type-makegenerictype.md b/docs/fundamentals/runtime-libraries/system-type-makegenerictype.md index 005e23cf3b7e1..46070208a5d9e 100644 --- a/docs/fundamentals/runtime-libraries/system-type-makegenerictype.md +++ b/docs/fundamentals/runtime-libraries/system-type-makegenerictype.md @@ -11,7 +11,7 @@ dev_langs: [!INCLUDE [context](includes/context.md)] -The method allows you to write code that assigns specific types to the type parameters of a generic type definition, thus creating a object that represents a particular constructed type. You can use this object to create run-time instances of the constructed type. +The method allows you to write code that assigns specific types to the type parameters of a generic type definition, thus creating a object that represents a particular constructed type. You can use this object to create runtime instances of the constructed type. Types constructed with can be open, that is, some of their type arguments can be type parameters of enclosing generic methods or types. You might use such open constructed types when you emit dynamic assemblies. For example, consider the classes `Base` and `Derived` in the following code. diff --git a/docs/fundamentals/runtime-libraries/system-xml-serialization-xmlserializer.md b/docs/fundamentals/runtime-libraries/system-xml-serialization-xmlserializer.md index 76bcd7fdd1c62..e35ec642b9968 100644 --- a/docs/fundamentals/runtime-libraries/system-xml-serialization-xmlserializer.md +++ b/docs/fundamentals/runtime-libraries/system-xml-serialization-xmlserializer.md @@ -192,7 +192,7 @@ public enum LargeNumbers: ulong { a = 9223372036854775808 } -// At run time, the following code will fail. +// At runtime, the following code will fail. xmlSerializer mySerializer=new XmlSerializer(typeof(LargeNumbers)); ``` diff --git a/docs/fundamentals/syslib-diagnostics/source-generator-overview.md b/docs/fundamentals/syslib-diagnostics/source-generator-overview.md index 18794f73ea496..24e8af539afe9 100644 --- a/docs/fundamentals/syslib-diagnostics/source-generator-overview.md +++ b/docs/fundamentals/syslib-diagnostics/source-generator-overview.md @@ -118,7 +118,7 @@ The following table provides an index to the `SYSLIB1XXX` diagnostics in .NET 6 | [SYSLIB1096][1096] | Use `GeneratedComInterfaceAttribute` instead of `ComImportAttribute` to generate COM marshalling code at compile time. | | [SYSLIB1097][1097] | This type implements at least one type with the `GeneratedComInterfaceAttribute` attribute. Add the `GeneratedComClassAttribute` to enable passing this type to COM and exposing the COM interfaces for the types with the `GeneratedComInterfaceAttribute` from objects of this type. | | [SYSLIB1098][1098] | .NET COM hosting with `EnableComHosting` only supports built-in COM interop. It does not support source-generated COM interop with `GeneratedComInterfaceAttribute`. | -| [SYSLIB1099][1099] | COM Interop APIs on `System.Runtime.InteropServices.Marshal` do not support source-generated COM and will fail at run time. | +| [SYSLIB1099][1099] | COM Interop APIs on `System.Runtime.InteropServices.Marshal` do not support source-generated COM and will fail at runtime. | | [SYSLIB1100][1100] | Configuration binding generator: Type is not supported. | | [SYSLIB1101][1101] | Configuration binding generator: Property on type is not supported. | | [SYSLIB1102][1102] | Configuration binding generator: Project's language version must be at least C# 12. | diff --git a/docs/fundamentals/syslib-diagnostics/syslib-cominterfacegenerator.md b/docs/fundamentals/syslib-diagnostics/syslib-cominterfacegenerator.md index 81ab4924dc239..6e53159e5face 100644 --- a/docs/fundamentals/syslib-diagnostics/syslib-cominterfacegenerator.md +++ b/docs/fundamentals/syslib-diagnostics/syslib-cominterfacegenerator.md @@ -29,5 +29,5 @@ The following table shows the diagnostic IDs for COM interop source-generation a | `SYSLIB1096` | Use `GeneratedComInterfaceAttribute` instead of `ComImportAttribute` to generate COM marshalling code at compile time. | | `SYSLIB1097` | This type implements at least one type with the `GeneratedComInterfaceAttribute` attribute. Add the `GeneratedComClassAttribute` to enable passing this type to COM and exposing the COM interfaces for the types with the `GeneratedComInterfaceAttribute` from objects of this type. | | `SYSLIB1098` | .NET COM hosting with `EnableComHosting` only supports built-in COM interop. It does not support source-generated COM interop with `GeneratedComInterfaceAttribute`. | -| `SYSLIB1099` | COM Interop APIs on `System.Runtime.InteropServices.Marshal` do not support source-generated COM and will fail at run time. | +| `SYSLIB1099` | COM Interop APIs on `System.Runtime.InteropServices.Marshal` do not support source-generated COM and will fail at runtime. | | [`SYSLIB1230`](syslib1230.md) | Deriving from a `GeneratedComInterface`-attributed interface defined in another assembly is not supported. | diff --git a/docs/fundamentals/syslib-diagnostics/syslib0003.md b/docs/fundamentals/syslib-diagnostics/syslib0003.md index 6177f58b1745b..3bc860fda406c 100644 --- a/docs/fundamentals/syslib-diagnostics/syslib0003.md +++ b/docs/fundamentals/syslib-diagnostics/syslib0003.md @@ -192,7 +192,7 @@ The complete list of obsolete CAS APIs is as follows: } ``` -- If you're demanding any permission (except ), remove the demand. All demands will succeed at run time. +- If you're demanding any permission (except ), remove the demand. All demands will succeed at runtime. ```csharp // REMOVE the attribute below; it will always succeed. diff --git a/docs/fundamentals/syslib-diagnostics/syslib0005.md b/docs/fundamentals/syslib-diagnostics/syslib0005.md index 0524c25113c50..8db9ddd9f1f16 100644 --- a/docs/fundamentals/syslib-diagnostics/syslib0005.md +++ b/docs/fundamentals/syslib-diagnostics/syslib0005.md @@ -13,11 +13,11 @@ The following GAC-related APIs are marked obsolete: - - Libraries and apps should not use the API to make determinations about run-time behavior, as it always returns `false` in .NET Core and .NET 5+. + Libraries and apps should not use the API to make determinations about runtime behavior, as it always returns `false` in .NET Core and .NET 5+. ## Workarounds -If your application queries the property, consider removing the call. If you use the value to choose between an "assembly in the GAC"-flow vs. an "assembly not in the GAC"-flow at run time, reconsider whether the flow still makes sense for a .NET 5+ application. +If your application queries the property, consider removing the call. If you use the value to choose between an "assembly in the GAC"-flow vs. an "assembly not in the GAC"-flow at runtime, reconsider whether the flow still makes sense for a .NET 5+ application. ## Suppress a warning diff --git a/docs/fundamentals/syslib-diagnostics/syslib0006.md b/docs/fundamentals/syslib-diagnostics/syslib0006.md index fb53cfc184546..0d3fff4512735 100644 --- a/docs/fundamentals/syslib-diagnostics/syslib0006.md +++ b/docs/fundamentals/syslib-diagnostics/syslib0006.md @@ -7,7 +7,7 @@ f1_keywords: --- # SYSLIB0006: Thread.Abort is not supported -The following APIs are marked obsolete, starting in .NET 5. Use of these APIs generates warning `SYSLIB0006` at compile time and a at run time. +The following APIs are marked obsolete, starting in .NET 5. Use of these APIs generates warning `SYSLIB0006` at compile time and a at runtime. - - diff --git a/docs/fundamentals/syslib-diagnostics/syslib0007.md b/docs/fundamentals/syslib-diagnostics/syslib0007.md index c726653339839..6032a917f264d 100644 --- a/docs/fundamentals/syslib-diagnostics/syslib0007.md +++ b/docs/fundamentals/syslib-diagnostics/syslib0007.md @@ -7,7 +7,7 @@ f1_keywords: --- # SYSLIB0007: Default implementations of cryptography algorithms not supported -The cryptographic configuration system in .NET Framework doesn't allow for proper cryptographic agility and isn't present in .NET Core and .NET 5+. .NET's backward-compatibility requirements also prohibit the framework from updating certain cryptographic APIs to keep up with advances in cryptography. As a result, the following APIs are marked obsolete, starting in .NET 5. Use of these APIs generates warning `SYSLIB0007` at compile time and a at run time. +The cryptographic configuration system in .NET Framework doesn't allow for proper cryptographic agility and isn't present in .NET Core and .NET 5+. .NET's backward-compatibility requirements also prohibit the framework from updating certain cryptographic APIs to keep up with advances in cryptography. As a result, the following APIs are marked obsolete, starting in .NET 5. Use of these APIs generates warning `SYSLIB0007` at compile time and a at runtime. - - diff --git a/docs/fundamentals/syslib-diagnostics/syslib0008.md b/docs/fundamentals/syslib-diagnostics/syslib0008.md index 19a5cbc69b800..ea74ed38fbd47 100644 --- a/docs/fundamentals/syslib-diagnostics/syslib0008.md +++ b/docs/fundamentals/syslib-diagnostics/syslib0008.md @@ -7,7 +7,7 @@ f1_keywords: --- # SYSLIB0008: CreatePdbGenerator is not supported -The API is marked obsolete, starting in .NET 5. Using this API generates warning `SYSLIB0008` at compile time and throws a at run time. +The API is marked obsolete, starting in .NET 5. Using this API generates warning `SYSLIB0008` at compile time and throws a at runtime. ## Suppress a warning diff --git a/docs/fundamentals/syslib-diagnostics/syslib0009.md b/docs/fundamentals/syslib-diagnostics/syslib0009.md index f1358b59d15da..3e0c6f408a8ca 100644 --- a/docs/fundamentals/syslib-diagnostics/syslib0009.md +++ b/docs/fundamentals/syslib-diagnostics/syslib0009.md @@ -8,13 +8,13 @@ f1_keywords: # SYSLIB0009: AuthenticationManager is not supported -The following APIs are marked obsolete, starting in .NET 5. Use of these APIs generates warning `SYSLIB0009` at compile time and throws a at run time. +The following APIs are marked obsolete, starting in .NET 5. Use of these APIs generates warning `SYSLIB0009` at compile time and throws a at runtime. - - In .NET 9 and later versions, the entire class is marked obsolete. Use of this class generates warning `SYSLIB0009` at compile time. -The methods in this class either no-op or throw a at run time. +The methods in this class either no-op or throw a at runtime. ## Workarounds diff --git a/docs/fundamentals/syslib-diagnostics/syslib0010.md b/docs/fundamentals/syslib-diagnostics/syslib0010.md index 3d0b45e683bb0..bae71cbe0da5b 100644 --- a/docs/fundamentals/syslib-diagnostics/syslib0010.md +++ b/docs/fundamentals/syslib-diagnostics/syslib0010.md @@ -7,7 +7,7 @@ f1_keywords: --- # SYSLIB0010: Unsupported remoting APIs -[.NET remoting](/previous-versions/dotnet/netframework-1.1/kwdt6w2k(v=vs.71)) is a legacy technology, and the infrastructure exists only in .NET Framework. The following remoting-related APIs are marked as obsolete, starting in .NET 5. Using them in code generates warning `SYSLIB0010` at compile time and throws a at run time. +[.NET remoting](/previous-versions/dotnet/netframework-1.1/kwdt6w2k(v=vs.71)) is a legacy technology, and the infrastructure exists only in .NET Framework. The following remoting-related APIs are marked as obsolete, starting in .NET 5. Using them in code generates warning `SYSLIB0010` at compile time and throws a at runtime. - - diff --git a/docs/fundamentals/syslib-diagnostics/syslib0011.md b/docs/fundamentals/syslib-diagnostics/syslib0011.md index b92b4d6ca25be..e23597d286efd 100644 --- a/docs/fundamentals/syslib-diagnostics/syslib0011.md +++ b/docs/fundamentals/syslib-diagnostics/syslib0011.md @@ -17,7 +17,7 @@ Due to [security vulnerabilities](../../standard/serialization/binaryformatter-s - - -Starting in .NET 8, and throw a at run time on most project types. In addition, is obsolete *as warning*, and the following APIs are obsolete *as error*: +Starting in .NET 8, and throw a at runtime on most project types. In addition, is obsolete *as warning*, and the following APIs are obsolete *as error*: - - diff --git a/docs/fundamentals/syslib-diagnostics/syslib0017.md b/docs/fundamentals/syslib-diagnostics/syslib0017.md index f4139a2c1df6e..82b44926cff8b 100644 --- a/docs/fundamentals/syslib-diagnostics/syslib0017.md +++ b/docs/fundamentals/syslib-diagnostics/syslib0017.md @@ -7,7 +7,7 @@ f1_keywords: --- # SYSLIB0017: Strong-name signing is not supported and throws PlatformNotSupportedException -The following APIS are marked as obsolete, starting in .NET 6. Using them in code generates warning `SYSLIB0017` at compile time. These APIs throw a at run time. +The following APIS are marked as obsolete, starting in .NET 6. Using them in code generates warning `SYSLIB0017` at compile time. These APIs throw a at runtime. - - diff --git a/docs/fundamentals/syslib-diagnostics/syslib0018.md b/docs/fundamentals/syslib-diagnostics/syslib0018.md index df01f7858909f..a6e5b6a1e227c 100644 --- a/docs/fundamentals/syslib-diagnostics/syslib0018.md +++ b/docs/fundamentals/syslib-diagnostics/syslib0018.md @@ -7,7 +7,7 @@ f1_keywords: --- # SYSLIB0018: Reflection-only loading is not supported and throws PlatformNotSupportedException -The following methods are marked as obsolete, starting in .NET 6. Calling them in code generates warning `SYSLIB0018` at compile time. These methods throw a at run time. +The following methods are marked as obsolete, starting in .NET 6. Calling them in code generates warning `SYSLIB0018` at compile time. These methods throw a at runtime. - - diff --git a/docs/fundamentals/syslib-diagnostics/syslib0019.md b/docs/fundamentals/syslib-diagnostics/syslib0019.md index 6aa483b402163..725055e86bc57 100644 --- a/docs/fundamentals/syslib-diagnostics/syslib0019.md +++ b/docs/fundamentals/syslib-diagnostics/syslib0019.md @@ -13,7 +13,7 @@ The following APIs are marked as obsolete, starting in .NET 6. Using them in cod - method - method -These APIs always throw a at run time. +These APIs always throw a at runtime. ## Workarounds diff --git a/docs/fundamentals/syslib-diagnostics/syslib0024.md b/docs/fundamentals/syslib-diagnostics/syslib0024.md index 6ea977df3b603..85bda57f7c5f3 100644 --- a/docs/fundamentals/syslib-diagnostics/syslib0024.md +++ b/docs/fundamentals/syslib-diagnostics/syslib0024.md @@ -7,7 +7,7 @@ f1_keywords: --- # SYSLIB0024: Creating and unloading AppDomains is not supported and throws an exception -The and methods are marked as obsolete, starting in .NET 6. Using them in code generates warning `SYSLIB0024` at compile time and throws an exception at run time. +The and methods are marked as obsolete, starting in .NET 6. Using them in code generates warning `SYSLIB0024` at compile time and throws an exception at runtime. ## Workarounds diff --git a/docs/fundamentals/syslib-diagnostics/syslib0031.md b/docs/fundamentals/syslib-diagnostics/syslib0031.md index d0e3c1b6c4446..8b3054bd418a1 100644 --- a/docs/fundamentals/syslib-diagnostics/syslib0031.md +++ b/docs/fundamentals/syslib-diagnostics/syslib0031.md @@ -7,7 +7,7 @@ f1_keywords: --- # SYSLIB0031: EncodeOID is obsolete -The method is marked as obsolete, starting in .NET 6. Using this API in code generates warning `SYSLIB0031` at compile time and throws a exception at run time. +The method is marked as obsolete, starting in .NET 6. Using this API in code generates warning `SYSLIB0031` at compile time and throws a exception at runtime. ## Workarounds diff --git a/docs/fundamentals/syslib-diagnostics/syslib0056.md b/docs/fundamentals/syslib-diagnostics/syslib0056.md index 81e2510b6a789..b682a4620dcf2 100644 --- a/docs/fundamentals/syslib-diagnostics/syslib0056.md +++ b/docs/fundamentals/syslib-diagnostics/syslib0056.md @@ -11,7 +11,7 @@ The overload of unconditionally throws a . This is a poor development experience. The overload looks like a valid API until it's used, and it throws at run time. Marking it as obsolete gives the necessary design-time signal to not use it. + unconditionally throws a . This is a poor development experience. The overload looks like a valid API until it's used, and it throws at runtime. Marking it as obsolete gives the necessary design-time signal to not use it. ## Workaround diff --git a/docs/fundamentals/syslib-diagnostics/syslib0062.md b/docs/fundamentals/syslib-diagnostics/syslib0062.md index cd86fc86946bc..1552b97b85cca 100644 --- a/docs/fundamentals/syslib-diagnostics/syslib0062.md +++ b/docs/fundamentals/syslib-diagnostics/syslib0062.md @@ -11,7 +11,7 @@ Starting in .NET 10, the was thrown at run time. This obsoletion turns a run-time error into a build warning, which provides better guidance for migration. +XSLT script blocks aren't supported on .NET (Core). Previously, if you set the property to `true`, a was thrown at runtime. This obsoletion turns a runtime error into a build warning, which provides better guidance for migration. ## Workaround diff --git a/docs/fundamentals/syslib-diagnostics/syslib1034.md b/docs/fundamentals/syslib-diagnostics/syslib1034.md index af3ff148c68ca..05eb169f5ec4d 100644 --- a/docs/fundamentals/syslib-diagnostics/syslib1034.md +++ b/docs/fundamentals/syslib-diagnostics/syslib1034.md @@ -12,6 +12,6 @@ The non-generic re ## Workarounds -Use instead, which doesn't require run-time code generation. +Use instead, which doesn't require runtime code generation. [!INCLUDE [suppress-syslib-warning](includes/suppress-source-generator-diagnostics.md)]