Monday, 31 October 2011

Showing ToolTip using jquery

var
$(hj).qtip({
content: 'asdjkbhajkdhajksdh
position: {
my:
at:
hj = 'div' + '#' + obj.id;.','bottom left','top right'},
show:
hide:
style: {
tip:
classes: 'style sheet'
});
'click mouseenter','click mouseout',true,}

Saturday, 22 October 2011

WebORB

WebORB is a cross-platform integration server that provides universal connectivity for desktop, browser and mobile clients and corresponding .NET classes, WCF, SOAP and REST services, data and media. Development teams all over the world also use WebORB's productivity tools to get their applications to market faster with greater business success and so can you.

WebORB for .NET is an amazing piece of software. In going over the documentation and examples its easy to see how you can use WebORB and .NET to communicate to your Flash, Flex, AJAX, or (support coming) Silverlight applications. The best thing about WebORB for .NET is that it’s free. You can purchase support for the product if you or your company needs it or your can their Professional Services people assist in any projects you might have (Note: I’m not affiliated with The Midnight Coders).
To go through this tutorial you will need the following:
1. Visual Studio 2008 (I used the professional edition, the Express and Standard Editions should work though)
2. WebORB for .NET
3. Windows with IIS installed
4. A copy of Flex Builder 3 (the evaluation version will work if you don’t own Flex Builder or if your brave you can use the Flex SDK)
Start by creating a new project in Visual Studio. Pick the “Class Library” template from the list of choices and call the new project “MyWebORBExample” and then click “Ok”.

Rename the class file to “MyClass.cs” an change the class’s name from “Class1″ to “MyClass”.
Now we’ll add a method to the class that we can use to communicate back and forth to Flex. Add a new method called “SayHello”:
using System;
using System.Web;
  
namespace MyWebORBExample
{
    public class MyClass
    {
        public string SayHello(string name)
        {
            return "Hello: " + name;
        }
    }
}
We simply pass in a string and get a string back that says hello back. Not hard stuff. Go ahead and compile that code. If the code compiles without error, set the project to build the assembly in “Release” mode and rebuild the solution. Thats all we need to do for now with the C# part of this.

Now we can cheat just a little bit. If you’ve already installed WebORB for .NET then you can go into the WebORB Management Console. If you haven’t installed WebORB for .NET then now would be a good time. On my machine the address is: http://localhost/weborb30/weborbconsole.html
The WebORB Management Console is a powerful tool for working with your projects. I won’t go into detail and what all it’s capable of other than what we will be doing in this tutorial. Click on the “Management” tab and you will see a “Deployed assemblies” area under the “Services” sub-tab. Now we’ll copy that released assembly we just built into WebORB. Copy the “MyWebORBExample.dll” from the release folder into “C:\Inetpub\wwwroot\weborb30\bin” (modify this path if your installation of IIS or WebORB are different). Now go back to the WebORB Management Console and hit the “Refresh” – you should see the assembly show up.

Click on the little grey arrow beside the assembly name and expand it. You’ll notice that the WebORB Management Console begins reflecting on the assembly showing us some information on our class and it’s method(s). You might also notice when you click on “MyClass” the “Code Generator” tab opens and some code is generated for us to call this assembly from Flex/Flash. How cool is that?

Well it gets even more cool when you click on the “sayHello” method below the “MyClass”. Now the “Test Drive” tab opens and we can actually call this method from the WebORB Management Console. Go ahead and call the method now to see how it works. Type in a value (your name) and then press the “Invoke” button. You should see something like this:

Time to fire up Flex Builder 3 and create a new Flex Builder project. Call the project “MyWebORBExampleClient” and make sure the “Application server type” is set to “ASP.NET” and press “Next”.

Click the “Use Internet Information Services (IIS)” radio button on the next screen and fill in the rest of the values with how your IIS and WebORB is setup and make sure to press the “Validate Configuration” button and press “Finish”.

We need to do one more modification to the project before we start on the MXML. Open the project properties from the menu at the top of Flex Builder and insert this into the Flex Compiler’s additional arguments:
-services c:\Inetpub\wwwroot\weborb30\web-inf\flex\services-config.xml
- Again, if your paths are different then adjust these to your settings. Also note that if your path contains spaces you need to wrap the path in quotes like this:
-services "c:\Inetpub\wwwroot\A SPACE IN THE PATH\weborb30\web-inf\flex\services-config.xml"
Click the “Apply” button and then close the window.

We are now ready to write some MXML. Click on the “Design” button in Flex Builder. Now drag a “MX:Panel” from the “Components” area onto the designer surface. Adjust the size to be a little bit bigger than the default and if you want you can set the constraints in the “Flex Properties” panel to be centered on the screen. Finally we need to drag an MX:TextInput, MX:Button, MX:Label, and MX:TextArea onto the panel control. Change the button’s “ID” property to “submit_btn”, it’s “On Click” to “submitClicked();” and it’s “Label” property to “Submit”. Change the label control’s “Text” property to “Enter Your Name:”. Finally set the “ID” property of the InputText control to “input_txt” and the TextArea’s “ID” property to “output_txt”.

Click on the “Source” button now (its right beside the “Design” button at the top of the designer screen). Here is the MXML so far:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Panel width="418" height="222" layout="absolute" horizontalCenter="0" verticalCenter="0" backgroundColor="#EEEEEE" fontFamily="Verdana" fontSize="12">
        <mx:TextInput x="134" y="25" id="input_txt" width="173"/>
        <mx:Button x="315" y="25" label="Submit" id="submit_btn" click="submitClicked();"/>
        <mx:TextArea x="10" y="80" width="377" height="82" id="output_txt"/>
        <mx:Label x="10" y="27" text="Enter Your Name:" fontFamily="Verdana" fontSize="12"/>
    </mx:Panel>
  
</mx:Application>
We will now “cheat” a little by taking that code the WebORB Management Console generated for us earlier and we will use it in here. Go back into the WebORB Management Console and click on “MyClass” so the code generator shows up. Off to the bottom right you will see a “Download Code” button. Click on that and save the resulting file to your file system. Go grab that Zip file and extract it somewhere. Now go back into Flex Builder and from the “Flex Navigator” panel right-click on the “src” folder and choose “New -> Folder”. Name the new folder “MyWebORBExample”. Again from the “Flex Navigator” panel right-click on the “src” folder and choose “Import” from the resulting menu. In the “Import” dialog that opens expand the “General” folder and pick “File System”.

Click on the “Next” button. Browse to where you put those extracted files and select them and then press the “Finish” button.

The result should be this:

Open up those files we just imported and have a look at them. Up in the comments section of the “MyClass.as” you’ll see that they even included some sample code to make this work. Go ahead and switch to the “MyWebORBExampleClient.mxml” window. Add the following code:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
  
    <mx:Script>
        <![CDATA[
           import MyWebORBExample.MyClass;
           import MyWebORBExample.MyClassModel;
  
           [Bindable]
           private var model:MyClassModel = new MyClassModel();
           private var serviceProxy:MyClass = new MyClass( model );
  
           private function submitClicked():void
           {
               serviceProxy.SayHello(input_txt.text);
           }
        ]]>
    </mx:Script>
  
    <mx:Panel width="418" height="222" layout="absolute" horizontalCenter="0" verticalCenter="0" backgroundColor="#EEEEEE" fontFamily="Verdana" fontSize="12">
        <mx:TextInput x="134" y="25" id="input_txt" width="173"/>
        <mx:Button x="315" y="25" label="Submit" id="submit_btn" click="submitClicked();"/>
        <mx:TextArea text="{model.SayHelloResult}" x="10" y="80" width="377" height="82" id="output_txt"/>
        <mx:Label x="10" y="27" text="Enter Your Name:" fontFamily="Verdana" fontSize="12"/>
    </mx:Panel>
  
</mx:Application>
First we imported the two ActionScript files we had imported earlier. Then we use a slightly modified version of the code that the generated MyClass.as had up in the comments. We set the model variable as bindable so it can be bound to other UI controls – like our output_txt control. We added an event handler for the “Submit” button’s click and then we added the data binding to the output_txt control:
<mx:TextArea text="{model.SayHelloResult}" x="10" y="80" width="377" height="82" id="output_txt"/>
Run the project from Flex Builder and you should be able to type in your name and then hit the “Submit” button and see the result:

Saturday, 24 September 2011

Its all about Lists

You have questions about the List collection in the .NET Framework, which is located in the System.Collections.Generic namespace. You want to see examples of using List and also explore some of the many useful methods it provides, making it an ideal type for dynamically adding data. This document has lots of tips and resources on the List constructed type, with examples using the C# programming language.
Key points: Lists are dynamic arrays in the C# language. They can grow as needed when you add elements. They are considered generics and constructed types. You need to use < and > in the List declaration.

Add values

To start, we see how to declare a new List of int values and add integers to it. This example shows how you can create a new List of unspecified size, and add four prime numbers to it. Importantly, the angle brackets are part of the declaration type, not conditional operators that mean less or more than. They are treated differently in the language.
Program that adds elements to List [C#]

using System.Collections.Generic;

class Program
{
    static void Main()
    {
 List<int> list = new List<int>();
 list.Add(2);
 list.Add(3);
 list.Add(5);
 list.Add(7);
    }
}
Adding objects. The above example shows how you can add a primitive type such as integer to a List collection, but the List collection can receive reference types and object instances. There is more information on adding objects with the Add method on this site.
List Add MethodFor loop.

Loops

Here we see how you can loop through your List with for and foreach loops. This is a very common operation when using List. The syntax is the same as that for an array, except your use Count, not Length for the upper bound. You can also loop backwards through your List by reversing the for loop iteration variables. Start with list.Count - 1, and proceed decrementing to >= 0.
Program that loops through List [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
 List<int> list = new List<int>();
 list.Add(2);
 list.Add(3);
 list.Add(7);

 foreach (int prime in list) // Loop through List with foreach
 {
     Console.WriteLine(prime);
 }

 for (int i = 0; i < list.Count; i++) // Loop through List with for
 {
     Console.WriteLine(list[i]);
 }
    }
}

Output
    (Repeated twice)
2
3
7

Count elements

To get the number of elements in your List, access the Count property. This is fast to access, if you avoid the Count() extension method. Count is equal to Length on arrays. See the section "Clearing List" for an example on using the Count property.

Clear List

Here we see how to use the Clear method, along with the Count property, to erase all the elements in your List. Before Clear is called, this List has 3 elements; after Clear is called, it has 0 elements. Alternatively, you can assign the List to null instead of calling Clear, with similar performance. However, after assigning to null, you must call the constructor again.
Program that counts List [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
 List<bool> list = new List<bool>();
 list.Add(true);
 list.Add(false);
 list.Add(true);
 Console.WriteLine(list.Count); // 3

 list.Clear();
 Console.WriteLine(list.Count); // 0
    }
}

