PROGRAMMER DESK

June 16, 2009

Inheritance

Inheritance

Written by – Vinay Hatwal

Dt. 16-Jun-2009

                                                                               

Inheritance is the OOPs concept in which new classes form from the existing classes i.e. using the class functionality in the new classes. Inheritance was first introduced in 1967 for Simula, a language which was used for simulation so the name is Simula.

Inheritance is intended to help reuse existing code with little or no modification. Inheritance is also sometimes called generalization, because the is-a relationships represent a hierarchy between classes of objects.

For Example, A “vehicle” is the generalization of “Car”, “Scooter”, “Bus” etc and the “Car”, “Scooter”, ”Bus” are the specialization of the “Vehicle”. Because the “Car” is a Vehicle so “Car” naturally inherits properties common to the entire vehicle like Color, No of Wheels, and EnginPower etc.

Following example show the inheritance in action. Shape is the Base Class and Square , Rectangle amd Circle are the classes derived from Shape Class and inherits all the functionality of the Shape class the shows the specialisation of the Shape Class.

Inheritance

Inheritance

Inheritance in Action

—————————————————————

VB.NET

—————————————————————

Public Class BaseClass

 

End Class

 

 

Public Class DerivedClass

    Inherits BaseClass

 

End Class

—————————————————————

 

—————————————————————

C#.NET

—————————————————————

public class BaseClass

{

}

 

public class DerivedClass : BaseClass

{

}

 

—————————————————————

 

 

 

Above DerivedClass Will contain all the inheritable funtionality of the BaseClass. Inheritane can be used in

 

VB.NET – Inherits

C#.NET – :

 

 

 

Access Specifires

 

Functionality VB.NET C#.NET
Gives variable public access which means that there is no restriction on their accessibility Public public
Gives variable private access which means that they are accessible only within their declaration content Private private
Protected access gives a variable accessibility within their own class or a class derived from that class Protected protected
Gives variable friend access which means that they are accessible within the program that contains their declaration Friend internal
Gives a variable both protected and friend access Protected Friend protected internal
Makes a variable static which means that the variable will hold the value even the procedure in which they are declared ends Static static
Declares a variable that can be shared across many instances and which is not associated with a specific instance of a class or structure Shared static
Makes a variable only to be read and cannot be written ReadOnly -

 

 

Keywords used in Inheritance in VB.NET/C#

 

1)      MustInherit, MustOverride /abstract

2)      Overridable/virtual

3)      Overrides/override

4)      NonInheritable/sealed

5)      Shadows/New

 

Concepts Regarding Interitance

1)      Abstraction

Abstraction is “the process of identifying common patterns that have systematic variations; an abstraction represents the common pattern and provides a means for specifying which variation to use” (Richard Gabriel).

In Abstraction we will look only on the keywords

a)      MustInherit, MustOverride /abstract

 

Abstract Classes or MustInherit class can not me instantiated. The can only be inherited in the derived class.

For Example –

 

—————————————————————

VB.NET

—————————————————————

 

Public MustInherit Class Base

    Public Sub NormalMethod()

    End Sub

    Public MustOverride Sub MustOverridableMethod()

End Class

 

 

Public Class Derived

    Inherits Base

    Public Overrides Sub MustOverridableMethod()

 

    End Sub

End Class

 

 

—————————————————————

 

 

—————————————————————

C#.NET

—————————————————————

 

public abstract class Base

{

        public void NormalMethod()

        {

        }

        public abstract void MustOverridableMethod();

}

   

  public class Derived : Base

  {

 

      public override void MustOverridableMethod()

              {

              throw new NotImplementedException();

      }

}

 

—————————————————————

 

 

In the above example if you are declaring the method as MustOverride/ abstract then u have to give definition of that method in the derived class. But if you are defining the method in the MustInherit/Abstract class then you may or may not define this method in the derived class.

 

 

 

b)      Overridable/virtual and Overrides/override

 

Overridable/virtual is used to polimorphically declare the base class method. A non overridable/not virtual method can not me polymorfically declared in the base class because it will hide the base class method in the derived class (Refer to Shadowing).

When we declare a Overridable/virtual method, it must contain a method body. Other wise the compiler will generate an error. Remember that, since Overridable/virtual methods are used for achieving polymorphism and since polymorphism works only with objects, it not possible to declare a static method as virtual in C#. Similarly the private methods are also not possible to declare virtual, since they can’t override inside a derived class.

 

For Example –
—————————————————————

VB.NET

—————————————————————

 

Public Class PolyBase

    Public Overridable Function GetName() As String

        Return “Base Polymorphic Class”

    End Function

End Class

 

Public Class PolyDerived

    Inherits PolyBase

    Public Overrides Function GetName() As String

        Return “Derived Polymorphic Class”

    End Function

End Class

 

—————————————————————

 

 

—————————————————————

C#.NET

—————————————————————

 

public class PolyBase

    {

        public virtual string GetName()

        {

            return “Base Polymorphic Class”;

        }

    }

 

    public class PolyDerived : PolyBase

    {

        public override string GetName()

        {

            return “Derived Polymorphic Class”;

        }

    }

—————————————————————

 

 

2)      Sealed Classes –

 

Sealed Class can be instanciated but can not be inherited in another class .In VB.Net NotInheritable keyword is used to declare a class Seald and In C#.Net it is declared by sealed.

 

—————————————————————

VB.NET

—————————————————————

 

Public NotInheritable Class NotInheritableClass

    Public Function Fun1() As String

        Return “My class can not be inherited”

    End Function

End Class

—————————————————————

 

 

—————————————————————

C#.NET

—————————————————————

 

sealed class NonInheritableClass

       {

        public string Fun1()

        {

            return “this class can not be inherited”;

        }

}

—————————————————————

 

 

 

 

3)      Shadowing

