Friday, January 28, 2011

Using the ASP.NET AJAX AutoCompleteExtender

The ASP.NET Extender controls require .NET Framework 3.5 to be installed. So the first step is to ensure this. After this download the AjaxControlToolkit.dll file.
Next, the controls have to be added to the Toolbox; To do this we need to add a reference to the AjaxControlToolkit.dll file. This is done in the following way:-

Now, add an AutoCompleteExtender to the WebForm. and set the TargetControlID to the textbox that you wish to have the auto suggestions. Remember, every page that uses an Ajax Control must have a script manager before any controls.
Here is the relevant code-
  <asp:ToolkitScriptManager runat="server">
    </asp:ToolkitScriptManager>

    </div>
    <asp:TextBox ID="txtAutoSuggest" runat="server" Width="400px"></asp:TextBox>
    <asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
        ServiceMethod="GetCompletionList" UseContextKey="True" TargetControlID ="txtAutoSuggest"  MinimumPrefixLength="2" >
    </asp:AutoCompleteExtender>

    </form>



Next, add a AutoCompletePage Method.
[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
    public static string[] GetCompletionList(string prefixText, int count, string contextKey)
    {
        string[] suggestions = { "Hypatia", "Hypatia of Alexandria", "Ptolemy", "Ptolemy Soter" };
        System.Collections.Generic.LinkedList<string> l = new System.Collections.Generic.LinkedList<string>();
        foreach (string suggestion in suggestions)
            if (suggestion.ToLower().Trim().StartsWith(prefixText.ToLower().Trim()))
                l.AddLast(suggestion);
        return l.ToArray<string >();
    }


This method receives the already typed string as prefixText. The code here should be self explanatory.
Here are the Pages:-
AutoSuggest.aspx
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="AutoSuggest.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Auto Suggest Page</title>
   
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:ToolkitScriptManager runat="server">
    </asp:ToolkitScriptManager>
    </div>
    <asp:TextBox ID="txtAutoSuggest" runat="server" Width="400px"></asp:TextBox>
    <asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
        ServiceMethod="GetCompletionList" UseContextKey="True" TargetControlID ="txtAutoSuggest" MinimumPrefixLength="2" >
    </asp:AutoCompleteExtender>
    </form>
</body>
</html>



AutoSuggest.aspx.cs



using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
    public static string[] GetCompletionList(string prefixText, int count, string contextKey)
    {
        string[] suggestions = { "Hypatia", "Hypatia of Alexandria", "Ptolemy", "Ptolemy Soter" };
        System.Collections.Generic.LinkedList<string> l = new System.Collections.Generic.LinkedList<string>();
        foreach (string suggestion in suggestions)
            if (suggestion.ToLower().Trim().StartsWith(prefixText.ToLower().Trim()))
                l.AddLast(suggestion);
        return l.ToArray<string >();
    }
}



web.config


<?xml version="1.0"?>
<!--
    Note: As an alternative to hand editing this file you can use the
    web admin tool to configure settings for your application. Use
    the Website->Asp.Net Configuration option in Visual Studio.
    A full list of settings and comments can be found in
    machine.config.comments usually located in
    \Windows\Microsoft.Net\Framework\v2.x\Config
-->
<configuration>
    <configSections>
        <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
            <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
                <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
                <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
                    <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
                    <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
                    <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
                    <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
                </sectionGroup>
            </sectionGroup>
        </sectionGroup>
    </configSections>
    <appSettings/>
    <connectionStrings/>
    <system.web>
        <!--
            Set compilation debug="true" to insert debugging
            symbols into the compiled page. Because this
            affects performance, set this value to true only
            during development.
        -->
        <compilation debug="true">
            <assemblies>
                <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
                <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
                <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
                <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
                <add assembly="System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
                <add assembly="System.Web.Extensions.Design, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
                <add assembly="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/></assemblies>
        </compilation>
        <!--
            The <authentication> section enables configuration
            of the security authentication mode used by
            ASP.NET to identify an incoming user.
        -->
        <authentication mode="Windows"/>
        <!--
            The <customErrors> section enables configuration
            of what to do if/when an unhandled error occurs
            during the execution of a request. Specifically,
            it enables developers to configure html error pages
            to be displayed in place of a error stack trace.

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        -->
        <pages>
            <controls>
                <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
                <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            </controls>
        </pages>
        <httpHandlers>
            <remove verb="*" path="*.asmx"/>
            <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
        </httpHandlers>
        <httpModules>
            <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        </httpModules>
    </system.web>
    <system.codedom>
        <compilers>
            <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
                <providerOption name="CompilerVersion" value="v3.5"/>
                <providerOption name="WarnAsError" value="false"/>
            </compiler>
            <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
                <providerOption name="CompilerVersion" value="v3.5"/>
                <providerOption name="OptionInfer" value="true"/>
                <providerOption name="WarnAsError" value="false"/>
            </compiler>
        </compilers>
    </system.codedom>
    <!--
        The system.webServer section is required for running ASP.NET AJAX under Internet
        Information Services 7.0.  It is not necessary for previous version of IIS.
    -->
    <system.webServer>
        <validation validateIntegratedModeConfiguration="false"/>
        <modules>
            <remove name="ScriptModule"/>
            <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        </modules>
        <handlers>
            <remove name="WebServiceHandlerFactory-Integrated"/>
            <remove name="ScriptHandlerFactory"/>
            <remove name="ScriptHandlerFactoryAppServices"/>
            <remove name="ScriptResource"/>
            <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        </handlers>
    </system.webServer>
    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
                <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
                <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
            </dependentAssembly>
        </assemblyBinding>
    </runtime>
