Pages

Thursday, January 22, 2009

How to call Server Side function from Client Side Code using PageMethods in ASP.NET AJAX

You cannot call server-side code ‘directly’ from client-side code. That is because by design, the server side code executes at server side and client side code at the client. However there are some workarounds. To call serverside code from javascript, you will need to use AJAX, and the easiest way out, is to use the ASP.NET AJAX Extensions.
One option while using Microsoft ASP.NET AJAX is to call ASP.NET Web services (.asmx files) from the browser by using client script. The script can call a webservice containing server-based methods (Web methods) and invoke these methods without a postback and without refreshing the whole page. However this approach could be overkill sometimes, to perform the simplest of tasks. Moreover the logic needs to be kept in a separate .asmx file. We need something that is more ‘integrated’ with our solution.
The option we are going to use in this article involves PageMethods. A PageMethod is basically a public static method that is exposed in the code-behind of an aspx page and is callable from the client script. PageMethods are annotated with the [WebMethod] attribute. The page methods are rendered as inline JavaScript.
Let us explore PageMethods with an example. The example we will be discussing here may not be the best example to explain PageMethods, but it will give you an idea of how to call server side code from client side. In this example, we will be connecting to the Customers table in the Northwind database. We will have some textboxes which will accept the CustomerID and in turn return the Contact Name of that Customer. The method returning ContactName will be called whenever the textbox loses focus. We will be using the onblur event where a javascript code will take in the value(CustomerID) from the textbox. This javascript function will then call a PageMethod (server side code) which returns the ContactName without any page refresh.
I assume that you have downloaded and installed ASP.NET AJAX extensions for ASP.NET 2.0. If not, I would advise you to download the extensions from here and install it before moving ahead. At any point of time, if you find a difficulty in understanding the code, download the sample project attached with this article at the end.
Step 1: Create an ASP.NET AJAX enabled website. Go to File > New > Website > ASP.NET AJAX-Enabled Web Site. Give the solution a name and location and click Ok.
Step 2: Drag and drop 2 labels and 4 textbox controls. We will be accepting the CustomerID from the user in the 2 textboxes and displaying the ‘ContactName’ in the other two textboxes. The textboxes that will display ‘ContactName’ has some properties set that will make it appear as a label without a border. Just set the BorderStyle=None, BorderColor=Transparent and ReadOnly=True. The markup will look similar to the following:
<form id="form1" runat="server">    
        <asp:ScriptManager ID="ScriptManager1" runat="server"/>
        <div>
        <asp:Label ID="lblCustId1" runat="server" Text="Customer ID 1">asp:Label>
        <asp:TextBox ID="txtId1" runat="server">asp:TextBox><br />
            <asp:TextBox ID="txtContact1" runat="server" BorderColor="Transparent" BorderStyle="None"
                ReadOnly="True">asp:TextBox><br />
        <br />
        <asp:Label ID="lblCustId2" runat="server" Text="Customer ID 2">asp:Label>
         
        <asp:TextBox ID="txtId2" runat="server">asp:TextBox><br />
            <asp:TextBox ID="txtContact2" runat="server" BorderColor="Transparent" BorderStyle="None"
                ReadOnly="True">asp:TextBox> <br />
            div>
    form>
Before moving ahead, we will store our connection string information in the Web.config. Add the following tag below your configSections> tag. Remember we have created an ‘ASP.NET AJAX enabled website’. The tag configSections> along with some other tags automatically get added to the web.config.
<connectionStrings>
            <removename="all"/>
            <addname="NorthwindConnectionString"connectionString="Data Source=(local); Initial Catalog=Northwind; Integrated Security = SSPI;"/>
      connectionStrings>
Step 3: Currently we will add a method, ‘GetContactName()’ which will accept a CustomerID and return the Contact Name information from the Northwind database, Customer table. We will then transform this method as a PageMethod.
C#
public static string GetContactName(string custid)
    {
        if (custid == null || custid.Length == 0)
            return String.Empty;
        SqlConnection conn = null;
        try
        {
            string connection = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
            conn = new SqlConnection(connection);
            string sql = "Select ContactName from Customers where CustomerId = @CustID";
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Parameters.AddWithValue("CustID", custid);
            conn.Open();
            string contNm = Convert.ToString(cmd.ExecuteScalar());
            return contNm;
        }
        catch (SqlException ex)
        {
            return "error";
        }
        finally
        {
            conn.Close();
        }
    }
