### Install Ruby and Bundler Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/README.md Steps to install Ruby and the Bundler gem, which are prerequisites for building the Jekyll site. Includes commands for installation and troubleshooting SSL errors. ```bash choco install ruby gem install bundler refreshenv ``` -------------------------------- ### Start InstantSearch.js Search Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_includes/search/algolia-search-scripts.html Initiates the search process by calling the start() method on the InstantSearch.js instance. ```javascript search.start(); ``` -------------------------------- ### Good Namespace Examples Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_rules/1725.md Illustrates effective namespace naming conventions in C# by showcasing examples that follow the recommended structure of names, layers, verbs, and features. ```csharp AvivaSolutions.Commerce.Web NHibernate.Extensibility Microsoft.ServiceModel.WebApi Microsoft.VisualStudio.Debugging FluentAssertion.Primitives CaliburnMicro.Extensions ``` -------------------------------- ### Pandoc Numbered Example Lists Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/Lib/Pandoc/Pandoc User's Guide.html Illustrates the use of the '@' marker for creating sequentially numbered example lists in Pandoc Markdown. It shows basic numbering, explanation paragraphs, and labeled examples with cross-referencing. ```markdown (@) My first example will be numbered (1). (@) My second example will be numbered (2). Explanation of examples. (@) My third example will be numbered (3). ``` ```markdown (@good) This is a good example. As (@good) illustrates, ... ``` -------------------------------- ### Build Jekyll Site Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/README.md Commands to build and serve the Jekyll website for the C# guidelines. This includes installing dependencies, serving the site, and options for incremental builds. ```bash bundle install bundle exec jekyll serve --incremental ``` -------------------------------- ### C# `var` Keyword Usage Examples Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_rules/1520.md Demonstrates correct and incorrect usage of the `var` keyword in C#. Includes examples for anonymous types, built-in types, and cases where the type is evident. ```csharp // Projection into anonymous type. var largeOrders = from order in dbContext.Orders where order.Items.Count > 10 && order.TotalAmount > 1000 select new { order.Id, order.TotalAmount }; // Built-in types. bool isValid = true; string phoneNumber = "(unavailable)"; uint pageSize = Math.Max(itemCount, MaxPageSize); // Types are evident. var customer = new Customer(); var invoice = Invoice.Create(customer.Id); var user = sessionCache.Resolve("john.doe@mail.com"); var subscribers = new List(); var summary = shoppingBasket.ToOrderSummary(); // All other cases. IQueryable recentOrders = ApplyFilter(order => order.CreatedAt > DateTime.Now.AddDays(-30)); LoggerMessage message = Compose(context); ReadOnlySpan key = ExtractKeyFromPair("email=john.doe@mail.com"); IDictionary productsPerCategory = shoppingBasket.Products.ToDictionary(product => product.Category); ``` -------------------------------- ### Task Continuation Example - C# Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_rules/2235.md Demonstrates the traditional approach using Task continuations, which is less readable than the async/await pattern. ```csharp public Task GetDataAsync() { return MyWebService.FetchDataAsync() .ContinueWith(t => new Data(t.Result)); } ``` -------------------------------- ### Async Method Example Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_rules/1835.md An example of an asynchronous method that fetches data from a web service. ```csharp private async Task GetDataAsync() { var result = await MyWebService.GetDataAsync(); return result.ToString(); } ``` -------------------------------- ### Async/Await Example - C# Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_rules/2235.md Illustrates the recommended async/await pattern for cleaner and more maintainable asynchronous operations. ```csharp public async Task GetDataAsync() { string result = await MyWebService.FetchDataAsync(); return new Data(result); } ``` -------------------------------- ### Guidance on Asynchronous Programming (C#) Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_pages/9999_ResourcesAndLinks.md Best practices for using `async`/`await` in C#. This resource includes examples of both correct and incorrect patterns for writing asynchronous code, crucial for modern application development. ```APIDOC Asynchronous Programming Guidance (C#): Applies to: `async`/`await` usage in C# Purpose: To outline best practices for writing efficient and correct asynchronous code. Content: - Examples of good `async`/`await` patterns. - Examples of bad `async`/`await` patterns and their pitfalls. - Recommendations for avoiding common asynchronous programming mistakes. Reference: https://github.com/davidfowl/AspNetCoreDiagnosticScenarios/blob/master/AsyncGuidance.md ``` -------------------------------- ### Citation Syntax and Examples Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/Lib/Pandoc/Pandoc User's Guide.html Explains the structure of citations within the document, including keys, prefixes, locators, and suffixes. Demonstrates various citation formats and in-text citation styles. ```markdown Basic citation: `[see @doe99, pp. 33-35; also @smith04, chap. 1]` Citation with range and emphasis: `[@smith04, pp. 33-35, 38-39 and *passim*]` Multiple citations: `[@smith04; @doe99]` In-text citation (author mentioned): `Smith says blah [-@smith04]` In-text citation with page number: `@smith04 [p. 33] says blah.` ``` -------------------------------- ### Async Targeting Pack for .NET Framework 4.0 Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_rules/2235.md Provides information on how to use async/await keywords in .NET Framework 4.0 by installing the Async Targeting Pack. ```text Install the [Async Targeting Pack](http://www.microsoft.com/en-us/download/details.aspx?id=29576). ``` -------------------------------- ### Explicit Reference Links Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/Lib/Pandoc/Pandoc User's Guide.html Demonstrates explicit reference links with different formats for URLs, titles, and labels. Includes examples of case-insensitivity and title placement. ```Markdown [my label 1]: /foo/bar.html "My title, optional" [my label 2]: /foo [my label 3]: http://fsf.org (The free software foundation) [my label 4]: /bar#special 'A title in single quotes' [my label 5]: [my label 3]: http://fsf.org "The free software foundation" Here is [my link][FOO] [Foo]: /bar/baz ``` -------------------------------- ### C# Optional Parameters Example Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_rules/1553.md Demonstrates replacing method overloads with a single method using optional parameters. The `startIndex` defaults to 0 and `count` defaults to -1, indicating the entire remaining string should be considered. ```csharp public virtual int IndexOf(string phrase, int startIndex = 0, int count = -1) { int length = count == -1 ? someText.Length - startIndex : count; return someText.IndexOf(phrase, startIndex, length); } ``` -------------------------------- ### C# Method Overloading Example Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_rules/1551.md Demonstrates how to implement method overloads by calling the most complete overload. This pattern improves maintainability by centralizing the core logic. ```csharp public class MyString { private string someText; public int IndexOf(string phrase) { return IndexOf(phrase, 0); } public int IndexOf(string phrase, int startIndex) { return IndexOf(phrase, startIndex, someText.Length - startIndex); } public virtual int IndexOf(string phrase, int startIndex, int count) { return someText.IndexOf(phrase, startIndex, count); } } ``` -------------------------------- ### C# TryParse Pattern Example Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_rules/1562.md Demonstrates the allowed usage of `out` parameters when implementing the `TryParse` pattern in C#. This pattern is an exception to the general rule against using `out` parameters. ```csharp bool success = int.TryParse(text, out int number); ``` -------------------------------- ### Specific Exception Handling Example Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_rules/1205.md Demonstrates throwing `ArgumentNullException` for null arguments, which is more specific than `ArgumentException`. ```csharp public void ProcessData(string data) { if (data == null) { throw new ArgumentNullException(nameof(data), "Input data cannot be null."); } // ... process data ... } ``` -------------------------------- ### LINQ Framework Design Guidelines Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_pages/9999_ResourcesAndLinks.md A set of rules and recommendations for implementing `IQueryable` within the LINQ framework. This guide is essential for developers creating custom LINQ providers or extending LINQ functionality. ```APIDOC LINQ Framework Design Guidelines: Applies to: Implementations of `IQueryable` Purpose: Provides rules and recommendations for creating custom LINQ providers. Key Areas: - Naming conventions - Method signatures - Exception handling - Performance considerations Reference: https://blogs.msdn.microsoft.com/mirceat/2008/03/12/linq-framework-design-guidelines/ ``` -------------------------------- ### C# Example: LSP Adherence Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_rules/1011.md Illustrates a correct implementation adhering to the Liskov Substitution Principle. The derived class provides a valid implementation for the base class's abstract method, ensuring substitutability. ```csharp public abstract class BaseClass { public abstract void DoSomething(); } public class DerivedClass : BaseClass { public override void DoSomething() { Console.WriteLine("DerivedClass implementation."); // Adheres to LSP } } public class Client { public void UseBase(BaseClass instance) { instance.DoSomething(); } public void Example() { DerivedClass derived = new DerivedClass(); UseBase(derived); // This works correctly } } ``` -------------------------------- ### Confusing Boolean Comparison Example Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_rules/1712.md Demonstrates a C# code snippet with short and potentially confusing variable names (b001, l0, lOl, 101) and comparisons that can lead to readability issues. ```csharp bool b001 = lo == l0 ? I1 == 11 : lOl != 101; ``` -------------------------------- ### EPUB Metadata in Pandoc Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/Lib/Pandoc/Pandoc User's Guide.html Provides an example of a YAML metadata block for specifying EPUB metadata in Pandoc. ```yaml --- title: - type: main text: My Book - type: subtitle text: An investigation of metadata creator: - role: author text: John Smith - role: editor text: Sarah Jones identifier: - scheme: DOI text: doi:10.234234.234/33 publisher: My Press rights: © 2007 John Smith, CC BY-NC ... ``` -------------------------------- ### Linking to Headers Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/Lib/Pandoc/Pandoc User's Guide.html Provides an example of creating a link to a specific header using its automatically generated or manually assigned identifier. This functionality is supported in HTML, LaTeX, and ConTeXt formats. ```markdown See the section on [header identifiers](#header-identifiers-in-html-latex-and-context). ``` -------------------------------- ### Pandoc Custom Writer Example (Lua) Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/Lib/Pandoc/Pandoc User's Guide.html Demonstrates how to use a custom Lua script as an output format for Pandoc. This allows for custom document generation based on Pandoc's internal document structure. ```bash pandoc -t data/sample.lua ``` -------------------------------- ### Markdown List Ambiguity Example Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/Lib/Pandoc/Pandoc User's Guide.html Demonstrates an ambiguity in Markdown list parsing related to lazy wrapping and the requirement of blank lines between list items. This example highlights why strict rules are necessary. ```markdown bar : definition foo : definition ``` -------------------------------- ### Small Caps using HTML Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/Lib/Pandoc/Pandoc User's Guide.html Provides an example of using an HTML span tag with the 'font-variant:small-caps;' style to render text in small caps. ```html Small caps ``` -------------------------------- ### Pandoc Table Captions Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/Lib/Pandoc/Pandoc User's Guide.html Illustrates the use of table captions in Pandoc Markdown, where a paragraph starting with 'Table:' or ':' provides a caption before or after the table. ```markdown Table: This is a sample table caption. | Header 1 | Header 2 | |----------|----------| | Cell 1 | Cell 2 | | Cell 3 | Cell 4 | ``` -------------------------------- ### Interface Decoupling Example Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_rules/1005.md Demonstrates how interfaces can be used to decouple classes in C#. This approach enhances flexibility by allowing easy swapping of implementations, aiding in unit testing and dependency injection. ```csharp public interface IDataService { string GetData(int id); } public class RealDataService : IDataService { public string GetData(int id) { // Implementation to fetch data from a real source return $"Data for {id} from real service"; } } public class MockDataService : IDataService { public string GetData(int id) { // Mock implementation for testing return $"Mock data for {id}"; } } public class DataProcessor { private readonly IDataService _dataService; public DataProcessor(IDataService dataService) { _dataService = dataService; } public void Process(int id) { string data = _dataService.GetData(id); // Process the data Console.WriteLine($"Processing: {data}"); } } // Usage example: // var realProcessor = new DataProcessor(new RealDataService()); // realProcessor.Process(1); // var mockProcessor = new DataProcessor(new MockDataService()); // mockProcessor.Process(2); ``` -------------------------------- ### Pandoc Markdown Extension: startnum and List Marker Preservation Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/Lib/Pandoc/Pandoc User's Guide.html Illustrates pandoc's `startnum` extension and its ability to preserve list marker types and starting numbers. It shows how different marker types initiate new lists and how to use '#' for default markers. ```markdown 9) Ninth 10) Tenth 11) Eleventh i. subone ii. subtwo iii. subthree (2) Two (5) Three 1. Four * Five #. one #. two #. three ``` -------------------------------- ### Pandoc YAML Metadata Block Example Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/Lib/Pandoc/Pandoc User's Guide.html Demonstrates the use of a YAML metadata block for document properties like title, author, and date, which can be used for document generation. ```markdown --- nocite: | @item1, @item2 --- @item3 ``` -------------------------------- ### Assembly Naming Convention Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_rules/1505.md Assemblies should be named using the pattern Company.Component.dll, where Component reflects the primary namespace. For example, an assembly containing classes in the AvivaSolutions.Web.Binding namespace should be named AvivaSolutions.Web.Binding.dll. ```csharp AvivaSolutions.Web.Controls.dll AvivaSolutions.Web.Binding.dll ``` -------------------------------- ### Multiline Table Syntax Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/Lib/Pandoc/Pandoc User's Guide.html Illustrates multiline Markdown tables, allowing headers and rows to span multiple lines. Requires a starting row of dashes and blank lines between rows. Column widths can be adjusted in the source. ```markdown ------------------------------------------------------------- Centered Default Right Left Header Aligned Aligned Aligned ----------- ------- --------------- ------------------------- First row 12.0 Example of a row that spans multiple lines. Second row 5.0 Here's another one. Note the blank line between rows. ------------------------------------------------------------- Table: Here's the caption. It, too, may span multiple lines. ``` -------------------------------- ### Markdown Initial Handling Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/Lib/Pandoc/Pandoc User's Guide.html Illustrates a Markdown rule to prevent paragraphs starting with initials (e.g., 'B. Russell') from being misinterpreted as list items. It also shows how to escape such cases using a backslash. ```markdown B. Russell was an English philosopher. (C\) 2007 Joe Smith ``` -------------------------------- ### Pandoc YAML Metadata Block Example Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/Lib/Pandoc/Pandoc User's Guide.html Demonstrates the structure and usage of a YAML metadata block in Pandoc, including how to include metadata like title, author, and abstract. It shows how to use literal blocks for multi-line content and how metadata fields are processed. ```bash pandoc chap1.md chap2.md chap3.md metadata.yaml -s -o book.html ``` ```yaml --- title: 'This is the title: it contains a colon' author: - name: Author One affiliation: University of Somewhere - name: Author Two affiliation: University of Nowhere tags: [nothing, nothingness] abstract: | This is the abstract. It consists of two paragraphs. ... ``` -------------------------------- ### Build C# Guidelines PDFs Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/README.md Instructions for building PDF versions of the C# coding guidelines and cheat sheet. This involves running a batch script and using a web browser's print-to-PDF functionality with specific settings. ```bash build.bat ``` -------------------------------- ### Copyright and Powered By Information Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_includes/footer.html Displays copyright information including the year and site name, along with attribution for the tools used to build the site (JetBrains Rider, Jekyll, Minimal Mistakes). ```jekyll © {{ site.time | date: '%Y' }} {{ site.name | default: site.title }}. {{ site.data.ui-text[site.locale].powered_by | default: "Powered by" }} [JetBrains Rider](https://www.jetbrains.com/rider/), [Jekyll](https://jekyllrb.com) & [Minimal Mistakes](https://mademistakes.com/work/minimal-mistakes-jekyll-theme/). ``` -------------------------------- ### Pandoc Command Line Synopsis Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/Lib/Pandoc/Pandoc User's Guide.html The basic command-line structure for using Pandoc. It specifies that Pandoc can take multiple input files and various options to perform document conversions. ```bash pandoc [_options_] [_input-file_]… ``` -------------------------------- ### Styling Reveal.js Presentations with Pandoc Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/Lib/Pandoc/Pandoc User's Guide.html Illustrates how to set reveal.js themes and custom stylesheets using Pandoc variables and options. ```bash pandoc your_presentation.md -t revealjs -V theme=moon --css custom.css -o presentation.html ``` -------------------------------- ### Search Functionality Integration Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_includes/scripts.html Integrates search functionality based on a site configuration, supporting either Lunr or Algolia as the search provider. ```liquid {% if site.search == true or page.layout == "search" %} {%- assign search_provider = site.search_provider | default: "lunr" -%} {%- case search_provider -%} {%- when "lunr" -%} {% include search/lunr-search-scripts.html %} {%- when "algolia" -%} {% include search/algolia-search-scripts.html %} {%- endcase -%} {% endif %} ``` -------------------------------- ### Fenced Code Blocks in Markdown (Tildes) Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/Lib/Pandoc/Pandoc User's Guide.html Pandoc supports fenced code blocks, which start and end with a row of three or more tildes (~). The closing row must be at least as long as the opening row. Code blocks must be separated by blank lines. For code containing tildes, use a longer row of tildes for fencing. ```markdown ~~~~~~~ if (a > 3) { moveShip(5 * gravity, DOWN); } ~~~~~~~ ~~~~~~~~~~~~~~~~~ ~~~~~~~~~~ code including tildes ~~~~~~~~~~ ~~~~~~~~~~~~~~~~~ ``` -------------------------------- ### Pandoc Command-Line Options Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/Lib/Pandoc/Pandoc User's Guide.html Overview of common pandoc command-line options for input and output format control. ```APIDOC Pandoc CLI Options: -o, --output=FILE Write output to FILE, rather than stdout. -s, --standalone Produce a standalone document, including header and footer. -r, --read=FORMAT -f, --from=FORMAT Specify the input format (e.g., markdown, html, latex). -w, --write=FORMAT -t, --to=FORMAT Specify the output format (e.g., html, markdown, latex, pdf). Input Handling: If no input file is specified, input is read from stdin. Multiple input files are concatenated with a blank line between them. Binary input formats (EPUB, odt, docx) do not support concatenation. Format Guessing: Pandoc attempts to guess input and output formats from file extensions. Defaults to Markdown for input and HTML for output if not specified. Encoding: Pandoc uses UTF-8 for input and output. Use iconv for non-UTF-8 local encodings. PDF Output: Specify output file with a .pdf extension. Pandoc uses LaTeX by default for PDF conversion. ``` -------------------------------- ### Facebook SDK Initialization (JavaScript) Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_includes/comments-providers/facebook.html Initializes the Facebook SDK for JavaScript, including handling app ID and script loading. ```javascript (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.5{% if site.comments.facebook.appid %}&appId={{ site.comments.facebook.appid }}{% endif %}"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); ``` -------------------------------- ### Styling Beamer Presentations with Pandoc Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/Lib/Pandoc/Pandoc User's Guide.html Demonstrates how to apply Beamer themes and color themes using Pandoc's -V option for PDF presentations. ```bash pandoc habits.txt -t beamer habits.txt -V theme:Warsaw -o habits.pdf ``` -------------------------------- ### C# Generic Constraints Example Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_rules/1240.md Demonstrates the correct usage of C# generic constraints (`where T : SomeClass`) to avoid casting to and from the object type. This improves type safety and performance. ```csharp class SomeClass { } // Don't class MyClass { void SomeMethod(T t) { object temp = t; SomeClass obj = (SomeClass) temp; } } // Do class MyClassWithConstraint where T : SomeClass { void SomeMethod(T t) { SomeClass obj = t; } } ``` -------------------------------- ### Configuration Management in C# Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_rules/2207.md Demonstrates how to avoid hard-coding deployment-specific strings by using configuration management. This includes accessing connection strings and settings from configuration files. ```csharp // Example using ConfigurationManager for connection strings string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString; // Example using Visual Studio generated Settings class // Assuming a Settings class is generated from app.settings or web.settings // string serverAddress = Properties.Settings.Default.ServerAddress; // Example using Resources for localized strings or constants // string welcomeMessage = MyProject.Properties.Resources.WelcomeMessage; ``` -------------------------------- ### Line Blocks Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/Lib/Pandoc/Pandoc User's Guide.html Preserves line breaks and leading whitespace for sequences of lines starting with a vertical bar (|) followed by a space. Useful for formatting verse and addresses. ```markdown | The limerick packs laughs anatomical | In space that is quite economical. | But the good ones I've seen | So seldom are clean | And the clean ones so seldom are comical | 200 Main St. | Berkeley, CA 94718 ``` ```markdown | The Right Honorable Most Venerable and Righteous Samuel L. Constable, Jr. | 200 Main St. | Berkeley, CA 94718 ``` -------------------------------- ### Best Practices for C# async/await Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_pages/9999_ResourcesAndLinks.md An overview of essential practices for adopting `async` and `await` in C# codebases. Although older, the guidance remains relevant for effective asynchronous programming. ```APIDOC C# async/await Best Practices: Applies to: `async`/`await` in C# Purpose: Provides a foundational understanding of crucial practices for using `async` and `await`. Key Practices: - Understanding the `async` and `await` keywords. - Proper use of `Task` and `Task`. - Avoiding deadlocks. - Best practices for I/O-bound operations. Reference: https://msdn.microsoft.com/en-us/magazine/jj991977.aspx ``` -------------------------------- ### SEO and Social Media Configuration Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_includes/seo.html This snippet demonstrates how to configure SEO metadata, social media sharing properties, and site verification tags for a website. It includes logic for generating canonical URLs, meta descriptions, and Open Graph tags based on page and site configurations. ```html {%- if site.url -%} {%- assign seo_url = site.url | append: site.baseurl -%} {%- endif -%} {%- assign seo_url = seo_url | default: site.github.url -%} {% if site.title_separator %} {% assign title_separator = site.title_separator | default: '-' | replace: '|', '|' %} {% endif %} {%- if page.title -%} {%- assign seo_title = page.title | append: " " | append: title_separator | append: " " | append: site.title -%} {%- endif -%} {%- if seo_title -%} {%- assign seo_title = seo_title | markdownify | strip_html | strip_newlines | escape_once -%} {%- endif -%} {%- assign canonical_url = page.url | replace: "index.html", "" | absolute_url %} {%- assign seo_description = page.description | default: page.excerpt | default: site.description -%} {%- if seo_description -%} {%- assign seo_description = seo_description | markdownify | strip_html | strip_newlines | escape_once -%} {%- endif -%} {%- assign author = page.author | default: page.authors[0] | default: site:author -%} {%- assign author = site.data.authors[author] | default: author -%} {%- if author.twitter -%} {%- assign author_twitter = author.twitter | replace: "@", "" -%} {%- endif -%} {%- assign page_large_image = page.header.og_image | default: page.header.overlay_image | default: page.header.image -%} {%- unless page_large_image contains '://' -%} {%- assign page_large_image = page_large_image | absolute_url -%} {%- endunless -%} {%- assign page_large_image = page_large_image | escape -%} {%- assign page_teaser_image = page.header.teaser | default: site.og_image -%} {%- unless page_teaser_image contains '://' -%} {%- assign page_teaser_image = page_teaser_image | absolute_url -%} {%- endunless -%} {%- assign page_teaser_image = page_teaser_image | escape -%} {%- assign site_og_image = site.og_image -%} {%- unless site_og_image contains '://' -%} {%- assign site_og_image = site_og_image | absolute_url -%} {%- endunless -%} {%- assign site_og_image = site_og_image | escape -%} {%- if page.date -%} {%- assign og_type = "article" -%} {%- else -%} {%- assign og_type = "website" -%} {%- endif -%} {{ seo_title | default: site.title }}{% if paginator %}{% unless paginator.page == 1 %} {{ title_separator }} {{ site.data.ui-text[site.locale].page | default: "Page" }} {{ paginator.page }}{% endunless %}{% endif %} {% if author.name %} {% endif %} {% if page.excerpt %} {% endif %} {% if page_large_image %} {% elsif page_teaser_image %} {% endif %} {% if site.twitter.username %} {% if page_large_image %} {% else %} {% if page_teaser_image %} {% endif %} {% endif %} {% if author_twitter %} {% endif %} {% endif %} {% if page.date %} {% endif %} {% if og_type == "article" and page.last_modified_at %} {% endif %} {% if site.facebook %} {% if site.facebook.publisher %} {% endif %} {% if site.facebook.app_id %} {% endif %} {% endif %} {% if paginator.previous_page %} {% endif %} {% if paginator.next_page %} {% endif %} {% if site.og_image %} { "@context": "http://schema.org", "@type": "Organization", "url": {{ seo_url | jsonify }}, "logo": {{ site_og_image | jsonify }} } {% endif %} {% if site.social %} { "@context": "http://schema.org", "@type": "{% if site.social.type %}{{ site.social.type }}{% else %}Person{% endif %}", "name": {{ site.social.name | default: site.name | jsonify }}, "url": {{ seo_url | jsonify }}, "sameAs": {{ site.social.links | jsonify }} } {% endif %} {% if site.google_site_verification %} {% endif %} {% if site.bing_site_verification %} {% endif %} {% if site.alexa_site_verification %} {% endif %} {% if site.yandex_site_verification %} {% endif %} {% if site.naver-site-verification %} {% endif %} ``` -------------------------------- ### Interface vs. Base Class for Extension Points Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_rules/1004.md Demonstrates the principle of using an interface for extension points to allow multiple implementations, contrasting it with the limitations of using a base class. ```csharp // Good Practice: Using an interface for an extension point public interface IExtensionPoint { void PerformAction(); } // Optional: Provide a default implementation public abstract class DefaultExtensionPoint : IExtensionPoint { public abstract void PerformAction(); } // User implementation deriving from the interface public class MyExtension : IExtensionPoint { public void PerformAction() { // Implementation details } } // User implementation deriving from the default implementation public class AnotherExtension : DefaultExtensionPoint { public override void PerformAction() { // Implementation details } } // Bad Practice: Forcing users to derive from a base class public abstract class BaseExtension { public abstract void PerformAction(); } // User implementation forced to derive from BaseExtension public class MyClassThatNeedsExtension : BaseExtension { public override void PerformAction() { // Implementation details } } ``` -------------------------------- ### Instantiate InstantSearch.js with Algolia Credentials Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_includes/search/algolia-search-scripts.html Initializes InstantSearch.js with Algolia application ID, API key, and index name. It also configures search parameters to restrict searchable attributes. ```javascript const search = instantsearch({ appId: '{{ site.algolia.application_id }}', apiKey: '{{ site.algolia.search_only_api_key }}', indexName: '{{ site.algolia.index_name }}', searchParameters: { restrictSearchableAttributes: [ 'title', 'content' ] } }); ``` -------------------------------- ### Pandoc Standalone Document Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/Lib/Pandoc/Pandoc User's Guide.html Creates a standalone HTML document with a proper header and footer. ```bash pandoc -s -o output.html input.txt ``` -------------------------------- ### Pandoc API Documentation Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/Lib/Pandoc/Pandoc User's Guide.html Provides an overview of Pandoc's command-line interface, detailing options for file processing, filtering, metadata management, output formatting, and template customization. ```APIDOC Pandoc Command-Line Options: File Scope: --file-scope Parse each file individually before combining for multifile documents. Allows footnotes in different files with the same identifiers to work as expected. If this option is set, footnotes and links will not work across files. Reading binary files (docx, odt, epub) implies --file-scope. Filters: --filter=EXECUTABLE Specify an executable to be used as a filter transforming the pandoc AST after the input is parsed and before the output is written. The executable should read JSON from stdin and write JSON to stdout. The JSON must be formatted like pandoc’s own JSON input and output. The name of the output format will be passed to the filter as the first argument. Example: pandoc --filter ./caps.py -t latex Filters may be written in any language. Text.Pandoc.JSON exports toJSONFilter to facilitate writing filters in Haskell. Libraries exist for Python, PHP, Perl, and Node.js. Note: The EXECUTABLE will be sought in the user’s PATH, and not in the working directory, if no directory is provided. If you want to run a script in the working directory, preface the filename with './'. Metadata and Variables: -M KEY[=VAL], --metadata=KEY[:VAL] Set the metadata field KEY to the value VAL. A value specified on the command line overrides a value specified in the document. Values will be parsed as YAML boolean or string values. If no value is specified, the value will be treated as Boolean true. Like --variable, --metadata causes template variables to be set. But unlike --variable, --metadata affects the metadata of the underlying document (which is accessible from filters and may be printed in some output formats). -V KEY[=VAL], --variable=KEY[:VAL] Set the template variable KEY to the value VAL when rendering the document in standalone mode. This is generally only useful when the --template option is used to specify a custom template, since pandoc automatically sets the variables used in the default templates. If no VAL is specified, the key will be given the value true. Normalization and Tabs: --normalize Normalize the document after reading: merge adjacent Str or Emph elements, for example, and remove repeated Spaces. -p, --preserve-tabs Preserve tabs instead of converting them to spaces (the default). Note that this will only affect tabs in literal code spans and code blocks; tabs in regular text will be treated as spaces. --tab-stop=NUMBER Specify the number of spaces per tab (default is 4). Track Changes and Media Extraction: --track-changes=accept|reject|all Specifies what to do with insertions, deletions, and comments produced by the MS Word “Track Changes” feature. 'accept' (the default), inserts all insertions, and ignores all deletions. 'reject' inserts all deletions and ignores insertions. Both 'accept' and 'reject' ignore comments. 'all' puts in insertions, deletions, and comments, wrapped in spans with 'insertion', 'deletion', 'comment-start', and 'comment-end' classes, respectively. The author and time of change is included. 'all' is useful for scripting: only accepting changes from a certain reviewer, say, or before a certain date. This option only affects the docx reader. --extract-media=DIR Extract images and other media contained in a docx or epub container to the path DIR, creating it if necessary, and adjust the images references in the document so they point to the extracted files. This option only affects the docx and epub readers. Standalone Output and Templates: -s, --standalone Produce output with an appropriate header and footer (e.g. a standalone HTML, LaTeX, TEI, or RTF file, not a fragment). This option is set automatically for pdf, epub, epub3, fb2, docx, and odt output. --template=FILE Use FILE as a custom template for the generated document. Implies --standalone. See Templates, below, for a description of template syntax. If no extension is specified, an extension corresponding to the writer will be added, so that --template=special looks for special.html for HTML output. If the template is not found, pandoc will search for it in the templates subdirectory of the user data directory (see --data-dir). If this option is not used, a default template appropriate for the output format will be used (see -D/--print-default-template). -D FORMAT, --print-default-template=FORMAT Print the system default template for an output FORMAT. (See -t for a list of possible FORMATs.) Templates in the user data directory are ignored. ``` -------------------------------- ### Pandoc Utility and Information Options Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/Lib/Pandoc/Pandoc User's Guide.html Provides options for generating bash completion scripts, enabling verbose debugging output, printing the version, and displaying help messages. The `--bash-completion` option is used to set up shell completion for Pandoc commands. ```APIDOC --bash-completion Generate a bash completion script. To enable bash completion with pandoc, add this to your .bashrc: eval "$(pandoc --bash-completion)" --verbose Give verbose debugging output. Currently this only has an effect with PDF output. -v, --version Print version. -h, --help Show usage message. ``` -------------------------------- ### C# Object and Collection Initializers Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_rules/1523.md Demonstrates the use of object and collection initializers in C# to simplify object creation and population. This pattern reduces boilerplate code compared to separate assignment statements. ```csharp var startInfo = new ProcessStartInfo("myapp.exe") { StandardOutput = Console.Output, UseShellExecute = true }; var countries = new List { "Netherlands", "United States" }; var countryLookupTable = new Dictionary { ["NL"] = "Netherlands", ["US"] = "United States" }; ``` -------------------------------- ### C# Method and Parameter Guidelines Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_pages/Cheatsheet.md Guidelines for C# method signatures, including parameter count, optional parameters, and the use of ref/out keywords. Also covers avoiding boolean flags in signatures. ```csharp /// /// Encapsulates complex expressions in a property, method or local function. /// // Rule: {{ site.default_rule_prefix }}1547 /// /// Calls the more overloaded method from other overloads. /// // Rule: {{ site.default_rule_prefix }}1551 /// /// Only use optional parameters to replace overloads. /// // Rule: {{ site.default_rule_prefix }}1553 /// /// Do not use optional parameters in interface methods or their concrete implementations. /// // Rule: {{ site.default_rule_prefix }}1554 /// /// Avoid using named arguments. /// // Rule: {{ site.default_rule_prefix }}1555 /// /// Don't declare signatures with more than 3 parameters. /// // Rule: {{ site.default_rule_prefix }}1561 /// /// Don't use `ref` or `out` parameters. /// // Rule: {{ site.default_rule_prefix }}1562 /// /// Avoid signatures that take a `bool` flag. /// // Rule: {{ site.default_rule_prefix }}1564 ``` -------------------------------- ### Pandoc PDF Production with ConTeXt or wkhtmltopdf Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/Lib/Pandoc/Pandoc User's Guide.html Explains how to generate PDF output using ConTeXt or wkhtmltopdf with Pandoc. It specifies the command-line arguments for selecting these engines. ```markdown Alternatively, pandoc can use ConTeXt or `wkhtmltopdf` to create a PDF. To do this, specify an output file with a `.pdf` extension, as before, but add `-t context` or `-t html5` to the command line. ``` -------------------------------- ### Stateless Properties in C# Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_rules/1100.md Properties should be stateless with respect to other properties. This means the order in which properties are set should not affect the object's state or behavior. For example, setting 'DataSource' then 'DataMember' should yield the same result as setting 'DataMember' then 'DataSource'. ```csharp public class MyClass { public string DataSource { get; set; } public string DataMember { get { // Example: If DataSource is null, return a default or throw an exception if (DataSource == null) { return "DefaultMember"; } return DataSource + "_Member"; } set { // Logic to set DataMember, potentially related to DataSource // Ensure this logic is independent of the order of setting properties } } } ``` -------------------------------- ### Pandoc Fetching from URI Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/Lib/Pandoc/Pandoc User's Guide.html Fetches content from a URI and converts it to Markdown. ```bash pandoc -f html -t markdown http://www.fsf.org ``` -------------------------------- ### C# Example: LSP Violation (NotImplementedException) Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_rules/1011.md Demonstrates a common violation of the Liskov Substitution Principle where a derived class throws NotImplementedException in an overridden method. This prevents the derived type from being a valid substitute for the base type. ```csharp public abstract class BaseClass { public abstract void DoSomething(); } public class DerivedClass : BaseClass { public override void DoSomething() { throw new NotImplementedException(); // Violation of LSP } } ``` -------------------------------- ### Math Rendering in HTML Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/Lib/Pandoc/Pandoc User's Guide.html Configures how TeX math is rendered in HTML output using various libraries. ```bash -m URL, --latexmathml[=URL] --mathml[=URL] --jsmath[=URL] --mathjax[=URL] --gladtex --mimetex[=URL] --webtex[=URL] --katex[=URL] --katex-stylesheet=URL ``` -------------------------------- ### C# Class Hierarchy Example with 'new' Keyword Source: https://github.com/dennisdoomen/csharpguidelines/blob/master/_rules/1010.md Demonstrates how using the 'new' keyword to hide a base class method can lead to unexpected behavior when accessing the method through base and derived class references. This breaks the principle of polymorphism. ```csharp public class Book { public virtual void Print() { Console.WriteLine("Printing Book"); } } public class PocketBook : Book { public new void Print() { Console.WriteLine("Printing PocketBook"); } } // Usage: // PocketBook pocketBook = new PocketBook(); // pocketBook.Print(); // Outputs "Printing PocketBook " // ((Book)pocketBook).Print(); // Outputs "Printing Book" ```