</configuration>



Using ASP.NET Ajax Extenders is not something that I particularly enjoy. So, in a subsequent I shall show how to do this via simple Java Script. That incidentally would also be of universal use, in PHP, JSP, ASP.NET, etc.













Sunday, January 16, 2011

Matrix Multiplication using Threads.

In general Matrix Multiplication requires m*n*r steps where the First Matrix is m*n, the second n*r and the result matrix m*r. However, realizing that the calculation of all the m*r entries of the result matrix are independent of each other we can do these calculations in parallel. In this application I have tried to contrast both these methods. The savings are pretty dramatic as the size of the matrices is increased. If the Threads were to be run on different processors the savings should be even more dramatic.


This application has two parts Main.java & MatrixMultiplicationForm.java

Main.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package threadedmatrixmultiplication;


public class Main {

    /**
     * @param args the command line arguments
     */
       public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MatrixMultiplicationForm().setVisible(true);
            }
        });
    }

}


MatrixMultiplicationForm.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MatrixMultiplicationForm.java
 *
 * Created on Jan 15, 2011, 8:57:03 PM
 */

package threadedmatrixmultiplication;

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class MatrixMultiplicationForm extends javax.swing.JFrame {

    private long t1,t2;
    private int NoofThread;
    private class MultiplyThread extends Thread
    {
    private int i,k,n;
    public MultiplyThread(int i,int k,int n)
    {
        this.i=i;
        this.k=k;
        this.n=n;
    }
    //**************************************************************@Override
    private synchronized void reduce()
    {
        NoofThread--;
        if(NoofThread<=0)
            t2=new java.util.Date().getTime();
        l2.setText("Thread Time = " + (t2-t1));
    }
    @Override
    public void run()
    {
        m3[i][k].setText("0");
        for(int j=0;j<=n-1;j++)
            m3[i][k].setText("" + (Integer.parseInt(m3[i][k].getText()) + Integer.parseInt(m1[i][j].getText())*Integer.parseInt(m2[j][k].getText())));
       
reduce();
    }
    }
    //***************************************************************


    /** Creates new form MatrixMultiplicationForm */
    private JPanel p1,p2,p3,p4;
    private JTextField txtM,txtN,txtR;
    private JButton bttnFirstMatrix,bttnSecondMatrix,bttnSolve,bttnReset;
    private JTextField[][] m1,m2,m3;
    private JLabel l1,l2;


    public MatrixMultiplicationForm() {
        initComponents();
        l1=new JLabel();
        l2=new JLabel();
        setLayout(new GridLayout(2,2));
        p1=new JPanel();
        p2=new JPanel();
        p3=new JPanel();
        p4=new JPanel();
        p1.setBackground(Color.GREEN);
        p2.setBackground(Color.GREEN);
        p3.setBackground(Color.YELLOW);
        p4.setBackground(Color.PINK);
        add(p1);
        add(p2);
        add(p3);
        add(p4);
        p4.setLayout(new GridLayout(6,2));
        txtM=new JTextField();
        txtN=new JTextField();
        txtR=new JTextField();
        p4.add(l1);
        p4.add(l2);
        p4.add(new JLabel("M"));
        p4.add(txtM);
         p4.add(new JLabel("N"));
        p4.add(txtN);
         p4.add(new JLabel("R"));
        p4.add(txtR);
        bttnFirstMatrix=new JButton("First Matrix");
        bttnSecondMatrix=new JButton("Second Matrix");
        bttnSolve=new JButton("Solve");
        bttnReset=new JButton("Reset");
        p4.add(bttnFirstMatrix);
        p4.add(bttnSecondMatrix);
        p4.add(bttnSolve);
        p4.add(bttnReset);

        bttnSolve.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                try
                {
                   
                    t1=(new java.util.Date()).getTime();
 int m=Integer.parseInt(txtM.getText());
int r=Integer.parseInt(txtR.getText());
    int n=Integer.parseInt(txtN.getText());
    int i,j,k;
    for(i=0;i<=m-1;i++)
        for(j=0;j<=r-1;j++)
            m3[i][j].setText("0");


    for(i=0;i<=m-1;i++)
        for(j=0;j<=n-1;j++)
            for(k=0;k<=r-1;k++)
                m3[i][k].setText("" + (Integer.parseInt(m3[i][k].getText()) + Integer.parseInt(m1[i][j].getText())*Integer.parseInt(m2[j][k].getText())));
     t2=(new java.util.Date()).getTime();
     l1.setText("Direct Time taken = " + (t2-t1));


JOptionPane.showMessageDialog(rootPane,"Now multiplying using Threads");
//Total Number of Thread
NoofThread=m*r;
t1=new java.util.Date().getTime();
for(i=0;i<=m-1;i++)
    for(k=0;k<=r-1;k++)
    {
        MultiplyThread t=new MultiplyThread(i, k, n);
        t.start();

    }


                }
                catch(Exception ex)
                {
                    JOptionPane.showMessageDialog(rootPane, ex);
                }
            }
        });





        bttnSecondMatrix.addActionListener(
                new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                try
                {
                    int m=Integer.parseInt(txtM.getText());
int r=Integer.parseInt(txtR.getText());
    int n=Integer.parseInt(txtN.getText());
    m2=new JTextField[n][r];
    p2.removeAll();
    p3.removeAll();
    p2.setLayout(new GridLayout(n,r));
    for(int i=0;i<=n-1;i++)
        for(int j=0;j<=r-1;j++)
        {
            m2[i][j]=new JTextField();
            p2.add(m2[i][j]);
        }
    p2.doLayout();

     p3.setLayout(new GridLayout(m,r));
     m3=new JTextField[m][r];
    for(int i=0;i<=m-1;i++)
        for(int j=0;j<=r-1;j++)
        {
            m3[i][j]=new JTextField();
            p3.add(m3[i][j]);
        }
    p3.doLayout();
                }
                catch(Exception ex)
                {
                    JOptionPane.showMessageDialog(rootPane, ex);
                }
            }
        }
                );

