Tipsy little box

Just another weblog

Importing Data From Excel with C# September 30, 2009

Filed under: ASP.NET, C# — evacion @ 1:16 pm

The following code block accepts an Excel file path and returns an ordinary DataTable object, which can be manipulated easily by the code that calls this method. The first row of the Excel document becomes the columns in the DataTable object and each row thereafter are DataRow objects.

ImportingFromExcel

If you like, take a look at both techniques for working with Excel data and see what one speaks to you.

(Source: http://blogs.popart.com/2008/07/importing-data-from-excel-with-c/ )

 

Delegates and Events in C# / .NET September 16, 2009

Filed under: ASP.NET, C# — evacion @ 5:22 pm

Delegates
A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.

Call a Function directly – No Delegate

In most cases, when we call a function, we specify the function to be called directly. If the class MyClass has a function named Process, we’d normally call it like this (SimpleSample.cs):

using System;
namespace evacion.NoDelegate{

public class MyClass {
public void Process() {
Console.WriteLine(“Process() begin”);
Console.WriteLine(“Process() end”);
}
}

public class Test {
static void Main(string[] args) {
MyClass myClass = new MyClass();
myClass.Process();
}
}
}

That works well in most situations. Sometimes, however, we don’t want to call a function directly – we’d like to be able to pass it to somebody else so that they can call it. This is especially useful in an event-driven system such as a graphical user interface, when I want some code to be executed when the user clicks on a button, or when I want to log some information but can’t specify how it is logged.
The very basic Delegate
An interesting and useful property of a delegate is that it does not know or care about the class of the object that it references. Any object will do; all that matters is that the method’s argument types and return type match the delegate’s. This makes delegates perfectly suited for “anonymous” invocation.
The signature of a single cast delegate is shown below:

delegate result-type identifier ([parameters]);
where:
result-type: The result type, which matches the return type of the function.
identifier: The delegate name.
parameters: The Parameters, that the function takes.
Examples:
public delegate void SimpleDelegate ()
This declaration defines a delegate named SimpleDelegate, which will encapsulate any method that takes
no parameters and returns no value.
public delegate int ButtonClickHandler (object obj1, object obj2)
This declaration defines a delegate named ButtonClickHandler, which will encapsulate any method that takes
two objects as parameters and returns an int.
A delegate will allow us to specify what the function we’ll be calling looks like without having to specify which function to call. The declaration for a delegate looks just like the declaration for a function, except that in this case, we’re declaring the signature of functions that this delegate can reference.

There are three steps in defining and using delegates:

Declaration
Instantiation
Invocation
A very basic example (SimpleDelegate1.cs):

using System;
namespace evacion.BasicDelegate{
// Declaration
public delegate void SimpleDelegate();

class TestDelegate {
public static void MyFunc(){
Console.WriteLine(“I was called by delegate …”);
}
public static void Main(){
// Instantiation
SimpleDelegate simpleDelegate = new SimpleDelegate(MyFunc);
// Invocation
simpleDelegate();
}
}
}

Compile an test:
# csc SimpleDelegate1.cs
# SimpleDelegate1.exe
I was called by delegate …

Calling Static Functions
For our next, more advanced example (SimpleDelegate2.cs), declares a delegate that takes a single string parameter and has no return type:

using System;
namespace evacion.SimpleDelegate{
// Delegate Specification
public class MyClass {
// Declare a delegate that takes a single string parameter
// and has no return type.

public delegate void LogHandler(string message);

// The use of the delegate is just like calling a function directly,
// though we need to add a check to see if the delegate is null
// (that is, not pointing to a function) before calling the function.

public void Process(LogHandler logHandler){
if (logHandler != null){
logHandler(“Process() begin”);
}
if (logHandler != null){
logHandler (“Process() end”);
}
}
}
// Test Application to use the defined Delegate
public class TestApplication {
// Static Function: To which is used in the Delegate. To call the Process()
// function, we need to declare a logging function: Logger() that matches
// the signature of the delegate.

static void Logger(string s){
Console.WriteLine(s);
}
static void Main(string[] args){
MyClass myClass = new MyClass();
// Crate an instance of the delegate, pointing to the logging function.
// This delegate will then be passed to the Process() function.

MyClass.LogHandler myLogger = new MyClass.LogHandler(Logger);
myClass.Process(myLogger);
}
}
}

Compile an test:
# csc SimpleDelegate2.cs
# SimpleDelegate2.exe
Process() begin
Process() end

Calling Member Functions
In the simple example above, the Logger( ) function merely writes the string out. A different function might want to log the information to a file, but to do this, the function needs to know what file to write the information to (SimpleDelegate3.cs)

using System;
using System.IO;
namespace evacion.SimpleDelegate{
// Delegate Specification
public class MyClass{
// Declare a delegate that takes a single string parameter
// and has no return type.

public delegate void LogHandler(string message);
// The use of the delegate is just like calling a function directly,
// though we need to add a check to see if the delegate is null
// (that is, not pointing to a function) before calling the function.

public void Process(LogHandler logHandler) {
if (logHandler != null) {
logHandler(“Process() begin”);
}
if (logHandler != null) {
logHandler (“Process() end”);
}
}
}
// The FileLogger class merely encapsulates the file I/O
public class FileLogger {
FileStream fileStream;
StreamWriter streamWriter;
// Constructor
public FileLogger(string filename) {
fileStream = new FileStream(filename, FileMode.Create);
streamWriter = new StreamWriter(fileStream);
}
// Member Function which is used in the Delegate
public void Logger(string s) {
streamWriter.WriteLine(s);
}
public void Close() {
streamWriter.Close();
fileStream.Close();
}
}
// Main() is modified so that the delegate points to the Logger()
// function on the fl instance of a FileLogger. When this delegate
// is invoked from Process(), the member function is called and
// the string is logged to the appropriate file.
public class TestApplication {
static void Main(string[] args) {
FileLogger fl = new FileLogger(“process.log”);
MyClass myClass = new MyClass();
// Crate an instance of the delegate, pointing to the Logger()
// function on the fl instance of a FileLogger.

MyClass.LogHandler myLogger = new MyClass.LogHandler(fl.Logger);
myClass.Process(myLogger);
fl.Close();
}
}
}

The cool part here is that we didn’t have to change the Process() function; the code to all the delegate is the same regardless of whether it refers to a static or member function.

Compile an test:
# csc SimpleDelegate3.cs
# SimpleDelegate3.exe
# cat process.log
Process() begin
Process() end

Multicasting

Being able to point to member functions is nice, but there are more tricks you can do with delegates. In C#, delegates are multicast, which means that they can point to more than one function at a time (that is, they’re based off the System.MulticastDelegate type). A multicast delegate maintains a list of functions that will all be called when the delegate is invoked. We can add back in the logging function from the first example, and call both delegates. Here’s what the code looks like:

using System;
using System.IO;
namespace evacion.SimpleDelegate{
// Delegate Specification
public class MyClass{
// Declare a delegate that takes a single string parameter
// and has no return type.

public delegate void LogHandler(string message);
// The use of the delegate is just like calling a function directly,
// though we need to add a check to see if the delegate is null
// (that is, not pointing to a function) before calling the function.

public void Process(LogHandler logHandler){
if (logHandler != null){
logHandler(“Process() begin”);
}
if (logHandler != null) {
logHandler (“Process() end”);
}
}
}
// The FileLogger class merely encapsulates the file I/O
public class FileLogger{
FileStream fileStream;
StreamWriter streamWriter;
// Constructor
public FileLogger(string filename) {
fileStream = new FileStream(filename, FileMode.Create);
streamWriter = new StreamWriter(fileStream);
}
// Member Function which is used in the Delegate
public void Logger(string s){
streamWriter.WriteLine(s);
}

public void Close() {
streamWriter.Close();
fileStream.Close();
}
}
// Test Application which calls both Delegates
public class TestApplication {
// Static Function which is used in the Delegate
static void Logger(string s) {
Console.WriteLine(s);
}
static void Main(string[] args) {
FileLogger fl = new FileLogger(“process.log”);
MyClass myClass = new MyClass();
// Crate an instance of the delegates, pointing to the static
// Logger() function defined in the TestApplication class and
// then to member function on the fl instance of a FileLogger.

MyClass.LogHandler myLogger = null;
myLogger += new MyClass.LogHandler(Logger);
myLogger += new MyClass.LogHandler(fl.Logger);
myClass.Process(myLogger);
fl.Close();
}
}
}

Compile an test:
# csc SimpleDelegate4.cs
# SimpleDelegate4.exe
Process() begin
Process() end
# cat process.log
Process() begin
Process() end

Events
The Event model in C# finds its roots in the event programming model that is popular in asynchronous programming. The basic foundation behind this programming model is the idea of “publisher and subscribers.” In this model, you have publishers who will do some logic and publish an “event.” Publishers will then send out their event only to subscribers who have subscribed to receive the specific event.
In C#, any object can publish a set of events to which other applications can subscribe. When the publishing class raises an event, all the subscribed applications are notified. The following figure shows this mechanism.

events

Conventions

The following important conventions are used with events:

  • Event Handlers in the .NET Framework return void and take two parameters.
  • The first paramter is the source of the event; that is the publishing object.
  • The second parameter is an object derived from EventArgs.
  • Events are properties of the class publishing the event.
  • The keyword event controls how the event property is accessed by the subscribing classes.

Simple Event
Let’s modify our logging example from above to use an event rather than a delegate:

using System;
using System.IO;
namespace evacion.SimpleEvent{
/* ========= Publisher of the Event ============== */
public class MyClass {
// Define a delegate named LogHandler, which will encapsulate
// any method that takes a string as the parameter and returns no value

public delegate void LogHandler(string message);
// Define an Event based on the above Delegate
public event LogHandler Log;
// Instead of having the Process() function take a delegate
// as a parameter, we’ve declared a Log event. Call the Event,
// using the OnXXXX Method, where XXXX is the name of the Event.

public void Process() {
OnLog(“Process() begin”);
OnLog(“Process() end”);
}
// By Default, create an OnXXXX Method, to call the Event
protected void OnLog(string message) {
if (Log != null) {
Log(message);
}
}
}
// The FileLogger class merely encapsulates the file I/O
public class FileLogger {
FileStream fileStream;
StreamWriter streamWriter;
// Constructor
public FileLogger(string filename) {
fileStream = new FileStream(filename, FileMode.Create);
streamWriter = new StreamWriter(fileStream);
}
// Member Function which is used in the Delegate
public void Logger(string s) {
streamWriter.WriteLine(s);
}
public void Close() {
streamWriter.Close();
fileStream.Close();
}
}
/* ========= Subscriber of the Event ============== */
// It’s now easier and cleaner to merely add instances
// of the delegate to the event, instead of having to
// manage things ourselves

public class TestApplication {
static void Logger(string s) {
Console.WriteLine(s);
}
static void Main(string[] args) {
FileLogger fl = new FileLogger(“process.log”);
MyClass myClass = new MyClass();
// Subscribe the Functions Logger and fl.Logger
myClass.Log += new MyClass.LogHandler(Logger);
myClass.Log += new MyClass.LogHandler(fl.Logger);
// The Event will now be triggered in the Process() Method
myClass.Process();
fl.Close();
}
}
}

Compile an test:
# csc SimpleEvent.cs
# SimpleEvent.exe
Process() begin
Process() end
# cat process.log
Process() begin
Process() end

The Second Change Event Example
Suppose you want to create a Clock class that uses events to notify potential subscribers whenever the local time changes value by one second. Here is the complete, documented example:

using System;
using System.Threading;
namespace evacion.SecondChangeEvent{
/* ======================= Event Publisher =============================== */
// Our subject — it is this class that other classes
// will observe. This class publishes one event:
// SecondChange. The observers subscribe to that event.

public class Clock {
// Private Fields holding the hour, minute and second
private int _hour;
private int _minute;
private int _second;
// The delegate named SecondChangeHandler, which will encapsulate
// any method that takes a clock object and a TimeInfoEventArgs
// object as the parameter and returns no value. It’s the
// delegate the subscribers must implement.

public delegate void SecondChangeHandler (
object clock,
TimeInfoEventArgs timeInformation
);

// The event we publish
public event SecondChangeHandler SecondChange;
// The method which fires the Event
protected void OnSecondChange(
object clock,
TimeInfoEventArgs timeInformation
) {
// Check if there are any Subscribers
if (SecondChange != null) {
// Call the Event
SecondChange(clock,timeInformation);
}
}

// Set the clock running, it will raise an
// event for each new second

public void Run() {
for(;;) {
// Sleep 1 Second
Thread.Sleep(1000);
// Get the current time
System.DateTime dt = System.DateTime.Now;
// If the second has changed
// notify the subscribers

if (dt.Second != _second) {
// Create the TimeInfoEventArgs object
// to pass to the subscribers

TimeInfoEventArgs timeInformation =
new TimeInfoEventArgs(
dt.Hour,dt.Minute,dt.Second);

// If anyone has subscribed, notify them
OnSecondChange (this,timeInformation);
}
// update the state
_second = dt.Second;
_minute = dt.Minute;
_hour = dt.Hour;
}
}
}
// The class to hold the information about the event
// in this case it will hold only information
// available in the clock class, but could hold
// additional state information

public class TimeInfoEventArgs : EventArgs {
public TimeInfoEventArgs(int hour, int minute, int second) {
this.hour = hour;
this.minute = minute;
this.second = second;
}
public readonly int hour;
public readonly int minute;
public readonly int second;
}
/* ======================= Event Subscribers =============================== */
// An observer. DisplayClock subscribes to the
// clock’s events. The job of DisplayClock is
// to display the current time

public class DisplayClock {
// Given a clock, subscribe to
// its SecondChangeHandler event

public void Subscribe(Clock theClock) {
theClock.SecondChange +=
new Clock.SecondChangeHandler(TimeHasChanged);

}
// The method that implements the
// delegated functionality

public void TimeHasChanged(
object theClock, TimeInfoEventArgs ti)
{
Console.WriteLine(“Current Time: {0}:{1}:{2}”,
ti.hour.ToString(),
ti.minute.ToString(),
ti.second.ToString());
}
}
// A second subscriber whose job is to write to a file
public class LogClock {
public void Subscribe(Clock theClock) {
theClock.SecondChange +=
new Clock.SecondChangeHandler(WriteLogEntry);
}
// This method should write to a file
// we write to the console to see the effect
// this object keeps no state

public void WriteLogEntry(
object theClock, TimeInfoEventArgs ti) {
Console.WriteLine(“Logging to file: {0}:{1}:{2}”,
ti.hour.ToString(),
ti.minute.ToString(),
ti.second.ToString());
}
}
/* ======================= Test Application =============================== */
// Test Application which implements the
// Clock Notifier – Subscriber Sample

public class Test {
public static void Main() {
// Create a new clock
Clock theClock = new Clock();
// Create the display and tell it to
// subscribe to the clock just created

DisplayClock dc = new DisplayClock();
dc.Subscribe(theClock);
// Create a Log object and tell it
// to subscribe to the clock

LogClock lc = new LogClock();
lc.Subscribe(theClock);
// Get the clock started
theClock.Run();
}
}
}

Conclusion
The Clock class from the last sample could simply print the time rather tahn raising an event, so why bother with the introduction of using delegates? The advantage of the publisg / subscribe idiom is that any number of classes can be notified when an event is raised. The subscribing classes do not need to know how the Clock works, and the Clock does not need to know what they are going to do in response to the event. Similarly a button can publish an Onclick event, and any number of unrelated objects can subscribe to that event, receiving notification when the button is clicked.
The publisher and the subscribers are decoupled by the delegate. This is highly desirable as it makes for more flexible and robust code. The clock can chnage how it detects time without breaking any of the subscribing classes. The subscribing classes can change how they respond to time changes without breaking the Clock. The two classes spin indepentdently of one another, which makes for code that is easier to maintain.

(Source: http://www.akadia.com/services/dotnet_delegates_and_events.html )

 

Cross-Page Postbacks in ASP.NET 2.0 September 16, 2009

Filed under: ASP.NET, C# — evacion @ 11:28 am

By default, an ASP.NET web form posts back to itself whenever a postback operation occurs. That behavior wasn’t terribly common in web pages before ASP.NET appeared, and isn’t always what you want to have happen: What if you want to post a web form to another web page in the application? ASP.NET made that fairly difficult in ASP.NET 1.0, but ASP.NET 2.0 makes developers lives easier in this regard by adding a new feature called “cross-page postbacks” that allows a web page to post its data back to a different web page. In cross-page postbacks, the page that initiates the postback is called the source page and the page to which the client posts is called the target page. Conveniently, the target page can still retrieve any control values posted by the source web page in a cross-page postback operation. In other words, from a development point of view, you can process the posted data in much the same way you would process any normal ASP.NET postback. The new feature means ASP.NET 2.0 developers now have three techniques for transferring processing from one web page to another in an application: Response.Redirect, Server.Transfer, and the new cross-page postback features.

The Response.Redirect Method

The Response.Redirect method is by far the simplest method of redirecting processing from a source page to a different destination or target page in the same or even across different applications. When the web server receives a request for redirection, it sends a response header to the client that causes the client to send a new request back to the server. In other words, a redirect causes two request/response cycles: one for the original and one for the new redirected request.
ASP.NET makes redirects easy. The following code snippet illustrates how to use the Response.Redirect method:
protected void Redirect_Click(object sender, EventArgs e) {
Response.Redirect(“menu.aspx”);
}
Note that the redirect request is a GET request, meaning that you can’t post data from the original page via the Response.Redirect command. You can work around that to pass data from the source to the target by using query strings in the Response.Redirect method call as shown below:

protected void Redirect_Click(object sender, EventArgs e) {
Response.Redirect(“menu.aspx?userName=” + UserName.Text));
}

The preceding example passes a query string as a parameter to the Response.Redirect method along with the target URL. The target can now use code such as the following to retrieve the source’s data as shown below:

protected void Page_Load(object sender, EventArgs e) {
string userName = Request["userName"];
//Other code
}

The Server.Transfer Method
Instead of relying on the client to make a request to a new page, Server.Transfer is a server-side redirection technique that simply changes the code’s “focus” on the web server to a new page. Server.Transfer is far more efficient than Response.Redirect when the target page resides on the same web server, because it avoids the extra roundtrip and uses only server resources for the redirection. Note that it has a side effect—the URL shown in the web browser does not change either—meaning clients may think they posted their data to one page while actually posting it to a different page. In most cases, that’s not a problem, but it can make debugging more difficult.
Server.Transfer also preserves the HttpContext of the initiating page; therefore the target page can access the control values of the source page. Specifically, you can use the FormsCollection property to retrieve the source control values from the target page when using the Server.Transfer technique. First, make sure you use the overloaded Server.Transfer method, which accepts two parameters—the target URL, and a Boolean preserveForm value which tells the server to preserve the query string and any control values from the source page. Set the preserveForm parameter to true in the source web page as shown below:
Server.Transfer(“Menu.aspx”,true);
Then, from the target page, to retrieve the value of a textbox control called txtUserName for example, use the following code:
object obj = Request.Form["txtUserName"];

Response.Redirect vs. Server.Transfer
Because Response.Redirect requires an extra round trip, you should avoid it for high-volume web sites due to associated performance and scalability issues. However, this is the only technique that you can use to redirect from one web server to another. In contrast, Server.Transfer is more efficient, but can transfer execution only to a different web page on the same server. In essence, you’d use Server.Transfer to eliminate unnecessary roundtrips when both the source and the target web page reside on the same server (they can be in different ASP.NET applications on that server), and use Response.Redirect when you need to redirect to a different server.

Cross-page Postbacks
In ASP.NET 2.0, the cross-page postback feature lets you configure page controls that implement the new IButtonControl interface to post to a different target page from the originating web form. Like Response.Redirect, cross-page postbacks are a client-based transfer mechanism—but like Server.Transfer, the target web page can (usually) access the control values of the source page. To set up a cross-page postback, you specify the target URL in the PostBackUrl property of the source web page.
Implementing Cross-page Postbacks
This section discusses how to implement cross-page postbacks in an ASP.NET 2.0 application. If you’re not already thoroughly familiar with ASP.NET postback operations, you can find out more here.
To begin with, assume that you have two web pages—a source and a target. The source web page initiates the cross-page postback operation using a Button control. You first have to set the PostBackUrl property for the button to the target web page’s URL. Incidentally, all web controls that implement the System.Web.UI.WebControls.IButtonControl interface have the cross-page postback feature enabled by default. The following code snippet shows how to set the property.

When you set the PostBackUrl property, the ASP.NET framework binds the corresponding control to a new JavaScript function named WebForm_DoPostBackWithOptions, generating HTML similar to the following:

With that HTML in place, when a user clicks the button, the browser will submit to the target URL (Target.aspx) rather than to the source URL.

Retrieving Source Control Values from the Target Page
ASP.NET 2.0 provides a new property called PreviousPage that returns a reference to the type of the source page whenever a cross-page post back occurs in your web application. Note that this property contains null (it’s not initialized) when the source and the target web pages are in different applications. Also note that when the target page accesses the PreviousPage property to retrieve the control values of the source page, the ASP.NET runtime loads and executes the source page. That fires the ProcessChildRequest event handler. Moreover, it also fires the Page_Init, Page_Load and any other source page button click events.
So that you can avoid doing all that work accidentally, it’s best to check the IsCrossPostBack Boolean property to determine whether a cross-page postback has actually occurred; the value is true if the target page was requested by a cross-page postback has actually occurred. The value is false if control reached the target web page another way (such as a normal request, a Response.Redirect, or a Server.Transfer). Here’s an example that illustrates how to use this property:

if ( PreviousPage.IsCrossPagePostBack) {
//Some code
}
The PreviousPage property works for both Server.Transfer and cross-page postbacks in ASP.NET 2.0. In ASP.NET 2.0, you can use the PreviousPageProperty after a Server.Transfer operation to retrieve the control values of the source page from within the target page. Here’s an example:

protected void Redirect_Click(object sender, EventArgs e) {
Server.Transfer(“menu.aspx”);
}

The receiving web page can now retrieve the control values of the sender web page as shown in the code snippet below:

protected void Page_Load(object sender, EventArgs e) {
if (PreviousPage != null) {
TextBox txtBox = (TextBox)
PreviousPage.FindControl(“txtUserName”);
if (textBox != null)
string userName = textBox.Text;
//Other code
}
}
Notice that the preceding code has to cast the txtUserName control to a TextBox type to access the value. There’s a better way, as you’ll see.

A Better Approach: Using PreviousPageType
The PreviousPageType property provides strongly typed access to a source web page in a cross-page postback operation, letting you retrieve control values from the source page without any typecasting overhead. The code snippets below illustrate how you can use this property.
In the source page you might write:

Note that clicking the button redirects the user to a “Menu.aspx” target page. The target page can retrieve the username and password values using this code:

protected void Page_Load(object sender, System.EventArgs e){
String userName = PreviousPage.txtUserName.Text;
String password = PreviousPage.txtPassword.Text;
//Other code
}

In the preceding code, the PreviousPageType property returns a strongly typed reference to the source web page, eliminating the need to cast.

ViewState Preserved
For cross-page postbacks, ASP.NET 2.0 embeds a hidden input field named __POSTBACK that contains the ViewState information of the source web page—provided the source page contains a server control with a non-null PostBackUrl property value. The target page can use that __POSTBACK information to retrieve the ViewState information of the source web page as shown below:

if(PreviousPage!=null && PreviousPage.IsCrossPagePostBack &&
PreviousPage.IsValid) {
TextBox txtBox = PreviousPage.FindControl(“txtUserName”);
Response.Write(txtBox.Text);
}

The preceding code checks to ensure that the PreviousPage property is not null. Incidentally, the PreviousPage property contains null if the target page is not in the same application. The IsCrossPagePostBack property will be true only if processing reached the target page due to a cross-page postback operation.
The Cross Page Postback feature, one of the most powerful features in ASP.NET 2.0, allows a web page to postback to another web page and still enable retrieval of the values of the server controls of the source web page from within the target web page seamlessly.

(Source: http://www.devx.com/dotnet/Article/33835/1763/page/1 )

 

Why does C# have both ‘ref’ and ‘out’? August 12, 2009

Filed under: ASP.NET, C# — evacion @ 10:23 am

Ref and out parameter passing modes are used to allow a method to alter variables passed in by the caller. The difference between ref and out is subtle but important. Each parameter passing mode is designed to apply to a slightly different programming scenario. The important difference between out and ref parameters is the definite assignment rules used by each.
The caller of a method which takes an out parameter is not required to assign to the variable passed as the out parameter prior to the call; however, the callee is required to assign to the out parameter before returning.
Here’s a simple example:

 class OutExample{
      // Splits a string containing a first and last name separated
      // by a space into two distinct strings, one containing the first name and one containing the last name

      static void SplitName(string fullName, out string firstName, out string lastName){
            // NOTE: firstName and lastName have not been assigned to yet.  Their values cannot be used.
            int spaceIndex = fullName.IndexOf(‘ ‘);
            firstName = fullName.Substring(0, spaceIndex).Trim();
            lastName = fullName.Substring(spaceIndex).Trim();
      }

      static void Main(){
            string fullName = “Yuan Sha”;
            string firstName;
            string lastName;

            // NOTE: firstName and lastName have not been assigned yet.  Their values may not be used.
            SplitName(fullName, out firstName, out lastName);
            // NOTE: firstName and lastName have been assigned, because the out parameter passing mode guarantees it.
            System.Console.WriteLine(“First Name ‘{0}’. Last Name ‘{1}’”, firstName, lastName);
      }
}

One way to think of out parameters is that they are like additional return values of a method. They are very convenient when a method returns more than one value, in this example firstName and lastName. Out parameters can be abused however. As a matter of good programming style if you find yourself writing a method with many out parameters then you should think about refactoring your code. One possible solution is to package all the return values into a single struct.
In contrast ref parameters are considered initially assigned by the callee. As such, the callee is not required to assign to the ref parameter before use. Ref parameters are passed both into and out of a method.
Here’s an example:

class RefExample{
      static object FindNext(object value, object[] data, ref int index){
            // NOTE: index can be used here because it is a ref parameter
            while (index < data.Length){
                  if (data[index].Equals(value)){
                        return data[index];
                  }
                   index += 1;
            }
             return null;
      }

      static void Main(){
            object[] data = new object[] {1,2,3,4,2,3,4,5,3};
            int index = 0;
            // NOTE: must assign to index before passing it as a ref parameter
            while (FindNext(3, data, ref index) != null){
                  // NOTE: that FindNext may have modified the value of index
                  System.Console.WriteLine(“Found at index {0}”, index);
                  index += 1;
            }
            System.Console.WriteLine(“Done Find”);
      }
}

The two parameter passing modes addressed by out and ref are subtly different, however they are both very common. The subtle difference between these modes leads to some very common programming errors. These include:

  • not assigning a value to an out parameter in all control flow paths
  • not assigning a value to variable which is used as a ref parameter

Because the C# language assigns different definite assignment rules to these different parameter passing modes, these common coding errors are caught by the compiler as being incorrect C# code.
The crux of the decision to include both ref and out parameter passing modes was that allowing the compiler to detect these common coding errors was worth the additional complexity of having both ref and out parameter passing modes in the language.

Source: http://msdn.microsoft.com/en-us/vcsharp/aa336814.aspx

 

Source of a PostBack June 11, 2009

Filed under: ASP.NET, C# — evacion @ 3:08 pm
Tags:

Basics of what a PostBack event is:  Most ASP.NET Controls are “Server Controls”. This means that when an action occurs, the Page, which hosts all its controls inside. But, how does the Page class “know” which control was “clicked, changed, or whatever”? Very simply, each control generates plain old client-side Javascript. Since HTTP is stateless and there is no “invisible connection” between the server-side classes and the client-side HTML document in your browser, how can a client-side event be handled on the server side? In ASP.NET, this is done by using hidden form fields. A client-side event, such as an “onclick” or “onchange” event, can be captured by a JavaScript event handler. ASP.Net provides the javascript __doPostBack() function. This records the name of the object that fired the event, as well as any additional event information, places it into the hidden form fields __EVENTTARGET and __EVENTARGUMENT, and then submits the form, initiating our PostBack.
On the server side, any controls that implement either the IPostBackDataHandler or IPostBackEventHandler interfaces (which means that they can process client-side events) will have the appropriate method called to examine the PostBack data and see if they have raised the client-side event. If so, the corresponding server-side event is raised and the event handler method is called. You can create your own custom PostBack by simply calling the ASP.NET “GetPostBackEventReference” method.

 Global.asax.cs codebehind file:

using System;
using System.Collections;
using System.ComponentModel;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;

namespace WhichControlPostedBack{
 public class Global : System.Web.HttpApplication{
  private System.ComponentModel.IContainer components = null;

  public Global(){
   InitializeComponent();
  } 

public static System.Web.UI.Control GetPostBackControl(System.Web.UI.Page page){
  Control control = null;
  string ctrlname = page.Request.Params["__EVENTTARGET"];
  if (ctrlname != null && ctrlname != String.Empty){
   control = page.FindControl(ctrlname);
  }
  // if __EVENTTARGET is null, the control is a button type and we need to 
  // iterate over the form collection to find it
  else{
   string ctrlStr=String.Empty;
   Control c=null;
   foreach (string ctl in page.Request.Form){
    // handle ImageButton controls ...
    if (ctl.EndsWith(".x") || ctl.EndsWith(".y")){
     ctrlStr = ctl.Substring(0,ctl.Length-2);
     c= page.FindControl(ctrlStr);
    }
    else{
     c = page.FindControl(ctl);
    }
          if (c is System.Web.UI.WebControls.Button || 
		c is System.Web.UI.WebControls.ImageButton){
     control = c;
     break;
    }
   }
  }
  return control;
 }
  private void InitializeComponent(){
   this.components = new System.ComponentModel.Container();
  }
 }
}

Its a static method – which means you can reference it without a class instance, simply by calling Global.GetPostBackControl(this), with the “this” being a reference to the Page class that you are in. Typically we would do this as follows, in the Page_Load event handler method:

private void Page_Load(object sender, System.EventArgs e){
if(IsPostBack)
Label1.Text=Global.GetPostBackControl(this).ID.ToString();
} 

source: ASP.NET: Which Control Posted Back?

 

ASP.NET Application Life Cycle Overview for IIS 5.0 and 6.0 May 26, 2009

Filed under: ASP.NET, C# — evacion @ 11:23 am
Tags:

Within ASP.NET, several processing steps must occur for an ASP.NET application to be initialized and process requests. Additionally, ASP.NET is only one piece of the Web server architecture that services requests made by browsers. It is important for you to understand the application life cycle so that you can write code at the appropriate life cycle stage for the effect you intend.

Application Life Cycle in General
User requests an application resource from the Web server. The life cycle of an ASP.NET application starts with a request sent by a browser to the Web server (for ASP.NET applications, typically IIS). ASP.NET is an ISAPI extension under the Web server. When a Web server receives a request, it examines the file-name extension of the requested file, determines which ISAPI extension should handle the request, and then passes the request to the appropriate ISAPI extension. ASP.NET handles file name extensions that have been mapped to it, such as .aspx, .ascx, .ashx, and .asmx. If a file name extension has not been mapped to ASP.NET, ASP.NET will not receive the request. This is important to understand for applications that use ASP.NET authentication. For example, because .htm files are typically not mapped to ASP.NET, ASP.NET will not perform authentication or authorization checks on requests for .htm files. Therefore, even if a file contains only static content, if you want ASP.NET to check authentication, create the file using a file name extension mapped to ASP.NET, such as .aspx. If you create a custom handler to service a particular file name extension, you must map the extension to ASP.NET in IIS and also register the handler in your application’s Web.config file.

ASP.NET receives the first request for the application. When ASP.NET receives the first request for any resource in an application, a class named ApplicationManager creates an application domain. Application domains provide isolation between applications for global variables and allow each application to be unloaded separately. Within an application domain, an instance of the class named HostingEnvironment is created, which provides access to information about the application such as the name of the folder where the application is stored. ASP.NET also compiles the top-level items in the application if required, including application code in the App_Code folder.

AppEnviron2

ASP.NET core objects are created for each request. After the application domain has been created and the HostingEnvironment object instantiated, ASP.NET creates and initializes core objects such as HttpContext, HttpRequest, and HttpResponse. The HttpContext class contains objects that are specific to the current application request, such as the HttpRequest and HttpResponse objects. The HttpRequest object contains information about the current request, including cookies and browser information. The HttpResponse object contains the response that is sent to the client, including all rendered output and cookies.

An HttpApplication object is assigned to the request. After all core application objects have been initialized, the application is started by creating an instance of the HttpApplication class. If the application has a Global.asax file, ASP.NET instead creates an instance of the Global.asax class that is derived from the HttpApplication class and uses the derived class to represent the application. The first time an ASP.NET page or process is requested in an application, a new instance of HttpApplication is created. However, to maximize performance, HttpApplication instances might be reused for multiple requests.
When an instance of HttpApplication is created, any configured modules are also created. For instance, if the application is configured to do so, ASP.NET creates a SessionStateModule module. After all configured modules are created, the HttpApplication class’s Init method is called.

AppEnviron1

The request is processed by the HttpApplication pipeline. The following events are executed by the HttpApplication class while the request is processed. The events are of particular interest to developers who want to extend the HttpApplication class.

  1. Validate the request, which examines the information sent by the browser and determines whether it contains potentially malicious markup. For more information, see ValidateRequest and Script Exploits Overview.
  2. Perform URL mapping, if any URLs have been configured in the UrlMappingsSection section of the Web.config file.
  3. Raise the BeginRequest event.
  4. Raise the AuthenticateRequest event.
  5. Raise the PostAuthenticateRequest event.
  6. Raise the AuthorizeRequest event.
  7. Raise the PostAuthorizeRequest event.
  8. Raise the ResolveRequestCache event.
  9. Raise the PostResolveRequestCache event.
  10. Based on the file name extension of the requested resource (mapped in the application’s configuration file), select a class that implements IHttpHandler to process the request. If the request is for an object (page) derived from the Page class and the page needs to be compiled, ASP.NET compiles the page before creating an instance of it.
  11. Raise the PostMapRequestHandler event.
  12. Raise the AcquireRequestState event.
  13. Raise the PostAcquireRequestState event.
  14. Raise the PreRequestHandlerExecute event.
  15. Call the ProcessRequest method (or the asynchronous version IHttpAsyncHandler..::.BeginProcessRequest) of the appropriate IHttpHandler class for the request. For example, if the request is for a page, the current page instance handles the request.
  16. Raise the PostRequestHandlerExecute event.
  17. Raise the ReleaseRequestState event.
  18. Raise the PostReleaseRequestState event.
  19. Perform response filtering if the Filter property is defined.
  20. Raise the UpdateRequestCache event.
  21. Raise the PostUpdateRequestCache event.
  22. Raise the EndRequest event.
  23. Raise the PreSendRequestHeaders event.
  24. Raise the PreSendRequestContent event.

Life Cycle Events and the Global.asax file
During the application life cycle, the application raises events that you can handle and calls particular methods that you can override. To handle application events or methods, you can create a file named Global.asax in the root directory of your application.
If you create a Global.asax file, ASP.NET compiles it into a class derived from the HttpApplication class, and then uses the derived class to represent the application.
An instance of HttpApplication processes only one request at a time. This simplifies application event handling because you do not need to lock non-static members in the application class when you access them. This also allows you to store request-specific data in non-static members of the application class. For example, you can define a property in the Global.asax file and assign it a request-specific value.
ASP.NET automatically binds application events to handlers in the Global.asax file using the naming convention Application_event, such as Application_BeginRequest. This is similar to the way that ASP.NET page methods are automatically bound to events, such as the page’s Page_Load event. For details, see ASP.NET Page Life Cycle Overview.
The Application_Start and Application_End methods are special methods that do not represent HttpApplication events. ASP.NET calls them once for the lifetime of the application domain, not for each HttpApplication instance.

source: http://msdn.microsoft.com/en-us/library/ms178473.aspx

 

Stopwatch Class April 13, 2009

Filed under: ASP.NET, C# — evacion @ 2:53 pm
Tags:

Provides a set of methods and properties that you can use to accurately measure elapsed time.
A Stopwatch instance can measure elapsed time for one interval, or the total of elapsed time across multiple intervals. In a typical Stopwatch scenario, you call the Start method, then eventually call the Stop method, and then you check elapsed time using the Elapsed property.

A Stopwatch instance is either running or stopped; use IsRunning to determine the current state of a Stopwatch. Use Start to begin measuring elapsed time; use Stop to stop measuring elapsed time. Query the elapsed time value through the properties Elapsed, ElapsedMilliseconds, or ElapsedTicks. You can query the elapsed time properties while the instance is running or stopped. The elapsed time properties steadily increase while the Stopwatch is running; they remain constant when the instance is stopped.

By default, the elapsed time value of a Stopwatch instance equals the total of all measured time intervals. Each call to Start begins counting at the cumulative elapsed time; each call to Stop ends the current interval measurement and freezes the cumulative elapsed time value. Use the Reset method to clear the cumulative elapsed time in an existing Stopwatch instance.

The Stopwatch measures elapsed time by counting timer ticks in the underlying timer mechanism. If the installed hardware and operating system support a high-resolution performance counter, then the Stopwatch class uses that counter to measure elapsed time. Otherwise, the Stopwatch class uses the system timer to measure elapsed time. Use the Frequency and IsHighResolution fields to determine the precision and resolution of the Stopwatch timing implementation.

The Stopwatch class assists the manipulation of timing-related performance counters within managed code. Specifically, the Frequency field and GetTimestamp method can be used in place of the unmanaged Win32 APIs QueryPerformanceFrequency and QueryPerformanceCounter.

private void MyStopWatch(){
string stringToConvert = “1234567890″;
int convertedString = 0;

Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 0; i < 300000000; i++){
convertedString = Convert.ToInt32(stringToConvert);
}
watch.Stop();
Console.WriteLine(“Time Elapsed : ” + watch.Elapsed.ToString());
watch.Reset();

watch.Start();
for (int i = 0; i < 300000000; i++){
convertedString = Int32.Parse(stringToConvert);
}
watch.Stop();
Console.WriteLine(“Time Elapsed : ” + watch.Elapsed.ToString());
}

(source: http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch(VS.80).aspx )

 

Session in ASP.NET November 6, 2008

Filed under: ASP.NET, C# — evacion @ 10:49 pm

Session in ASP.net can be stored in 3 ways.

    1. Inproc
    2. State Server
    3. SqlServer

The InProc mode of Session State management is the fastest among all of the storage modes available and stores the Session data in the ASP.NET worker process. Performance will be effected if the amount of data stored in the session is large. Basically the session is stored in the memory space of an application domain and is volatile. So if asp.net worker process i.e. aspnet_wp.exe restarts then the session state will be lost.
The Session State here entirely depends on the lifetime of the application domain that it runs on. Note that the Session_End event which is fired internally by the web server is supported only in InProc mode. Note that even if the Session State is set to read only using the EnableSessionState attribute, in the InProc mode one can still modify the session. The Session_OnEnd event is invoked by the runtime environment when we make a call to the Session.Abandon() method or when the user’s session times out. Further, any change made in the settings in the web.config file unloads the application domain and the Session State too.

The StateServer mode uses a stand-alone Microsoft Windows service that is independent of IIS and can run on a separate server. In this case the session state is serialized and stored in memory in a separate process that is managed by the aspnet_state.exe file. This has got some performance drawbacks due to the overhead involved in serialization and de-serialization of objects. The main primary advantage of storing the Session State in a State Server is that it is not in the same process as the ASP.NET and a crash of ASP.NET would in no way destroy the session data.  Secondly, this mode of Session State storage enables to share the information across a web garden or a web farm. Rememeber that this mode is slow compared to the InProc mode as it is stored in an external process.

The SQLServer mode of Session State management is a reliable, secure and centralized storage of a session state. In this the Session data is serialized and stored in a database table in the SQL Server database. It can typically be used in the web farms. It has performance bottlenecks as in the State Server mode of Session State management due to the overhead involved in serialization and de-serialization of the objects that are stored and retrieved to and from the Session. SQL Server is more secure than the InProc or the State server modes of Session State storages as the data can be secured easily by configuring the SQL Server security.

 

Master page – reload/flickering October 30, 2008

Filed under: ASP.NET, C# — evacion @ 10:12 am

I’m afraid there’s no way to prevent the master page from reloading after
postback.

At run time, master pages are handled in the following sequence:
1. Users request a page by typing the URL of the content page.
2. When the page is fetched, the @ Page directive is read. If the directive
references a master page, the master page is read as well. If this is the
first time the pages have been requested, both pages are compiled.
3. The master page with the updated content is merged into the control tree
of the content page.
4. The content of individual Content controls is merged into the
corresponding ContentPlaceHolder control in the master page.
5. The resulting merged page is rendered to the browser.

From the browser’s point of view, it’s a single html page, so there’s no
way to only reload a part of it if it’s posted back.

 

Getting started with Windows Presentation Foundation October 6, 2008

Filed under: ASP.NET, C# — evacion @ 4:11 pm

Windows Presentation Foundation (formerly code named “Avalon”) is Microsoft’s unified presentation subsystem for Windows and is exposed through .NET Framework v3.0, Windows Vista’s managed-code programming model. Windows Presentation Foundation (WPF) consists of a display engine that takes full advantage of modern graphics hardware and an extensible set of managed classes that development teams can use to create rich, visually stunning applications. WPF also introduces Extensible Application Markup Language (XAML), which enables developers and designers to use an XML-based model to declaratively specify the desired user interface (UI) behavior. Windows Presentation Foundation provides a unified approach to user interface, 2D and 3D graphics, animation, documents and media. It allows designers to be an integral part of the application development process.

Windows Presentation Foundation:

  • Allows you to:
    • Deliver innovative user interfaces rapidly
    • Increase designer-developer productivity using XAML’s declaritive programming model and WPF tools specifically designed for this designer-developer workflow
    • Leverage your existing code bases and design/development skill sets in building rich applications or controls   

  • Provides a managed code application development framework. Applications using Extensible Application Markup Language (XAML) currently support C# and Microsoft Visual Basic .NET. If you write a Windows Presentation Foundation application entirely in procedural code, you can use any compatible language.
  • Helps you build applications that consist of an Application object and a set of pages. The Application object enables you to handle top-level events, and share code and state between pages.
  • Uses XAML, a declarative markup language, to implement the user interface (UI) of each page. The markup elements control page layout, display text and images, interact with users, and so on. As users progress through the application, they navigate from page to page, much like a Web application.
  • Uses XAML to program the underlying Windows Presentation Foundation object model. Every tag maps to a class and every attribute to a property. When you compile your project, the XAML parser converts the markup into equivalent object model–based code. So, anything you do with XAML, you can also do by manipulating the object model with procedural code.
  • Supports XAML pages that contain both procedural code and markup. For example, if you want to handle an event that is raised by one of the XAML elements on the page, you use XAML to attach a handler to the event. You then implement the event handler in procedural code. Windows Presentation Foundation applications usually separate design from coding by putting the procedural code in a separate code-behind file.
  • Supports two types of applications:
    • XAML Browser Application—Deployed from a server and hosted in the browser. This application type runs in the Internet zone, which limits its access to system resources.
    • Windows Application—Hosted in a window and has full access to system resources.

    You typically use the same code with either application type as long as it does not violate the Internet zone permission set.

 

Windows Presentation Foundation architecture

Windows Presentation Foundation architecture