VB.NET
 Public Shared Function GetContactName(ByVal custid As String) As String
        If custid Is Nothing OrElse custid.Length = 0 Then
            Return String.Empty
        End If
        Dim conn As SqlConnection = Nothing
        Try
            Dim connection As String = ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString
            conn = New SqlConnection(connection)
            Dim sql As String = "Select ContactName from Customers where CustomerId = @CustID"
            Dim cmd As SqlCommand = New SqlCommand(sql, conn)
            cmd.Parameters.AddWithValue("CustID", custid)
            conn.Open()
            Dim contNm As String = Convert.ToString(cmd.ExecuteScalar())
            Return contNm
        Catch ex As SqlException
            Return "error"
        Finally
            conn.Close()
        End Try
    End Function
Step 4: We will now transform this method as a PageMethod and then call this method GetContactName() from client side code; i.e. using JavaScript. To enable the method as a PageMethod, add the attribute [WebMethod] on top of the method:
C#
[System.Web.Services.WebMethod]
public static string GetContactName(string custid)
{
}
VB.NET
_
    Public Shared Function GetContactName(ByVal custid As String) As String
   End Function
At the sametime, add the attribute EnablePageMethods="true" to the ScriptManager as shown below:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/>
Step 5: Let us now create the JavaScript that will call this server side code. Add a javascript file called script.js to your solution (Right Click Project > Add New Item > Jscript File > Rename file to script.js). Add the following code to the javascript file.
function CallMe(src,dest)
 {    
     var ctrl = document.getElementById(src);
     // call server side method
     PageMethods.GetContactName(ctrl.value, CallSuccess, CallFailed, dest);
 }
 
 // set the destination textbox value with the ContactName
 function CallSuccess(res, destCtrl)
 {    
     var dest = document.getElementById(destCtrl);
     dest.value = res;
 }
 
 // alert message on some failure
 function CallFailed(res, destCtrl)
 {
     alert(res.get_message());
 }
 
Step 6: We now need to reference this JavaScript file from our aspx page and invoke the ‘CallMe()’ method whenever the textbox loses focus. To do so:
Add a reference to the javascript file in the body tag as shown below:
<body>
<script type="text/javascript" language="javascript" src="script.js"> script>
    <form id="form1" runat="server">    
………
Step 7: To invoke the methods whenever the textbox looses focus, add these lines of code in the Page_Load() event
C#
if (!Page.IsPostBack)
        {
            txtId1.Attributes.Add("onblur", "javascript:CallMe('" + txtId1.ClientID + "', '" + txtContact1.ClientID + "')");
            txtId2.Attributes.Add("onblur", "javascript:CallMe('" + txtId2.ClientID + "', '" + txtContact2.ClientID + "')");
        }
VB.NET
If (Not Page.IsPostBack) Then
                  txtId1.Attributes.Add("onblur", "javascript:CallMe('" & txtId1.ClientID & "', '" & txtContact1.ClientID & "')")
                  txtId2.Attributes.Add("onblur", "javascript:CallMe('" & txtId2.ClientID & "', '" & txtContact2.ClientID & "')")
End If
As shown above, we are using the Attributes.Add that lets us add an attribute to the server control’s System.Web.UI.AttributeCollection object. The function ‘CallMe’ kept in the ‘script.js’ file will be invoked. We are passing the source and destination textboxes as parameters. The source textbox will contain the CustomerID. The CustomerID will be looked up in the Customers table and the corresponding ‘ContactName’ will be retrieved in the destination textbox.
Well that is all that is needed to invoke server side code from client side. Run the code. Type ‘ALFKI’ in the first textbox and hit the tab key. You will see that the javascript function goes ahead and calls the PageMethod GetContactName() using PageMethods.GetContactName. It passes the value of the source textbox which contains the CustomerID. The ‘ContactName’ returned is displayed in the second textbox below the first one, in our case the value displayed is ‘Maria Anders’.
Troubleshooting: ‘PageMethods Is 'Undefined'’ error
 
1.    Try setting EnablePageMethods="true" in the script manager tag
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/>
2.    Don't add the javascript references or code in the section. Add it to the tag.
 
<body>
<script type="text/javascript" language="javascript" src="script.js"> script>
    <form id="form1" runat="server"> 
    form>
body>
 
3.    Page methods needs to be static in code behind.
 
I hope you have got an idea of how to call server side code using JavaScript. I have used this technique successfully in a few projects and just love and admire PageMethods. I hope you found this article useful and I thank you for viewing it. The source code for this article can be downloaded from ServerCodeFromClientSide.zip

Using RSS Feeds with Asp.net

Introduction:

