Category Archives: C#

Logical Examples

Prime number logic.

using System;
using System.Collections.Generic;
using System.Text;

namespace Primenumbers
{
class Program
{
static void Main(string[] args)
{
//define limit
int limit = 100;

Console.WriteLine(“Prime numbers between 1 and ” + limit);

//loop through the numbers one by one
for(int i=1; i < 100; i++)
{

bool isPrime = true;

//check to see if the number is prime
for(int j=2; j < i ; j++)
{

if(i % j == 0){
isPrime = false;
break;
}
}
// print the number
if(isPrime)
Console.Write(i + ” “);
}
}
}
}

Fibonacci Series Example

/*
Fibonacci Series Example
This Fibonacci Series Example shows how to create and print
Fibonacci Series using .
*/
using System;
using System.Collections.Generic;
using System.Text;

namespace Primenumbers
{
class Program
{
static void Main(string[] args)
{
//number of elements to generate in a series
int limit = 20;

long[] series = new long[limit];

//create first 2 series elements
series[0] = 0;
series[1] = 1;

//create the Fibonacci series and store it in an array
for(int i=2; i < limit; i++){
series[i] = series[i-1] + series[i-2];
}

//print the Fibonacci series numbers

Console.WriteLine(“Fibonacci Series upto ” + limit);
for(int i=0; i< limit; i++){
Console.Write(series[i] + ” “);
}
}
}
}
/*
Output of the Fibonacci Series Example would be
Fibonacci Series upto 20
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
*/

Read Number from Console and Check if it is a Palindrome Number

/*
Read Number from Console and Check if it is a Palindrome Number
This example shows how to input the number from console and
check if the number is a palindrome number or not.
*/
using System;
using System.Collections.Generic;
using System.Text;

namespace Primenumbers
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(“Enter the number to check..”);
double number = 0;

try
{
//take input from console
string br =Console.ReadLine();
//parse the line into int
number = Convert.ToDouble(br);

}
catch(FormatException ne)
{
Console.WriteLine(“Invalid input: ” + ne.Message);

}

Console.WriteLine(“Number is ” + number);
double n = number;
double reversedNumber = 0;
double temp=0;

//reverse the number
while(n > 0){
temp = n % 10;
n = n / 10;
reversedNumber = reversedNumber * 10 + temp;
}

/*
* if the number and it’s reversed number are same, the number is a
* palindrome number
*/
if(number == reversedNumber)
Console.WriteLine(number + ” is a palindrome number”);
else
Console.WriteLine(number + ” is not a palindrome number”);
}

}
}
/*
Output of the program would be
Enter the number to check..
121
Number is 121
121 is a palindrome number
*/

Largest and Smallest Number in an Array Example

/*
Find Largest and Smallest Number in an Array Example
This Example shows how to find largest and smallest number in an
array.
*/

using System;
using System.Collections.Generic;
using System.Text;

namespace LogicalSamples
{
class Program
{
static void Main(string[] args)
{
//array of 10 numbers
int[] numbers = new int[]{32,43,53,54,32,65,63,98,43,23};

//assign first element of an array to largest and smallest
int smallest = numbers[0];
int largetst = numbers[0];

for(int i=1; i< numbers.Length; i++) { if(numbers[i] > largetst)
largetst = numbers[i];
else if (numbers[i] < smallest)
smallest = numbers[i];

}

Console.WriteLine(“Largest Number is : ” + largetst);
Console.WriteLine(“Smallest Number is : ” + smallest);

}
}
}

/*
Output of this program would be
Largest Number is : 98
Smallest Number is : 23
*/

Reverse Number

/*

This Reverse Number Example shows how to reverse a given number.
*/

using System;
using System.Collections.Generic;
using System.Text;

namespace LogicalSamples
{
class Program
{
static void Main(string[] args)
{
//original number
int number = 1234;
int reversedNumber = 0;
int temp = 0;

while(number > 0){

//use modulus operator to strip off the last digit
temp = number%10;

//create the reversed number
reversedNumber = reversedNumber * 10 + temp;
number = number/10;

}

//output the reversed number
Console.WriteLine(“Reversed Number is: ” + reversedNumber);
}
}
}

/*
Output of this Number Reverse program would be
Reversed Number is: 4321
*/

Run a .sql script files in C#

If you have placed in situation to execute .sql script files from .NET code on SQL Server, you will see that SqlCommand class is not that useful. In other words, you can’t execute batch commands that contains ‘GO’ (batch finalizer command). So you can think of several options, like split that script to several commands, and execute one by one. But you realize how complex is that task.
If you wanted to do that prior to SQL Server 2005, the only option is using osql utility. Since SQL Server 2005 there is another option which is much better and preferred. That option is using SMO library which comes with SQL Server and can be used for managing everything on SQL Server 2005. You can backup, restore databases, configure permissions, replication, etc.
I plan to post about how to backup and restore database using this SMO library in near future. Here will write only about how to read sql file and execute the content on SQL Server.

