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

Statistics and Data Analysis Terminnologies-I

Variance

Variance in mathematics is a measure of how spread out the values in a set of data are. It quantifies the average squared deviation of each data point from the mean (average) of the dataset. In simpler terms, it tells us how far individual data points are from the center of the data.

The formula for variance is:

Where:

Higher variance means the data points are more spread out, while lower variance indicates they are closer to the mean.

Standard Deviation

Standard deviation tells us how much data points tend to deviate from the mean on average. A small standard deviation indicates that the data points are clustered closely around the mean, whereas a large standard deviation shows that the data points are spread out.

Example

Alright, let’s walk through an example to make the concept of standard deviation clearer!

Imagine you have the test scores of five students in a math exam: 80, 85, 90, 95, and 100. Here’s how we calculate the standard deviation step by step:

Step 1: Find the Mean

The mean ((\mu)) is the average of the data:
$$\mu = \frac{80 + 85 + 90 + 95 + 100}{5} = 90$$

Step 2: Calculate Deviations from the Mean

Subtract the mean from each score to find the deviations:

  • (80 – 90 = -10)
  • (85 – 90 = -5)
  • (90 – 90 = 0)
  • (95 – 90 = 5)
  • (100 – 90 = 10)

Step 3: Square Each Deviation

Square the deviations to eliminate negative values:


Step 4: Find the Average of the Squared Deviations

Add up the squared deviations and divide by the total number of data points ((n = 5)):
$$\text{Variance} (\sigma^2) = \frac{100 + 25 + 0 + 25 + 100}{5} = 50$$

Step 5: Take the Square Root of the Variance

The square root of the variance gives us the standard deviation:
$$\sigma = \sqrt{50} \approx 7.07$$

Final Result:

The standard deviation is approximately 7.07. This means that, on average, the test scores deviate from the mean by about 7.07 points.

Now, with this example, you see how the standard deviation helps visualize the spread of scores

Moving Averages

The moving averages method is a statistical technique used to analyze time-series data by smoothing out short-term fluctuations and highlighting trends or patterns over time. It’s often applied in fields like finance, economics, and sales forecasting.

Here’s how it works:

  1. Determine the Window: Choose the number of data points (known as the “window”) you want to consider for calculating the average. For example, you might decide on a 3-month or 5-day moving average.
  2. Calculate the Average: For each period, calculate the average of the chosen number of data points. This average is the moving average for that period.
  3. Shift the Window: Move the window one period forward (e.g., from days 1–5 to days 2–6) and calculate the next average.
  4. Repeat: Continue shifting the window and calculating averages across the entire dataset.

The result is a new series of data (the moving averages), which smooths out random variations in the original data, allowing you to better understand trends.

There are different types of moving averages:

  • Simple Moving Average (SMA): Equal weight is given to all data points in the window.
  • Weighted Moving Average (WMA): More weight is given to recent data points.
  • Exponential Moving Average (EMA): Uses a formula to give progressively more weight to recent data points.
sample c# code for moving averages
// Simple moving average calculation 
double[] data = { 10, 12, 14, 16, 18, 20, 22, 24, 26, 28 }; 
int windowSize = 3; 
double[] movingAverages = new double[data.Length - windowSize + 1]; 
for (int i = 0; i < movingAverages.Length; i++) { 
              movingAverages[i] = data.Skip(i).Take(windowSize).Average(); 
} 
Console.WriteLine("Moving Averages: " + string.Join(", ", movingAverages));
Explanation

Sure! Let me break down the code for you step by step:

Purpose

This code calculates the Simple Moving Average (SMA) of an array of numbers, given a specified window size.


Variables and Initialization

  1. double[] data:
    This array holds the input data (in this case, {10, 12, 14, 16, 18, 20, 22, 24, 26, 28}), which represents a time-series or sequential dataset.
  2. int windowSize:
    This is the size of the moving average window, set to 3. It determines how many consecutive numbers are used to calculate each average.
  3. double[] movingAverages:
    This array will store the computed moving averages. Its length is:
    $$\text{Length of data array} – \text{windowSize} + 1$$
    This ensures that the moving average calculation stops when the remaining data is insufficient to fill the window.

