Wednesday, 23 April 2025

List All Power Automate Cloud Flows Programmatically

Leave a Comment

When a cloud flow is part of a solution in Power Automate, it gets stored in Microsoft Dataverse as a type of record in the workflow table.

Using either

  • Dataverse SDK for .NET: for C# developers, or
  • Dataverse Web API: for RESTful access via HTTP,
Use the Dataverse SDK in C#/.NET

Step 1. Create a new .NET console app project. For this project, we are using Visual Studio 2022 and targeting .NET 6.

Step 2. In Solution Explorer, right-click the project you created and select Manage NuGet Packages... in the context menu.


Step 3.
 Browse for the latest version of Microsoft.PowerPlatform.Dataverse.Client NuGet package and install it.

Step 4. Add the below code in program.cs file

using Microsoft.Crm.Sdk.Messages;
using Microsoft.PowerPlatform.Dataverse.Client;
using Microsoft.Xrm.Sdk;

class Program
{
   // TODO Enter your Dataverse environment's URL and logon info.
   static string url = "https://yourorg.crm.dynamics.com";  // Replace your Power Platform Environment Url from https://admin.powerplatform.microsoft.com
   static string userName = "[email protected]"; // Power Platform User Login Id
   static string password = "yourPassword"; // Power Platform user password

   // This service connection string uses the info provided above.
   // The AppId and RedirectUri are provided for sample code testing.
   static string connectionString = $@"AuthType=OAuth;Url={url};UserName={userName};Password= {password};AppId=51f81489-12ee-4a9e-aaae-a2591f45987d;RedirectUri=app://58145B91-0C36-4500-8554-080854F2AC97;LoginPrompt=Auto;RequireNewInstance=True";

   static void Main()
   {
    //ServiceClient implements IOrganizationService interface
    IOrganizationService service = new ServiceClient(connectionString);
    OutputActiveFlows(service);

    // Pause the console so it does not close.
    Console.WriteLine("Press the <Enter> key to exit.");
    Console.ReadLine();
   }
   public static void OutputActiveFlows(IOrganizationService service)
   {
     var query = new QueryExpression("workflow")
     {
         ColumnSet = new ColumnSet("category",
                                   "createdby",
                                   "createdon",
                                   "description",
                                   "ismanaged",
                                   "modifiedby",
                                   "modifiedon",
                                   "name",
                                   "ownerid",
                                   "statecode",
                                   "type",
                                   "workflowid",
                                   "workflowidunique"),
         Criteria = new FilterExpression(LogicalOperator.And)
         {
             Conditions =
             {
              { new ConditionExpression("category",ConditionOperator.Equal,5) }, // Cloud Flow
              { new ConditionExpression("statecode",ConditionOperator.Equal,1) } // Active
             }
         },
         //TopCount = 1 // Limit to one record
     };

     EntityCollection workflows = service.RetrieveMultiple(query);

     //Entity workflow = workflows.Entities.FirstOrDefault();
     foreach (var workflow in workflows.Entities)
     {
         Console.WriteLine($"category: {workflow.FormattedValues["category"]}");
         Console.WriteLine($"createdby: {workflow.FormattedValues["createdby"]}");
         Console.WriteLine($"createdon: {workflow.FormattedValues["createdon"]}");
         // Description may be null
         Console.WriteLine($"description: {workflow.GetAttributeValue<string>("description")}");
         Console.WriteLine($"ismanaged: {workflow.FormattedValues["ismanaged"]}");
         Console.WriteLine($"modifiedby: {workflow.FormattedValues["modifiedby"]}");
         Console.WriteLine($"modifiedon: {workflow.FormattedValues["modifiedon"]}");
         Console.WriteLine($"name: {workflow["name"]}");
         Console.WriteLine($"ownerid: {workflow.FormattedValues["ownerid"]}");
         Console.WriteLine($"statecode: {workflow.FormattedValues["statecode"]}");
         Console.WriteLine($"type: {workflow.FormattedValues["type"]}");
         Console.WriteLine($"workflowid: {workflow["workflowid"]}");
         Console.WriteLine($"workflowidunique: {workflow["workflowidunique"]}");
     }

 }
}

Sample Output

category: Modern Flow
createdby: SYSTEM
createdon: 5/20/2020 9:37 PM
description:
ismanaged: Unmanaged
modifiedby: Kiana Anderson
modifiedon: 5/6/2023 3:37 AM
name: When an account is updated -> Create a new record
ownerid: Monica Thomson
statecode: Activated
type: Definition
workflowid: d9e875bf-1c9b-ea11-a811-000d3a122b89
workflowidunique: c17af45c-10a1-43ca-b816-d9cc352718cf

