Sunday, June 24, 2012

Writing a Text File

This short piece of code demonstrates how to write a text file in Java. The PrinterWriter class contains a number of methods for outputting text to a file. The FileWriter class is a convenience class for writing to a text file. It uses the default code page for the operating environment your virtual machine is running in. If you need to specify a specific code page, then you must use the OutputStreamWriter class instead.


 1:/** Simple Program to write a text file
   2:*/
   3:
   4: import java.io.*;
   5:
   6: public class WriteText{
   7:    public static void main(String[] args){
   8:        try {
   9:            FileWriter outFile = new FileWriter(args[0]);
  10:            PrintWriter out = new PrintWriter(outFile);
  11:            
  12:            // Also could be written as follows on one line
  13:            // Printwriter out = new PrintWriter(new FileWriter(args[0]));
  14:        
  15:            // Write text to file
  16:            out.println("This is line 1");
  17:            out.println("This is line 2");
  18:            out.print("This is line3 part 1, ");
  19:            out.println("this is line 3 part 2");
  20:            out.close();
  21:        } catch (IOException e){
  22:            e.printStackTrace();
  23:        }
  24:    }
  25: }
 
 

How to Create a JavaScript Animation

JavaScript animations aren't difficult to write. Once you learn a few main ideas, you can create complex animations that take up as much or as little of the browser window as you like, including interactive content that degrades well for people who don't have JavaScript enabled. What's more, the content inside your animations will be available to search engines because the content is in machine-readable (X)HTML.
In this tutorial we'll start out with the basics of animation, how to make things move, turn animations on and off, and determine the edges of the space where you want the motion to take place. All of the code in this tutorial has been tested on Mozilla Firefox, Windows, Linux; Konquerer on Linux; and MS IE on Windows.

A Matter of Timing

At some point most of us have played with a flip book to see how animation works. The classic flip book is a little ball that bounces around the field of the page as the pages flip past. The image isn't really moving, but each page has the image placed slightly differently from the last, and our brains perceive that as movement. In TV and movies, the same thing happens, only without all the pages sitting in our hands. The images flip past our vision, one at a time, at a rate of 24, 25 or 30 images per second, depending on the medium we are viewing (film, PAL video and NTSC video respectively). This is known as the "frame rate."
To make an animation on the computer, we want to move an image in a similar way, only we don't have "frames" to work with. Instead, we have milliseconds in which we can execute commands. We can change what's on the screen every millisecond in order to create the appearance of motion. We don't have to change the screen nearly that fast, though. The human eye can only register motion at a rate of approximately 24 frames per second. Faster than that, and the brain just doesn't recognize the difference. For the ease of calculation, then, it's simple to consider an optimum image change rate or 25 frames/1000 milliseconds. That's the same as saying 1/40, or 1"frame" change every 40 milliseconds.
On the Internet, we often cheat a bit, seeing exactly how far we can push the weaknesses in human perception to use smaller files and less computer power to present the same experience to the end user. It just so happens that for most Web animations you can get away with exactly half the optimal frame rate without the movement looking too choppy. So, for this tutorial we'll use 1 frame every 80 milliseconds.
In JavaScript, we have the setTimeout() and setInterval() functions to help us count time and create our frame rate. The function setTimeout() will count the time and then run the command that you give it. The setInterval() function will repeat a function every time it reaches the time count that you have given it. Both functions count by milliseconds.

Examples:


1setTimeout('animBall()', 80);      // run the function animBall after 80 milliseconds. 
2setInterval('animBall()', 80);      // run the function animBall() every 80 milliseconds. 


In the case of setTimeout(),



 if you want to run a single function over and over at the time count that you have set, you need to put the function inside of the function it calls. So you will end up with a function that looks something like:

