Selection Sort Algorithm using C#

Selection Sort Algorithm is one of the simplest sorting algorithm like BubbleSort. However this is not efficient when it comes to TimeCompexity.

Overview

In this algorithm we try to divide the array into two halves – sorted half and unsorted half. In the first pass, the sorted half contains the first element of the array. In the first pass, we compare the first element (from the sorted half) against the first element in the unsorted half. If first element (in sorted half) is greater than the first element in the unsorted half, we do a swapping of these two items. We continue this process until we finish comparing all elements in the unsorted half. At the end of the first pass, we make sure that first element in the array is the lowest one.This is one pass.

In the second pass, we consider 2nd element in the array and compare against each and every element in the unsorted half. We continue with passing for n-1 iterations (covering up to n-2 th item in the sorted half).

Advantages

  1. Easy to implement the algorithm
  2. In-place sort requires no additional memory for storage

Pseudocode

//Outer loop for passes

for (int i=0 ; i<num.Lenth-1 ; i++)

{

// Inner loop for check and pass

for (int j = i+1; i<num.length;i++)

{

//Check and Swap

if(num[i] > num[j])

{

//Do a swap

temp = a[[i];

a[i] = a[j];

a[j] = temp;

}

}

}

Implementation in C#

using System;

namespace SelectionSort
{
    class Program
    {
        static int [] num = {8,6,5,7,1,2,3};
        static int swapcount = 0;
        static int swapcheck = 0;
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            SelectionSort();
            PrintSortedItems();
        }

        static void SelectionSort()
        {
         
           //Outer loop for number of passes till n-2 th item in the array
            for (int i = 0; i < num.Length-1; i++)
            {
                   int minIndex = i;
                   int passcount = i+1;
                
                Console.WriteLine("This is pass number ----->"+passcount);

                //Inner loop for checking to perform a swap
                for (int j = i+1; j < num.Length; j++)
                {
                    swapcheck = swapcheck+1;
                    Console.WriteLine("  This check for swap -->"+swapcheck);
                    if (num[i]>num[j])
                    {
                        swapcount=swapcount+1;
                        int temp;
                        temp = num[i];
                        num[i] = num[j];
                        num[j] = temp;

                        Console.WriteLine("         This is swap count------->"+swapcount);

                        //minIndex = j;

                    }

                }
                
            }
        }

        static void PrintSortedItems()
        {
            for (int i = 0; i < num.Length; i++)
            {
                Console.WriteLine(num[i]);
            }
        }
    }
}

The complete .NET core project is available in this Github repository https://github.com/sundarnarasiman/SortingAlgorithms

Execution and Results

This is pass number —–>1
This check for swap –>1
This is swap count——->1
This check for swap –>2
This is swap count——->2
This check for swap –>3
This check for swap –>4
This is swap count——->3
This check for swap –>5
This check for swap –>6


This is pass number —–>2

This check for swap –>7
This is swap count——->4
This check for swap –>8
This check for swap –>9
This is swap count——->5
This check for swap –>10
This is swap count——->6
This check for swap –>11


This is pass number —–>3
This check for swap –>12
This is swap count——->7
This check for swap –>13
This is swap count——->8
This check for swap –>14
This is swap count——->9
This check for swap –>15
This is swap count——->10


This is pass number —–>4

This check for swap –>16
This is swap count——->11
This check for swap –>17
This is swap count——->12
This check for swap –>18
This is swap count——->13


This is pass number —–>5
This check for swap –>19
This is swap count——->14
This check for swap –>20
This is swap count——->15


This is pass number —–>6
This check for swap –>21
This is swap count——->16


Printing sorted array
1
2
3
5
6
7
8

Summary

For sorting 7 items, it took 6 passes, 21 checks for swaps and 16 actual swaps. Again, the number of swaps and swap checks are completely dependent on how the elements are arranged in the array. This is not the best performing sorting algorithm. This has the worst case complexity of O(n^2).

Bubble Sort Algorithm C#

Bubble Sort is one of the simplest Sort Algorithms to implement, at the same time it’s not the most efficient.

Overview