Output

3
0

Copy array to List

Here we see an easy way to create a new List with the elements in an array that already exists. You can use the List constructor and pass it the array as the parameter. List receives this parameter, and fills its values from it.
Program that copies array to List [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
 int[] arr = new int[3]; // New array with 3 elements
 arr[0] = 2;
 arr[1] = 3;
 arr[2] = 5;
 List<int> list = new List<int>(arr); // Copy to List
 Console.WriteLine(list.Count);       // 3 elements in List
    }
}

Output
    (Indicates number of elements.)

3
Notes. It is useful to use the List constructor code here to create a new List from Dictionary keys. This will give you a List of the Dictionary keys. The array element type must match the type of the List elements, or the compiler will refuse to compile your code.

Find elements

Here we an example of how you can test each element in your List for a certain value. This shows the foreach loop, which tests to see if 3 is in the List of prime numbers. Note that more advanced List methods are available to find matches in the List, but they often aren't any better than this loop. They can sometimes result in shorter code.
List Find Method
Program that uses foreach on List [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
 // New list for example
 List<int> primes = new List<int>(new int[] { 2, 3, 5 });

 // See if List contains 3
 foreach (int number in primes)
 {
     if (number == 3) // Will match once
     {
  Console.WriteLine("Contains 3");
     }
 }
    }
}