bttnFirstMatrix.addActionListener(
        new ActionListener()
{
    public void actionPerformed(ActionEvent evt)
    {
try
{
    int m=Integer.parseInt(txtM.getText());
    int n=Integer.parseInt(txtN.getText());
    m1=new JTextField[m][n];
    p1.removeAll();
    p1.setLayout(new GridLayout(m,n));
    for(int i=0;i<=m-1;i++)
        for(int j=0;j<=n-1;j++)
        {
            m1[i][j]=new JTextField();
            p1.add(m1[i][j]);
        }
    p1.doLayout();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(rootPane, ex);
}
    }
});

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Matrix Multiplication");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 452, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>                       

    /**
    * @param args the command line arguments
    */


    // Variables declaration - do not modify                    
    // End of variables declaration                  

}




Friday, January 14, 2011

Breadth First traversal in Binary Trees.

Developed this Program with a friend today. For Depth First traversal a stack is used, and for Breadth First a queue is used.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define SIZE 10


typedef struct mynode
{
int data;
struct mynode* lft;
struct mynode* rt;
}TreeNode;
typedef struct
{
int front,back,count;
TreeNode* data[SIZE];
}Queue;
void addNode(TreeNode** root,int value);
void enque(Queue* q,TreeNode* link);
void deque(Queue* q,TreeNode** link);
void init(Queue* q);
int isEmpty(Queue q);
void breadthFirst(TreeNode* root);
void main()
{
TreeNode* root=NULL;
clrscr();
addNode(&root,10);
addNode(&root,8);
addNode(&root,9);
addNode(&root,7);
addNode(&root,12);
addNode(&root,11);
addNode(&root,13);
breadthFirst(root);
getch();
}
void breadthFirst(TreeNode* root)
{
Queue q;
init(&q);
enque(&q,root);
while(!isEmpty(q))
{
deque(&q,&root);
if(root==NULL)
continue;
printf("%d,",root->data);
enque(&q,root->lft);
enque(&q,root->rt);
}
}
int isEmpty(Queue q)
{
if(q.count<=0)
return(1);
else
return(0);
}
void deque(Queue* q,TreeNode** link)
{
if(q->count<=0)
printf("\nQueue is Empty\n");
else
{
*link=q->data[q->front];
q->front =(q->front + 1) % SIZE;
q->count--;
if(q->count==0)
{
q->front=-1;
q->back=-1;
}
}
}