In .Net it is possible to declare the member of the base class with the same name in the derived class. In this class we are actully hiding the base class member in the derived class , if u do so then .Net compiler will show a warning.

Consider the following example-

 

—————————————————————

VB.NET

—————————————————————

sh

—————————————————————

 

 

 

—————————————————————

C#.NET

—————————————————————

ssss

—————————————————————

 

 

See the compiler warning closely.

In VB.Net it is clearly advising to use the Shadows with the new Fun1() to hide the base class functionality. Here the correct code is -

—————————————————————

VB.NET

—————————————————————

 

Public Class Base

    Private x As Integer

    Private y As Integer

    Public Function Fun1() As Integer

        Return x + y

    End Function

End Class

 

 

Public Class Derived

    Inherits Base

    Public Shadows Function Fun1() As Integer

        Return 10

    End Function

End Class

—————————————————————

 

Shadows keyword hides the base class functionality and warning too.

 

And in the C# it is advising to use the new keyword to hide the base class method. Here the correct code is-

 

—————————————————————

C#.NET

—————————————————————

 

class Base

    {

        private  int x = 10;

        private int y = 20;

        public int Fun1()

        {

            return x + y;

        }

    }

   

    class Derived : Base

    {

        public new int Fun1()

        {

            return 10;

        }

    }

 

—————————————————————

 

__________________________________________________________________________

 

April 17, 2009

New Features in Microsoft VS 2010

Filed under: VS-2010 — vinayhatwal @ 8:31 am
Tags: , ,

New Features in Microsoft VS 2010

 

 

Cloud Development

With Windows Azure Tools for Microsoft Visual Studio, developers can build, debug and deploy services and applications for Azure, the new cloud environment Microsoft announced in October 2008.

 

 

Web Development

In Visual Studio 2010, Microsoft is continuing their investment in great web development tools. Visual Studio 2010 enhancements for web developers include:

·         A high-performance and standards-compliant JavaScript, IntelliSense® engine

·         ‘One Click Deployment’ for quickly and easily publishing a website’s files and configuration settings from the development machines to the final deployed site

·         Full support for Silverlight for developers wishing to build cutting-edge, rich internet applications.

 

 

 

 

Democratising Application Lifecycle Management

Microsoft Visual Studio Team System 2010 will deliver new capabilities that embrace the needs of the users in the lifecycle – from architects to developers, from project managers to testers. Among the great new functionality in Visual Studio Team System 2010:

·         Discover and identify existing code assets and architecture with the new Architecture Explorer

·         Design and share multiple diagram types, including use case, activity and sequence diagrams

·         Improve testing efforts with tooling for better documentation of test scenarios and more thorough collection of test data

·         Easily identify and run only the tests affected by a code change with the new Test Impact View

·         Enhanced version control capabilities including gated check-in, branch visualisation and build workflow.

 

 

 

 

Inspiring Developer Delight

Since the first release of Visual Studio, Microsoft has made application development more productive, efficient, flexible and profitable to the developers and companies that use it. Visual Studio 2010 continues to deliver on the core developer experience by significantly improving the day-to-day process for development teams:

·         Understand existing (and write new) code

·         Intuitive web development from the back-end to the end result

·         Wrangle disparate C++ code into one arena

·         Build new Windows 7 applications or upgrade existing applications

·         Enable Office tools to make your solutions more flexible and productive for specific needs.

 

 

Resource –

 

http://download.microsoft.com/download/C/0/9/C0965791-049B-4200-9008-F07A783026F6/VisualStudio2010_ProductOverview.pdf

.Net Framework 4.0

Filed under: .Net Framework 4.0 — vinayhatwal @ 7:51 am
Tags: , , , ,

.Net Framework 4.0

 Every year the industry develops new technology and new trends. Now Microsoft is again come to provide next version of .net framework i.e. .Net Framework 4.0. As a result MS Visual Studio 2010 is just around the corner with the new innovation in application architecture, development, and deployment. So in this article I am describing some new features coming in the .Net Framework 4.0. Before describing new features of .Net Framework 4.0, I am giving a summary of some of the main functionality in each .net version. 

 

 

.NET Framework 4.0

(The Future Release)

PLINQ

TPL

.NET Framework 3.5

LINQ

ADO.NET Entity Framework

.NET Framework 3.0

WPF

WCF

WF

Card Space

.NET Framework 2.0

WinForms

ASP.NET

ADO.NET

Base Class Library

CLR

 

So you have just seen the major change in each version on .Net Framework. Above figure defines the feature stack of the .Net Framework.  

Following are new features provided by .NET Framework 4.0 – 

  • New Languages 

.NET 4.0 will include IronPython, IronRuby, and F#, among others. The three named languages have been available in some form for a few years now, but it appears that with .NET 4.0 they become “official” in the same way as C#, Visual Basic .NET. Both IronPython and IronRuby leverage the Dynamic Language Runtime (DLR), a subsystem that supports dynamic languages on .NET. The DLR has been around for a couple of years now, but with .NET 4.0 becomes an integral part of the .NET runtime. 

In order to support the new languages, and to ensure language interoperability, the CLR team did make some changes. Two additions are particularly interesting to me: BigInteger and Tuple. Because these features are in the base class libraries, all .NET languages can use them 

  • Threading improvements 

Framework 4.0 includes the Task Parallel Library (TPL), a library of objects that make it easier to write code that takes advantage of multiple cores. Not only do TPL functions relieve you of the tedium involved with starting and managing threads, they also help you to structure your code to make the most of the computing resources available. 

During development and use of the TPL, the CLR team found a number of areas in which the .NET thread pool (the subsystem that the TPL depends on) was less than optimum. They have since improved the thread pool, giving a performance boost not only TPL programs, but to all programs that make use of .NET threading services.  

  • Garbage Collector Improvements 

All in all, the .NET garbage collector is considered a good thing. However, it does have some drawbacks. In particular, it can severely impact performance in some cases.

