Category Archives: ASP.NET

Remove obsolete nuget package references

To get rid of deprecated nuget packages in your solution follow the procedure below.

In Visual Studio first manage the nuget packages for your project (or solution) by right clicking the project in the solution explorer and choose Manage NuGet Packages…

Then the deprecated packages will show up in the list:

To remove those packages you have to remove them from the project file (or do an uninstall with the nuget package manager). I prefer to do this in the project file. So open the project file and remove the package entry (marked lines in the image below).

Now you have to add the FrameworkReference item to the project file. See the project file below and checkout the marked lines.

Check also this link for a more verbose explanation.

Share

c# async in constructors

In C#, constructors cannot be declared as async because they are special methods used for object initialization and cannot be awaited. However, you can use an asynchronous factory method or an initialization method to perform asynchronous operations during object creation. Here’s an example:

public class MyClass
{
    private MyClass()
    {
        // Private constructor to enforce the usage of factory method
    }

    public static async Task<MyClass> CreateAsync()
    {
        var instance = new MyClass();
        await instance.InitializeAsync();
        return instance;
    }

    private async Task InitializeAsync()
    {
        // Perform asynchronous initialization tasks here
        await Task.Delay(1000); // Example asynchronous operation
    }
}

In the above example, the constructor for MyClass is marked as private to enforce the usage of the CreateAsync factory method. The CreateAsync method creates an instance of MyClass, calls the private constructor, and then asynchronously initializes the object by calling the InitializeAsync method. You can perform any necessary asynchronous operations within the InitializeAsync method.

To create an instance of MyClass, you would use the CreateAsync method as follows:

var myObject = await MyClass.CreateAsync();

By using this approach, you can achieve asynchronous behavior during object construction in C#.

Share

Bootstrap Image dropdown

Below is a bootstrap fragment to setup a dropdown input with images.

<html>

<head>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <style>
        .img-dropdown {
            display: inline-block;
            vertical-align: middle;
            margin-right: 10px;
            width: 20px;
            height:20px;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col">
                <div style="float:left">
                    <div class="dropdown">
                        <button class="btn btn-secondary" type="button" id="dropdownMenuButton"
                            data-bs-toggle="dropdown" aria-expanded="false">
                            <div id="languageButtonText">??</div>
                        </button>
                        <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton" id="ulLanguages">
                            <li>
                                <a class="dropdown-item" href="#" data-value="DE">
                                    <img src="img/de.svg" alt="Image 1" class="img-dropdown">
                                    German
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item" href="#" data-value="FR">
                                    <img src="img/fr.svg" alt="Image 2" class="img-dropdown">
                                    French
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item" href="#" data-value="GB">
                                    <img src="img/gb.svg" alt="Image 3" class="img-dropdown">
                                    English
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item" href="#" data-value="NL">
                                    <img src="img/nl.svg" alt="Image 4" class="img-dropdown">
                                    Dutch
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item" href="#" data-value="Frisian">
                                    <img src="img/frisian.svg" alt="Image 5" class="img-dropdown">
                                    Frisian
                                </a>
                            </li>
                        </ul>
                    </div>
                </div>
                <div style="float:left">
                    <div id="selected-image" style="align-items: center; display:flex;margin-left:5px"></div>
                </div>
            </div>
        </div>
    </div>
</body>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"
    integrity="sha512-3gJwYpMe3QewGELv8k/BX9vcqhryRdzRMxVfq6ngyWXwo03GFEzjsUm8Q7RZcHPHksttq7/GFoxjCVUjkjvPdw=="
    crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
    crossorigin="anonymous"></script>
<script>
    $(document).ready(function () {

        // When a dropdown item is clicked
        $('.dropdown-item').click(function () {
            var lang = $(this).data('value');
            var id = 'Language';
            $('#' + id).val(lang);

            // Get the image source of the clicked item
            var selectedImageSrc = $(this).find('img').attr('src');

            // Set the selected image in the div
            $('#selected-image').html('<img src="' + selectedImageSrc + '" alt="Selected Image" width="51">');
            $("#languageButtonText").html(lang);
        });

        $("#ulLanguages li a").filter("[data-value=" + "Frisian" + "]").trigger("click");

    });
</script>

</html>
Share

Add syntax highlighting to ASP.NET site

To enable syntax highlighting on your ASP.NET site follow the steps below:

  1. Goto prismjs.com and press the Download button.
  2. Add the next items to the default languages: C#, ASP.NET (C#), Bash + Shell + Shell, C#, Razor C# and SQL.
  3. Also add the plugin “line-numbers”.
  4. At the bottom of the page download the prims.js and prism.css files.

In the Shared/_Layout.cshtml add both the prism.js and prism.css file.

In the Index.cshtml view add some code to test it out

<div class="row">
    <div class="col line-numbers">
<pre><code class="language-csharp">public class HelloWorld
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Hello, World!");
    }
}
</code>
</pre>
</div>
    <div class="col">
        <pre>
<code class="language-sql">
SELECT * FROM AspNetUsers u
LEFT JOIN AspNetRols on r.Id = u.Id
WHERE ID = 1;
</code>
    </pre>
    </div>
</div>

The resulting page will look like this

Share

Determine domain behind proxy in ASP.NET MVC controller

Sometimes you need to know the domain on which your app is running. If you are behind a proxy there is not a straightforward way to determine this.

To get the “real” domain name for your app check the “X-Forwarded-Host” HTTP header and use this as your host name when, for example, sending links in emails to your app.

First step is to get the host name:

public static string GetForwardedHost(HttpRequest Request)
{
   string host = Request.Headers["X-Forwarded-Host"];
   if (host == null)
   {
      host = Request.Host.ToString();
   }
   return host;
}

Next when you assemble a link for in example an email you want so sent use the code below

var host = Utils.GetForwardedHost(Request);

var callbackUrl = Url.Page(
                    "/Account/ResetPassword",
                    pageHandler: null,
                    values: new { area = "Identity", code },
                    protocol: Request.Scheme, host : host);

this.SendEmail(Input.Email, "Reset Password", $"Please reset your password by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
Share

Enable the ASP.NET page again

asp.net.logoSometimes your ASP.NET tab disappears in the IIS manager. To show this tab again follow the steps below.

Steps involved

  1. Stop the IIS Admin service (and any services that depend on it)
  2. Open C:WINDOWSsystem32inetsrvMetaBase.xml in notepad or your favorite XML Editor. DELETE the line that reads ‘Enable32BitAppOnWin64=”TRUE”‘
  3. Start -> Run -> iisreset
Share