Output

Contains 3

Capacity

You can use the Capacity property on List, or pass an integer into the constructor, to improve allocation performance when using List. My research shows that capacity can improve performance by nearly two times for adding elements. Note however that this is not usually a performance bottleneck in programs that access data.
Capacity Property
TrimExcess method. There is the TrimExcess method on List as well, but its usage is very limited and I have never needed to use it. It reduces the memory used. Note: "The TrimExcess method does nothing if the list is at more than 90 percent of capacity".
msdn.microsoft.com

BinarySearch

You can use the binary search algorithm on List with the instance BinarySearch method. Binary search uses guesses to find the correct element much faster than linear searching. It is often much slower than Dictionary.
BinarySearch List

AddRange and InsertRange

You can use AddRange and InsertRange to add or insert collections of elements into your existing List. This can make your code simpler. See an example of these methods on this site.
List AddRange Use

ForEach method

Foreach loop construct.
Sometimes you may not want to write a regular foreach loop, which makes ForEach useful. This accepts an Action, which is a void delegate method. Be very cautious when you use Predicates and Actions, because they can decrease the readability of your code.
Another useful method. There is a TrueForAll method that accepts a Predicate. If the Predicate returns true for each element in your List, the TrueForAll method will return true also. Else, it will return false.

Join string List example

