Shortest Path Algorithm C++

This blog article shows you an understandable Shortest Path Algorithm (this is the Dijkstra’s Algorithm). The long explanation is here https://www.educative.io/edpresso/how-to-implement-dijkstras-algorithm-in-cpp. I try to have a short explanation. Look at the picture, run the code, see the result. Likely you can understand if you are a bit stupid like me.


You really there are 6 nodes then there must be a 6×6 array. Some article has 5 nodes and has a 6×6 array …. errrrrr… Another thong you need to pay attention is the modes are from a to f. See the distance between the nodes for example, a to b is 10.

The code as follow:

#include<iostream>

#include<climits>

using namespace std;

// this method returns a minimum distance for the

// vertex which is not included in Tset.

int minimumDist(int
dist[], bool Tset[])

{

    int min = INT_MAX, index;

    for (int i = 0; i < 6; i++)

    {

        if (Tset[i] == false && dist[i] <= min)

        {

            min = dist[i];

            index = i;

        }

    }

    return index;

}

void Dijkstra(int
graph[6][6], int
src) // adjacency matrix used is 6×6

{

    int dist[6]; // integer array to calculate minimum distance for each node.

    bool Tset[6];// boolean array to mark visted/unvisted for each node.

    // set the nodes with infinity distance

    // except for the initial node and mark

    // them unvisited.

    for (int i = 0; i < 6; i++)

    {

        dist[i] = INT_MAX;

        Tset[i] = false;

    }

    dist[src] = 0; // Source vertex distance is set to zero.

    for (int i = 0; i < 6; i++)

    {

        int m = minimumDist(dist, Tset); // vertex not yet included.

        Tset[m] = true;// m with minimum distance included in Tset.

        for (int i = 0; i < 6; i++)

        {

            // Updating the minimum distance for the particular node.

            if (!Tset[i] && graph[m][i] && dist[m] != INT_MAX && dist[m] + graph[m][i] < dist[i])

                dist[i] = dist[m] + graph[m][i];

        }

    }

    cout << “Vertex\t\tDistance from source” << endl;

    for (int i = 0; i < 6; i++)

    { //Printing

        char str = 65 + i; // Ascii values for pritning A,B,C..

        cout << str << “\t\t\t” << dist[i] << endl;

    }

}

int main()

{

    int graph[6][6] = {

        {0, 10, 20, 0, 0, 0},

        {10, 0, 0, 50, 10, 0},

        {20, 0, 0, 20, 33, 0},

        {0, 50, 20, 0, 20, 2},

        {0, 10, 33, 20, 0, 1},

        {0, 0, 0, 2, 1, 0} };

    Dijkstra(graph, 0);

    return 0;

}

The result after executing the code.


Source code download: https://github.com/chanmmn/cpp/tree/master/ConAppShorterPath

Reference (Video): https://www.youtube.com/watch?v=pVfj6mxhdMw

Posted in .Net, Cloud, Community, Computers and Internet | Tagged , | Leave a comment

Data Transfer Object C#

This blog article tries to explain DTO with code. The code is taken in https://code-maze.com/automapper-net-core/. The focus should be just on the 2 classes. The internally use class.

public class User

{

    public int Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string Email { get; set; }

    public Address Address { get; set; }

    public string GetFullName()

    {

        return $”{this.LastName}, {this.FirstName};

    }

}

And the Data Transfer Object (DTO) that the developer has created as a View Model.

public class UserViewModel

{

    [Display(Name = “Full Name”)]

    public string FullName { get; set; }

    [Display(Name = “Country”)]

    public string AddressCountry { get; set; }

    public string Email { get; set; }

}

You will see the following when you run the code.


You can get the source code below of from the link above. But this source code has not implemented the Edit. Some far this is one of the DTO concept code that I found it running from Googel (pretty hard to get one actually).

Source code download: https://github.com/chanmmn/ByOtherDeveloper

Reference: https://www.youtube.com/watch?v=BxWS2E90WHw

Posted in .Net, Cloud, Community, Computers and Internet, Data Platform | Tagged , | Leave a comment

DataTables html

This blog article shows you how to get started with DataTables js and html. I am using Visual Studio 2019. Create a Empty Web Application. Add the following html page.<html>

<head>

    <!–<link href=”DataTables/datatables.css” rel=”stylesheet” />

    http://DataTables/datatables.min.js–>

    <link rel=”stylesheet” type=”text/css”  href=”https://cdn.datatables.net/1.10.25/css/jquery.dataTables.css”&gt;

    <script src=”https://code.jquery.com/jquery-3.6.0.min.js&#8221; integrity=”sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=” crossorigin=”anonymous”></script>

    <script type=”text/javascript” charset=”utf8″ src=”https://cdn.datatables.net/1.10.25/js/jquery.dataTables.js”></script>

    <meta charset=”utf-8″ />

    <title></title>