Loop Logic

The for loop iterates through the data array to calculate the moving averages:

  1. Iteration:
    The loop runs from i = 0 to i < movingAverages.Length. During each iteration, it computes the average of a specific slice (sub-array) of the input data.
  2. data.Skip(i).Take(windowSize):
  • Skip(i): Skips the first i elements of the data array.
  • Take(windowSize): Takes the next windowSize elements starting from the current position.
    For example:
  • At i = 0: Takes {10, 12, 14}
  • At i = 1: Takes {12, 14, 16}
  • At i = 2: Takes {14, 16, 18}, and so on.
  1. .Average():
    Computes the average of the selected windowSize elements and stores it in the movingAverages[i] array.

Output

After the loop finishes, all the calculated moving averages are stored in the movingAverages array. Finally, the code prints them using:

Console.WriteLine("Moving Averages: " + string.Join(", ", movingAverages));

This will output the moving averages as a comma-separated list.


Example

For the given data array and windowSize = 3:

  • Moving average for {10, 12, 14} = ((10 + 12 + 14) / 3 = 12)
  • Moving average for {12, 14, 16} = ((12 + 14 + 16) / 3 = 14)
  • Moving average for {14, 16, 18} = ((14 + 16 + 18) / 3 = 16)
  • And so on.

The final output will be:

Moving Averages: 12, 14, 16, 18, 20, 22, 24, 26

The Skip(i) function is used to shift the starting position of the window when calculating moving averages. Here’s why it’s necessary:

  • In the first iteration (i = 0), we want to start the window at the beginning of the data array, which includes the first three elements (e.g., {10, 12, 14}).
  • In the next iteration (i = 1), we want the window to move forward by one position, so it starts at the second element and includes the next three elements (e.g., {12, 14, 16}).
  • This shifting process continues for each subsequent iteration, ensuring that each moving average is calculated using the right set of consecutive numbers.

Without Skip(i), the function would always start from the beginning of the array, and you’d end up calculating the same average repeatedly instead of progressively shifting the window. By skipping i elements, the window moves forward as intended, covering all possible sets of data points.

In the first iteration ((i = 0)), nothing is skipped because (Skip(0)) means “skip zero elements”—essentially, it starts at the beginning of the array, so it includes 10, 12, and 14 as intended.

The confusion might stem from interpreting Skip(i) too literally. Here’s what happens step by step:

  • At (i = 0), data.Skip(0) takes the array as-is (no skipping), so it starts with {10, 12, 14}.
  • At (i = 1), data.Skip(1) skips the first element (10), resulting in {12, 14, 16} being taken.
  • At (i = 2), data.Skip(2) skips the first two elements (10, 12), resulting in {14, 16, 18} being taken.

The Skip(i) ensures the window shifts correctly as the loop progresses. But in the first iteration, nothing is skipped, and 10 is included in the moving average calculation.

Convolution

What is Convolution?

Convolution is a mathematical operation that combines two sequences (arrays) to produce a new sequence. It essentially slides one sequence (called the “kernel” or “filter”) across another sequence (the “input data”) and calculates weighted sums at each step.

Simple Example

Let’s use a very basic case:

Input Data:

Imagine you have the sequence:

Kernel (Filter):

The kernel is a smaller sequence:

How Convolution Works:

The kernel slides across the input data. At each position, we multiply the kernel values by the corresponding input values and sum them up.


Step-by-Step Calculation

Step 1: First Position

Align the kernel with the first three values of the input:
[ [1, 2, 3] ]
Multiply each input value by the corresponding kernel value:

So, the first result is -2.


Step 2: Second Position

Move the kernel one step to the right:
[ [2, 3, 4] ]
Multiply and sum:

The second result is -2.


Step 3: Third Position

Move the kernel again:
[ [3, 4, 5] ]
Multiply and sum:

The third result is -2.


Final Result:

The output of the convolution is:
[ [-2, -2, -2] ]


Why Is This Useful?