Note. Only flows inside Solutions are accessible this way—not personal flows in the "My Flows" section.

Conclusion

Managing Power Automate cloud flows through code gives developers and IT teams powerful tools to automate, secure, and scale their operations. Whether you prefer the structured approach of the .NET SDK or the flexibility of REST APIs, you can perform critical tasks—like listing, deleting, sharing, and exporting flows—without ever opening the Power Automate UI.

We will see Create, Update, and Delete operations for cloud flows in my next Article.

ASP.NET Core 9.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 9.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

Read More...

Sunday, 20 April 2025

Advanced Configuration in .NET Core

Leave a Comment

 

1. Configuration Providers

.NET Core supports many configuration sources.


  • appsettings.json
  • appsettings.{Environment}.json
  • Environment variables
  • Command-line arguments
  • User Secrets
  • Azure Key Vault
var builder = WebApplication.CreateBuilder(args);

builder.Configuration
    .AddJsonFile("appsettings.json")
    .AddJsonFile(
        $"appsettings.{builder.Environment.EnvironmentName}.json",
        optional: true
    )
    .AddEnvironmentVariables()
    .AddCommandLine(args);
2. Strongly Typed Configuration

Map configuration to C# classes using the IOptions pattern.

// appsettings.json
{
  "MySettings": {
    "SiteTitle": "My App",
    "MaxItems": 10
  }
}
public class MySettings
{
    public string SiteTitle { get; set; }
    public int MaxItems { get; set; }
}
builder.Services.Configure<MySettings>(
    builder.Configuration.GetSection("MySettings")
);
public class HomeController : Controller
{
    private readonly MySettings _settings;
    public HomeController(IOptions<MySettings> options)
    {
        _settings = options.Value;
    }
}
3. Validate Options at Startup
builder.Services
    .AddOptions<MySettings>()
    .Bind(builder.Configuration.GetSection("MySettings"))
    .Validate(settings => settings.MaxItems > 0, "MaxItems must be > 0");
4. Reloading Config on Changes

Enable hot reload for appsettings.json.

builder.Configuration
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

Use IOptionsSnapshot<T> to get updated config per request.

5. Secret Management

Use User Secrets for local development.

dotnet user-secrets init
dotnet user-secrets set "MySettings:ApiKey" "123456"
builder.Configuration
       .AddUserSecrets<Program>();
6. Azure Key Vault Integration
builder.Configuration.AddAzureKeyVault(
    new Uri("https://yourvault.vault.azure.net/"),
    new DefaultAzureCredential());

Make sure your app is registered and granted access to the vault.

7. Custom Configuration Provider

You can create a custom provider for things like databases or external services.

  • Inherit from ConfigurationProvider and ConfigurationSource
  • Inject it into the builder with the Add method

Points to consider

  • Use IConfiguration for raw access to values
  • Use IOptions for dependency injection & structured data
  • Store secrets outside of source-controlled files
  • Group related settings into sections

ASP.NET Core 9.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 9.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

Read More...

Tuesday, 15 April 2025

RadioButtonList Control Overview

Leave a Comment

In this walk-through, you will learn about RadioButtonList in detail, and you get answers of the following questions.

  1. What is RadioButtonList?
  2. How many Layout types?
  3. Which Layout is good to use?
  4. Generate a RadioButtonList with the following:
    1. List Collection Object C#
    2. Database Table data
    3. Manually ListItem
  5. Working Suggestion with RadioButtonList.
 

What is RadioButtonList?

RadioButtonList is a Form-Control of Standard section under the Asp.Net WebForms project template. Naming conventions for RadioButtonList is rbl. Using naming conventions helps you find objects on an aspx page very smartly and easily.

RadioButtonList render a group of Radio-Buttons by using data-source, manually added list-item. RadioButtonList allows users to select only one option (Radio -Button) from a list.

RadioButtonList Layout Types

RepeatDirection: Set rendering direction on browser. There are two types.

  • Horizontal
  • Vertical

RepeatLayout: Support the following types of layout.

  • Flow: Normal rendering.
  • OrderedList: This will display options with 1,2,3,4,5 numbering.
  • Table: Under Table layout.
  • UnorderedList: This will display a bulleted list •.
Which Layout is good to use?
  • Table: For perfect alignment and view. This will render using HTML tags.
  • Flow: It is very lightweight, and Custom CSS can be applied for beautification and alignment as per your current design.

Right Combination of RepeatDirection and RepeatLayout.