The server garbage collector in .NET 3.51 and earlier versions is optimized for higher throughput, but has to pause all threads when it does a full collection. The result is that processing comes to a halt whenever a full collection occurs. This can be very annoying. 

The pauses still occur in .NET 4.0, but the system will notify your program before a full collection starts, and notify it again when the garbage collector has finished with collection. In a multi-server environment, you can use this feature to direct traffic away from your server while it’s in the middle of a full collection. That helps with server farms, but doesn’t help with memory-intensive applications that are running on a single machine. 

The workstation garbage collector in 4.0 gets a new background collection feature, which results in fewer pauses and doesn’t require any changes to your code. Only very unusual circumstances will result in the long latency that you might have seen in versions 3.51 or earlier 

  • PLINQ 

.Net Framework 3.5 introduced new concept i.e. LINQ(Language Integrated Queries). Microsoft original motivation behind LINQ was to address the impedance mismatch between programming languages and database 

Microsoft LINQ defines a set of proprietary query operators that can be used to query, project and filter data in arrays, enumerable classes, XML (XLINQ), relational database, and third party data sources. While it allows any data source to be queried, it requires that the data be encapsulated as objects. So, if the data source does not natively store data as objects, the data must be mapped to the object domain. Queries written using the query operators are executed either by the LINQ query processing engine or, via an extension mechanism, handed over to LINQ providers which either implement a separate query processing engine or translate to a different format to be executed on a separate data store (such as on a database server as SQL queries (DLINQ)). The results of a query are returned as a collection of in-memory objects that can be enumerated using a standard iterator function such as C#’s foreach. 

Like all constructs in LINQ, PLINQ is based on extension methods, in this case the AsParallel method. Once you’ve built the expression tree representing the query, the AsParallel operation is added at the very end, which tells the “LINQ engine” to figure out parallel jobs and do all of the magic required to make the app benefit from multi-threaded execution. A conceptual example is shown below: 

var result = (from p in db.Products join pd in xml.ProductDescriptions on p.ID equals pd.ID where p.Price > 100 select new { p.Name, p.Price, pd.Description }).AsParallel(); 

April 10, 2009

Windows Services

Filed under: Windows Services — vinayhatwal @ 7:58 am
Tags: , , ,

Windows Services

By: Vinay Hatwal

Dated: Apr 10, 2009

Level: Beginner

 

The idea of using Windows services came into my mind when I was working on Finger Print Attendance System for Bajaj Capital Ltd. This system was going to be used by all the branches of the company. So I wanted to synchronize the attendance of the employees of each branch with our company’s ERP system. So that, I decided to develop windows services for the same purpose. There was one issue in real time synchronization of attendance with the Head Office. The issue was slow internet connection and no internet connectivity available all the time. So the solution was to send the attendance when internet is connected not on the time of attendance punching. So the solution was WINDOWS SERVICES.

In this article I will explain how to make Windows Services by using c#.net.

Windows services are long running executable file developed for running in background as long a windows is running. These executables run in the background and there is no any requirement for the user interaction. They run in the background so that there is no need to take graphical interface in the Windows Services. You can think about UNIX Daemon if u r familiar with the UNIX environment. On the Windows the same concept is Windows Services. Windows Services can be configured to run automatically when Windows is booted. They can also be configured to run on Local machine, single user account, and also on Network.

You can find windows services in your local machine on

Start-> Control Panel -> Administrative Tools -> Services

These services looks like this—

Windows Service Browser

Windows Service Browser

 

By using windows service you can use databases, text files, and all shareable resources with it etc.

To create Windows Services in .net (I am creating in .net 2.0)

Creating Windows Services

<!–[if !supportLists]–>1) <!–[endif]–>To create windows services, go to File menu and then select New Project, then select Windows Service. You will see the dialog box shown below. Name the project – MyWindowService.

12

2) After clicking on OK you will see the following. Change the name of the service from Service1.cs to MyService.cs.

2

3) Now go to in on the properties on the MyService and change the property Service Name to MyService.

 

 

4) Do right click on the MyService design view and select View Code option from the context menu. You can see two overrided methods in the window OnStart() and OnStop().

 

 

These are the members of the ServiceBase class and inheritted by the MyService Class. There are some more members also present in the ServiceBase class like OnContinue(), OnPause() etc. but I am just describing about these two only.

 

The idea of using windows service is only behind these to methods. Any work u want to perform on the sharable resources, you can write code for that in the OnStart() method. I have just put Beep () here. It will give the beep sound on starting the Window Service. And just 2 beep on Stoping it. You can see in the coding below.

3

<!–[if !supportLists]–>5) <!–[endif]–>to install this Windows Service on the local system you need to add installers in your Service. Just right click on the Service Design window and then select Add Installer.

<!–[if !supportLists]–>6) <!–[endif]–>Project Installer will automatically be added in your solution, name ProjectInstaller.sc. and you can also find two component in it

<!–[if !supportLists]–>a. <!–[endif]–>serviceProcessInstaller1

<!–[if !supportLists]–>b. <!–[endif]–>serviceInstaller1

 

 

<!–[if !supportLists]–>7) <!–[endif]–>You can now decide how your Windows Process will be display, you can set the account for your service on which it will be running, and you can give the Display Service Name, Description and the start type of the service like Automat, Manual, or Disabled. For doing all these you can follow these steps

<!–[if !supportLists]–>a. <!–[endif]–>Go to on the properties of serviceProcessInstaller1, and set Account property to Local System, so that it would be sharable to all users.

<!–[if !supportLists]–>b. <!–[endif]–>Now go to on the properties of serviceInstaller1, and ser Description as u like and set Display Name as u want to display in the Services Console, and now set StartType to Automatic so that the service can be run on the starting of the Windows operation system.

 

<!–[if !supportLists]–> 8) <!–[endif]–>After doing all the configuration just press F6 for building the solution. Now Your Window Service is ready to use.

 

