10 August 2014

Could not find any resources appropriate for the specified culture or the neutral culture

In properties go to Application Tab. Here in applicatin tab verify your assembly name and Default namespace.
You need to change them appropriately in order to eliminate this error.

09 August 2014

Add character in the ascii sequence

Today, we will take a One Scenario for  add character in the ascii sequence to a given string immediately after every character.
   Input :LAKSHMI
  Output:LM AB KL ST HI MN IJ.
Here is a Code:
#region Declaration
private string _addValue = string.Empty;
private string _result = string.Empty;
private string _res = string.Empty;
 #region Functions
private string AddValues(string c)
switch (c)
case "A": _addValue = "AB";
 case "B": _addValue = "BC";
case "C":
 _addValue = "CD";
case "D":
_addValue = "DE";
case "E":
 _addValue = "EF";
case "F":
_addValue = "FG";
case "G":
 _addValue = "GH";
case "H":
 _addValue = "HI";
case "I":
 _addValue = "IJ";
case "J":
_addValue = "JK";
case "K":
_addValue = "KL";
case "L":
 _addValue = "LM";
case "M":
_addValue = "MN";
case "N":
_addValue = "NO";
case "O":
_addValue = "OP";
case "P":
 _addValue = "QR";
case "R":
_addValue = "RS";
case "S":
_addValue = "ST";
case "T":
 _addValue = "TU";
 case "U":
 _addValue = "UV";
 case "V":
 _addValue = "VW";
case "W":
 _addValue = "WX";
case "X":
_addValue = "XY";
case "Y":
_addValue = "YZ";
case "Z":
_addValue = "ZA";
return _addValue;
private string FinalResult(TextBox txt)
String str = Convert.ToString(txt.Text);
 char[] szArr = str.ToCharArray();
 for (int idx = 0; idx < szArr.Length; idx++)
_result = AddValues(Convert.ToString(szArr[idx]));
if (_res == string.Empty)
_res = _result;
_res = _res + " " + _result;
 return _res;
Call this function in Button Click Event
private void button1_Click(object sender, EventArgs e)
textBox2.Text = FinalResult(textBox1);
   Thanks for your read this article.

06 August 2014

Find All Monday in Current and Previous Year

Find All Monday in Current and Previous Year
SELECT Mondays = DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), n.num) FROM (SELECT TOP 732 num = ROW_NUMBER() OVER(ORDER BY a.NAME)-366 FROM dbo.syscolumns a, dbo.syscolumns b) n WHERE DATENAME(weekday, DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), n.num)) = 'Monday'

Find All Monday in Current Year

Find All Monday in Current Year
SELECT Mondays = DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), n.num) FROM (SELECT TOP 366 num = ROW_NUMBER() OVER(ORDER BY a.NAME)-1 FROM dbo.syscolumns a, dbo.syscolumns b) n WHERE DATENAME(weekday, DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), n.num)) = 'Monday'

05 August 2014

Find All Fridays in Current AND Next Year

Find All Fridays in Current AND Next Year

SELECT Fridays = DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), n.num) FROM (SELECT TOP 732 num = ROW_NUMBER() OVER(ORDER BY a.NAME)-1 FROM dbo.syscolumns a, dbo.syscolumns b) n WHERE DATENAME(weekday, DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), n.num)) = 'Friday'

04 August 2014

Find All Fridays in Current Year

Find All Fridays in Current Year

SELECT Fridays = DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), n.num) FROM (SELECT TOP 366 num = ROW_NUMBER() OVER(ORDER BY a.NAME)-1 FROM dbo.syscolumns a, dbo.syscolumns b) n WHERE DATENAME(weekday, DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), n.num)) = 'Friday'

03 August 2014

Get Only Time from datetime 2008

get Only Time from datetime 2008
CONVERT(time,GETDATE(),108) AS HourMinuteSecond

02 August 2014

Get Only Date from datetime in SQL Server 2008

get Only Date from datetime in SQL Server 2008
CONVERT(Date,GETDATE(),101) AS DateOnly

01 August 2014

Why OnAfterInstall not trigger

Please check "Primary Output from (Active)" in Your Application "Custom Action" Install Folder.

Get Only Time from datetime 2005

get Only Time from datetime 2005
CONVERT(VARCHAR(8),GETDATE(),108) AS HourMinuteSecond

30 July 2014

14 Principles on Total Quality Management

Professional Development – Dr W. Edwards Deming’s 14 Principles on Total Quality Management
Dr. Demings’s 14 principles

  1. Create a constant purpose toward improvement
  2. Adopt the new philosophy
  3. Cease dependence on mass inspection
  4. Use a single supplier for any one item
  5. Improve every process
  6. Create training on the job
  7. Adopt and institute leadership aimed at helping people do a better job
  8. Drive out fear
  9. Break down barriers between departments
  10. Get rid of unclear slogans
  11. Eliminate arbitrary numerical targets
  12. Permit pride of workmanship
  13. Implement education and self-improvement
  14. Make transformation everyone’s job

29 July 2014

IIF funciton in SQL Server 2012 and give an Example

If you are using SQL Server 2012 you can use IIF and get the same effect as CASE statement.
Create a Table
Insert some value into table
IIF Statement
UPDATE SimpleTable
FROM SimpleTable

28 July 2014

Example for CASE Function in SQL

Create a Table
Insert some value into table
CASE Funciton:
UPDATE SimpleTable
FROM SimpleTable

27 July 2014

Example for REPLACE Function in SQL

Create a Table
CREATE TABLE SimpleTable (ID INT, Gender VARCHAR(10))
Insert some value into table
INSERT INTO SimpleTable (ID, Gender)
SELECT 1, 'female'
SELECT 2, 'male'
SELECT 3, 'male'
Replace male into female using UPDATE Query
UPDATE SimpleTable
SET Gender = REPLACE(('fe'+Gender),'fefe','')
FROM SimpleTable

26 July 2014

SQL SERVER – 2005 – Find Stored Procedure Create Date and Modified Date

SELECT name, create_date, modify_date
FROM sys.objects
WHERE type = 'P'
AND name = '<Sp_name>'

Get Current Date in SQL Server 2005

get Only Date from datetime in SQL Server 2005

24 July 2014

Column Exists or Not in SQL Server

Column Exists or Not in SQL Server

 @TableName VARCHAR(100) ,
@ColumnName VARCHAR(100) )
 DECLARE @Result VARCHAR(100);
              WHERE TABLE_NAME = @TableName AND COLUMN_NAME = @ColumnName ) BEGIN
 SET @Result = 'Already Exsits'
 BEGIN SET @Result = 'Not Available, You can create now!'
 END RETURN (@Result)

23 July 2014

SQL SERVER – 2005 – Search Stored Procedure Code – Search Stored Procedure Text

FROM sys.procedures

22 July 2014

CTE in SQL Server

the common table expression (CTE) is a temporary named result set that you can reference within a SELECT, INSERT, UPDATE, or DELETE statement. You can also use a CTE in a CREATE VIEW statement, as part of the view’s SELECT query. In addition, as of SQL Server 2008, you can add a CTE to the new MERGE statement.

21 July 2014

SQL SERVER – Find Stored Procedure Related to Table in Database – Search in All Stored Procedure

SELECT DISTINCT o.name, o.xtype
FROM syscomments c
INNER JOIN sysobjects o ON c.id=o.id
WHERE c.TEXT LIKE '%tablename%'

20 July 2014

SQL SERVER – Find Column Used in Stored Procedure – Search Stored Procedure for Column Name

SELECT obj.Name SPName, sc.TEXT SPText
FROM sys.syscomments sc
INNER JOIN sys.objects obj ON sc.Id = obj.OBJECT_ID
WHERE sc.TEXT LIKE '%' + 'Name Your Column Here' + '%'

19 July 2014

SQL Constraints

SQL constraints are used to specify rules for the data in a table.
 If there is any violation between the constraint and the data action, the action is aborted by the constraint.

Syntax for SQL Constraints

CREATE TABLE table_name
column_name1 data_type(size) constraint_name,
column_name2 data_type(size) constraint_name,
column_name3 data_type(size) constraint_name,
 In SQL, we have the following constraints:
NOT NULL - Indicates that a column cannot store NULL value
UNIQUE - Ensures that each row for a column must have a unique value
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Ensures that a column (or combination of two or more columns) have an unique identity which helps to find a particular record in a table more easily and quickly
FOREIGN KEY - Ensure the referential integrity of the data in one table to match values in another table
CHECK - Ensures that the value in a column meets a specific condition
DEFAULT - Specifies a default value when specified none for this column