SR. NO. RepeatDirection RepeatLayout Remarks
1 Horizontal Flow Working fine.
2 Horizontal OrderedList Not Working, Error Message:
The UnorderedList and OrderedList layouts only support vertical layout.
3 Horizontal Table Working fine.
4 Horizontal UnorderedList Not Working, Error Message:
The UnorderedList and OrderedList layouts only support vertical layout.
5 Vertical Flow Working fine.
6 Vertical OrderedList Working fine.
7 Vertical Table Working fine.
8 Vertical UnorderedList Working fine.

Generate a RadioButtonList with the following.

1. List Collection Object C# to generate RadioButtonList

ASPX Page Code

<div style="border:1px solid black;width:50%;">
    <h2>Hardcoded Radiobutton List using C# List Collection Object</h2>
    <hr />

    <asp:RadioButtonList
        ID="rblListObj"
        runat="server"
        onClick="HardCodeRbl()"
        ClientIDMode="Static">
    </asp:RadioButtonList>

    <br /><br />

    <span id="lblListObj" style="font:20px arial;"></span>
</div>

C# Code

// Create a list of fruits
List<string> fruits = new List<string>
{
    "Apple",
    "Banana",
    "Cherry",
    "Mango",
    "Orange",
    "Pineapple",
    "Strawberry"
};
rblListObj.DataSource = fruits;
rblListObj.DataBind();

JavaScript Code

<script>
    function HardCodeRbl() {
        var selected = "";

        // Read Hardcoded RadioButton List
        var rbl = document.getElementById("rblListObj");

        // Get all input elements
        var inputs = rbl.getElementsByTagName('input');
        var flag = false;

        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].checked) {
                selected = inputs[i];
                flag = true;
                break;
            }
        }

        // Check if a selection was made
        if (flag) {
            alert(selected.value);
            document.getElementById("lblListObj").innerHTML =
                "HardCoded List Collection Object Radiobutton List <br>Selected: <b>" + selected.value + "</b>";
        } else {
            alert('Please select an option.!');
            return false;
        }
    }
</script>

Output


2. Database Table data used to generate RadioButtonList
ASPX Page Code
<div style="border:2px solid green; width:50%; margin-top:50px;">
    <h2>Database Table used to populate Radiobutton List</h2>
    <hr />

    <asp:RadioButtonList
        ID="rblTableBase"
        runat="server"
        onClick="TableBaseRbl()"
        ClientIDMode="Static">
    </asp:RadioButtonList>

    <br /><br />

    <span id="lblTableBase" style="font:20px arial;"></span>
</div>
C# Code
// Database Table used to populate Radiobutton List
BindSportsList();

// BindSportsList Method
private void BindSportsList()
{
    // Database connection string
    string connStr = ConfigurationManager.ConnectionStrings["dbTestConstr"].ConnectionString;

    using (SqlConnection conn = new SqlConnection(connStr))
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand("SELECT SportID, SportName FROM tblSports", conn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);

        rblTableBase.DataSource = dt;
        rblTableBase.DataTextField = "SportName";
        rblTableBase.DataValueField = "SportID";
        rblTableBase.DataBind();
    }
}
Javascript Code
<script>
    function TableBaseRbl() {
        var selected = "";
        var selectedText = "";

        // Read Hardcoded RadioButton List
        var rbl = document.getElementById("rblTableBase");

        // Get all input elements
        var inputs = rbl.getElementsByTagName('input');
        var flag = false;

        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].checked) {
                selected = inputs[i];
                selectedText = document.querySelector("label[for='" + inputs[i].id + "']").innerText;
                flag = true;
                break;
            }
        }

        // Check if a selection was made
        if (flag) {
            alert(selected.value);
            document.getElementById("lblTableBase").innerHTML =
                "Tablebase Radiobutton List Selected: <b>" + selected.value + " ----- " + selectedText + "</b>";
        } else {
            alert('Please select an option.!');
            return false;
        }
    }
</script>

OUTPUT

3. Manually ListItem added to generated RadioButtonList

ASPX Page Code

<div style="border:2px solid red; width:50%; margin-top:50px;">
    <h2>Manually Added ListItem to populate Radiobutton List</h2>
    <hr />

    <asp:RadioButtonList
        ID="rblListItemManually"
        runat="server"
        onClick="rblListItem()"
        ClientIDMode="Static"
        RepeatDirection="Vertical"
        RepeatLayout="UnorderedList">

        <asp:ListItem Text="Bougainvillea" Value="1" />
        <asp:ListItem Text="Petunia" Value="2" />
        <asp:ListItem Text="Zinnia" Value="3" />
        <asp:ListItem Text="Sunflower" Value="4" />
        <asp:ListItem Text="Daffodil" Value="5" />
        <asp:ListItem Text="Lotus" Value="6" />

    </asp:RadioButtonList>

    <br /><br />

    <span id="lblListItem" style="font:20px arial;"></span>