Here we see how you can use string.Join on a List of strings. This is useful when you need to turn several strings into one comma-delimited string. It requires the ToArray instance method on List. The biggest advantage of Join here is that no trailing comma is present on the resulting string, which would be present in a loop where each string is appended.
Program that joins List [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
 // List of cities we need to join
 List<string> cities = new List<string>();
 cities.Add("New York");
 cities.Add("Mumbai");
 cities.Add("Berlin");
 cities.Add("Istanbul");

 // Join strings into one CSV line
 string line = string.Join(",", cities.ToArray());
 Console.WriteLine(line);
    }
}

Output

New York,Mumbai,Berlin,Istanbul

Get List from Keys in Dictionary

Here we see how you can use the List constructor to get a List of keys in your Dictionary collection. This gives you a simple way to iterate over Dictionary keys, or store them elsewhere. The Keys instance property accessor on Dictionary returns an enumerable collection of keys, which can be passed to the List constructor as a parameter.
Program that converts Keys [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
 // Populate example Dictionary
 var dict = new Dictionary<int, bool>();
 dict.Add(3, true);
 dict.Add(5, false);

 // Get a List of all the Keys
 List<int> keys = new List<int>(dict.Keys);
 foreach (int key in keys)
 {
     Console.WriteLine(key);
 }
    }
}

Output

3, 5

Insert elements

Here we see how you can insert an element into your List at any position. The string "dalmation" is inserted into index 1, which makes it become the second element in the List. Note that if you have to Insert elements extensively, you should consider the Queue and LinkedList collections for better performance. Additionally, a Queue may provide clearer usage of the collection in your code.
Program that inserts into List [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
 List<string> dogs = new List<string>(); // Example List

 dogs.Add("spaniel");         // Contains: spaniel
 dogs.Add("beagle");          // Contains: spaniel, beagle
 dogs.Insert(1, "dalmation"); // Contains: spaniel, dalmation, beagle

 foreach (string dog in dogs) // Display for verification
 {
     Console.WriteLine(dog);
 }
    }
}

Output

spaniel
dalmation
beagle

Remove elements

The removal methods on List are covered in depth in another article on this site. It contains examples for Remove, RemoveAt, RemoveAll, and RemoveRange, along with my notes.
List Remove Methods

Sort and reverse

Sorted letters: A through Z.
You can use the powerful Sort and Reverse methods in your List collection. These allow you to order your List in ascending or descending order. Additionally, you can use Reverse even when your List is not presorted. There is more information on these topics, as well as sorting your List with LINQ on a property on this site.
Sort List Method

Convert List to array

Array type.
You can convert your List to an array of the same type using the instance method ToArray. There are examples of this conversion, and the opposite, on this site.
Convert List to Array List CopyTo Method

Get range of elements

