31 July, 2011

OOP interview questions and answers...

Q. What is difference between overloading and overriding?
A. Having same name methods with different parameters is called overloading, while having same name and parameter functions in base and drive class called overriding.

Q. What is Operator Overloading?
A. The operator overloading is a specific case of polymorphisms in which some or all of operators like +, -, %, etc. are treated as polymorphic functions and as such have different behaviors depending on the types of its operands.

Q. What is copy constructor?
A. Constructor which initializes it's object member variables ( by shallow copying) with another object of the same class. If you don't implement one in your class then compiler implements one for you.
for example:
Test t1(10); // calling Test constructor
Test t2(t1); // calling Test copy constructor
Test t2 = t1;// calling Test copy constructor
Copy constructors are called in following cases:
  • when a function returns an object of that class by value.
  • when the object of that class is passed by value as an argument to a function.
  • when you construct an object based on another object of the same class.
  • When compiler generates a temporary object.

Q. What is friend function?
A. As the name suggests, the function acts as a friend to a class. As a friend of a class, it can access its private and protected members. A friend function is not a member of the class. But it must be listed in the class definition.

Q. What are virtual functions? Describe a circumstance in which virtual functions would be appropriate?
A. Virtual functions are functions with the same function prototype that are defined throughout a class hierarchy. At least the base class occurrence of the function is preceded by the keyword virtual. Virtual functions are used to enable generic processing of an entire class hierarchy of objects through a base class pointer. For example, in a shape hierarchy, all shapes can be drawn. If all shapes are derived from a base class Shape which contains a virtual draw function, then generic processing of the hierarchy can be performed by calling every shape’s draw generically through a base class Shape pointer.

28 July, 2011

ASP.NET interview questions and answers...

Q.What is the difference between an EXE and a DLL?

A. An exe is an executible program. A DLL (Dynamic Link Library) is a file that can be loaded and executed by programs dynamically. Basically it's an external code repository for programs. Since usually several different programs reuse the same DLL instead of having that code in their own file, this dramatically reduces required storage space. A synonym for a DLL would be library.

DLL does not have main function but exe has main function.

Here DLL is inprocess component, both component and consumer will share same memory and Exe is out process component, it will run in its own memory.



Q. What is CLR?

A. Common Language Runtime (CLR) is a run-time environment that manages the execution of .NET code and provides services like memory management, debugging, security, etc. The CLR is also known as Virtual Execution System (VES).


Q. List the various stages of Page-Load lifecycle.

A. 1. Init()

2. Load()

3. PreRender()

4. Unload()


Q. Explain the differences between server-side and client-side code?

A. Server side scripting means that all the script will be executed by the server and interpreted as needed. Client side scripting means that the script will be executed immediately in the browser such as form field validation, clock, email validation, etc. Client side scripting is usually done in VBScript or JavaScript. Since the code is included in the HTML page, anyone can see the code by viewing the page source. It also poses as a possible security hazard for the client computer.


Q. What is Code-Behind?

A. Code-Behind is a concept where the contents of a page are in one file and the server-side code is in another. This allows different people to work on the same page at the same time and also allows either part of the page to be easily redesigned, with no changes required in the other. An Inherits attribute is added to the @ Page directive to specify the location of the Code-Behind file to the ASP.NET page.


Q. Describe the difference between inline and code behind.

A. Inline code is written along side the HTML in a page. There is no separate distinction between design code and logic code. Code-behind is code written in a separate file and referenced by the .aspx page.


Q. List the ASP.NET validation controls?

A. RequiredFieldValidator

RangeValidator

CompareValidator

RegularExpressionValidator

CustomValidator

ValidationSummary


Q. What is the difference between Server.Transfer and Response.Redirect?

A. Response.Redirect: This tells the browser that the requested page can be found at a new location. The browser then initiates another request to the new page loading its contents in the browser. This results in two requests by the browser.

Server.Transfer: It transfers execution from the first page to the second page on the server. As far as the browser client is concerned, it made one request and the initial page is the one responding with content. The benefit of this approach is one less round trip to the server from the client browser. Also, any posted form variables and query string parameters are available to the second page as well.


Q. What is an interface and what is an abstract class?

A. In an interface, all methods must be abstract (must not be defined). In an abstract class, some methods can be defined. In an interface, no accessibility modifiers are allowed, whereas it is allowed in abstract classes.


Q. Session state vs. View state:

A. In some cases, using view state is not feasible. The alternative for view state is session state. Session state is employed under the following situations:

• Large amounts of data - View state tends to increase the size of both the HTML page sent to the browser and the size of form posted back. Hence session state is used.

• Secure data - Though the view state data is encoded and may be encrypted, it is better and secure if no sensitive data is sent to the client. Thus, session state is a more secure option.

• Problems in serializing of objects into view state - View state is efficient for a small set of data. Other types like DataSet are slower and can generate a very large view state.


Q. How does System.Web.UI.Page's IsPostBack property work?

A. IsPostBack checks to see whether the HTTP request is accompanied by postback data containing a __VIEWSTATE or __EVENTTARGET parameter. If there are none, then it is not a postback.


Q. How ASP .NET different from ASP?

A. Scripting is separated from the HTML, Code is compiled as a DLL, these DLLs can be executed on the server.


Q. What is smart navigation?

A. The cursor position is maintained when the page gets refreshed due to the server side validation and the page gets refreshed.


Q. What is view state?

A. The web is stateless. But in ASP.NET, the state of a page is maintained in the in the page itself automatically. How? The values are encrypted and saved in hidden controls. this is done automatically by the ASP.NET. This can be switched off / on for a single control.


