Skip to main content

Posts

Showing posts from April, 2013

How to create custom config section in asp.net

You can extend ASP.NET configuration settings with XML configuration elements of
your own. To do this, you create a custom configuration section handler.
The handler must be a .NET Framework class that inherits from 
the System.Configuration.ConfigurationSection class. The section handler 
interprets and processes the settings that are defined in XML configuration 
elements in a specific section of a Web.config file. You can read and write 
these settings through the handler's properties.
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; namespace CustomConfigSection { publicclass LoginRedirectByRoleSection : ConfigurationSection { [ConfigurationProperty("roleRedirects")] public RoleRedirectCollection RoleRedirects { get { return (RoleRedirectCollection)this["roleRedirects"]; } set { this["roleRedirects"] = valu…

How to read webpage asynchronously in c#

most programming languages a called method is executed synchronously, i.e. in the thread of execution from which it is invoked. If the method needs a long time to completion, e.g. because it is loading data over the internet, the calling thread is blocked until the method has finished. When this is not desired, it is possible to start a "worker thread" and invoke the method from there. In most programming environments this requires many lines of code, especially if care is taken to avoid the overhead that may be caused by creating many threads. AMI solves this problem in that it augments a potentially long-running ("synchronous") object method with an "asynchronous" variant that returns immediately, along with additional methods that make it easy to receive notification of completion, or to wait for completion at a later time.




using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Threading; na…

Silverlight MVVM

What is MVVM pattern as per wikipedia "The Model View ViewModel (MVVM) is an architectural pattern used in software engineering that originated from Microsoft as a specialization of the Presentation Model design pattern introduced by Martin Fowler.[1] Largely based on the model–view–controller pattern (MVC), MVVM is a specific implementation targeted at UI development platforms which support the event-driven programming in Windows Presentation Foundation (WPF) and Silverlight on the .NET platforms using XAML and .NET languages. Technically different, but similar, Presentation Model design patterns are available in HTML5[2][3] through KnockoutJS, and for Java the ZK framework (Model-View-Binder)." ViewModelBase.csusing System; using System.ComponentModel; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; u…

Kth Largest Element in Array

publicclass KthElement { publicstaticint kthElement(int[] arr, int k) { int n = arr.Length; int lo = 0; int hi = n - 1; if (lo == hi) return arr[lo]; while (true) { int pivotIndex = Partition(arr, lo, hi); int rank = pivotIndex - lo + 1; if (rank == k) return arr[pivotIndex]; elseif (k < rank) return kthElement(arr, k); elsereturn kthElement(arr, k - rank); } } privatestaticint Partition(int[] arr, int left, int right) { int pivot = arr[left]; int i = left + 1; int j = right; while (i < j) { while (arr[i] <pivot) i++; while (arr[j] >= pivot) j--; if (i < j) Swap(arr, i, j); } Swap(arr, left, j); return j; } privatestaticvoid Swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; …

Levenshtein distance (Edit distance)

The edit distance of two strings, s1 and s2, is defined as the minimum number of point mutations required to change s1 into s2, where a point mutation is one of:

change a letter,insert a letter, ordelete a letter



class EditDistanceAlgo { staticint[,] m; publicstaticchar diagCh; publicstaticint LevenshteinDistance(string s, string t) { int[,] d = newint[s.Length + 1, t.Length + 1]; for (int i = 0; i <= s.Length; i++) d[i, 0] = i; for (int j = 0; j <= t.Length; j++) d[0, j] = j; for (int j = 1; j <= t.Length; j++) for (int i = 1; i <= s.Length; i++) if (s[i - 1] == t[j - 1]) d[i, j] = d[i - 1, j - 1]; //no operationelse d[i, j] = Math.Min(Math.Min( d[i - 1, j] + 1, //a deletion d[i, j - 1] + 1), //an insertion d[i - 1, j - 1] +…

Longest increasing subsequence problem (Dynamic Programming)

The input consists of two sequences ~x = x1, . . . , xn and ~y = y1, . . . , ym. The goal is to find a longest common subsequence of ~x and ~y, that is a sequence z1, . . . , zk that is a subsequence both of ~x and of ~y. Note that a subsequence is not always substring: if ~z is a subsequence of ~x, and zi = xj and zi+1 = xj 0, then the only requirement is that j 0 > j, whereas for a substring it would have to be j 0 = j + 1.For example, let ~x and ~y be two DNA strings ~x = T GACT A and ~y = GT GCAT G; n = 6 and m = 7. Then one common subsequence would be GT A. However, it is not the longest possible common subsequence: there are common subsequences T GCA, T GAT and T GCT of length 4

0/1 Knapsack problem

Description

using System; publicclass Knapsack { staticint nbObjects = 8; staticint[] weight = { 2, 3, 5, 2, 4, 6, 3, 1 }; staticint[] utility = { 5, 8, 14, 6, 13, 17, 10, 4 }; staticint weightmax = 12; staticint[,] array; staticvoid Display() { int i, u, w; u = 0; w = weightmax; for (i = nbObjects - 1; i >= 1; i--) { if (array[i, w] != array[i - 1, w]) { Console.Write((i + 1) + " "); w = w - weight[i]; u = u + utility[i]; } } if (array[0, w] != 0) { Console.WriteLine("1"); w = w - weight[0]; u = u + utility[0]; } } publicstaticvoid SolveDP() { array = newint[nbObjects, weightmax + 1]; // initialize the first rowfor (int j = 0; j <= weightmax; j++) if (j < weight[0]) { arr…

Generate permutations of a given string in c#

In this post I will show you how to generate the permutations of a given string in c#.

Pseudocode:
If you have no more characters left to rearrange, print current permutation

for (every possible choice among the characters left to rearrange) { Make a choice and add that character to the permutation so far Use recursion to rearrange the remaining letters } using System.Collections.Generic; using System; using System.Generic; using System.Linq; using System.Text; namespace Permutation { class Program { staticvoid Main(string[] args) { Permutation("abc"); } /// <summary>/// Wrapper function/// </summary>/// <param name="input"></param>publicstaticvoid Permutation(string input) { RecPermutation("", input); } privatestaticvoid RecPermutation(string soFar, string input) { if (string.IsNullOrEmpty(input)) { …

Recursive merge sort implementation in c#

Merge Sort

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MergeSort { publicclass Program { privateint[] originalArray; privateint[] resultArray; publicvoid MergeSort(int[] array) { this.originalArray = array; this.resultArray = newint[array.Length]; Merge(0, array.Length - 1); } privatevoid Merge(int low, int high) { if (low < high) { int middle = (low + high) / 2; Merge(low, middle); Merge(middle + 1, high); Sort(low, middle, high); } } /// <summary>/// Returns a new sorted list containing the same elements as L/// </summary>/// <param name="low"></param>/// <param name="middle"></param>/// <param name="high"></param>privatevoid Sort(int lo…

Quicksort implementation in c#

Quicksort is a very efficient sorting algorithm invented by C.A.R. Hoare. It has two phases:the partition phase andthe sort phase.Quicksort a good example of the divide and conquer strategy for solving problems. In quicksort, we divide the array of items to be sorted into two partitions and then call the quicksort procedure recursively to sort the two partitions, ie we divide the problem into two smaller ones and conquer by solving the smaller ones.

How to implement selection sort in c#

In this post I will show you how to implement selection sort in c#.Before going to implement selection sort let's describe how selection sort works.

go through the list one item at a time.keep track of the smallest item found.Find the smallest item out and add it to a list of sorted items.Repeat until all the items have been sorted



class Program { // Selection Sort Algorithmpublicstaticvoid SelectionSort(int[] arr) { int i, j; int min; for (i = 0; i < arr.Length - 1; i++) { min = i; for (j = i + 1; j < arr.Length; j++) { if (arr[j] < arr[min]) { min = j; } } Swap(arr, i, min); } } privatestaticvoid Swap(int[] arr, int i, int min) { int temp = arr[i]; arr[i] = arr[min]; arr[m…

C# Lambda Expression One-Liners

In this post I will show you  some  powerful one liner Lambda expression

//Write factorial function using lambda expression Func<int, int> fact = null; fact = x => x == 0 ? 1 : x * fact(x - 1); //Function that prints nth fibonacci number Func<int, int> Fib = null; Fib = (n) => n == 0 || n == 1 ? 1 : Fib(n - 1) + Fib(n - 2); //Function checks that number is odd or even Func<int, bool> IsOdd = null; IsOdd = x => x % 2 != 0; //Merge two array into single arrayint[] arr = newint[] { 1, 2, 3, 4, 5, 6 }; Func<int[], int, int[]> MultiplyEachArrayElement = null; MultiplyEachArrayElement = (n, i) => n.Select(x => x * i).ToArray(); //Merge Two array into single arrayint[] arr2 = newint[] { 1, 2, 3, 4, 5, 6 }; Func<int[], int[], int[]> Merge = null; Merge = (x, y) =>…

Boyer-Moore search algorithm implementation in c#

Boyer-Mooreis a string searching algorithm. It avoids checking most positions in the source string. The implementation here uses constant characters.
publicclass Search { privatestaticint[] BuildBadCharTable(char[] needle) { int[] badShift = newint[256]; for (int i = 0; i < 256; i++) { badShift[i] = needle.Length; } int last = needle.Length - 1; for (int i = 0; i < last; i++) { badShift[(int)needle[i]] = last - i; } return badShift; } publicstaticint boyerMooreHorsepool(String pattern, String text) { char[] needle = pattern.ToCharArray(); char[] haystack = text.ToCharArray(); if (needle.Length > haystack.Length) { return -1; } int[] badShift = BuildBadCharTable(needle); int offset = 0;�����������…