We try to compare ‘i’ the element and ‘i+1’ the element in the array of numbers to be sorted. If ‘i’ th element is greater than ‘i+1″, we swap the position of these two numbers in the array. We keep on going next in the array and complete the check and swapping unitil ‘n-1’ and ‘n’ the element. This complete round is called a pass. We try do up to n-1 passes (check and swap) until all the numbers are sorted. This is for sorting in ascending order.

Pseudocode

// Outer loop for n-1 passes

static int [] num = {numbers to be sorted}

For (int k=0;k<n-1);k++)

{

for (int i=0;i<n-k-1;i)

{

if (num[i] > num [i+1])

{

Do a swap

}

}

}

n – size of the array (num.length)

Implementation in C#

The complete code is C# is below.

using System;

namespace BubbleSort
{
    class Program
    {
         static int [] num = {7,6,5,4,3,2,1};
         static int swapcount = 0;
        static void Main(string[] args)
        {
           
            // Total number of passes for swap it is 0 to arr.length-1
           for (int k=0;k<num.Length-1;k++)
           {
               int passcount = k+1;
                Console.WriteLine("This is "+"pass number-----> "+passcount);
                PassAndSwap(num,k);
            }
          // PrintSortedArray(num);
            Console.WriteLine("Hello World!");
        }



        public static void PassAndSwap(int [] input, int pass)
        {
            // Total number of swaps = 0 to arr.length-swap_iteration-1
            for (int i=0; i<input.Length-pass-1;i++)
            {
                

                if (input[i] > input[i+1])
                {
                    swapcount = swapcount+1;
                Console.WriteLine("     This is "+ "swap number ---> "+ swapcount);
                    int temp;
                    temp = input[i];
                    input[i]=input[i+1];
                    input[i+1]=temp;
                   
                }
            }
            PrintSortedArray(num);

        }

       
           
        

        public static void PrintSortedArray(int [] Sorted)
        {
            
            for (int j = 0 ;j<Sorted.Length;j++)
            {
                Console.Write(Sorted[j]+",");
               
            }
             Console.WriteLine("\n");

        }
    }
}

The link for Github repo is https://github.com/sundarnarasiman/SortingAlgorithms/tree/main/BubbleSort

Execution and Output

