Connect to Dynamics 365 CRM Online using a client ID and secret in a C# console app


1. Prerequisites

  • Install the Dynamics 365 SDK assemblies. You can install the necessary NuGet packages, such as:
  • Microsoft.CrmSdk.CoreAssemblies
  • Microsoft.CrmSdk.XrmTooling.CoreAssembly
  • Register your app in Azure Active Directory (AAD) to retrieve the client ID, client secret, and tenant ID.

2. Code Implementation

The following code demonstrates how to authenticate and interact with Dynamics 365 CRM using the CRM SDK:

using System;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Tooling.Connector;

class Program
{
    static void Main(string[] args)
    {
        string clientId = "Your_Client_ID";
        string clientSecret = "Your_Client_Secret";
        string tenantId = "Your_Tenant_ID";
        string crmUrl = "https://Your_CRM_Organization.crm.dynamics.com/";

        // Create connection string
        string connectionString = $@"
            AuthType=ClientSecret;
            ClientId={clientId};
            ClientSecret={clientSecret};
            TenantId={tenantId};
            Url={crmUrl};";

        // Establish connection
        CrmServiceClient serviceClient = new CrmServiceClient(connectionString);

        if (serviceClient.IsReady)
        {
            Console.WriteLine("Connected to CRM successfully!");

            // Example: Retrieve accounts
            IOrganizationService service = serviceClient.OrganizationServiceProxy;
            QueryExpression query = new QueryExpression("account")
            {
                ColumnSet = new ColumnSet("name", "accountnumber")
            };

            EntityCollection results = service.RetrieveMultiple(query);

            foreach (var entity in results.Entities)
            {
                Console.WriteLine($"Account Name: {entity.GetAttributeValue<string>("name")}, Account Number: {entity.GetAttributeValue<string>("accountnumber")}");
            }
        }
        else
        {
            Console.WriteLine($"Failed to connect: {serviceClient.LastCrmError}");
        }
    }
}

3. Explanation

  • Authentication: The connection string uses AAD authentication with the client ID, client secret, and tenant ID.
  • Connection: CrmServiceClient establishes a connection to Dynamics 365.
  • Query: The QueryExpression retrieves data from the CRM, such as accounts in this example.

Note : This article was created with assistance from AI and there could be mistakes / error

Oracle Database in Docker Container

visit the below url
https://container-registry.oracle.com/ords/ocr/ba/database/free

pull the latest image
docker pull container-registry.oracle.com/database/free:latest

Run the container using the image
docker run –name oracleexpressdev -p 1521:1521 -p 5500:5500 -e ORACLE_PWD=oracle@1234 -v D:\LocalDB\OracleExpress\Datafiles:/opt/oracle/oradata container-registry.oracle.com/database/free:latest
The following is the explanation of the parameters
docker run: This is the Docker command to create and start a new container.
–name oracleexpressdev: This sets the name of the container to oracleexpressdev.
p 1521:1521 -p 5500:5500: These parameters map ports on your host machine to ports in the container.
p 5500:5500 maps port 5500 on the host to port 5500 in the container. This port is used for Oracle Enterprise Manager.
e ORACLE_PWD=oracle1234: This sets an environment variable inside the container. ORACLE_PWD is the the Oracle Database SYS, SYSTEM and PDB_ADMIN password (default: auto generated)
v D:\LocalDB\OracleExpress\Datafiles:/opt/oracle/oradata: This mounts a volume from your host machine to the container.
/opt/oracle/oradata is the path inside the container.
This allows the Oracle database to persist data on your host machine.
container-registry.oracle.com/database/free:latest: This specifies the Docker image to use for the container.
In this case, it’s the latest version of the free Oracle database image from Oracle’s container registry.

after the command is run , i got an error , Password cannot be null .

This implies there is an issue with the password that we provided to run the container .In my case , i provided oracle@1234 . so the issue here was @ symbol seems it is not accepting the special character .

so i changed password
docker run –name oracleexpressdev -p 1521:1521 -p 5500:5500 -e ORACLE_PWD=oracle1234 -v D:\LocalDB\OracleExpress\Datafiles:/opt/oracle/oradata container-registry.oracle.com/database/free:latest

Now every thing was fine . If all fgoes well , it will do some back ground work
and finally gives


VS Code Workspace & few example use cases for customizing your VS Code workspace:

what is a VSCode Workspace ?

A VS Code workspace is a feature in Visual Studio Code that allows you to organize your projects, files, and settings in a cohesive environment. Workspaces can be as simple as a single folder containing your project files, or as complex as a multi-root workspace that includes multiple folders and projects.

Here are some key aspects of a VS Code workspace:

  1. Single Folder Workspace: The most basic form, where you open a single folder containing your project files.
  2. Multi-root Workspace: Allows you to work on multiple projects simultaneously by adding multiple folders to the same workspace.
  3. Workspace Settings: Customize settings specific to your workspace, such as editor preferences, extensions, and debugging configurations.
  4. Launch Configurations: Manage launch configurations for debugging your projects.
  5. Task Configurations: Define tasks for building, testing, and running your projects.

