Sunday, April 17, 2011

static constructor

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.

class SimpleClass
{
// Static variable that must be initialized at run time.
static readonly long baseline;

// Static constructor is called at most one time, before any
// instance constructor is invoked or member is accessed.
static SimpleClass()
{
baseline = DateTime.Now.Ticks;
}
}

Static constructors have the following properties:

  • A static constructor does not take access modifiers or have parameters.

  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

  • A static constructor cannot be called directly.

  • The user has no control on when the static constructor is executed in the program.

  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

  • If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

In this example, class Bus has a static constructor. When the first instance of Bus is created (bus1), the static constructor is invoked to initialize the class. The sample output verifies that the static constructor runs only one time, even though two instances of Bus are created, and that it runs before the instance constructor runs.

Example:

  public class Bus
{
// Static variable used by all Bus instances.
// Represents the time the first bus of the day starts its route.
protected static readonly DateTime globalStartTime;

// Property for the number of each bus.
protected int RouteNumber { get; set; }

// Static constructor to initialize the static variable.
// It is invoked before the first instance constructor is run.
static Bus()
{
globalStartTime = DateTime.Now;

// The following statement produces the first line of output,
// and the line occurs only once.
Console.WriteLine("Static constructor sets global start time to {0}",
globalStartTime.ToLongTimeString());
}

// Instance constructor.
public Bus(int routeNum)
{
RouteNumber = routeNum;
Console.WriteLine("Bus #{0} is created.", RouteNumber);
}

// Instance method.
public void Drive()
{
TimeSpan elapsedTime = DateTime.Now - globalStartTime;

// For demonstration purposes we treat milliseconds as minutes to simulate
// actual bus times. Do not do this in your actual bus schedule program!
Console.WriteLine("{0} is starting its route {1:N2} minutes after global start time {2}.",
this.RouteNumber,
elapsedTime.TotalMilliseconds,
globalStartTime.ToShortTimeString());
}
}

