<?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>C# .Net | DXSdata</title>
	<atom:link href="https://www.dxsdata.com/category/c-sharp-dot-net/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.dxsdata.com</link>
	<description>Software &#124; Network &#124; Administration</description>
	<lastBuildDate>Sat, 30 Sep 2023 13:16:22 +0000</lastBuildDate>
	<language>en-GB</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.1</generator>

<image>
	<url>https://www.dxsdata.com/wp-content/uploads/2023/08/cropped-logo-32x32.jpg</url>
	<title>C# .Net | DXSdata</title>
	<link>https://www.dxsdata.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Solving Visual Studio 2022 slow, lagging IntelliSense</title>
		<link>https://www.dxsdata.com/2023/09/solving-visual-studio-2022-slow-lagging-intellisense/</link>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 30 Sep 2023 12:44:35 +0000</pubDate>
				<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[C# .Net]]></category>
		<category><![CDATA[Microsoft Visual Studio]]></category>
		<category><![CDATA[slow]]></category>
		<guid isPermaLink="false">https://www.dxsdata.com/?p=2216</guid>

					<description><![CDATA[Problem MS Visual Studio 2022 (currently v17.4), e.g. within a simple C# .NET console app, becomes nearly unresponsive, taking multiple seconds while typing a few characters into the editor. Solution/Workaround This should improve the editor&#8217;s AutoComplete feature a lot. If not, have a look at the references, there are a few additional option tweaks which [&#8230;]]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">Problem</h2>



<p>MS Visual Studio 2022 (currently v17.4), e.g. within a simple C# .NET console app, becomes nearly unresponsive, taking multiple seconds while typing a few characters into the editor.</p>



<p></p>



<h2 class="wp-block-heading">Solution/Workaround</h2>



<ol class="wp-block-list">
<li>Watch the current background tasks VS is running at the moment (bottom left), and make sure every task finishes within a few seconds.
<ul class="wp-block-list">
<li>If you experience e.g. a very long indexing of project files, this could be suspicious.</li>
</ul>
</li>



<li>Reset VS settings to default:
<ul class="wp-block-list">
<li>devenv /ResetSettings</li>



<li>devenv /ResetUserData</li>
</ul>
</li>



<li>Delete .vs subfolder of your project</li>



<li>Disable project cache:
<ul class="wp-block-list">
<li>Tools -&gt; Options -&gt; Environment -&gt; Preview Features -&gt; Use the project cache &#8230;</li>
</ul>
</li>
</ol>



<p>This should improve the editor&#8217;s AutoComplete feature a lot.</p>



<p>If not, have a look at the references, there are a few additional option tweaks which might be helpful.</p>



<p></p>



<figure class="wp-block-image size-full"><img fetchpriority="high" decoding="async" width="741" height="434" src="https://www.dxsdata.com/wp-content/uploads/2023/09/image.png" alt="" class="wp-image-2219" srcset="https://www.dxsdata.com/wp-content/uploads/2023/09/image.png 741w, https://www.dxsdata.com/wp-content/uploads/2023/09/image-480x281.png 480w" sizes="(min-width: 0px) and (max-width: 480px) 480px, (min-width: 481px) 741px, 100vw" /><figcaption class="wp-element-caption">(German Screenshot)</figcaption></figure>



<p></p>



<h2 class="wp-block-heading">References</h2>



<p><a href="https://stackoverflow.com/questions/72237599/how-to-disable-that-new-filecontentindex-folder-and-vsidx-files-in-vs-2022">https://stackoverflow.com/questions/72237599/how-to-disable-that-new-filecontentindex-folder-and-vsidx-files-in-vs-2022</a></p>



<p><a href="https://superuser.com/questions/1663409/how-to-fully-reset-all-visual-studio-settings-to-factory-defaults">https://superuser.com/questions/1663409/how-to-fully-reset-all-visual-studio-settings-to-factory-defaults</a></p>



<p><a href="https://stackoverflow.com/questions/73787513/what-is-vsidx-in-visual-studio-and-why-is-it-autogenerated">https://stackoverflow.com/questions/73787513/what-is-vsidx-in-visual-studio-and-why-is-it-autogenerated</a></p>



<p><a href="https://www.asdfreddit.com/r/VisualStudio/comments/zm252q/vs_2022_very_laggy_and_slow/">https://www.reddit.com/r/VisualStudio/comments/zm252q/vs_2022_very_laggy_and_slow/</a></p>



<p></p>



<p></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>[:de]AutoMapper mit statischen ExtensionMethods für .NET Standard[:en]AutoMapper with static ExtensionMethods for .NET Standard[:]</title>
		<link>https://www.dxsdata.com/2019/12/automapper-with-static-extensionmethods-for-net-standard/</link>
					<comments>https://www.dxsdata.com/2019/12/automapper-with-static-extensionmethods-for-net-standard/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Thu, 19 Dec 2019 18:10:31 +0000</pubDate>
				<category><![CDATA[C# .Net]]></category>
		<guid isPermaLink="false">https://www.dxsdata.com/?p=2148</guid>

					<description><![CDATA[[:en]Because the team of the original AutoMapper project removed several static methods with the start of v9, I created a project which keeps the most important static ExtensionMethods like Map() or ProjectTo for easier access. Get it via NuGet or Github. [github-commits username=&#8221;DXSdata&#8221; repository=&#8221;AutoMapper&#8221; limit=&#8221;10&#8243;][:]]]></description>
										<content:encoded><![CDATA[<p>[:en]Because the team of the original <a href="https://github.com/AutoMapper/AutoMapper">AutoMapper</a> project removed several static methods with the start of v9, I created a project which keeps the most important static ExtensionMethods like Map() or ProjectTo for easier access.</p>
<p>Get it via <a href="https://www.nuget.org/packages/DXSdata.AutoMapper">NuGet</a> or <a href="https://github.com/DXSdata/AutoMapper">Github</a>.</p>
<p>[github-commits username=&#8221;DXSdata&#8221; repository=&#8221;AutoMapper&#8221; limit=&#8221;10&#8243;][:]</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.dxsdata.com/2019/12/automapper-with-static-extensionmethods-for-net-standard/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>[:de]C# ASP.NET Core MVC: Benutzerdefinierte Controller-Authorisierungsattribute[:en]C# ASP.NET Core MVC: Customized Controller Authorization Attributes[:]</title>
		<link>https://www.dxsdata.com/2019/12/c-asp-net-core-mvc-customized-controller-authorization-attributes/</link>
					<comments>https://www.dxsdata.com/2019/12/c-asp-net-core-mvc-customized-controller-authorization-attributes/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Mon, 09 Dec 2019 18:49:32 +0000</pubDate>
				<category><![CDATA[C# .Net]]></category>
		<guid isPermaLink="false">https://www.dxsdata.com/?p=2135</guid>

					<description><![CDATA[[:en]Using ASP.NET Core controllers, you can add e.g. the attribute [Authorize] to methods or whole classes to prevent unauthorized access. The following example extends this functionality by allowing access if the client user resides in the local network. namespace myns.Helpers { public class AuthorizeOrInternalAttribute : TypeFilterAttribute { /// &#60;summary&#62; /// If set, user is able [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[:en]Using ASP.NET Core controllers, you can add e.g. the attribute [Authorize] to methods or whole classes to prevent unauthorized access.</p>
<p>The following example extends this functionality by allowing access if the client user resides in the local network.</p>
<pre class="lang:c# decode:true" title="AuthorizeOrInternal.cs">namespace myns.Helpers
{    
    public class AuthorizeOrInternalAttribute : TypeFilterAttribute
    {
        /// &lt;summary&gt;
        /// If set, user is able to access the controller method if logged in or requests from LAN
        /// &lt;/summary&gt;
        public AuthorizeOrInternalAttribute() : base(typeof(AuthorizeOrInternalFilter))
        {            
        }
    }

    public class AuthorizeOrInternalFilter : IAuthorizationFilter
    {        
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var internalIps = new[] { "::1", "127.0.0.1", "192.168." };
            var remoteIp = context.HttpContext.Connection.RemoteIpAddress.ToString();
            var isLAN = internalIps.Any(iI =&gt; remoteIp.StartsWith(iI));
                        
            if (!isLAN)
                if (context.HttpContext.User == null)
                    context.Result = new ForbidResult();
        }
    }



}</pre>
<p>&nbsp;</p>
<pre class="lang:c# decode:true " title="AccountController.cs">[HttpGet("[action]")]
[AuthorizeOrInternal]
public User Details()
{
    return this.GetAnyDetails();            
}
</pre>
<p>&nbsp;</p>
<p><a href="https://stackoverflow.com/questions/31464359/how-do-you-create-a-custom-authorizeattribute-in-asp-net-core">Reference</a>[:]</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.dxsdata.com/2019/12/c-asp-net-core-mvc-customized-controller-authorization-attributes/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>[:de]openTRANS für .NET Core[:en]openTRANS for .NET Core[:]</title>
		<link>https://www.dxsdata.com/2019/08/opentrans-for-net-core/</link>
					<comments>https://www.dxsdata.com/2019/08/opentrans-for-net-core/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 25 Aug 2019 14:40:56 +0000</pubDate>
				<category><![CDATA[C# .Net]]></category>
		<guid isPermaLink="false">https://www.dxsdata.com/?p=2126</guid>

					<description><![CDATA[[:en]openTRANS is a collection of XML definitions for automated ordering systems, developed by Fraunhofer IAO. I partly implemented the openTRANS v2.1 definitions in C# .NET Standard 2.0. Get it on Github and NuGet. [github-commits username=&#8221;DXSdata&#8221; repository=&#8221;openTRANS&#8221; limit=&#8221;10&#8243;][:]]]></description>
										<content:encoded><![CDATA[<p>[:en]openTRANS is a collection of XML definitions for automated ordering systems, developed by Fraunhofer IAO.</p>
<p>I partly implemented the openTRANS v2.1 definitions in C# .NET Standard 2.0.</p>
<p>Get it on <a href="https://github.com/DXSdata/openTRANS">Github</a> and <a href="https://www.nuget.org/packages/openTRANS">NuGet</a>.</p>
<p>[github-commits username=&#8221;DXSdata&#8221; repository=&#8221;openTRANS&#8221; limit=&#8221;10&#8243;][:]</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.dxsdata.com/2019/08/opentrans-for-net-core/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>explorerFilePreview</title>
		<link>https://www.dxsdata.com/2019/04/explorerfilepreview/</link>
					<comments>https://www.dxsdata.com/2019/04/explorerfilepreview/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Tue, 16 Apr 2019 12:41:30 +0000</pubDate>
				<category><![CDATA[Administration]]></category>
		<category><![CDATA[C# .Net]]></category>
		<guid isPermaLink="false">https://www.dxsdata.com/?p=2106</guid>

					<description><![CDATA[[:en]Released a tool which can be used for non-Outlook PCs to be able to see email files (.msg, .eml) as preview in Windows Explorer. Get it via GitHub. [github-commits username=&#8221;DXSdata&#8221; repository=&#8221;explorerFilePreview&#8221; limit=&#8221;10&#8243;][:]]]></description>
										<content:encoded><![CDATA[<p>[:en]Released a tool which can be used for non-Outlook PCs to be able to see email files (.msg, .eml) as preview in Windows Explorer.</p>
<p>Get it via <a href="https://github.com/DXSdata/explorerFilePreview">GitHub</a>.</p>
<p>[github-commits username=&#8221;DXSdata&#8221; repository=&#8221;explorerFilePreview&#8221; limit=&#8221;10&#8243;][:]</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.dxsdata.com/2019/04/explorerfilepreview/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>[:de]C# .NET WinForms: Placeholder für TextBox setzen[:en]C# .NET WinForms: Setting a placeholder for a TextBox[:]</title>
		<link>https://www.dxsdata.com/2019/04/c-net-winforms-setting-a-placeholder-for-a-textbox/</link>
					<comments>https://www.dxsdata.com/2019/04/c-net-winforms-setting-a-placeholder-for-a-textbox/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Thu, 11 Apr 2019 16:36:13 +0000</pubDate>
				<category><![CDATA[C# .Net]]></category>
		<guid isPermaLink="false">https://www.dxsdata.com/?p=2103</guid>

					<description><![CDATA[[:en]Useful snippet for adding a placeholder text feature to a common Windows Forms TextBox like you might know it from HTML&#8217;s &#60;input&#62; tag. Add e.g. to your ExtensionMethods: private const int EM_SETCUEBANNER = 0x1501; [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern Int32 SendMessage(IntPtr hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)]string lParam); public static void SetPlaceholder(this TextBox [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[:en]Useful snippet for adding a placeholder text feature to a common Windows Forms TextBox like you might know it from HTML&#8217;s &lt;input&gt; tag.</p>
<p>Add e.g. to your ExtensionMethods:</p>
<pre class="lang:c# decode:true ">private const int EM_SETCUEBANNER = 0x1501;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern Int32 SendMessage(IntPtr hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)]string lParam);

public static void SetPlaceholder(this TextBox box, string text)
{
    SendMessage(box.Handle, EM_SETCUEBANNER, 0, text);
}</pre>
<p>Result:</p>
<p><a href="https://www.dxsdata.com/wp-content/uploads/2019/04/search.jpg" rel="attachment wp-att-2104"><img loading="lazy" decoding="async" class="size-medium wp-image-2104 alignleft" src="https://www.dxsdata.com/wp-content/uploads/2019/04/search-300x47.jpg" alt="" width="300" height="47" /></a></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p><a href="https://stackoverflow.com/questions/11873378/adding-placeholder-text-to-textbox">Reference</a>[:]</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.dxsdata.com/2019/04/c-net-winforms-setting-a-placeholder-for-a-textbox/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>[:de]Visual Studio: Unmanaged DLL- (oder beliebige) Datei zu NuGET-Paket der Projektausgabe hinzufügen[:en]Visual Studio: Adding unmanaged DLL (or any) file to project&#8217;s NuGET package output[:]</title>
		<link>https://www.dxsdata.com/2019/02/visual-studio-adding-unmanaged-dll-or-any-file-to-projects-nuget-package-output/</link>
					<comments>https://www.dxsdata.com/2019/02/visual-studio-adding-unmanaged-dll-or-any-file-to-projects-nuget-package-output/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Fri, 22 Feb 2019 16:44:42 +0000</pubDate>
				<category><![CDATA[C# .Net]]></category>
		<guid isPermaLink="false">https://www.dxsdata.com/?p=2094</guid>

					<description><![CDATA[[:en] Goal We want to include an unmanaged DLL file to our VS project which produces a NuGET .nupkg output. We are using .NET Framework v4.6.1 in this case (should be equal with similar versions). The unmanaged file should be included within the generated .nupkg automatically. Referencing the NuGET package in other projects, the unmanaged [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[:en]</p>
<h3>Goal</h3>
<p>We want to include an unmanaged DLL file to our VS project which produces a NuGET .nupkg output. We are using .NET Framework v4.6.1 in this case (should be equal with similar versions).</p>
<p>The unmanaged file should be included within the generated .nupkg automatically. Referencing the NuGET package in other projects, the unmanaged file should also be copied to that project&#8217;s output automatically.</p>
<h3>Steps</h3>
<p>We don&#8217;t need a .nuspec file. Instead, we edit the <strong>.csproj</strong> file of the project which produces the .nupkg.</p>
<p>Before the final &#8220;project&#8221; end tag, we add or append/edit the ItemGroup tag like:</p>
<blockquote><p>&lt;ItemGroup&gt;<br />
&lt;None Include=&#8221;unmanaged.dll&#8221; Pack=&#8221;true&#8221; PackagePath=&#8221;build\&#8221;&gt;<br />
&lt;CopyToOutputDirectory&gt;Always&lt;/CopyToOutputDirectory&gt;<br />
&lt;/None&gt;<br />
&lt;None Include=&#8221;unmanaged.targets&#8221; Pack=&#8221;true&#8221; PackagePath=&#8221;build\&#8221;&gt;<br />
&lt;CopyToOutputDirectory&gt;Always&lt;/CopyToOutputDirectory&gt;<br />
&lt;/None&gt;<br />
&lt;/ItemGroup&gt;</p></blockquote>
<p>With this configuration, the 2 mentioned files will be added to the .nupkg file, under a separated &#8220;build&#8221; subfolder.</p>
<p>The file unmanaged.dll should exist in your project&#8217;s root directory. In addition, we create a new file &#8220;<strong>unmanaged.targets</strong>&#8221; there, and insert:</p>
<blockquote><p>&lt;Project xmlns=&#8221;http://schemas.microsoft.com/developer/msbuild/2003&#8243;&gt;<br />
&lt;ItemGroup&gt;<br />
&lt;NativeLibs Include=&#8221;$(MSBuildThisFileDirectory)**\*.dll&#8221; /&gt;<br />
&lt;None Include=&#8221;@(NativeLibs)&#8221;&gt;<br />
&lt;Link&gt;%(RecursiveDir)%(FileName)%(Extension)&lt;/Link&gt;<br />
&lt;CopyToOutputDirectory&gt;PreserveNewest&lt;/CopyToOutputDirectory&gt;<br />
&lt;/None&gt;<br />
&lt;/ItemGroup&gt;<br />
&lt;/Project&gt;</p></blockquote>
<p>The .targets file ensures that your unmanaged file is copied to the Debug/Release output of the project where you are actually using your NuGET package.</p>
<p>Build your NuGET project, the .nupkg file should be created and contains your unmanaged file.</p>
<p>&nbsp;</p>
<h4>Update: Publishing unmanaged DLL via ClickOnce</h4>
<p>If you have finished the steps above, the unmanaged file is copied to Debug output, but will not yet be published if you deploy your final app via ClickOnce method. You might get FileNotFoundExceptions.</p>
<p>To achieve this, you have to add a link to your unmanaged file from your ClickOnce project.</p>
<p>So one way would be to install your NuGet package, then go to your project&#8217;s solution and add a reference to an existing element, which is your unmanaged file within your project&#8217;s &#8220;packages\MyNugetModule&#8221; folder. I recommend adding it as a <strong>link</strong> instead of the file (see the dropdown in the dialog!). In the file&#8217;s properties, choose &#8220;Copy if newer&#8221;.</p>
<p>Finally, the file should be included in your ClickOnce deployment.</p>
<p>&nbsp;</p>
<h4>References</h4>
<p>https://stackoverflow.com/questions/19478775/add-native-files-from-nuget-package-to-project-output-directory</p>
<p>https://stackoverflow.com/questions/51217832/including-unmanaged-dll-in-nuget-package-using-csproj</p>
<p>&nbsp;</p>
<p>&nbsp;[:]</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.dxsdata.com/2019/02/visual-studio-adding-unmanaged-dll-or-any-file-to-projects-nuget-package-output/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>.NET Core Entity Framework DbContext Converter</title>
		<link>https://www.dxsdata.com/2018/12/net-core-entity-framework-dbcontext-converter/</link>
					<comments>https://www.dxsdata.com/2018/12/net-core-entity-framework-dbcontext-converter/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Mon, 24 Dec 2018 19:42:16 +0000</pubDate>
				<category><![CDATA[C# .Net]]></category>
		<guid isPermaLink="false">https://www.dxsdata.com/?p=2058</guid>

					<description><![CDATA[[:en]Released a tool for .NET Core which optimizes the default output of .NET&#8217;s &#8220;DB First&#8221; entity class file generator. It offers a more flexible re-generated DbContext.cs file and you can simply append it to your existing DB scaffolding command. Optimizes generated DbContext output of &#8220;dotnet ef dbcontext scaffold&#8221;: Makes DB schema changeable at runtime&#8221; Removes [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[:en]Released a tool for .NET Core which optimizes the default output of .NET&#8217;s &#8220;DB First&#8221; entity class file generator.</p>
<p>It offers a more flexible re-generated DbContext.cs file and you can simply append it to your existing DB scaffolding command.</p>
<p>Optimizes generated DbContext output of &#8220;dotnet ef dbcontext scaffold&#8221;:</p>
<ul>
<li>Makes DB schema changeable at runtime&#8221;</li>
<li>Removes OnConfiguring method (including connectionString), so you can implement your own partial OnConfiguring method outside the generated context.</li>
<li>Optional parameter &#8211;winforms optimizes all generated .cs files in the context file&#8217;s folder for usage in Windows Forms (grids etc).</li>
</ul>
<p>&nbsp;</p>
<p>Read more and find the latest infos on <a href="https://github.com/DXSdata/DotnetEfDbcontextConverter">Github</a>.</p>
<p>Latest commits:</p>
<p>[github-commits username=&#8221;DXSdata&#8221; repository=&#8221;DotnetEfDbcontextConverter&#8221; limit=&#8221;10&#8243;][:]</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.dxsdata.com/2018/12/net-core-entity-framework-dbcontext-converter/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>[:de].NET: LINQ SQL-Queries mit AutoMapper optimieren[:en].NET: Optimizing LINQ SQL queries with AutoMapper[:]</title>
		<link>https://www.dxsdata.com/2018/12/net-optimizing-linq-sql-queries-with-automapper/</link>
					<comments>https://www.dxsdata.com/2018/12/net-optimizing-linq-sql-queries-with-automapper/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Thu, 06 Dec 2018 18:48:04 +0000</pubDate>
				<category><![CDATA[C# .Net]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[Software]]></category>
		<guid isPermaLink="false">https://www.dxsdata.com/?p=2052</guid>

					<description><![CDATA[[:en]AutoMapper is not only a useful tool for mapping e.g. DB model classes to flatter ViewModels, it can also simplify and optimize SQL queries / expressions generated by LINQ. You can get it via NuGet for any .NET framework type. Example Let&#8217;s suppose we have a simple DB table User. Each user belongs to a [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[:en]AutoMapper is not only a useful tool for mapping e.g. DB model classes to flatter ViewModels, it can also simplify and optimize SQL queries / expressions generated by LINQ.</p>
<p>You can get it via NuGet for any .NET framework type.</p>
<h2>Example</h2>
<p>Let&#8217;s suppose we have a simple DB table <strong>User</strong>. Each user belongs to a <strong>UserGroup</strong> and owns several items, stored in <strong>UserItem</strong>. The tables are &#8220;connected&#8221; via common IDs and SQL foreign keys. The DB classes were generated via common tools like &#8220;dotnet ef scaffold&#8221;.</p>
<p>We want to get an overview of the users, including a property of the parent (UserGroup.Name) and a sum of the user&#8217;s items. The table is huge, so the whole preparation and calculation should be done by the server to reduce network traffic.</p>
<p>The data will be stored in a flat ViewModel class <strong>UserView</strong>, which contains the same structure as User, but with 2 additional fields, <em>UserGroupName</em> and <em>UserItemSum</em>.</p>
<p>First we prepare AutoMapper:</p>
<pre title="Program.cs, Startup.cs or similar" class="lang:c# decode:true">//using AutoMapper;
Mapper.Initialize(cfg =&gt;
{
    cfg.CreateMap&lt;User, UserView&gt;()
      .ForMember(uview =&gt; uview.UserItemSum, opt =&gt; opt.MapFrom(user =&gt; user.UserItem.Sum(item =&gt; item.Number)))
});
</pre>
<p>Create the context instance for DB access:</p>
<pre title="anyClass.cs" class="lang:c# decode:true">var db = new mydbContext();

var dto = db.User.ProjectTo&lt;UserView&gt;().ToList();

//example for proceeding
myBindingSourceForDataGrid.DataSource = dto;</pre>
<p>&#8230;and that was about it. We do not need any more Include() of subtables, Where(), Select() or anything else, and the whole query is run on the server side (the SQL server).</p>
<p>AutoMapper is smart enough to recognize that the UserView.UserGroupName column should belong to the user&#8217;s UserGroup.Name property.</p>
<p>In CreateMap(), we just need to tell how it handles the UserItemSum column.</p>
<p>Taking a look at the SQL query log, we see that the query in fact contains only the needed data:</p>
<pre class="lang:mysql decode:true ">SELECT `User`.`Fullname`, `User.UserGroup`.`Name` AS `UserGroupName`, `User`.`id`, (
    SELECT SUM(`item`.`Number`)
    FROM `mydb`.`UserItem` AS `item`
    WHERE `User`.`id` = `item`.`userId`
) AS `UserItemSum`
FROM `mydb`.`User` AS `User`
INNER JOIN `mydb`.`UserGroup` AS `User.UserGroup` ON `User`.`UserGroupid` = `User.UserGroup`.`id`</pre>
<p>&nbsp;</p>
<p>&nbsp;</p>
<h3>References</h3>
<p>http://docs.automapper.org/en/stable/Queryable-Extensions.html</p>
<p>&nbsp;</p>
<p>&nbsp;[:]</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.dxsdata.com/2018/12/net-optimizing-linq-sql-queries-with-automapper/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>[:de].NET Framework, MySQL: DataSets parallel mit EntityFrameworkCore-Scaffolding nutzen[:en].NET Framework, MySQL: Using DataSets in parallel with EntityFrameworkCore scaffolding[:]</title>
		<link>https://www.dxsdata.com/2018/12/net-framework-mysql-using-datasets-in-parallel-with-entityframeworkcore-scaffolding/</link>
					<comments>https://www.dxsdata.com/2018/12/net-framework-mysql-using-datasets-in-parallel-with-entityframeworkcore-scaffolding/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Thu, 06 Dec 2018 10:16:22 +0000</pubDate>
				<category><![CDATA[C# .Net]]></category>
		<category><![CDATA[Software]]></category>
		<guid isPermaLink="false">https://www.dxsdata.com/?p=2049</guid>

					<description><![CDATA[[:en]Keeping .NET projects up to date is simple in general, but when it comes to details of huge (and old) projects, it can be challenging. In this case, I created a .NET project with MySQL DB about 10 years ago, using mainly DataSets. They were quite easy to handle with VS GUI tools. Nowadays, MySQL [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[:en]Keeping .NET projects up to date is simple in general, but when it comes to details of huge (and old) projects, it can be challenging.</p>
<p>In this case, I created a .NET project with MySQL DB about 10 years ago, using mainly DataSets. They were quite easy to handle with VS GUI tools.</p>
<p>Nowadays, MySQL VS and Connector Add-Ins seem buggy and error-prone. DataSets are not recommended any more at all, MS came up with platform-independent .NET Core and .NET Standard, and the EntityFramework scaffolding works quite well in .NET Core. So basically, it would be a good idea to migrate DataSets to Core/Standard DB entity scaffolding.</p>
<h2>Situation</h2>
<p>The main problem: DataSet/TableAdapter methods, commands and properties must be replaced manually because it&#8217;s a completely different approach to access data. In large projects, this can take weeks or even months. So I was looking for a way to be able to use both options in parallel within the same VS solution, for a simpler and smoother transition which does not block other project feature developments.</p>
<p>Basically, we will add a .NET Standard project to our existing .NET Framework project. The new one will contain the DB classes generated by .NET Core scaffolding. Running it in parallel with DataSets will be a bit tricky.</p>
<h2>Steps</h2>
<p>First, install the latest version of Visual Studio and .NET Framework and Core SDKs.</p>
<p>Make sure your existing .NET Framework project(s) version is at least 4.6.1 to be compatible with Standard and Core.</p>
<p>Add a new .NET Core class library project to your solution, we will call it &#8220;DB&#8221;. Edit DB.csproj, change TargetFramework to &#8220;netstandard2.0&#8221; to be make it most compatible, then restart VS.</p>
<p>Install packages via NuGet for DB:</p>
<ul>
<li>MySql.Data.EntityFrameworkCore</li>
<li>MySql.Data.EntityFrameworkCore.Design</li>
<li>(NETStandard.Library)</li>
</ul>
<p>Create an empty project folder &#8220;Models&#8221;.</p>
<p>Because we created a library, to run the scaffolding .NET Core also needs an application project (see notes below for details).</p>
<p>Add a new .NET Core console application named &#8220;DbBuildTmp&#8221; and install NugetPackes</p>
<ul>
<li>MySql.Data.EntityFrameworkCore.Design</li>
<li>(Microsoft.NETCore.App)</li>
</ul>
<p>In DbBuildTmp, reference project DB.</p>
<p>Open developer command prompt and navigate to the DB folder.</p>
<p>Run the scaffolding command to generate classes of your existing database:</p>
<pre class="lang:sh decode:true ">dotnet ef dbcontext scaffold "server=myserver;port=3306;user=myuser;password=mypw;database=mydb" MySql.Data.EntityFrameworkCore -o Models -f --startup-project ..\DbBuildTmp</pre>
<p>You should now have one C# class file per DB table within the Models folder, and an additional mydbContext.cs file.</p>
<h3>Accessibility from .NET Framework project</h3>
<p>To be able to simply access the new EF class structure from your existing project, e.g. via &#8220;new mydbContext().mytable.First().id&#8221;, we need a few more steps.</p>
<p>Important: Ensure your previously installed MySQL Connector (and therefore MySql.Data reference) version matches the NuGet MySql.* package versions exactly (e.g. 8.0.13)!</p>
<p>Add a reference to your new DB project.</p>
<p>Add in both existingProject.csproj and DB.csproj (within &lt;PropertyGroup&gt; element):</p>
<pre class="lang:xhtml decode:true ">&lt;AutoGenerateBindingRedirects&gt;true&lt;/AutoGenerateBindingRedirects&gt;
&lt;GenerateBindingRedirectsOutputType&gt;true&lt;/GenerateBindingRedirectsOutputType&gt;
&lt;CopyLocalLockFileAssemblies&gt;true&lt;/CopyLocalLockFileAssemblies&gt;</pre>
<p>With these properties set, the compiler seems to solve versioning issues better itself, and also copies the .NET Standard/Core output with (most, not all?) needed references.</p>
<p>For your existing Framework project, install NuGet package</p>
<ul>
<li>Microsoft.EntityFrameworkCore</li>
<li>and all suggested dependencies.</li>
</ul>
<p>Note: the packages&#8217; version must match the version which is referenced to by MySql.Data.Entity* packages in the DB project exactly!</p>
<p>Now you should be able to get some test data e.g. via your original Program.cs:</p>
<pre class="lang:c# decode:true ">var testdb = new DB.Models.myContext();
Console.WriteLine(testdb.myTable.Find("myId").SomeColValue);</pre>
<p>If versioning conflicts occur, empty your projects&#8217; bin/obj folders and double-check the (sub)-references of all your NuGet packages compared to non-Nuget references like maybe MySql.data.</p>
<p>One error which also might occur is &#8220;unknown: providers&#8221; &#8211; on runtime, when accessing the DbSet property the first time. Have a look at existingProject.csproj. The EntityFramework element might contain a &#8220;providers&#8221; tag which is useless for MySQL; delete the full providers tag and recompile.</p>
<h3>Using original connection string</h3>
<p>The class generator sets the connection data within the mydbContext&#8217;s &#8220;OnConfiguring&#8221; method, which is fine for testing, but we want to use the same connection string for DataSet and EF entity access, set in the Framework project&#8217;s Properties.Settings file.</p>
<p>At the moment, there seems to be no way to prevent the CLI scaffolding command from generating this method.</p>
<p>In my opinion, the least inconvenient way is to create a separate &#8220;partial class&#8221; which stays out of the Models folder, but uses the same namespace. So you can simply move this method out from the mydbContext file to the a place where it cannot be overwritten. Re-Running DB scaffolding will recreate the method but at least you get a compiler error message (&#8220;duplicate&#8221;) as a reminder to delete it again.</p>
<p>In Framework project&#8217;s Program.cs file, you can set e.g. some static variable like</p>
<pre class="lang:sh decode:true">DB.MyStaticCommonFile.connstr = Properties.Settings.Default.OriginalConnStr;</pre>
<p>Then modify DB project&#8217;s DbContext OnConfiguring method like</p>
<pre class="lang:c# decode:true ">protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        optionsBuilder.UseMySQL(MyStaticCommonFile.connstr);
    }
}</pre>
<p>&nbsp;</p>
<h2>Some notes</h2>
<p>Usually, it should also be possible to use the existing Framework 4.x project as &#8220;startup project&#8221; for DB scaffolding. In fact, this might end with an MSBuild error &#8220;MSB4006 / GetEFProjectMetadata&#8221;. So we have to use the additional .NET core console application project until this is fixed.</p>
<p>Usually a good alternative to the original MySQL EF packages for Core is <a href="https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql">Pomelo</a>, it was way less buggy than the original packages months ago. Anyway, we have to use original MySQL EF here to be compatible with the existing MySql.Data in the Framework project. Pomelo contains a dependency to MySqlClient which causes a huge load of version and naming conflicts if included.</p>
<p>&nbsp;</p>
<h3>References</h3>
<p>https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db</p>
<p>https://stackoverflow.com/questions/43837638/how-to-get-net-core-projects-to-copy-nuget-references-to-build-output/43841481</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;[:]</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.dxsdata.com/2018/12/net-framework-mysql-using-datasets-in-parallel-with-entityframeworkcore-scaffolding/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