To get started with a workspace, you can simply open a folder in VS Code. For more complex setups, you can create a multi-root workspace by selecting “Add Folder to Workspace” from the File menu.

1. Workspace Settings

Use Case: You’re working on a Python project and want to enforce specific linting rules.
Solution: Configure workspace settings to enable pylint and set custom rules.

{
    "python.linting.pylintEnabled": true,
    "python.linting.pylintArgs": ["--max-line-length=100"]
}

2. Adding Extensions

Use Case: You’re developing a web app and need tools to streamline your workflow.
Solution: Install extensions like Live Server, ESLint, and Prettier.

{
    "recommendations": [
        "ritwickdey.liveserver",
        "dbaeumer.vscode-eslint",
        "esbenp.prettier-vscode"
    ]
}

3. Multi-root Workspaces

Use Case: You have frontend and backend projects that need to be worked on simultaneously.
Solution: Add both projects to a single workspace for easier navigation and management.

"folders": [
    {
        "path": "frontend"
    },
    {
        "path": "backend"
    }
]

4. Task Configurations

Use Case: You need to automate the build process for a Node.js application.
Solution: Create tasks to install dependencies and run the build script.

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Install Dependencies",
            "type": "npm",
            "script": "install",
            "group": "build"
        },
        {
            "label": "Build Project",
            "type": "npm",
            "script": "build",
            "group": "build"
        }
    ]
}

5. Launch Configurations

Use Case: You’re debugging a Python application and need to set breakpoints and environment variables.
Solution: Configure launch settings to run your application with necessary parameters.

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "env": {
                "FLASK_ENV": "development"
            }
        }
    ]
}

6. Custom Keybindings

Use Case: You frequently need to format your code and want a custom shortcut.
Solution: Create a custom keybinding for the format document action.

{
    "key": "ctrl+shift+f",
    "command": "editor.action.formatDocument"
}

7. Snippets

Use Case: You often use a specific code pattern for React components.
Solution: Create a snippet to insert the boilerplate code quickly.

"React Component": {
    "prefix": "rfc",
    "body": [
        "import React from 'react';",
        "",
        "const ${1:ComponentName} = () => {",
        "    return (",
        "        <div>",
        "            ${2:/* component code */}",
        "        </div>",
        "    );",
        "};",
        "",
        "export default ${1:ComponentName};"
    ],
    "description": "Create a React functional component"
}

8. Theme and Appearance

Use Case: You prefer a dark theme and custom icons for a better coding experience.
Solution: Change the color theme and icon theme.

{
    "workbench.colorTheme": "Dark+ (default dark)",
    "workbench.iconTheme": "vscode-icons"
}

These examples demonstrate how customizing your workspace can streamline your development process, improve efficiency, and create a more enjoyable coding environment. 🌟

Do you have any specific customization in mind, or would you like more examples?

(This article was created with assistance from AI)

Create a Console app and run in a Container with Visual Studio 2022

I couldn’t find an article on this topic . so i thought i will put one .

Now there are many ways to interact with the container .You can do it with visual studio , Docker Desktop /terminal window
The following shows how to interact with the console app running in container using visual studio .
click the button shown below to open the terminal window .

It opens the power shell in the /app directory
cd in to the the directory that has the dll file .Fo e.g in this case it will be
cd /app/bin/Debug/net9.0/
dotnet <.dllfile>
Now you will be able to interact with it


Another way to do it is to build the image from the docker file generated by visual studio, as shown below

so try to open a separate terminal window to interact with the container .

here i built the image from the docker file visual studio generated and then started a container from it.using the following command
D:\LocalProjects\2024\DotNetConsoleApps\JuiceShop.Solution>docker buildx build -t juiceshop:v2 -f ./JuiceShop/Dockerfile .
The following is the output of theabove command

Once the above command is successful , it created a container image .

if you have installed docker desktop you could see this local image .

Now, to spin a container from the image , you can execute the following command in the terminal
docker run -it –name “zzzz” juiceshop:v2

if you don’t specify –name followed by container name (in this example zzzz) then docker gives an arbitrary name to the container.

Run the container
docker run -it –name “zzzz” juiceshop:v2
Hello please enter your name ?
Ethan Hunt
hello Ethan Hunt


Mount Local file on windows to a Docker container

Imagine you have a web application container that needs to access configuration settings stored in a file on your host system. This file might contain sensitive information like database credentials or API keys. Storing such sensitive data directly within the container image can lead to security risks, particularly when sharing the image. To mitigate this issue, Docker provides storage options that help bridge the gap between container isolation and your host machine’s data.

Docker offers two primary storage options for persisting data and sharing files between the host machine and containers: volumes and bind mounts.

Here we will use the bind mount

docker run -it --mount type=bind,source=d:\\MyFolder\\temp,target=/app/data wordcounterapp:latest -s /app/data/config

e.g The above is the example of a console app running in a container . It counts the words in a sentence . I ve put a sentence in a file on my d drive in windows and mounted it to container and passed the argument 