<!–[if !supportLists]–>9) <!–[endif]–>Now for using it u have to install this service on your local machine. You can do this by using the instalUtill.exe utility provided by .net framework to install this service on your machine.

 

Now take the executable of this service and jus copy it into your system32 directory.

 

Go to your application path where your project is running, and go to the bin\debug directory then copy MyWindowServices.exe and paste it into syetem32.

 

 

Now go to on the Visual Studio 2005 Command Prompt and type the following for installing the newly developed Window Service–

 

C:\> installutil c:\windows\system32\ MyWindowServices.exe

4

To uninstall use –

 

C:\> installutil /u c:\windows\system32\ MyWindowServices.exe

 

 

You can see your service in the service console like

5

Now just do right click on it and the start. You will listen one beep on starting and two beep on stopping the Windows Service.

 

So friends. Enjoy the Window Services, hope your will learn by this article. Hope you will be enjoying after creation the windows service.

 

I am always waiting for your comments and suggestion so that I can improve my articles.

 

Again Coming Soon…………………….

 

 

 

Vinay Hatwal

August 13, 2008

Crystal Report With .Net

Filed under: Crystal Report With .Net — vinayhatwal @ 6:09 am

Crystal Report with C#.Net 2.0

 

Using Crystal Report is very easy task. Sometime we afraid to use crystal reports with the code of Vb.Net or C#.Net even when we have used crystal reports in the previous technologies like Visual Basic 6. Before writing this tutorial I found some of my friends unable to user crystal report and stuck out in small problems regarding Crystal Report. So I decided to write this tutorial for them and also for those people who are afraid with Crystal Reports and found some difficulties to use it. This tutorial may play a very important role to learn Crystal with Vb.Net/C#.Net for those are new to take crystal with .Net but have used crystal with some of the earlier technologies or who are new even to Crystal.

 

So Friends, Lets Have a look on the tools used in crystal reports with VB.Net/C#.Net.

 

1)      DataSet (System.Data.DataSet)

2)      Crystal Report

3)      CrystalReportViewer1 (CrystalDecisions.Windows.Forms.CrystalReportViewer)

4)      System.Data.SqlClient

 

Now Follow these Steps for the first stage to learn the crystal reports

 

Stage 1 Create Data Base Table (I ussed SqlServer2000)

 

1. Create These Basic Tables using SqlServer2000

 

Create Table DemoStudentMaster

(

            StudentId int primary key,

            StudentName varchar(15),

            StudentAddress varchar(50),

            StudentCity varchar(20),

            StudentMobile varchar(10)

)

 

Create Table StudentFeeDetails

(

            StudentId int references DemoStudentMaster(StudentId),

            SumittedFeeAmt int,

            ForMonth int,

            ForYear int

)

 

2. Insert Values in These Tables

 

DemoStudentMaster

insert into DemoStudentMaster values (1,’Vinay Hatwal’,'Nehru Place’,'New Delhi’,'9911884523′);

insert into DemoStudentMaster values (2,’Panjak Pundir’,'Nehru Place’,'New Delhi’,'7483434356′);

insert into DemoStudentMaster values (3,’Ashish C.’,'Nehru Place’,'New Delhi’,'7473949866′);

insert into DemoStudentMaster values (4,’Sandeep S.’,'Nehru Place’,'New Delhi’,'791198475′);

insert into DemoStudentMaster values (5,’Pradeep K.’,'Nehru Place’,'New Delhi’,'8911884523′);

 

StudentFeeDetails

 

insert into StudentFeeDetails values (1,1000,2,2008);

insert into StudentFeeDetails values (1,1000,3,2008);

insert into StudentFeeDetails values (1,1000,4,2008);

insert into StudentFeeDetails values (1,1000,5,2008);

insert into StudentFeeDetails values (1,1000,6,2008);

insert into StudentFeeDetails values (1,1000,7,2008);

 

 

insert into StudentFeeDetails values (2,4000,2,2008);

insert into StudentFeeDetails values (2,4000,3,2008);

insert into StudentFeeDetails values (2,4000,4,2008);

insert into StudentFeeDetails values (2,4000,5,2008);

insert into StudentFeeDetails values (2,4000,6,2008);

 

 

insert into StudentFeeDetails values (3,3000,2,2008);

insert into StudentFeeDetails values (3,3000,3,2008);

insert into StudentFeeDetails values (3,3000,4,2008);

 

 

insert into StudentFeeDetails values (5,10000,2,2008);

insert into StudentFeeDetails values (5,10000,3,2008);

 

 

Now Your Tables Are Ready To Use in Crystal Report.

 

Stage 2 – Creating Sample Application in .Net

 

  1. Using C#.Net 2.0

 

 

 

a)      Open a new Project with C# names MyDemoCrystalPrj.

 

b)      Open Solution Explorer , Right Click on MyDemoCrystalPrj then click on Add and then click on New Items.

 

c)      Now Select The DataSet. Renamed it as SampleDataSet , Click on Add Button. Now The SampleDataSet.xsd tab will display.

 

 

   d) Right click on the middle of the page and then click on Add and then DataTable, After Clicking on it a Data Table will Appear on screen.

 

 

e)      Now Right Click on DataTable1 and select Rename . Rename id as StudentMasterTable.

f)      After it Right Click on The table and Select Add then Column. Make The Following Column in it.

a.       StudentID

b.      StudentName

c.       StudentAddress

d.      StuentMob

 

g)      Now Again Open Solution Explorer , Right Click on MyDemoCrystalPrj then click on Add and then click on New Items then select Crystal Report. Rename it as MasterCrystalReport.rpt(All the related references will be automatically added in the references)

h)      After Adding Crystal In Project Following Dialog Box Will appear on the screen

 

 

 

 

i)      Select option As a Blank Report and then press OK. Crystal Report will appear and looks like

 

 