Q. What is an Intermediate language?

A. Assemblies are made up of IL code modules and the metadata that describes them. Although programs may be compiled via an IDE or the command line, in fact, they are simply translated into IL, not machine code. The actual machine code is not generated until the function that requires it is called. This is the just-in-time, or JIT, compilation feature of .NET. JIT compilation happens at runtime for a variety of reasons, one of the most ambitious being Microsoft's desire for cross-platform .NET adoption. If a CLR is built for another operating system (UNIX or Mac), the same assemblies will run in addition to the Microsoft platforms. The hope is that .NET assemblies are write-once-run-anywhere applications. This is a .NET feature that works behind-the-scenes, ensuring that developers are not limited to writing applications for one single line of products. No one has demonstrated whether or not this promise will ever truly materialize.


Q. What is an assembly?

A. An assembly is the primary building block of a .NET Framework application. It is a collection of functionality that is built, versioned, and deployed as a single implementation unit (as one or more files). All managed types and resources are marked either as accessible only within their implementation unit, or as accessible by code outside that unit. .NET Assembly contains all the metadata about the modules, types, and other elements it contains in the form of a manifest. The CLR loves assemblies because differing programming languages are just perfect for creating certain kinds of applications. For example, COBOL stands for Common Business-Oriented Language because it’s tailor-made for creating business apps. However, it’s not much good for creating drafting programs. Regardless of what language you used to create your modules, they can all work together within one Portable Executable Assembly. There’s a hierarchy to the structure of .NET code. That hierarchy is Assembly - > Module -> Type -> Method." Assemblies can be static or dynamic. Static assemblies can include .NET Framework types (interfaces and classes), as well as resources for the assembly (bitmaps, JPEG files, resource files, and so on). Static assemblies are stored on disk in portable executable (PE) files. You can also use the .NET Framework to create dynamic assemblies, which are run directly from memory and are not saved to disk before execution. You can save dynamic assemblies to disk after they have executed.


Q. What is Serialization in .NET?

A. When developing smaller applications that do not have a database (or other formal storage mechanism) or data that doesn’t need to be stored in a database (such as the state of a web application), you often still would like to save the data for later retrieval. There are many ways to do this, but many of them are subject to a lot of extra code (work) and extra time spent debugging. With .NET, there is now an easy way to add this functionality to your code with only a few lines of easily tested code. This easy way is called serialization.

The serialization is the process of converting the objects into stream of bytes.

they or used for transport the objects(via remoting) and persist objects(via files and databases).


Q. What is a CLR?

A. Full form of CLR is Common Language Runtime and it forms the heart of the .NET

framework.All Languages have runtime and its the responsibility of the runtime to take care of

the code execution of the program.For example VC++ has MSCRT40.DLL,VB6 has

MSVBVM60.DLL , Java has Java Virtual Machine etc. Similarly .NET has CLR.Following are the

responsibilities of CLR

• Garbage Collection :- CLR automatically manages memory thus eliminating memory leakes. When objects are not referred GC automatically releases those memory thus providing efficient memory management.

• Code Access Security :- CAS grants rights to program depending on the security configuration of the machine.Example the program has rights to edit or create a new file but the security configuration of machine does not allow the program to delete a file.CAS will take care that the code runs under the environment of machines security configuration.

• Code Verification :- This ensures proper code execution and type safety while the code runs.It prevents the source code to perform illegal operation such as accessing invalid memory locations etc.

• IL( Intermediate language )-to-native translators and optimizer’s :- CLR uses JIT and compiles the IL code to machine code and then executes. CLR also determines depending on platform what is optimized way of running the IL code.


Q. What is a Assembly ?

A.

• Assembly is unit of deployment like EXE or a DLL.

• An assembly consists of one or more files (dlls, exe’s, html files etc.), and represents a group of resources, type definitions, and implementations of those types. An assembly may also contain references to other assemblies. These resources, types and references are described in a block of data called a manifest. The manifest is part of the assembly, thus making the assembly self-describing.

• An assembly is completely self-describing.An assembly contains metadata information, which is used by the CLR for everything from type checking and security to actually invoking the components methods.As all information is in assembly itself it is independent of registry.This is the basic advantage as compared to COM where the version was stored in registry.

• Multiple versions can be deployed side by side in different folders. These different versions can execute at the same time without interfering with each other.Assemblies can be private or shared. For private assembly deployment,the assembly is copied to the same directory as the client program that references it.No registration is needed, and no fancy installation program is required. When the component is removed, no registry cleanup is needed,and no uninstall

• program is required. Just delete it from the hard drive.

• In shared assembly deployment, an assembly is installed in the Global Assembly Cache (or GAC). The GAC contains shared assemblies that are globally accessible to all .NET applications on the machine.


Q. What is NameSpace?

A. Namespace has two basic functionality:-

• NameSpace Logically group types.Example System.Web.UI logically groups our UI related features.

• In Object Oriented world may times its possible that programmers will use the same class name.By qualifying NameSpace with classname this collision can be removed.


Q. What is Difference between NameSpace and Assembly?

A. Following are the differences between namespace and assembly :

• Assembly is physical grouping of logical units. Namespace logically groups classes.

• Namespace can span multiple assemblies.


Q. What is Manifest?

A. Assembly metadata is stored in Manifest.Manifest contains all the metadata needed to do the

following things( See Figure Manifest View for more details) :

• Version of assembly

• Security identity

• Scope of the assembly