</head>

<body>

    <table id=”table_id” class=”display”>

        <thead>

            <tr>

                <th>Column 1</th>

                <th>Column 2</th>

            </tr>

        </thead>

        <tbody>

            <tr>

                <td>Row 1 Data 1</td>

                <td>Row 1 Data 2</td>

            </tr>

            <tr>

                <td>Row 2 Data 1</td>

                <td>Row 2 Data 2</td>

            </tr>

        </tbody>

    </table>

    <script>

        $(document).ready(function () {

            $(‘#table_id’).DataTable();

        });

    </script>

</body>

</html>

Click Run then you will see the effect below.

Source code download: https://github.com/chanmmn/webforms/tree/master/WebAppDataTable

Reference: https://datatables.net/examples/basic_init/zero_configuration.html

Posted in .Net, Cloud, Community, Computers and Internet | Tagged , | Leave a comment

Execute SSIS package using C#

This blog article shows you how to execute SSIS package using C# code. You need to reference to Microsoft.SqlServer.ManagedDTS.dll. In the article https://chanmingman.wordpress.com/2021/06/13/ssis-transfer-data-from-one-table-to-another-basic/ I have created a simple package. Use the code below to execute the SSIS package. I have hardcoded the path below, you can replace that.

static void Main(string[] args)

{

    string pkgLocation;

    Package pkg;

    Application app;

    DTSExecResult pkgResults;

    pkgLocation =

     @”C:\test\ssis\ssis1\ssis1\Package.dtsx”;

    app = new Application();

    pkg = app.LoadPackage(pkgLocation, null);

    pkgResults = pkg.Execute();

    Console.WriteLine(pkgResults.ToString());

    Console.ReadKey();

}

After running the code you can see whether it is successful.


Source code download: https://github.com/chanmmn/ssis/tree/master/ConAppSsis

Reference: https://docs.microsoft.com/en-us/sql/integration-services/run-manage-packages-programmatically/loading-and-running-a-local-package-programmatically?view=sql-server-ver15?WT.mc_id=DP-MVP-36769

Posted in .Net, Cloud, Community, Computers and Internet, Data Platform | Tagged | Leave a comment

SSIS Transfer data from one table to another – Basic

This blog article shows you how SSIS transfer data between 2 tables in SQL Server. This article expect you to have basic knowledge of Visual Studio 2019 and you have installed SSIS, https://chanmingman.wordpress.com/2019/06/04/ssis-for-visual-studio-2019/.

This is basic and is good for anyone wants to start with SSIS. I have reviewed all my blog articles but nothing as simple and straightforward so I would create this one. For example, I have 2 tables, Products and ProductsNew, in poc database.

Both with the following table structure.

CREATE TABLE [dbo].[Products](

    [ProductID] [int] IDENTITY(1,1) NOT NULL,

    [ProductName] [nvarchar](40) NOT NULL,

    [SupplierID] [int] NULL,

    [CategoryID] [int] NULL,

    [QuantityPerUnit] [nvarchar](20) NULL,

    [UnitPrice] [money] NULL,

    [UnitsInStock] [smallint] NULL,

    [UnitsOnOrder] [smallint] NULL,

    [ReorderLevel] [smallint] NULL,

    [Discontinued] [bit] NOT
NULL
)
ON [PRIMARY]

Create a SSIS Project in Visual Studio. Drag Data Flow Task to Control Flow.

Double click the Data Flow Task. Drag OLE DB Source to Data Flow page.

Double click Data Flow Task.to configure a new Connection Manager. In this example I am using localhost so I put a . (dot) in the Server name and Select he poc database.

Choose Products table.

Drag the OLD BE Destination to Data Flow page.

Double click OLD BE Destination. Select the same database connection created for the OLD DB Source. Select ProductsNew as the destination table.

Click Mappings to map all the columns except ProductID because ProductID is an i==Identity column.

Click OK and execute the package.

Source code download: https://github.com/chanmmn/ssis/tree/master/ssisTransfer2Tables.

Video: https://youtu.be/GGCZWxumk2A

Reference: https://docs.microsoft.com/en-us/sql/integration-services/lesson-1-create-a-project-and-basic-package-with-ssis?view=sql-server-ver15?WT.mc_id=DP-MVP-36769

Posted in .Net, Cloud, Community, Computers and Internet, Data Platform | Tagged , | 1 Comment

Function returns multiple value C#

This blog shows you how to define a function that returns multiple values in C#. In the sample below I defined 3 return values. I used to teach students that function can only returns a single value. This no longer apply to C#. Below is the signature for a function returns 3 values, it can be 2.

private static (int, int, int) fun()

{

    return (4, 5, 3);

}

I then have code calling the above function like the one below.

static void Main(string[] args)

{

    (int x, int y, int z) = fun();

    Console.WriteLine(“{0} {1} {2}”,x,y,z);

    Console.ReadLine();

}

You can see the result as below when you run it.


Source Code Download: https://github.com/chanmmn/general/tree/master/ConAppMultipleReturn

Reference: https://docs.microsoft.com/en-us/dotnet/csharp/methods?WT.mc_id=DP-MVP-36769

Posted in .Net, Cloud, Community, Computers and Internet | Leave a comment

SQL Server Create a table from another database

This blog article should you just a single statement to duplicate a table from another database but in the same instance. For example, I have 2 databases one is called NorthWind and another is called poc. I want to create the same table structure as the Products in Northwind in poc database.

The poc has no table.

Issue the statement below then you will be able to duplicate the table structure including the data. In my case, the Product is duplicated to poc database.

SELECT
*
INTO Products FROM [NorthWind].[dbo].[Products]

Reference: https://docs.microsoft.com/en-us/sql/t-sql/queries/select-into-clause-transact-sql?view=sql-server-ver15?WT.mc_id=DP-MVP-36769

Posted in .Net, Cloud, Community, Computers and Internet, Data Platform | Tagged , | Leave a comment

ASP.NET Blazor Master Details CRUD

This blog article shows you how to do Create, Read, Update Delete (CRUD) in ASP.NET Blazor in a single page. This blog expert you to have basic knowledge of C#. First create a model class to hold 2 data members as follow.

public class ProductModel

{

    public string ProductName { get; set; }

    public string UnitPrice { get; set; }

}

Create a Razor Component under the Pages folder. I named the page.ProductMasterDetail.razor.


Replace all the code on the page with the following code

@page “/productmd”

@using BlazorCRUDList.Data

<h3>Product</h3>

@if (list == null)

{

    <p><em>Loading…</em></p>

}

else

{

    @*<p>Product Name: @productName</p>*@

    <p>Product Name: <input @bind=”productName/></p>

    @*<p>Product Name: @unitPrice</p>*@

    <p>Unit Price: <input @bind=”unitPrice/></p>

    <button class=”btn btn-primary” @onclick=”AddProduct“>Add</button>

    <button class=”btn btn-primary” @onclick=”SaveProduct“>Save</button>

    <button class=”btn btn-primary” @onclick=”DeleteProduct“>Delete</button>

    <table class=”table”>

        <thead>

            <tr>

                <th>Product Name</th>

                <th>Unit Price (C)</th>

            </tr>

        </thead>

        <tbody>

            @foreach (var product in list)

            {

                <tr>

                    <td>@product.ProductName.</td>

                    <td>@product.UnitPrice</td>

                    @*<input @bind=”unitPrice” />*@

                    <td><input type=”button” class=”btn btn-primary” @onclick=”(() => PrepareForEdit(product))data-toggle=”modal” data-target=”#taskModal” value=”Edit”/></td>

                </tr>

            }

        </tbody>

    </table>

}

@code
{

    private ProductModel[] productModels;

    private List<ProductModel> list = new List<ProductModel>();

    private float unitPrice { get; set; }

    private string productName { get; set; }

    protected override async Task OnInitializedAsync()

    {

        list = new List<ProductModel>()

            {

                new ProductModel{ProductName=“Chai”, UnitPrice=“1” },

                new ProductModel{ProductName=“Aniseed Syrup”, UnitPrice=“2” },

                new ProductModel{ProductName=“Chang”, UnitPrice = “3”}

            };

    }

    private void PrepareForEdit(ProductModel task)

    {

        productName = task.ProductName;

        unitPrice = float.Parse(task.UnitPrice);

    }

    private void AddProduct()

    {

        ProductModel product = new ProductModel();

        product.ProductName= productName;

        product.UnitPrice = unitPrice.ToString();

        list.Add(product);

    }

    private void SaveProduct()

    {

        var result = from r in list where r.ProductName == productName select r;

        result.First().UnitPrice = unitPrice.ToString();

    }

    private void DeleteProduct()

    {

        var result = from r in list where r.ProductName == productName select r;

        list.Remove(result.First());

    }

}

Run the application. Use http://localhost:44185/productmd to reach the page.


Source Code Download: https://github.com/chanmmn/BlazorApp/tree/master/BlazorCRUDList

Reference: https://docs.microsoft.com/en-us/aspnet/core/blazor/?view=aspnetcore-5.0?WT.mc_id=DP-MVP-36769

Posted in .Net, Cloud, Community, Computers and Internet, Data Platform | Tagged , , | Leave a comment

Winform Master Detail CRUD C#

This blog article provides a complete CRUD in Winform with Master Detail concept. Not all the applications are suitable for web such as Point of Sales application. This blog is good for those who want to start a Winform project as well as the student learning Winform.

This sample application is using C# List for CRHD.


The code 4 key features are listed below.

1. Get the data for editing.

private void btnEdit_Click(object sender, EventArgs e)

{

    if (dataGridView1.SelectedRows.Count != 0)

    {

        DataGridViewRow row = this.dataGridView1.SelectedRows[0];

        txtProductID.Text = row.Cells[“ProductID”].Value.ToString();

        txtProductName.Text = row.Cells[“ProductName”].Value.ToString();

    }

}

2. Save the data after edit.

privat evoid btnSave_Click(object sender, EventArgs e)

{

    var result = from r in list where r.ProductID == int.Parse(txtProductID.Text) select r;

    result.First().ProductName = txtProductName.Text;

//Bind to datagridvview

    var bindingList = new BindingList<Products>(list);

    var source = new BindingSource(bindingList, null);

    dataGridView1.DataSource = source;

}

3. Delete a record from List.

private
void btnDelete_Click(object sender, EventArgs e)

{

    if (txtProductID.Text != “”)

    {

        int pid = int.Parse(txtProductID.Text);

        var result = from r in list where r.ProductID == pid select r;

        list.Remove(result.First());

        var bindingList = new BindingList<Products>(list);

        var source = new BindingSource(bindingList, null);

        dataGridView1.DataSource = source;

}

4. Add a record from List.

private
void btnAdd_Click(object sender, EventArgs e)

{

    Products product = new Products();

    product.ProductID = int.Parse(txtProductID.Text);

    product.ProductName = txtProductName.Text;

    list.Add(product);

    var bindingList = new BindingList<Products>(list);

    var source = new BindingSource(bindingList, null);

    dataGridView1.DataSource = source;

    }

}

Source Code Download: Net5Winform/WinFormsMaintenance at master · chanmmn/Net5Winform (github.com)


Reference: https://docs.microsoft.com/en-us/dotnet/desktop/winforms/?view=netdesktop-5.0?WT.mc_id=DP-MVP-36769

Posted in .Net, Cloud, Community, Computers and Internet, Data Platform | Tagged , , , | Leave a comment

CTO May 2021 articles and resources

These are the good reads found in this month.

16 traits of a world class chief innovation officer

  • Collaborative
  • Valuing diversity
  • Humble …


https://www.cio.com/article/3613075/16-traits-of-a-world-class-chief-innovation-officer.html?upd=1618132623483

3 Opportunities For CMOs To Capitalize On In 2021

  • Opportunities for CMOs in 2021: More Channels of Communication—and Cooperation
  • Opportunities for CMOs in 2021: Embracing the Right Amount of Digital
  • Opportunities for CMOs in 2021: Focusing on the Real Customer

https://www.forbes.com/sites/danielnewman/2021/03/22/3-opportunities-for-cmos-to-capitalize-on-in-2021/?ss=bigdata&sh=2485bb871715

7 business skills every IT leader needs to succeed

1. An entrepreneurial mindset

2. Strong leadership skills

3. A consumer-oriented focus

https://www.cio.com/article/3613957/7-business-skills-every-it-leader-needs-to-succeed.html?upd=1618741672230

5 great security tools built right into Windows

  • Scan options
  • Parental controls
  • System restore point

https://www.pcworld.com/article/3614627/5-security-tools-built-into-windows-10.html

How IT Executives Are Running IT as a Business

  • Business Value Realization: Ashley Pettit, Sr. VP and CIO (State Farm)
  • Reaching the Value Layer of IT: Chris Burger, VP Global Technology (IHG)
  • Cross-Functional Partnerships Unlock Insights: Atticus Tysen, SVP & CIO, Sharon Hutchins, Director, IT Business Operations and Special Services, Gregory Moreau, Senior Manager, Finance (Intuit)

https://thestrategicciojournal.com/2021/03/15/how-it-executives-are-running-it-as-a-business-2/

Resources: Delivering personalised experiences in times of change https://bit.ly/3dr6R2l

Posted in .Net, Cloud, Community, Computers and Internet, CTO | Tagged | Leave a comment