Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, August 13, 2020

Performance: Linking a List of Child Objects To a List of Parent Objects

Many a time I've had to build a relationship where a parent object has a list of child objects linked to it, where the parent itself also belongs to a list. There are many ways of doing this, however, the most performant way I've found is to use an extension on the Enumerable class; ToLookup. Lets say we have a list of parent objects and a list of child objects, and that we need to link to each parent all its children. Parent Object:
public class Parent
{
    public long Identifier { get; set; }

    public List Children { get; set; } = new List();

    public Parent(long identifier)
    {
        this.Identifier = identifier;
    }
}
Child Object:
public class Child
{
    public long Identifier { get; set; }

    public long ParentIdentifier { get; set; }

    public Child(long identifier, long parentIdentifier)
    {
        this.Identifier = identifier;
        this.ParentIdentifier = parentIdentifier;
    }
}
We will assume we have some code that gets us a large list of parents and a large list of children to link to the parents. Each parent has an average of 25 children, some could have no children, some could have more than 25.
List parents = GetParents().ToList(); // 15,000 parents
List children = GetChildren().ToList(); // 300,000 children.
Typically, I would loop through the parents and do a search of the children for any that have a corresponding parent id.
foreach (var parent in parents)
{
    parent.Children = children.Where(d => d.ParentIdentifier == parent.Identifier).ToList();
}
While this method of linking the children to the parents is straightforward, and works fine for small data sets, it really hits the wall on a large dataset; such as our example. The above method takes an average of 88 seconds to complete the linking. We can do better. Lets use the Enumerable.ToLookup instead. We will use ToLookup to build a dictionary of the children grouped by the parent. Then its a simple retrieval of the children for a given parent.
var childrenLookup = children.ToLookup(d => d.ParentIdentifier);

foreach (var parent in parents)
{
    parent.Children = childrenLookup[parent.Identifier].ToList();
}
Using the ToLookup knocks our average linking time down to 0.08 seconds! That's a 99% performance increase!

Monday, March 2, 2020

Read WCF Service Web.config Sections and Values

Get the Web.Config contents as a Configuration object.
private static Configuration GetWebConfig()
{
    var vdm = new VirtualDirectoryMapping(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath, true);
    var wcfm = new WebConfigurationFileMap();
    wcfm.VirtualDirectories.Add("/", vdm);

    var webConfig = WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");

    return webConfig;
}
Get a value from the appSettings section.
public static string GetConfigurationValue(string keyName)
{
    string value = null;

    var webConfig = GetWebConfig();

    if (webConfig.AppSettings.Settings.Count > 0)
    {
        var setting = webConfig.AppSettings.Settings[keyName];
        if (setting != null)
        {
            value = setting.Value;
        }
    }

    return value;
}
Get a specific binding.
public static Binding ResolveBinding(string name)
{
    var section = GetBindingsSection();
    var nameLower = name.ToLower();

    foreach (var bindingCollection in section.BindingCollections.Where(collection => collection.ConfiguredBindings.Any()))
    {
        var bindingElement = bindingCollection.ConfiguredBindings.FirstOrDefault(element => element.Name.ToLower() == nameLower);
        if (bindingElement == null)
        {
            continue;
        }

        var binding = (Binding)Activator.CreateInstance(bindingCollection.BindingType);
        binding.Name = bindingElement.Name;
        bindingElement.ApplyConfiguration(binding);

        return binding;
    }

    var message = $"Binding with name '{name}' could not be found in the service web.config.";
    throw new FaultException(new FaultReason(message));
}
Get a specific endpoint.
public static ChannelEndpointElement ResolveClientEndpoint(string name)
{
    var section = GetClientSection();
    var nameLower = name.ToLower();

    var endpoint = section.Endpoints.OfType()
        .FirstOrDefault(e => e.Name.ToLower() == nameLower);

    if (endpoint != null)
    {
        return endpoint;
    }

    var message = $"Client endpoint with name '{name}' could not be found in the service web.config.";
    throw new FaultException(new FaultReason(message));
}
Get the Binding section.
public static BindingsSection GetBindingsSection()
{
    var webConfig = GetWebConfig();
    var bindingSection = ServiceModelSectionGroup.GetSectionGroup(webConfig)?.Bindings;

    if (bindingSection != null)
    {
        return bindingSection;
    }

    const string message = "The service web.config is missing the bindings section.";
    throw new FaultException(new FaultReason(message));
}
Get the Client section.
public static ClientSection GetClientSection()
{
    var webConfig = GetWebConfig();
    var clientSection = ServiceModelSectionGroup.GetSectionGroup(webConfig)?.Client;

    if (clientSection != null)
    {
        return clientSection;
    }

    const string message = "The service web.config is missing the client section.";
    throw new FaultException(new FaultReason(message));
}