void enque(Queue* q,TreeNode* link)
{
if(q->count>=SIZE)
printf("\nQueue is full\n");
else
{
q->back =(q->back + 1) % SIZE;
q->count++;
q->data[q->back]=link;
if(q->count==1)
q->front=0;
}
}
void init(Queue* q)
{
q->count=0;
q->front=-1;
q->back=-1;
}
void addNode(TreeNode** root,int value)
{
if((*root)==NULL)
{
*root=(TreeNode*)malloc(sizeof(TreeNode));
(*root)->data=value;
(*root)->lft=NULL;
(*root)->rt=NULL;
}
else
{
if(value<(*root)->data)
addNode(&((*root)->lft),value);
else
addNode(&(*root)->rt,value);
}
}



Think of this as a supplement to the earlier post


Implementing Binary Trees in C


Thursday, January 13, 2011

The Hypatia Software Project

The Hypatia Software Project is a collection of utilities of immense value. It is an exciting collection of Programs & Program samples. It is a collection of applications that are always under development. To download it click here.
Here is a listing of some of the features in the project:-
Search Programs
Just open the View Programs form. Type some text and get matching results. Double click on the options list to get the programs. You can add your own programs via the management menu under utilities.





The Mathematical Graphics

The Mathematical Graphics is available under Utilities/Mathematics/Mathematical Graphics.
It requires a minimum X, a maximum X, a step value, and a mathematical expression in x. Create the axes, then press draw the graph to view the results.

The Calculator:-
The Calculator can be accessed at Utilities/Mathematics/Calculator
In this calculator you can simply type an expression and view the answers immediately.You can also create variables, set their values, and use them in your expressions. Practically all mathematical functions have been implemented.

The Gauss Seidel Iteration Method
The calculator can be accessed at Utilities/Mathematics/The Gauss Seidel Iteration Method.
The picture below shows how to enter the equation.
1) Enter the no of equations and press the Enter Equations button.
2) Enter the equations using any variable name that you desire.
Press the solve button to see it advance to the next step


 The Sorting & Searching form is at Utilities/Algorithms/Sorting & Searching
Enter the array as sequence of numbers separated by a comma .(2,-3,4,5,65,-90). No comma after the last number. Then press Make Array. Then press any of the sorting buttons to view the sort in action.


Fun Graphics
This is at When you must have some fun/Some Fun Graphics
Click the Start Drawing button and then change the parameters to get some brilliant graphics. 
Here are a few samples.


The Towers of Hanoi
This  is at When you must have some fun/The Towers of Hanoi
Enter the no of disks and press the Make Disks button.





Blocker Chess
In this game there is no violence. completely AhinsaWadi. The person with the Yellow coin has to try & get to the opposite end, while the Green coiner has to stop him. Moves can only be diagonal. To start  the game enter your names, enter the points you are playing for and press Start the game.
To move the yellow coin simply click on the desired location. To move the green coin, click to select the coin, then click on the desired destination. There is a list of all played games, and a replay facility. Have fun...



To be continued


Tuesday, January 11, 2011

Creating & using the SQL Membership Provider in ASP.NET 2

This is a continuation of the previous blog Creating & using the SQL Membership Provider in ASP.NET 1.
In this post we shall cover the use of the Login controls in ASP.NET. They are:-
  1. Login
  2. LoginView
  3. PasswordRecovery
  4. LoginStatus
  5. LoginName
  6. CreateUserWizard
  7. ChangePassword
The default Login Page.
ASP.NET requires that we have a default login page. There are two ways of assigning this:-
  • Name a page as Login.aspx
  • Add the following code to the web.config file.
<authentication mode="Forms">
            <forms loginUrl="mylogin.aspx" />
        </authentication>

This will assign mylogin.aspx as the default login page, instead of Login.aspx.



The Login control.

The Login control is used for logging in an user to a ASP.NET website. Be careful not to create the Authenticate event, in which case you have to perform the authentication through code(A part which we shall cover next).We need to set the DestinationPageUrl to which the user shall be directed on successful Login.
Here is the code for the Login Page.
Login.aspx
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Login.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Login Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:Login ID="Login1" runat="server" DestinationPageUrl="~/Welcome.aspx">
        </asp:Login>
   
    </div>
    </form>
</body>
</html>


Login.aspx.cs
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
  
}