I have a windows 11 host machine so my example is the use case where i have file in my local machine in a directory called "temp" and i want to mount it to a container .so i will mount the content of the directory on my source system to the container file system.
so in the above command , the source is d:\\MyFolder\\temp
target is /app/data/config

Note: Please make sure that file path is correct and there is no spaces for source and target values. for e.g
the space shown below between cmdline argument and value will also give error

create a dev container using vscode and push it docker hub

The following article describes how to create dev containers using vscode and publish it to docker hub .

1. Install Prerequisites

  • Docker: Install Docker Desktop from here.
  • VS Code: Install Visual Studio Code from here.
  • Remote – Containers Extension: Install the Remote – Containers extension in VS Code. You can find it in the Extensions view in VS Code .

2. Create a Dev Container Configuration

  1. Open your project in VS Code.
  2. Press Ctrl+Shift+P (or Cmd+Shift+P on Mac) to open the Command Palette.
  3. Type and select Remote-Containers: Add Development Container Configuration Files.
  4. Choose a predefined container configuration that suits your project’s needs or customize your own.

This will create a .devcontainer folder with a devcontainer.json file in your project.

3. Customize devcontainer.json

Edit the devcontainer.json file to include any specific tools, extensions, or settings your project requires. Here’s an example:

4. Build and Open the Dev Container

  1. Reopen the Command Palette and select Remote-Containers: Reopen in Container.
  2. VS Code will rebuild the container and reopen your project inside it.

we could see the vs code opening the code in dev container

you can see that that the container has loaded and i am able to run the code from within the container

5. Push the Container to Docker Hub

we need to first make sure that we are authenticated successfully in the docker hub .so
First, log in to Docker Hub from your terminal using:

Then here i will use dev container CLI to build and publish images .

  1. Install DevContainer CLI using Node JS package manager npm as follows :

2. Build and Push the Container

devcontainer build --workspace-folder <path_to_your_workspace> --push true --image-name <your_dockerhub_username>/<your_image_name>:<version>

Replace <path_to_your_workspace>, <your_dockerhub_username>, <your_image_name>, and <version> with your actual values.
Note : This command need to be execute in the host file system not inside container

Here’s a breakdown of that command:

  • devcontainer build: This is the main command for building a development container. It’s part of the Dev Containers specification, which allows you to define your development environment as code.
  • --workspace-folder <my_repo>: This flag specifies the root folder of your workspace. Replace <my_repo> with the path to your repository. For example, if your repository is in a folder named project, you would use --workspace-folder project.
  • --push true: This flag indicates whether the built image should be pushed to a container registry. By setting it to true, the image will be pushed after the build.
  • --image-name <your_dockerhub_username>/<my_image_name>:<optional_image_version>: This flag specifies the name (and optionally the version) of the image. Replace <your_dockerhub_username> with the docker user name which you can find it once you login to docker.com under the profile .
    Replace <my_image_name> with the desired name for your image. You can also include an optional version tag by replacing <optional_image_version>. For example, myapp:latest.

for example , refer the above command
i am executing the devcontainer command from the root directory of my repo that contains .devcontainer folder which makes it easy . Hence you will see that i ve indicated a “.” (dot) after the –workspace-folder parameter switch .

Once i execute command , since you have already authenticated docker earlier it will push your image to the docker hub and if it is successful , you will get the following :

Connect to localdb\mssqllocaldb in visual studio Server Explorer

The following are the steps to connect LocalDB in Visual Studio,

  • To connect to LocalDB in Visual Studio, follow these steps
  • Open Visual Studio and go to the Server Explorer window.
  • Right-click Data Connections and select Add Connection.
  • In the Add Connection dialogue box, select Microsoft SQL Server as the data source.
  • In the Server Name box, type (localdb)\MSSQLLocalDB.
  • Select Windows Authentication as the authentication method.
  • Click Test Connection to verify that the connection is successful.
  • Click OK to close the dialogue box and save the connection.

C#11-And , Or Operators in lambda Expressions

we can use the new and and or operators in C# 11 to create enhanced lambda expressions as follows

using System;

class Program
{
    static void Main(string[] args)
    {
        Func<int, bool> isEven = x => x % 2 == 0;
        Func<int, bool> isPositive = x => x > 0;

        // Using the 'and' operator
        Func<int, bool> isEvenAndPositive = isEven and isPositive;
        Console.WriteLine(isEvenAndPositive(4)); // Output: True
        Console.WriteLine(isEvenAndPositive(-4)); // Output: False

        // Using the 'or' operator
        Func<int, bool> isEvenOrPositive = isEven or isPositive;
        Console.WriteLine(isEvenOrPositive(4)); // Output: True
        Console.WriteLine(isEvenOrPositive(-4)); // Output: True
    }
}

DotnetCore Series

Installing dotnetcore on Fedora Linux

Screen 1 : Open a Terminal Window and type the command – dnf install dotnet-sdk-<version>
Screen 2
Screen 3 – Installation Complete