Convolution is used in many fields:

  • Moving Averages: To smooth data or detect trends.
  • Image Processing: To apply filters like blurring or edge detection.
  • Machine Learning: In convolutional neural networks for feature extraction.

Basics of Machine Learning

What is a scalar ?

A scalar is also called a zero Dimensional Array . any single number or value is a scalar
example:

Weight: 70 kg

Temperature: 36.6°C

what is a vector ?

A vector is a 1-D array or an array which in most progrmming languages is written as [1,3,4,5]
For example:

A 3D point in space: [2, 5, 7] (x, y, z coordinates)

what is a matrix ?

A matrix is a 2-D array . i.e for e.g a table with rows and columns is a 2D array . It is also called an array inside an array i.e [ [ 1,2,3,4],[7,8,4,3] ]
A matrix is organized in rows and columns. It’s like a grid where each entry corresponds to a specific row and column. For instance:

3D Array..NDarray

A 3D array adds another dimension to the grid. Imagine stacking multiple 2D arrays like slices in a cube. .The same concept applies to higher order arrays like 4D , 5 D arrays . i.e a 4D array is nothing but stacked 3D arrays . Refer to the other blog also about array indexing How elements are indexed in a 3Dimensional array
For instance: the following is the example of a 3D array.
import numpy as np

# Create a 3D array
array = np.array([[[1, 2, 3],
[4, 5, 6]],
[[7, 8, 9],
[10, 11, 12]]])

# Access element at index (1, 0, 2)
element = array[1, 0, 2] # Result: 9
print(element)
# prints 9

Access Element in a 3 Dimensional Array using numpy

import numpy as np

# Create a 3D array
array = np.array([[[1, 2, 3], [4, 5, 6]],
                  [[7, 8, 9], [10, 11, 12]]])

# Access element 9
# Explanation : consider the above 3D array  as a stacked 2D array with 2 layers 
layer 0 :
[[1, 2, 3], [4, 5, 6]]
layer 1 :
[[7, 8, 9], [10, 11, 12]]
9 is in layer 1 
Within that layer, pick the first row.
Then, take the third element in that row
element = array[1, 0, 2]
print(element)  # Output: 9

This structure makes it easy to navigate, slice, and manipulate data in three-dimensional space.

How elements are indexed in a 3Dimensional array

In a 3D array, elements are organized in three dimensions, and their positions are specified using three indices, typically written as [i][j][k] or (i, j, k). Here’s a breakdown:

How Indexing Works:

This hierarchy lets you pinpoint any element in the 3D array.

How Indexing Works:

  1. First Dimension (i):
  • Determines which “block” or “layer” of the array you’re accessing.
  • Think of it as choosing a specific 2D “sheet” within the 3D array.
  1. Second Dimension (j):
  • Specifies the “row” within the selected 2D sheet.
  1. Third Dimension (k):
  • Points to the “column” within the chosen row.

This hierarchy lets you pinpoint any element in the 3D array.

Example:

Imagine a 3D array as a stack of 2D grids:

Layer 0:
[[1, 2, 3],
 [4, 5, 6]]

Layer 1:
[[7, 8, 9],
 [10, 11, 12]]
  • To access the number 9, you’d use indices [1][0][2]:
  • 1: Select the second layer (index 1 because indexing starts at 0).
  • 0: Within that layer, pick the first row.
  • 2: Then, take the third element in that row.

In Code (Using NumPy):

import numpy as np

# Create a 3D array
array = np.array([[[1, 2, 3], [4, 5, 6]],
                  [[7, 8, 9], [10, 11, 12]]])

# Access element 9
element = array[1, 0, 2]
print(element)  # Output: 9

This structure makes it easy to navigate, slice, and manipulate data in three-dimensional space.

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


Deploy Flask Web App- Set up Apache as a reverse proxy to Gunicorn

Deploying a Flask app to a Fedora Linux server involves several steps to ensure your app runs smoothly and securely. Here’s a step-by-step guide:

