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
{
    public class LoginRedirectByRoleSection : ConfigurationSection
    {
        [ConfigurationProperty("roleRedirects")]
    public RoleRedirectCollection RoleRedirects
        {
    get
            {
    return (RoleRedirectCollection)this["roleRedirects"];
            }
    set
            {
    this["roleRedirects"] = value;
            }
        }
    }
    public class RoleRedirect : ConfigurationElement
    {
        [ConfigurationProperty("role", IsRequired = true)]
    public string Role
        {
    get
            {
    return (string)this["role"];
            }
    set
            {
    this["role"] = value;
            }
        }
        [ConfigurationProperty("url", IsRequired = true)]
    public string Url
        {
    get
            {
    return (string)this["url"];
            }
    set
            {
    this["url"] = value;
            }
        }
    }
    public class RoleRedirectCollection : ConfigurationElementCollection
    {
    public RoleRedirect this[int index]
        {
    get
            {
    return (RoleRedirect)BaseGet(index);
            }
        }
    public RoleRedirect this[object key]
        {
    get
            {
    return (RoleRedirect)BaseGet(key);
            }
        }
    protected override ConfigurationElement CreateNewElement()
        {
    return new RoleRedirect();
        }
    protected override object GetElementKey(ConfigurationElement element)
        {
    return ((RoleRedirect)element).Role;
        }
    }
}

<configSections>
    <section name="loginRedirectByRole" type="CustomConfigSection.LoginRedirectByRoleSection,CustomConfigSection" allowLocation="true" allowDefinition="Everywhere" />
    </configSections>
    <loginRedirectByRole>
    <roleRedirects>
    <add role="Administrator" url="~/Admin/Default.aspx" />
    <add role="User" url="~/User/Default.aspx" />
    </roleRedirects>
    </loginRedirectByRole>

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using CustomConfigSection;
namespace CustomConfigSection
{
    public partial class WebForm1 : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
        {
           LoginRedirectByRoleSection roleRedirectSection = (LoginRedirectByRoleSection)ConfigurationManager.GetSection("loginRedirectByRole");
    foreach (RoleRedirect roleRedirect in roleRedirectSection.RoleRedirects)
            {
    if (Roles.IsUserInRole("", roleRedirect.Role))
                {
                    Response.Redirect(roleRedirect.Url);
                }
            }
        }
    }
}

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;
namespace AsyncDemo
{
class Program
    {
static void Main(string[] args)
        {
string url = @"http://microsoft.com";
            DownloadAsync(url);
            Console.WriteLine("Doing Some more work in main");
            Console.ReadLine();
        }
private static void DownloadAsync(string url)
        {
var httpwebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpwebRequest.BeginGetResponse(ar =>
                {
var webResponse = httpwebRequest.EndGetResponse(ar);
using (var responseStream = webResponse.GetResponseStream())
                    {
var manulaResetEvent = new ManualResetEvent(false);
//Set the buffer size
byte[] buffer = new byte[1024];
//Callback
                        AsyncCallback readCallback = null;
                        readCallback = ir =>
                            {
var bytesRead = responseStream.EndRead(ir);
if (bytesRead > 0)
                                {
                                    Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, buffer.Length));
                                    responseStream.BeginRead(buffer, 0, buffer.Length, readCallback, null);
                                }
else
                                {
//Alowing waiting thread to proceed
                                    manulaResetEvent.Set();
                                }
                            };
                        responseStream.BeginRead(buffer, 0, buffer.Length, readCallback, null);
//Block the current thread
                        manulaResetEvent.WaitOne();
                    }
                }, null);
        }
    }
}

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.cs



using 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;
using System.Windows.Shapes;

namespace MVVMDEMO.ViewModel
{
    /// <summary>
    /// 
    /// </summary>
    public class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            var propertyChanged = PropertyChanged;

            if (propertyChanged != null)
            {
                propertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }



    }
}

Kth Largest Element in Array


public class KthElement
    {
    public static int 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];
    else if (k < rank)
    return kthElement(arr, k);
    else
    return kthElement(arr, k - rank);
           }
           
       }
    private static int 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;
       }
    private static void Swap(int[] arr, int i, int j)
       {
    int temp = arr[i];
           arr[i] = arr[j];
           arr[j] = temp;
       }
    }

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:

  1. change a letter,
  2. insert a letter, or
  3. delete a letter




class EditDistanceAlgo
    {
        static int[,] m;
        public static char diagCh;
        public static int LevenshteinDistance(string s, string t)
        {
        int[,] d = new int[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 operation
        else
                        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] + 1 //a substitution
                            );
            TraceBack("", "", "", d, s.Length, t.Length, s, t);
        return d[s.Length, t.Length];
        }
        public static void TraceBack(string row1, string row2, string row3, int[,] mm, int i, int j, string s1, string s2)
        {
        string result = "";
        if (i > 0 && j > 0)
            {
        var diag = mm[i - 1, j - 1];
                diagCh = '|';
        if (s1[i - 1] != s2[j - 1])
                {
                    diag++; diagCh = ' ';
                }
        if (mm[i, j] == diag)
                    TraceBack(s1[i - 1] + row1, diagCh + row2, s2[j - 1] + row3, mm, i - 1, j - 1, s1, s2);    // change or match
        else if (mm[i, j] == mm[i - 1, j] - 0 + 1) // delete
                    TraceBack(s1[i - 1] + row1, ' ' + row2, '-' + row3, mm, i - 1, j, s1, s2);
        else
                    TraceBack('-' + row1, ' ' + row2, s2[j - 1] + row3, mm, i, j - 1, s1, s2);      // insertion
            }
        else if (i > 0)
                TraceBack(s1[i - 1] + row1, ' ' + row2, '-' + row3, mm, i - 1, j, s1, s2);
        else if (j > 0)
                TraceBack('-' + row1, ' ' + row2, s2[j - 1] + row3, mm, i, j - 1, s1, s2);
        else // i==0 and j==0
                result += row1 + '\n' + row2 + '\n' + row3 + '\n';
            Console.WriteLine(result);
        }//traceBack
    }


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;

public class Knapsack
{
    static int nbObjects = 8;
    static int[] weight = { 2, 3, 5, 2, 4, 6, 3, 1 };
    static int[] utility = { 5, 8, 14, 6, 13, 17, 10, 4 };
    static int weightmax = 12;
    static int[,] array;
    static void 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];
        }
    }
    public static void SolveDP()
    {
        array = new int[nbObjects, weightmax + 1];
        // initialize the first row
        for (int j = 0; j <= weightmax; j++)
            if (j < weight[0])
            {
                array[0, j] = 0;

            }
            else
            {
                array[0, j] = utility[0];

            }
        // for all other rows
        for (int i = 1; i < nbObjects; i++)
        {
            for (int j = 0; j <= weightmax; j++)
            {
                if (j - weight[i] < 0)
                    array[i, j] = array[i - 1, j];
                else
                    array[i, j] = Math.Max(array[i - 1, j], array[i - 1, j - weight[i]] + utility[i]);
            }
        }
        Display();
    }

}