Thursday, September 19, 2019

ASP.Net Core – Overriding the Web.config

In ASP.Net Core, when publishing the project, the web.config file is generated with some default data.

Example:
<configuration>
  <system.webServer>
    <handlers>
      <add modules="AspNetCoreModule" name="aspNetCore" path="*" resourceType="Unspecified" verb="*" />
    </handlers>
    <aspNetCore processPath=".\My.WebApp.exe" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
  </system.webServer>
</configuration>
At times, you may need to override the contents of this file or change the values of some of the keys. To do this, simply add a web.config file to your ASP.Net Core project. You can add the file through the usual way of right-clicking the project and choosing "Add -> New Item…". Next, browse through the list of available templates and select Web Configuration File. This will add a new web.config file to your project with a commented out template which you can modify to fit your needs.

Example:
<configuration>

  <!-- To customize the asp.net core module uncomment and edit the following section. 
  For more info see https://go.microsoft.com/fwlink/?linkid=838655 -->
  <!--
  <system.webServer>
    <handlers>
      <remove name="aspNetCore"/>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
    </handlers>
    <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
  </system.webServer>
  -->

</configuration>
Simply uncomment the section and change, or add, any values you need. In the following example, I want to remove the arguments attribute as my application does not require it, and override the value of the processPath; my application exe is located in a sub folder named “bin”.

Example:
<configuration>
  <system.webServer>
    <handlers>
      <add modules="AspNetCoreModule" name="aspNetCore" path="*" resourceType="Unspecified" verb="*" />
    </handlers>
    <aspNetCore processPath=".\bin\My.WebApp.exe" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
  </system.webServer>
</configuration>
By adding the web.config file, most of the values in the web.config will be overridden when the project is published. However, for some reason, the customized processPath value gets ignored and the automatic generated value gets outputted instead. To fix this issue, you will need to modify your project file and add a new keyword to your Publish build profiles; IsTransformWebConfigDisabled. This will ensure that whatever you put in your web.config remains.

Example:
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
  <PlatformTarget>x86</PlatformTarget>
  <DocumentationFile>.\bin\Release\net472\My.WebApp.xml</DocumentationFile>
  <NoWarn>1701;1702;1705;1591;NU1603</NoWarn>
  <Optimize>false</Optimize>
  <IsTransformWebConfigDisabled>true</IsTransformWebConfigDisabled>
</PropertyGroup>

Friday, June 28, 2019

WinForms: How To Add a Border To a Panel Control

To add a border to a Panel control, extend the control with the following class:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
 
class MyPanel : Panel
{
    private Color colorBorder = Color.Transparent;
 
    public MyPanel() : base()
    {
        this.SetStyle(ControlStyles.UserPaint, true);
    }
 
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        e.Graphics.DrawRectangle(
            new Pen(
                new SolidBrush(colorBorder), 2), e.ClipRectangle);
    }
 
    public Color BorderColor
    {
        get { return colorBorder; }
        set { colorBorder = value; }
    }
}
You can then use the new BorderColor property to set the border to any color you like.

Wednesday, June 26, 2019

Tuesday, June 25, 2019

WPF: How To Remove The Min, Max and Close Buttons On a WPF Window

WPF doesn’t have a built-in property to hide the title bar’s Min, Max and Close buttons, however, you can do it with a few lines of P/Invoke.

First, add these declarations to your Window class:
private const int GWL_STYLE = -16;
private const int WS_SYSMENU = 0x80000;
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

Then put this code in the Window’s Loaded Event:
private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
{
    var hwnd = new WindowInteropHelper(this).Handle;
    SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU);
}

No more window buttons. You also won’t have a window icon on the left side of the title bar, which means no System menu, even when you right-click the title bar – they all go together.