Step-by-Step Guide to Deploy a Flask App to Fedora Linux Server

  1. Set Up Your Fedora Server: Ensure your server is up-to-date and has Python installed. You can update your server and install Python with the following commands: sudo dnf update sudo dnf install python3 python3-venv
  2. Create a Virtual Environment: Set up a virtual environment to manage your project’s dependencies: python3 -m venv myenv source myenv/bin/activate
  3. Install Flask and Gunicorn: Install Flask and Gunicorn within your virtual environment: pip install Flask gunicorn
  4. Create Your Flask App: Develop your Flask application and save it in a directory (e.g., myapp). Here’s a simple example (app.py):
    from flask import

    Flask app = Flask(__name__)

    @app.route('/')
    def home():
    return "Hello, World!"

    if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5000)
  5. Test Your Flask App Locally: Before deploying, test your app locally to ensure it works: python app.py Access your app at http://localhost:5000.
  6. Set Up Gunicorn: Configure Gunicorn to serve your Flask app:

    gunicorn --bind 127.0.0.1:5000 app:app

    Replace app:app with module_name:class_name if your app is structured differently.
    module_name is the python file which will act as the entry point for the web app in this example it is app.py so the module_name is app
    class_name : is the class that references a flask instance . In this example you can see
    Flask app = Flask(__name__) ” , so the class_name is app .
  7. Deploy Your App: Transfer your Flask app to the server and run it with Gunicorn:
    if your source code is checked in to git , then use the following , else copy the source files to a directory on a server . The following is the example with git .
    git clone https://your_repository_url.git
    cd your_repository_directory
    #activate virtual environment
    source myenv/bin/activate
    # run the app to verify if gunicorn is serving the web app by doing the following :
    sudo gunicorn --bind 127.0.0.1:5000 app:app
    Open your web browser and navigate to http://localhost:5000. to see your Flask app running on the Fedora server.

Now in production deployments we need to ensure that the app is accessible through a url , so we can do that by setting up a reverse proxy . This setup uses Apache as a reverse proxy and Gunicorn as the WSGI server to serve your Flask app. The steps are described below :

Using Apache as a Reverse Proxy to Gunicorn in Fedora Linux(same applies for other distros too)

Create a system d service

Create a system d service for gunicorn so that it runs continuously in the back ground listening to the port of your web app .
For example Create a systemd service file for Gunicorn, for example, /etc/systemd/system/myapp.service

Example systemd Service File for Gunicorn:

```ini
[Unit]
Description=Gunicorn instance to serve my Flask app
After=network.target

[Service]
User=flaskuser
Group=flaskgroup
WorkingDirectory=/var/www/myproject
Environment="PATH=/var/www/myproject/myenv/bin"
ExecStart=/var/www/myproject/myenv/bin/gunicorn --workers 3 --bind 127.0.0.1:5000 app:app

[Install]
WantedBy=multi-user.target
```
Reload systemd and Start the Gunicorn Service:
sudo systemctl daemon-reload
sudo systemctl start myapp.service
sudo systemctl enable myapp.service

Configure Reverse Proxy in Apache web server

  1. Install Apache2: If you haven’t installed Apache2 yet, you can do so with the following command:
    bash sudo apt install apache2
  2. Enable Necessary Apache Modules: Enable the required Apache modules for proxying HTTP requests.
    sudo a2enmod proxy
    sudo a2enmod proxy_http
    sudo a2enmod headers
    sudo a2enmod deflate
  3. Create a Virtual Host Configuration: Create or edit your Apache virtual host configuration file. For example, create a configuration file named myapp.conf in the /etc/apache2/sites-available/ directory.
    sudo vi /etc/apache2/sites-available/myapp.conf
    Add the following configuration . Let us say we use port 8035 which inturn routes the traffic to port 8000 where the gunicorn serves the web app
    <VirtualHost *:8035>
    ServerName myhobby.com
    ProxyPreserveHost On
    ProxyRequests Off
    ProxyPass / http://127.0.0.1:8000/
    ProxyPassReverse / http://127.0.0.1:8000/
    ErrorLog ${APACHE_LOG_DIR}/myapp_error.log CustomLog ${APACHE_LOG_DIR}/myapp_access.log combined
    </VirtualHost>
    This configuration will forward requests from myhobby.com to the Gunicorn server running on http://127.0.0.1:8000.
  4. Enable the Site Configuration: Enable your new site configuration and disable the default site configuration if necessary.
    sudo a2ensite myapp.conf
    sudo a2dissite 000-default.conf (if we are using port 80 used by default conf)
  5. Restart Apache: Restart Apache to apply the new configuration.
    sudo systemctl restart apache2
  6. Reload Apache: Restart Apache to apply the new configuration.
    sudo systemctl restart httpd
  7. Verify the app : Ensure your Flask app is running by opening a browser session with url
    http://localhost : 8035/. This should display a web page with hello world.