Entity Framework Tips

Namespace of Entity framework:
Entity Framework 5.0:
Entity Framework 6.0:
Entity Framework 5.0 Features:

  • This release can be used in Visual Studio 2010 and Visual Studio 2012 to write applications that target .NET 4.0 and .NET 4.5. When targeting .NET 4.5 this release introduces some new features including enum support, table-valued functions, spatial data types and various performance improvements.
  • If you create a new model using the Entity Framework Designer in Visual Studio 2012, the EF5 NuGet package will be installed to your project and the generated code will make use of EF5. New ASP.NET projects created in Visual Studio 2012 (including MVC projects) also have the EF5 NuGet package installed by default.
  • The Entity Framework Designer in Visual Studio 2012 also introduces support for multiple-diagrams per model, coloring of shapes on the design surface and batch import of stored procedures.

Entity Framework 6.0 Features:

  • Async Query and Save adds support for the task-based asynchronous patterns that were introduced in .NET 4.5.
  • Connection Resiliency enables automatic recovery from transient connection failures.
  • Code-Based Configuration gives you the option of performing configuration – that was traditionally performed in a config file – in code.
  • Dependency Resolution introduces support for the Service Locator pattern and we've factored out some pieces of functionality that can be replaced with custom implementations.
  • Interception/SQL logging provides low-level building blocks for interception of EF operations with simple SQL logging built on top.
  • Testability improvements make it easier to create test doubles for DbContext and DbSet when using a mocking framework or writing your own test doubles.
  • DbContext can now be created with a DbConnection that is already opened which enables scenarios where it would be helpful if the connection could be open when creating the context (such as sharing a connection between components where you can not guarantee the state of the connection).
  • Improved Transaction Support provides support for a transaction external to the framework as well as improved ways of creating a transaction within the Framework.
  • Enums, Spatial and Better Performance on .NET 4.0 - By moving the core components that used to be in the .NET Framework into the EF NuGet package we are now able to offer enum support, spatial data types and the performance improvements from EF5 on .NET 4.0.
  • Improved performance of Enumerable.Contains in LINQ queries.
  • Improved warm up time (view generation), especially for large models. 
  • Pluggable Pluralization & Singularization Service.
  • Custom implementations of Equals or GetHashCode on entity classes are now supported.
  • DbSet.AddRange/RemoveRange provides an optimized way to add or remove multiple entities from a set.
  • DbChangeTracker.HasChanges provides an easy and efficient way to see if there are any pending changes to be saved to the database.
  • SqlCeFunctions provides a SQL Compact equivalent to the SqlFunctions.


17 July 2014

SQL SERVER – Disable All the Foreign Key Constraint in Database – Enable All the Foreign Key Constraint in Database

-- Disable all the constraint in database

-- Enable all the constraint in database

16 July 2014

SQL SERVER – Create Unique Constraint on Table Column on Existing Table

by using UNIQUE for Unique constraint.

   UNIQUE([col name])
USE tempdb
-- Create Table
-- Alter Table Create Constraint
-- Clean up

15 July 2014

Parts in CTE

A Common Table Expression contains three core parts:
The CTE name (this is what follows the WITH keyword)
The column list (optional)
The query (appears within parentheses after the AS keyword)
The query using the CTE must be the first query appearing after the CTE.
How to use CTE in SQL Server?
Syntax of CTE:
With Parameter
With T(<col Name>, <col name1>, <Col name2>)  --Column names for Temporary table
SELECT A.<Col name>, E.<col name1>, E.<col name2> from <table_name> A
INNER JOIN <table_name> E ON E.<col name> = A.<col name>
SELECT * FROM T  --SELECT or USE CTE temporary Table
WHERE T.[col name]  > 50
ORDER BY T.<col name>

Without Parameter
(SELECT c.[Col name]
FROM [table_name] pc
INNER JOIN [table_name] c ON c.[Col name] = pc.[Col name])
SELECT cte.[Col name], p.[Col name]
FROM [table_name] p
INNER JOIN [table_name].[Col name] ea ON ea.[Col name] = p.[Col name]
INNER JOIN MyCTE cte ON cte.[Col name] = p.[Col name]
INNER JOIN [table_name].PersonPhone ph ON ph.[Col name] = p.[Col name];

14 July 2014

SQL DB Formatting

  • Use upper case for all SQL keywords
  • Indent code to improve readability
  • Comment code blocks that are not easily understandable
  • Use single-line comment markers(–)
  • Reserve multi-line comments (/*.. ..*/) for blocking out sections of code
  • Use single quote characters to delimit strings.
  • Nest single quotes to express a single quote or apostrophe within a string
  • For example, SET @sExample = ‘SQL”s Authority’
  • Use parentheses to increase readability
  • WHERE (color=’red’ AND (size = 1 OR size = 2))
  • Use BEGIN..END blocks only when multiple statements are present within a conditional code segment.
  • Use one blank line to separate code sections.
  • Use spaces so that expressions read like sentences.
  • fillfactor = 25, not fillfactor=25
  • Format JOIN operations using indents
  • Also, use ANSI Joins instead of old style joins4
  • Place SET statements before any executing code in the procedure.

13 July 2014

SQL DB Structure

  • Each table must have a primary key
  • In most cases it should be an IDENTITY column named ID
  • Normalize data to third normal form
  • Do not compromise on performance to reach third normal form. Sometimes, a little de-normalization results in better performance.
  • Do not use TEXT as a data type; use the maximum allowed characters of VARCHAR instead
  • In VARCHAR data columns, do not default to NULL; use an empty string instead
  • Columns with default values should not allow NULLs
  • As much as possible, create stored procedures on the same database as the main tables they will be accessing

12 July 2014

SQL DB General Rules

  • Do not use spaces in the name of database objects
  • Do not use SQL keywords as the name of database objects
  • In cases where this is necessary, surround the
  • object name with brackets, such as [Year]
  • Do not prefix stored procedures with ‘sp_’2
  • Prefix table names with the owner name3

11 July 2014

SQL SERVER – Guidelines and Coding Standards

Use “Pascal” notation for SQL server Objects Like Tables, Views, Stored Procedures. Also tables and views should have ending “s”.
Example: UserDetails
If you have big subset of table group than it makes sense to give prefix for this table group. Prefix should be separated by _.
Example: Page_ UserDetails
Use following naming convention for Stored Procedure. sp<Application Name>_[<group name >_]<action type><table name or logical instance> Where action is: Get, Delete, Update, Write, Archive, Insert… i.e. verb
Use following Naming pattern for triggers: TR_<TableName>_<action><description>
Indexes : IX_<tablename>_<columns separated by_>
Primary Key : PK_<tablename>
Foreign Key : FK_<tablename_1>_<tablename_2>
Default: DF_<table name>_<column name>
Example:DF_ UserDetails_UserName
Normalize Database structure based on 3rd Normalization Form. Normalization is the process of designing a data model to efficiently store data in a database. (Read More Here)
Avoid use of SELECT * in SQL queries. Instead practice writing required column names after SELECT statement.
Example:SELECT Username, Password
FROM UserDetails
Use SET NOCOUNT ON at the beginning of SQL Batches, Stored Procedures and Triggers. This improves the performance of Stored Procedure. (Read More Here)
Properly format SQL queries using indents.
Example:SELECT Username, Password
FROM UserDetails ud
INNER JOIN Employee e ON e.EmpID = ud.UserID
Practice writing Upper Case for all SQL keywords.
It is common practice to use Primary Key as IDENTITY column but it is not necessary. PK of your table should be selected very carefully.
If “One Table” references “Another Table” than the column name used in reference should use the following rule :
Column of Another Table : <OneTableName> ID
If User table references Employee table than the column name used in reference should be UserID where User is table name and ID primary column of User table and UserID is reference column of Employee table.
Columns with Default value constraint should not allow NULLs.
Practice using PRIMARY key in WHERE condition of UPDATE or DELETE statements as this will avoid error possibilities.
Always create stored procedure in same database where its relevant table exists otherwise it will reduce network performance.
Avoid server-side Cursors as much as possible, instead use SELECT statement. If you need to use cursor then replace it next suggestion.
Instead of using LOOP to insert data from Table B to Table A, try to use SELECT statement with INSERT statement. (Read More Here)
INSERT INTO TABLE A (column1, column2)
SELECT column1, column2
WHERE ....
Avoid using spaces within the name of database objects; this may create issues with front-end data access tools and applications. If you need spaces in your database object name then will accessing it surround the database object name with square brackets.
Example:[Order Details]
Do not use reserved words for naming database objects, as that can lead to some unpredictable situations. (Read More Here)
Practice writing comments in stored procedures, triggers and SQL batches, whenever something is not very obvious, as it won’t impact the performance.
Do not use wild card characters at the beginning of word while search using LIKE keyword as it results in Index scan.
Indent code for better readability. (Example)
While using JOINs in your SQL query always prefix column name with the table name. (Example). If additionally require then prefix Table name with ServerName, DatabaseName, DatabaseOwner. (Example)
Default constraint must be defined at the column level. All other constraints must be defined at the table level. (Read More Here)
Avoid using rules of database objects instead use constraints.
Do not use the RECOMPILE option for Stored Procedure unless there is specific requirements.
Practice to put the DECLARE statements at the starting of the code in the stored procedure for better readability (Example)
Put the SET statements in beginning (after DECLARE) before executing code in the stored procedure. 