• Resolve references to resources and classes.

• The assembly manifest can be stored in either a PE file (an .exe or .dll) with Microsoft intermediate language (MSIL) code or in a stand-alone PE file that contains only assembly manifest information.


Q. Where is version information stored of a assembly?

A. Version information is stored in assembly in manifest.


Q. What are different type of JIT?

A. JIT compiler is a part of the runtime execution environment.

In Microsoft .NET there are three types of JIT compilers:

• Pre-JIT. Pre-JIT compiles complete source code into native code in a single compilation cycle. This is done at the time of deployment of the application.

• Econo-JIT. Econo-JIT compiles only those methods that are called at runtime. However, these compiled methods are removed when they are not required.

• Normal-JIT. Normal-JIT compiles only those methods that are called at runtime. These methods are compiled the first time they are called, and then they are stored in cache. When the same methods are called again, the compiled code from cache is used for execution.


Q. What are Value types and Reference types?

A. Value types directly contain their data are either allocated on the stack or allocated in-line in a structure.

Reference types store a reference to the value's memory address, and are allocated on the heap. Reference types can be self-describing types, pointer types, or interface types.

Variables that are value types each have their own copy of the data, and therefore operations on one variable do not affect other variables. Variables that are reference types can refer to the same object; therefore, operations on one variable can affect the same object referred to by another variable. All types derive from the System.Object base type.


Q. What is Multi-tasking ?

A. Its a feature of modern operating systems with which we can run multiple programs at

same time example Word,Excel etc.


Q. What is Multi-threading ?

A. Multi-threading forms subset of Multi-tasking instead of having to switch between programs

this feature switches between different parts of the same program.Example you are writing

in word and at the same time word is doing a spell check in background.


Q. What is a Thread ?

A. A thread is the basic unit to which the operating system allocates processor time.


Q. What’s difference between thread and process?

A. A thread is a path of execution that run on CPU, a process is a collection of threads that

share the same virtual memory. A process has at least one thread of execution, and a thread always run in a process context.


Q. What is a Web Service?

A. Web Services are business logic components which provide functionality via the Internet

using standard protocols such as HTTP.

Web Services uses Simple Object Access Protocol (SOAP) in order to expose the business

functionality. SOAP defines a standardized format in XML which can be exchanged between two entities over standard protocols such as HTTP.SOAP is platform independent so the consumer of a Web Service is therefore completely shielded from any implementation details about the platform exposing the Web Service. For the consumer it is simply a black box of send and receive XML over HTTP. So any web service hosted on windows can also be consumed by UNIX and LINUX platform.


Q. Which various modes of storing ASP.NET session ?

A.

• InProc:- In this mode Session state is stored in the memory space of the Aspnet_wp.exe process.This is the default setting.If the IIS reboots or web application restarts then session state is lost.

• StateServer:-In this mode Session state is serialized and stored in a separate process (Aspnet_state.exe); therefore, the state can be stored on a separate computer(a state server).

• SQL SERVER:- In this mode Session state is serialized and stored in a SQL Server database.

Session state can be specified in element of application configuration

file.Using State Server and SQL SERVER session state can be shared across web farms

but note this comes at speed cost as ASP.NET needs to serialize and deserialize data over

network again and again.


Q. What are the other ways you can maintain state?

A. Other than session variables you can use the following technique to store state :

• Hidden fields

• View state

• Hidden frames

• Cookies

• Query strings


Q. What are benefits and Limitation of using Hidden fields?

A. Following are the benefits of using Hidden fields :-

• They are simple to implement.

• As data is cached on client side they work with Web Farms.

• All browsers support hidden field.

• No server resources are required.

Following are limitations of Hidden field :-

• They can be tampered creating a security hole.

• Page performance decreases if you store large data , as the data is stored in pages itself.

• Hidden fields do not support rich structures as HTML hidden fields are only single valued.Then you have to work around with delimiters etc to handle complex structures.

Below is how you will actually implement hidden field in a project



Q. What is ViewState ?

A. Viewstate is a built-in structure for automatically retaining values among multiple requests

for the same page. The view state is internally maintained as a hidden field on the page but is hashed, providing greater security than developer-implemented hidden fields do.


Q. What are benefits and Limitation of using Viewstate for state management?

A. Following are the benefits of using Viewstate :-

• No server resources are required because state is contained in a structure in the page code.

• Simplicity.

• States are retained automatically.

• The values in view state are hashed, compressed, and encoded, thus representing a higher state of security than hidden fields.

• View state is good for caching data in Web farm configurations because the data is cached on the client.

Following are limitation of using Viewstate:-

• Page loading and posting performance decreases when large values are stored because view state is stored in the page.

• Although view state stores data in a hashed format, it can still be tampered with because it is stored in a hidden field on the page. The information in the hidden field can also be seen if the page output source is viewed directly, creating a potential security risk.

Below is sample of storing values in view state.

this.ViewState["EnterTime"] = DateTime.Now.ToString();


Q. What are benefits and Limitation of using Cookies?

A. Following are benefits of using cookies for state management :-

• No server resources are required as they are stored in client.

• They are light weight and simple to use

Following are limitation of using cookies :-

• Most browsers place a 4096-byte limit on the size of a cookie,although support for 8192-byte cookies is becoming more common in the new browser and client-device versions available today.

• Some users disable their browser or client device’s ability to receive cookies, thereby limiting the use of cookies.

• Cookies can be tampered and thus creating a security hole.

• Cookies can expire thus leading to inconsistency.

Below is sample code of implementing cookies