1function animBall(){ 
2       setTimeout('animBall()', 80);   // set the timer so that this function will run again in 80 milliseconds 
3       moveRight(); 
4       doOtherStuff(); 
5


In the case of setInterval(), the call should be made outside the function that you want to repeat. Otherwise, you end up with multiple instances of your interval, a strange acceleration of movement, and a big, fat memory leak.

1<script language="javascript"
2      function animBall() { 
3    moveRight(); 
4    doOtherStuff(); 
5      } 
6</script><a href="javascript:setIntveral('animBall()', 80)">Start Animation</a> 


Chances are, at some point you'll want to stop the animation. To do so, you'll need either clearTimeout() or clearInterval(). Both of these clearing functions take a variable which represents a timing object, and clears it's timer. To make these work, you need to create the object that your clear function will stop.

Timeout Example:


1<script language="javascript"
2var t; 
3function animBall(){ 
4t=setTimeout('animBall()', 80); 
5moveRight(); 
6doOtherStuff(); 
7
8</script><a href="javascript:animBall()">Start Animation</a> <a href="javascript:clearTimeout(t)">Stop Animation</a> 


Interval Example:


1<script language="javascript"
2        function animBall() { 
3            moveRight(); 
4            doOtherStuff(); 
5        } 
6        </script><a href="javascript:var t=setIntveral('animBall()', 80)">  Start Animation</a>      
















Saturday, June 23, 2012

Fast Technology: Application, Session, HttpContext, and ViewState

Fast Technology: Application, Session, HttpContext, and ViewState: Application, Session, HttpContext, and ViewState

Application, Session, HttpContext, and ViewState

Application, Session, HttpContext, and ViewState Caching

Application, Session, HttpContext, and ViewState Caching

Using the Application, Session, HttpContext and ViewState objects for caching data is not a new technique, and while extremely simple, it shouldn't be left out or ignored because of other techniques. All three objects provide simple key based collections for storage of data through the lifetime of the object. Since this lifetime is not persistent, you should only store data that is ephemeral in nature; anything that requires long-lived storage should use a database, or perhaps the Profile object for user-related data.

Using the Application State

The Application object exists for the lifetime of the application; that is, from the moment the first request to the application is received to the moment the application is shut down. Application shutdown can occur under different circumstances, and you should be aware that it can happen while the site is being used. ASP.NET is self-monitoring and can restart an application if, for example, memory demands exceed set limits. This means that you shouldn't rely on an item automatically being stored in the Application object; you should always check for a null value.
Using the Application object for state storage is as simple as indexing the Application object. For example:
Application["Start"] = DateTime.Now;

This will add the current date and time to the Application cache, indexed by Start. To extract the value, you use the same indexing scheme; but the application stores objects, so casting is required:
DateTime appStart = (DateTime)Application["Start"];

Because object storage is supported, you can store complex types, such as data. For example, a common caching pattern is to check to see if the data is in the cache (irrespective of which form of caching is used), and if it's present, return the data. If the data isn't present in the cache, it is fetched from its original location and stored in the cache. For example, consider some data from a database that is required in all pages, which could be stored in the application, as shown in Listing 6.1.
Storing Data in the Application
DataTable cachedData = (DataTable)Application["CommonData"];
if (cachedData == null)
{
  cachedData = DataLayer.FetchCommonData();
  Application["CommonData"] = cachedData;
}

Here the data is fetched from the Application, which returns null if the item isn't present, and if it isn't present, then it is fetched from the data layer and placed in the Application for subsequent requests. When using this form of caching, you have to balance the resource use (when storing the data in the application) against the time taken to fetch it from its original location. Performance and memory monitoring tools are useful in helping you make this decision.
If you know that every single page is going to use some cached data, you can use the Application_Start event to load the data, because this event runs once when the application starts. In this situation, you wouldn't need to check for the cached item, because you know it wouldn't be present when the application is just starting. If, however, only a selected number of pages use the cached data, or if use of the cached data is dependent upon user actions, you can use the code in Listing 6.1 to lazy load the datathat is, load it only when it is first requested and then cache it for later use.

Using the Session State

Session state is similar in use to Application state, but with one major exception: It is unique to each user of the site and is destroyed when the user leaves the site (after a timeout). Session state is therefore useful for storing data that a user would require throughout his or her use of the application. Bear in mind that Session state is intended for storage of transient datadata that doesn't need to be retained after the user leaves the site. For long-lived data, such as user preferences, you should use the Profile.
Listing 6.2 shows a common pattern for using the Session object for state storage.
Storing Data in the Session
DataTable cachedData = (DataTable)Session["UserData"];
if (cachedData == null)
{
  cachedData = DataLayer.FetchUserData();
  Session["UserData"] = cachedData;
}

Like the Application state, Session state takes resources, so you should examine your needs carefully. By default, Session state is enabled for applications and pages but can be turned off or disabled completely.
Disabling Session State
Disabling Session state is a performance optimization that you can perform at several levels. In pages, you can use the EnableSessionState attribute of the Page directive:
<% Page EnableSessionState="false" ... %>

Alternatively, if you require access to Session state but don't plan to update it, you can make it read-only for a page:
<% Page EnableSessionState="ReadOnly" ... %>

This ensures that you still have access, but don't go through the overhead of locking the state for update.
Configuring Session State
At the application level, you configure Session state in web.config, as seen in Listing 6.3.
The attributes are documented in Figure.
Attributes of SessionState Configuration
Attribute
Description
allowCustomSqlDatabase
Only relevant when mode is set to SQLServer, and indicates whether or not a custom database name can be specified in the Initial Catalog attribute of the SQL Server connection string. The default value is false, meaning the default ASP.NET session database is used.
cookieless
Indicates how cookies are used, and can be one of:
AutoDetect, where ASP.NET determines whether the requesting device supports cookies. If so, then cookies are used; otherwise the query string is changed to include the session identifier.
UseCookies, where cookies are always used. This is the default value.
UseDeviceProfile, where ASP.NET uses the browser capabilities to determine whether cookies should be used.
UseUri, where the query string is always used.
true, which has the same effect as UseUri.
false, which has the same effect as UseCookies.
cookieName
Defines the default cookie name used to store the session ID. The default value is ASP.NET_SessionId.
customProvider
Indicates the name of the provider when the mode is Custom. The name attribute should match one of the provider names declared in the <Providers/> section, and defaults to an empty string.
mode
Indicates how session state is being managed, and can be one of:
Custom, which indicates that session state is stored in a custom manner.
InProc, where session state is stored within the ASP.NET process. This is the default value.
Off, where session state is turned off for the application.
SQLServer, where session state is stored in a SQL Server database.
StateServer, where session state is stored in a separate ASP.NET State Service.
partitionResolverType
Defines a type to be used to resolve the connection string for the request. Resolvers are used to enable session state to be partitioned to scale in Web Farm situations. If this attribute is set, the sqlConnectionString and stateConnectionString attributes are ignored. The default value is an empty string.
regenerateExpiredSessionId
Indicates whether or not the session identifier will be reissued when an invalid identifier is used by the client. The default value is true, where identifiers are only reissued when cookies aren't being used.
sqlCommandTimeout
Indicates, in seconds, the timeout for a SQL command when the mode is SQLServer. The default value is 30.
sqlConnectionString
Indicates the name of the connection string when using SQL Server to store session state. The default value is "data source=127.0.0.1; Integrated Security=SSPI", pointing at a local, trusted SQL Server database.
stateConnectionString
Required when mode is StateServer, and defines the server name/address and port where session state is stored. The default value is "127.0.0.1:42424".
stateNetworkTimeout
For when mode is StateServer, and defines the number of seconds to wait for the remote state server before the request is cancelled. The default value is 10 seconds.
timeout
Defines the number of minutes to wait after session activity (i.e., idle time) before the session is abandoned. The default value is 20 minutes.
useHostingIdentity
Indicates whether or not session state will revert to the hosting identity or use client impersonation. The default value is true, indicating that the identity of the hosting process (ASPNET on IIS5 or NETWORK SERVER on IIS6) or the identity specified in the process <identity> section is used. If false, the credentials of the current OS thread are used.

You can see that there are a number of ways in which Session state can be stored. By default, the ASP.NET process stores the state, because this provides the fastest storage. However, because it is process-bound, Session state would not survive an application restart, which is where the state server and database options come in. The downsides of these, however, are that performance is slower than with the in-process method. For more detailed information on session state and performance, there is an excellent article in the MSDN Magazine, available online at http://msdn.microsoft.com/msdnmag/issues/05/09/SessionState/default.aspx.
Session State Configuration
<sessionState
  allowCustomSqlDatabase="[true|false]"
  cookieless="[AutoDetect|UseCookies|UseDeviceProfile|
               UseUri|true|false]"
  cookieName="String"
  customProvider="String"
  mode="[Custom|InProc|Off|StateServer|SQLServer|]"
  partitionResolverType="String"
  regenerateExpiredSessionId="[true|false]"
  sessionIdManagerType="String"
  sqlCommandTimeout="Integer"
  sqlConnectionString="String"
  stateConnectionString="String"
  stateNetworkTimeout="Integer"
  timeout="Integer"
  useHostingIdentity="[true|false]"
  >
  <providers>
    <clear />
    <add
      Name="String"
      Type="String"
      [providerSpecificConfiguration] />
  </providers>
</sessionState>


The SessionState configuration element should not be confused with the SessionPageState element, which is used to keep a history of view state and control state within the session.

Using HttpContext

If you don't need to store data across an entire session, but perhaps require data across multiple user controls within a page, then you can use the current context of the request. Each request has an associated HttpContext object associated with it, which provides access to many objects used within pages, such as the Request, Profile, and Trace. Also available on the context is an Items collection that can be used for storage and is particularly useful when you have multiple user controls on a page that need to share data. It is important to realize that this technique is only useful between controls within a single end-to-end request and that it does not apply between separate page requests.
For example, consider two grids that use the same data. You could use the data source controls and their built-in caching, but if you have an existing code library and need to bind in code, you might have the code shown in Listing 6.4 in both user controls:
Simple Binding to a Business Layer
protected void Page_Load(object sender, EventArgs e)
{
  if (!Page.IsPostBack)
  {
    GridView3.DataSource = Shippers.GetShippers();
    GridView3.DataBind();
  }
}

This code, if used in multiple user controls, would result in the same SQL command being run multiple times. There are several ways to cure this, and we'll look at others later in the chapter, but a simple solution would be for one control to read the data and cache it in the context. Rather than explicitly putting the code into your user control (which would limit the order of the controls on the page to ensure that the one that cached the data was executed first), you could create a central class, as shown in Listing 6.5.
A Caching Class Using the HttpContext
public static class Caching
{
  public static List<Shipper> GetShippers()
  {
    List<Shipper> ships =
        (List<Shipper>)HttpContext.Current.Items["Shippers"];
    if (ships == null)
    {
      ships = Shippers.GetItems();
      HttpContext.Current.Items["Shippers"] = ships;
    }
    return ships;
  }
}

This code is extremely simple and follows the by-now familiar pattern used in caching. It first fetches the data from the Items collection, and if it's not present in the cache, gets the data from the Shippers business class and stores it in the Items collection. Subsequent calls will fetch it from the collection.

Using ViewState

Another method of caching data is to use ViewState, although this does come with the warning that ViewState is transferred to and from the client on each request. The ViewState can be accessed just like other collections:

ViewState["CachedData"] = DateTime.Now;

You should generally try to use as little ViewState caching as possible in order to reduce overheads in transferring pages, but it does provide an alternative storage mechanism for small amounts of data. For best performance, you should turn off ViewState for controls and pages that don't require it. ASP.NET 2.0 supports a new feature for state storage, Control-State, which controls use to support the minimum state requirements for the control to operate. This allows ViewState to be turned off but for the control to still operate correctly.

Asp.net User Control Concept

User controls are one of ASP.NET methods to increase reusability of code, implement encapsulation and reduce maintenance. User control is similar to web page. Both web pages and user controls contain HTML elements and markup for web controls. Some tags, like <html>, <head> or <form> cannot be used in web user controls.

User controls are saved with .ascx extension, instead of .aspx for web pages. User controls can use code behind feature like web pages. Code behind file of web user controls ends with .ascx.cs. Markup code of user controls starts with @Control directive. Simplest web user control could contains only static HTML, like in this example:

<%@ Control Language="VB" AutoEventWireup="false" CodeFile="WebUserControl.ascx.vb" Inherits="WebUserControl" %>
 
<p>Hello, I am very simple <b>web user control</b> with static HTML only.</p>
This web user control could be used when you need to repeat same code on many pages. Good examples are page footer, header or some kind of site navigation (depending of your case, it is good idea to consider using of Master Pages for this task as well). Except static HTML code, web user controls could contain web controls. You can simply drag and drop items from toolbox to user control. Like any other control, user controls can have properties, methods and events which make them very useful.
If user control solves more general problem, like progress bar or data pager control then can be useful on many different web sites. On this way, user controls can provide more stable and tested code.

How to create web user control

All user controls are derived from the System.Web.UI.UserControl class. UserControl and Page classes both inherits from TemplateControl class. You can add web user control to existing web site project, in Visual Studio menu go to WebSite -> Add New Item..., like in image bellow
Adding new user control in Visual Studio
New dialog will appear. To create new web user control, select web user control template, like in next image. Choose a name for your control and click Add.
Web user control template selected

How to add web user control to ASP.NET web page

To add web user control to web page, we need two lines. First, we need to register user control with Register directive on top of the page:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register tagprefix="bean" Tagname="footer" src="~/footer.ascx" %>




With Register directive we define user control on page. The important parameters are:
TagPrefix: prefix for user control tag. This prefix will be used in markup code later.
TagName: tag name of user control tag.
Src: path to .ascx file.
After registration with Register directive, you can place user control inside web form with tag formatted as <tagprefix:tagname, like this:

<bean:footer runat="server" id="MyUserControl" />

Registering user controls in web.config

If you'll use user control on many pages on web site then you can register control in web.config file. On this way you can use user control in complete web site without need to register it on every page. You can do this in <controls > section with code like this:

<configuration>
  <system.web>
    <pages>
      <controls>
        <add src="Footer.ascx" tagPrefix="bs" tagName="footer" />
      </controls >
    </pages >
  </system.web>
</configuration>

Dynamically loading web user controls


Although web user controls looks like a parts of web page, they are still "controls". You can add them to web page at design time, and also you can add web user controls at run time by using ASP.NET server side code and by using of some container. Container is usually PlaceHolder or Panel control. We can add user control dynamically with simple code like this:
[ C# ]
protected void Page_Load(object sender, EventArgs e)
{
// Declare user control variable
Control MyUserControl;
// Load user control dynamically
MyUserControl = LoadControl("UserControl1.ascx");
// Place user control in PlaceHolder control
MyPlaceHolder.Controls.Add(MyUserControl);
}

[ VB.NET ]

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' Declare user control variable
Dim MyUserControl As Control
' Load user control dynamically
MyUserControl = LoadControl("UserControl1.ascx")
' Place user control in PlaceHolder control
myPlaceHolder.Controls.Add(MyUserControl)
End Sub
 
On this way, you can choose when and which control to load, based on user preferences, user or role rights etc. In detail guide how to load user controls dynamically you can read on Working with Web User Controls at Run-time tutorial.

Web user control properties and methods

We can add properties and methods to user control class like in code bellow:
[ C# ]

public void DoSomething()
{
  // Public method that do something great
}
// Public property
 public string FirstName
 {
     get
   {
     return lblFirstName.Text;
    }
   set
   {
     lblFirstName.Text = value;
    }
}


[ VB.NET ]


Public Sub DoSomething()
  ' Public method that do something great
End Sub

' Public property
Public Property FirstName() As String
   Get
    Return lblFirstName.Text
   End Get
  Set(ByVal value As String)
     lblFirstName.Text = value
   End Set
End Property

Web user control events

User control has predefined events like web page, so you don't need to learn anything new. There are Load, Init, PreRender, Error etc. events, used on the same way like in common web page:


[ C# ]


protected void Page_Load(object sender, EventArgs e) {

   // You can add code for user control events,
   // it looks like procedure for web page load
   // so you don't need to learn anything new
}
[ VB.NET ]

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
 ' You can add code for user control events,
 ' it looks like procedure for web page load
 ' so you don't need to learn anything new
End
Sub

Custom events in user controls

Except predefined events, it is possible to declare your own events so your user control can notify the rest of application when something happen. Every event procedure use two parameters. First parameter is sender, the control that sent an event, and the second parameter is EventArgs object, or the custom class that inherits from System.EventArgs class. If we use custom class, we can add additional information that can be used in event procedure. But, in case that we have simple event, we can use generic EventArgs class.
You can create your own event in two simple steps. First, declare an event with code like this:

[ C# ]

public event EventHandler TitleChanged;

[ VB.NET ]

Public Event TitleChanged(ByVal sender As Object, ByVal e As EventArgs)

Second, inside some property or procedure, when certain circumstances occurs, you can raise an event with code like this:

[ C# ]
TitleChanged(this, EventArgs.Empty);

[ VB.NET ]

RaiseEvent TitleChanged(sender, e)

Web user control examples

Ok, enough about theory, we created two pretty useful examples of user controls. Maybe you can find them useful in some of your web projects.
First example is A simple Month Calendar Control which could be used for month selection when using of classic calendar control is inappropriate.
Month Calendar ASP.NET Control
Second example explains How to create ProgressBar user control when visitor expects to know a progress or current state of some operation.
Progress Bar ASP.NET Control

Conclusion

User controls could be very useful to save your time and avoid confusion. ASP.NET provides other types of controls, including custom server controls, components and web parts. Also there are a number of third party controls from independent software vendors. These controls are already well tested on many web sites and for small price can save you a lot of work. Third party controls are rarely created as user controls. Usually, they are compiled as custom server controls. Although user controls are easier to create, custom controls are easier to use. They can be placed on Visual Studio toolbox and act as standard built-in controls.