10 July 2014

SQL SERVER – Stored Procedure Optimization Tips – Best Practices

  • Include SET NOCOUNT ON statement
  • Use schema name with object name
  • Do not use the prefix “sp_” in the stored procedure name
  • Use IF EXISTS (SELECT 1) instead of (SELECT *)
  • Use the sp_executesql stored procedure instead of the EXECUTE statement
  • Try to avoid using SQL Server cursors whenever possible
  • Keep the Transaction as short as possible
  • Use TRY-Catch for error handling

09 July 2014

Expression Blend

Welcome to Expression Blend:

Expression Blend 2.0
Introducing Microsoft Expression Blend 2, a full-featured professional design tool for creating engaging and sophisticated user interfaces for Windows Presentation Foundation (WPF) and Microsoft Silverlight applications. Expression Blend lets designers focus on creativity while letting developers focus on programming.
In Expression Blend, you design your application visually, drawing shapes, paths, and controls on the artboard, and then modifying their appearance and behavior. You can import images, video, and sound. In Windows-based applications, you can also import and change 3D objects.
Silverlight 2 is supported in Expression Blend 2 with Service Pack 1 installed.
You can import graphics and Extensible Application Markup Language (XAML) resources that are generated by Microsoft Expression Design 2 into your Expression Blend 2 project. You can also import Silverlight media projects that were created in Microsoft Expression Encoder 2, to add new features or visual elements to the project, or to modify the media player template that can be reused in Expression Encoder 2.
In Microsoft Expression Web 2, you can import Silverlight 1.0 websites and compiled Silverlight 2 application files into an existing or new project, and then publish your work.
Microsoft Visual Studio 2008 works seamlessly with Expression Blend 2 to automatically update code-behind files in your project when you specify events to listen for. From the Project panel in Expression Blend 2, you can open individual code-behind files or your whole project. You can also use the deployment tools of Visual Studio 2008 to deploy your applications.
Expression Blend produces Windows Presentation Foundation (WPF) applications, Silverlight 1.0 websites, and Silverlight 2 user controls (.xap and supporting files). Your visual design is represented by XAML. Just as HTML is the markup language for web applications, XAML is the markup language for WPF.
Blend is mainly Focused on Creating High Quality UI. where as Visual Studio for WPF/Silverlight is Mainly Focused on EventHandlers / Coding.

Advantages of Expression Blend:

  • DRAWING vector art, paths, etc
  • Data binding dialogs with properties and complex options
  • Re-templating

08 July 2014

C# Coding Guide

Open braces should always be at the beginning of the line after the statement that begins the block. Contents of the brace should be indented by 4 spaces. For example:
“case” statements should be indented from the switch statement like this:
Braces should never be considered optional. Even for single statement blocks, you should always use braces. This increases code readability and maintainability.
Single line statements
         Single line statements can have braces that begin and end on the same line.
It is suggested that all control structures (if, while, for, etc.) use braces, but it is not required.
         Spaces improve readability by decreasing code density. Here are some guidelines for the use of space characters within code:

  • Do use a single space after a comma between function arguments.
  • Do not use a space after the parenthesis and function arguments
  • Do not use spaces between a function name and parenthesis.
  • Do not use spaces inside brackets.
  • Do use a single space before flow control statements
  • Do use a single space before and after comparison operators
  • Naming
  • Follow all .NET Framework Design Guidelines for both internal and external members. Highlights of these include:
  • Do not use Hungarian notation
  • Do not use a prefix for member variables (_, m_, s_, etc.). If you want to distinguish between local and member variables you should use “this.” in C# and “Me.” in VB.NET.
  • Do use camelCasing for member variables
  • Do use camelCasing for parameters
  • Do use camelCasing for local variables
  • Do use PascalCasing for function, property, event, and class names
  • Do prefix interfaces names with “I”
  • Do not prefix enums, classes, or delegates with any letter

                The reasons to extend the public rules (no Hungarian, no prefix for member variables, etc.) is to produce a consistent source code appearance. In addition a goal is to have clean readable source. Code legibility should be a primary goal.
Interop Classes
        Classes that are there for interop wrappers (DllImport statements) should follow the naming convention below:
NativeMethods – No suppress unmanaged code attribute, these are methods that can be used anywhere because a stack walk will be performed.
UnsafeNativeMethods – Has suppress unmanaged code attribute. These methods are potentially dangerous and any caller of these methods must do a full security review to ensure that the usage is safe and protected as no stack walk will be performed.
SafeNativeMethods – Has suppress unmanaged code attribute. These methods are safe and can be used fairly safely and the caller isn’t needed to do full security reviews even though no stack walk will be performed.
          All interop classes must be private, and all methods must be internal. In addition a private constructor should be provided to prevent instantiation.
File Organization

  • Source files should contain only one public type, although multiple internal classes are allowed
  • Source files should be given the name of the public class in the file
  • Directory names should follow the namespace for the class
  • For example, I would expect to find the public class “System.Windows.Forms.Control” in “System\Windows\Forms\Control.cs”…
  • Classes member should be alphabetized, and grouped into sections (Fields, Constructors, Properties, Events, Methods, Private interface implementations, Nested types)
  • Using statements should be inside the namespace declaration.

07 July 2014


            ADO.NET provides consistent access to data sources such as SQL Server and XML, and to data sources exposed through OLE DB and ODBC. Data-sharing consumer applications can use ADO.NET to connect to these data sources and retrieve, handle, and update the data that they contain.
ADO.NET 2.0 Features:

  • Enhancements to the DataSet and Datatable classes.
  • Optimized DataSet Serialization.
  • Conversion of a DataReader to a DataSet or a DataTable and vice versa.
  • Data Paging.
  • Batch Updates — Reduction in database roundtrips.
  • Asynchronous Data Access.
  • Common Provider Model.
  • Bulk Copy.

ADO.NET 3.5 Features:

  • Expanded Entity Framework (EF 4.0 and 1.0) Support .
  • Connection Pooling Performance Enhancements .
  • Increased Breadth of Support.


06 July 2014

Mutable and Immutable string in C#

Mutable -->means -->change in value
Immutable -->means -->No change in value

Event In C#

              Event is a kind of Notification(Information) giving one by one object to perform task. Event handling is not possible without delegate because it is delegate who will be responsible to call Event handler which even is fired.

04 July 2014

Partial Class In C#

                 we can break a large class code into small pieces by specifying more than one class with same but with partial keyword. In that case those same name classes will not be treated as different classes so when we will made the object of the class, we will get all the method and member for all same name class.

Method Hiding in C#

             We can predefined the method of parent class in child class by implementing the concept of method hiding. In method hiding the base(parent) class method is predefined in child class by specify new keyword.

03 July 2014

Run Function in SQL Server

Run Function in SQL Server
DECLARE <Variable> <Date Time>;
EXEC <variable> = <funciton name> '<Pass Value>';

PRINT <Variable>;

02 July 2014

types of delegates in c#

  • Single cast delegate
  • Double cast delegate

Single cast delegate                                                                        
One delegate object can call only one method, is known as single cast delegate.
Double cast delegate in c#
One delegate object can call more than one method in sequence ,is known as  multicast delegate.

01 July 2014

Method Parameters in C#

Value Parameters.
Reference Parameters.
Output Parameters.
Parameter arrays.

Value Parameters in C#
The Value  Parameters are used to pass for passing parameters into method by value.
Reference Parameters in C#
Reference parameters are used to pass parameters into Method by reference.
Output Parameters in C#
The Output parameters are used to pass results back to the calling Method.
use of  Parameter arrays in C#
A Method that can handle variable number of arguments,is known as parameter arrays.Parameter arrays  are declared using the keyword param.
Method Overloading in C#
To create More than one Method with same class name but with the different parameter lists and different definitions,is known as Method Overloading.