Here we see how you can get a range of elements in your List collection using the GetRange instance method. This is similar to the Take and Skip methods from LINQ, but has different syntax.
Program that gets ranges from List [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
 List<string> rivers = new List<string>(new string[]
 {
     "nile",
     "amazon",     // River 2
     "yangtze",    // River 3
     "mississippi",
     "yellow"
 });

 // Get rivers 2 through 3
 List<string> range = rivers.GetRange(1, 2);
 foreach (string river in range)
 {
     Console.WriteLine(river);
 }
    }
}

Output

amazon
yangtze

List with DataGridView

You can use the List type with a DataGridView collection in Windows Forms. Sometimes, though, it is better to convert your List to a DataTable. For a List of string arrays, this will make the DataGridView display the elements correctly.
Convert List to DataTable, Use DataGridView

Test Lists for equality

Sometimes you may need to test two Lists for equality, even when their elements are unordered. You can do this by sorting both of them and then comparing, or by using a custom List equality method. This site contains an example of a method that tests lists for equality in an unordered way.
List Element Equality

List with structs

When using List, you can improve performance and reduce memory usage with structs instead of classes. A List of structs is allocated in contiguous memory, unlike a List of classes. This is an advanced optimization. Note that in many cases using structs will actually decrease the performance when they are used as parameters in methods such as those on the List type.
Var keyword.

Var