j)      Now right click on DataBase Fields in the Field Explorer , Select Database Expert. After selecting it following screen will appear.

      Select Project Data > ADO.NET DataSets > MyDemoCrystalPrj.SampleDataSet

then add it and then click on OK

 

k)      Now Field Explorer will look like

 

l)      Drag then Fields of StudentMasterTable in the detail section of the Crystal Report. You Can also take the heading on the Report Header Section .Right Client On Report Header Section , Select Insert then Select Text Object. Give the Text as Student Detail and format it according to your need. After Inserting all the things your report will look like

 

 

 

m)      Now Open Form1 and Take CrystalReportViewer Form the Crystal Report Strip in the Toolbox.

n)      Now Go To the Coding Window of  Form1 and write the following code.

 

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Data.SqlClient;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

 

namespace MyDemoCrystalPrj

{

    public partial class Form1 : Form

    {

        SqlConnection con;

        DataSet ds;

        public Form1()

        {

            SqlDataAdapter adp;

            con = new SqlConnection(“Server=.;Database=master;Integrated Security=true”);

            ds = new DataSet();

            adp = new SqlDataAdapter(“select StudentId,StudentName,StudentAddress,StudentCity,StudentMobile from DemoStudentMaster”, con);

            adp.Fill(ds, “StudentTable”);

            InitializeComponent();

        }

 

        private void Form1_Load(object sender, EventArgs e)

        {

            MasterCrystalReport cr = new MasterCrystalReport();

            cr.SetDataSource(ds.Tables["StudentTable"].DefaultView);

            crystalReportViewer1.ReportSource = cr;

            crystalReportViewer1.Show();

        }

    }

}

 

o)      Finally Run The Project. Your Crystal Report Will Look Like

 

Note – If you find the helps you for learning the crystal report as a beginner the please write comment on this tutorial or just writ few words on vinayhatwal@gmail.com. I will be back by taking some new tutorial on new technologies soon.

  

July 25, 2008

ADO.NET INTERVIEW QUESTIONS

Filed under: .Net, Ado.Net — vinayhatwal @ 5:06 am
Tags: ,

 

To test a Web Service you must create a windows application or web application to consume this service? It is True/False?
FALSEHow many classes can a single.NET DLL contain?
Answer1:
As many

Answer2:
One or more

What are good ADO.NET object(s) to replace the ADO Recordset object?
The differences includes
In ADO, the in-memory representation of data is the recordset.
In ADO.net, it is the dataset
A recordset looks like a single table in ADO
In contrast, a dataset is a collection of one or more tables in ADO.net
ADO is designed primarily for connected access
ADO.net the disconnected access to the database is used
In ADO you communicate with the database by making calls to an OLE DB provider.
In ADO.NET you communicate with the database through a data adapter (an OleDbDataAdapter, SqlDataAdapter, OdbcDataAdapter, or OracleDataAdapter object), which makes calls to an OLE DB provider or the APIs provided by the underlying data source.
In ADO you cant update the database from the recordset. ADO.NET the data adapter allows you to control how the changes to the dataset are transmitted to the database.

On order to get assembly info which namespace we should import?
System.Reflection Namespace

How do you declare a static variable and what is its lifetime? Give an example.
Answer1
static int Myint–The life time is during the entire application.
br&gt; Answer2
The static modifier is used to declare a static member, which belongs to the type itself rather than to a specific object. The static modifier can be used with fields, methods, properties, operators, events and constructors, but cannot be used with indexers, destructors, or types. In C#, the static keyword indicates a class variable. In VB, the equivalent keyword is Shared. Its scoped to the class in which it occurs.

Example
a. Static int var //in c#.net
b. static void Time( ) //in c#.net

How do you get records number from 5 to 15 in a dataset of 100 records? Write code.
Answer1
DataSet ds1=new DataSet(); String strCon=”data source=IBM-6BC8A0DACEF;initial catalog=pubs;integrated security=SSPI;persist” +” security info=False;user
id=sa;workstation id=IBM-6BC8A0DACEF;packet size=4096?;
String strCom1=”SELECT * FROM employee”;
SqlDataAdapter sqlDa1=new SqlDataAdapter(strCom1,strCon);
ds1.Tables.Add(”employee”);
sqlDa1.Fill(ds1,40,50,ds1.Tables[”employee”].TableName);
DataGrid dg1.DataSource=ds1.Tables[”employee”].DefaultView;
dg1.DataBind();

Answer2
OleDbConnection1.Open()
OleDbDataAdapter1.Fill(DataSet21, 5, 15, “tab”)
This will fill the dataset with the records starting at 5 to 15
.NET Database interview questions

How do you call and execute a Stored Procedure in.NET? Give an example.
Answer1
ds1=new DataSet();
sqlCon1=new SqlConnection(connectionstring);
String strCom1=”byroyalty”;
sqlCom1=new SqlCommand(strCom1,sqlCon1);
sqlCom1.CommandType=CommandType.StoredProcedure;
sqlDa1=new SqlDataAdapter(sqlCom1);
SqlParameter myPar=new SqlParameter(”@percentage”,SqlDbType.Int);
sqlCom1.Parameters.Add (myPar);
myPar.Value=40;
sqlDa1.Fill(ds1);
dg1.DataSource=ds1;
dg1.DataBind();

Answer2
Yes
Dim cn as new OleDbConnection ( “Provider=Microsoft.Jet.OLEDB.4.0;”+ _
“Data Source=C:\Documents and Settings\User\My Documents\Visual Studio Projects\1209\db1.mdb”+ _
“User ID=Admin;”+ _
“Password=;”);
Dim cmd As New OleDbCommand(”Products”, cn)
cmd.CommandType = CommandType.StoredProcedure
Dim da As New OleDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds, “Products”)
DataGrid1.DataSource = ds.Tables(”Products”)

