PriorityQueue in C#

PriorityQueue is a binary heap. Heap is commonly used algorithm. in some area such Graph shortest path and minimum spanning tree, it is very helpful.

both Java and C++ has PriorityQueue, but C# don’t have.

Here is a version of PriorityQueue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class PriorityQueue<T> where T : IComparable<T>
    {
        private List<T> data;
        private bool isMaxHeap = false; 
        /// <summary>
        /// 
        /// </summary>
        public PriorityQueue()
        {
            this.data = new List<T>();
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="isMaxHeap"></param>
        public PriorityQueue(bool isMaxHeap)
        {
            this.data = new List<T>();
            this.isMaxHeap = isMaxHeap;
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="item"></param>
        public void Enqueue(T item)
        {
            data.Add(item);
            int ci = data.Count - 1; // child index; start at end
            while (ci > 0)
            {
                int pi = (ci - 1) / 2; // parent index
                if(isMaxHeap)
                {
                    if (data[ci].CompareTo(data[pi]) <= 0) break;
                } else if (data[ci].CompareTo(data[pi]) >= 0)
                    break; // child item is larger than (or equal) parent so we're done
                T tmp = data[ci]; data[ci] = data[pi]; data[pi] = tmp;
                ci = pi;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public T Dequeue()
        {
            // assumes pq is not empty; up to calling code
            int li = data.Count - 1; // last index (before removal)
            T frontItem = data[0];   // fetch the front
            data[0] = data[li];
            data.RemoveAt(li);
 
            --li; // last index (after removal)
            int pi = 0; // parent index. start at front of pq
            while (true)
            {
                int ci = pi * 2 + 1; // left child index of parent
                if (ci > li) break;  // no children so done
                int rc = ci + 1;     // right child
                if (isMaxHeap)
                {
                    if (rc <= li && data[rc].CompareTo(data[ci]) >= 0) // if there is a rc (ci + 1), and it is smaller than left child, use the rc instead
                        ci = rc;
                    if (data[pi].CompareTo(data[ci]) >= 0) break; // parent is smaller than (or equal to) smallest child so done
                }
                else
                {
 
                    if (rc <= li && data[rc].CompareTo(data[ci]) < 0) // if there is a rc (ci + 1), and it is smaller than left child, use the rc instead
                        ci = rc;
                    if (data[pi].CompareTo(data[ci]) <= 0) break; // parent is smaller than (or equal to) smallest child so done
                }
 
                T tmp = data[pi]; data[pi] = data[ci]; data[ci] = tmp; // swap parent and child
                pi = ci;
            }
            return frontItem;
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public T Peek()
        {
            T frontItem = data[0];
            return frontItem;
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public int Count()
        {
            return data.Count;
        }
 
        public override string ToString()
        {
            string s = "";
            for (int i = 0; i < data.Count; ++i)
                s += data[i].ToString() + " ";
            s += "count = " + data.Count;
            return s;
        }
 
        public bool IsConsistent()
        {
            // is the heap property true for all data?
            if (data.Count == 0) return true;
            int li = data.Count - 1; // last index
            for (int pi = 0; pi < data.Count; ++pi) // each parent index
            {
                int lci = 2 * pi + 1; // left child index
                int rci = 2 * pi + 2; // right child index
 
                if (lci <= li && data[pi].CompareTo(data[lci]) > 0) return false; // if lc exists and it's greater than parent then bad.
                if (rci <= li && data[pi].CompareTo(data[rci]) > 0) return false; // check the right child too.
            }
            return true; // passed all checks
        } // IsConsistent
    }
Posted in Algorithm | Comments Off on PriorityQueue in C#

WCF – How to publish WCF into IIS

1. copy web.config
2. copy service.svc
3. copy dll and pdb file into bin folder
4. in iis, setup a new web instance, and point physical folder address into published folder
setup .net support version correctly for web instance.
5. try http://ip-address:port/service.svc/js or http://ip-address:port/service.svc/jsdebug

Posted in Uncategorized | Comments Off on WCF – How to publish WCF into IIS

Interface out T vs T

The out keyword in generics is used to denote that the type T in the interface is covariant.

check following code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 
        class Fruit { }
 
        class Banana : Fruit { }
 
        interface ICovariantSkinned<out T> { }
 
        interface ISkinned<T> { }
 
        class A<T> : ISkinned<T> { }
        class B<T> : ICovariantSkinned<T> { }
 
        public static void Main()
        {
            ISkinned<Banana> a1 = new A<Banana>();
            ISkinned<Fruit> a = a1;    // compiling error happens here
 
            ICovariantSkinned<Banana> b1 = new B<Banana>();
            ICovariantSkinned<Fruit> b = b1; // compiling passed
        }
Posted in Uncategorized | Comments Off on Interface out T vs T

How to set Visual Studio support C# 7 features.

  • open visual studio and click on project and choose ‘Properties’
  • in ‘Build’ tab, choose ‘Advanced…’, check screen dump
  • in language version, in dropdown list showing in screen dump, there is not ‘C#7’ and ‘C# 7.2’ for visual studio 2015
  • in visual studio 2017, same dropdown list has ‘C# 7.x’ options

Although some ways could update visual studio 2015 to support C# 7, I higly recommand to use visual studio 2017.

wp_check C# version number

wp_language_version_vs2017

Posted in Uncategorized | Comments Off on How to set Visual Studio support C# 7 features.

Typescript – tsc didn’t copy .html .css .txt to destination folder

tsc would translate .ts file to js and keep folder struction.
however, for some special file for tsc, such as .txt, .html, .css, tsc command chooses to ignore them.

we have to copy manually

for cross-platform, we are using node.js copyfiles package to do it.

but ‘copyfiles ./src/**/*.txt ./dist’ won’t work, the final result of that command is all text file would go under ‘./dist/src/path/to/file.txt’

but luckily copyfiles has options to handle and it is key reason why we uses it beside cross-platform.

in package.json add

1
2
3
4
5
  "scripts": {
    ...
    "copy-template": "copyfiles -u 1 ./src/**/*.txt ./dist"
    ...
  }

another way to is to use gulpfiles.js and gulp command line.

1
2
3
4
gulp.task('copy-template', function() {
     return gulp.src('./src/**/*.txt', {base: './src'})
            .pipe(gulp.dest('./dist'));
});

later on, add package.json to invoke this gulpfiles.js

Posted in Typescript | Comments Off on Typescript – tsc didn’t copy .html .css .txt to destination folder

Orchard 2 – Microsoft open source CMS using asp.net core

Here we assume that %Orchard% is Orchard Source code workspace folder

Orchard 2 uses autofac as DI library as well as NHibernate.

%Orchard%\src\Orchard.Web\Global.asax.cs is entry of whole website.

%Orchard%\src\Orchard.Web\Modules\Orchard.Setup\Views\Setup\Index.cshtml
%Orchard%\src\Orchard.Web\Modules\Orchard.Setup\Controllers\SetupController.cs

orchard

after filling at required field, ‘finish setup’ is clicked.
it would invoke following code

1
2
3
4
5
[HttpPost, ActionName("Index")]
public ActionResult IndexPOST(SetupViewModel model)
{
   ...
}

Orchard Init Stage Steps.
– Orchard use lots of Plugin and Module. It has complex loading and caching mechanism.
– I would write a new post for init stage source code of Orchard.

Posted in Orchard | Comments Off on Orchard 2 – Microsoft open source CMS using asp.net core

Asp.net Core publish on Ubuntu

1. Download asp.net core sdk 2 from Microsoft website
2. link ‘dotnet’ command line to ‘/usr/bin/dotnet’
3. publish project and zip all binary files including dlls, scp zip to ubuntu vps
4. export ASPNETCORE_URLS=”http://*:80″
This step is very important, because by default ‘dotnet’ command only create port for ‘localhost:5000’.
without this command, public network interface ‘eth0’ may not get listen any port.

5. run ‘dotnet Target-Project.dll’

Posted in Uncategorized | Comments Off on Asp.net Core publish on Ubuntu

.net core – create project and adding reference by command line only

dotnet new sln # new solution file
mkdir webapi
cd webapi
dotnet new webapi # new project named webapi
dotnet add package Autofac # try to add Autofac
dotnet add package Autofac.Extensions.DependencyInjection
dotnet add package MongoDB.Driver

cd ..
mkdir webapi_test ###important: dont’ name folder to be ‘xunit’, command has bugs for it
dotnet new xunit
dotnet add reference ../webapi/webapi.csproj
dotnet add package Microsoft.AspNetCore.Mvc
dotnet restore # download all references

Posted in .net core | Comments Off on .net core – create project and adding reference by command line only

Code-First EntityFramework – step by step

This is first post for code-first entity framework and how to use it.

1. add entity framework, open project, in VS Package Management
PM> Install-Package EntityFramework

2. Don’t enable migrations, if you enable migrations then, add
Enable migrations only after database is created.

3. create class inherits from DbContext

1
2
3
4
5
    public class SchoolContext : DbContext {
        public DbSet<Course> Courses { get; set; }
        public DbSet<Department> Departments { get; set; }
 
    }

add connection string in web.config with same name ‘SchoolContext’

4. enable migrations
check screen dump, it will create ‘Migrations’ folder and configuration.cs
enable-migration

5. Add-Migration
PM> Add-Migration

VS will ask you to input name and generate cs with today’s Date, check screen dump above.

Posted in entityframework | Comments Off on Code-First EntityFramework – step by step

IIS subdomain configuration

1. open ‘IIS manager’
2. right click on ‘site’ to create a new site
3.leave ip as ‘unsigned’, put all ‘host name’ to subdomain name
for example ‘tool.wudilab.com’
4. go to godaddy to add ‘core’ as subdomain

Posted in IIS | Comments Off on IIS subdomain configuration