The CreateUserWizard is used to create a new user.
Registration.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Registration.aspx.cs" Inherits="Registration" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Registration Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:CreateUserWizard ID="CreateUserWizard1" runat="server">
            <WizardSteps>
                <asp:CreateUserWizardStep runat="server" />
                <asp:CompleteWizardStep runat="server" />
            </WizardSteps>
        </asp:CreateUserWizard>
   
    </div>
    </form>
</body>
</html>



Registration.aspx.cs


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Registration : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}





The LoginView control contains two templates an Anonymous Template for showing content to unauthenticated users, and a LoggedIn Template for showing content to LoggedIn users. In addition we can have templates for different roles(a topic we shall cover in the future). I have placed a LoginView control on the welcome.aspx page. In the Logged In template I have placed a ChangePassword control for changing an existing password. In the anonymous template I have placed the words "Not Logged In". I have also placed a LoginStatus control on the page. This will display an option for Login if no user is logged in.It will display Logout otherwise.
 Here is the code for Welcome.aspx


Welcome.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Welcome.aspx.cs" Inherits="Welcome" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
    </div>
    <asp:LoginView ID="LoginView1" runat="server">
        <LoggedInTemplate>
            <asp:ChangePassword ID="ChangePassword1" runat="server">
            </asp:ChangePassword>
        </LoggedInTemplate>
        <AnonymousTemplate>
            Not Logged In
        </AnonymousTemplate>
    </asp:LoginView>
    <asp:LoginStatus ID="LoginStatus1" runat="server" />
    <asp:LoginName ID="LoginName1" runat="server" />
    </form>
</body>
</html>


Welcome.aspx.cs

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Welcome : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}




The PasswordRecovery control requires  configuration of smtp server. Place the following code in the web.config file

<system.net>
        <mailSettings >
            <smtp>
                <network host="localhost" port="25"   defaultCredentials ="true"/>
            </smtp>
        </mailSettings>
       
    </system.net>



    The password recovery control requires an EMail account to be configured. Here is the code:-
<asp:PasswordRecovery ID="PasswordRecovery1"
            style="position:absolute; top: 282px; left: 280px;" runat="server">
            <MailDefinition From="webmaster@supermail.com">
            </MailDefinition>
        </asp:PasswordRecovery>






Here is the code for the PasswordRecovery.aspx page that contains a PasswordRecovery Control.
PasswordRecovery.aspx
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="PasswordRecovery.aspx.cs" Inherits="PasswordRecovery" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Password Recovery Control</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
  
    </div>
    <asp:PasswordRecovery ID="PasswordRecovery1" runat="server">
        <MailDefinition From="webmaster@supermail.com">
        </MailDefinition>
    </asp:PasswordRecovery>
    </form>
</body>
</html>

 The Registration Page in action:-

The Login Page in action:-

The Welcome Page after Login:-
The PasswordRecovery Page in action:-

In a future post we shall use the Roles API, and also use the Membership API through code.

Saturday, January 8, 2011

Creating & using the SQL Membership Provider in ASP.NET 1

The SQL Membership Provider provides a easy to use,highly customizable and comprehensive framework for creating and managing the membership & role management system for a web site. It provides both a Web Control based framework, and also a programmatic API. To start we need to create a SQL Server database. Here is how you do it ---
  • Create a new Website
  • Open View/Server Explorer
  • Right Click on Data Connections
  • Select Create New SQL Server Database
  • Enter the name of location & name of the Server, then the name of the database.
  • Then press OK.




Now we shall use the aspnet_regsql tool that ships with Visual Studio tools, to configure the newly created database for membership use.

 Here is how you do it ---


Here is the configured database.

Now we shall register our Membership Provider in the machine.config XML File that is to be found under 
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG
Replace C:\Windows with the path of your windows installation.

add the following code in the Connection Strings section:
    <add name="NewMembershipDB" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=MemberShipDB" providerName="System.Data.SqlClient"/>

Add the new MemberShip Provider in the membership/providers section
<add name="NewMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="NewMembershipDB" enablePasswordRetrieval="true" enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="true" passwordFormat="Clear" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="4" minRequiredNonalphanumericCharacters="2" passwordAttemptWindow="10" passwordStrengthRegularExpression=""/>





Use the ASP.Net Configuration tool to configure the membership provider for your website. Select the membership provider that we prepared before:-
Select the Provider Tab and select our membership provider NewMembershipProvider which should be visible there 


Then, open the security tab and select authentication type to: From the Internet
The membership provider is now ready. In the next post we shall use the membership controls in ASP.NET.
This is the link to the next post in the series:-