using System.Data.SqlClient;

using System.IO;

using Microsoft.SqlServer.Management.Common;

using Microsoft.SqlServer.Management.Smo;

namespace ConsoleApplication1

{

class Program

{

static void Main(string[] args)

{

string sqlConnectionString =

“Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True”;

FileInfo file = new FileInfo(“C:\\myscript.sql”);

string script = file.OpenText().ReadToEnd();

SqlConnection conn = new SqlConnection(sqlConnectionString);

Server server = new Server(new ServerConnection(conn));

server.ConnectionContext.ExecuteNonQuery(script);

}

}

}

A Reference should be added to the following DLLs.

Microsoft.SqlServer.ConnectionInfo

Microsoft.SqlServer.Smo

What is delegate?What is the advantages of delegates?

Delegate is like a pointer to a function.suppose we want to call one or more than one function simultaniously then we have to delegate.
we have to define the function in the delegate and now if we call the delegate then the functions
will automatically called.
but to call that function we have to keep in mind that “the parameter type,return type and number of parameters will be same.”

using System;

namespace Deleg
{
	class Calculation
	{
		public delegate void calcHandler(double d1, double d2);
		public void calculate(calcHandler clc, double d1,double d2)
		{
			clc(d1,d2);
		}
	}
	class MyClass
	{
		public static void add(double d1, double d2)
		{
			Console.WriteLine("Summation = " + (d1+d2));
		}
		public static void subtract(double d1, double d2)
		{
			Console.WriteLine("Subtract = " + (d1-d2));
		}
		public static void multiply(double d1, double d2)
		{
			Console.WriteLine("Multiplication = " + (d1*d2));
		}

		public static void devide(double d1, double d2)
		{
			Console.WriteLine("Devision = " + (d1/d2));
		}

		public static void Main()
		{
		Calculation.calcHandler myDele = new Calculation.calcHandler  (add);
		myDele += new Calculation.calcHandler(subtract);
		myDele += new Calculation.calcHandler(multiply);
		myDele += new Calculation.calcHandler(devide);
		Calculation c = new Calculation();
		c.calculate(myDele,50,40);
		Console.Read();
		}
	}
}

Advantages:

Dynamic binding can be done by using delegate because we can call more than one methods at a time dynamically by calling the delegate in which the methods is defined.

Why multiple inheritance is not supported in .net?

C#/VB.net don’t support the Multiple inheritance because to avoid the ambiguty of member of parents class
but we use interface for same purpose as like multiple inheritance

Because interfaces do not the implementation details, they only know what operations an object can do.
Multiple inheritance is difficult when there are two different implementations are found for the method with
same signature in both the base classes. But in case of interface both the interface may define a common method with
same signature but they are not implemented at the interface level, they are only implemented by the object or type that
implement both the interfaces. Here though there are two different interfaces defining two methods with same signatures,
the object provides the common implementation satisfying both the methods in both the interfaces. So there is no ambiguity
between implementations, both the methods have common implementation hence you could have multiple inheritance in case of
interfaces

Dot Net Certification Details: Microsoft MCTS(70-528, 70-536), MCP , MCPD (70-547), MCSE, MVP AND MCSD

Very confusing. Every aspirant has to search a lot to demystified the best exams etc. Here in next few paragraph i am going to demystify Microsoft Certification .net 2.0
In .net Microsoft offers many categories

.net certificationList

* MCTS
* MCPD
* MCSD
* MCP
* MVP

MCTS – The Microsoft Certified Technology Specialist. its comes under .net 2.0 certification. This is the fresh exam and do not require any previous exams to clear it. So a new developer can start from this exam.

Following are the specialization and exams under those

.NET Framework 2.0 Web Applications

one has to pass the following examinations:

* Exam 70–536: TS: Microsoft .NET Framework 2.0 – Application Development Foundation

* Exam 70–528: TS: Microsoft .NET Framework 2.0 – Web-Based Client Development

.NET Framework 2.0 Windows Applications

one has to pass the following examinations:

* Exam 70–536: TS: Microsoft .NET Framework 2.0 – Application Development Foundation

* Exam 70-526: TS: Microsoft .NET Framework 2.0 – Windows-Based Client Development

.NET Framework 2.0 Distributed Applications
one has to pass the following examinations:

* Exam 70–536: TS: Microsoft .NET Framework 2.0 – Application Development Foundation

* Exam 70–529: TS: Microsoft .NET Framework 2.0 – Distributed Application Development
——————————————————————————————–

MCPD -Microsoft Certified Professional Developer