RSS stands for (Really Simple Syndication). Basically RSS feeds are xml files which are provided by many websites so you can view their contents on your own websites rather than browsing their site. Suppose you are a movie lover and you want to get the list of top 5 movies from 10 websites. One way will be to visit all 10 websites and see the top 5 list. This method though is used in general by lot of people but its quite tiring method. It will take you 10-15 minutes to browse all the websites and see the top 5 list of movies. One easy way will be if those movie websites provides RSS feeds to be used by the users. If they provide RSS feeds you can embed them in your page and now you don't have to browse all the websites since the information is available on a single page. Hence, this saves you a time and a lot of browsing.
Most of the Blogs websites provide RSS feeds so you can embed your or someone's else latest entries of blog on your website. In this article we will see how we can embed RSS feeds to our webform using Asp.net.

Making a simple user interface:

The application that we will build in this article will be really simple which extracts the Rss feeds from some website and display it in the datagrid. Below is the image of the User interface.
As you can see the user interface is pretty simple. It consists of a Label control which says "Rss Feeds". It has a datagrid and a button with the text "Display RSS Feeds". Let's now dig into the code behind and see what's happening behind the scenes.

Getting RSS Feeds from the website:

We have set up our interface and now our task is to find a website that provides Rss so we can display it on our webform. Luckily our own www.msdn.microsoft.com provides Rss feeds. This Rss feeds is about the latest news in the Microsoft industry. Here are the steps that you can use to get to the Rss feeds from the msdn website.
2) You will see a "RSS" link at the top as shown in the picture below:
// Gets the xml from the Url using XmlTextReader
XmlTextReader reader = new XmlTextReader("http://msdn.microsoft.com/rss.xml");
As you can see that we have used XmlTextReader to extract the Xml out of the url. The XmlTextReader has many overloads but we used the one which takes string url as a parameter. The parameter that we are sending is the url that you previously saved.
Now we got the Xml, next we put the xml into the dataset so we can bind it to the datagrid or else the datagrid will feel lonely :). So the next step is to create a DataSet object.
// creates a new instance of DataSet
DataSet ds = new DataSet();
After creating the DataSet we need to fill the dataset with the Xml. DataSet has a ReadXml method that will allow us to ReadXml.
// Reads the xml into the dataset
ds.ReadXml(reader);
Okay now the dataset, which is ds contains the xml. The final step will be to bind the dataset to the datagrid. Here is the line that binds the dataset to the datagrid.
// Assigns the datset to the datagrid
myDataGrid.DataSource = ds;
// Binds the datagrid
myDataGrid.DataBind();
Okay looks good to me. Lets run the application and see what will happen. When you press the button the xml is extracted from the specified url and will be bind to the datagrid. You will see something like this:
Well, we can see that it did got something from the url and binding is done okay. So what's wrong ? It seems like the data we were expecting is not correct. You can blame Microsoft for not providing us with the correct url but before that lets check our code again and see if we can fix it. The following code in button click event will fix the problem:
// Gets the xml from the Url using XmlTextReader
XmlTextReader reader = new XmlTextReader("http://msdn.microsoft.com/rss.xml");
// creates a new instance of DataSet
DataSet ds = new DataSet();
// Reads the xml into the dataset
ds.ReadXml(reader);
// Assigns the data table to the datagrid
myDataGrid.DataSource = ds.Tables[2];
// Binds the datagrid
myDataGrid.DataBind();

As you see we replaced the line where we were binding dataset to the datagrid. Now we are binding Data Table. When the xml is put in the dataset it is put in layers. So first layer/level of xml nesting is placed in first row , 2nd layer in second row and so on. Each Rss file 3rd tag is the item tag which contains the information. Hence our 3rd tag is at he index '2' since we start from '0'. You can try out different combinations with using different indexes and you will be returned with different types of tables.  
Look at the code below in which I am referring to a different table and get the different result.
// Assigns the data table to the datagrid
myDataGrid.DataSource = ds.Tables[4];
// Binds the datagrid
myDataGrid.DataBind();
Conclusion:
As you see embedding Rss feeds on your own page is easy as baking a pie. The good side of using Rss will be that your website will be updated automatically and you won't have to do anything. These days most of the websites are providing Rss feeds that you can use in your web pages.
Project files are also attached with this article. In the project I have added a textbox so you can enter the url of any Rss feed and when you press the button it will be extract the xml, which will be displayed on the web form in the datagrid.
Attachments:
   Project Files: RssFeeds.Zip

Sunday, January 18, 2009

ASP.Net Impersonate