What is the maximum length of a varchar in SQL Server?
Answer1
VARCHAR[(n)]
Null-terminated Unicode character string of length n,
with a maximum of 255 characters. If n is not supplied, then 1 is assumed.

Answer2
8000

Answer3
The business logic is the aspx.cs or the aspx.vb where the code is being written. The presentation logic is done with .aspx extention.

How do you define an integer in SQL Server?
We define integer in Sql server as
var_name int

How do you separate business logic while creating an ASP.NET application?
There are two level of asp.net debugging
1. Page level debugging
For this we have to edit the page level debugging enable the trace to true in the line in the html format of the page.
%@ Page Language=”vb” trace=”true”AutoEventWireup=”false” Codebehind=”WebForm1.aspx.vb” Inherits=”WebApplication2.WebForm1?&gt;

2. You can enable the debugging in the application level for this
Edit the following trace value in web.config file
Enable trace enabled=true.

If there is a calendar control to be included in each page of your application, and and we do not intend to use the Microsoft-provided calendar control, how do you develop it? Do you copy and paste the code into each and every page of your application?

Create the Calendar User Control
The control we will create will contain a calendar control and a label which has the corresponding date and time written
Steps are:-

Creating a CalenderControl
1) To begin, open Visual Studio .NET and begin a new C# Windows Control Library.
2) You may name it whatever you like, for this sample the project name will be CalenderControl

Using the Calender Control in a Windows Application
It’s just like adding any other control like a button or a label.
1) First, create a new Windows Application project named: CustomControl.
2) Add a reference to the Calender Control DLL named: CalenderControl.dll.
3) Now you a can customize the Toolbox:
Right-Click the Toolbox&gt; .NET Framework Components&gt; Browse&gt; select the CalenderControl.dll.
4)The Calender Control is now added to the Toolbox and can be inserted in Windows Form as any other control. The control itself will take care of the date display

How can you deploy an asp.net application ?
You can deploy an ASP.NET Web application using any one of the following three deployment options.
a) Deployment using VS.NET installer
b) Using the Copy Project option in VS .NET
c) XCOPY Deployment

Explain similarities and differences between Java and.NET?
Comparing Java and .NET is comparing apples and oranges. Either the question needs to be to compare Java and C# or J2EE and .NET.

What are the XML files that are important in developing an ASP.NET application?
The XML file necessary for the for developing an asp.net application is Web.config

Specify the best ways to store variables so that we can access them in various pages of ASP.NET application?
Declare the variables in Global.aspx

How many objects are there in ASP?
Answer1
8 objects, they are request,response, server,application,session,file, dictionary, textstream.

Answer2
There are 6 objects in ASP.net
a) Server
b) Session
c) Application
d) ObjectContext
e) Response
f) Request

Which DLL file is needed to be registered for ASP?
The dll needed for the ASP.net is SYSTEM.WEB.dll

Is there any inbuilt paging (for example shoping cart, which will show next 10 records without refreshing) in ASP? How will you do pating?
Use DataGrid control which has in-built paging features for the purpose.

What does Server.MapPath do?
Answer1
srver.mappath() maps the path given in the argument to the server’s physical path.

Answer2
It returns the complete(absolute) path of the file used in parameter.

Answer3
It returns a string containing the physical path in the server’s file system that corresponds to the virtual or relative path specified by the Path argument.

Name atleast three methods of response object other than Redirect.
Answer1
a) Response.Clear( )
Clears the content of the current output stream.
b) Response.Close( )
Closes the network socket for the current response.
c) Response.End( )
Stops processing the current request and sends all buffered content to the client immediately.

Answer2
methods of Response is Redirect a. Transfer

Name atleast two methods of response object other than Transfer.
a) Response.ClearContent( )
Clears the content of the current output stream.
b) Response.ClearHeaders( )
Clears the HTTP headers from the current output stream.

What is State?
It is the property of the web forms.
ASP.NET provides four types of state:
Application state
Session state
Cookie state
View state.

Explain differences between ADO and DAO.
dao- can access only access database
ado- can access any databases

How many types of cookies are there?
2 types, persistant and impersistant.

How many types of cookies are there?
Answer1
Two type of cookeies.
a) single valued eg request.cookies(”UserName”).value=”Mahesh”
b)Multivalued cookies. These are used in the way collections are used.
e.g.
request.cookies(”CookiName”)(”UserName”)=”Mahesh”
request.cookies(”CookiName”)(”UserID”)=”ABC003?
rember no value method in multivalued cooki

Answer2
There are two types of cookies:
Session cookies
Persistent cookies

Tell few steps for optimizing (for speed and resource) ASP page/application.
Avoid mixing html code with asp code

Which command using Query Analyzer will give you the version of SQL Server and Operating System?
@@VERSION
Returns version, processor architecture, build date, and operating system for the current installation of SQL Server.

How to find the SQL server version from Query Analyser
Answer1
To determine which version of Microsoft SQL Server 2005 is running, connect to SQL Server 2005 by using SQL Server Management Studio, and then run the following Transact-SQL statement:
SELECT SERVERPROPERTY(’productversion’), SERVERPROPERTY (’productlevel’), SERVERPROPERTY (’edition’)
The results are:
• The product version (for example, “9.00.1399.06?)
. • The product level (for example, “RTM”).
• The edition (for example, “Enterprise Edition”).
For example, the result looks similar to:
9.00.1399.06 RTM Enterprise Edition

How to determine which version of SQL Server 2000 is running
To determine which version of SQL Server 2000 is running, connect to SQL Server 2000 by using Query Analyzer, and then run the following code:
SELECT SERVERPROPERTY(’productversion’), SERVERPROPERTY (’productlevel’), SERVERPROPERTY (’edition’)
The results are:
• The product version (for example, 8.00.534).
• The product level (for example, “RTM” or “SP2?).
• The edition (for example, “Standard Edition”). For example, the result looks similar to
:
8.00.534 RTM Standard Edition

