6 posts tagged “tutorial”
Note: This article assumes you have done some Java web development in the past, and you are capable of compiling and executing web applications with J2EE.
Overview
J2EE has done some amazing things in progressing the creation of custom tags. Now it is fairly easy to integrate any custom HTML tag within your application further separating the view from designers. This article will show you how to implement a custom HTML tag that calculates the square of a number by simply placing <math:square num="12" /> into your web application. Hopefully, you can feel the power with this simple feature.
Creating the class
Every custom tag extends SimpleTagSupport. This is a class implemented by the J2EE spec which allows a class to output information to a jsp. So, lets get right to coding. Create a class in your web application that extends javax.servlet.jsp.tagext.SimpleTagSupport. If you are compiling by hand, the class file must go in the package structure under /WEB-INF/classes/ i.e. /WEB-INF/classes/com/cyberkruz/test/NewMath.class
l
Every attribute in your custom tag must have a Java Bean mutator property to go with it. This is handled with reflection to send the parameter to your class.package com.cyberkruz.test;
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class NewMath extends SimpleTagSupport {
private Integer num;
/**
* Method overridden which is called
* by the jsp.
*/
public void doTag() throws JspException, IOException {
// Gets the jsp context and prints the
// number squared.
this.getJspContext().getOut().print(this.num * this.num);
}
/**
* Sets a number that our custom
* tag squares.
* @param num The number to which
* we want to square.
*/
public void setNum(Integer num) {
this.num = num;
}
}
Configuring the application to use the class
Now, all we have to do is let our application know that the new tag is there. To do so, we can set up a TLD file which looks much like the document descriptor for configuring servlets. So lets do it! Create a new file called MyTags.tld and place it in the /WEB-INF directory. Then type the following:
<?xml version="1.0" encoding="iso-8859-1" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3c.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<tlib-version>1.2</tlib-version>
<uri>myTags</uri>
<tag>
<description>Custom tags</description>
<name>Square</name>
<tag-class>com.cyberkruz.test.NewMath</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>num</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
This file configures our web application to use our new custom tag. Multiple tags can be placed and mapped with this single file. The taglib directive just specifies the schemas for this particular file and version. The uri specifies what location these tags are being mapped to. Under the tag element, the description and name should be pretty straight forward. The tag-class element points this tag to the class that we wrote previously. the body-content is stating that we don't want inline scripting for this element. Now the attribute tag is fairly interesting. While optional, it maps the num variable to our setter in the class we specified. Then, it says we must have it there (required element) and it can be specified at run time (rtexprvalue).
Now all we have to do is use it!
Place our new tag in a jsp
Allowing our jsp to use the custom tag is the easiest part. It only requires a single declaration.
<%@ taglib prefix="math" uri="myTags" %>
The taglib keyword tells the jsp what we are trying to do. The prefix is what we want to put before the tags when we call them, and the uri points to the uri specified in the tld file. This is going to load every tag that is configured in that tld file that we made previously.
Now, let's put it in a jsp. Create a jsp file called SimpleTest.jsp and place it in your web application. Place the following in your jsp:
<%@page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib="" prefix="math" uri="myTags" %>
<html>
<head>
<title>SimpleTest</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
10 squared is: <math:Square num="10" />.
</body>
</html>
Run it on your web server and... YAY! This is a base introduction to what you can do with custom simple tags. More information about how to use these is below. Enjoy!
More information
http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPTags7.html
For archive purposes, I am posing a custom, generic, sortable, event-driven, doubly-linked list. In the future I will run some tests on it to see if it beats the current linked list implementation provided by the .NET framework. For those unsure of what a linked list is, here is a small tutorial on it.
Collections
When programming a computer, it is very common to store many items of the same type. Some different types of storing methods include array's, lists, and linked lists. The array is probably the most common for those attempting to store items. When an array of items is specified, the computer goes into memory and searches for a place to allocate the array. If it cannot allocate the entire array, it will keep searching. until it can.
Note: I put 5 spaces in the array definition. This is because of a manifest placed in the array, however, the inter workings of memory is beyond the scope of this article.
Now the problem with the array rises when someone runs out of room in their array. If they have an array that is 5 items large, and they want to hold a 6th, they must now re-define an entirely new array that can hold the new information. This requires the computer to go through and find another spot in memory that is big enough, place the new array in there, and then copy the elements from the original array to the new array. This problem is where a linked list comes in handy.
The Linked List
When a linked list is used, every item is stored in a chain of items. The linked list works by housing the references to the next (and previous in doubly linked lists) items in the chain. To do this, it is common to house your value inside a node. That node contains a reference in memory to the next node. Thus, you can define nodes anywhere you want in memory as long as you link to it making it easy to add and remove any amount of elements in the chain. The code would look something like this if you are trying to store integers:
public class LinkedList
{
Node firstNode;
public class Node
{
Node previous;
Node next;
int value;
}
}
Problems
With anything in computer science, there are downfalls to using Linked Lists. In order to get to an element in the linked list, you must traverse the entire list until you get to that element. This can be time consuming if there are a lot of nodes. Another problem is if you lose a reference to one of the nodes, you break the entire list. However, in a lot of circumstances, it is very useful to be able to add and remove items on the fly just by changing references.
Source
Here is an example doubly linked list example that I wrote. Thank dusda for the event driven idea. It is a doubly linked list that will convert to an array if needed. It supports any data type, and automatically sorts if specified. There is even support for getting an item by it's location (index). I hope you all find it useful.
using System;
namespace Systepic.Collections
{
/// <summary>
/// Event Handler designed to be thrown
/// when a collection's list items change.
/// </summary>
/// <param name="sender">The list that
/// fired the event.</param>
/// <param name="e">Information about
/// what the event did.</param>
public delegate void CollectionEventHandler(
Object sender, CollectionEventArgs e);
/// <summary>
/// Class inheriting from EventArgs designed
/// to hold information about the state change
/// of a collection.
/// </summary>
public class CollectionEventArgs : EventArgs
{
public CollectionEventArgs():base(){}
}
/// <summary>
/// A generic sortable linked list.
/// </summary>
/// <typeparam name="T">The type
/// that the linked list is. The type
/// should be a valuetype or a string
/// in order to be sorted.</typeparam>
public class LinkedList<T>
{
/// <summary>
/// An event fired whenever the collection
/// contents change.
/// </summary>
public event CollectionEventHandler ListChanged;
/// <summary>
/// The initial node to iterate in the list.
/// </summary>
private Node<T> firstNode;
/// <summary>
/// The number of items in the linked list.
/// </summary>
private int count;
/// <summary>
/// Whether or not it is a sorted list.
/// </summary>
private bool sorted;
/// <summary>
/// Create a new unsorted
/// linked list.
/// </summary>
public LinkedList() : this(false) { }
/// <summary>
/// Create a new linked list that
/// can be a sorted linked list.
/// </summary>
/// <param name="sorted">Whether or not
/// the linked list should be sorted.</param>
public LinkedList(bool sorted)
{
this.count = 0;
this.sorted = sorted;
}
/// <summary>
/// Adds an item to the end of the current
/// linked list. If the linked list is a
/// sorted list, the list is re-sorted.
/// </summary>
/// <param name="item">The item that should
/// be added to the linked list.</param>
/// <returns>Whether or not the item was
/// added successfully.</returns>
public bool Add(T item)
{
// Add if there is none
if (this.count == 0)
this.firstNode = new Node<T>(item);
else
{
Node<T> temp = this.firstNode;
for (int x = 1; x < this.count; ++x)
temp = temp.Next;
// Add a new item to the list
temp.Next = new Node<T>(
item, temp, null);
}
// increment the counter.
++count;
if (this.sorted) this.Sort();
// fire the event
if (this.ListChanged != null)
this.ListChanged(this,
new CollectionEventArgs());
// Call the insertAt method.
return true;
}
/// <summary>
/// Insert an item at a specified index in
/// the linked list. If the linked list is
/// a sorted list, the list is re-sorted.
/// </summary>
/// <param name="item">The item to add to the
/// linked list.</param>
/// <param name="index">The 0 based index of where
/// it should be added at.</param>
/// <returns>Whether or not the item was added
/// successfully.</returns>
public bool InsertAt(T item, int index)
{
// make sure the index is valid
if (index < 0)
throw new IndexOutOfRangeException();
if (index >= this.count)
throw new IndexOutOfRangeException();
// make sure there is an actual place to insert
if (count == 0)
return false;
// Create temp node to store info
Node<T> tempNode = new Node<T>(item);
// Create a temporary for iteration
Node<T> temp = this.firstNode;
// get to the specified index
for (int x = 1; x <= index; ++x)
temp = temp.Next;
// get the current reference.
if (index > 0)
{
Node<T> prev = temp.Previous;
prev.Next = tempNode;
tempNode.Previous = prev;
}
// set the references
tempNode.Next = temp;
temp.Previous = tempNode;
if (index == 0)
this.firstNode = tempNode;
// update the list information
++count;
if(this.sorted) this.Sort();
// fire event
if (this.ListChanged != null)
this.ListChanged(this,
new CollectionEventArgs());
return true;
}
/// <summary>
/// Find a particular item and remove
/// it from the linked list.
/// </summary>
/// <param name="item">The item to find
/// in the list.</param>
/// <returns>Whether or not the item
/// was removed successfully.</returns>
public bool Remove(T item)
{
// make sure we can remove
if (count < 1)
return false;
Node<T> temp = this.firstNode;
// Iterate and find item
for (int x = 1; x <= this.count; ++x)
{
if ((item as object) == (temp.Value as object))
{
// Change the references
if (temp.HasNext && temp.HasPrevious)
{
temp.Previous.Next = temp.Next;
temp.Next.Previous = temp.Previous;
}
else if (temp.HasNext)
temp.Next.Previous = null;
else if (temp.HasPrevious)
temp.Previous.Next = null;
else
temp = null;
// Reset the first Node if we
// removed it.
if (x == 1 && temp != null)
this.firstNode = temp.Next;
// Handle the counter
--count;
}
if (temp != null && temp.HasNext)
temp = temp.Next;
}
// Resort the algorithm if it is
// a sorted algorithm
if (this.sorted) this.Sort();
// fire event
if (this.ListChanged != null)
this.ListChanged(this,
new CollectionEventArgs());
return true;
}
/// <summary>
/// Sorts a list using insertion sort. Although
/// this algorithm is considered slow, since the
/// list is always almost sorted, the time to sort
/// the list is really fast whereas most high speed
/// algorithms will not beat this in this particular
/// instance because they handle near-sorted
/// algorithms the same as unsorted.
/// </summary>
/// <returns>Whether or not the
/// list was sorted successfully.</returns>
public bool Sort()
{
if (this.firstNode.Value is IComparable)
{
// check index out of range
if (this.firstNode.Next == null)
return true;
// get the base comparison
Node<T> baseNode = this.firstNode.Next;
// traverse the nodes
for (int x = 2; x <= this.count; ++x)
{
if ((baseNode.Previous.Value as
IComparable).CompareTo(
baseNode.Value) == 1)
{
Node<T> comp = this.firstNode;
bool found = false;
for (int y = 1; y < x && found != true; ++y)
{
if ((baseNode.Value as
IComparable).CompareTo(comp.Value) != 1)
{
// We need to change the references
// to all of the nodes to re-order them.
if (baseNode.HasNext)
{
baseNode.Next.Previous =
baseNode.Previous;
baseNode.Previous.Next =
baseNode.Next;
}
else
baseNode.Previous.Next = null;
baseNode.Next = comp;
if (comp.HasPrevious)
{
comp.Previous.Next =
baseNode;
baseNode.Previous =
comp.Previous;
}
else
baseNode.Previous = null;
comp.Previous = baseNode;
// the references are set... make
// sure the first node gets reset
// if needed.
if (y == 1)
this.firstNode = baseNode;
found = true;
}
// Set the next node
if (comp.HasNext)
comp = comp.Next;
}
}
// Set the next node
if (baseNode.HasNext)
baseNode = baseNode.Next;
}
return true;
}
else
return false;
}
/// <summary>
/// Clears all of the items in the
/// list by removing the reference
/// to the first node. The remaining
/// nodes no longer have references to
/// the application and will be collected
/// by the GC.
/// </summary>
public void Clear()
{
// kill the reference
this.firstNode = null;
// reset the count
this.count = 0;
// let everyone know.
if (this.ListChanged != null)
this.ListChanged(this,
new CollectionEventArgs());
}
/// <summary>
/// Converts the linked list to
/// an array.
/// </summary>
/// <returns>An array of the items
/// in the linked list ordered by
/// their location in the list top
/// down.</returns>
public T[] ToArray()
{
if (this.count < 1)
return default(T[]);
T[] newArray = new T[this.count];
// create a temp node
Node<T> temp = this.firstNode;
newArray[0] = temp.Value;
// iterate and get the node
for (int x = 1; x < this.count; ++x)
{
temp = temp.Next;
newArray[x] = temp.Value;
}
return newArray;
}
/// <summary>
/// Allows the use of this linked list
/// like it is an array. Get an item
/// in the linked list by it's location
/// in the list.
/// </summary>
/// <param name="index">The 0 based location
/// of the item to get in the list.</param>
/// <returns>The item at the specified
/// location.</returns>
public T this[int index]
{
get
{
// make sure we can do it before traversal.
if (index + 1 > count)
throw new IndexOutOfRangeException();
// create a temp node
Node<T> temp = this.firstNode;
// iterate and get the node
for (int x = 1; x <= index; ++x)
temp = temp.Next;
// return the node value
return temp.Value;
}
set
{
// make sure we can do it before traversal.
if(index + 1 > count)
throw new IndexOutOfRangeException();
// create a temp node
Node<T> temp = this.firstNode;
// iterate and get the node
for (int x = 0; x < index; ++x)
temp = temp.Next;
// set the node to value
temp.Value = value;
}
}
/// <summary>
/// How many nodes are contained in the
/// Linked List.
/// </summary>
public int Length
{
get { return this.count; }
}
/// <summary>
/// Whether or not this list sorts
/// automatically.
/// </summary>
public bool IsSorted
{
get { return this.sorted; }
set { this.sorted = value; }
}
/// <summary>
/// Generic node with pre and post references
/// for use in a linked list.
/// </summary>
/// <typeparam name="U">The type of
/// information contained within the node.</typeparam>
private class Node<U>
{
/// <summary>
/// The node reference to the node
/// before this node reference.
/// </summary>
Node<U> pre;
/// <summary>
/// The node reference to the node after
/// this node reference.
/// </summary>
Node<U> post;
/// <summary>
/// The generic information stored within
/// the node.
/// </summary>
U assignment;
/// <summary>
/// Create a new node with references
/// to both sides of the node.
/// </summary>
/// <param name="info">What the node actually
/// contains.</param>
/// <param name="previous">The node before this
/// node.</param>
/// <param name="next">The node after this
/// node.</param>
public Node(U info, Node<U> previous, Node<U> next)
{
this.assignment = info;
this.pre = previous;
this.post = next;
}
/// <summary>
/// Create a new node with no references
/// to nodes.
/// </summary>
/// <param name="info">The information
/// that the node actually contains.</param>
public Node(U info) : this(info, null, null) { }
/// <summary>
/// The node before this node in the chain.
/// </summary>
public Node<U> Previous
{
get { return this.pre; }
set { this.pre = value; }
}
/// <summary>
/// The node after this node in the chain.
/// </summary>
public Node<U> Next
{
get { return this.post; }
set { this.post = value; }
}
/// <summary>
/// Whether or not the node has a node
/// reference to the previous node.
/// </summary>
public bool HasPrevious
{
get { return (this.pre == null) ? false : true; }
}
/// <summary>
/// Whether or not the node has a node
/// reference to the next node.
/// </summary>
public bool HasNext
{
get { return (this.post == null) ? false : true; }
}
/// <summary>
/// The actual value stored in this node.
/// </summary>
public U Value
{
get { return this.assignment; }
set { this.assignment = value; }
}
}
}
}
This small tutorial is really just a personal reference, but to those who find it useful I'm glad. I'm currently running a T60p, and the wireless when we upgraded the internet was still slow. With a few optimizations however, one can get the full speed and usage of their network card.
First, go to http://www.dslreports.com/tweaks.
Click on start.
If start doesn't come up, you might need the JRE plugin for your browser. If so, then download and install it.
Click on Results once it has finished.
Fill out the connectivity form for tweak suggestions.
If you are like me, you got a suggestion for optimization.
Under Notes and Recommendations, look for "choose RWIN between some number and some number."
Download DRTCP.
When you open the application, under Tcp Receive Window, put in the second number listed on choose RWIN between some number and some number.
Make sure that you have the right network adapter selected.
Save the settings.
Restart your computer.
Here are my before and afters. The difference is kind of amazing. Thank you vancottt for this information. Have fun.
Introduction
I decided for my reference and by requests of various people, that I would write a full installation tutorial for Ubuntu with all of the cool features of XGL and Beryl on the T60. The cool thing about Ubuntu is it installs and configures a lot of your drivers for you (including wireless) so it is fairly painless to get everything up and running. I wrote this tutorial dual-booting Windows XP with my T60p (2007-93U).
Getting the live cd
Snag the latest desktop download iso from here. Burn it off and boot her up. When everything boots up and you are in UBUNTU, double click the installer. Follow the instructions for partitoning and the keyboard and everything. I will post pictures soon. Then sit back and watch it install. After it is done installing, reboot and pull the cd out.
This is how my partitions are set up.
Holy moly, the majority of our stuff is installed aready. Network support for the T60 hardware is fully functional for both the wired and wireless connection. That definatly makes things easy. You are going to want to be online for this so go configure your networking. It is in:
System->Administraton->Networking
Once you set up your network settings, you can test them by opening up a browser and trying to navigate to a site.
Video
Now that we can access the internet, we need to get the video drivers installed so we can use XGL. In order to do that, we need to change our package manager to have the restricted packages. So open up a terminal (Applications->Accessories->Terminal) and type the following:
sudo nano /etc/apt/sources.list
I went and uncommented every line that started with deb in order to get all of the packages we could use. Also, if you are on a broadband connection, I usually delete the top cdrom line as well. Once this is done, type ctrl-x-y and hit enter to get back to the terminal. Now we must update our packages and it is a good idea to upgrade any packages we have installed and may be out of date so type into the terminal:
sudo aptitude update
sudo aptitude upgrade
sudo aptitude install linux-restricted-modules
sudo aptitude install xorg-driver-fglrx
sudo depmod -a
There we go, now we have video driver support installed. But we have to set up our xserver to reflect our new found drivers.
sudo aticonfig --initial
sudo aticonfig --overlay-type=Xv
And now, I like to go into my configuration and give myself a higher resolution to run at:
sudo cp /etc/X11/xorg.conf /etc/X11/xorg.conf.bak
sudo nano /etc/X11/xorg.conf
Scroll down to where it says Section "Screen" and look for a section called SubSection "Display with a Depth of 24. Under Modes, I like a higher resolution so add 1600x1200 like shown below:
SubSection "Display"
Depth 24
Modes "1600x1200" "1024x768" "800x600" "640x480"
EndSubSection
Now scroll all the way to the bottom and add the following to the bottom of the configuration file.
Section "Extensions"
Option "Composite" "0"
EndSection
Just for those wondering why this is done, the fglrx drivers at the time of this writing don't have support for composite extensions. Now press ctrl-x-y and press alt+backspace to restart the x-server. You should see a higher resolution x-server, and when you log in, things should be smoother. Just to verify, open up a terminal (Applications->Accessories->Terminal) and type:
glxinfo |grep direct
If the response is:
direct rendering: Yes
Congratulations you have working video drivers!
XGL and Beryl
Well that was fairly boring, now on to XGL. Using your terminal, open up your sources.list again by typing:
sudo nano /etc/apt/sources.list
Scroll to the bottom and add this line:
deb http://ubuntu.beryl-project.org/ edgy main-edgy
ctrl-x-y to save and exit and now we can get the key. The key? Well the packages are digitally signed with a key for validation and we need to add that key. So type this in command to get the key:
sudo wget http://ubuntu.beryl-project.org/quinn.key.asc --quiet -O - | sudo apt-key add -
And it should come back with the response: OK. Now we can install XGL and beryl with our package manager. So type:
sudo apt-get update
sudo apt-get install beryl beryl-core beryl-plugins beryl-plugins-data beryl-settings beryl-manager emerald emerald-themes xserver-xgl
We have everything we need installed, now we just have to configure it. We are going to create a custom session for XGL. So type the following into your terminal:
sudo nano /usr/share/xsessions/xgl.desktop
When it opens, add this too it:
[Desktop Entry]
Encoding=UTF-8
Name=Xgl
Exec=/usr/bin/startxgl.sh
Icon=
Type=Application
ctrl-x-y to save and close the file and then type:
sudo nano /usr/bin/startxgl.sh
When it opens, add this to it:
#!/bin/sh
Xgl -fullscreen :1 -ac -accel glx:pbuffer -accel xv:pbuffer &
sleep 4
export DISPLAY=:1
exec gnome-session
ctrl-x-y to save and close. We need to be able to execute the scripts we just wrote so type:
sudo chmod a+x /usr/bin/startxgl.sh
If you are wondering exactly what we just did with this text editing, we created a desktop entry for our xserver session manager (The first edit). This entry points to our script that executes gnome with xgl (Second edit). Now we just type ctrl-alt-backspace to kill the xserver again. At the login screen, click sessions and select XGL. Now login as normal.
Well things changed, but it looks a little worse then before. Don't worry, we will get to that. We need to test beryl first. Open up a terminal again (Applications->Accessories->Terminal) and type:
beryl-manager
Holy wow again. a logo should pop up and all your borders dissapear, and then ... your windows are all wavy when you move them. Pretty cool. Now we have to finish it all up. First thing we have to do is make beryl start on your startup so click System->Preferences->Sessions. Click on the startup tab and click Add. Type beryl-manager under the startup command and press ok. This will make beryl-manager load on the start. However, we also want to make it look a little better so press add again and type gnome-settings-daemon and press ok. Now press ctrl+alt+backspace to restart xserver again and login again.
Wow, super cool huh? The little red ruby is where you do all your configuration. Have fun!
Another little issue I have is accidentally hitting shift-backspace. If you find this is annoying as well, I have another post about it below.
Note: When using OpenGL games and other programs of the sort, it is better to run them using regular gnome and not XGL. You can do this just by switching the session when you login.
For more information the ATI Wiki and the Beryl Project Wiki are both really good resources.
Overview
I was originally going to just post the information needed for my
reference, but I decided that I had to reference many things all the
time, so I will just post a tutorial. For those people using ASP.NET
often on a large amount of projects have no doubt-ably come across
ASP.NET 2.0's custom roles and membership tools. These tools allow you
to use a lot of prefabricated tools written by the Microsoft developers
in order to perform menial tasks like authentication and role
assignment. The problem is that this system is so flexible, it is hard
to get a lot of documentation about using all of the features, and
searchers are usually pointed to specific information. This tutorial is
going to be short and sweet and demonstrate what I feel would be the
most common and useful usage for the membership and role system.
Our task: A custom authentication system implementing users and roles.
Our technologies: ASP.NET 2.0 written in C# (Visual Studio) using a SqlServer 2005 database.
Setting up the database
Origonally, I was under the assumtion that unless I wrote my own custom
membership and role classes, I would be required to use the ASPNETDB on
SqlExpress (I later found out that a lot of people were under the same
assumption). Well I have no intention of writing unnessissary code, and
I found out that there is a tool that will set up a remote database
according to the specifications of Microsoft's default membership and
role providers. so...
- Run the Visual Studio Command Prompt
- Type aspnet_regsql and press enter
- Go through the wizard provided to set up your database
This will set up your database with all of the stored procedures and tables required. Very fast eh? Onward...
Setting up the website
- Create a new ASP.NET website or open up the existing site.
- Create a new or open up your web.config files
Use the following in your web.config under the <configuration> section
<connectionStrings>
<add name="TestConnection"
connectionString="your connection string here"/>
</connectionStrings>
This section is the connection string for your SqlServer2005 server that you previously configured. It will be used by our membership and roles declarations below. Add the following too your web.config file under the <system.web> section
<roleManager enabled="true" defaultProvider="MyTestRoleProvider">
<providers>
<clear />
<add connectionStringName="TestConnection"
applicationName="/ApplicationName"
name="MyTestRoleProvider"
type="System.Web.Security.SqlRoleProvider" />
</providers>
</roleManager>
<membership defaultProvider="MyTestMembershipProvider"
userIsOnlineTimeWindow="20"
hashAlgorithmType="MD5">
<providers>
<clear />
<add name="MyTestMembershipProvider"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
applicationName="/ApplicationName"
requiresUniqueEmail="true"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
passwordStrengthRegularExpression=""
connectionStringName="TestConnection"
type="System.Web.Security.SqlMembershipProvider" />
</providers>
</membership>
<authentication mode="Forms" />
A little explaination of the above. This section configures your asp.net to handle your new Sql connection with custom membership and roles. The <roleManager> section creates a custom role provider that will be used by asp.net to handle... well roles. The <membership> section defines a custom membership provider that asp.net will use to manage your users. The settings within the TestMembership declaration should be fairly straight forward to control your application as much as possible. That last little bit, just lets ASP.net know that you are using custom authentication.
Now you can use all of the authentication controls within asp.net using SqlServer2005 as well as the nifty ASP.net Web Site Administration Tool.
Happy Coding.
Problem
I was working on a remoting project for an assignment and we came
across a problem in 2.0. As of 2.0 you cannot make cross-thread calls
to a windows forms control. This means that if you are doing an
asyncronous call, most likely, unless your polling the async result, it
will come back on a different thread and you cannot change a windows
form or the controls on it without coming back to the origonal thread.
This is fine if you are making all of your asyncronous calls on the
actual form (You just need to call the Invoke method), but if you are
seperating the asyncronous logic from the presentation layer (Which is
recommended), any results processed from that logic can be difficult to
update in windows forms. Fortunatly, there is a solution within the
AsyncOperation class. I recommend looking into this class if you are
doing anything thread related, but I created a wrapper around the class
to make it a bit easier to use. Hopefully, it will be as useful to you
as it was for me.
How it works
My wrapper simply operates the AsyncOperation class. When you
instantiate the object, you instantiate a copy of the AsyncOperation
class which will hold a reference to the initial thread you
instantiated it on. This means you can make cross-thread calls to it,
and it will execute the code on the origonal thread it was instantiated
on. So, if you instantiate this class within your dll's constructor,
any events or code that you execute that need to work on the windows
forms thread you just call in an anonymous delegate under the
Syncronize method.
Place this class somewhere in your project.
using System;
using System.ComponentModel;
using System.Threading;/// <summary>
/// Class that allows multithread syncronization
/// from asyncronous calls. Anything wrapped with
/// the syncronize method will be executed on the
/// same thread as where the AsyncSyncronizer
/// is instantiated.
/// </summary>
/// <example>
/// Instantiate on thread you want to use
/// AsyncSyncronizer sync = new AsyncSyncronizer();
///
/// // Run on the code you would like to execute.
/// this.sync.Syncronize(
/// delegate
/// {
/// /*Code to Execute*/
/// });
///</example>
public class AsyncSyncronizer
{
/// <summary>
/// Delegate pointing to code executed
/// within the Syncronize method.
/// </summary>
public delegate void AsyncDelegate();/// <summary>
/// Async operation which will push execution
/// to the proper thread.
/// </summary>
private AsyncOperation operation;/// <summary>
/// Creates an object of the AsyncSyncronizer
/// Everything wrapped within the Syncronize
/// method will be executed by default on the
/// thread this is instantiated on. In order to change
/// the thread, run SetThread.
/// </summary>
public AsyncSyncronizer()
{
// Set to this thread.
this.SetThread();
}/// <summary>
/// Sets the thread code will by syncronized to
/// to the current thread running.
/// </summary>
public void SetThread()
{
this.operation =
AsyncOperationManager.CreateOperation(null);
}/// <summary>
/// Runs code within this method on the
/// thread either set by set thread or
/// where the object was instantiated.
/// </summary>
/// <param name="render">The code
/// to execute on the specified thread.</param>
public void Syncronize(
AsyncDelegate render)
{
this.operation.Post(new SendOrPostCallback(delegate(object state)
{
render();
}), null);
this.operation.OperationCompleted();
}
}