Sunday, 1 September 2019

Working with AWS Parameter Store in .NET

Using from code

Before starting, I installed the AWS CLI. When trying to figure out how to pass credentials into the AWS SDK, I stumbled upon the SDK's local credential discovery chain.

Among other options, the SDK automatically checks for local configuration files created in your user directory when you run aws configure via the CLI. It handles authentication seamlessly behind the scenes—a handy trick for local development!

Setting Up the Project & Package

I created a new ASP.NET Core MVC project and added the official AWS configuration package via NuGet:


Then I created a simple “Settings” class that holds the configuration values we’ll get back from AWS.
public class Settings
{
   public string awsvalue { get; set; }
   public string awsvalue2 { get; set; }
}
In the appsettings.json file, I told my app which AWS region to use.
{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "AWS": {
    "Profile": "default",
    "Region": "us-west-2"
  }
}
In Program.cs, I updated the web host builder to hook into Systems Manager as a configuration provider. Here, I'm pulling all settings stored under the /seroterdemo path:
public class Program
{
  public static void Main(string[] args)
  {
     CreateWebHostBuilder(args).Build().Run();
  }

  public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
     WebHost.CreateDefaultBuilder(args)
       .ConfigureAppConfiguration(builder =>
       {
          builder.AddSystemsManager("/seroterdemo");
       })
       .UseStartup<Startup>();
    }

Binding and Accessing Options

To make these values available to the application, I bound the configuration section to my Settings POCO in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<Settings>(Configuration.GetSection("properties"));

    services.Configure<CookiePolicyOptions>(options =>
    {
       options.CheckConsentNeeded = context => true;
       options.MinimumSameSitePolicy = SameSiteMode.None;
     });
}
Finally, I injected IOptionsSnapshot<Settings> into the controller constructor. Using IOptionsSnapshot ensures that when the background reload timer fetches updated parameters from AWS, the controller automatically picks up the latest values on the next request!
        private readonly Settings _settings;

        public HomeController(IOptions<Settings> settings)
        {
            _settings = settings.Value;
        }

        public IActionResult Index()
        {
            ViewData["configval"] = _settings.awsvalue;
            ViewData["configval2"] = _settings.awsvalue2;

            return View();
        }
After updating my View to render the two properties, I launched the application—and both values stored in Parameter Store populated as expected.

What I Like About Parameter Store

  • Unbeatable Price: Standard parameters are free (up to 10,000 per account), which makes it a no-brainer for basic configuration and string parameters.

  • Full Audit Trail: Every update increments the version number and records an explicit change history showing who changed what and when.

  • Native .NET Core Integration: AWS’s Amazon.Extensions.Configuration.SystemsManager package integrates seamlessly into ASP.NET Core’s native IConfigurationBuilder, complete with automatic background reloads using TimeSpan.

The AWS team built this extension for .NET Core, and they added capabilities for reloading parameters automatically. Nice touch!

Friday, 30 August 2019

Quick Look: AWS Parameter store

AWS offers a parameter store as part of the AWS Systems Manager service. Parameter Store serves a more fundamental purpose: a central, secure key-value store for application configuration and secrets.
Getting started is simple. Navigate to the AWS Console, open AWS Systems Manager, and select Parameter Store from the left navigation panel. The interface allows you to view, edit, delete, and create parameters—supporting three data types: String, StringList, and encrypted SecureString (backed by AWS Key Management Service).
Each parameter gets a name and value. For the name, I used a “/” to define a hierarchy. The parameter type can be a string, list of strings, or encrypted string.
The UI was smart enough that when I went to go add a second parameter (/seroterdemo/properties/awsvalue2), it detected my existing hierarchy.
And that's it!! Now you are ready to use it in a .NET Core web app.


And lastly , some Real-World Usage Patterns

While it remains a lightweight way to store static variables, modern cloud architectures rely on Parameter Store for critical integrations:

  • Infrastructure as Code (IaC): AWS CloudFormation, Terraform, and AWS CDK directly resolve Parameter Store values at deployment time using dynamic references.

  • Container & Serverless Injection: ECS task definitions and AWS Lambda functions natively fetch Parameter Store values as runtime environment variables, separating application logic from secrets and config.

Wednesday, 21 August 2019

Adding an app.debug.config app.release.config transformations in .NET applications

