<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>.NET Core Blog &#8212; onthecode</title>
	<atom:link href="https://onthecode.co.uk/blog/category/net-core/feed" rel="self" type="application/rss+xml" />
	<link>https://onthecode.co.uk/blog/category/net-core</link>
	<description>onthecode blog</description>
	<lastBuildDate>Fri, 30 Dec 2022 00:32:38 +0000</lastBuildDate>
	<language>en-GB</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.6.3</generator>

<image>
	<url>https://onthecode.co.uk/wp-content/uploads/2019/02/onthecode-icon-1-100x100.png</url>
	<title>.NET Core Blog &#8212; onthecode</title>
	<link>https://onthecode.co.uk/blog/category/net-core</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Automate API Documentation with NSwag</title>
		<link>https://onthecode.co.uk/blog/automating-api-documentation-nswag</link>
					<comments>https://onthecode.co.uk/blog/automating-api-documentation-nswag#respond</comments>
		
		<dc:creator><![CDATA[Umut Esen]]></dc:creator>
		<pubDate>Sat, 16 Jan 2021 22:53:34 +0000</pubDate>
				<category><![CDATA[.NET Core]]></category>
		<category><![CDATA[api-development]]></category>
		<category><![CDATA[documentation]]></category>
		<guid isPermaLink="false">https://onthecode.co.uk/?p=3137</guid>

					<description><![CDATA[<p>Producing documentation is a laborious task that most developers dislike. Considering software delivery is an iterative approach, maintaining documentation becomes a full time work, especially for public APIs. For small teams and solo devs, tools like NSwag can do the heavy lifting of creating and maintaining documentation. Benefits of NSwag: Documentation based on XML code comments Interactive web-based API client using SwaggerUI3 Ability to generate API client in a wide range of languages such as Typescript, C# and Java. Getting started In this post, we will set up NSwag in a .NET Core web API. The first step is to add the NSwag.AspNetCore package to your API project. The package contains the middleware you need to add and use Swagger in Startup.cs. Inside the ConfigureServices method, register Open API document generation. If your API does not use JWT authentication, you do not need to add security configuration above. Adding this configuration produces authentication controls on the Swagger UI web interface. The next step is to use the Open API and SwaggerUI3. Again in Startup.cs, add the following code to before you map your controllers: That&#8217;s it! Swagger UI is now available on /swagger route. You should see all of your API resources, operations and code comments you have been adding to controllers and objects exposed from your API. Define SwaggerResponse If you notice the accept header in SwaggerUI is not set to application/json. This is be because Swagger does not know the return types of your endpoints. Setting SwaggerResponse on each controller action is a good habit to get into. After all, a tool is as good as you use it. This is an example controller action: Hide a resource from SwaggerUI For those &#8220;secret&#8221; resources that you do not want to show on the SwaggerUI, you can use the ApiExplorerSettings annotation. This annotation also works on controller actions to hide individual endpoints. Change swagger route The default Swagger UI route is /swagger. I personally do not like it so I change it to /docs whenever I start a new API project. Rename swagger.json In order to rename the default swagger.json specification file, you need to define your path in both the open api specification and the swagger UI. The following example produces a specification file docs.json: Expand resources SwaggerUI allows us to control the way API resources are presented on the page. By default, DocExpansion property is set to none, meaning all resources and operations are collapsed. I prefer displaying expanding resources and keeping operations collapsed, by setting DocExpansion to list. This achieves the look of Swagger Petstore. Preserve authentication header SwaggerUI provides a way for users to authenticate with the API and save the token so that it is added to each request automatically. While this is a great feature, the authentication token is wiped when the page is closed/refreshed. Having researched online, I came across a pull request on the SwaggerUI GitHub repository. User @AmirBitaraf implemented a feature toggle the preserve authentication between page refreshes. From what I can see online, this feature toggle has not been made available in NSwag. It is possible to add a key/value pair to the AdditionalSettings list available in UseSwaggerUi3 middleware. Customise object names If you use DTO objects for exposing data in your API, you will find that SwaggerUI displays the class names as they are defined. In my opinion, including keyword DTO in a class name in the documentation just adds noise. Fortunately, this can be changed with a custom schema name generator. Inside Startup.cs, configure OpenApiDocument to accept a custom name generator for SwaggerUI. NSwagNameGenerator overrides the Generate method to modify the class name. Inject custom JavaScript to SwaggerUI If, for any reason you need to manipulate SwaggerUI HTML page, you can inject a JavaScript file. This would allow further modifications such as logo replacement, colour schemes etc. If you haven&#8217;t changed the default swagger route, your path would be /swagger/hello.js. In order for the JavaScript file to be used correctly, you need to place it under wwwroot/docs/. Also, enable serving static files in your API before using SwaggerUI middleware. This approach also works for custom stylesheets, which is available with CustomStylesheetPath property. Include XML documentation when building the project Any code comment you add to your classes will appear on relevant operations within SwaggerUI interface. Usually, Visual Studio build places the XML documentation file inside the bin folder: Project/bin/debug/.netcoreapp3.1/MyProject.xml Swagger uses this file to populate its UI with your code comments. Since XML documentation is considered a dev artefact, this file is not included when the application is built remotely via dotnet build on Azure DevOps server. We can include the XML documentation file by generating it on the project root and setting its Copy to output directory property to Alyways. Right-click on Project and select &#8220;Edit project file&#8221;. Alternatively open csproj file in a text editor. Set the DocumentationFile property to a desired file name. Ensure the file name appears on its own. Save and rebuild your project. This forces Visual Studio to generate documentation XML on the root of the project. We can now include this file in the build output by adding the following to the csproj file: You can alternatively use Visual Studio user interface to make the same change via file properties. SwaggerUI will now show documentation when you publish your API. Final thoughts NSwag is an amazing tool that I use in all APIs that I work on. It saves a lot time when it comes to producing documentation and client code generation. Do you use NSwag or an alternative? I look forward to hearing your opinion in the comments!</p>
<p>The post <a href="https://onthecode.co.uk/blog/automating-api-documentation-nswag">Automate API Documentation with NSwag</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Producing documentation is a laborious task that most developers dislike. Considering software delivery is an iterative approach, maintaining documentation becomes a full time work, especially for public APIs. For small teams and solo devs, tools like <code>NSwag</code> can do the heavy lifting of creating and maintaining documentation. </p>



<p>Benefits of <code>NSwag</code>:</p>



<ul class="wp-block-list"><li>Documentation based on XML code comments</li><li>Interactive web-based API client using <code>SwaggerUI3</code></li><li>Ability to generate API client in a wide range of languages such as Typescript, C# and Java.</li></ul>






<h2 class="wp-block-heading" id="getting-started">Getting started</h2>



<p>In this post, we will set up <code>NSwag</code> in a .NET Core web API.</p>



<p>The first step is to add the <code>NSwag.AspNetCore</code> package to your API project. </p>


<pre class="wp-block-code"><span><code class="hljs language-bash">dotnet add package NSwag.AspNetCore</code></span></pre>


<p>The package contains the middleware you need to add and use Swagger in <code>Startup.cs</code>.</p>



<p>Inside the <code>ConfigureServices</code> method, register Open API document generation.</p>


<pre class="wp-block-code"><span><code class="hljs language-cs">services.AddOpenApiDocument(document =&gt;
{
    document.Version = <span class="hljs-string">"v1"</span>;
    document.Title = Configuration&#091;<span class="hljs-string">"API:Name"</span>];
    document.Description = Configuration&#091;<span class="hljs-string">"API:Description"</span>];

    <span class="hljs-comment">// For APIs that use JWT authentication</span>
    document.AddSecurity(<span class="hljs-string">"Bearer"</span>, Enumerable.Empty&lt;<span class="hljs-keyword">string</span>&gt;(), <span class="hljs-keyword">new</span> OpenApiSecurityScheme
    {
        Type = OpenApiSecuritySchemeType.ApiKey,
        Name = <span class="hljs-string">"Authorization"</span>,
        In = OpenApiSecurityApiKeyLocation.Header,
        Description = <span class="hljs-string">"Type into the textbox: Bearer {your JWT token}."</span>
    });
    document.OperationProcessors.Add(<span class="hljs-keyword">new</span> AspNetCoreOperationSecurityScopeProcessor(<span class="hljs-string">"Bearer"</span>));
});</code></span></pre>


<p>If your API does not use <code>JWT authentication</code>, you do not need to add security configuration above. Adding this configuration produces authentication controls on the Swagger UI web interface.</p>



<p>The next step is to use the <code>Open API</code> and <code>SwaggerUI3</code>. Again in <code>Startup.cs</code>, add the following code to before you map your controllers:</p>


<pre class="wp-block-code"><span><code class="hljs language-cs">app.UseOpenApi();

app.UseSwaggerUi3(cfg =&gt;
{
    cfg.DocumentTitle = <span class="hljs-string">"My Awesome API"</span>;
});

app.UseEndpoints(endpoints =&gt;
{
    endpoints.MapControllers();
});</code></span></pre>


<p>That&#8217;s it! Swagger UI is now available on <code>/swagger</code> route.</p>



<p>You should see all of your API resources, operations and code comments you have been adding to controllers and objects exposed from your API.</p>



<h2 class="wp-block-heading" id="define-swaggerresponse">Define SwaggerResponse</h2>



<p>If you notice the accept header in SwaggerUI is not set to <code>application/json</code>.</p>



<p>This is be because Swagger does not know the return types of your endpoints. Setting <code>SwaggerResponse</code> on each controller action is a good habit to get into. After all, a tool is as good as you use it.</p>



<p>This is an example controller action:</p>


<pre class="wp-block-code"><span><code class="hljs language-cs">&#091;<span class="hljs-meta">HttpGet</span>]
&#091;<span class="hljs-meta">SwaggerResponse(typeof(IEnumerable&amp;lt;BrandDto&gt;))</span>]
<span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&amp;lt;IActionResult&gt; Get(<span class="hljs-keyword">string</span> filter)
{
    <span class="hljs-keyword">var</span> brands = <span class="hljs-keyword">await</span> _brandRepository.GetAllAsync(filter);
    <span class="hljs-keyword">var</span> dtos = _mapper.Map&amp;lt;List&amp;lt;BrandDto&gt;&gt;(brands);
    <span class="hljs-keyword">return</span> Ok(dtos);
}</code></span></pre>


<h2 class="wp-block-heading" id="hide-a-resource-from-swaggerui">Hide a resource from SwaggerUI</h2>



<p>For those &#8220;secret&#8221; resources that you do not want to show on the SwaggerUI, you can use the <code>ApiExplorerSettings</code> annotation.</p>


<pre class="wp-block-code"><span><code class="hljs language-cs">&#091;<span class="hljs-meta">ApiController</span>]
&#091;<span class="hljs-meta">Route(<span class="hljs-meta-string">"v1/&#091;controller]"</span>)</span>]
&#091;<span class="hljs-meta">ApiExplorerSettings(IgnoreApi = true)</span>]
&#091;<span class="hljs-meta">Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)</span>]
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">SecretController</span> : <span class="hljs-title">ControllerBase</span>
{}</code></span></pre>


<p>This annotation also works on controller actions to hide individual endpoints.</p>



<h2 class="wp-block-heading" id="change-swagger-route">Change swagger route</h2>



<p>The default Swagger UI route is <code>/swagger</code>. I personally do not like it so I change it to <code>/docs</code> whenever I start a new API project.</p>


<pre class="wp-block-code"><span><code class="hljs language-cs">app.UseSwaggerUi3(cfg =&gt;
{
    cfg.Path = <span class="hljs-string">"/docs"</span>;
});</code></span></pre>


<h2 class="wp-block-heading" id="rename-swagger-json">Rename swagger.json</h2>



<p>In order to rename the default swagger.json specification file, you need to define your path in both the open api specification and the swagger UI.</p>



<p>The following example produces a specification file <code>docs.json</code>:</p>


<pre class="wp-block-code"><span><code class="hljs language-cs">app.UseOpenApi(cfg =&gt;
{
    cfg.Path = <span class="hljs-string">"/docs/{documentName}/doc.json"</span>; ;
});

app.UseSwaggerUi3(cfg =&gt;
{
    cfg.DocumentPath = <span class="hljs-string">"/docs/{documentName}/doc.json"</span>;
});</code></span></pre>


<h2 class="wp-block-heading" id="expand-resources">Expand resources</h2>



<p>SwaggerUI allows us to control the way API resources are presented on the page. By default, <code>DocExpansion</code> property is set to <code>none</code>, meaning all resources and operations are collapsed. </p>



<p>I prefer displaying expanding resources and keeping operations collapsed, by setting <code>DocExpansion</code> to <code>list</code>. This achieves the look of <a href="https://petstore.swagger.io" target="_blank" rel="noreferrer noopener nofollow">Swagger Petstore</a>.</p>


<pre class="wp-block-code"><span><code class="hljs language-cs">app.UseSwaggerUi3(cfg =&gt;
{
    cfg.DocExpansion = <span class="hljs-string">"list"</span>;
});</code></span></pre>


<h2 class="wp-block-heading" id="preserve-authentication-header">Preserve authentication header</h2>



<p>SwaggerUI provides a way for users to authenticate with the API and save the token so that it is added to each request automatically. </p>



<p>While this is a great feature, the authentication token is wiped when the page is closed/refreshed. </p>



<p>Having researched online, I came across a <a href="https://github.com/swagger-api/swagger-ui/pull/5939" target="_blank" rel="noreferrer noopener nofollow">pull request</a> on the SwaggerUI GitHub repository. User <a href="https://github.com/AmirBitaraf" target="_blank" rel="noreferrer noopener nofollow">@AmirBitaraf</a> implemented a feature toggle the preserve authentication between page refreshes. </p>



<p>From what I can see online, this feature toggle has not been made available in NSwag. It is possible to add a key/value pair to the <code>AdditionalSettings</code> list available in <code>UseSwaggerUi3</code> middleware. </p>


<pre class="wp-block-code"><span><code class="hljs language-cs">app.UseSwaggerUi3(cfg =&gt;
{
    cfg.AdditionalSettings.Add(<span class="hljs-string">"persistAuthorization"</span>, <span class="hljs-literal">true</span>);
});</code></span></pre>


<h2 class="wp-block-heading" id="customise-object-names">Customise object names</h2>



<p>If you use DTO objects for exposing data in your API, you will find that SwaggerUI displays the class names as they are defined. In my opinion, including keyword <code>DTO</code> in a class name in the documentation just adds noise. </p>



<p>Fortunately, this can be changed with a custom schema name generator.</p>



<p>Inside <code>Startup.cs</code>, configure <code>OpenApiDocument</code> to accept a custom name generator for SwaggerUI.</p>


<pre class="wp-block-code"><span><code class="hljs language-cs">services.AddOpenApiDocument(document =&gt;
{
    document.SchemaNameGenerator = <span class="hljs-keyword">new</span> NSwagNameGenerator();
});</code></span></pre>


<p><code>NSwagNameGenerator</code> overrides the <code>Generate</code> method to modify the class name.</p>


<pre class="wp-block-code"><span><code class="hljs language-cs"><span class="hljs-keyword">internal</span> <span class="hljs-keyword">class</span> <span class="hljs-title">NSwagNameGenerator</span> : <span class="hljs-title">DefaultSchemaNameGenerator</span>, <span class="hljs-title">ISchemaNameGenerator</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">string</span> <span class="hljs-title">Generate</span>(<span class="hljs-params">Type type</span>)</span>
    {
        <span class="hljs-keyword">return</span> type.FullName.Replace(<span class="hljs-string">"Dto"</span>, <span class="hljs-string">""</span>);
    }
}</code></span></pre>


<h2 class="wp-block-heading" id="inject-custom-javascript-to-swaggerui">Inject custom JavaScript to SwaggerUI</h2>



<p>If, for any reason you need to manipulate SwaggerUI HTML page, you can inject a JavaScript file. This would allow further modifications such as logo replacement, colour schemes etc.</p>


<pre class="wp-block-code"><span><code class="hljs language-cs">app.UseSwaggerUi3(cfg =&gt;
{
    cfg.CustomJavaScriptPath = <span class="hljs-string">"/docs/hello.js"</span>;
});</code></span></pre>


<p>If you haven&#8217;t changed the default swagger route, your path would be <code>/swagger/hello.js</code>.</p>



<p>In order for the JavaScript file to be used correctly, you need to place it under <code>wwwroot/docs/</code>.</p>



<p>Also, enable serving static files in your API before using SwaggerUI middleware.</p>


<pre class="wp-block-code"><span><code class="hljs language-cs">app.UseStaticFiles();</code></span></pre>


<p>This approach also works for custom stylesheets, which is available with <code>CustomStylesheetPath</code> property.</p>



<h2 class="wp-block-heading" id="include-xml-documentation-when-building-the-project">Include XML documentation when building the project </h2>



<p>Any code comment you add to your classes will appear on relevant operations within SwaggerUI interface. Usually, Visual Studio build places the XML documentation file inside the bin folder:</p>



<p><code>Project/bin/debug/.netcoreapp3.1/MyProject.xml</code></p>



<p>Swagger uses this file to populate its UI with your code comments. Since XML documentation is considered a dev artefact, this file is not included when the application is built remotely via <code>dotnet build</code> on Azure DevOps server.</p>



<p>We can include the XML documentation file by generating it on the project root and setting its <code>Copy to output directory</code> property to <code>Alyways</code>.</p>



<ol class="wp-block-list"><li>Right-click on Project and select &#8220;Edit project file&#8221;. Alternatively open <code>csproj</code> file in a text editor.</li><li>Set the <code>DocumentationFile</code> property to a desired file name. Ensure the file name appears on its own.</li><li>Save and rebuild your project.</li></ol>


<pre class="wp-block-code"><span><code class="hljs language-xml"><span class="hljs-meta">&lt;?xml version="1.0" encoding="utf-8"?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">Project</span> <span class="hljs-attr">Sdk</span>=<span class="hljs-string">"Microsoft.NET.Sdk.Web"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">PropertyGroup</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">TargetFramework</span>&gt;</span>netcoreapp3.1<span class="hljs-tag">&lt;/<span class="hljs-name">TargetFramework</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">PropertyGroup</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">PropertyGroup</span> <span class="hljs-attr">Condition</span>=<span class="hljs-string">" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">DocumentationFile</span>&gt;</span>MyProject.API.xml<span class="hljs-tag">&lt;/<span class="hljs-name">DocumentationFile</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">PropertyGroup</span>&gt;</span>
...
<span class="hljs-tag">&lt;/<span class="hljs-name">Project</span>&gt;</span></code></span></pre>


<p>This forces Visual Studio to generate documentation XML on the root of the project. We can now include this file in the build output by adding the following to the <code>csproj</code> file:</p>


<pre class="wp-block-code"><span><code class="hljs language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">ItemGroup</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">None</span> <span class="hljs-attr">Update</span>=<span class="hljs-string">"MyProject.API.xml"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">CopyToOutputDirectory</span>&gt;</span>Always<span class="hljs-tag">&lt;/<span class="hljs-name">CopyToOutputDirectory</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">None</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">ItemGroup</span>&gt;</span></code></span></pre>


<p>You can alternatively use Visual Studio user interface to make the same change via file properties.</p>



<p>SwaggerUI will now show documentation when you publish your API.</p>



<h2 class="wp-block-heading" id="final-thoughts">Final thoughts</h2>



<p>NSwag is an amazing tool that I use in all APIs that I work on. It saves a lot time when it comes to producing documentation and client code generation. Do you use NSwag or an alternative? I look forward to hearing your opinion in the comments!</p>
<p>The post <a href="https://onthecode.co.uk/blog/automating-api-documentation-nswag">Automate API Documentation with NSwag</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://onthecode.co.uk/blog/automating-api-documentation-nswag/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Generating a SQL Database with Entity Framework Core in a Web API Project</title>
		<link>https://onthecode.co.uk/blog/generating-sql-database-with-entity-framework-core-web-api</link>
					<comments>https://onthecode.co.uk/blog/generating-sql-database-with-entity-framework-core-web-api#respond</comments>
		
		<dc:creator><![CDATA[Umut Esen]]></dc:creator>
		<pubDate>Thu, 14 Jan 2021 14:57:57 +0000</pubDate>
				<category><![CDATA[.NET Core]]></category>
		<guid isPermaLink="false">https://onthecode.co.uk/?p=3110</guid>

					<description><![CDATA[<p>Learn how to generate a database with a code-first flow using EntityFramework Core in a Web API project. TL;DR:&#160;This article will show you how to build your Web API with the new ASP.NET Core 3.1 and how to integrate with EntityFramework Core in order to provide a backing database for retaining data. Following the steps described in this tutorial, you will end up building a simple Web API project, whose full code you can find&#160;in this GitHub repository. Create an API in Visual Studio The first step is to create an API solution in Visual Studio. If you already have a project in place, skip to the next step. Before starting to create an API, ensure that you have Visual Studio installed. This will bring along the .NET Core SDK and required dependencies. These instructions are created using Visual Studio for Mac with .Net Core 3.1. If you are on Windows, the steps are likely to be similar. In Visual Studio, click File &#62; New solution and select API template. Next step is to give your project a name and configure the template. You should now see the project structure in Visual Studio solution explorer. Go ahead and launch the API against a browser, which should open a new window with sample data coming from the WeatherForecastController. Now that we have an API in place, we are ready to generate a database using EntityFramework Core. Add NuGet packages The following NuGet packages exist in the nuget.org package feed. This should already be configured in Visual Studio. Navigate to Manage NuGet packages window by right clicking on the solution and search for the packages above. You may be asked to install other EntityFrameworkCore.* packages as you install these packages. Create database context In order for EntityFramework to create tables for our model classes, we need to create a class that inherits from DbContext. Through conventions, EntityFramework will recognise the DbSet properties declared in the context and create/update table SQL table definitions accordingly. AppDbContext should live in a folder called Data or Infrastructure, to help you establish nicely separated namespaces. This is also a good place to define column restrictions, manual relationship setup etc. via OnModelCreating hook. Register the context at Startup The next step is to register the context with the Startup.cs file as shown below. Notice the call to UseSqlServer method, where I specify the connection string from the configuration file. By default, appsettings.json is the config file used in non-development environment, while appsettings.Development.json is used for development environment. These configuration files should have relevant connection strings. An example of a development configuration is below. Generate first migration A migration contains a set of changes and a rollback plan for EntityFramework to execute. Every time you make a change to DbSet classes, a migration needs to be created to allow EntityFramework to keep the database up to date. To generate your first migration, open a terminal window and navigate to project folder. Then run the migration command below. Running commands above will create a Migrations folder in your project, containing files that has instructions for EntityFramework to generate the database. Migrate database on startup At this point, your database is still not created. That is because we have not instructed EntityFramework Core to run the first migration we generated. I prefer to auto-migrate the database when the API starts, instead of manually running migrations. This has the added benefit of not having to run migrations against remote environments such as staging/prod. As soon as the API starts, the database will be created/migrated by EntityFramework. The first entry point of the API, Program.cs, contains a Main method, which is responsible for building the web host to start the API. This makes it a great place to run our auto-migration code to keep the database up to date. The code above pulls out the context we registered in Startup.cs and invokes Migrate to run all of the migrations in the project. When you run the API, the database should be created with tables matching DbSet properties in the context file.</p>
<p>The post <a href="https://onthecode.co.uk/blog/generating-sql-database-with-entity-framework-core-web-api">Generating a SQL Database with Entity Framework Core in a Web API Project</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></description>
										<content:encoded><![CDATA[</p>
<p>Learn how to generate a database with a code-first flow using EntityFramework Core in a Web API project. </p>
</p>
<p><strong>TL;DR:</strong>&nbsp;This article will show you how to build your Web API with the new ASP.NET Core 3.1 and how to integrate with EntityFramework Core in order to provide a backing database for retaining data. Following the steps described in this tutorial, you will end up building a simple Web API project, whose full code you can find&nbsp;<a rel="noreferrer noopener" href="#" target="_blank">in this GitHub repository</a>.</p>
</p>
<p>
</p>
</p>
<h2 class="wp-block-heading" id="create-an-api-in-visual-studio">Create an API in Visual Studio</h2>
</p>
<p>The first step is to create an API solution in Visual Studio. If you already have a project in place, skip to the next step<strong>.</strong></p>
</p>
<p>Before starting to create an API, ensure that you have Visual Studio installed. This will bring along the .NET Core SDK and required dependencies. These instructions are created using Visual Studio for Mac with .Net Core 3.1. If you are on Windows, the steps are likely to be similar. </p>
</p>
<p>In Visual Studio, click File &gt; New solution and select API template.</p>
</p>
<figure class="wp-block-image size-large is-resized"><img fetchpriority="high" decoding="async" src="https://onthecode.co.uk/wp-content/uploads/2021/01/choose-api-template-1024x774.png" alt="" class="wp-image-3122" width="522" height="394" srcset="https://onthecode.co.uk/wp-content/uploads/2021/01/choose-api-template-1024x774.png 1024w, https://onthecode.co.uk/wp-content/uploads/2021/01/choose-api-template-300x227.png 300w, https://onthecode.co.uk/wp-content/uploads/2021/01/choose-api-template-768x581.png 768w, https://onthecode.co.uk/wp-content/uploads/2021/01/choose-api-template-1536x1161.png 1536w, https://onthecode.co.uk/wp-content/uploads/2021/01/choose-api-template.png 2026w" sizes="(max-width: 522px) 100vw, 522px" /><figcaption>Choose .NET Core API template when creating the project</figcaption></figure>
</p>
<p>Next step is to give your project a name and configure the template.</p>
</p>
<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://onthecode.co.uk/wp-content/uploads/2021/01/configure-template-1024x772.png" alt="" class="wp-image-3124" width="527" height="397" srcset="https://onthecode.co.uk/wp-content/uploads/2021/01/configure-template-1024x772.png 1024w, https://onthecode.co.uk/wp-content/uploads/2021/01/configure-template-300x226.png 300w, https://onthecode.co.uk/wp-content/uploads/2021/01/configure-template-768x579.png 768w, https://onthecode.co.uk/wp-content/uploads/2021/01/configure-template-1536x1158.png 1536w, https://onthecode.co.uk/wp-content/uploads/2021/01/configure-template.png 2032w" sizes="(max-width: 527px) 100vw, 527px" /><figcaption>Configure API template</figcaption></figure>
</p>
<p>You should now see the project structure in Visual Studio solution explorer.</p>
</p>
<figure class="wp-block-image size-large is-resized"><img decoding="async" src="https://onthecode.co.uk/wp-content/uploads/2021/01/solution-explorer-1024x674.png" alt="" class="wp-image-3125" width="465" height="305" srcset="https://onthecode.co.uk/wp-content/uploads/2021/01/solution-explorer-1024x674.png 1024w, https://onthecode.co.uk/wp-content/uploads/2021/01/solution-explorer-300x198.png 300w, https://onthecode.co.uk/wp-content/uploads/2021/01/solution-explorer-768x506.png 768w, https://onthecode.co.uk/wp-content/uploads/2021/01/solution-explorer.png 1078w" sizes="(max-width: 465px) 100vw, 465px" /></figure>
</p>
<p>Go ahead and launch the API against a browser, which should open a new window with sample data coming from the <code>WeatherForecastController</code>.</p>
</p>
<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="819" height="115" src="https://onthecode.co.uk/wp-content/uploads/2021/01/sample-api-response.png" alt="" class="wp-image-3126" srcset="https://onthecode.co.uk/wp-content/uploads/2021/01/sample-api-response.png 819w, https://onthecode.co.uk/wp-content/uploads/2021/01/sample-api-response-300x42.png 300w, https://onthecode.co.uk/wp-content/uploads/2021/01/sample-api-response-768x108.png 768w" sizes="(max-width: 819px) 100vw, 819px" /><figcaption>API response in browser</figcaption></figure>
</p>
<p>Now that we have an API in place, we are ready to generate a database using EntityFramework Core.</p>
</p>
<h2 class="wp-block-heading" id="add-nuget-packages">Add NuGet packages</h2>
</p>
<p>The following NuGet packages exist in the nuget.org package feed. This should already be configured in Visual Studio.</p>
</p>
<pre class="wp-block-code"><code>Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Design</code></pre>
</p>
<p>Navigate to Manage NuGet packages window by right clicking on the solution and search for the packages above.</p>
</p>
<figure class="wp-block-image size-large is-resized"><img loading="lazy" decoding="async" src="https://onthecode.co.uk/wp-content/uploads/2021/01/manage-nuget-packages.png" alt="" class="wp-image-3127" width="527" height="374" srcset="https://onthecode.co.uk/wp-content/uploads/2021/01/manage-nuget-packages.png 912w, https://onthecode.co.uk/wp-content/uploads/2021/01/manage-nuget-packages-300x213.png 300w, https://onthecode.co.uk/wp-content/uploads/2021/01/manage-nuget-packages-768x547.png 768w" sizes="(max-width: 527px) 100vw, 527px" /></figure>
</p>
<p>You may be asked to install other EntityFrameworkCore.* packages as you install these packages. </p>
</p>
<h2 class="wp-block-heading" id="create-database-context">Create database context</h2>
</p>
<p>In order for EntityFramework to create tables for our model classes, we need to create a class that inherits from <code>DbContext</code>.</p>
</p>
<pre class="wp-block-code"><code>public class AppDbContext : DbContext
{
    public DbSet&lt;Book&gt; Books { get; set; }

    public AppDbContext(DbContextOptions&lt;AppDbContext&gt; options) : base(options)
    {
    }
}</code></pre>
</p>
<p>Through conventions, EntityFramework will recognise the <code>DbSet</code> properties declared in the context and create/update table <code>SQL</code> table definitions accordingly. <code>AppDbContext</code> should live in a folder called <code>Data</code> or <code>Infrastructure</code>, to help you establish nicely separated namespaces.</p>
</p>
<p>This is also a good place to define column restrictions, manual relationship setup etc. via <code>OnModelCreating</code> hook.</p>
</p>
<h2 class="wp-block-heading" id="register-the-context-at-startup">Register the context at Startup</h2>
</p>
<p>The next step is to register the context with the <code>Startup.cs</code> file as shown below. </p>
</p>
<pre class="wp-block-code"><code>public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext&lt;AppDbContext&gt;(cfg =&gt;
                cfg.UseSqlServer(Configuration.GetConnectionString("DbConnection"))
        );

    // omitted for brevity..
}</code></pre>
</p>
<p>Notice the call to <code>UseSqlServer</code> method, where I specify the connection string from the configuration file. By default, <code>appsettings.json</code> is the config file used in non-development environment, while <code>appsettings.Development.json</code> is used for development environment. </p>
</p>
<p>These configuration files should have relevant connection strings. An example of a development configuration is below.</p>
</p>
<pre class="wp-block-code"><code>{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "ConnectionStrings": {
    "DbConnection": "Server=localhost,1433;Database=MyDatabase;User=sa;Password=RandomPassword@1"
  }
}</code></pre>
</p>
<h2 class="wp-block-heading" id="generate-first-migration">Generate first migration</h2>
</p>
<p>A migration contains a set of changes and a rollback plan for EntityFramework to execute. Every time you make a change to <code>DbSet</code> classes, a migration needs to be created to allow EntityFramework to keep the database up to date. </p>
</p>
<p>To generate your first migration, open a terminal window and navigate to project folder. Then run the migration command below.</p>
</p>
<pre class="wp-block-code"><code>cd myprojectpath
dotnet ef migrations add FirstMigration</code></pre>
</p>
<p>Running commands above will create a <code>Migrations</code> folder in your project, containing files that has instructions for EntityFramework to generate the database.</p>
</p>
<h2 class="wp-block-heading" id="migrate-database-on-startup">Migrate database on startup</h2>
</p>
<p>At this point, your database is still not created. That is because we have not instructed EntityFramework Core to run the first migration we generated. </p>
</p>
<p>I prefer to auto-migrate the database when the API starts, instead of manually running migrations. This has the added benefit of not having to run migrations against remote environments such as staging/prod. As soon as the API starts, the database will be created/migrated by EntityFramework. </p>
</p>
<p>The first entry point of the API, <code>Program.cs</code>, contains a <code>Main</code> method, which is responsible for building the web host to start the API. This makes it a great place to run our auto-migration code to keep the database up to date. </p>
</p>
<pre class="wp-block-code"><code>public static void Main(string&#091;] args)
{
    var host = CreateHostBuilder(args).Build();

    using (var scope = host.Services.CreateScope())
    {
        var services = scope.ServiceProvider;
        var context = services.GetService&lt;AppDbContext&gt;();
        context.Database.Migrate();
    }

    host.Run();
}

//.. rest of the code</code></pre>
</p>
<p>The code above pulls out the context we registered in <code>Startup.cs</code> and invokes <code>Migrate</code> to run all of the migrations in the project. </p>
</p>
<p>When you run the API, the database should be created with tables matching <code>DbSet</code> properties in the context file. </p>
</p>
<figure class="wp-block-image aligncenter size-large"><img loading="lazy" decoding="async" width="407" height="211" src="https://onthecode.co.uk/wp-content/uploads/2021/01/generated-database.png" alt="" class="wp-image-3134" srcset="https://onthecode.co.uk/wp-content/uploads/2021/01/generated-database.png 407w, https://onthecode.co.uk/wp-content/uploads/2021/01/generated-database-300x156.png 300w, https://onthecode.co.uk/wp-content/uploads/2021/01/generated-database-330x170.png 330w" sizes="(max-width: 407px) 100vw, 407px" /></figure>
</p></p>
<p>The post <a href="https://onthecode.co.uk/blog/generating-sql-database-with-entity-framework-core-web-api">Generating a SQL Database with Entity Framework Core in a Web API Project</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://onthecode.co.uk/blog/generating-sql-database-with-entity-framework-core-web-api/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Enable CORS in .NET Core</title>
		<link>https://onthecode.co.uk/blog/enable-cors-net-core</link>
					<comments>https://onthecode.co.uk/blog/enable-cors-net-core#respond</comments>
		
		<dc:creator><![CDATA[Umut Esen]]></dc:creator>
		<pubDate>Wed, 07 Oct 2020 21:20:03 +0000</pubDate>
				<category><![CDATA[.NET Core]]></category>
		<category><![CDATA[cors]]></category>
		<category><![CDATA[same-origin]]></category>
		<guid isPermaLink="false">https://onthecode.co.uk/?p=3090</guid>

					<description><![CDATA[<p>Due to the same-origin policy, most browsers restrict making requests to different domains than the originally served the website. This is a security feature that prevents a harmful site from accessing sensitive data on other sites. If you are developing an API though, cross-origin requests (CORS) are something you want to allow to make sure client applications can use the API. Using a named CORS policy has been my preferred approach to enable CORS in .NET Core. This is simply because it applies the CORS policy to all endpoints in the API. Code snippet below shows that I am opening up the API to the whole world: Unfortunately, this does not appear to work and I get the following error when an AJAX request is issued in Chrome: [Error] Access to XMLHttpRequest at &#8216;https://api.com/end-point&#8217; from origin &#8216;https://mywebsite.com&#8217; has been blocked by CORS policy: Response to preflight request doesn&#8217;t pass access control check: No &#8216;Access-Control-Allow-Origin&#8217; header is present on the requested resource. Safari on Mac OS logs the following errors: [Error] XMLHttpRequest cannot load https://staging.xyz.com/api/orders due to access control checks. [Error] Failed to load resource: Preflight response is not successful AllowAnyOrigin&#160;affects preflight requests and the&#160;Access-Control-Allow-Origin&#160;header.&#160;It sets the header to be a wildcard '*', which is ignored by browser as it is considered insecure. Solution The solution is to avoid using AllowAnyOrigin when defining the CORS policy and specify the origins that will consume your API. The origin can be a full domain such as above or a sub domain. It is also possible to use wildcard subdomains:</p>
<p>The post <a href="https://onthecode.co.uk/blog/enable-cors-net-core">Enable CORS in .NET Core</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></description>
										<content:encoded><![CDATA[</p>
<p>Due to the <a href="https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy" target="_blank" rel="noreferrer noopener nofollow">same-origin policy</a>, most browsers restrict making requests to different domains than the originally served the website. This is a security feature that prevents a harmful site from accessing sensitive data on other sites. If you are developing an API though, cross-origin requests (CORS) are something you want to allow to make sure client applications can use the API. </p>
</p>
<p>Using a named CORS policy has been my preferred approach to enable CORS in .NET Core. This is simply because it applies the CORS policy to all endpoints in the API. </p>
</p>
<p>Code snippet below shows that I am opening up the API to the whole world:</p>
</p>
<pre class="wp-block-code"><code>public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(o =&gt; o.AddPolicy("CorsPolicy", builder =&gt;
    {
        builder.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials();
    }));
    ...
}
public void Configure(IApplicationBuilder app,IHostingEnvironment env)
{
    ...
    app.UseCors("CorsPolicy");
    ...
}</code></pre>
</p>
<p>Unfortunately, this does not appear to work and I get the following error when an AJAX request is issued in Chrome:</p>
</p>
<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>[Error] Access to XMLHttpRequest at &#8216;https://api.com/end-point&#8217; from origin &#8216;https://mywebsite.com&#8217; has been blocked by CORS policy: Response to preflight request doesn&#8217;t pass access control check: <strong>No &#8216;Access-Control-Allow-Origin&#8217;</strong> header is present on the requested resource.</p>
</blockquote>
</p>
<p>Safari on Mac OS logs the following errors:</p>
</p>
<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>[Error] XMLHttpRequest cannot load https://staging.xyz.com/api/orders due to access control checks.</p>
<p>[Error] Failed to load resource: <strong>Preflight response is not successful</strong></p>
</blockquote>
</p>
<p><code>AllowAnyOrigin</code>&nbsp;affects preflight requests and the&nbsp;<code>Access-Control-Allow-Origin</code>&nbsp;header.&nbsp;It sets the header to be a wildcard <code>'*'</code>, which is ignored by browser as it is considered insecure.</p>
</p>
<h2 class="wp-block-heading" id="solution">Solution</h2>
</p>
<p>The solution is to avoid using <code>AllowAnyOrigin</code> when defining the CORS policy and specify the origins that will consume your API.</p>
</p>
<pre class="wp-block-code"><code>services.AddCors(o =&gt; o.AddPolicy("CorsPolicy", builder =&gt;
{
    builder.WithOrigins("https://mywebsite.com")
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials();
}));</code></pre>
</p>
<p>The origin can be a full domain such as above or a sub domain. It is also possible to use wildcard subdomains:</p>
</p>
<pre class="wp-block-code"><code>services.AddCors(o =&gt; o.AddPolicy("CorsPolicy", builder =&gt;
{
    builder.WithOrigins("https://*.mywebsite.com")
        .SetIsOriginAllowedToAllowWildcardSubdomains();
}));</code></pre>
</p></p>
<p>The post <a href="https://onthecode.co.uk/blog/enable-cors-net-core">Enable CORS in .NET Core</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://onthecode.co.uk/blog/enable-cors-net-core/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Installing SQL Server 2019 on MacOS</title>
		<link>https://onthecode.co.uk/blog/sql-server-2019-using-mac-mojave</link>
					<comments>https://onthecode.co.uk/blog/sql-server-2019-using-mac-mojave#comments</comments>
		
		<dc:creator><![CDATA[Umut Esen]]></dc:creator>
		<pubDate>Sat, 19 Jan 2019 22:24:44 +0000</pubDate>
				<category><![CDATA[.NET Core]]></category>
		<category><![CDATA[docker]]></category>
		<category><![CDATA[sql on mac]]></category>
		<category><![CDATA[sql server 2019]]></category>
		<guid isPermaLink="false">https://onthecode.co.uk/?p=8</guid>

					<description><![CDATA[<p>Installing with SQL Server on a non-Microsoft platform was a dream just a few years ago. With the release of SQL Server 2017, Microsoft made it possible to directly install SQL Server on Unix-based operating systems. Since MacOS is Unix-based, we can directly install SQL Server on it using Docker. In this post, we will install the preview version of SQL Server 2019 on macOS Mojave. We will use Docker to run SQL Server and look at available tools to work with a SQL database. Install Docker Firstly, download and install Docker Desktop for Mac. It is free for personal projects. Install it by opening the .dmg file and move the Docker icon into Applications folder as shown below: Launch Docker and you should see the docker icon in the MacOS menu bar. Download SQL Server 2019 Open the Terminal and execute the following to pull the preview version of SQL Server 2019 container image for Ubuntu. The container image is a substantial download (~2GB) so it might take a while. Consider making yourself a cuppa in the mean time! Install SQL Server Install the downloaded docker image using the following in the terminal. A few things to note here: -e ACCEPT_EULA=Y indicates that you agree to Microsoft&#8217;s EUA (End User Licence Agreement). -e SA_PASSWORD is where you set the system administrator password for SQL Server. The password must be at least 8 characters long and contain characters from three of the following four sets: uppercase letters, lowercase letters, numbers &#38; symbols. -p flag allows the 1433 to be used as the TCP port number. --name sets the instance name to sqlserver2019. -d runs docker in deamon mode, used to run the container in the background. Once the command executes, you can confirm the installation by running docker ps -a Start the container with command: Executing SQL Queries Microsoft recommends the use of sqlcmd to connect to SQL Server on Mac. Use the following command to start an interactive shell inside your newly installed container: Once you are in the container, you can finally connect to SQL Server locally: If successful, you will get &#62;1 response, which allows you to run SQL commands. Execute the following SQL commands one by one: You can pretty much run any SQL command using sqlcmd. Although the command line works well, I prefer to use a GUI-based application to manage databases. SQL Server Management Studio is my primary choice for managing databases on Windows but it comes to mac, I use SQLPro for MSSQL nowadays. Another alternative is DataGrip from JetBrains, which is pretty close to SSMS experience in Windows. Connection string example If your application needs to connect to SQL Server locally, the following connection string will be useful: So there you have it, you can now work with SQL Server databases natively on your Mac!</p>
<p>The post <a href="https://onthecode.co.uk/blog/sql-server-2019-using-mac-mojave">Installing SQL Server 2019 on MacOS</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></description>
										<content:encoded><![CDATA[</p>
<p>Installing with SQL Server on a non-Microsoft platform was a dream just a few years ago. With the release of SQL Server 2017, Microsoft made it possible to directly install SQL Server on Unix-based operating systems. Since MacOS is Unix-based, we can directly install SQL Server on it using Docker. </p>
</p>
<p>In this post, we will install the preview version of SQL Server 2019 on macOS Mojave. We will use Docker to run SQL Server and look at available tools to work with a SQL database.</p>
</p>
<p>
</p>
</p>
<h2 class="wp-block-heading" id="install-docker">Install Docker</h2>
</p>
<p>Firstly, <a href="https://hub.docker.com/editions/community/docker-ce-desktop-mac?tab=description" target="_blank" rel="noreferrer noopener">download</a> and install Docker Desktop for Mac. It is free for personal projects. </p>
</p>
<p>Install it by opening the <code>.dmg</code> file and move the Docker icon into Applications folder as shown below:</p>
</p>
<figure class="wp-block-image aligncenter"><img loading="lazy" decoding="async" width="1024" height="556" src="https://onthecode.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-19-at-22.25.48-1024x556.png" alt="Installing Docker" class="wp-image-30" srcset="https://onthecode.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-19-at-22.25.48-1024x556.png 1024w, https://onthecode.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-19-at-22.25.48-300x163.png 300w, https://onthecode.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-19-at-22.25.48-768x417.png 768w, https://onthecode.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-19-at-22.25.48-700x380.png 700w, https://onthecode.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-19-at-22.25.48.png 1664w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption>Installing Docker</figcaption></figure>
</p>
<p>Launch Docker and you should see the docker icon in the MacOS menu bar.</p>
</p>
<h2 class="wp-block-heading" id="download-sql-server-2019">Download SQL Server 2019</h2>
</p>
<p>Open the Terminal and execute the following to pull the preview version of SQL Server 2019 container image for Ubuntu. </p>
</p>
<pre class="wp-block-code"><code>docker pull mcr.microsoft.com/mssql/server:2019-latest</code></pre>
</p>
<p>The container image is a substantial download (~2GB) so it might take a while. </p>
</p>
<p>Consider making yourself a cuppa in the mean time!</p>
</p>
<h2 class="wp-block-heading" id="install-sql-server">Install SQL Server</h2>
</p>
<p>Install the downloaded docker image using the following in the terminal.</p>
</p>
<pre class="wp-block-code"><code>sudo docker run -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=MyStrongPassword@1' -p 1433:1433 --name sqlserver2019 -d mcr.microsoft.com/mssql/server:2019-latest</code></pre>
</p>
<p>A few things to note here:</p>
</p>
<ol class="wp-block-list">
<li><code>-e ACCEPT_EULA=Y</code> indicates that you agree to Microsoft&#8217;s EUA (End User Licence Agreement).</li>
<li><code>-e SA_PASSWORD</code> is where you set the system administrator password for SQL Server. The password must be at least 8 characters long and contain characters from three of the following four sets: uppercase letters, lowercase letters, numbers &amp; symbols.</li>
<li><code>-p</code> flag allows the 1433 to be used as the TCP port number.</li>
<li><code>--name</code> sets the instance name to sqlserver2019.</li>
<li><code>-d</code> runs docker in deamon mode, used to run the container in the background.</li>
</ol>
</p>
<p>Once the command executes, you can confirm the installation by running <code>docker ps -a</code></p>
</p>
<figure class="wp-block-image aligncenter size-large is-resized"><img loading="lazy" decoding="async" src="https://onthecode.co.uk/wp-content/uploads/2022/03/Screenshot-2022-03-08-at-20.30.25-1024x84.png" alt="SQL Server running in Docker" class="wp-image-4440" width="573" height="46" srcset="https://onthecode.co.uk/wp-content/uploads/2022/03/Screenshot-2022-03-08-at-20.30.25-1024x84.png 1024w, https://onthecode.co.uk/wp-content/uploads/2022/03/Screenshot-2022-03-08-at-20.30.25-300x25.png 300w, https://onthecode.co.uk/wp-content/uploads/2022/03/Screenshot-2022-03-08-at-20.30.25-768x63.png 768w, https://onthecode.co.uk/wp-content/uploads/2022/03/Screenshot-2022-03-08-at-20.30.25.png 1266w" sizes="(max-width: 573px) 100vw, 573px" /><figcaption>SQL Server running in Docker</figcaption></figure>
</p>
<p>Start the container with command:</p>
</p>
<pre class="wp-block-code"><code>docker start sqlserver2019</code></pre>
</p>
<h2 class="wp-block-heading" id="execute-sql-queries">Executing SQL Queries</h2>
</p>
<p>Microsoft recommends the use of <code>sqlcmd</code> to connect to SQL Server on Mac. </p>
</p>
<p>Use the following command to start an interactive shell inside your newly installed container:</p>
</p>
<pre class="wp-block-code"><code>sudo docker exec -it sqlserver2019 "bash"</code></pre>
</p>
<p>Once you are in the container, you can finally connect to SQL Server locally:</p>
</p>
<pre class="wp-block-code"><code>/opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P 'MyStrongPassword@1'</code></pre>
</p>
<p>If successful, you will get <code>&gt;1</code> response, which allows you to run SQL commands. </p>
</p>
<p>Execute the following SQL commands one by one:</p>
</p>
<pre class="wp-block-code"><code>CREATE DATABASE MyDatabase
SELECT Name from sys.Databases
GO</code></pre>
</p>
<figure class="wp-block-image aligncenter"><img loading="lazy" decoding="async" width="1024" height="604" src="https://onthecode.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-19-at-22.02.06-1024x604.png" alt="Testing sql server 2019 on mac" class="wp-image-26" srcset="https://onthecode.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-19-at-22.02.06-1024x604.png 1024w, https://onthecode.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-19-at-22.02.06-300x177.png 300w, https://onthecode.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-19-at-22.02.06-768x453.png 768w, https://onthecode.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-19-at-22.02.06-700x413.png 700w, https://onthecode.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-19-at-22.02.06.png 1562w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption>Testing SQL Server 2019 on Mac</figcaption></figure>
</p>
<p>You can pretty much run any SQL command using <code>sqlcmd</code>. </p>
</p>
<p>Although the command line works well, I prefer to use a GUI-based application to manage databases. SQL Server Management Studio is my primary choice for managing databases on Windows but it comes to mac, I use <a href="https://www.macsqlclient.com">SQLPro for MSSQL</a>  nowadays. </p>
</p>
<p>Another alternative is <a href="https://www.jetbrains.com/datagrip/" target="_blank" rel="noreferrer noopener">DataGrip</a> from JetBrains, which is pretty close to SSMS experience in Windows.</p>
</p>
<h2 class="wp-block-heading">Connection string example</h2>
</p>
<p>If your application needs to connect to SQL Server locally, the following connection string will be useful:</p>
</p>
<pre class="wp-block-code"><code>Server=localhost,1433;Database=MyAwesomeApp;User=sa;Password=MyStrongPassword@1</code></pre>
</p>
<p>So there you have it, you can now work with SQL Server databases natively on your Mac!</p></p>
<p>The post <a href="https://onthecode.co.uk/blog/sql-server-2019-using-mac-mojave">Installing SQL Server 2019 on MacOS</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://onthecode.co.uk/blog/sql-server-2019-using-mac-mojave/feed</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
	</channel>
</rss>