It also comes under .net 2.0 certification
this is next step to the MCTS, so to clear it you firstly need to have MCTS in your tally
Folloings are .NET 2.0, Visual Studio 2005 and SQL Server 2005.

Professional Developer: Web Developer
* Prerequisite: MCTS: .NET Framework 2.0 Web Applications
* Exam 70-547: PRO: Designing and Developing Web Applications by Using the Microsoft .NET Framework

Professional Developer: Windows Developer
Following examinations:

* Prerequisite: MCTS: .NET Framework 2.0 Windows Applications
* Exam 70–548: PRO: Designing and Developing Windows Applications by Using the Microsoft .NET Framework

Professional Developer: Enterprise Applications Developer
Following examinations:

* Prerequisite: MCTS: .NET Framework 2.0 Web Applications
* Prerequisite: MCTS: .NET Framework 2.0 Windows Applications
* Prerequisite: MCTS: .NET Framework 2.0 Distributed Applications
* Exam 70–549: PRO: Designing and Developing Enterprise Applications by Using the
Microsoft .NET Framework

MCP Microsoft Certified Professional. Person having any ms certification is called MCP

MVP Microsoft Most Valuable Professional. This does not require any exam. It is related with how you contributed in the microsoft communties or any site that promote ms technologies. You could be MVP of any of the these c#,asp.net,web services,word,excel,

Web application maintainance related ASP.NET Interview Questions

Why is it important to monitor a deployed a Web application?
After you have deployed a Web application, you need to monitor how it performs on the server. Many issues can crop up at this point because of
1. The number of users accessing the application.
2. The unpredictable nature of user interaction.
3. The possibility of malicious attack.

What are the 3 major steps invloved in maintaining a deployed web application?
Maintaining a deployed application is an ongoing task that involves three major steps:
1. Monitoring the application for error, performance, and security issues.
2. Repairing the application as issues are discovered.
3. Tuning the application to respond to user traffic.

What are the MMC snap-ins provided by windows for monitoring security, performance, and error events?
The Event Viewer snap-in : Lists application, system, and security events as they occur on the system. Use this tool to see what is currently happening on the server and to get specific information about a particular event.
The Performance snap-in : Lets you create new events to display in the Event Viewer and allows you to track event counters over time for display graphically or in report form.

How do run the Event Viewer to view application, system, and security events as they happen?
To run the Event Viewer, choose Event Viewer from the Administrative Tools submenu on the Windows Start menu. (You can show the Administrative Tools menu in Windows XP Professional by opening the Start button’s Properties dialog box and clicking the Customize button on the Start Menu tab. The Administrative Tools option is located on the Advanced tab of the Customize Start Menu dialog box.) After clicking the Event Viewer shortcut, Windows displays the Event Viewer snap-in in the MMC.

What are the 3 levels at which the Event Viewer snap-in displays general application, system, and security events?
1. Informational events.
2. Warning events.
3. Error events.

Can you repair a deployed web application in place without restarting the server or IIS?
Yes, to repair a deployed Web application, copy the new assembly (.dll) and/or content files (.aspx, .ascx, and so on) to the application folder on the server. ASP.NET automatically restarts the application when you replace the assembly. You do not need to install or register the assembly on the server.

What is ASP.NET Process recycling?
ASP.NET Web applications have a limited ability to repair themselves through process recycling. Process recycling is the technique of shutting down and restarting an ASP.NET worker process (aspnet_wp.exe) that has become inactive or is consuming excessive resources. You can control how ASP.NET processes are recycled through attributes in the processModel element in the Machine.config file.

Describes the processModel attributes found in machine.config that relate to process recycling?
1. timeout attribute :The amount of time (hh:mm:ss) before the process is shut down and restarted. Use this setting to automatically recycle a process after a certain number of requests as a preventive measure.
2. shutDownTimeOut attribute : How much time each process has to shut itself down. After this amount of time, the process is terminated by the system if it still running.
3. requestLimit attribute : The number of queued requests to serve before the process is shut down and restarted. Use this setting the same way you use the timeout attribute.
4. restartQueueLimit attribute : The number of queued requests to retain while the process is shut down and restarted.
5. memoryLimit attribute : The percentage of physical memory the ASP.NET process is allowed to consume before that process is shut down and a new process is started. This setting helps prevent memory leaks from degrading the server.
6. responseRestart­ – DeadlockInterval : The amount of time to wait before restarting a process that was shut down because it was deadlocked. This setting is usually several minutes to prevent applications with serious errors from degrading the server.
7. responseDeadlockInterval : The amount of time to wait before restarting a process that is deadlocked. The process is restarted if there are queued requests and the process has not responded within this time limit.

What is the use of processModel element apart from providing process recycling?
The processModel element in the server’s Machine.config file provides attributes that control certain performance aspects, such as
1. The maximum number of requests to be queued.
2. How long to wait before checking whether a client is connected.
3. How many threads to allow per processor.