Most applications need to run on multiple environments and with multiple configurations. At a minimum we usually have at least a local and production environment, but more often we have a local environment, a system test, UAT as well as our production and pre-production environments. Transformations allow you can have different settings for different configurations (debug or release). 

For example, the most common transformation is our connection string. For different databases , we will always have different connection strings That means a lot of different configurations are needed for each environment. Currently for ASP.NET, MVC and Web API projects, we have this functionality supported with our Web.config transformations. However for our app.config, i.e. for console or class libraries this is still not supported, out of the box. So we have to manually create our own transformations.

Previously, I have achieved these transformations manually, as you can see from this previous article I wrote: Adding an app.debug.config app.release.config transformations in .NET applications   , but now there are many different extension and Nuget packages for Visual studio, like Slow Cheetah and Configuration Transform which help you to achieve this much easily. 

Slow Cheetah 

Lately I have been using Slow Cheetah a lot and I really like it, this package allows you to automatically transform your app.config in Visual studio. You can either download it as a Visual Studio extension from the website or just add it to your project from Nuget.







Once installed ,you get a right click option to 
Add Transform, when you right click on your app.config in your project solution . 


Clicking this option will automatically create your new debug and release configs for you. 
And as you can see they are correctly nested underneath the app.config. This is because Slow Cheetah has automatically updated our project file to contain the necessary settings to tell the release and debug config that they are dependent upon the app.config. Before we had to manually make these adjustments to the project file ourselves.


If we open our project file and check the settings added, we can now see something like this, this is how we would normally have to edit our project file to look like, this basically defines the dependency between the app.config and the release and debug config.


Also notice the IsTransformFile element, this is the important setting for Slow cheetah. Instructing it to automatically transform the App.config file depending on the chosen configuration.

And that's it, a lot of manual work saved already. Now you can can add whatever customization's you like inside the transform files, for example if you want to tweak app settings and connection string.

E.G here I have just added an app setting to the app.config and the app.release.config , setting the value to true in the release config and false in the app.config. 




Note, the use of the replace transform key to prompt the replacement of this value and the locator key. 

So if we walk-through the example above, the replace transform key, sends the instruction to replace the true value from the isProd key located beneath the appSetting element. This is done using the xdt:Transform attribute. 

Also note , that all XDT documents, i.e. your app.config, and each environment config, need a namespace declaration in the root element, otherwise your transformations will not happen.





When you build your application the files are transformed and dropped into the output directory. If you are transforming the app.config then when the file is transformed it will be renamed in the output directory as usual to ensure that your application picks it up at runtime.

Preview Transform 


You can also quickly preview your transform using the Preview Transform context menu on the transform file. By selecting the release config and right clicking in the solution explorer, we are presented with the differences, which in our case, is the app setting differences we added between the app and release configs. However as you know, environment configs can become very long and detailed, so this Preview Transform tool can be a god send when you are trying to check settings or connection strings to debug an issue. 


Wednesday, 10 January 2018

How to fix: HTTP could not register URL error

Often when running a service , you might get the following annoying error :

HTTP could not register URL http://+:8000/MyWCF/. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details).

To get around this you need to run up a command window and run the following for your service and domain :

netsh http add urlacl url=http://+:80/MyUri user=DOMAIN\user


Thanks to Brian via stackoverflow for this command and the explanation of the invalid exception text and how to find what's really going wrong.

Friday, 6 January 2017

Using FOR XML PATH(”) for String Concatenation

FOR XML PATH

Every now and then  I need to concatenate a column of strings returned from a SQL query, often I use the COALESCE function,

COALESCE





....but lately I've been using FOR XML PATH(”) a lot and am finding it easier to use. FOR XML PATH function can also be used for string concatenation when generating XML:










STUFF FOR XML PATH
Another handy function for string manipulation is STUFF. The STUFF function inserts a string

into another string. It deletes a specified length of characters in the first string at the start position and then inserts the second string into the first string at the start position.


STUFF (character_expression , start , length ,character_expression)

So applying that to the code above , we get something like this :

Thursday, 5 January 2017

Calling a action/controller with params and showing a partial view in modal dialog in MVC3/4/5

Pretty much every MVC user application you write need a modal popup or even modal form dialog containing a partial view.
Therefore we need a mechnism for calling an action and controller , passing in an Id and returning a view model with results to a partial view inside a modal dialog.