Answer2
One can also use SELECT @@Version where the result would look like
Microsoft SQL Server 2005 – 9.00.1399.06 (Intel X86)
Oct 14 2005 00:33:37
Copyright (c) 1988-2005 Microsoft Corporation
Express Edition on Windows NT 5.1 (Build 2600: Service Pack 2)

Using query analyzer, name 3 ways you can get an accurate count of the number of records in a table.
Answer1.
a. Select count(*) from table1
b. SELECT object_name(id) ,rowcnt FROM sysindexes WHERE indid IN (1,0) AND OBJECTPROPERTY(id, ‘IsUserTable’) = 1
c. exec sp_table_validation @table = ‘authors’

Answer2.
SELECT count( * ) as totalrecords FROM employee
This will display total records under the name totalrecords in the table employee
use COUNT_BIG
Returns the number of items in a group.
@@ROWCOUNT
Returns the number of rows affected by the last statement.
Use this statement after an SQL select * statement, to retrieve the total number of rows in the table

 

 

 

To test a Web Service you must create a windows application or web application to consume this service? It is True/False?
FALSEHow many classes can a single.NET DLL contain?
Answer1:
As many

Answer2:
One or more

What are good ADO.NET object(s) to replace the ADO Recordset object?
The differences includes
In ADO, the in-memory representation of data is the recordset.
In ADO.net, it is the dataset
A recordset looks like a single table in ADO
In contrast, a dataset is a collection of one or more tables in ADO.net
ADO is designed primarily for connected access
ADO.net the disconnected access to the database is used
In ADO you communicate with the database by making calls to an OLE DB provider.
In ADO.NET you communicate with the database through a data adapter (an OleDbDataAdapter, SqlDataAdapter, OdbcDataAdapter, or OracleDataAdapter object), which makes calls to an OLE DB provider or the APIs provided by the underlying data source.
In ADO you cant update the database from the recordset. ADO.NET the data adapter allows you to control how the changes to the dataset are transmitted to the database.

On order to get assembly info which namespace we should import?
System.Reflection Namespace

How do you declare a static variable and what is its lifetime? Give an example.
Answer1
static int Myint–The life time is during the entire application.
br&gt; Answer2
The static modifier is used to declare a static member, which belongs to the type itself rather than to a specific object. The static modifier can be used with fields, methods, properties, operators, events and constructors, but cannot be used with indexers, destructors, or types. In C#, the static keyword indicates a class variable. In VB, the equivalent keyword is Shared. Its scoped to the class in which it occurs.

Example
a. Static int var //in c#.net
b. static void Time( ) //in c#.net

How do you get records number from 5 to 15 in a dataset of 100 records? Write code.
Answer1
DataSet ds1=new DataSet(); String strCon=”data source=IBM-6BC8A0DACEF;initial catalog=pubs;integrated security=SSPI;persist” +” security info=False;user
id=sa;workstation id=IBM-6BC8A0DACEF;packet size=4096?;
String strCom1=”SELECT * FROM employee”;
SqlDataAdapter sqlDa1=new SqlDataAdapter(strCom1,strCon);
ds1.Tables.Add(”employee”);
sqlDa1.Fill(ds1,40,50,ds1.Tables[”employee”].TableName);
DataGrid dg1.DataSource=ds1.Tables[”employee”].DefaultView;
dg1.DataBind();

Answer2
OleDbConnection1.Open()
OleDbDataAdapter1.Fill(DataSet21, 5, 15, “tab”)
This will fill the dataset with the records starting at 5 to 15
.NET Database interview questions

How do you call and execute a Stored Procedure in.NET? Give an example.
Answer1
ds1=new DataSet();
sqlCon1=new SqlConnection(connectionstring);
String strCom1=”byroyalty”;
sqlCom1=new SqlCommand(strCom1,sqlCon1);
sqlCom1.CommandType=CommandType.StoredProcedure;
sqlDa1=new SqlDataAdapter(sqlCom1);
SqlParameter myPar=new SqlParameter(”@percentage”,SqlDbType.Int);
sqlCom1.Parameters.Add (myPar);
myPar.Value=40;
sqlDa1.Fill(ds1);
dg1.DataSource=ds1;
dg1.DataBind();

Answer2
Yes
Dim cn as new OleDbConnection ( “Provider=Microsoft.Jet.OLEDB.4.0;”+ _
“Data Source=C:\Documents and Settings\User\My Documents\Visual Studio Projects\1209\db1.mdb”+ _
“User ID=Admin;”+ _
“Password=;”);
Dim cmd As New OleDbCommand(”Products”, cn)
cmd.CommandType = CommandType.StoredProcedure
Dim da As New OleDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds, “Products”)
DataGrid1.DataSource = ds.Tables(”Products”)

What is the maximum length of a varchar in SQL Server?
Answer1
VARCHAR[(n)]
Null-terminated Unicode character string of length n,
with a maximum of 255 characters. If n is not supplied, then 1 is assumed.

Answer2
8000

Answer3
The business logic is the aspx.cs or the aspx.vb where the code is being written. The presentation logic is done with .aspx extention.

How do you define an integer in SQL Server?
We define integer in Sql server as
var_name int

How do you separate business logic while creating an ASP.NET application?
There are two level of asp.net debugging
1. Page level debugging
For this we have to edit the page level debugging enable the trace to true in the line in the html format of the page.
%@ Page Language=”vb” trace=”true”AutoEventWireup=”false” Codebehind=”WebForm1.aspx.vb” Inherits=”WebApplication2.WebForm1?&gt;

2. You can enable the debugging in the application level for this
Edit the following trace value in web.config file
Enable trace enabled=true.

If there is a calendar control to be included in each page of your application, and and we do not intend to use the Microsoft-provided calendar control, how do you develop it? Do you copy and paste the code into each and every page of your application?