Request.Cookies.Add(New HttpCookie(“name”, “user1”))


Q. What is Query String and What are benefits and Limitation of using Query Strings?

A. A query string is information sent to the server appended to the end of a page URL.

Following are the benefits of using query string for state management:-

• No server resources are required. The query string is contained in the HTTP request for a specific URL.

• All browsers support query strings.

Following are limitations of query string :-

• Query string data is directly visible to user thus leading to security problems.-

• Most browsers and client devices impose a 255-character limit on URL length.

Below is a sample “Login” query string passed in URL http://www.querystring.com/

login.asp?login=testing.This querystring data can then be requested later by using

Request.QueryString(“login”).


Q. What’s a Class?

A. A class describes all the attributes of objects , as well as the methods that implement the

behavior of member objects.Its a comprehensive data type which represent a blue print

of objects.It’s a template of object.


Q. What’s a Object?

A. It’s a basic unit of a system.An object is an entity that has attributes, behavior, and identity. Objects are members of a class.Attributes and behavior of an object are defined by the class definition.


Q. What’s the relation between Classes and Objects?

A.They look very much same but are not same.Class is a definition , while object is a instance of the class created.Class is a blue print while objects are actual objects existing in real world.Example we have class CAR which has attributes and methods like Speed,Brakes,Type of Car etc.Class CAR is just a prototype , now we can create real time objects which can be used to provide functionality . Example we can create a Maruti car object with 100 km speed and urgent brakes.


Q. What is difference between abstract classes and interfaces?

A. Following are the differences between abstract and interfaces :-

• Abstract classes can have concrete methods while interfaces have no methods implemented.

• Interfaces do not come in inheriting chain , while abstract classes come in inheritance.


Q. What are different accessibility levels defined in .NET ?

A. Following are the five levels of access modifiers :-

• Private : Only members of class have access.

• Protected :-All members in current class and in derived classes can access the variables.