ASP.NET Impersonation
When using impersonation, ASP.NET applications can optionally execute with the identity of the client on whose behalf they are operating. The usual reason for doing this is to avoid dealing with authentication and authorization issues in the ASP.NET application code. Instead, you rely on Microsoft Internet Information Services (IIS) to authenticate the user and either pass an authenticated token to the ASP.NET application or, if unable to authenticate the user, pass an unauthenticated token. In either case, the ASP.NET application impersonates whichever token is received if impersonation is enabled. The ASP.NET application, now impersonating the client, then relies on the settings in the NTFS directories and files to allow it to gain access, or not. Be sure to format the server file space as NTFS, so that access permissions can be set.

Impersonation is disabled by default. For ASP compatibility, the user must explicitly enable impersonation. If impersonation is enabled for a given application, ASP.NET always impersonates the access token that IIS provides to ISAPI extensions. That token can be either an authenticated user token, or the token for the anonymous user (such as IUSR_MACHINENAME). The impersonation occurs regardless of the type of authentication being used in the application.

Only application code is impersonated; compilation and configuration are read as the process token. The result of the compilation is put in the "Temporary ASP.NET files" directory. The account that is being impersonated needs to have read/write access to this directory. If an application is on a universal naming convention (UNC) share, ASP.NET will always impersonate the token provided to IIS to access that share unless a configured account is used. If an explicit configured account is provided, ASP.NET will use that account in preference to the IIS UNC token. Applications that do want per-request impersonation can simply be configured to impersonate the user making the request.

Impersonation is disabled at the computer level by default and, unless overridden, all the application domains inherit this setting. You can enable impersonation by putting a configuration file in the application root directory. For more information about the ASP.NET configuration system, see ASP.NET Configuration.

As is the case with other configuration directives, this directive applies hierarchically. It is respected by nested applications in the hierarchy, unless explicitly overridden. The default value for this setting is as follows.

 Copy Code
A minimal configuration file to enable impersonation for an application might look similar to the following example.

 Copy Code

There is also name support for running an application as a configurable identity. For example:

 Copy Code
This enables the entire application to run as contoso\Jane, regardless of the identity of the request, as long as the password is correct. This type of impersonation can be delegated to another computer.

You can programmatically read the identity of the impersonated user, as shown in the following example.