Here we see how you can use List collections with the var keyword. This can greatly shorten your lines of code, which sometimes improves readability. The var keyword has no effect on performance, only readability for programmers.
Program that uses var with List [C#]

using System.Collections.Generic;

class Program
{
    static void Main()
    {
 var list1 = new List<int>();       // <- var keyword used
 List<int> list2 = new List<int>(); // <- Is equivalent to
    }
}

Summary

In this tutorial, we saw lots of examples with the List constructed type. You will find that List is powerful and performs well. It provides flexible allocation and growth, making it much easier to use than arrays. In most programs that do not have memory or performance constraints and must add elements dynamically, the List constructed type in the C# programming language is ideal.

Friday, 16 September 2011

MVC

What the hell is a “Model-View-Controller”?

The Model-View-Controller Architecture, or MVC for short, is a way of programming that separates your application into three main parts:
  1. the Model
  2. the View
  3. and (you guessed it) the Controller
Basically, the separation of these three allows developers to differentiate three aspects of your application:
  1. Business Data (represented by the Model)
  2. Presentation Data (represented by the View)
  3. and Application Logic (represented by the Controller)
This allows for very rapid development – each aspect can be developed side by side by different developers at the same time. For example, we can have a designer working on the View and just allocating spaces where data will appear and at the same time, we can have a developer programming the Controller, who will just provide the View the data to be displayed. While all of this is being done, we can have another developer working on the Models, who will be in charge of retrieving data from the database and implementing the business-specific logic to them, and making sure that there are methods available for the Controller to be able to retrieve the data in different situations.
Using this also makes decoupling and modularization of your application very easy. Since each action on your application will have its own view-controller pair, this pair can be developed separately from another function with little or no setback.
The first time I read about MVC, I was a bit confused about the concept of three separated aspects of my application. I’ve read countless analogies trying to explain the MVC, and for me, one of the best analogies I’ve seen so far was from this article – Another way to think about MVC:
So, let’s imagine a bank.
The safe is the Database – this is where all the most important goodies are stored, and are nicely protected from the outside world.
Then we have the bankers or in programmatic terms the Models. The bankers are the only ones who have access to the safe (the DB). They are generally fat, old and lazy, which follows quite nicely with one of the rules of MVC: *fat models, skinny controllers*. We’ll see why and how this analogy applies a little later.
Now we’ve got our average bank workers, the gophers, the runners, the Controllers. Controllers or gophers do all the running around, that’s why they have to be fit and skinny. They take the loot or information from the bankers (the Models) and bring it to the bank customers the Views.
The bankers (Models) have been at the job for a while, therefore they make all the important decisions. Which brings us to another rule: *keep as much business logic in the model as possible*. The controllers, our average workers, should not be making such decisions, they ask the banker for details, get the info, and pass it on to the customer (the View). Hence, we continue to follow the rule of *fat models, skinny controllers*. The gophers do not make important decisions, but they cannot be plain dumb (thus a little business logic in the controller is OK). However, as soon as the gopher begins to think too much the banker gets upset and your bank (or you app) goes out of business. So again, always remember to offload as much business logic (or decision making) to the model.
Now, the bankers sure as hell aren’t going to talk to the customers (the View) directly, they are way too important in their cushy chairs for that. Thus another rule is followed: *Models should not talk to Views*. This communication between the banker and the customer (the Model and the View) is always handled by the gopher (the Controller).
(Yes, there are some exception to this rule for super VIP customers, but let’s stick to basics for the time being).
It also happens that a single worker (Controller) has to get information from more than one banker, and that’s perfectly acceptable. However, if the bankers are related (otherwise how else would they land such nice jobs?)… the bankers (Models) will communicate with each other first, and then pass cumulative information to their gopher, who will happily deliver it to the customer (View). So here’s another rule: *Related models provide information to the controller via their association (relation)*.

So what about our customer (the View)? Well, banks do make mistakes and the customer should be smart enough to balance their own account and make some decisions. In MVC terms we get another simple rule: *it’s quite alright for the views to contain some logic, which deals with the view or presentation*. Following our analogy, the customer will make sure not forget to wear pants while they go to the bank, but they are not going to tell the bankers how to process the transactions.

MVC in Web Development

Currently, a lot of web applications and Frameworks (Zend, CakePHP, Symfony, to name a few)  make use of the MVC Architecture. According to the Cookbook from CakePHP:
Why use MVC? Because it is a tried and true software design pattern that turns an application into a maintainable, modular, rapidly developed package. Crafting application tasks into separate models, views, and controllers makes your application very light on its feet. New features are easily added, and new faces on old features are a snap. The modular and separate design also allows developers and designers to work simultaneously, including the ability to rapidly prototype. Separation also allows developers to make changes in one part of the application without affecting others.
If you’ve never built an application this way, it takes some time getting used to, but we’re confident that once you’ve built your first application using CakePHP, you won’t want to do it any other way.
A diagram from ash.MVC, another PHP framework which uses the MVC architecture, illustrates the usual data-flow for a web application built with MVC in mind:
  1. First, the browser sends an HTTP request to the web application
  2. A dispatcher usually will get this HTTP request and determine which controller to be used. This dispatcher is usually called a Front Controller (not illustrated)
  3. The appropriate controller will receive it and from the data received, determine which model/s are needed, what data is required and what action is to be done to the data
  4. The model will be told by the controller and retrieve the data and implement any necessary actions. Then, it will return the results to the controller, successful or not.
  5. The controller, based on the results from the model, will then determine which view should be used and provide the view whatever data is to be published to the browser.
  6. The view will receive this data, implement any presentation logic to the data, and return it back to the controller.
  7. The controller will then return the results to the browser.
From this data-flow, we can see what role each part of the MVC plays in every request made.
On a standard web application, the MVC can be represented by the following:

Model

The model, in a web application, is usually composed of classes which represent data from the database and manipulative logic relative to the data. Let say you have a table called “guestbook_entries”. On your application, a Guestbook Model will represent this table, and be responsible for retrieving data from this table in many different situations – for example, on one page, you could probably be viewing all of the guestbook entries, so your model should have a “fetchAll” method somewhere. On another page, you can also be viewing one entry, so this model should also be responsible for finding and retrieving the data of a single record from the table as well. There could also be situations where you need the entries to be retrieved based on a particular post, a date, or even a set of records, limited to 5, starting on the 10th index of all records (read: pagination). All of this should be handled exclusively by the model.

View

The view is obviously the HTML/CSS aspect any web application. The view should never retrieve data from the Model, and should only be able to get this data based on what the controller gives it. This makes the view decoupled from the business logic, and makes it easier to change the logic with little or no effect on the view. This separation also allows for the application to reuse the view, making your application instantly template-friendly. Continuing from our example above, we can have a single view which is used to display a single guestbook entry. On a page which displays all of the entries, we can reuse the html file which displays one guestbook entry,and include it multiple times to show all of the entries.

Controller

The controller is the hub of all requests – it is usually the one who implements the actual application logic to the data-flow. It determines which model and view to use, based on the request that a user sends to it. It is usually represented by the different pages of a web application, like for example, the login page will usually have an Authentication controller, as would a registration page and a downloads page. From our example above, the guestbook page would have a controller, and this controller would be able to support requests for viewing a single guestbook entry and viewing all of these entries as well.

Note: Front Controller

Additionally, most MVC applications implement the use of a Front Controller. Basically, it’s a controller for all of the controllers. It determines which of the controllers is appropriate for specific pages and dispatches necessary information to them. For example, in our guestbook page, we send an HTTP request to view all of the guestbook entries to the application. This request will be received by the Front Controller, and based on the request data (POST, GET), it determines that it should be handled by the Guestbook controller. It will then send the data (the user, wanting to view all of the guestbook entries) to the controller.

Tuesday, 6 September 2011

State Management

State Management in ASP.NET


Web form pages are HTTP-Based, they are stateless, which means they don�t know whether the requests are all from the same client, and pages are destroyed and recreated with each round trip to the server, therefore information will be lost, therefore state management is really an issue in developing web applications

We could easily solve these problems in ASP with cookie, query string, application, session and so on. Now in ASP.NET, we still can use these functions, but they are richer and more powerful, so let�s dive into it.

Mainly there are two different ways to manage web page�s state: Client-side and Server-side.

1.Client-side state management :
There is no information maintained on the server between round trips. Information will be stored in the page or on the client�s computer.

A. Cookies.

A cookie is a small amount of data stored either in a text file on the client's file system or in-memory in the client browser session. Cookies are mainly used for tracking data settings. Let�s take an example: say we want to customize a welcome web page, when the user request the default web page, the application first to detect if the user has logined before, we can retrieve the user informatin from cookies:
[c#]
if (Request.Cookies[�username�]!=null)
lbMessage.text=�Dear �+Request.Cookies[�username�].Value+�, Welcome shopping here!�;
else
lbMessage.text=�Welcome shopping here!�;

If you want to store client�s information, you can use the following code:
[c#]
Response.Cookies[�username�].Value=username;

So next time when the user request the web page, you can easily recongnize the user again.
B. Hidden Field
A hidden field does not render visibly in the browser, but you can set its properties just as you can with a standard control. When a page is submitted to the server, the content of a hidden field is sent in the HTTP Form collection along with the values of other controls. A hidden field acts as a repository for any page-specific information that you would like to store directly in the page. Hidden field stores a single variable in its value property and must be explicitly added it to the page.
ASP.NET provides the HtmlInputHidden control that offers hidden field functionality.
[c#]
protected System.Web.UI.HtmlControls.HtmlInputHidden Hidden1;
//to assign a value to Hidden field
Hidden1.Value=�this is a test�;
//to retrieve a value
string str=Hidden1.Value;

Note: Keep in mind, in order to use hidden field, you have to use HTTP-Post method to post web page. Although its name is �Hidden�, its value is not hidden, you can see its value through �view source� function.
C. View State

Each control on a Web Forms page, including the page itself, has a ViewState property, it is a built-in struture for automatic retention of page and control state, which means you don�t need to do anything about getting back the data of controls after posting page to the server.

Here, which is useful to us is the ViewState property, we can use it to save information between round trips to the server.
[c#]
//to save information
ViewState.Add(�shape�,�circle�);
//to retrieve information
string shapes=ViewState[�shape�];

Note: Unlike Hidden Field, the values in ViewState are invisible when �view source�, they are compressed and encoded.

D. Query Strings
Query strings provide a simple but limited way of maintaining some state information.You can easily pass information from one page to another, But most browsers and client devices impose a 255-character limit on the length of the URL. In addition, the query values are exposed to the Internet via the URL so in some cases security may be an issue.
A URL with query strings may look like this:

http://www.examples.com/list.aspx?categoryid=1&productid=101

When list.aspx is being requested, the category and product information can be obtained by using the following codes:
[c#]
string categoryid, productid;
categoryid=Request.Params[�categoryid�];
productid=Request.Params[�productid�];

Note: you can only use HTTP-Get method to post the web page, or you will never get the value from query strings.

2. Server-side state management:
Information will be stored on the server, it has higher security but it can use more web server resources.
A. Aplication object
The Application object provides a mechanism for storing data that is accessible to all code running within the Web application, The ideal data to insert into application state variables is data that is shared by multiple sessions and does not change often.. And just because it is visible to the entire application, you need to used Lock and UnLock pair to avoid having conflit value.
[c#]
Application.Lock();
Application[�mydata�]=�mydata�;
Application.UnLock();
B. Session object

Session object can be used for storing session-specific information that needs to be maintained between server round trips and between requests for pages. Session object is per-client basis, which means different clients generate different session object.The ideal data to store in session-state variables is short-lived, sensitive data that is specific to an individual session.

Each active ASP.NET session is identified and tracked using a 120-bit SessionID string containing URL-legal ASCII characters. SessionID values are generated using an algorithm that guarantees uniqueness so that sessions do not collide, and SessionID�s randomness makes it harder to guess the session ID of an existing session.
SessionIDs are communicated across client-server requests either by an HTTP cookie or a modified URL, depending on how you set the application's configuration settings. So how to set the session setting in application configuration? Ok, let�s go further to look at it.

Every web application must have a configuration file named web.config, it is a XML-Based file, there is a section name �sessionState�, the following is an example:

<sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;user id=sa;password=" cookieless="false" timeout="20" />

�cookieless� option can be �true� or �false�. When it is �false�(default value), ASP.NET will use HTTP cookie to identify users. When it is �true�, ASP.NET will randomly generate a unique number and put it just right ahead of the requested file, this number is used to identify users, you can see it on the address bar of IE:

http://localhost/Management/(2yzakzez3eqxut45ukyzq3qp)/Default.aspx

Ok, it is further enough, let is go back to session object.
[c#]
//to store information
Session[�myname�]=�Mike�;
//to retrieve information
myname=Session[�myname�];
C. Database

Database enables you to store large amount of information pertaining to state in your Web application. Sometimes users continually query the database by using the unique ID, you can save it in the database for use across multiple request for the pages in your site.

Summary


ASP.NET has more functions and utilities than ASP to enable you to manage page state more efficient and effective. Choosing among the options will depand upon your application, you have to think about the following before making any choose:
  • How much information do you need to store?
  • Does the client accept persistent or in-memory cookies?
  • Do you want to store the information on the client or server?
  • Is the information sensitive?
  • What kind of performance experience are you expecting from your pages?
Client-side state management summary


Method
Use when
Cookies
You need to store small amounts of information on the client and security is not an issue.
View state
You need to store small amounts of information for a page that will post back to itself. Use of the ViewState property does supply semi-secure functionality.
Hidden fields
You need to store small amounts of information for a page that will post back to itself or another page, and security is not an issue.
Note   You can use a hidden field only on pages that are submitted to the server.
Query string
You are transferring small amounts of information from one page to another and security is not an issue.
Note   You can use query strings only if you are requesting the same page, or another page via a link.


Server-side state management summary


Method
Use when
Application state object
You are storing infrequently changed, application-scope information that is used by many users, and security is not an issue. Do not store large quantities of information in an application state object.
Session state object
You are storing short-lived information that is specific to an individual session, and security is an issue. Do not store large quantities of information in a session state object. Be aware that a session state object will be created and maintained for the lifetime of every session in your application. In applications hosting many users, this can occupy significant server resources and affect scalability.
Database support
You are storing large amounts of information, managing transactions, or the information must survive application and session restarts. Data mining is a concern, and security is an issue.

Monday, 5 September 2011

sealed class

A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class. Sealed classes are primarily used to prevent derivation. Because they can never be used as a base class, some run-time optimizations can make calling sealed class members slightly faster. Sealing a class means one can not derive from it. Sealing a method means one can not override it. In C# structs are implicitly sealed; therefore, they cannot be inherited. If we try to inherit from a sealed class in another class we will get compile time error about Inconsistent accessibility (code is shown in following code listing).

Sunday, 4 September 2011

c# Reserved Keywords

List of Reserved Keywords . If the specific keyword need  to be used as a variable . User @ before the keyword . Ex;  class can be used as @class