There are many different options now but i always go back to this method when i need to achieve this as it gives me so much control not only over the params i can pass in ,but dialog size and style too.

This is the jquery code , i copy this to a separate js file in the project script directory.

$(document).ready(function () {
      $(".openDialog").on("click", function (e) {
          e.preventDefault();
          $("<div></div>")
              .addClass("dialog")
              .attr("id", $(this)
              .attr("data-dialog-id"))
              .appendTo("body")
              .dialog({
                  title: $(this).attr("data-dialog-title"),
                  close: function (ev, ui) { window.location.reload() }, //function () { $(this).remove() },
                  width: 600,
                  modal: true,
                  height: 'auto',
                  show: 'fade',
                  hide: 'fade',
                  resizable: 'false',
 
                  //buttons: {
                  //    "Close": function ()
                  //    { $(this).dialog("close"); }
                  //}
              })
 
 
          .load(this.href);
       
 
      });
 
   
 
      $(".close").on("@Html.ActionLink("Edit", "EditDocumentDetails", "Document",
             new { id = item.DocumentId }, 
             new 
             {     @class = "openDialog", 
                   data_dialog_id = "interestDialog", 
                   data_dialog_title = "Edit Document Details" 
             })click", function (e) {
          e.preventDefault();
          $(this).closest(".dialog").dialog("close");
      });
   
  });


An example of where this is called from a view is :

@Html.ActionLink("Edit", "EditDocumentDetails", "Document",
             new { id = item.DocumentId }, 
             new 
             {     @class = "openDialog", 
                   data_dialog_id = "interestDialog", 
                   data_dialog_title = "Edit Document Details" 
             })

And an example of your controller code :

public ActionResult EditDocumentDetails(int id)
      {
          var doc = this.context.ApplicantDocuments.Find(id);
          if (doc == null)
          {
              return HttpNotFound();
          }
 
          IEnumerable<SelectListItem> docTypes = this.GetReferenceList(Constants.ReferenceDocumentTypeList);
          ViewBag.DocumentTypes = new SelectList(docTypes, "Value", "Text", doc.DocumentTypeRef);
          
          return PartialView("_EditDocumentDetails", doc);
      }

Saturday, 17 October 2015

Quick Look: Deduplicating Data with CTEs and ROW_NUMBER()

I recently ran into a common issue while querying data for a UI component: dealing with potential duplicate records in the database. To solve it cleanly without creating physical temp tables, I used a Common Table Expression (CTE) combined with T-SQL's ROW_NUMBER() window function.

What is a CTE?

A CTE (Common Table Expression) is essentially a temporary, named result set defined within the execution scope of a single SELECT, INSERT, UPDATE, or DELETE statement.

Think of it as an inline, readable view that exists only for the duration of the query. Unlike #temp tables or @table variables, CTEs require no explicit drop commands or storage overhead in tempdb.

How ROW_NUMBER() and PARTITION BY Help

The ROW_NUMBER() function assigns a sequential integer to each row within your result set. When paired with PARTITION BY, it allows you to reset the row counter for different logical groupings.

For example, instead of numbering all rows continuously from 1 to 10 across your entire dataset, PARTITION BY CategoryId can number rows 1–5 for Category A, and reset back to 1–5 for Category B.

Putting It Together: The Deduplication Pattern

Here is how you can use a CTE and ROW_NUMBER() to identify and eliminate duplicate rows in a single step:

WITH DuplicateCTE AS (
    SELECT 
        CustomerId,
        Email,
        CreatedDate,
        ROW_NUMBER() OVER (
            PARTITION BY Email 
            ORDER BY CreatedDate DESC
        ) AS RowNum
    FROM Customers
)
SELECT 
    CustomerId, 
    Email, 
    CreatedDate
FROM DuplicateCTE
WHERE RowNum = 1;


How This Query Works:

  1. PARTITION BY Email: Groups rows sharing the same email address into their own partition.

  2. ORDER BY CreatedDate DESC: Ranks the newest record first (RowNum = 1), while older duplicate entries get assigned 2, 3, etc.

  3. WHERE RowNum = 1: Filters out all subsequent duplicates, instantly returning only the single most recent record for each email address to your UI!