Create the Calendar User Control
The control we will create will contain a calendar control and a label which has the corresponding date and time written
Steps are:-

Creating a CalenderControl
1) To begin, open Visual Studio .NET and begin a new C# Windows Control Library.
2) You may name it whatever you like, for this sample the project name will be CalenderControl

Using the Calender Control in a Windows Application
It’s just like adding any other control like a button or a label.
1) First, create a new Windows Application project named: CustomControl.
2) Add a reference to the Calender Control DLL named: CalenderControl.dll.
3) Now you a can customize the Toolbox:
Right-Click the Toolbox&gt; .NET Framework Components&gt; Browse&gt; select the CalenderControl.dll.
4)The Calender Control is now added to the Toolbox and can be inserted in Windows Form as any other control. The control itself will take care of the date display

How can you deploy an asp.net application ?
You can deploy an ASP.NET Web application using any one of the following three deployment options.
a) Deployment using VS.NET installer
b) Using the Copy Project option in VS .NET
c) XCOPY Deployment

Explain similarities and differences between Java and.NET?
Comparing Java and .NET is comparing apples and oranges. Either the question needs to be to compare Java and C# or J2EE and .NET.

What are the XML files that are important in developing an ASP.NET application?
The XML file necessary for the for developing an asp.net application is Web.config

Specify the best ways to store variables so that we can access them in various pages of ASP.NET application?
Declare the variables in Global.aspx

How many objects are there in ASP?
Answer1
8 objects, they are request,response, server,application,session,file, dictionary, textstream.

Answer2
There are 6 objects in ASP.net
a) Server
b) Session
c) Application
d) ObjectContext
e) Response
f) Request

Which DLL file is needed to be registered for ASP?
The dll needed for the ASP.net is SYSTEM.WEB.dll

Is there any inbuilt paging (for example shoping cart, which will show next 10 records without refreshing) in ASP? How will you do pating?
Use DataGrid control which has in-built paging features for the purpose.

What does Server.MapPath do?
Answer1
srver.mappath() maps the path given in the argument to the server’s physical path.

Answer2
It returns the complete(absolute) path of the file used in parameter.

Answer3
It returns a string containing the physical path in the server’s file system that corresponds to the virtual or relative path specified by the Path argument.

Name atleast three methods of response object other than Redirect.
Answer1
a) Response.Clear( )
Clears the content of the current output stream.
b) Response.Close( )
Closes the network socket for the current response.
c) Response.End( )
Stops processing the current request and sends all buffered content to the client immediately.

Answer2
methods of Response is Redirect a. Transfer

Name atleast two methods of response object other than Transfer.
a) Response.ClearContent( )
Clears the content of the current output stream.
b) Response.ClearHeaders( )
Clears the HTTP headers from the current output stream.

What is State?
It is the property of the web forms.
ASP.NET provides four types of state:
Application state
Session state
Cookie state
View state.

Explain differences between ADO and DAO.
dao- can access only access database
ado- can access any databases

How many types of cookies are there?
2 types, persistant and impersistant.

How many types of cookies are there?
Answer1
Two type of cookeies.
a) single valued eg request.cookies(”UserName”).value=”Mahesh”
b)Multivalued cookies. These are used in the way collections are used.
e.g.
request.cookies(”CookiName”)(”UserName”)=”Mahesh”
request.cookies(”CookiName”)(”UserID”)=”ABC003?
rember no value method in multivalued cooki

Answer2
There are two types of cookies:
Session cookies
Persistent cookies

Tell few steps for optimizing (for speed and resource) ASP page/application.
Avoid mixing html code with asp code

Which command using Query Analyzer will give you the version of SQL Server and Operating System?
@@VERSION
Returns version, processor architecture, build date, and operating system for the current installation of SQL Server.

How to find the SQL server version from Query Analyser
Answer1
To determine which version of Microsoft SQL Server 2005 is running, connect to SQL Server 2005 by using SQL Server Management Studio, and then run the following Transact-SQL statement:
SELECT SERVERPROPERTY(’productversion’), SERVERPROPERTY (’productlevel’), SERVERPROPERTY (’edition’)
The results are:
• The product version (for example, “9.00.1399.06?)
. • The product level (for example, “RTM”).
• The edition (for example, “Enterprise Edition”).
For example, the result looks similar to:
9.00.1399.06 RTM Enterprise Edition

How to determine which version of SQL Server 2000 is running
To determine which version of SQL Server 2000 is running, connect to SQL Server 2000 by using Query Analyzer, and then run the following code:
SELECT SERVERPROPERTY(’productversion’), SERVERPROPERTY (’productlevel’), SERVERPROPERTY (’edition’)
The results are:
• The product version (for example, 8.00.534).
• The product level (for example, “RTM” or “SP2?).
• The edition (for example, “Standard Edition”). For example, the result looks similar to
:
8.00.534 RTM Standard Edition

Answer2
One can also use SELECT @@Version where the result would look like
Microsoft SQL Server 2005 – 9.00.1399.06 (Intel X86)
Oct 14 2005 00:33:37
Copyright (c) 1988-2005 Microsoft Corporation
Express Edition on Windows NT 5.1 (Build 2600: Service Pack 2)

Using query analyzer, name 3 ways you can get an accurate count of the number of records in a table.
Answer1.
a. Select count(*) from table1
b. SELECT object_name(id) ,rowcnt FROM sysindexes WHERE indid IN (1,0) AND OBJECTPROPERTY(id, ‘IsUserTable’) = 1
c. exec sp_table_validation @table = ‘authors’

Answer2.
SELECT count( * ) as totalrecords FROM employee
This will display total records under the name totalrecords in the table employee
use COUNT_BIG
Returns the number of items in a group.
@@ROWCOUNT
Returns the number of rows affected by the last statement.
Use this statement after an SQL select * statement, to retrieve the total number of rows in the table

 

 

Blog at WordPress.com.