• Friend (internal in C#) :- Only members in current project have access to the elements.

• Protected friend (protected internal in C#) :- All members in current project and all members in derived class can access the variables.

• Public :- All members have access in all classes and projects.


Q. What are similarities between Class and structure ?

A. Following are the similarities between classes and structures :-

• Both can have constructors, methods, properties, fields, constants, enumerations, events, and event handlers.

• Structures and classes can implement interface.

• Both of them can have constructors without parameter and with parameter.

• Both can have delegates and events.


Q. What’s the difference between Class and structure’s?

A. Following are the key differences between them:-

• Structure are value types and classes are reference types.So structures use stack and classes use heap.

• Structures members can not be declared as protected , but class members can be.You can not do inheritance in structures.

• Structures do not require constructors while classes require.

• Objects created from classes are terminated using Garbage collector.Structures are not destroyed using GC.


Q. What does virtual keyword mean?

A. That method and property can be overridden.


Q. What is ENUM?

A. It’s used to define constants.


Q. How can we identify that the Page is PostBack?

A. Page object has a “IsPostBack” property which can be checked to know that is the page

posted back.


Q. What’s the use of SmartNavigation property?

A. It’s a feature provided by ASP.NET to prevent flickering and redrawing when the page is

posted back.


Q. Where is ViewState information stored?

A. In HTML Hidden Fields.


Q. Can you explain what is “AutoPostBack” feature in ASP.NET ?

A. If we want the control to automatically postback in case of any event , we will need to

check this attribute as true.Example on a ComboBox change we need to send the event

immediately to the server side then set the “AutoPostBack” attribute to true.


Q. What’s difference between Server.Transfer and response.Redirect ?

A. Following are the major differences between them:-

• Response.Redirect sends message to the browser saying it to move to some different page.While server.transfer does not send any message to the browser but rather redirects the user directly from the server itself. So in server.transfer there is no round trip while response.redirect has a round trip and hence puts a load on server.

• Using Server.Transfer you can not redirect to a different from the server itself. Example If your server is www.yahoo.com you can use server.transfer to move to www.microsoft.com but yes you can move to www.yahoo.com/travels , i.e. within websites. This cross server redirect is possible only using Response.redirect.

• With server.transfer you can preserve your information. It has a parameter called as “preserveForm”. So the existing query string etc. will be able in the calling page. In response.redirect you can maintain the state. You can but has lot of drawbacks.


Q. What’s difference between Authentication and authorization?

A. Authentication is verifying the identity of a user and authorization is process where we check does this identity have access rights to the system. Authorization is the process of allowing an authenticated user access to resources. Authentication is always precedes to Authorization; even if your application lets anonymous users connect and use the application, it still authenticates them as being anonymous.


Q. What’s difference between Datagrid , Datalist and repeater ?

A. A Datagrid, Datalist and Repeater are all ASP.NET data Web controls.

They have many things in common like DataSource Property , DataBind Method

ItemDataBound and ItemCreated.

When you assign the DataSource Property of a Datagrid to a DataSet then each DataRow present in the DataRow Collection of DataTable is assigned to a corresponding DataGridItem and this is same for the rest of the two controls also.But The HTML code generated for a Datagrid has an HTML TABLE element created for the particular DataRow and its a Table form representation with Columns and Rows.

For a Datalist its an Array of Rows and based on the Template Selected and the RepeatColumn Property value We can specify how many DataSource records should appear per HTML row. In short in datagrid we have one record per row, but in datalist we can have five or six rows per row.

For a Repeater Control,The Datarecords to be displayed depends upon the Templates specified and the only HTML generated is the due to the Templates.

In addition to these , Datagrid has a in-built support for Sort,Filter and paging the Data ,which is not possible when using a DataList and for a Repeater Control we would require to write an explicit code to do paging.


Q. How can we kill a user session?

A. Session.abandon


Q. How do you upload a file in ASP.NET ?

A. I will leave this to the readers … Just a hint we have to use System.Web.HttpPostedFile class.


Q. Explain the differences between Server-side and Client-side code?

A. Server side code is executed at the server side on IIS in ASP.NET framework , while

client side code is executed on the browser.


Q. What is difference between dataset and datareader?

A. Following are some major differences between dataset and datareader :-

• DataReader provides forward-only and read-only access to data , while the DataSet object can hold more than one table (in other words more than one rowset) from the same data source as well as the relationships between them.

• Dataset is a disconnected architecture while datareader is connected architecture.

• Dataset can persists contents while datareader can not persist contents , they are forward only.


Q. What’s difference between Dataset. clone and Dataset.copy?

A. Clone: - It only copies structure, does not copy data.

Copy: - Copies both structure and data

27 July, 2011

Simple Midlet application in J2ME

package healthPackage;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;


/*
* @author Syed Imran Hossen
*/
public class mainMIDlet extends MIDlet implements CommandListener{
//Declaration of all controls
private Display display;
private TextField age;
private ChoiceGroup gender=new ChoiceGroup("Gender:", Choice.POPUP); //Male or Female
private TextField tc;
private TextField hdlc;
private ChoiceGroup smoker=new ChoiceGroup("Smoker:", Choice.POPUP); //Yes or No
private TextField sbp;
private ChoiceGroup isBPMedication=new ChoiceGroup("Taking BP Medication:", Choice.POPUP); //Yes or No
private Form form;
private Form splashScreen;
private Command exit;
private Command ok;
private ImageItem imageItem;
private Image image;


private int result=0;
private int riskPercentage=0;
private int output=0;
private int valid=0;

public mainMIDlet() {
//initialization of all controls
form = new Form("Cardiac Risk Calculator");
splashScreen = new Form("Novartis (Bangladesh) Limited.");

age = new TextField("Age(Yr):", "", 10, TextField.DECIMAL);

gender.append("Male", null);
gender.append("Female", null);

tc = new TextField("TC(mg/dl):", "", 10, TextField.DECIMAL);
hdlc = new TextField("HDL-C(mg/dl):", "", 10, TextField.DECIMAL);

smoker.append("No", null);
smoker.append("Yes", null);

sbp = new TextField("SBP(mg/hg):", "", 10, TextField.DECIMAL);

isBPMedication.append("No", null);
isBPMedication.append("Yes", null);

exit = new Command("Exit", Command.EXIT, 1);
ok = new Command("OK", Command.OK, 0);

try{
image = Image.createImage("/sandozLogo.jpg");
} catch (Exception e){ }
imageItem = new ImageItem("",image, ImageItem.LAYOUT_CENTER, "");

}

public void startApp() {
//add controls to the form
display = Display.getDisplay(this);

//Splash screen for 5 second
splashScreen.append(imageItem);
splashScreen.setCommandListener(this);
display.setCurrent(splashScreen);
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
}
//End splash screen after 5 seconds
form.append(age);
form.append(gender);
form.append(tc);
form.append(hdlc);
form.append(smoker);
form.append(sbp);
form.append(isBPMedication);
form.addCommand(exit);
form.addCommand(ok);
form.setCommandListener(this);
display.setCurrent(form);
}
public void pauseApp() {
}
public int validationForm() // Value is not null or empty and more than 0
{
valid=1;
if(age.getString() == null || age.getString().equals("") || Integer.parseInt(age.getString())<1 )
{
Alert check = new Alert("ERROR!!","Age must be provided...", null, AlertType.WARNING);
check.setTimeout(Alert.FOREVER);
display.setCurrent(check, form);
valid=0;
}
else if(tc.getString() == null || tc.getString().equals("") || Integer.parseInt(tc.getString())<1)
{
Alert check = new Alert("ERROR!!","Total Cholesterol (TC) must be provided..", null, AlertType.WARNING);
check.setTimeout(Alert.FOREVER);
display.setCurrent(check, form);
valid=0;
}
else if(hdlc.getString() == null || hdlc.getString().equals("") || Integer.parseInt(hdlc.getString())<1)
{
Alert check = new Alert("ERROR!!","High-density lipoprotein (HDL) cholesterol must be provided..", null, AlertType.WARNING);
check.setTimeout(Alert.FOREVER);
display.setCurrent(check, form);
valid=0;
}
else if(sbp.getString() == null || sbp.getString().equals("") || Integer.parseInt(sbp.getString())<1)
{
Alert check = new Alert("ERROR!!","Systolic BP (SBP) must be provided..", null, AlertType.WARNING);
check.setTimeout(Alert.FOREVER);
display.setCurrent(check, form);
valid=0;
}

return valid;
}
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}

//Get result for corresponding data provided
public int result()
{
riskPercentage=0;
result=0;
//========================================MALE=====================================================
if(gender.getSelectedIndex()==0) //male
{
//Calculation for age-male
if(Integer.parseInt(age.getString())<=34)
result+=-9;
else if(Integer.parseInt(age.getString())>=35 && Integer.parseInt(age.getString())<=39)
result+=-4;
else if(Integer.parseInt(age.getString())>=40 && Integer.parseInt(age.getString())<=44)
result+=0;
else if(Integer.parseInt(age.getString())>=45 && Integer.parseInt(age.getString())<=49)
result+=3;
else if(Integer.parseInt(age.getString())>=50 && Integer.parseInt(age.getString())<=54)
result+=6;
else if(Integer.parseInt(age.getString())>=55 && Integer.parseInt(age.getString())<=59)
result+=8;
else if(Integer.parseInt(age.getString())>=60 && Integer.parseInt(age.getString())<=64)
result+=10;
else if(Integer.parseInt(age.getString())>=65 && Integer.parseInt(age.getString())<=69)
result+=11;
else if(Integer.parseInt(age.getString())>=70 && Integer.parseInt(age.getString())<=74)
result+=12;
else if(Integer.parseInt(age.getString())>=75)
result+=13;

//Calculation for smoker-male
if(smoker.getSelectedIndex()==1) //yes=1 and No=0
{
if(Integer.parseInt(age.getString())<=39)
result+=8;
else if(Integer.parseInt(age.getString())>=40 && Integer.parseInt(age.getString())<=49)
result+=5;
else if(Integer.parseInt(age.getString())>=50 && Integer.parseInt(age.getString())<=59)
result+=3;
else if(Integer.parseInt(age.getString())>=60)
result+=1;
}

//Systolic BP (mmhg)-SBP calculation -male
if(Integer.parseInt(sbp.getString())<120)
{
if(isBPMedication.getSelectedIndex()==0) //No
result+=0;
else if(isBPMedication.getSelectedIndex() == 1) //No
result+=0;
}
else if(Integer.parseInt(sbp.getString())>=120 && Integer.parseInt(sbp.getString())<=129)
{
if(isBPMedication.getSelectedIndex()==0) //No
result+=0;
else if(isBPMedication.getSelectedIndex() == 1) //No
result+=1;
}
else if(Integer.parseInt(sbp.getString())>=130 && Integer.parseInt(sbp.getString())<=139)
{
if(isBPMedication.getSelectedIndex()==0) //No
result+=1;
else if(isBPMedication.getSelectedIndex() == 1) //No
result+=2;
}
else if(Integer.parseInt(sbp.getString())>=140 && Integer.parseInt(sbp.getString())<=159)
{
if(isBPMedication.getSelectedIndex()==0) //No
result+=1;
else if(isBPMedication.getSelectedIndex() == 1) //No
result+=2;
}
else if(Integer.parseInt(sbp.getString())>=160)
{
if(isBPMedication.getSelectedIndex()==0) //No
result+=2;
else if(isBPMedication.getSelectedIndex() == 1) //No
result+=3;
}


//HDL-C calculation -male
if(Integer.parseInt(hdlc.getString())<40)
{
result+=2;
}
else if(Integer.parseInt(hdlc.getString())>=40 && Integer.parseInt(hdlc.getString())<=49)
{
result+=1;
}
else if(Integer.parseInt(hdlc.getString())>=50 && Integer.parseInt(hdlc.getString())<=59)
{
result+=0;
}
else if(Integer.parseInt(hdlc.getString())>=60)
{
result+=-1;
}

//Total Cholesterol TC -male
if(Integer.parseInt(tc.getString())<160)
{
if(Integer.parseInt(age.getString())<=39)
result+=0;
else if(Integer.parseInt(age.getString())>=40 && Integer.parseInt(age.getString())<=49)
result+=0;
else if(Integer.parseInt(age.getString())>=50 && Integer.parseInt(age.getString())<=59)
result+=0;
else if(Integer.parseInt(age.getString())>=60 && Integer.parseInt(age.getString())<=69)
result+=0;
else if(Integer.parseInt(age.getString())>=70)
result+=0;
}
else if(Integer.parseInt(tc.getString())>=160 && Integer.parseInt(tc.getString())<=199)
{
if(Integer.parseInt(age.getString())<=39)
result+=4;
else if(Integer.parseInt(age.getString())>=40 && Integer.parseInt(age.getString())<=49)
result+=3;
else if(Integer.parseInt(age.getString())>=50 && Integer.parseInt(age.getString())<=59)
result+=2;
else if(Integer.parseInt(age.getString())>=60 && Integer.parseInt(age.getString())<=69)
result+=1;
else if(Integer.parseInt(age.getString())>=70)
result+=0;
}
else if(Integer.parseInt(tc.getString())>=200 && Integer.parseInt(tc.getString())<=239)
{
if(Integer.parseInt(age.getString())<=39)
result+=7;
else if(Integer.parseInt(age.getString())>=40 && Integer.parseInt(age.getString())<=49)
result+=5;
else if(Integer.parseInt(age.getString())>=50 && Integer.parseInt(age.getString())<=59)
result+=3;
else if(Integer.parseInt(age.getString())>=60 && Integer.parseInt(age.getString())<=69)
result+=1;
else if(Integer.parseInt(age.getString())>=70)
result+=0;
}
else if(Integer.parseInt(tc.getString())>=240 && Integer.parseInt(tc.getString())<=279)
{
if(Integer.parseInt(age.getString())<=39)
result+=9;
else if(Integer.parseInt(age.getString())>=40 && Integer.parseInt(age.getString())<=49)
result+=6;
else if(Integer.parseInt(age.getString())>=50 && Integer.parseInt(age.getString())<=59)
result+=4;
else if(Integer.parseInt(age.getString())>=60 && Integer.parseInt(age.getString())<=69)
result+=2;
else if(Integer.parseInt(age.getString())>=70)
result+=1;
}
else if(Integer.parseInt(tc.getString())>=280)
{
if(Integer.parseInt(age.getString())<=39)
result+=11;
else if(Integer.parseInt(age.getString())>=40 && Integer.parseInt(age.getString())<=49)
result+=8;
else if(Integer.parseInt(age.getString())>=50 && Integer.parseInt(age.getString())<=59)
result+=5;
else if(Integer.parseInt(age.getString())>=60 && Integer.parseInt(age.getString())<=69)
result+=3;
else if(Integer.parseInt(age.getString())>=70)
result+=1;
}

//Cardiac Risk calculation of male percentage
if(result<0)
riskPercentage=0; //less than 1
else if(result==0)
riskPercentage=1;
else if(result==1)
riskPercentage=1;
else if(result==2)
riskPercentage=1;
else if(result==3)
riskPercentage=1;
else if(result==4)
riskPercentage=1;
else if(result==5)
riskPercentage=2;
else if(result==6)
riskPercentage=2;
else if(result==7)
riskPercentage=3;
else if(result==8)
riskPercentage=4;
else if(result==9)
riskPercentage=5;
else if(result==10)
riskPercentage=6;
else if(result==11)
riskPercentage=8;
else if(result==12)
riskPercentage=10;
else if(result==13)
riskPercentage=12;
else if(result==14)
riskPercentage=16;
else if(result==15)
riskPercentage=20;
else if(result==16)
riskPercentage=25;
else if(result>=17)
riskPercentage=30; //More than 30

}
//========================================FEMALE=====================================================
else if(gender.getSelectedIndex() == 1) //female
{
//Calculation for age - female
if(Integer.parseInt(age.getString())<=34)
result+=-7;
else if(Integer.parseInt(age.getString())>=35 && Integer.parseInt(age.getString())<=39)
result+=-3;
else if(Integer.parseInt(age.getString())>=40 && Integer.parseInt(age.getString())<=44)
result+=0;
else if(Integer.parseInt(age.getString())>=45 && Integer.parseInt(age.getString())<=49)
result+=3;
else if(Integer.parseInt(age.getString())>=50 && Integer.parseInt(age.getString())<=54)
result+=6;
else if(Integer.parseInt(age.getString())>=55 && Integer.parseInt(age.getString())<=59)
result+=8;
else if(Integer.parseInt(age.getString())>=60 && Integer.parseInt(age.getString())<=64)
result+=10;
else if(Integer.parseInt(age.getString())>=65 && Integer.parseInt(age.getString())<=69)
result+=12;
else if(Integer.parseInt(age.getString())>=70 && Integer.parseInt(age.getString())<=74)
result+=14;
else if(Integer.parseInt(age.getString())>=75)
result+=16;

//Calculation for smoker -female
if(smoker.getSelectedIndex()==1) //yes=1 and No=0
{
if(Integer.parseInt(age.getString())<=39)
result+=9;
else if(Integer.parseInt(age.getString())>=40 && Integer.parseInt(age.getString())<=49)
result+=7;
else if(Integer.parseInt(age.getString())>=50 && Integer.parseInt(age.getString())<=59)
result+=4;
else if(Integer.parseInt(age.getString())>=60 && Integer.parseInt(age.getString())<=69)
result+=2;
else if(Integer.parseInt(age.getString())>=70)
result+=1;
}

//Systolic BP (mmhg)-SBP calculation -female
if(Integer.parseInt(sbp.getString())<120)
{
if(isBPMedication.getSelectedIndex()==0) //No
result+=0;
else if(isBPMedication.getSelectedIndex() == 1) //No
result+=0;
}
else if(Integer.parseInt(sbp.getString())>=120 && Integer.parseInt(sbp.getString())<=129)
{
if(isBPMedication.getSelectedIndex()==0) //No
result+=1;
else if(isBPMedication.getSelectedIndex() == 1) //No
result+=3;
}
else if(Integer.parseInt(sbp.getString())>=130 && Integer.parseInt(sbp.getString())<=139)
{
if(isBPMedication.getSelectedIndex()==0) //No
result+=2;
else if(isBPMedication.getSelectedIndex() == 1) //No
result+=4;
}
else if(Integer.parseInt(sbp.getString())>=140 && Integer.parseInt(sbp.getString())<=159)
{
if(isBPMedication.getSelectedIndex()==0) //No
result+=3;
else if(isBPMedication.getSelectedIndex() == 1) //No
result+=5;
}
else if(Integer.parseInt(sbp.getString())>=160)
{
if(isBPMedication.getSelectedIndex()==0) //No
result+=4;
else if(isBPMedication.getSelectedIndex() == 1) //No
result+=6;
}

//HDL-C calculation -female
if(Integer.parseInt(hdlc.getString())<40)
{
result+=2;
}
else if(Integer.parseInt(hdlc.getString())>=40 && Integer.parseInt(hdlc.getString())<=49)
{
result+=1;
}
else if(Integer.parseInt(hdlc.getString())>=50 && Integer.parseInt(hdlc.getString())<=59)
{
result+=0;
}
else if(Integer.parseInt(hdlc.getString())>=60)
{
result+=-1;
}


//Total Cholesterol TC -female
if(Integer.parseInt(tc.getString())<160)
{
if(Integer.parseInt(age.getString())<=39)
result+=0;
else if(Integer.parseInt(age.getString())>=40 && Integer.parseInt(age.getString())<=49)
result+=0;
else if(Integer.parseInt(age.getString())>=50 && Integer.parseInt(age.getString())<=59)
result+=0;
else if(Integer.parseInt(age.getString())>=60 && Integer.parseInt(age.getString())<=69)
result+=0;
else if(Integer.parseInt(age.getString())>=70)
result+=0;
}
else if(Integer.parseInt(tc.getString())>=160 && Integer.parseInt(tc.getString())<=199)
{
if(Integer.parseInt(age.getString())<=39)
result+=4;
else if(Integer.parseInt(age.getString())>=40 && Integer.parseInt(age.getString())<=49)
result+=3;
else if(Integer.parseInt(age.getString())>=50 && Integer.parseInt(age.getString())<=59)
result+=2;
else if(Integer.parseInt(age.getString())>=60 && Integer.parseInt(age.getString())<=69)
result+=1;
else if(Integer.parseInt(age.getString())>=70)
result+=1;
}
else if(Integer.parseInt(tc.getString())>=200 && Integer.parseInt(tc.getString())<=239)
{
if(Integer.parseInt(age.getString())<=39)
result+=8;
else if(Integer.parseInt(age.getString())>=40 && Integer.parseInt(age.getString())<=49)
result+=6;
else if(Integer.parseInt(age.getString())>=50 && Integer.parseInt(age.getString())<=59)
result+=4;
else if(Integer.parseInt(age.getString())>=60 && Integer.parseInt(age.getString())<=69)
result+=2;
else if(Integer.parseInt(age.getString())>=70)
result+=1;
}
else if(Integer.parseInt(tc.getString())>=240 && Integer.parseInt(tc.getString())<=279)
{
if(Integer.parseInt(age.getString())<=39)
result+=11;
else if(Integer.parseInt(age.getString())>=40 && Integer.parseInt(age.getString())<=49)
result+=8;
else if(Integer.parseInt(age.getString())>=50 && Integer.parseInt(age.getString())<=59)
result+=5;
else if(Integer.parseInt(age.getString())>=60 && Integer.parseInt(age.getString())<=69)
result+=3;
else if(Integer.parseInt(age.getString())>=70)
result+=2;
}
else if(Integer.parseInt(tc.getString())>=280)
{
if(Integer.parseInt(age.getString())<=39)
result+=13;
else if(Integer.parseInt(age.getString())>=40 && Integer.parseInt(age.getString())<=49)
result+=10;
else if(Integer.parseInt(age.getString())>=50 && Integer.parseInt(age.getString())<=59)
result+=7;
else if(Integer.parseInt(age.getString())>=60 && Integer.parseInt(age.getString())<=69)
result+=4;
else if(Integer.parseInt(age.getString())>=70)
result+=2;
}

//Cardiac Risk calculation of female percentage
if(result<9)
riskPercentage=0; //less than 1
else if(result==9)
riskPercentage=1;
else if(result==10)
riskPercentage=1;
else if(result==11)
riskPercentage=1;
else if(result==12)
riskPercentage=1;
else if(result==13)
riskPercentage=1;
else if(result==14)
riskPercentage=2;
else if(result==15)
riskPercentage=3;
else if(result==16)
riskPercentage=4;
else if(result==17)
riskPercentage=5;
else if(result==18)
riskPercentage=6;
else if(result==19)
riskPercentage=8;
else if(result==20)
riskPercentage=11;
else if(result==21)
riskPercentage=14;
else if(result==22)
riskPercentage=17;
else if(result==23)
riskPercentage=22;
else if(result==24)
riskPercentage=27;
else if(result>=25)
riskPercentage=30; //More than 30

}
return riskPercentage;
}

public void commandAction(Command c, Displayable d) {
//set commad execution
if(c == exit) {
destroyApp(false);
}
else if(c==ok)
{
if(validationForm()>0)
{
output=0;
output=result();
if(output < 1)
{
Alert calculation = new Alert("Result...","10 Year Risk of hard CHD Less Than 1 %", null, AlertType.INFO);
calculation.setTimeout(5000);
//calculation.setTimeout(Alert.FOREVER);
display.setCurrent(calculation, form);
}
else if(output >= 30)
{
Alert calculation = new Alert("Result...","10 Year Risk of hard CHD More Than "+output+" %", null, AlertType.INFO);
calculation.setTimeout(5000);
//calculation.setTimeout(Alert.FOREVER);
display.setCurrent(calculation, form);
}
else
{
Alert calculation = new Alert("Result...","10 Year Risk of hard CHD is "+output+" %", null, AlertType.INFO);
calculation.setTimeout(5000);
//calculation.setTimeout(Alert.FOREVER);
display.setCurrent(calculation, form);
}
}
}
}
}

04 July, 2011

Export Data from GridView to Excel in ASP.NET using C#

/*If the GridView is not under a form tag which run at server*/

private void ExportGridView()

{

Response.Clear();

Response.AddHeader("content-disposition", "attachment;filename= Result.xls");

Response.Charset = "";

Response.ContentType = "application/vnd.xls";

StringWriter stringWrite = new StringWriter();

HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

HtmlForm frm = new HtmlForm();

GridView1.Parent.Controls.Add(frm);

frm.Attributes["runat"] = "server";

frm.Controls.Add(GridView1);

frm.RenderControl(htmlWrite);

Response.Write(stringWrite);

Response.End();

}

/*If the GridView is under a form tag which run at server*/

private void ExportGridView()

{

Response.Clear();

Response.AddHeader("content-disposition", "attachment;filename= Result.xls");

Response.Charset = "";

Response.ContentType = "application/vnd.xls";

StringWriter stringWrite = new StringWriter();

HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

GridView1. RenderControl(htmlWrite);

Response.Write(stringWrite);

Response.End();

}