{"id":22065634,"url":"https://github.com/karenpayneoregon/resharper-templates","last_synced_at":"2026-04-30T17:32:05.866Z","repository":{"id":184928995,"uuid":"672693700","full_name":"karenpayneoregon/resharper-templates","owner":"karenpayneoregon","description":"Examples for writing Source Templates for ReSharper","archived":false,"fork":false,"pushed_at":"2023-07-31T10:07:11.000Z","size":481,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-23T18:16:56.100Z","etag":null,"topics":["chsarp-core","resharper","resharper-source-templates","visual-studio","visualstudio2022"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/karenpayneoregon.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-07-31T00:02:32.000Z","updated_at":"2024-06-11T18:38:36.000Z","dependencies_parsed_at":"2023-07-31T01:57:21.173Z","dependency_job_id":"f46581f3-2df4-4ad8-bdac-8e48ce739620","html_url":"https://github.com/karenpayneoregon/resharper-templates","commit_stats":null,"previous_names":["karenpayneoregon/resharper-templates"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/karenpayneoregon/resharper-templates","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/karenpayneoregon%2Fresharper-templates","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/karenpayneoregon%2Fresharper-templates/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/karenpayneoregon%2Fresharper-templates/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/karenpayneoregon%2Fresharper-templates/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/karenpayneoregon","download_url":"https://codeload.github.com/karenpayneoregon/resharper-templates/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/karenpayneoregon%2Fresharper-templates/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32472396,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-30T13:12:12.517Z","status":"ssl_error","status_checked_at":"2026-04-30T13:12:06.837Z","response_time":57,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["chsarp-core","resharper","resharper-source-templates","visual-studio","visualstudio2022"],"created_at":"2024-11-30T19:20:58.626Z","updated_at":"2026-04-30T17:32:05.859Z","avatar_url":"https://github.com/karenpayneoregon.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Learn Resharper PostFix and Source Templates\n\nIn this article learn how to create and use Jetbrains ReSharper�s [Source templates](https://www.jetbrains.com/help/resharper/Source_Templates.html) and to explore [Postfix templates](https://www.jetbrains.com/help/resharper/2023.1/Reference__Options__Environment__Postfix_Templates.html).\n\n\u003e **Note**\n\u003e All source templates presented are in the GitHub repository\n\n\n## Postfix templates\n\nWith these templates a developer can write less code in many cases.\n\nSimple example, we want to write the following code which without Postfix templates everything needs to be hand typed.\n\n```csharp\nusing (var cn = new SqlConnection())\n{\n    \n}\n```\n\n### With PostFix templates type\n\n**Working with SqlClient**\n\n```csharp\nnew SqlConnection()\n```\n\nNext type `using` and press \u003ckbd\u003eEnter\u003c/kbd\u003e \n\n![initial response](assets/figure2.png)\n\nAfter pressing \u003ckbd\u003eEnter\u003c/kbd\u003e there is a prompt to use `var` or the type, use \u003ckbd\u003eUp\u003c/kbd\u003e and  \u003ckbd\u003eDown\u003c/kbd\u003e arrows to select.\n\n![select type for using statement](assets/figure3.png)\n\nPress \u003ckbd\u003eTAB\u003c/kbd\u003e and name choices appear, use \u003ckbd\u003eUp\u003c/kbd\u003e and  \u003ckbd\u003eDown\u003c/kbd\u003e arrows to select or type in your own name.\n\n![select name for variable](assets/figure4.png).\n\n**Create a foreach**\n\nThe task is to iterate data read from a file using a foreach which should look like the following.\n\n```csharp\nList\u003cCustomers\u003e customersList =\n    JsonSerializer.Deserialize\u003cList\u003cCustomers\u003e\u003e(\n        File.ReadAllText(\"Customers.json\"));\n\nforeach (var customer in customersList!)\n{\n    Console.WriteLine($\"{customer.Id,-3}{customer.Company}\");\n}\n```\n\n:small_blue_diamond: Step 1, create the model.\n\n```csharp\npublic class Customers\n{\n    public int Id { get; set; }\n    public string Company { get; set; }\n    public string Title { get; set; }\n    public string Contact { get; set; }\n    public string Country { get; set; }\n    public string Phone { get; set; }\n    public DateTime Modified { get; set; }\n}\n```\n\n:small_blue_diamond: Step 2, read the file\n\n```csharp\nList\u003cCustomers\u003e customersList =\n    JsonSerializer.Deserialize\u003cList\u003cCustomers\u003e\u003e(\n        File.ReadAllText(\"Customers.json\"));\n```\n\nType the variable name, \u003ckbd\u003e.\u003c/kbd\u003e then **foreach** (no upper casing) and press \u003ckbd\u003eEnter\u003c/kbd\u003e\n\n![selecting foreach](assets/figure5.png) \n\nto get a prompt same as last example for var or type then variable name.\n\n### PostFix templates list\n\nSee the following [documentaton](https://www.jetbrains.com/help/resharper/2023.1/Reference__Options__Environment__Postfix_Templates.html#code-completion) for a list of postfix templates.\n\nAlso, under Resharper options they are listed and can be turned off.\n\n![Postfix options in Visual Studio](assets/figure1.png)\n\n## Source templates\n\nThese templates are really cool to create your own postfix templates were the template is for a specific project or solution as per [documentation](https://www.jetbrains.com/help/resharper/Source_Templates.html). Templates can be created in the same project they will be used in or create a Visual Studio solution for source templates only and reference the class project into your projects.\n\n### Working with DateTime, DateOnly and TimeOnly\n\nThe task is to get parts for a DateOnly.\n\nOur source\n\n```csharp\nstatic DateOnly BirthDate() \n    =\u003e new(2022, 9, 2);\n```\n\nExtract Month, Day and Year\n\n```csharp\nvar dateOnly = BirthDate();\nvar month = dateOnly.Day;\nvar year = dateOnly.Year;\nvar day = dateOnly.Day;\n```\n\nOr we can [Deconstruct](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/deconstruct) were after typing `var dateOnly = BirthDate();` \n\n![Deconstruct context option](assets/figure6.png)\n\nWhich is possible using the following method incuded in SourceTemplateLibrary class project along with other similar methods.\n\nAfter accepting\n\n```csharp\nvar (day, month, year) = BirthDate();\n```\n\nCode For BirthDate()\n\n```csharp\nstatic DateOnly BirthDate() \n    =\u003e new(2022, 9, 2);\n```\n\nTo create the above with a source template.\n\n- Create a static class\n- Add the following NuGet package [JetBrains.Annotations](https://www.nuget.org/packages/JetBrains.Annotations/2023.2.0?_src=template)\n- Create the following extension method\n\n```csharp\n[SourceTemplate]\npublic static void ds(this DateTime sender)\n{\n    var (day, month, year) = sender;\n}\n```\n\n- Builds the project\n- Type **BirthDate()** for this example follows bs `ds`, press \u003ckbd\u003eEnter\u003c/kbd\u003e\n\n![using ds](assets/figure7.png)\n\nAnd Resharper provides\n\n```csharp\nvar (day, month, year) = BirthDate();\n```\n\nLet's say you don't need one of the parts, use a [discard](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/discards).\n\n```csharp\nvar (day, _, year) = BirthDate();\n```\n\nThe same can be done for a TimeOnly, create the following extension method.\n\n```csharp\npublic static class TimeOnlyExtensions\n{\n    public static void Deconstruct(this TimeOnly time, out int hour, out int minutes, out int seconds, out int milliseconds)\n        =\u003e (hour, minutes, seconds, milliseconds) = \n            (time.Hour, time.Minute, time.Second, time.Microsecond);\n}\n```\n\nCreate the source template in a static class\n\n```csharp\n[SourceTemplate]\npublic static void ds(this TimeOnly sender)\n{\n    var (hour, minutes, seconds, milliseconds) = sender;\n}\n```\n\n\u003e **Note**\n\u003e Two things, Reshaper uses lower casing for source templates which is done here, secondly, the names were kept simple ds for Deconstruct. Feel free to use different names that make sense to you.\n\n\nSuppose there is a need to see if a DateTime is a weekday or weekend.\n\nCreate the following class for logic to see if a date is a weekday or weekend.\n\n```csharp\npublic static class DateTimeExtensions\n{\n    public static bool IsWeekend(this DateTime self) \n        =\u003e self.DayOfWeek is DayOfWeek.Sunday or DayOfWeek.Saturday;\n\n    public static bool IsWeekDay(this DateTime self)\n        =\u003e !self.IsWeekend();\n\n    public static bool IsWeekDay(this DayOfWeek sender)\n    {\n        return sender is DayOfWeek.Monday or \n            DayOfWeek.Tuesday or \n            DayOfWeek.Wednesday or \n            DayOfWeek.Thursday or \n            DayOfWeek.Friday;\n    }\n\n    public static bool IsWeekend(this DayOfWeek sender) =\u003e !sender.IsWeekDay();\n}\n```\nCreate the source template in a static class. Note **//$ $END$** which is the final cursor position.\n\n```csharp\n[SourceTemplate]\npublic static void weekday(this DateTime sender)\n{\n    if (sender.IsWeekDay())\n    {\n        //$ $END$\n    }\n}\n```\n\nNow to iterate a list of DateTime the final results for this code sample will be...\n\n```csharp\nvar dates = DateTimesList();\n\nforeach (var date in dates)\n{\n    if (date.IsWeekDay())\n    {\n        Console.WriteLine(date.DayOfWeek);\n    }\n}\n```\n\nWith the following source\n\n```csharp\nprivate static List\u003cDateTime\u003e DateTimesList()\n    =\u003e Enumerable.Range(1, 7)\n        .Select(day =\u003e new DateTime(2023, 7, day))\n        .ToList();\n```\n\nOnce the following has been entered\n\n```csharp\nvar dates = DateTimesList();\n```\n\nType dates `dates.foreach` and press \u003ckbd\u003eEnter\u003c/kbd\u003e to use the built in postfix template. We get the following.\n\n\n```csharp\nforeach (var dateTime in dates)\n{\n    \n}\n```\n\nPlace the cursor in the body of the `foreach` and type the following to use the custom source template.\n\n```csharp\ndateTime.weekday\n```\n\nPress \u003ckbd\u003eEnter\u003c/kbd\u003e  or \u003ckbd\u003eTAB\u003c/kbd\u003e and the following is written.\n\n```csharp\nforeach (var dateTime in dates)\n{\n    if (dateTime.IsWeekDay())\n    {\n        \n    }\n}\n```\n\n## Working with a data provider DataReader\n\nIn this example the task is to iterate a [SqlDataReader](https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqldatareader?view=dotnet-plat-ext-7.0) from a [SqlCommand](https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand?view=dotnet-plat-ext-7.0).\n\n:small_orange_diamond: Desired finished code\n\n```csharp\nvar statement = \"SELECT CountryId, [Name] FROM dbo.Countries;\";\nvar connectionString = _configuration.GetValue\u003cstring\u003e(\"ConnectionStrings:ApplicationConnection\");\nusing SqlConnection cn = new(connectionString);\nusing SqlCommand cmd = new(statement, cn);\ntry\n{\n    cn.Open();\n    SqlDataReader? reader = cmd.ExecuteReader();\n    while (reader.Read())\n    {\n        \n    }\n}\ncatch (Exception exception)\n{\n    Console.WriteLine(exception.Message);\n}\n```\n\nEven if the developer types fast with source templates the above code can be in about 20 seconds or less.\n\n\nThis example is done in a Console project so there are several NuGet packages needed. Open the project file and note packages starting with `Microsoft.Extensions`.\n\nThe connection string is in appsettings.json\n\n```json\n{\n  \"Logging\": {\n    \"LogLevel\": {\n      \"Default\": \"Information\",\n      \"Microsoft.AspNetCore\": \"Warning\"\n    }\n  },\n  \"AllowedHosts\": \"*\",\n  \"ConnectionStrings\": {\n    \"ApplicationConnection\": \"Data Source=.\\\\SQLEXPRESS;Initial Catalog=EF.UsingInterfaces;Integrated Security=True;Encrypt=False\"\n  }\n}\n```\n\nAdd the following variable for getting the connection string\n\n```csharp\nprivate static IConfiguration? _configuration;\n```\n\nNow lets use one standard postfix template and two custom source templates.\n\nData to read\n\n![Data to read in SSMS](assets/figure8.png)\n\nCreate the following method\n\n```csharp\nstatic void SqlClientExample()\n{\n    var statement = \"SELECT CountryId, [Name] FROM dbo.Countries;\";\n    \n}\n```\n\nUnder `var statment` type the following and press \u003ckbd\u003eEnter\u003c/kbd\u003e \n\n```csharp\nnew SqlConnection().create\n```\n\nWhich writes out the following\n\n```csharp\nstatic void SqlClientExample()\n{\n    var statement = \"SELECT CountryId, [Name] FROM dbo.Countries;\";\n\n    var connectionString = _configuration.GetValue\u003cstring\u003e(\"ConnectionStrings:ApplicationConnection\");\n    using SqlConnection cn = new(connectionString);\n    using SqlCommand cmd = new(\"statement\", cn);\n    try\n    {\n        cn.Open();\n            \n    }\n    catch (Exception exception)\n    {\n        Console.WriteLine(exception.Message);\n    }\n}\n```\n\nRemove the quotes on statement\n\n```csharp\nusing SqlCommand cmd = new(statement, cn);\n```\n\nUnder `cn.Open()` type the following and press \u003ckbd\u003eEnter\u003c/kbd\u003e \n\n```csharp\ncmd.reader\n```\n\nWhich writes out a variale for a SqlDataReader and a while statement as follows.\n\n```csharp\nstatic void SqlClientExample()\n{\n    var statement = \"SELECT CountryId, [Name] FROM dbo.Countries;\";\n\n    var connectionString = _configuration.GetValue\u003cstring\u003e(\"ConnectionStrings:ApplicationConnection\");\n    using SqlConnection cn = new(connectionString);\n    using SqlCommand cmd = new(statement, cn);\n    try\n    {\n        cn.Open();\n        SqlDataReader? reader = cmd.ExecuteReader();\n        while (reader.Read())\n        {\n                \n        }\n            \n    }\n    catch (Exception exception)\n    {\n        Console.WriteLine(exception.Message);\n    }\n}\n```\n\nAdd a line to read out data to the console and run the code.\n\n```csharp\nwhile (reader.Read())\n{\n    Console.WriteLine($\"{reader.GetInt32(0),-3}{reader.GetString(1)}\"); \n}\n```\n\n## Razor Pages/ASP.NET Core\n\nTo get a connection string for EF Core in Program.cs this is one method.\n\n```csharp\nbuilder.Services.AddDbContext\u003cContext\u003e(options =\u003e\n    options.UseSqlServer(builder.Configuration.GetConnectionString(\"ApplicationConnection\"))\n        .EnableSensitiveDataLogging());\n```\n\nThe following is only here to show how to create a source template for a [DbContext](https://learn.microsoft.com/en-us/dotnet/api/system.data.entity.dbcontext?view=entity-framework-6.2.0).\n\nCreate the following class where source templates reside.\n\n```csharp\ninternal class Context : DbContext\n{\n}\n```\n\n\u003e **Note**\n\u003e In this case your DbContext is named Context, change it for the DbContext used in your project.\n\n\nNow the following source templates can be used.\n\n```csharp\npublic static class AspNetCoreTemplates\n{\n    [SourceTemplate]\n    public static void connectstring(this WebApplicationBuilder builder)\n    {\n        var connectionString = builder.Configuration.GetConnectionString(\"ApplicationConnection\");\n    }\n\n    [SourceTemplate]\n    public static void connectionpool(this WebApplicationBuilder builder)\n    {\n        builder.Services.AddDbContextPool\u003cContext\u003e(options =\u003e\n            options.UseSqlServer(\n                builder.Configuration.GetConnectionString(\"ApplicationConnection\")));\n    }\n\n    [SourceTemplate]\n    public static void connection(this WebApplicationBuilder builder)\n    {\n        builder.Services.AddDbContext\u003cContext\u003e(options =\u003e\n            options.UseSqlServer(\n                builder.Configuration\n                    .GetConnectionString(\"ApplicationConnection\")));\n    }\n}\n```\nIn Program.cs type builder.connection and press \u003ckbd\u003eEnter\u003c/kbd\u003e to write the following.\n\n```csharp\npublic class Program\n{\n    public static void Main(string[] args)\n    {\n        var builder = WebApplication.CreateBuilder(args);\n\n        builder.Services.AddDbContext\u003cContext\u003e(options =\u003e\n            options.UseSqlServer(\n                builder.Configuration\n                    .GetConnectionString(\"ApplicationConnection\")));\n```\n\n## SqlClient SqlDataReader DateOnly TimeOnly\n\nUsing NuGet package Microsoft.Data.SqlClient version 5.1.1 (at the time of this article) its possible to return DateOnly and TimeOnly using SqlClient data provider.\n\nFirst create several extension methods\n\n```csharp\npublic static class SqlClientExtensions\n{\n    public static DateOnly GetDateOnly(this SqlDataReader reader, int index)\n        =\u003e reader.GetFieldValue\u003cDateOnly\u003e(index);\n\n    public static TimeOnly GetTimeOnly(this SqlDataReader reader, int index)\n        =\u003e reader.GetFieldValue\u003cTimeOnly\u003e(index);\n}\n```\n\nIn a static class add the following source template\n\n```csharp\n[SourceTemplate]\n[Macro(Target = \"dto\")]\npublic static void gdo(this SqlDataReader reader, int index)\n{\n    var dto = reader.GetDateOnly(index); \n}\n```\n\nWhere there is a SqlDataReader type and press \u003ckbd\u003eEnter\u003c/kbd\u003e \n\n```csharp\nreader.gdo\n```\n\nThe following is written, first prompting for a ordinal position in plac of **index**\n\n```csharp\nvar dto = reader.GetDateOnly(index);\n```\n\nEnter the index, press \u003ckbd\u003eTAB\u003c/kbd\u003e to optionally change the current variable name from dto to something useful.\n\n\n## Simple generic Enum source template\n\nAdd the following method to a static class\n\n```csharp\n[SourceTemplate]\n[Macro(Target = \"T\")]\n[Macro(Target = \"varName\")]\npublic static void checker\u003cT\u003e(this string sender, T type) where T : struct\n{\n    if (Enum.TryParse(sender, true, out T varName))\n    {\n            \n    }\n}\n```\n\nWhen invoked\n\n- There is a prompt for **T** to enter an enum\n- Press \u003ckbd\u003eTAB\u003c/kbd\u003e for a prompt for a out variable name\n\n**Usage**\n\n```csharp\npublic enum DemoEnum\n{\n    One,\n    Two,\n    Three\n}\n```\n\nIn your code add \n\n```csharp\nvar value = \"one\";\n```\n\nType value.checker and the following is written\n\n![output from checker](assets/figure9.png)\n\n- Enter the type\n- \u003ckbd\u003eTAB\u003c/kbd\u003e\n- Enter the variable name\n\n```csharp\nvar value = \"one\";\n\nif (Enum.TryParse(value, true, out DemoEnum result))\n{\n\n}\n```\n\n## Summary\n\nWith what has been presented a developer can use the source templates provided along with created their own templates along with knowledge that Postfix templates built into ReSharper can reduce coding time.\n\n## Source code\n\nClone the following GitHub repository and run the script under ConsoleApp1 project in the Scripts folder.\n\n## Article\n\nhttps://dev.to/karenpayneoregon/learn-resharper-postfix-and-source-templates-32lo\n\n\n\n\n\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkarenpayneoregon%2Fresharper-templates","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkarenpayneoregon%2Fresharper-templates","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkarenpayneoregon%2Fresharper-templates/lists"}