By setting up Apache as a reverse proxy to Gunicorn, Apache will handle incoming HTTP requests, pass them to Gunicorn, and then return the responses to the clients. This setup allows you to leverage Apache’s robust features while efficiently serving your Flask application with Gunicorn.

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


Running a local SQL Server Express in Docker Container

The following describes how to run SQL Server Express instance in a Docker Container .The quick way to ‘install’ a SQL Express, is to run a Docker container from the mssql-server-linuximage. You can start one by running the following command from cmd or powershell.

docker run -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=Pass@word" -e "MSSQL_PID=Express" -p 1433:1433 -d --name=mssqlexpress  mcr.microsoft.com/mssql/server:latest

The above command will start a background Docker container named ‘sqlsrvr’. The SA password is Pass@word

From any application , you may connect using this connection string

Server=localhost,1433;Initial Catalog=Testdb;Integrated Security=True;User Id=sa;Password=Pass@word

Also , the container exposes the container port 1433 to the localhost on 1433, which is used for communication if this conflicts with your setup / any other SQL instance you have running on your local machine , you may either stop the running SQL instance using services.msc or try to run the container on another host port.

For e.g the below code we are mapping the SQL server port 1433 to 1439 on the host machine

docker run -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=MyPass@word" -e "MSSQL_PID=Express" -p 1439:1433 -d --name=mssqlexpress mcr.microsoft.com/mssql/server:latest

Connecting via SSMS should be fairly straightforward

connected

Starting and Stopping the sql container

docker start mssqlexpress
docker stop mssqlexpress

The running sql container is volatile i.e if you remove the container, the data is gone with it.

To persist your data, you need to mount it to a Docker volume / docker mount

A Docker volume maps a directory within a container file system to a path on the host file system . In the sample below, we’ll map the d:\LocalDB\SQLExpress\Datafiles on a Windows host to the datafolder from the mssql-server-linux container, on path/var/opt/mssql/data

for e.g below is the command and followed by it’s explanation

  • docker run: This is the command to create and start a new Docker container.
  • -e "ACCEPT_EULA=Y": This sets an environment variable ACCEPT_EULA to Y, which indicates that you accept the End User License Agreement.
  • -e "SA_PASSWORD=pass@word1": This sets another environment variable SA_PASSWORD with the value pass@word1. This password will be used for the SQL Server sa (system administrator) account.
  • -e "MSSQL_PID=Express": This sets the MSSQL_PID environment variable to Express, specifying that you want to use the SQL Server Express edition.
  • -p 1433:1433: This maps port 1433 of your host machine to port 1433 of the Docker container. SQL Server listens on port 1433 by default.
  • -d: This runs the container in detached mode, which means it will run in the background.
  • --name=mssqlexpress: This assigns a name to the container, which in this case is mssqlexpress.
  • --mount type=bind,source=d:\\LocalDB\\SQLExpress\\Datafiles,target=/var/opt/mssql/data: This binds a directory from your host machine (d:\\LocalDB\\SQLExpress\\Datafiles) to a directory inside the container (/var/opt/mssql/data). This allows the container to use the data files from your host machine.
  • mcr.microsoft.com/mssql/server:latest: This specifies the Docker image to use, which in this case is the latest version of the SQL Server image from the Microsoft Container Registry.

You can now back up database files and use it to restore the back up files created at your mounted path d:\\LocalDB\\SQLExpress\\Datafiles