30 June 2014

Solve Unknown Device Issue

f you are getting “Unknown Device“ issue.
Please follow the step by step procedure:
1) Go to Windows Registry.
3) Click “SYSTEM”
4) Click “CurrentControlSet”
5) Click “Services”
6) Click “USBSTOR”
7) Check Data of “Start” (in the Right side of the Screen)
         Data is 0x00000003(3) -- USB Port works fine.
         Data is 0x00000004(4) -- USB Port doesn’t work fine.  

29 June 2014

keyword var and dynamic

A: Dynamic and var represent two completely different ideas.
var essentially asks the compiler to figure out the type of the variable based on the expression on the right hand side of the assignment statement. The variable is then treated exactly as if it were explicitly declared as the type of the expression. For example the following two statements are equivalent
var a = "foo";
string a = "foo";
The key to take away here is that "var" is 100% type safe and is a compile time operation.
Dynamic is in many ways the exact opposite of var. Using dynamic is essentially eliminating all type safety for that particular variable. It many ways it has no type. When you call a method or field on the variable, the determination on how to invoke that field occurs at runtime. For example
dynamic d = SomeOperation();
d.Foo(); // Will this fail or not?  Won't know until you run the program
The key to take away here is that "dynamic" is not type safe and is a runtime operation.

28 June 2014

set the process priority

o set the process priority, we  can set the Process.PriorityClass property. PriorityClass is captured in the ProcessPriorityClass enumeration, which lets us set the process priority to Idle, Normal, High, AboveNormal, BelowNormal, or RealTime.   Process.BasePriority is an integer value property and is read-only.
The following table shows the relationship between the BasePriority and PriorityClass values:
BasePriority            PriorityClass
4 Idle
8 Normal
13 High
24 RealTime
In Windows 98, and the Windows Millennium Edition Platform, setting the priority class to AboveNormal or BelowNormal causes an exception to be thrown.
How do I capture a screenshot of a process’s main window?
Here is one method to take a process screenshot.  We will use the process “notepad” for this example.   Please follow these steps:

1.   Use System.Diagnostics.Process.MainWindowHandle to get the process information we require to take a screenshot.
2.   Use the Windows API, SetForegroundWindow, to activate the target process.
3.   Pass the window handle to the first parameter of the Windows API GetWindowRect, to get the location information of the target process.
4.   Define the coordinates of the process window on the screen with the location information in step 3.
5.   Use the coordinates in step 4 and Graphics.CopyFromScreen to take the screenshot.

27 June 2014

Object Initializers and Collection Initializers

Object Initializers
Object initializers provide a way to assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor.
Object initializers with named types
Here we use auto-implemented properties featured in Visual C# 3.0 to define a class.  For details on auto-implemented properties, please check Auto-Implemented Properties (C# Programming Guide).
public class Point
    public int X { get; set; }
    public int Y { get; set; }
When we instantiate the objects of a Point class, we can use:
Point p = new Point();
p.X = 0;
p.Y = 1;
In Visual C# 3.0, there is a short way to achieve the same results:
// {X = 0, Y = 1} is field or property assignments
Point p = new Point { X = 0, Y = 1 };
In LINQ, we can use named object initializer like this:
The following example shows how we can use named object initializer with LINQ.  The example assumes that an object contains many fields and methods related to a product, but we are only interested in creating a sequence of objects that contain the product name and the unit price.
 var productInfos =
      from p in products
      select new { ProductName = p.ProductName, UnitPrice = p.UnitPrice };
Collection Initializers
Collection Initializers are similar in concept to Object Initializers.  They allow you to create and initialize a collection in one step.  By using a collection initializer you do not have to specify multiple calls to the Add method of the class in your source code; the compiler adds the calls.
List<int> numbers = new List<int> { 1, 100, 100 };
In fact, it is the short form of the following:
List<int> numbers = new List<int>();
Note: To be able to use a Collection Initializer on an object, the object must satisfy these two requirements:

  •          It must implement the IEnumerable interface.
  •          It must have a public Add() method.

26 June 2014

Implicit type var and Anonymous Types

                  Beginning in Visual C# 3.0, variables that are declared in the method scope can have an implicit type var.  We can use the modifier var to instruct the compiler to infer and assign the type, as shown below:
var i = 23;      // int i = 23;
var s = "Hello"; // string s = "Hello";
Arrays can also be declared with implicit typing as shown below:
var a = new[] { 1, 2, 3, 4 }; // int[]
var b = new[] { "hello", null, "world" }; // string[]
var c = new[] { a, new[] { 5, 6, 7, 8 } }; // single-dimension jagged array
Note: The following restrictions apply to implicitly-typed variable declarations:
  • var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null literal, because it does not have a type – like lambda expressions or method groups.  However, it can be initialized with an expression that happens to have the value null, as long as the expression has a type.
  • var cannot be used on fields in class scope.
  • Variables declared by using var cannot be used in their own initialization expression.  
  • In other words, var v = v++; will result in a compile-time error.
  • Multiple implicitly-typed variables cannot be initialized in the same statement.
  • If a type named var is in scope, then we will get a compile-time error if we attempt to initialize a local variable with the var keyword.
Anonymous Type
                 Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to first explicitly define a type.  The type name is generated by the compiler and is not available at the source code level.  The type of the properties is inferred by the compiler.
                The following example shows an anonymous type being initialized with two properties called Amount and Message:
var v = new { Amount = 123, Message = "Hello" };
              Anonymous types are class types that consist of one or more public read-only properties.   No other kinds of class members such as methods or events are allowed.
Note: Some rules on anonymous types:
  •  You must provide a name to a property that is being initialized with an expression, except in the situation that the second bullet describes.
  • If you do not specify member names in the anonymous type, the compiler gives the anonymous type members the same name as the variable, field or property being used to initialize them.    
  • Anonymous types are limited to a local scope.

25 June 2014

Can base/derived classes be exported to COM

  •  COM only deals with interfaces.   Base/derived classes have no meaning or functionality in COM.   Inheritance is not applicable either.
  • In COM, interfaces can inherit from one another.   However, the .NET implementation that exports the .NET interface to COM does not support inheritance.   Therefore, you must replicate any interface members in a base interface to the derived interface.
  • Moving members between a base and derived class will have no impact on what is visible to COM.
  • Only the programmer can define what is exposed to COM.   The complier will not use reflection or anything else to determine what should be exposed.
  • All COM classes have a single, default interface.   This is the interface that is normally used for an object.   A COM class can expose other interfaces but the COM client must then query for the interface.   In .NET the first COM visible interface is used as the default interface for a COM class. 

23 June 2014

Difference between Object and Dynamic

This keyword is nothing more than a shortcut for System.Object, which is the root type in the C# class hierarchy
Here is a short example that demonstrates some of the benefits and problems of using the object keyword.
object obj = 10;
obj = (int)obj + 10;
The dynamic type enables the operations in which it occurs to bypass compile-time type checking. Instead, these operations are resolved at run time. The dynamic type simplifies access to COM APIs such as the Office Automation APIs, and also to dynamic APIs such as IronPython libraries, and to the HTML Document Object Model (DOM).
dynamic dyn = 10;
dyn = dyn + 10;
dyn = 10.0;
dyn = dyn + 10;
dyn = "10";
dyn = dyn + 10;
This is one of the main differences between object and dynamic –
with dynamic you tell the compiler that the type of an object can be known only at run time, and the compiler doesn’t try to interfere.
As a result, you can write less code.
I want to emphasize that this is no more dangerous than using the original object keyword. However, it is not less dangerous either, so all the type-checking techniques that you need to use when operating with objects (such as reflection) have to be used for dynamic objects as well.
Refer : http://blogs.msdn.com/b/csharpfaq/archive/2010/01/25/what-is-the-difference-between-dynamic-and-object-keywords.aspx

22 June 2014