When we execute the above code we’ll get this output below. For sorting 7 (n) numbers, we can clearly see that this is doing 6 (n-1 passes.

This is pass number—–> 1
This is swap number —> 1
This is swap number —> 2
This is swap number —> 3
This is swap number —> 4
This is swap number —> 5
This is swap number —> 6
6,5,4,3,2,1,7,

This is pass number—–> 2
This is swap number —> 7
This is swap number —> 8
This is swap number —> 9
This is swap number —> 10
This is swap number —> 11
5,4,3,2,1,6,7,

This is pass number—–> 3
This is swap number —> 12
This is swap number —> 13
This is swap number —> 14
This is swap number —> 15
4,3,2,1,5,6,7,

This is pass number—–> 4
This is swap number —> 16
This is swap number —> 17
This is swap number —> 18
3,2,1,4,5,6,7,

This is pass number—–> 5
This is swap number —> 19
This is swap number —> 20
2,1,3,4,5,6,7,

This is pass number—–> 6
This is swap number —> 21
1,2,3,4,5,6,7,

The number of swaps depends on how these numbers are arranged in the array.

Time Complexity

When it comes to time complexity, this is not the best performing sorting algorithm. The time complexity in worst case is O(n^2). We’ll see another sorting algorithm in another post.

AWS DevAx::connect Webinar series – June 2021

We know our developer community is continuously looking for new ways to innovate, build and scale their businesses. Join us for AWS DevAx::connect Webinar Series, a 4-day technical walk through sessions with live demos for developers to learn and build on AWS.

Event Schedule

·       Tuesday, June 1, 2021: Building scalable and maintainable infrastructure with the AWS CDK

·       Thursday, June 3, 2021: Accelerate idea to implementation of Microservices using AWS Copilot

·       Tuesday, June 8, 2021: CI/CD with AWS proton for containers

·       Thursday, June 10, 2021: Build GraphQL enabled applications using Amazon AppSync

Check the full agenda here

Why Attend?

 Whether you are an early-stage developer or have an advanced proficiency level, this series caters to everyone and will show you how to modernize your applications like an expert!

Learn through interactive presentations, live demos and technical insights from AWS experts.

Get your queries answered through Live Q&A session with the experts.

Presenters

  • Mohammed Fazalullah Qudrath, Developer SA – ASEAN, AWS
  • Sundararajan Narasiman, SA – Developer Specialist, AISPL
  • Anitha Deenadayalan, Specialist SA, Dev Readiness, AWS

Join us for AWS DevAx::connect series

WSL2 apt update not working

I have recently set up Windows Subsystem for Linux (WSL2) on my Windows 10 laptop and installed Ubuntu 20.04 LTS. When i tried ‘apt update’ on Ubuntu distro, it failed with following error messages.

> sudo apt-get update
Err:1 http://security.ubuntu.com/ubuntu bionic-security InRelease
  Temporary failure resolving 'security.ubuntu.com'
Err:2 http://archive.ubuntu.com/ubuntu bionic InRelease
  Temporary failure resolving 'archive.ubuntu.com'
Err:3 http://archive.ubuntu.com/ubuntu bionic-updates InRelease
  Temporary failure resolving 'archive.ubuntu.com'
Err:4 http://archive.ubuntu.com/ubuntu bionic-backports InRelease
  Temporary failure resolving 'archive.ubuntu.com'

I did the following to get it working.

Step #1.

On the Ubuntu distro, create a file at this location /etc/wsl.conf.

The file should have the following configuration.

[network]
generateResolvConf = false

If we don’t set this file, WSL will automatically load a default /etc/resolv.conf with default namesever configuration.

Shut down and restart the distro.

Step #2

Delete the default /etc/resolv.conf file.

sudo rm /etc/resolv.conf

Create a new /etc/resolv.conf with the following entry.

nameserver 8.8.8.8

Now, restart the WSL2 and open the distro again. The apt update on WSL2 should work like a charm.

Install Docker Desktop on Windows 10 using WSL2 backend

Nowadays, Docker is the most widely used container runtime for building and running containerized applications/micro-services. The Docker Desktop for Windows is a compelling package that comes with Docker Engine, Docker CLI client, Docker Compose, Notary, Kubernetes and CredentialHelper. In Windows 10, you can install Docker Desktop for Windows and run containers in two modes – Windows Containers mode and Linux Container mode.

I followed the steps in this article to get going. There are two options for setting up Docker on Windows – one using WSL2 back-end and other using hyper-v backend.

In this post, i’m leveraging WSL2 back-end. For leveraging WSL2 backend, Linux kernel update package needs to be installed. Download and run the Docker Desktop install after meeting all the pre-requisistes in the above mentioned article. For setting up WSL2 on Windows 10, you can refer my other blog post.

After successful installation of Docker Desktop for Windows, Log out and Log in back.

The Docker is started automated.

Now I can pull a container image from Powershell terminal.

I can also run the same image from WSL2 terminal.

Thus WSL2 provides seamless integration with Windows 10.

Install WSL2 on Windows 10

I’m a big fan of Windows Subsystem for Linux on Windows 10. I use WSL terminal as the default shell for lot of software development activities. I followed the following steps mentioned in this article Install WSL on Windows 10 | Microsoft Docs to install WSL2 on my Windows 10 (OS Build 19042.928).

Step 1 – Enable the Windows Subsystem for Linux

dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart

Step 2 – Enable Virtual Machine feature

Enable Virtual Machine Platform (an optional feature) before installing WSL2.

dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart

If you have hyper-v enabled, disable that. If you don’t disable hyper-v, you won’t be able to install Linux Kernel update package in step 3.

Restart the machine to complete the installation of WSL.

Step 3 – Linux Kernel update paxckage

Download and run the following Linux Kernel update package.

https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi

If you have hyper-v windows feature enabled, you won’t be able to install this package.

Step 4 – Set WSL 2 as default version

wsl --set-default-version 2

Step 6 – Install required Linux Distro.

In this case, i’m installing Ubuntu 20.0.4 by navigating to WSL store.

This completes the installation of WSL2 on Windows 10.

How to get list of SharePoint Lists in SharePoint 2013 Online using CSOM

In this post, we’ll see how to get the list of the SharePoint List in SharePoint 2013 Online using CSOM.

Open Visual Studio 2013.

File –> New –> Project –> Visual C# –> Console Application  and name it as ‘ReadSharePointLists’

Add a reference to assemblies ‘Microsoft.SharePoint.Client’ and ‘Microsoft.SharePoint.Client.Runtime’.

Import the following two namespaces.

using Microsoft.SharePoint.Client;
using System.Security;

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Copy and paste the following snippet of the code that will help us to fetch the list of SharePoint lists in the SharePoint Online site.

namespace ReadSharePointLists
{
    class Program
    {
        static void Main(string[] args)
        {
            //Replace it with the url of your tenant or your site-collection
            string SiteUrl = "https://yoursite.sharepoint.com";

            System.Uri oUri = new System.Uri(SiteUrl);

            using (ClientContext oClientContext = new ClientContext(SiteUrl))
            {
                //Replace it with your user id for SharePoint Online
                string UserName = "userid@yoursite.onmicrosoft.com";


                //Replace it with your password
                string Password = "password";

                //Create a SecureString object from password string, needed for SharePointOnlineCredentials class
                SecureString SecurePassword = GetSecureString(Password);
                oClientContext.Credentials = new SharePointOnlineCredentials(UserName, SecurePassword);

                //load the properties of web object
                Web oWeb = oClientContext.Web;
                
                //Get all the lists in the web
                oClientContext.Load(oWeb.Lists);
                oClientContext.ExecuteQuery();


                foreach (List oList in oWeb.Lists)
                {
                    Console.WriteLine(oList.Title.ToString());
                
                }
                Console.ReadLine();


            
            }

        }

        private static SecureString GetSecureString(String Password)
        {
            SecureString oSecurePassword = new SecureString();

            foreach (Char c in Password.ToCharArray())
            {
                oSecurePassword.AppendChar(c);

            }
            return oSecurePassword;
        }

    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

After executing this we’ll see the below result, which displays the names of the SharePoint lists in the SharePoint 2013 Online site.clip_image002

 Subscribe to my blog

Configure internet access in Microsoft Azure Virtual Network

I’m setting up a Virtual Network in Azure to host my SharePoint 2013 farm. I’ve configured added the DNS servers of 10.0.0.4 and 10.0.0.5 (as per my pervious article), expecting that I would be able to access the public internet inside the SharePoint 2013 VM’s. I’m able to access only google and few other internet sites inside the VMs, most of the sites including microsoft.com was not accessible.

The fix for this issue is to add the Public DNS servers (168.63.129.16 and 168.62.167.9) to the list of DNS servers in the Azure Virtual Network.

image

After adding the Public DNS servers (168.63.129.16 and 168.62.167.9) , the internet connectivity worked like a charm.

 Subscribe to my blog

How to create a site-collection using CSOM in SharePoint Online

In this post, we’ll see how to create a site-collection using SharePoint 2013 CSOM in SharePoint Online. We’ll be using a console application for the purpose of demonstration.

Open Visual Studio 2013 –> File –> New –> Console Application and name it as ‘CreateSiteCollCSOM’.

Add references to the following assemblies

Microsoft.SharePoint.Client.dll

Microsoft.SharePoint.Client.runtime.dll

Microsoft.Online.SharePoint.Client.Tenant.dll

.

The Microsoft.Online.SharePoint.Client.Tenant.dll will be available in the location C:Program FilesSharePoint Client ComponentsAssemblies, if the SharePoint Client Components SDK is installed.

Import the following namespaces at the top of Program.cs

using  Microsoft.SharePoint.Client;
using System.Security;
using Microsoft.Online.SharePoint.TenantAdministration;

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

static void Main(string[] args)
        {
            


            using (ClientContext oClientContext = new ClientContext("https://yoursite-admin.sharepoint.com"))
            {
                //Assign User Id for your SharePoint Online tenant     
                string UserName = "userid@yoursite.onmicrosoft.com";

                //Assign password for your SharePoint online tenant
                string Password = "password";

                //Create a SecureString object from password string, needed for SharePointOnlineCredentials class
                SecureString SecurePassword = GetSecureString(Password);

                oClientContext.Credentials = new SharePointOnlineCredentials(UserName, SecurePassword);
                

                var oTenant = new Tenant(oClientContext);

                var oSiteCreationProperties = new SiteCreationProperties();


                //Set the url of site-collection to be created
                oSiteCreationProperties.Url = "https://yoursite.sharepoint.com/sites/TestSiteColl";

                //Set the title of site
                oSiteCreationProperties.Title = "Test SiteColl from code";

                //set the site-collection owner
                oSiteCreationProperties.Owner = "userid@yoursite.onmicrosoft.com";

                //set the template of site-collection to be created as TeamSite
                oSiteCreationProperties.Template = "STS#0";

                //set the storge maxium level in MB
                oSiteCreationProperties.StorageMaximumLevel = 200;

                oSiteCreationProperties.UserCodeMaximumLevel = 100;



                SpoOperation oSpoOperation = oTenant.CreateSite(oSiteCreationProperties);

                oClientContext.Load(oTenant);

                oClientContext.Load(oSpoOperation, i=>i.IsComplete);
                oClientContext.ExecuteQuery();

               

                Console.WriteLine("SiteCollection successfully reated");




            }




        }

        private static SecureString GetSecureString(String Password)
        {
            SecureString oSecurePassword = new SecureString();

            foreach (Char c in Password.ToCharArray())
            {
                oSecurePassword.AppendChar(c);

            }
            return oSecurePassword;
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

SharePoint Multitenancy – Faqs–Part 2

This post is the continuation to my previous post tiled SharePoint Multitenancy – Faqs

1. What are multiple ways in which customer sites can be deployed a SharePoint farm enabled with multi-tenancy ?

  • Dedicated application pool and Web application
  • Shared application pool and dedicated Web application
  • Authenticated Sites
  • Unauthenticated Sites
  • Shared Web application

2.  When to choose dedicated web applications for tenants ?

If the customizations required for tenants affect the resources that are shared across a web application, such as a web.config file

3. What will be the recommended strategy when multiple tenants need to be combined in a single web application ?

While combining multiple tenants into one, it is recommended to have one dedicated web application for authenticated content of all the tenants and another dedicated tenant for all unauthenticated content for all the tenants. Finally, it will require two different subscription IDs for tenants for both the types of content. This approach also will make the licensing simpler.

4. What are the factors to be considered while deploying customizations to a multi-tenant environment ?

The following factors need to be considered while deploying customizations to multi-tenant environment :-

  • Do not allow full-trust code to be deployed to the sites
  • Do not allow the customizations that require changes to the shared resources like web.config file
  • Use host named site-collections to create multiple root-level site-collections (domain-named sites) within a web application

5. What is the factor to be considered when the tenant must span 1 database ?

If the tenant needs to span more than 1 database, there must one and only tenant in all those databases (dedicated content databases for a tenant)

6. What is the factor to be considered when the multiple tenant needs to share a database ?

If a tenant needs to share a database with another tenant, those tenants should NOT span databases.

7. How a hosted environment can be scaled out ?

The hosted environment can be scaled out by creating separate set of farms.

a)Services farm – A dedicated services farm can be created for all the services (applicable) that can be shared across farms.

b)Search farm – A dedicated farm can be created to host Search

c)Tenant content farm – Tenant content farms can be scaled out in a similar way as the services farm

8. What is Organizational Units (OU) of Active Directory and how its is relevant in the context of SharePoint hosting?

Organizational units are used to organize users and computer objects in the Active Directory environment. The same Organizational Unit for SharePoint is illustrated below :-

organizational units IU

9. What is the role of Domain Root ?

The Security policies that need to be applied to the entire domain is applied in the Domain policy. They are configured in the GPOs that apply to the entire domain.

10. What is the role of Domain Controllers OU ?

It holds the most sensitive data in the organization, the data which controls the security configuration itself. GPOs are applied at this level to protect the domain controller.

11. What is the role of SharePoint Server OU ?

It has unique role not included in other servers in the directory. It can be placed in its own OU to allow unique policies to be applied on the servers. It can also be segregated from other servers in the directory.

12. What is the role of customers OU ?

The Customer OU (top-level OU) allows all users accounts to be segregated from the rest of the directory. The next level OU would be the respective customer’s OU (like Customer A OU or Customer B OU). In order to give the users the impression they are logging into their own customer domain, use ADSI Edit or another Active Directory tool to edit the uPNSuffixes attributes.

 Subscribe to my blog