class TestBus
{
static void Main()
{
// The creation of this instance activates the static constructor.
Bus bus1 = new Bus(71);

// Create a second bus.
Bus bus2 = new Bus(72);

// Send bus1 on its way.
bus1.Drive();

// Wait for bus2 to warm up.
System.Threading.Thread.Sleep(25);

// Send bus2 on its way.
bus2.Drive();

// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
/* Sample output:
Static constructor sets global start time to 3:57:08 PM.
Bus #71 is created.
Bus #72 is created.
71 is starting its route 6.00 minutes after global start time 3:57 PM.
72 is starting its route 31.00 minutes after global start time 3:57 PM.
*/




Saturday, April 16, 2011

Return a string using EnterpriseLibrary

This code sample gives a simple example of handling out parameter of stored procedure using EnterpriseLibrary.

Prerequisites: EnterpriseLibrary 4.1

1. Add the reference to Microsoft.Practices.EnterpriseLibrary.Data.dll
2. Add the reference to Microsoft.Practices.EnterpriseLibrary.Common.dll
3. In the web.config file, create the database conection string
4. In the business layer, class file add reference to

using Microsoft.Practices.EnterpriseLibrary.Data;


public string GetEmployeeId(string strEmpName)
{
string strEmployeeId = string.Empty;
Database objDatabase = DatabaseFactory.CreateDatabase("HRPortal");
DbCommand objDBCommand = objDatabase.GetStoredProcCommand("spHR_GetEmployeeId");
objDatabase.AddInParameter(objDBCommand, "EmpName", DbType.String, strEmpName);
objDatabase.AddOutParameter(objDBCommand, "iEmpId", DbType.String);
objDatabase.ExecuteScalar(objDBCommand);
strEmployeeId = objDatabase.GetParameterValue(objDBCommand, "iEmpId").ToString();
return strEmployeeId;
}

Wednesday, April 13, 2011

Agile -Scrum methodologies

Agile Manifesto made in revising a philosophical approach to software development, it didn’t provide the concrete processes that development teams depend on when deadlines — and stakeholders — start applying pressure. As a result, when it comes to the nuts and bolts of running a team with agile every day, organizations turn to particular subsets of the agile methodology. These include Crystal Clear, Extreme Programming, Feature Driven Development, Dynamic Systems Development Method (DSDM), Scrum, and others. At my organization, we use Scrum and I’ve found it to be an incredibly effective management methodology for everyone involved, including developers and stakeholders. If you’re interested in learning about the other agile methodologies, there are plenty of resources out there. This blog is designed to provide some essential background for those who are new to Scrum.


What’s Unique about Scrum?

Of all the agile methodologies, Scrum is unique because it introduced the idea of “empirical process control.” That is, Scrum uses the real-world progress of a project — not a best guess or uninformed forecast — to plan and schedule releases. In Scrum, projects are divided into succinct work cadences, known as sprints, which are typically one week, two weeks, or three weeks in duration. At the end of each sprint, stakeholders and team members meet to assess the progress of a project and plan its next steps. This allows a project’s direction to be adjusted or reoriented based on completed work, not speculation or predictions.

Philosophically, this emphasis on an ongoing assessment of completed work is largely responsible for its popularity with managers and developers alike. But what allows the Scrum methodology to really work is a set of roles, responsibilities, and meetings that never change. If Scrum’s capacity for adaption and flexibility makes it an appealing option, the stability of its practices give teams something to lean on when development gets chaotic.

The Roles of Scrum
Scrum has three fundamental roles: Product Owner, ScrumMaster, and team member.

Product Owner: In Scrum, the Product Owner is responsible for communicating the vision of the product to the development team. He or she must also represent the customer’s interests through requirements and prioritization. Because the Product Owner has the most authority of the three roles, it’s also the role with the most responsibility. In other words, the Product Owner is the single individual who must face the music when a project goes awry.

The tension between authority and responsibility means that it’s hard for Product Owners to strike the right balance of involvement. Because Scrum values self-organization among teams, a Product Owner must fight the urge to micro-manage. At the same time, Product Owners must be available to answer questions from the team.

ScrumMaster: The ScrumMaster acts as a liaison between the Product Owner and the team. The ScrumMaster does not manage the team. Instead, he or she works to remove any impediments that are obstructing the team from achieving its sprint goals. In short, this role helps the team remain creative and productive, while making sure its successes are visible to the Product Owner. The ScrumMaster also works to advise the Product Owner about how to maximize ROI for the team.

Team Member: In the Scrum methodology, the team is responsible for completing work. Ideally, teams consist of seven cross-functional members, plus or minus two individuals. For software projects, a typical team includes a mix of software engineers, architects, programmers, analysts, QA experts, testers, and UI designers. Each sprint, the team is responsible for determining how it will accomplish the work to be completed. This grants teams a great deal of autonomy, but, similar to the Product Owner’s situation, that freedom is accompanied by a responsibility to meet the goals of the sprint.

Tuesday, April 12, 2011

.Net Framework

When compiling to managed code, the compiler translates your source code into Microsoft intermediate language (MSIL), which is a CPU-independent set of instructions that can be efficiently converted to native code. MSIL includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations. Microsoft intermediate language (MSIL) is a language used as the output of a number of compilers and as the input to a just-in-time (JIT) compiler. The common language runtime includes a JIT compiler for converting MSIL to native code.

Can I write IL programs directly?
Yes. Peter Drayton posted this simple

Before Microsoft intermediate language (MSIL) can be executed, it must be converted by a .NET Framework just-in-time (JIT) compiler to native code, which is CPU-specific code that runs on the same computer architecture as the JIT compiler.

Rather than using time and memory to convert all the MSIL in a portable executable (PE) file to native code, it converts the MSIL as it is needed during execution and stores the resulting native code so that it is accessible for subsequent calls.

The runtime supplies another mode of compilation called install-time code generation. The install-time code generation mode converts MSIL to native code just as the regular JIT compiler does, but it converts larger units of code at a time, storing the resulting native code for use when the assembly is subsequently loaded and executed.

As part of compiling MSIL to native code, code must pass a verification process unless an administrator has established a security policy that allows code to bypass verification. Verification examines MSIL and metadata to find out whether the code can be determined to be type safe, which means that it is known to access only the memory locations it is authorized to access.

What is strong name?
A name that consists of an assembly's identity—its simple text name, version number, and culture information (if provided)—strengthened by a public key and a digital signature generated over the assembly.

What is portable executable (PE)?
The file format defining the structure that all executable files (EXE) and Dynamic Link Libraries (DLL) must use to allow them to be loaded and executed by Windows. PE is derived from the Microsoft Common Object File Format (COFF). The EXE and DLL files created using the .NET Framework obey the PE/COFF formats and also add additional header and data sections to the files that are only used by the CLR. The specification for the PE/COFF file formats is available at http://www.microsoft.com/whdc/hwdev/hardware/pecoffdown.mspx

Saturday, April 9, 2011

Early Binding vs. Late Binding

Before discussing about the differences, let's know what is meant by Early and Late Binding.

Early Binding

The name itself describes that compiler knows about what kind of object it is, what are all the methods and properties it contains. As soon as you declared the object, .NET Intellisense will populate its methods and properties on click of the dot button.

Common Examples:


ComboBox cboItems;


ListBox lstItems;

In the above examples, if we type the cboItem and place a dot followed by, it will automatically populate all the methods, events and properties of a combo box, because compiler already know it's an combobox.

Late Binding

The name itself describes that compiler does not know what kind of object it is, what are all the methods and properties it contains. You have to declare it as an object, later you need get the type of the object, methods that are stored in it. Everything will be known at the run time.

Common Examples:


Object objItems;


objItems = CreateObject("DLL or Assembly name");

Here during the compile time, type of objItems is not determined. We are creating an object of a dll and assigning it to the objItems, so everything is determined at the run time.

Early Binding vs. Late Binding

Now coming into the picture…


Application will run faster in Early binding, since no boxing or unboxing are done here.


Easier to write the code in Early binding, since the intellisense will be automatically populated


Minimal Errors in Early binding, since the syntax is checked during the compile time itself.


Late binding would support in all kind of versions, since everything is decided at the run time.


Minimal Impact of code in future enhancements, if Late Binding is used.


Performance will be code in early binding.

Both have merits and demerits, it's the developer decision to choose the appropriate binding based on the scenario.

Friday, April 1, 2011

Page Life Cycle Events






































EventDescription
PreInit

This is the first real event you might handle for a page. You typically use this event only if you need to dynamically (from code) set values such as master page or theme.


This event is also useful when you are working with dynamically created controls for a page. You want to create the controls inside this event.

Init

This event fires after each control has been initialized. You can use
this event to change initialization values for controls.

InitComplete

Raised once all initializations of the page and its controls have been completed.

PreLoadThis event fires before view state has been loaded for the page and its controls and before PostBack processing. This event is useful when you need to write code after the page is initialized but before the view state has been wired back up to the controls.
Load

The page is stable at this time; it has been initialized and its state has been reconstructed. Code inside the page load event typically checks for PostBack and then sets control properties appropriately.


The page’s load event is called first. Then, the load event for each child control is called in turn (and their child controls, if any). This is important to know if you are writing your own user or custom controls.

Control (PostBack) event(s)ASP.NET now calls any events on the page or its controls that caused the PostBack to occur. This might be a button’s click event, for example.
LoadCompleteAt this point all controls are loaded. If you need to do additional processing at this time you can do so here.
PreRenderAllows final changes to the page or its control. This event takes place after all regular PostBack events have taken place. This event takes place before saving ViewState, so any changes made here are saved.
SaveStateComplete

Prior to this event the view state for the page and its controls is set. Any changes to the page’s controls at this point or beyond are ignored. This is useful if you need to write processing that requires the view state to be set.

Render

This is a method of the page object and its controls (and not an event). At this point, ASP.NET calls this method on each of the
page’s controls to get its output.
The Render method generates the client-side HTML, Dynamic Hypertext Markup Language (DHTML), and script that are necessary to properly display a control at the browser. This method is useful if you are writing your own custom control. You override this method to control output for the control.

UnLoad

This event is used for cleanup code. You use it to release any managed resources in this stage. Managed resources are resources
that are handled by the runtime, such as instances of classes created by the .NET common language runtime.

Popular Posts

Recent Posts

Unordered List

Text Widget