</div>

NO C# Code Wirtten

Javascript Code

<script>
    function rblListItem() {
        var selected = "";
        var selectedText = "";

        // Read Hardcoded RadioButton List
        var rbl = document.getElementById("rblListItemManually");

        // Get all input elements
        var inputs = rbl.getElementsByTagName('input');
        var flag = false;

        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].checked) {
                selected = inputs[i];
                selectedText = document.querySelector("label[for='" + inputs[i].id + "']").innerText;
                flag = true;
                break;
            }
        }

        // Check if a selection was made
        if (flag) {
            alert(selected.value);
            document.getElementById("lblListItem").innerHTML =
                "Manually Added ListItem Radiobutton List Selected: <b>" + selected.value + " ----- " + selectedText + "</b>";
        } else {
            alert('Please select an option.!');
            return false;
        }
    }
</script>

OUTPUT

Working Suggestion with RadioButtonList

1. Use CLientIDMode = “Static”. This will not generate a dynamic id of RadioButtonList control. This will help you use id easily in Javascript.

ClientIDMode="Static"

Note: The above settings are recommended for all Form-Controls.

2. Use Javascript for the event and get the selected value of the Radio Button. Try to use Maximum Javascript because this will reduce the server roundtrip and help to run the application faster.

3. For handling server-side events, you have to use the following settings.

  • AutoPostBack="true"
  • OnSelectedIndexChanged event method.

Happy Coding!

Best ASP.NET Core 9 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 9 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFEASP.NET, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

 

Read More...

Tuesday, 8 April 2025

Unit Test Web API CRUD operations with the NUnit Testing Framework

Leave a Comment

A key component of software development is unit testing, which is examining individual code units—usually functions or methods—to make sure they operate as intended. You can use a variety of testing frameworks to write unit tests in C#, such as:



NUnit: A well-liked.NET testing framework with an intuitive API and an extensive feature set.
Another popular testing framework that provides a more contemporary and adaptable method of unit testing is xUnit.

Unit testing in C# can be made more effective and dependable by using libraries like Moq or NSubstitute to isolate dependencies and construct mock objects.

NUnit is a popular, open-source unit testing framework for C# and other .NET languages, initially ported from JUnit, used for writing and executing automated tests to ensure code quality.

Here, we are implementing basic CRUD operation in web API using C#, and then we are enlisting the different test cases for all those operations and writing a code to test those scenarios using the NUnit framework.

Pre-requisite

1. Open VS 2022

2. Create a Web API project


 3. Add NUnit Test Project


 4. Install required packages from NuGet Package


Core Features of NUnit

NUnit framework has extensive tools for streamlining unit testing, including accurate code verification, logical test design, and broad test coverage. Let's look at three crucial aspects for building good tests.

NUnit Test Lifestyle Attributes

  • [Test Fixture]: is a class or function that has the [TestFixture] attribute, which indicates that it contains tests.
  • [SetUp]: This method initializes resources.
  • [Test]: It contains the test logic.
  • [TearDown]: It assures cleanup after each test.

Now, list down all possible test case scenarios w.r.t the web API and create a test method for each of them.


In each test method, we need to follow the 3A pattern of the NUnit Framework i.e. AAA[Arrange-Act-Assert]. It is a common way to structure unit tests to make them more readable and organized.

  • Arrange: Set up everything needed for the test—objects, variables, mock data, etc.
  • Act: Perform the actual action that you want to test.
  • Assert: Verify that the outcome is what you expected.


Once we have done coding on all possible scenarios, then we can run the NUnit project by executing the “Run All Test” option.

We can run all test cases at a single time, and for complex test cases, we can also debug at a breakpoint by opting for “Debug All Tests”.

On running all test cases, a Test Explorer will open a listing of all test methods as a monitoring window, which depicts the result of all test cases.

If any scenario doesn’t meet the required criteria or expected results, then it will be indicated in the test explorer in red color with the reasonable issue and its possible solution.

In this article, we've explored the key features of NUnit testing, from understanding the basics of unit testing to setting up and using the NUnit framework for your.NET unit testing applications. You may efficiently validate your code by learning how to build simple unit tests, leverage test assertions, and arrange them with test fixtures.

NUnit's adaptability makes it a powerful tool for unit testing in software engineering, whether concentrating on isolated components or complicated situations. Using NUnit testing tools and rigorous testing techniques can lead to high-quality, bug-free code in your apps.

Best ASP.NET Core 9 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 9 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFEASP.NET, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

 

Read More...