h1.post-title { color:orange; font-family:verdana,Arial; font-weight:bold; padding-bottom:5px; text-shadow:#64665b 0px 1px 1px; font-size:32px; } -->

Pages

Solve Unknown Device Issue

Please follow the step by step procedure

  • Go to Windows Registry. 
  • Click “HKEY_LOCAL_MACHINE” 
  • Click “SYSTEM” 
  • Click “CurrentControlSet” 
  • Click “Services” 
  • Click “USBSTOR” 
  • 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.

keyword var and dynamic

var:
            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:
        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.

Set the process priority

                   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:
S.No BasePriority PriorityClass
1 4 Idle.
2 8 Normal.
3 13 High.
4 24 RealTime.

Note:
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.

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>();
numbers.Add(1);
numbers.Add(10);
numbers.Add(100);
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.


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.


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. 


Difference between Object and Dynamic

object
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;
Console.WriteLine(obj.GetType());
obj = (int)obj + 10;
Dynamic
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;
Console.WriteLine(dyn.GetType());
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

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.


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.

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

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");
        Thread.Sleep(10000);
    }

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

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

        t.Join();

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

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:
BEGIN TRY
stmts..
END TRY
BEGIN CATCH
stmts..
END CATCH
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.
AVG, MIN CHECKSUM_AGG, SUM, COUNT, STDEV, COUNT_BIG, STDEVP, GROUPING, VAR, MAX. VARP
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.

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;

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.

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.

String Method in C#

There are some important string methods in C#.
S.NoMethodsMeaning
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.


Constants Vs Read-only variables

S.NoConstantsRead-only
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.

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.

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:

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?

Array:

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.
Collection:

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?

Class:

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.
Structure:

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.
Interface

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.

System.UnauthorizedAccessException: Access to the path denied in C#.net

Delete
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
Copy
File.Copy(file, dest, true);
File.SetAttributes(dest, FileAttributes.Normal);

Set File Readonly in C#.Net

Call this Code for Set File ReadOnly Mode using C#.Net:
public void SetReadOnly(string fileName)
{
FileInfo fi = new FileInfo(fileName);
fi.IsReadOnly = true;
}

Create INI File in C#.Net

Today , we will discuss about Create,Read and Write INI File in C#.Net


Create a Class file for INI File Operation

Class file name : INIOperation.cs
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Text;
 #region Declarations
        private string path = string.Empty;
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
        int count = 0;
        private static string _SDevice = string.Empty;
string GetInputPath  =string.Empty;
string GetOutputPath =string.Empty;
        #endregion


     #region Constructor
        /// <summary>
        /// INI Operation
        /// </summary>
        /// <param name="INIPath">Pass INI Path</param>
        public INIOperation(string INIPath)
        {
            if (!File.Exists(INIPath))
            {
                path = INIPath;
            }
            else
            {
                File.SetAttributes(INIPath, FileAttributes.Normal);
                File.Delete(INIPath);
                path = INIPath;
            }
        }
        /// <summary>
        /// INI OPperation
        /// </summary>
        /// <param name="INIPath">Pass INI Path</param>
        /// <param name="mode">Pass Mode [Read]</param>
        public INIOperation(string INIPath, string mode)
        {
            if (mode == "Read")
            {
                path = INIPath;
            }
        }
        #endregion Constructor

        #region Functions/Methods    
        /// <summary>
        /// Write Data to the INI File
        /// </summary>
        /// <PARAM name="Section"></PARAM>
        /// Section name
        /// <PARAM name="Key"></PARAM>
        /// Key Name
        /// <PARAM name="Value"></PARAM>
        /// Value Name
        public void IniWriteValue(string Section, string Key, string Value)
        {
            WritePrivateProfileString(Section, Key, Value, this.path);
        }
        /// <summary>
        /// Read Data Value From the Ini File
        /// </summary>
        /// <PARAM name="Section"></PARAM>
        /// <PARAM name="Key"></PARAM>
        /// <PARAM name="Path"></PARAM>
        /// <returns></returns>
        public string IniReadValue(string Section, string Key)
        {
            StringBuilder temp = new StringBuilder(255);
            int i = GetPrivateProfileString(Section, Key, "", temp, 255, this.path);
            return temp.ToString();
        }



   /// <summary>
        /// Default INI File
        /// </summary>
        public void DefaultINI()
        {
            IniWriteValue("InputPath", "Input", Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + @"\EasyconWS\PCL");
            IniWriteValue("OutputPath", "Output", Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + @"\EasyconWS\Data");
       
        }
        /// <summary>
        /// Read Ini File
        /// </summary>
        public void ReadINI()
        {
            GetInputPath = IniReadValue("InputPath", "Input");
            GetOutputPath = IniReadValue("OutputPath", "Output");        
        }

Custom Control vs User Control


S.NoCustom ControlUser Control
1A loosely coupled control w.r.t code and UI.A tightly coupled control w.r.t code and UI.
2Derives from Control.Derives from UserControl.
3Defines UI in a ResourceDictionary.Defines UI as normal XAML.
4UI is skinable.Child controls are skinable.
5Has dynamic layout.Has static layout.
6UI can be changed in different projects.UI is fixed and can't have different looks in different project.
7Has full toolbox support.Can't be added to the toolbox.
8Defines a single control.Defines a set of controls.
9More flexible.Not very flexible like a Custom Control.

Display Cell Value into ListBox in C#.Net

Add  DataGridview,Button  and ListBox in your form.
Create  one method for getting Particular Cell data for listbox:

void DisplayCellDataintoListBox(int cellId)
{ foreach (DataGridViewRow row in dataGridView1.Rows)
{ listBox1.Items.Add(Convert.ToString(row.Cells[cellId].Value));
}
}

Call this method in the Button Click event:
DisplayCellDataintoListBox(<Pass Datagridview CellId>);

Create Text File and Values in C#.net

First Add Class file for CreateTextFile.
  Class file name: CreateTextFile.cs
  #region Declaration
CreateTextFile obj = new CreateTextFile(<Text File PATH>);
obj.AppendText(<Message/Text>);