Define C#.net Advantages

  • XML documentation generated from source code comments. (This is coming in VB.NET with Whidbey (the code name for the next version of Visual Studio and .NET), and there are tools which will do it with existing VB.NET code already.)
  • Operator overloading - again, coming to VB.NET in Whidbey.
  • Language support for unsigned types (you can use them from VB.NET, but they aren't in the language itself). Again, support for these is coming to VB.NET in Whidbey.
  • The using statement, which makes unmanaged resource disposal simple.
  • Explicit interface implementation, where an interface which is already implemented in a base class can be reimplemented separately in a derived class. Arguably this makes the class harder to understand, in the same way that member hiding normally does.
  • Unsafe code. This allows pointer arithmetic etc, and can improve performance in some situations. However, it is not to be used lightly, as a lot of the normal safety of C# is lost (as the name implies). Note that unsafe code is still managed code, i.e. it is compiled to IL, JITted, and run within the CLR.

21 June 2014

Define VB.net Advantages

  • Support for optional parameters - very handy for some COM interoperability
  • Support for late binding with Option Strict off - type safety at compile time goes out of the window, but legacy libraries which don't have strongly typed interfaces become easier to use.
  • Support for named indexers (aka properties with parameters).
  • Various legacy VB functions (provided in the Microsoft.VisualBasic namespace, and can be used by other languages with a reference to the Microsoft.VisualBasic.dll). Many of these can be harmful to performance if used unwisely, however, and many people believe they should be avoided for the most part.
  • The with construct: it's a matter of debate as to whether this is an advantage or not, but it's certainly a difference.
  • Simpler (in expression - perhaps more complicated in understanding) event handling, where a method can declare that it handles an event, rather than the handler having to be set up in code.
  • The ability to implement interfaces with methods of different names. (Arguably this makes it harder to find the implementation of an interface, however.)
  • Catch ... When ... clauses, which allow exceptions to be filtered based on runtime expressions rather than just by type.
  • The VB.NET part of Visual Studio .NET compiles your code in the background. While this is considered an advantage for small projects, people creating very large projects have found that the IDE slows down considerably as the project gets larger.

20 June 2014

use an alias for a namespace or class

Use the using directive to create an alias for a long namespace or class name. You can then use it anywhere you normally would have used that class or namespace. The using alias has a scope within the namespace you declare it in. Sample

// Namespace:
using act = System.Runtime.Remoting.Activation;
// Class:
using list = System.Collections.ArrayList;
list l = new list(); // Creates an ArrayList
act.UrlAttribute foo; // Equivalent to System.Runtime.Remoting.Activation.UrlAttribute foo

19 June 2014

Simple Threading in C#.net

Today ,we will discuss about small threading program in C#.Net

using System;
using System.Threading;

class ThreadTest
    public void Run()
        Console.WriteLine("Run Called");

    public static void Main(String[] args)
        ThreadTest b = new ThreadTest();
        Thread t = new Thread(new ThreadStart(b.Run));

        Console.WriteLine("Thread 't' started.");
        Console.WriteLine("There is no telling when " +
                          "'Run' will be invoked. ");


        Console.WriteLine("Thread 't' has ended.");

18 June 2014

SQL Server Interview Questions

1. What are the basic functions for master, msdb, model, tempdb and resource databases?
The master database holds information for all databases located on the SQL Server instance and is theglue that holds the engine together. Because SQL Server cannot start without a functioning masterdatabase, you must administer this database with care.
The msdb database stores information regarding database backups, SQL Agent information, DTS packages, SQL Server jobs, and some replication information such as for log shipping.
The tempdb holds temporary objects such as global and local temporary tables and stored procedures.
The model is essentially a template database used in the creation of any new user database created in the instance.
The resoure Database is a read-only database that contains all the system objects that are included with SQL Server. SQL Server system objects, such as sys.objects, are physically persisted in the Resource database, but they logically appear in the sys schema of every database. The Resource database does not contain user data or user metadata.
2. What is Service Broker?
Service Broker is a message-queuing technology in SQL Server that allows developers to integrate SQL Server fully into distributed applications. Service Broker is feature which provides facility to SQL Server to send an asynchronous, transactional message. it allows a database to send a message to another database without waiting for the response, so the application will continue to function if the remote database is temporarily unavailable.
3. Where SQL server user names and passwords are stored in SQL server?
They get stored in System Catalog Views sys.server_principals and sys.sql_logins.
4. What is Policy Management?
Policy Management in SQL SERVER 2008 allows you to define and enforce policies for configuring and managing SQL Server across the enterprise. Policy-Based Management is configured in SQL Server Management Studio (SSMS). Navigate to the Object Explorer and expand the Management node and the Policy Management node; you will see the Policies, Conditions, and Facets nodes.
5. What is Replication and Database Mirroring?
Database mirroring can be used with replication to provide availability for the publication database. Database mirroring involves two copies of a single database that typically reside on different computers. At any given time, only one copy of the database is currently available to clients which are known as the principal database. Updates made by clients to the principal database are applied on the other copy of the database, known as the mirror database. Mirroring involves applying the transaction log from every insertion, update, or deletion made on the principal database onto the mirror database.
6. What are Sparse Columns?
A sparse column is another tool used to reduce the amount of physical storage used in a database. They are the ordinary columns that have an optimized storage for null values. Sparse columns reduce the space requirements for null values at the cost of more overhead to retrieve nonnull values.
7. What does TOP Operator Do?
The TOP operator is used to specify the number of rows to be returned by a query. The TOP operator has new addition in SQL SERVER 2008 that it accepts variables as well as literal values and can be used with INSERT, UPDATE, and DELETES statements.
8. What is CTE?
CTE is an abbreviation Common Table Expression. A Common Table Expression (CTE) is an expression that can be thought of as a temporary result set which is defined within the execution of a single SQL statement. A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query.
9. What is MERGE Statement?
MERGE is a new feature that provides an efficient way to perform multiple DML operations. In previous versions of SQL Server, we had to write separate statements to INSERT, UPDATE, or DELETE data based on certain conditions, but now, using MERGE statement we can include the logic of such data modifications in one statement that even checks when the data is matched then just update it and when unmatched then insert it. One of the most important advantages of MERGE statement is all the data is read and processed only once.
10. What is Filtered Index?
Filtered Index is used to index a portion of rows in a table that means it applies filter on INDEX which improves query performance, reduce index maintenance costs, and reduce index storage costs compared with full-table indexes. When we see an Index created with some where clause then that is actually a FILTERED INDEX.
11. Which are new data types introduced in SQL SERVER 2008?
The GEOMETRY Type: The GEOMETRY data type is a system .NET common language runtime (CLR) data type in SQL Server. This type represents data in a two-dimensional Euclidean coordinate system.
The GEOGRAPHY Type: The GEOGRAPHY datatype’s functions are the same as with GEOMETRY. The difference between the two is that when you specify GEOGRAPHY, you are usually specifying points in terms of latitude and longitude.
New Date and Time Datatypes: SQL Server 2008 introduces four new datatypes related to date and time: DATE, TIME, DATETIMEOFFSET, and DATETIME2.
DATE: The new DATE type just stores the date itself. It is based on the Gregorian calendar and handles years from 1 to 9999.
TIME: The new TIME (n) type stores time with a range of 00:00:00.0000000 through 23:59:59.9999999. The precision is allowed with this type. TIME supports seconds down to 100 nanoseconds. The n in TIME (n) defines this level of fractional second precision, from 0 to 7 digits of precision.
The DATETIMEOFFSET Type: DATETIMEOFFSET (n) is the time-zone-aware version of a datetime datatype. The name will appear less odd when you consider what it really is: a date + a time + a time-zone offset. The offset is based on how far behind or ahead you are from Coordinated Universal Time (UTC) time.
The DATETIME2 Type: It is an extension of the datetime type in earlier versions of SQL Server. This new datatype has a date range covering dates from January 1 of year 1 through December 31 of year 9999. This is a definite improvement over the 1753 lower boundary of the datetime datatype. DATETIME2 not only includes the larger date range, but also has a timestamp and the same fractional precision that TIME type provides
12. What are the Advantages of using CTE?
Using CTE improves the readability and makes maintenance of complex queries easy.
The query can be divided into separate, simple, logical building blocks which can be then used to build more complex CTEs until final result set is generated.
CTE can be defined in functions, stored procedures, triggers or even views.
After a CTE is defined, it can be used as a Table or a View and can SELECT, INSERT, UPDATE or DELETE Data.
13. What is CLR?
In SQL Server 2008, SQL Server objects such as user-defined functions can be created using such CLR languages. This CLR language support extends not only to user-defined functions, but also to stored procedures and triggers. You can develop such CLR add-ons to SQL Server using Visual Studio 2008.
14. What are synonyms?
Synonyms give you the ability to provide alternate names for database objects. You can alias object names; for example, using the Employee table as Emp. You can also shorten names. This is especially useful when dealing with three and four part names; for example, shortening server.database.owner.object to object.
15. What is LINQ?
Language Integrated Query (LINQ) adds the ability to query objects using .NET languages. The LINQ to SQL object/relational mapping (O/RM) framework provides the following basic features:
Tools to create classes (usually called entities) mapped to database tables
Compatibility with LINQ’s standard query operations
The DataContext class, with features such as entity record monitoring, automatic SQL statement generation, record concurrency detection, and much more
16. What is Isolation Levels?
Transactions specify an isolation level that defines the degree to which one transaction must be isolated from resource or data modifications made by other transactions. Isolation levels are described in terms of which concurrency side-effects, such as dirty reads or phantom reads, are allowed.
Transaction isolation levels control:
Whether locks are taken when data is read, and what type of locks are requested.
How long the read locks are held.
Whether a read operation referencing rows modified by another transaction:
Blocks until the exclusive lock on the row is freed.
Retrieves the committed version of the row that existed at the time the statement or transaction started.
Reads the uncommitted data modification.
17. What is use of EXCEPT Clause?
EXCEPT clause is similar to MINUS operation in Oracle. The EXCEPT query and MINUS query returns all rows in the first query that are not returned in the second query. Each SQL statement within the EXCEPT query and MINUS query must have the same number of fields in the result sets with similar data types.
18. How would you handle error in SQL SERVER 2008?
SQL Server now supports the use of TRY…CATCH con handling. TRY…CATCH lets us build error handling at the level we need, in the way w to, by setting a region where if any error occurs, it will break out of the region and head to an error handler.
The basic structure is as follows:
19. What is RAISEERROR?
RaiseError generates an error message and initiates error processing for the session. RAISERROR can either reference a user-defined message stored in the sys.messages catalog view or build a message dynamically. The message is returned as a server error message to the calling application or to an associated CATCH block of a TRY | CATCH construct.
20. How to rebuild Master Database?
Master database is system database and it contains information about running server’s configuration. When SQL Server 2005 is installed it usually creates master, model, msdb, tempdb resource and distribution system database by default. Only Master database is th one which is absolutely must have database. Without Master database SQL Server cannot be started. This is the reason it is extremely important to backup Master database.
To rebuild the Master database, Run Setup.exe, verify, and repair a SQL Server instance, and rebuild the system databases. This procedure is most often used to rebuild the master database for a corrupted installation of SQL Server.
21. What is XML Datatype?
The xml data type lets you store XML documents and fragments in a SQL Server database. An XML fragment is an XML instance that is missing a single top-level element. You can create columns and variables of the xml type and store XML instances in them. The xml data type and associated methods help integrate XML into the relational framework of S Server.
22. What is Data Compression?
In SQL SERVE 2008 Data Compression comes in two flavors:
Row Compression: Row compression changes the format of physical storage of data. It minimize the metadata (column information, length, offsets etc) associated with each record. Numeric data types and fixed length strings are stored in variable-length storage format, just like Varchar.
Page Compression: Page compression allows common data to be shared between rows for a given page. Its uses the following techniques to compress data:Dictionary Compression: Dictionary compression searches for duplicate values throughout the page and stores them in CI. The main difference between prefix and dictionary compression is that prefix is only restricted to one column while dictionary is applicable to the complete page.
Row compression.
Prefix Compression. For every column in a page duplicate prefixes are identified. These prefixes are saved in compression information headers (CI) which resides after page header. A reference number is assigned to these prefixes and that reference number is replaced where ever those prefixes are being used.
23. What is Catalog Views?
Catalog views return information that is used by the SQL Server Database Engine. Catalog Views are the most general interface to the catalog metadata and provide the most efficient way to obtain, transform, and present customized forms of this information. All user- available catalog metadata is exposed through catalog views.
24. What is PIVOT and UNPIVOT?
A Pivot Table can automatically sort, count, and total the data stored in one table or spreadsheet and create a second table displaying the summarized data. The PIVOT operator turns the values of a specified column into column names, effectively rotating a table.
UNPIVOT table is reverse of PIVOT Table.
25. What is Dirty Read ?
A dirty read occurs when two operations say, read and write occurs together giving the incorrect or unedited data. Suppose, A has changed a row, but has not committed the changes. B reads the uncommitted data but his view of the data may be wrong so that is Dirty Read.
26. What is Aggregate Functions?
Aggregate functions perform a calculation on a set of values and return a single value. Aggregate functions ignore NULL values except COUNT function. HAVING clause is used, along with GROUP BY, for filtering query using aggregate values.
Following functions are aggregate functions.
27. What do you mean by Table Sample?
TABLESAMPLE allows you to extract a sampling of rows from a table in the FROM clause. The rows retrieved are random and they are not in any order. This sampling can be based on a percentage of number of rows. You can use TABLESAMPLE when only a sampling of rows is necessary for the application instead of a full result set.
28. What is the difference between UNION and UNION ALL?
UNION The UNION command is used to select related information from two tables, much like the JOIN command. However, when using the UNION command all selected columns need to be of the same data type. With UNION, only distinct values are selected.
UNION ALL The UNION ALL command is equal to the UNION command, except that UNION ALL selects all values.
The difference between Union and Union all is that Union all will not eliminate duplicate rows, instead it just pulls all rows from all tables fitting your query specifics and combines them into a table.
29. What is B-Tree?
The database server uses a B-tree structure to organize index information. B-Tree generally has following types of index pages or nodes:
root node: A root node contains node pointers to branch nodes which can be only one.
branch node: A branch node contains pointers to leaf nodes or other branch nodes which can be two or more.
leaf nodes: A leaf node contains index items and orizantal pointers to other leaf nodes which can be many.

17 June 2014

Define variable and constant.

A variable can be defined as a meaningful name that is given to a data storage location in the computer memory that contains a value. Every variable associated with a data type determines what type of value can be stored in the variable, for example an integer, such as 100, a decimal, such as 30.05, or a character, such as ‘A’.
You can declare variables by using the following syntax:
<Data_type> <variable_name> ;

A constant is similar to a variable except that the value, which you assign to a constant, cannot be changed, as in case of a variable. Constants must be initialized at the same time they are declared. You can declare constants by using the following syntax:

const int interestRate = 10;

16 June 2014

Data Types and Types of Data Types

A data type is a data storage format that can contain a specific type or range of values. Whenever you declare variables, each variable must be assigned a specific data type. Some common data types include integers, floating point, characters, and strings. The following are the two types of data types available in .NET:

Value type - Refers to the data type that contains the data. In other words, the exact value or the data is directly stored in this data type. It means that when you assign a value type variable to another variable, then it copies the value rather than copying the reference of that variable. When you create a value type variable, a single space in memory is allocated to store the value (stack memory). Primitive data types, such as int, float, and char are examples of value type variables.

Reference type - Refers to a data type that can access data by reference. Reference is a value or an address that accesses a particular data by address, which is stored elsewhere in memory (heap memory). You can say that reference is the physical address of data, where the data is stored in memory or in the storage device. Some built-in reference types variables in .Net are string, array, and object.

15 June 2014

Which statement is used to replace multiple if-else statements in code.

                 In Visual Basic, the Select-Case statement is used to replace multiple If – Else statements and in C#, the switch-case statement is used to replace multiple if-else statements.

14 June 2014

String Method in C#

There are some important string methods in C#.
1Copy()Create a new string by copying another string.
2CopyTo()Copies specified number of characters to an array of Unicode character.
3Compare()It is used for compare two string.
4CompareTo()It is used to compare the current instance with another instance.
5Equals()It determines if two string are equal.
6Insert()Return a new string with a substring insert ed at a specified location.
7Remove()It is used for delete the characters from the string.
8Join()It is used to join an array string together.
9Replace()It is used to replace all instances of a character with a new character.
10Split()It is used for splitting the string.
11Trim()It is used to remove white space from the string.
12Concat()It is used to concatenates two or more strings.

While Vs For Loop in C#

               The while and for loops are used to execute those units of code that need to be repeatedly executed, unless the result of the specified condition evaluates to false. The only difference between the two is in their syntax. The for loop is distinguished by setting an explicit loop variable.

13 June 2014

Constants Vs Read-only variables

1Constants are dealt with at compile-time.Read-only variables are evaluated at runtime.
2Constants supports value-type variables.Read-only variables can hold reference type variables.
3Constants should be used when it is very unlikely that the value will ever change.Read-only variables should be used when run-time calculation is required.

12 June 2014

sub-procedure Vs function

The sub-procedure is a block of multiple visual basic statements within Sub and End Sub statements. It is used to perform certain tasks, such as changing properties of objects, receiving or processing data, and displaying an output. You can define a sub-procedure anywhere in a program, such as in modules, structures, and classes.
          We can also provide arguments in a sub-procedure; however, it does not return a new value.
The function is also a set of statements within the Function and End Function statements. It is similar to sub-procedure and performs the same task. The main difference between a function and a sub-procedure is that sub-procedures do not return a value while functions do.

11 June 2014

How to setup main form window to allow resizing

          Setting the AutoSizeMode property to GrowAndShrink will prevent you from being able to resize the window manually so don't set it to this value.
           Just set the Height and Width properties of the window to specify the default size and then constraint the size by setting the MaxiumSize and MinimumSize properties:

10 June 2014

OOPS Interview Questions and Answers

1. What is object-oriented programming (OOP)?
            OOP is a technique to develop logical modules, such as classes that contain properties, methods, fields, and events. An object is created in the program to represent a class. Therefore, an object encapsulates all the features, such as data and behavior that are associated to a class. OOP allows developers to develop modular programs and assemble them as software. Objects are used to access data and behaviors of different software modules, such as classes, namespaces, and sharable assemblies. .NET Framework supports only OOP languages, such as Visual Basic .NET, Visual C#, and Visual C++.
2. What is a class?
           A class describes all the attributes of objects, as well as the methods that implement the behavior of member objects. It is a comprehensive data type, which represents a blue print of objects. It is a template of object. A class can be defined as the primary building block of OOP. It also serves as a template that describes the properties, state, and behaviors common to a particular group of objects.A class contains data and behavior of an entity. For example, the aircraft class can contain data, such as model number, category, and color and behavior, such as duration of flight, speed, and number of passengers. A class inherits the data members and behaviors of other classes by extending from them.
3. What is an object?
           They are instance of classes. It is a basic unit of a system. An object is an entity that has attributes, behavior, and identity. Attributes and behavior of an object are defined by the class definition.

4. What is the relationship between a class and an object?

A class acts as a blue-print that defines the properties, states, and behaviors that are common to a number of objects. An object is an instance of the cass. For example, you have a class called Vehicle and Car is the object of that class. You can create any number of objects for the class named Vehicle, such as Van, Truck, and Auto.

The new operator is used to create an object of a class. When an object of a class is instantiated, the system allocates memory for every data member that is present in the class.

5. Explain the basic features of OOPs.

The following are the four basic features of OOP:

Abstraction - Refers to the process of exposing only the relevant and essential data to the users without showing unnecessary information.
Polymorphism - Allows you to use an entity in multiple forms.
Encapsulation - Prevents the data from unwanted access by binding of code and data in a single unit called object.
Inheritance - Promotes the reusability of code and eliminates the use of redundant code. It is the property through which a child class obtains all the features defined in its parent class. When a class inherits the common properties of another class, the class inheriting the properties is called a derived class and the class that allows inheritance of its common properties is called a base class.

6. What is the difference between arrays and collection?


You need to specify the size of an array at the time of its declaration. It cannot be resized dynamically.
The members of an array should be of the same data type.

The size of a collection can be adjusted dynamically, as per the user’s requirement. It does not have fixed size.
Collection can have elements of different types.
7. What are collections and generics?

A collection can be defined as a group of related items that can be referred to as a single unit. TheSystem.Collections namespace provides you with many classes and interfaces. Some of them are - ArrayList,List, Stack, ICollection, IEnumerable, and IDictionary. Generics provide the type-safety to your class at the compile time. While creating a data structure, you never need to specify the data type at the time of declaration. The System.Collections.Generic namespace contains all the generic collections.

8. How can you prevent your class to be inherited further?

You can prevent a class from being inherited further by defining it with the sealed keyword.

9. What is the index value of the first element in an array?

In an array, the index value of the first element is 0 (zero).

10. Can you specify the accessibility modifier for methods inside the interface?

All the methods inside an interface are always public, by default. You cannot specify any other access modifier for them.

11. Is it possible for a class to inherit the constructor of its base class?

No, a class cannot inherit the constructor of its base class.

12. How is method overriding different from method overloading?

Overriding involves the creation of two or more methods with the same name and same signature in different classes (one of them should be parent class and other should be child). 

Overloading is a concept of using a method at different places with same name and different signatures within the same class.

13. What is the difference between a class and a structure?


A class is a reference type.
While instantiating a class, CLR allocates memory for its instance in heap.
Classes support inheritance.
Variables of a class can be assigned as null.
Class can contain constructor/destructor.

A structure is a value type.
In structure, memory is allocated on stack.
Structures do not support inheritance.
Structure members cannot have null values.
Structure does not require constructor/destructor and members can be initialiazed automatically.

14. What are similarities between a class and a structure.

Structures and classes are the two most important data structures that are used by programmers to build modular programs by using OOP languages, such as Visual Basic .NET, and Visual C#. The following are some of the similarities between a class and a structure:

Access specifiers, such as public, private, and protected, are identically used in structures and classes to restrict the access of their data and methods outside their body.
The access level for class members and struct members, including nested classes and structs, is private by default. Private nested types are not accessible from outside the containing type.
Both can have constructors, methods, properties, fields, constants, enumerations, events, and event handlers.
Both structures and classes can implement interfaces to use multiple-inheritance in code.
Both structures and classes can have constructors with parameter.
Both structures and classes can have delegates and events.

15. What is a multicast delegate?

Each delegate object holds reference to a single method. However, it is possible for a delegate object to hold references of and invoke multiple methods. Such delegate objects are called multicast delegates or combinable delegates.

16. Can you declare an overridden method to be static if the original method is not static?

No. Two virtual methods must have the same signature.

17. Why is the virtual keyword used in code?

The virtual keyword is used while defining a class to specify that the methods and the properties of that class can be overridden in derived classes.

18. Can you allow a class to be inherited, but prevent a method from being overridden in C#?

Yes. Just declare the class public and make the method sealed.

19. Define enumeration?

Enumeration is defined as a value type that consists of a set of named values. These values are constants and are called enumerators. An enumeration type is declared using the enum keyword. Each enumerator in an enumeration is associated with an underlying type that is set, by default, on the enumerator. The following is an example that creates an enumeration to store different varieties of fruits:

enum Fruits {Mango, Apple, orange, Guava}; 

In the preceding example, an enumeration Fruits is created, where number 0 is associated with Mango, number 1with Apple, number 2 with Orange, and number 3 with Guava. You can access the enumerators of an enumeration by these values.

20. In which namespace, all .NET collection classes are contained?

The System.Collections namespace contains all the collection classes.

21. Is it a good practice to handle exceptions in code?

Yes, you must handle exceptions in code so that you can deal with any unexpected situations that occur when a program is running. For example, dividing a number by zero or passing a string value to a variable that holds an integer value would result in an exception.

22. Explain the concept of constructor?

Constructor is a special method of a class, which is called automatically when the instance of a class is created. It is created with the same name as the class and initializes all class members, whenever you access the class. The main features of a constructor are as follows:

Constructors do not have any return type
Constructors are always public
It is not mandatory to declare a constructor; it is invoked automatically by .NET Framework.

23. Can you inherit private members of a class?

No, you cannot inherit private members of a class because private members are accessible only to that class and not outside that class.

24. Does .NET support multiple inheritance?

.NET does not support multiple inheritance directly because in .NET, a class cannot inherit from more than one class. .NET supports multiple inheritance through interfaces.

25. How has exception handling changed in .NET Framework 4.0?

In .NET 4.0, a new namespace, System.Runtime.ExceptionServices, has been introduced which contains the following classes for handling exceptions in a better and advanced manner:

HandleProcessCorruptedStateExceptionsAttribute Class – Enables managed code to handle the corrupted state exceptions that occur in an operating system. These exceptions cannot be caught by specifying the try…catch block. To handle such exceptions, you can apply this attribute to the method that is assigned to handle these exceptions.
FirstChanceExceptionEventArgs Class – Generates an event whenever a managed exception first occurs in your code, before the common language runtime begins searching for event handlers.

26. What is a delegate?

A delegate is similar to a class that is used for storing the reference to a method and invoking that method at runtime, as required. A delegate can hold the reference of only those methods whose signatures are same as that of the delegate. Some of the examples of delegates are type-safe functions, pointers, or callbacks.

27. What is the syntax to inherit from a class in C#?

When a class is derived from another class, then the members of the base class become the members of the derived class. The access modifier used while accessing members of the base class specifies the access status of the base class members inside the derived class.

The syntax to inherit a class from another class in C# is as follows: 
class MyNewClass : MyBaseclass

28. State the features of an interface.

An interface is a template that contains only the signature of methods. The signature of a method consists of the numbers of parameters, the type of parameter (value, reference, or output), and the order of parameters. An interface has no implementation on its own because it contains only the definition of methods without any method body. An interface is defined using the interface keyword. Moreover, you cannot instantiate an interface. The various features of an interface are as follows:

An interface is used to implement multiple inheritance in code. This feature of an interface is quite different from that of abstract classes because a class cannot derive the features of more than one class but can easily implement multiple interfaces.
It defines a specific set of methods and their arguments.
Variables in interface must be declared as public, static, and final while methods must be public andabstract.
A class implementing an interface must implement all of its methods.
An interface can derive from more than one interface.

29. Can you use the ‘throws’ clause to raise an exception?

No, the throws clause cannot be used to raise an exception. The throw statement signals the occurrence of an exception during the execution of a program. When the program encounters a throw statement, the method terminates and returns the error to the calling method.

30. Define an array.

An array is defined as a homogeneous collection of elements, stored at contiguous memory locations, which can be referred by the same variable name. All the elements of an array variable can be accessed by index values. An Index value specifies the position of a particular element in an array variable.

31. What are methods?

Methods are the building blocks of a class, in which they are linked together to share and process data to produce the result. In other words, a method is a block of code that contains a series of statements and represents the behavior of a class. While declaring a method you need to specify the access specifier, the return value, the name of the method, and the method parameters. All these combined together is called the signature of the method.

32. What is a namespace?

Namespace is considered as a container that contains functionally related group of classes and other types.

33. Do events have return type?

No, events do not have return type.

34. What is the function of the Try-Catch-Finally block?

The try block encloses those statements that can cause exception and the catch block handles the exception, if it occurs. Catch block contains the statements that have to be executed, when an exception occurs. The finally block always executes, irrespective of the fact whether or not an exception has occurred. The finally block is generally used to perform the cleanup process. If any exception occurs in the try block, the program control directly transfers to its corresponding catch block and later to the finally block. If no exception occurs inside the try block, then the program control transfers directly to the finally block.

35. How can you prevent a class from overriding in C# and Visual Basic?

You can prevent a class from overriding in C# by using the sealed keyword; whereas, the NotInheritablekeyword is used to prevent a class from overriding in Visual Basic.

36. What are abstract classes? What are the distinct characteristics of an abstract class?

An abstract class is a class that cannot be instantiated and is always used as a base class.
The following are the characteristics of an abstract class:

You cannot instantiate an abstract class directly. This implies that you cannot create an object of the abstract class; it must be inherited.
You can have abstract as well as non-abstract members in an abstract class.
You must declare at least one abstract method in the abstract class.
An abstract class is always public.
An abstract class is declared using the abstract keyword.
The basic purpose of an abstract class is to provide a common definition of the base class that multiple derived classes can share.

37. Give a brief description of properties in C# and the advantages that are obtained by using them in programs.

In C#, a property is a way to expose an internal data element of a class in a simple and intuitive manner. In other words, it is a simple extension of data fields. You can create a property by defining an externally available name and then writing the set and get property accessors. The get property accessor is used to return the property value. The set property accessor is used to assign a new value to the property.

38. Explain different types of inheritance.

Inheritance in OOP is of four types:

Single inheritance - Contains one base class and one derived class
Hierarchical inheritance - Contains one base class and multiple derived classes of the same base class
Multilevel inheritance - Contains a class derived from a derived class
Multiple inheritance - Contains several base classes and a derived class
All .NET languages supports single, hierarchical, and multilevel inheritance. They do not support multiple inheritance because in these languages, a derived class cannot have more than one base class. However, you can implement multiple inheritance in.NET through interfaces. 

39. You have defined a destructor in a class that you have developed by using the C# programming language, but the destructor never executed. Why did the destructor not execute?

The runtime environment automatically invokes the destructor of a class to release the resources that are occupied by variables and methods of an object. However, in C#, programmers cannot control the timing for invoking destructors, as Garbage Collector is only responsible for releasing the resources used by an object. Garbage Collector automatically gets information about unreferenced objects from .NET’s runtime environment and then invokes the Finalize()method.

Although, it is not preferable to force Garbage Collector to perform garbage collection and retrieve all inaccessible memory, programmers can use the Collect() method of the Garbage Collector class to forcefully execute Garbage Collector.

40. What is a hashtable?

Hashtable is a data structure that implements the IDictionary interface. It is used to store multiple items and each of these items is associated with a unique string key. Each item can be accessed using the key associated with it. In short, hashtable is an object holding the key-value pairs.

41. Can users define their own exceptions in code?

Yes, customized exceptions can be defined in code by deriving from the System.Exception class.

42. Is it possible to execute two catch blocks?

You are allowed to include more than one catch block in your program; however, it is not possible to execute them in one go. Whenever, an exception occurs in your program, the correct catch block is executed and the control goes to the finally block.

43. What do you mean by data encapsulation?

Data encapsulation is a concept of binding data and code in single unit called object and hiding all the implementation details of a class from the user. It prevents unauthorized access of data and restricts the user to use the necessary data only.

44. What is the difference between procedural and object-oriented programming?

Procedural programming is based upon the modular approach in which the larger programs are broken into procedures. Each procedure is a set of instructions that are executed one after another. On the other hand, OOP is based upon objects. An object consists of various elements, such as methods and variables.

Access modifiers are not used in procedural programming, which implies that the entire data can be accessed freely anywhere in the program. In OOP, you can specify the scope of a particular data by using access modifiers - public,private, internal, protected, and protected internal.

45. Explain the concept of destructor?

A destructor is a special method for a class and is invoked automatically when an object is finally destroyed. The name of the destructor is also same as that of the class but is followed by a prefix tilde (~).

A destructor is used to free the dynamic allocated memory and release the resources. You can, however, implement a custom method that allows you to control object destruction by calling the destructor.

The main features of a destructor are as follows:

Destructors do not have any return type
Similar to constructors, destructors are also always public
Destructors cannot be overloaded.

46. Can you declare a private class in a namespace?

The classes in a namespace are internal, by default. However, you can explicitly declare them as public only and not as private, protected, or protected internal. The nested classes can be declared as private,protected, or protected internal.

47. A structure in C# can implement one or more interfaces. Is it true or false?

Yes, it is true. Like classes, in C#, structures can implement one or more interfaces.

48. What is a static constructor?

Static constructors are introduced with C# to initialize the static data of a class. CLR calls the static constructor before the first instance is created.

The static constructor has the following features:

No access specifier is required to define it.
You cannot pass parameters in static constructor.
A class can have only one static constructor.
It can access only static members of the class.
It is invoked only once, when the program execution begins.
49. What are the different ways a method can be overloaded?

The different ways to overload a method are given as follows:

By changing the number of parameters used
By changing the order of parameters
By using different data types for the parameters

50. Differentiate between an abstract class and an interface.

Abstract Class:

A class can extend only one abstract class
The members of abstract class can be private as well as protected.
Abstract classes should have subclasses
Any class can extend an abstract class.
Methods in abstract class can be abstract as well as concrete.
There can be a constructor for abstract class.
The class extending the abstract class may or may not implement any of its method.
An abstract class can implement methods.

A class can implement several interfaces
An interface can only have public members.
Interfaces must have implementations by classes
Only an interface can extend another interface.
All methods in an interface should be abstract
Interface does not have constructor.
All methods of interface need to be implemented by a class implementing that interface.
Interfaces cannot contain body of any of its method.

51. What are queues and stacks?

Stacks refer to a list in which all items are accessed and processed on the Last-In-First-Out (LIFO) basis. In a stack, elements are inserted (push operation) and deleted (pop operation) from the same end called top. 

Queues refer to a list in which insertion and deletion of an item is done on the First-In-First-Out (FIFO) basis. The items in a queue are inserted from the one end, called the rear end, and are deleted from the other end, called thefront end of the queue.

52. Define an event.

Whenever an action takes place in a class, that class provides a notification to other classes or objects that are assigned to perform particular tasks. These notifications are called events. For example, when a button is clicked, the class generates an event called Click. An event can be declared with the help of the event keyword.

53. What are structures?

Structure is a heterogeneous collection of elements referenced by the same name. A structure is declared using the struct keyword. The following is an example that creates a structure to store an employee’s information:

struct emp
 fixed int empID[15];
 fixed char name[30];
 fixed char addr[50];
 fixed char dept[15];
 fixed char desig[15];
The preceding example defines a structure emp and the members of this structure specify the information of an employee. 

54. When do you really need to create an abstract class?

We define abstract classes when we define a template that needs to be followed by all the derived classes.