[Visual Basic] Copy Code
Dim username As String = System.Security.Principal.WindowsIdentity.GetCurrent().Name
[C#]
String username = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

In the preceding example, userName and password are stored in clear text in the configuration file. Although IIS will not transmit .config files in response to a user agent request, configuration files can be read by other means, for instance by an authenticated user with proper credentials on the domain that contains the server. To help increase security, the identity section supports storage of encrypted userName and password attributes in the registry as shown in the following example.

 Copy Code
   userName="registry:HKLM\Software\AspNetIdentity,Name"
   password="registry:HKLM\Software\AspNetIdentity,Password"The portion of the string after the keyword registry and before the comma indicates the name of the registry key that ASP.NET opens. The portion after the comma contains a single string value name from which ASP.NET will read the credentials. The comma is required, and the credentials must be stored in the HKLM hive. If the configuration format is incorrect, ASP.NET will not launch the worker process and the current account creation failure code path will be followed.

The credentials must be in REG_BINARY format, containing the output of a call to the Windows API function CryptProtectData. You can create the encrypted credentials and store them in the registry with the ASP.NET Set Registry console application(Aspnet_setreg.exe), which uses CryptProtectData to accomplish the encryption. To download Aspnet_setreg.exe, along with the Visual C++ source code and documentation, visit the Web site www.asp.net and search for "aspnet_setreg".

You should configure access to the key storing the encrypted credentials so that access is provided only to Administrators and SYSTEM. Because the key will be read by the ASP.NET process running as SYSTEM, you should set the following permissions:

Administrators:F
SYSTEM:F
CREATOR OWNER:F
ProcessAccount:R
This provides two lines of defense to protect the data:

The ACL permissions require the identity accessing the data to be an Administrator.
An attacker must run code on the server (CryptUnprotectData) to recover the credentials for the account.

Sunday, January 11, 2009

Wanna b hacker

Hacking Knowledge: 77 Ways to Learn Faster, Deeper, and Better

knowledgeIf someone granted you one wish, what do you imagine you would want out of life that you haven't gotten yet? For many people, it would be self-improvement and knowledge. New knowledge is the backbone of society's progress. Great thinkers such as Leonardo da Vinci, Thomas Edison, Benjamin Franklin, Albert Einstein, and others' quests for knowledge have led society to many of the marvels we enjoy today. Your quest for knowledge doesn't have to be as Earth-changing as Einstein's, but it can be an important part of your life, leading to a new job, better pay, a new hobby, or simply knowledge for knowledge's sake — whatever is important to you as an end goal.
Life-changing knowledge does typically require advanced learning techniques. In fact, it's been said that the average adult only uses 10% of his/her brain. Imagine what we may be capable of with more advanced learning techniques. Here are 77 tips related to knowledge and learning to help you on your quest. A few are specifically for students in traditional learning institutions; the rest for self-starters, or those learning on their own. Happy learning.

Health

  1. Shake a leg. Lack of blood flow is a common reason for lack of concentration. If you've been sitting in one place for awhile, bounce one of your legs for a minute or two. It gets your blood flowing and sharpens both concentration and recall.
  2. Food for thought: Eat breakfast. A lot of people skip breakfast, but creativity is often optimal in the early morning and it helps to have some protein in you to feed your brain. A lack of protein can actually cause headaches.
  3. Food for thought, part 2: Eat a light lunch. Heavy lunches have a tendency to make people drowsy. While you could turn this to your advantage by taking a "thinking nap" (see #23), most people haven't learned how.
  4. Cognitive enhancers: Ginkgo biloba. Ginkgo biloba is a natural supplement that has been used in China and other countries for centuries and has been reputed to reverse memory loss in rats. It's also suggested by some health practitioners as a nootrope and thus a memory enhancer.
  5. Reduce stress + depresssion. Stress and depression may reduce the ability to recall information and thus inhibit learning. Sometimes, all you need to reduce depression is more white light and fewer refined foods.

Balance

  1. Sleep on it. Dr. Maxwell Maltz wrote about in his book Psycho-Cybernetics about a man who was was paid good money to come up with ideas. He would lock his office door, close the blinds, turn off the lights. He'd focus on the problem at hand, then take a short nap on a couch. When he awoke, he usually had the problem solved.
  2. Take a break. Change phyical or mental perspective to lighten the invisible stress that can sometimes occur when you sit in one place too long, focused on learning. Taking a 5-15 minute break every hour during study sessions is more beneficial than non-stop study. It gives your mind time to relax and absorb information. If you want to get really serious with breaks, try a 20 minute ultradian break as part of every 90 minute cycle. This includes a nap break, which is for a different purpose than #23.
  3. Take a hike. Changing your perspective often relieves tension, thus freeing your creative mind. Taking a short walk around the neighborhood may help.
  4. Change your focus. Sometimes there simply isn't enough time to take a long break. If so, change subject focus. Alternate between technical and non-technical subjects.

Perspective and Focus

  1. Change your focus, part 2. There are three primary ways to learn: visual, kinesthetic, and auditory. If one isn't working for you, try another.
  2. Do walking meditation. If you're taking a hike (#25), go one step further and learn walking meditation as a way to tap into your inner resources and your strengthen your ability to focus. Just make sure you're not walking inadvertently into traffic.
  3. Focus and immerse yourself. Focus on whatever you're studying. Don't try to watch TV at the same time or worry yourself about other things. Anxiety does not make for absorption of information and ideas.
  4. Turn out the lights. This is a way to focus, if you are not into meditating. Sit in the dark, block out extraneous influences. This is ideal for learning kinesthetically, such as guitar chord changes.
  5. Take a bath or shower. Both activities loosen you up, making your mind more receptive to recognizing brilliant ideas.

Recall Techniques

  1. Listen to music. Researchers have long shown that certain types of music are a great "key" for recalling memories. Information learned while listening to a particular song or collection can often be recalled simply by "playing" the songs mentally.
  2. Speedread. Some people believe that speedreading causes you to miss vital information. The fact remains that efficient speedreading results in filtering out irrelevant information. If necessary, you can always read and re-read at slower speeds. Slow reading actually hinders the ability to absorb general ideas. (Although technical subjects often requirer slower reading.) If you're reading online, you can try the free Spreeder Web-based application.
  3. Use acronyms and other mnemonic devices. Mnemonics are essentially tricks for remembering information. Some tricks are so effective that proper application will let you recall loads of mundane information years later.

Visual Aids

  1. Every picture tells a story. Draw or sketch whatever it is you are trying to achieve. Having a concrete goal in mind helps you progress towards that goal.
  2. Brainmap it. Need to plan something? Brain maps, or mind maps, offer a compact way to get both an overview of a project as well as easily add details. With mind maps, you can see the relationships between disparate ideas and they can also act as a receptacle for a brainstorming session.
  3. Learn symbolism and semiotics. Semiotics is the study of signs and symbols. Having an understanding of the symbols of a particular discipline aids in learning, and also allows you to record information more efficiently.
  4. Use information design. When you record information that has an inherent structure, applying information design helps convey that information more clearly. A great resource is Information Aesthetics, which gives examples of information design and links to their sources.
  5. Use visual learning techniques. Try gliffy for structured diagrams. Also see Inspiration.com for an explanation of webs, idea maps, concept maps, and plots.
  6. Map your task flow. Learning often requires gaining knowledge in a specific sequence. Organizing your thoughts on what needs to be done is a powerful way to prepare yourself to complete tasks or learn new topics.

Verbal and Auditory Techniques

  1. Stimulate ideas. Play rhyming games, utter nonsense words. These loosen you up, making you more receptive to learning.
  2. Brainstorm. This is a time-honored technique that combines verbal activity, writing, and collaboration. (One person can brainstorm, but it's more effective in a group.) It's fruitful if you remember some simple rules: Firstly, don't shut anyone's idea out. Secondly, don't "edit" in progress; just record all ideas first, then dissect them later. Participating in brainstorming helps assess what you already know about something, and what you didn't know.
  3. Learn by osmosis. Got an iPod? Record a few of your own podcasts, upload them to your iPod and sleep on it. Literally. Put it under your pillow and playback language lessons or whatever.
  4. Cognitive enhancers: binaural beats. Binaural beats involve playing two close frequencies simultaneously to produce alpha, beta, delta, and theta waves, all of which produce either sleeping, restfulness, relaxation, meditativeness, alertness, or concentration. Binaural beats are used in conjunction with other excercises for a type of super-learning.
  5. Laugh. Laughing relaxes the body. A relaxed body is more receptive to new ideas.

Kinesthetic Techniques

  1. Write, don't type. While typing your notes into the computer is great for posterity, writing by hand stimulates ideas. The simple act of holding and using a pen or pencil massages acupuncture points in the hand, which in turn stimulates ideas.
  2. Carry a quality notebook at all times. Samuel Taylor Coleridge dreamed the words of the poem "In Xanadu (did Kubla Khan)...". Upon awakening, he wrote down what he could recall, but was distracted by a visitor and promptly forgot the rest of the poem. Forever. If you've been doing "walking meditation" or any kind of meditation or productive napping, ideas may suddenly come to you. Record them immediately.
  3. Keep a journal. This isn't exactly the same as a notebook. Journaling has to do with tracking experiences over time. If you add in visual details, charts, brainmaps, etc., you have a much more creative way to keep tabs on what you are learning.
  4. Organize. Use sticky colored tabs to divide up a notebook or journal. They are a great way to partition ideas for easy referral.
  5. Use post-it notes. Post-it notes provide a helpful way to record your thoughts about passages in books without defacing them with ink or pencil marks.

Self-Motivation Techniques

  1. Give yourself credit. Ideas are actually a dime a dozen. If you learn to focus your mind on what results you want to achieve, you'll recognize the good ideas. Your mind will become a filter for them, which will motivate you to learn more.
  2. Motivate yourself. Why do you want to learn something? What do want to achieve through learning? If you don't know why you want to learn, then distractions will be far more enticing.
  3. Set a goal. W. Clement Stone once said "Whatever the mind of man can conceive, it can achieve." It's an amazing phenomenon in goal achievement. Prepare yourself by whatever means necessary, and hurdles will seem surmountable. Anyone who has experienced this phenomenon understands its validity.
  4. Think positive. There's no point in setting learning goals for yourself if you don't have any faith in your ability to learn.
  5. Organize, part 2. Learning is only one facet of the average adult's daily life. You need to organize your time and tasks else you might find it difficult to fit time in for learning. Try Neptune for a browser-based application for "getting things done."
  6. Every skill is learned. With the exception of bodily functions, every skill in life is learned. Generally speaking, if one person can learn something, so can you. It may take you more effort, but if you've set a believable goal, it's likely an achievable goal.
  7. Prepare yourself for learning. Thinking positive isn't sufficient for successfully achieving goals. This is especially important if you are an adult, as you'll probably have many distractions surrounding your daily life. Implement ways to reduce distractions, at least for a few hours at a time, else learning will become a frustrating experience.
  8. Prepare yourself, part 2. Human nature is such that not everyone in your life will be a well-wisher in your self-improvement and learning plans. They may intentionally or subconsciously distract you from your goal. If you have classes to attend after work, make sure that work colleagues know this, that you are unable to work late. Diplomacy works best if you think your boss is intentionally giving you work on the days he/she knows you have to leave. Reschedule lectures to a later time slot if possible/ necessary.
  9. Constrain yourself. Most people need structure in their lives. Freedom is sometimes a scary thing. It's like chaos. But even chaos has order within. By constraining yourself — say giving yourself deadlines, limiting your time on an idea in some manner, or limiting the tools you are working with — you can often accomplish more in less time.

Supplemental Techniques

  1. Read as much as you can. How much more obvious can it get? Use Spreeder (#33) if you have to. Get a breadth of topics as well as depth.
  2. Cross-pollinate your interests. Neurons that connect to existing neurons give you new perspectives and abilities to use additional knowledge in new ways.
  3. Learn another language. New perspectives give you the ability to cross-pollinate cultural concepts and come up with new ideas. As well, sometimes reading a book in its original language will provide you with insights lost in translation.
  4. Learn how to learn. Management Help has a resource page, as does SIAST (Virtual Campus), which links to articles about learning methods. They are geared towards online learning, but no doubt you gain something from them for any type of learning. If you are serious about optimum learning, read Headrush's Crash course in learning theory.
  5. Learn what you know and what you don't. Many people might say, "I'm dumb," or "I don't know anything about that." The fact is, many people are wholly unaware of what they already know about a topic. If you want to learn about a topic, you need to determine what you already know, figure out what you don't know, and then learn the latter.
  6. Multi-task through background processes. Effective multi-tasking allows you to bootstrap limited time to accomplish several tasks. Learning can be bootstrapped through multi-tasking, too. By effective multitasking, I don't mean doing two or more things at exactly the same time. It's not possible. However, you can achieve the semblance of effective multitasking with the right approach, and by prepping your mind for it. For example, a successful freelance writer learns to manage several articles at the same time. Research the first essay, and then let the background processes of your mind takeover. Move on consciously to the second essay. While researching the second essay, the first one will often "write itself." Be prepared to record it when it "appears" to you.
  7. Think holistically. Holistic thinking might be the single most "advanced" learning technique that would help students. But it's a mindset rather than a single technique.
  8. Use the right type of repetition. Complex concepts often require revisting in order to be fully absorbed. Sometimes, for some people, it may actually take months or years. Repetition of concepts and theory with various concrete examples improves absorption and speeds up learning.
  9. Apply the Quantum Learning (QL) model. The Quantum Learning model is being applied in some US schools and goes beyond typical education methods to engage students.
  10. Get necessary tools. There are obviously all kinds of tools for learning. If you are learning online like a growing number of people these days, then consider your online tools. One of the best tools for online research is the Firefox web browser, which has loads of extensions (add-ons) with all manner of useful features. One is Googlepedia, which simultaneously displays Google search engine listings, when you search for a term, with related entries from Wikipedia.
  11. Get necessary tools, part 2. This is a very niche tip, but if you want to learn fast-track methods for building software, read Getting Real from 37 Signals. The Web page version is free. The techniques in the book have been used to create Basecamp, Campfire, and Backpack web applications in a short time frame. Each of these applications support collaboration and organization.
  12. Learn critical thinking. As Keegan-Michael Key's character on MadTV might say, critical thinking takes analysis to "a whole notha level". Read Wikipedia's discourse on critical thinking as a starting point. It involves good analytical skills to aid the ability to learn selectively.
  13. Learn complex problem solving. For most people, life is a series of problems to be solved. Learning is part of the process. If you have a complex problem, you need to learn the art of complex problem solving. [The latter page has some incredible visual information.]

For Teachers, Tutors, and Parents

  1. Be engaging. Lectures are one-sided and often counter-productive. Information merely heard or witnessed (from a chalkboard for instance) is often forgotten. Teaching is not simply talking. Talking isn't enough. Ask students questions, present scenarios, engage them.
  2. Use information pyramids. Learning happens in layers. Build base knowledge upon which you can add advanced concepts.
  3. Use video games. Video games get a bad rap because of certain violent games. But video games in general can often be an effective aid to learning.
  4. Role play. Younger people often learn better by being part of a learning experience. For example, history is easier to absorb through reenactments.
  5. Apply the 80/20 rule. This rule is often interpreted in dfferent ways. In this case, the 80/20 rule means that some concepts, say about 20% of a curriculum, require more effort and time, say about 80%, than others. So be prepared to expand on complex topics.
  6. Tell stories. Venus Flytrap, a character from the sitcom WKRP in Cincinnati, once taught a student gang member about atoms, electrons, and protons by saying that an atom was one big neighborhood, and the protons and neutrons had their own smaller neighborhoods and never mixed. Just like rival gangs. The story worked, and understanding sparked in the students eyes.
  7. Go beyond the public school curriculum. The public school system is woefully lacking in teaching advanced learning and brainstorming methods. It's not that the methods cannot be taught; they just aren't. To learn more, you have to pay a premium in additional time and effort, and sometimes money for commercially available learning tools. There's nothing wrong with that in itself, but what is taught in schools needs to be expanded. This article's author has proven that a nine-year old can learn (some) university level math, if the learning is approached correctly.
  8. Use applied learning. If a high school student were having trouble in math, say with fractions, one example of applied learning might be photography, lenses, f-stops, etc. Another example is cooking and measurement of ingredients. Tailor the applied learning to the interest of the student.

For Students and Self-Studiers

  1. Be engaged. Surprise. Sometimes students are bored because they know more than is being taught, maybe even more than a teacher. (Hopefully teachers will assess what each student already knows.) Students should discuss with a teacher if they feel that the material being covered is not challenging. Also consider asking for additional materials.
  2. Teach yourself. Teachers cannot always change their curricula. If you're not being challenged, challenge yourself. Some countries still apply country-wide exams for all students. If your lecturer didn't cover a topic, you should learn it on your own. Don't wait for someone to teach you. Lectures are most effective when you've pre-introduced yourself to concepts.
  3. Collaborate. If studying by yourself isn't working, maybe a study group will help.
  4. Do unto others: teach something. The best way to learn something better is to teach it to someone else. It forces you to learn, if you are motivated enough to share your knowledge.
  5. Write about it. An effective way to "teach" something is to create an FAQ or a wiki containing everything you know about a topic. Or blog about the topic. Doing so helps you to realize what you know and more importantly what you don't. You don't even have to spend money if you grab a freebie account with Typepad, Wordpress, or Blogger.
  6. Learn by experience. Pretty obvious, right? It means put in the necessary time. An expert is often defined as someone who has put in 10,000 hours into some experience or endeavor. That's approximately 5 years of 40 hours per week, every week. Are you an expert without realizing it? If you're not, do you have the dedication to be an expert?
  7. Quiz yourself. Testing what you've learned will reinforce the information. Flash cards are one of the best ways, and are not just for kids.
  8. Learn the right things first. Learn the basics. Case in point: a frustrating way to learn a new language is to learn grammar and spelling and sentence constructs first. This is not the way a baby learns a language, and there's no reason why an adult or young adult has to start differently, despite "expert" opinion. Try for yourself and see the difference.
  9. Plan your learning. If you have a long-term plan to learn something, then to quote Led Zeppelin, "There are two paths you can go by." You can take a haphazard approach to learning, or you can put in a bit of planning and find an optimum path. Plan your time and balance your learning and living.

Parting Advice

  1. Persist. Don't give up learning in the face of intimdating tasks. Anything one human being can learn, most others can as well. Wasn't it Einstein that said, "Genius is 1% inspiration and 99% perspiration"? Thomas Edison said it, too.
  2. Defy the experts. Dyslexia, in a nutshell, is the affliction of mentally jumbling letters and digits, causing difficulties in reading, writing and thus learning. Sometimes spoken words or numbers get mixed up as well. In the past, "experts" declared dyslexic children stupid. Later, they said they were incapable of learning. This author has interacted with and taught dyslexic teens. It's possible. Helen Keller had no experience of sight, sound, or speech, and yet she learned. Conclusion: There is more than one way to learn; never believe you cannot.
  3. Challenge yourself. People are often more intelligent than they realize. In a world that compartmentalizes and categorizes everything, not everyone is sure where they fit in. And genius can be found in many walks of life. If you honestly suspect that there's more to you than has been "allowed" to be let out, try an IQ test such as the one offered by MENSA. It's unlike the standardized IQ tests given in many schools. You know the kind — the ones which traumatize many young students into thinking they are stupid, simply because the tests don't really assess all student's knowledge and learning ability. And the ability to learn is far, far more important than what you already know.
  4. Party before an exam. Well, don't go that far. The key is to relax. The worse thing to do is cram the night before an exam. If you don't already know a subject by then, cramming isn't going to help. If you have studied, simply review the topic, then go do something pleasant (no more studying). Doing so tells your brain that you are prepared and that you will be able to recall anything that you have already learned. On the other hand, if you didn't spend the semester learning the ideas you need, you might as well go party anyways because cramming at the last minute isn't going to help much at that point.
  5. Don't worry; learn happy. Have a real passion for learning and want to share that? Join a group such as the Joyful Jubilant Learning community [via LifeHack].

Sources For This Article

This is only a partial list of sources, focusing only on Web sites. Many of the ideas presented above come from long years of experience, with information gleaned from dozens of books and tapes on learning and, more recently, Web sites. The Web sites below either present original articles related to the ideas above, or summaries of ideas with links to other Web sites. In the latter case, such Web sites have likely been linked above. Book sources have either been long forgotten or mentioned above.