Describe the processModel attributes that relate to performance tuning?
requestQueueLimit
The number of queued requests allowed before ASP.NET returns response code 503 (Server too busy) to new requests
clientConnectedCheck
The amount of time (hh:mm:ss) to wait before checking whether a client is still connected
maxWorkerThreads
The maximum number of threads per processor
maxIOThreads
The maximum number of I/O threads per processor

In general, lowering these settings allows your server to handle fewer clients more quickly. Increasing these settings permits more clients and more queued requests, but slows response times.

How do you turn off Session state?
To turn off Session state, in the application’s Web.config file, set the sessionState element’s mode attribute to Off.

If you turn of Session State, can you use Session state variables in code anywhere in the application?
No

What is Optimization?
Optimization usually refers to writing code in a way that executes more quickly or consumes fewer resources. In general, optimizations simply reflect the good programming practices.

List some of the common steps to follow to optimize a web application for performance?
Turn off debugging for deployed applications.
Code that has been compiled with release options runs faster than code compiled with debug options.
Avoid round-trips between the client and server.
ASP.NET uses postbacks to process server events on a page. Try to design Web forms so that the data on the Web form is complete before the user posts the data to the server. You can use the validation controls to ensure that data is complete on the client side before the page is submitted.
Turn off Session state if it isn’t needed.
In some cases, you can design your code to use other techniques, such as cookies, to store client data.
Turn off ViewState for server controls that do not need to retain their values.
Saving ViewState information adds to the amount of data that must be transmitted back to the server with each request.
Use stored procedures with databases.
Stored procedures execute more quickly than ad hoc queries.
Use SqlDataReader rather than data sets for read-forward data retrieval.
Using SqlDataReader is faster and consumes less memory than creating a data set.

Important notes of constructors and static classes

C# supports two types of constructor, a class constructor (static constructor) and an instance constructor (non-static constructor).

Static constructor is used to initialize static data

members as soon as the class is referenced first time, whereas an instance constructor is used to create an instance of that class with <new> keyword. A static constructor does not take access modifiers or have parameters and can’t access any non-static data member of a class.

Since static constructor is a class constructor, they are guaranteed to be called as soon as we refer to that class or by creating an instance of that class.

You may say, why not initialize static data members where we declare them in the code.  Like this :

private static int id = 10;
private static string name = “jack”;

Static data members can certainly be initialized at the time of their declaration but there are times when value of one static member may depend upon the value of another static member. In such cases we definitely need some mechanism to handle conditional initialization of static members. To handle such situation, C# provides static constructor.

Let me explain you with examples :

//File Name : Test.cs
using System;
namespace Constructor
{
class Test
{
//Declaration and initialization of static data member
private static int id = 5;
public static int Id
{
get
{
return id;
}
}
public static void print()
{
Console.WriteLine(“Test.id = ” + id);
}
static void Main(string[] args)
{
//Print the value of id
Test.print();
}
}
}

In the above example, static data member <id> is declared and initialized in same line. So if you compile and run this program your output would look similar to this :

Test.id = 5

Lets create one more class similar to class Test but this time the value of its static data member would depend on the value of static data member <id> of class Test.id.

//File Name : Test1.cs
using System;
namespace Constructor
{
class Test1
{
private static int id ;
//Static constructor, value of data member id is set conditionally here.
//This type of initialization is not possible at the time of declaration.
static Test1()
{
if( Test.Id < 10 )
{
id = 20;
}
else
{
id = 100;
}
Console.WriteLine(“Static<Class> Constructor for Class Test1 Called..”);
}
public static void print()
{
Console.WriteLine(“Test1.id = ” + id);
}
static void Main(string[] args)
{
//Print the value of id
Test1.print();
}
}
}

As you can see in the above static constructor, static data member <id> is initialized conditionally. This type of initialization is not possible at the time of declaration. This is where static constructor comes in picture. So if you compile and run this program your output would look similar to this :

Static<Class> Constructor for Class Test1 Called..
id = 20

Since <id> in class Test was initialized with a value of 5, therefore <id> in class Test1 got initialized to a value of 20.

Some important point regarding static constructor from C# Language Specification and C# Programmer’s Reference :

1) The static constructor for a class executes before any instance of the class is created.
2) The static constructor for a class executes before any of the static members (ie functions or methods) for the class are referenced.
3) The static constructor for a class executes after the static field initializers (if any) for the class.
4) The static constructor for a class executes at most one time during a single program instantiation
5) A static constructor does not take access modifiers or have parameters.
6) A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
7) A static constructor cannot be called directly.
8) The user has no control on when the static constructor is executed in the program.
9)  A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

Hopefully, this would clear the confusion some of developers have about static constructor.