Note that Alt+F4 will still close the Window. If you don’t want to allow the window to close before the background thread is done, then you could also override OnClosing and set Cancel to true.

Wednesday, June 5, 2019

C#: Convert List<long> to List<string> and Vice Versa

List listOfNumbers = new List() { 1, 2, 3 };
List listOfStrings = listOfNumbers.ConvertAll(n => n.ToString());
listOfNumbers = listOfStrings.ConvertAll(long.Parse);

Sunday, June 2, 2019

C#: Convert string[] to int[]

Given an array of integers in string form:
var myStrings = new string[] {"1", "2", "3"};
Convert the array of strings into an array of integers:
var myInts = Array.ConvertAll(myStrings, int.Parse);
An alternative way is to use LINQ, however that would require an extra call to ToArray to get an array:
var myInts = myStrings.Select(int.Parse).ToArray()

Saturday, June 1, 2019

Handy Online Tools For Developers

The following is a list of helpful online tools.

SQL Fiddle
If you do not know SQL or basic database concepts, this site is not going to be very useful to you. However, if you are a database developer, there are a few different use-cases of SQL Fiddle intended for you:

You want help with a tricky query, and you’d like to post a question to a Q/A site like StackOverflow. Build a representative database (schema and data) and post a link to it in your question. Unique URLs for each database (and each query) will be generated as you use the site; just copy and paste the URL that you want to share, and it will be available for anyone who wants to take a look. They will then be able to use your DDL and your SQL as a starting point for answering your question. When they have something they’d like to share with you, they can then send you a link back to their query.

You want to compare and contrast SQL statements in different database back-ends. SQL Fiddle easily lets you switch which database provider (MySQL, PostgreSQL, MS SQL Server, Oracle, and SQLite) your queries run against. This will allow you to quickly evaluate query porting efforts, or language options available in each environment.

You do not have a particular database platform readily available, but you would like to see what a given query would look like in that environment. Using SQL Fiddle, you don’t need to bother spinning up a whole installation for your evaluation; just create your database and queries here!

.Net Fiddle
Online .Net compiler (C#, VB.Net, F#)

Diff Now
DiffNow lets you compare text files, documents, binary files, and archives up to 2048KB in size. 

XPath Generator
The Xpath generator will help you automatically generate xpaths. Paste in your xml and place the cursor in the element you need the xpath to and it will generate an xpath. The xpath will be shown in the xpath results text area.

Online regex tester and debugger: JavaScript, Python, PHP, and PCRE
Free PCRE-based regular expression debugger with real time explanation, error detection and highlighting.

Binary Hex Decimal Ascii Converters
Easily convert bin, hex, decimal, and ascii numbers to each other. All you need is to open the conversion pair page and type the number in the relevant box.

Tables Generator
Generate tables, with data, in various formats; such as Markdown Tables for use with docuwiki. 

P/Invoke.Net
PInvoke.net is primarily a wiki, allowing developers to find, edit and add PInvoke* signatures, user-defined types, and any other information related to calling Win32 and other unmanaged APIs from managed code (written in languages such as C# or VB.NET).

.Net Reference Source Code
Browse the .NET Framework source code online, with search and navigation powered by Roslyn.

Collection Of Input Output Tools
The Online Tools site has a large list of online tools, including the following:
Hash
File Hash
Encode
Decode
Misc
CRC-16 CRC-16 Base32 Base32 Syntax Highlight
CRC-32 CRC-32 Base32 File Base32 File
MD2 MD2 Base64 Base64
MD4 MD4 Base64 File Base64 File
MD5 MD5 HTML HTML
SHA1 SHA1 URL URL
SHA224 SHA224
SHA256 SHA256
SHA384 SHA384
SHA512 SHA512
SHA512/224 SHA512/224
SHA512/256 SHA512/256
SHA3-224 SHA3-224
SHA3-256 SHA3-256
SHA3-384 SHA3-384
SHA3-512 SHA3-512
Keccak-224 Keccak-224
Keccak-256 Keccak-256
Keccak-384 Keccak-384
Keccak-512 Keccak-512
Shake-128 Shake-128
Shake-256 Shake-256

Performance: Linking a List of Child Objects To a List of Parent Objects

Many a time I've had to build a relationship where a parent object has a list of child objects linked to it, where the parent itself als...